alchemylab 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,40 +2,40 @@
2
2
  if(void 0!==r)return r.exports
3
3
  var module=s[t]={exports:{}}
4
4
  return o[t].call(module.exports,module,module.exports,e),module.exports}var t,r,n,o={76(e,exports,t){"use strict"
5
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateTask=async function(e,t,i,a,c,l,d){const u=a.child({tool:"create_task"})
6
- u.info("Creating new task",{args:e})
7
- const h=c.startTimer("tool_handler_duration")
8
- try{const a=function(e){try{return r.CreateTaskSchema.parse(e)}catch(t){throw new n.ValidationError("Invalid input: "+(0,s.getErrorMessage)(t),{args:e,error:t})}}(e),l=t.projectId
9
- if(!l)throw u.error("Missing project ID in context",{contextKeys:Object.keys(t)}),new n.ValidationError("Project ID is required for creating tasks with the new API structure")
10
- let g
11
- u.info("Using project ID from context",{projectId:l}),c.incrementCounter("create_task_attempts",1,{requestId:a.requestId,projectId:l}),i.setProjectId(l)
12
- try{const e=i.getRequestClient(),t=await e.getRequest(a.requestId)
13
- u.info("Raw request verification response data",{responseData:JSON.stringify(t)})
14
- const r=(0,o.extractDataFromResponse)(t,{logger:u,operationName:"verifyRequestExists",throwOnNoData:!0})
15
- g="object"==typeof r&&null!==r&&"data"in r?r.data:r,u.info(`Verified request ${a.requestId} exists`,{requestId:a.requestId,projectId:l,requestStatus:g.status})}catch(e){throw new n.NotFoundError(`Request ${a.requestId} not found in project ${l}. Please provide a valid request ID.`,{requestId:a.requestId,projectId:l,originalError:e})}if(["pending_approval","completed","canceled","ready_for_review","ready_for_merge","reverted"].includes(g.status)){const e={pending_approval:"is pending approval. Approve the request before creating tasks.",completed:"is already completed and merged. Create a new request for additional changes.",canceled:"was canceled. Create a new request or reopen this one if needed.",ready_for_review:"is being tested. Wait for test results before making changes.",ready_for_merge:"is ready to merge. Call merge to complete it.",reverted:"was reverted and cannot accept new tasks. Re-complete the request first or create a new request."}[g.status]||`has status '${g.status}' and cannot accept new tasks.`
16
- throw u.warn(`Task creation blocked on ${g.status} request`,{requestId:a.requestId,requestStatus:g.status,projectId:l}),new n.ValidationError(`The request ID "${a.requestId}" ${e}`,{requestId:a.requestId,requestStatus:g.status,reason:"request_"+g.status})}u.info("Request status validation passed for "+a.requestId,{requestId:a.requestId,requestStatus:g.status,projectId:l})
17
- const p=i.getTaskClient()
18
- u.info("Creating task with project context",{projectId:l})
19
- const f={requestId:a.requestId,projectId:l,title:a.title,description:a.description,status:"pending",...d&&{cliOrigin:d}}
20
- u.info("Task input prepared",{taskInput:JSON.stringify(f)}),u.info("Creating task via task client",{projectId:l,requestId:a.requestId,title:a.title})
21
- const m=await p.createTask(f)
22
- u.debug("Task creation response structure",{type:typeof m,isArray:Array.isArray(m),hasData:null!=m,properties:m?Object.keys(m):[],dataPreview:m?JSON.stringify(m).substring(0,200)+"...":"null"})
23
- const y=(0,o.extractDataFromResponse)(m,{logger:u,operationName:"createTask",defaultValue:{id:"tas"+Date.now().toString().substring(5,11),title:f.title,description:f.description,status:"pending",requestId:f.requestId,projectId:l,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}}),w="data"in y?y.data:y,k=w.localId||w.id||"tas"+Date.now().toString().substring(5,11),b=w.title||f.title,I=w.description||f.description,v=w.status||"pending",C=w.requestId||f.requestId
24
- let _,E="unknown"
25
- w&&"object"==typeof w&&"_workingEndpoint"in w&&(E=w._workingEndpoint),u.info("Successfully extracted task data from response",{taskId:k,requestId:C,title:b})
26
- try{const e=i.getToolRecordClient()
27
- if(e){const t=await e.createToolRecord({taskId:k,requestId:C,projectId:l,type:"create-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:b,taskDescription:I,taskStatus:v},note:"Created task "+b})
28
- _=t?.id}}catch(e){u.error("Failed to create tool record for task creation, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:k,requestId:C})}h({success:!0,requestId:a.requestId,projectId:l}),u.info("Task created successfully",{taskId:k,requestId:C,title:b,projectId:l})
29
- let q=`Created Task ${k}: ${b}`
30
- return _&&(q+=`\n[RECORD:${_}]`),{content:[{type:"text",text:q}]}}catch(r){if(u.error("Failed to create task",{error:r instanceof Error?r.stack:r+"",args:e}),t.projectId)try{if(r instanceof Error&&(r.message.includes("Project is disabled")||r.message.includes("Project cannot accept new tasks")||r.message.includes("disabled due to tier limits")||r.message.includes("Project is inactive due to tier limits")))u.info("Skipping tool record creation for disabled project error",{projectId:t.projectId,error:r.message})
31
- else{const n=i.getToolRecordClient()
32
- n&&await n.createToolRecord({requestId:e.requestId,projectId:t.projectId,type:"create-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.title,taskDescription:e.description?.substring(0,100)+(e.description?.length>100?"...":""),error:(0,s.getErrorMessage)(r),errorDetails:r instanceof Error?r.stack:r+""},note:"Failed to create task: "+e.title})}}catch(e){u.error("Failed to create failure record for task creation",{error:e instanceof Error?e.message:e+""})}h({success:!1,error:r instanceof Error?r.name:"unknown"})
33
- let o=(0,s.getErrorMessage)(r),c=""
34
- return r instanceof n.NotFoundError?o=`The request ID "${e.requestId}" was not found. Please provide a valid request ID.`:r instanceof n.ValidationError&&(o.includes("Project cannot accept new tasks")||o.includes("Project is inactive due to tier limits")?c="\n\nThis project is currently inactive due to tier limits. Only your oldest projects can accept new tasks. Please use an active project or upgrade your tier for more simultaneous projects.":o="Invalid input: "+o),a.error("Detailed error when creating task",{error:(0,s.getErrorMessage)(r),stack:r instanceof Error?r.stack:void 0}),i.isOffline,i.apiClient,{content:[{type:"text",text:`Error: ${o}${c}`}],isError:!0}}}
35
- const r=t(6183),n=t(9860),o=t(2960),s=t(8824)},184(e,exports,t){"use strict"
5
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateTask=async function(e,t,a,c,l,d,u){const h=c.child({tool:"create_task"})
6
+ h.info("Creating new task",{args:e})
7
+ const g=l.startTimer("tool_handler_duration")
8
+ try{const c=function(e){try{return r.CreateTaskSchema.parse(e)}catch(t){throw new n.ValidationError("Invalid input: "+(0,s.getErrorMessage)(t),{args:e,error:t})}}(e),d=t.projectId
9
+ if(!d)throw h.error("Missing project ID in context",{contextKeys:Object.keys(t)}),new n.ValidationError("Project ID is required for creating tasks with the new API structure")
10
+ let p
11
+ h.info("Using project ID from context",{projectId:d}),l.incrementCounter("create_task_attempts",1,{requestId:c.requestId,projectId:d}),a.setProjectId(d)
12
+ try{const e=a.getRequestClient(),t=await e.getRequest(c.requestId)
13
+ h.info("Raw request verification response data",{responseData:JSON.stringify(t)})
14
+ const r=(0,o.extractDataFromResponse)(t,{logger:h,operationName:"verifyRequestExists",throwOnNoData:!0})
15
+ p="object"==typeof r&&null!==r&&"data"in r?r.data:r,h.info(`Verified request ${c.requestId} exists`,{requestId:c.requestId,projectId:d,requestStatus:p.status})}catch(e){throw new n.NotFoundError(`Request ${c.requestId} not found in project ${d}. Please provide a valid request ID.`,{requestId:c.requestId,projectId:d,originalError:e})}if(["pending_approval","completed","canceled","ready_for_review","ready_for_merge","reverted"].includes(p.status)){const e={pending_approval:"is pending approval. Approve the request before creating tasks.",completed:"is already completed and merged. Create a new request for additional changes.",canceled:"was canceled. Create a new request or reopen this one if needed.",ready_for_review:"is being tested. Wait for test results before making changes.",ready_for_merge:"is ready to merge. Call merge to complete it.",reverted:"was reverted and cannot accept new tasks. Re-complete the request first or create a new request."}[p.status]||`has status '${p.status}' and cannot accept new tasks.`
16
+ throw h.warn(`Task creation blocked on ${p.status} request`,{requestId:c.requestId,requestStatus:p.status,projectId:d}),new n.ValidationError(`The request ID "${c.requestId}" ${e}`,{requestId:c.requestId,requestStatus:p.status,reason:"request_"+p.status})}h.info("Request status validation passed for "+c.requestId,{requestId:c.requestId,requestStatus:p.status,projectId:d})
17
+ const f=a.getTaskClient()
18
+ h.info("Creating task with project context",{projectId:d})
19
+ const m={requestId:c.requestId,projectId:d,title:c.title,description:c.description,status:"pending",...u&&{cliOrigin:u}}
20
+ h.info("Task input prepared",{taskInput:JSON.stringify(m)}),h.info("Creating task via task client",{projectId:d,requestId:c.requestId,title:c.title})
21
+ const y=await f.createTask(m)
22
+ h.debug("Task creation response structure",{type:typeof y,isArray:Array.isArray(y),hasData:null!=y,properties:y?Object.keys(y):[],dataPreview:y?JSON.stringify(y).substring(0,200)+"...":"null"})
23
+ const w=(0,o.extractDataFromResponse)(y,{logger:h,operationName:"createTask",defaultValue:{id:"tas"+Date.now().toString().substring(5,11),title:m.title,description:m.description,status:"pending",requestId:m.requestId,projectId:d,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}}),k="data"in w?w.data:w,b=k.localId||k.id||"tas"+Date.now().toString().substring(5,11),I=k.title||m.title,v=k.description||m.description,C=k.status||"pending",_=k.requestId||m.requestId
24
+ let E,q="unknown"
25
+ k&&"object"==typeof k&&"_workingEndpoint"in k&&(q=k._workingEndpoint),h.info("Successfully extracted task data from response",{taskId:b,requestId:_,title:I})
26
+ try{const e=a.getToolRecordClient()
27
+ if(e){const t=await e.createToolRecord({taskId:b,requestId:_,projectId:d,type:"create-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:I,taskDescription:v,taskStatus:C},note:"Created task "+I})
28
+ E=t?.id}}catch(e){h.error("Failed to create tool record for task creation, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:b,requestId:_})}g({success:!0,requestId:c.requestId,projectId:d}),h.info("Task created successfully",{taskId:b,requestId:_,title:I,projectId:d})
29
+ let S=`Created Task ${k.sequenceNumber&&_?(0,i.formatTaskRef)(_,k.sequenceNumber):b}: ${I}`
30
+ return E&&(S+=`\n[RECORD:${E}]`),{content:[{type:"text",text:S}]}}catch(r){if(h.error("Failed to create task",{error:r instanceof Error?r.stack:r+"",args:e}),t.projectId)try{if(r instanceof Error&&(r.message.includes("Project is disabled")||r.message.includes("Project cannot accept new tasks")||r.message.includes("disabled due to tier limits")||r.message.includes("Project is inactive due to tier limits")))h.info("Skipping tool record creation for disabled project error",{projectId:t.projectId,error:r.message})
31
+ else{const n=a.getToolRecordClient()
32
+ n&&await n.createToolRecord({requestId:e.requestId,projectId:t.projectId,type:"create-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.title,taskDescription:e.description?.substring(0,100)+(e.description?.length>100?"...":""),error:(0,s.getErrorMessage)(r),errorDetails:r instanceof Error?r.stack:r+""},note:"Failed to create task: "+e.title})}}catch(e){h.error("Failed to create failure record for task creation",{error:e instanceof Error?e.message:e+""})}g({success:!1,error:r instanceof Error?r.name:"unknown"})
33
+ let o=(0,s.getErrorMessage)(r),i=""
34
+ return r instanceof n.NotFoundError?o=`The request ID "${e.requestId}" was not found. Please provide a valid request ID.`:r instanceof n.ValidationError&&(o.includes("Project cannot accept new tasks")||o.includes("Project is inactive due to tier limits")?i="\n\nThis project is currently inactive due to tier limits. Only your oldest projects can accept new tasks. Please use an active project or upgrade your tier for more simultaneous projects.":o="Invalid input: "+o),c.error("Detailed error when creating task",{error:(0,s.getErrorMessage)(r),stack:r instanceof Error?r.stack:void 0}),a.isOffline,a.apiClient,{content:[{type:"text",text:`Error: ${o}${i}`}],isError:!0}}}
35
+ const r=t(6183),n=t(9860),o=t(2960),s=t(8824),i=t(4466)},184(e,exports,t){"use strict"
36
36
  function r(e,t,r,n,o={}){const s=d.default.resolve(e)
37
37
  if(O.has(s))return t.child({component:"mcp-server-registry"}).debug("Using existing server for path",{path:s}),O.get(s)
38
- const i=new x(s,t,r,n,o)
38
+ const i=new M(s,t,r,n,o)
39
39
  return O.set(s,i),i}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
40
40
  var o=Object.getOwnPropertyDescriptor(t,r)
41
41
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[]
@@ -45,13 +45,13 @@ var t={}
45
45
  if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
46
46
  return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
47
47
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.McpServer=void 0,exports.resetStdoutWrite=function(){process.stdout.write=R},exports.getMcpServer=r,exports.createServer=function(e,t,n,o,s={}){return r(e,t,n,o,s)}
48
- const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),p=t(3444),f=t(7660),m=t(1253),y=t(5172),w=i(t(7478)),k=t(4139),b=new Set,I=t(9860),v=t(1472),C=t(3328),_=t(8955),E=t(3217),q=t(5278),S=t(446),T=t(9060),P=t(8824),j=(0,p.createLogger)({serviceName:"stdout-capture",console:!1,logToFile:!1}),R=process.stdout.write,M=process.argv.includes("--stdio")||"true"===process.env.MCP_DIRECT_MODE
49
- !(0,p.isDebugToolsEnabled)()||M&&"true"!==process.env.DEBUG_STDOUT_CAPTURE||(process.stdout.write=function(e){try{return(0,p.isDebugToolsEnabled)()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()&&"string"==typeof e&&!e.trim().startsWith('{"jsonrpc":"2.0"')&&e.trim().length>0&&j.debug("Stdout output",{content:e.substring(0,100),length:e.length}),R.call(process.stdout,e)}catch(e){return j.error("Error in safeStdoutWrite",{error:e+""}),!0}})
50
- class x{constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,k.ALCHEMY_DIR_NAME),this.metrics=r,this.remoteServerUrl=n,this.existingProjectId=o.existingProjectId,this.gitBinary=(0,l.detectGitBinary)(),this.logger.info("Detected git binary",{gitBinary:this.gitBinary,version:(0,l.getGitVersion)()}),this.projectContext=new f.ProjectContext(e,t),this.tokenManager=new m.TokenManager(t,e,{remoteServerUrl:n}),this.lockOverrideManager=new S.LockOverrideManager(t),this.configManager=new T.ConfigManager(t),this.logger.debug("Server paths initialized",{basePath:this.basePath,alchemyPath:this.alchemyPath}),this.server=new g.Server({name:"alchemy",version:"1.0.0"},{capabilities:{tools:{search:{},create_request:{},complete_task:{},get_task_information:{},complete_request:{},revert_request:{},get_request_information:{},list_tasks:{},list_requests:{},switch_to_branch:{},read_files:{},create_directory:{},move_files:{},write_file:{},replace_strings:{},insert_lines:{},replace_lines:{},delete_files:{},document_operations:{},file_history:{},task_file_history:{},request_file_history:{},quick_write:{},quick_replace:{},quick_manage:{}}}}),(0,y.setGlobalClientInfo)("OpenCode","1.0.0"),this.metrics.incrementCounter("mcp_server_init_started",1),this.logger.info("Starting initialization for server instance"),this.initializationPromise=this.initialize()}get branchState(){if(!this.workspaceManager)return{currentBranch:null,activeRequestId:null,isOnMainBranch:!0}
51
- const e=this.workspaceManager.getCurrentContext()
48
+ const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),p=t(3444),f=t(7660),m=t(1253),y=t(5172),w=i(t(7478)),k=t(4139),b=new Set,I=t(9860),v=t(1472),C=t(3328),_=t(8955),E=t(3217),q=t(5278),S=t(446),T=t(9060),P=t(8824),j=(0,p.createLogger)({serviceName:"stdout-capture",console:!1,logToFile:!1}),R=process.stdout.write,x=process.argv.includes("--stdio")||"true"===process.env.MCP_DIRECT_MODE
49
+ !(0,p.isDebugToolsEnabled)()||x&&"true"!==process.env.DEBUG_STDOUT_CAPTURE||(process.stdout.write=function(e){try{return(0,p.isDebugToolsEnabled)()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()&&"string"==typeof e&&!e.trim().startsWith('{"jsonrpc":"2.0"')&&e.trim().length>0&&j.debug("Stdout output",{content:e.substring(0,100),length:e.length}),R.call(process.stdout,e)}catch(e){return j.error("Error in safeStdoutWrite",{error:e+""}),!0}})
50
+ class M{constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,k.ALCHEMY_DIR_NAME),this.metrics=r,this.remoteServerUrl=n,this.existingProjectId=o.existingProjectId,this.gitBinary=(0,l.detectGitBinary)(),this.logger.info("Detected git binary",{gitBinary:this.gitBinary,version:(0,l.getGitVersion)()}),this.projectContext=new f.ProjectContext(e,t),this.tokenManager=new m.TokenManager(t,e,{remoteServerUrl:n}),this.lockOverrideManager=new S.LockOverrideManager(t),this.configManager=new T.ConfigManager(t),this.logger.debug("Server paths initialized",{basePath:this.basePath,alchemyPath:this.alchemyPath}),this.server=new g.Server({name:"alchemy",version:"1.0.0"},{capabilities:{tools:{search:{},create_request:{},complete_task:{},get_task_information:{},complete_request:{},revert_request:{},get_request_information:{},list_tasks:{},list_requests:{},switch_to_branch:{},read_files:{},create_directory:{},move_files:{},write_file:{},replace_strings:{},insert_lines:{},replace_lines:{},delete_files:{},document_operations:{},file_history:{},task_file_history:{},request_file_history:{},quick_write:{},quick_replace:{},quick_manage:{}}}}),(0,y.setGlobalClientInfo)("OpenCode","1.0.0"),this.metrics.incrementCounter("mcp_server_init_started",1),this.logger.info("Starting initialization for server instance"),this.initializationPromise=this.initialize()}get branchState(){if(!this.workspaceManager)return{currentBranch:null,activeRequestId:null,isOnMainBranch:!0}
51
+ const e=this.workspaceManager.getCurrentContext("__server__")
52
52
  return{currentBranch:e.branchName,activeRequestId:e.requestId,isOnMainBranch:e.isMainBranch}}async updateBranchState(e,t){this.logger.debug("updateBranchState called - managed by WorkspaceManager",{branch:e,requestId:t})}async getCurrentBranchContext(){if(!this.workspaceManager)return{branch:null,requestId:null,isMain:!0}
53
- const e=this.workspaceManager.getCurrentContext()
54
- return{branch:e.branchName,requestId:e.requestId,isMain:e.isMainBranch}}async syncBranchState(){this.logger.debug("syncBranchState called - managed by WorkspaceManager")}async switchToMainContext(){return this.workspaceManager?this.workspaceManager.switchToMain():{success:!1,message:"WorkspaceManager not available"}}getCurrentRequestId(){return this.workspaceManager?.getCurrentContext().requestId||null}async getNextId(e){try{const t=this.metrics.startTimer("remote_id_generation"),r=this.apiClient.getProjectClient()
53
+ const e=this.workspaceManager.getCurrentContext("__server__")
54
+ return{branch:e.branchName,requestId:e.requestId,isMain:e.isMainBranch,permanentBranch:e.permanentBranch}}async syncBranchState(){this.logger.debug("syncBranchState called - managed by WorkspaceManager")}async switchToMainContext(){return this.workspaceManager?this.workspaceManager.switchToMain("__server__"):{success:!1,message:"WorkspaceManager not available"}}getCurrentRequestId(){return this.workspaceManager?.getCurrentContext("__server__").requestId||null}async getNextId(e){try{const t=this.metrics.startTimer("remote_id_generation"),r=this.apiClient.getProjectClient()
55
55
  if(!r||"function"!=typeof r.getNextId)throw Error("Project client or getNextId method not available")
56
56
  const n=await r.getNextId(e)
57
57
  return t({success:!0,type:e}),this.metrics.incrementCounter("remote_id_success",1,{type:e}),n}catch(t){throw this.metrics.incrementCounter("remote_id_failure",1,{type:e,error:t instanceof Error?t.name:"unknown"}),this.logger.warn("Failed to get ID from remote server, unable to perform operation",{type:e,error:(0,P.getErrorMessage)(t)}),Error("Failed to get ID from remote server.")}}async initialize(){const e=this.remoteServerUrl||"https://api.alchemylabcode.com"
@@ -106,17 +106,17 @@ const r=new g.SSEServerTransport("/sse",e)
106
106
  this.currentSSEConnection={transport:r,response:e}
107
107
  try{await this.server.connect(r),this.logger.info("SSE transport connected successfully")}catch(e){this.logger.error("Error connecting SSE transport",{error:(0,P.getErrorMessage)(e)})}return r}async connectStdio(){await this.waitForInitialization(),this.logger.debug("Connecting stdio transport"),this.stdioTransport=new g.StdioServerTransport
108
108
  try{await this.server.connect(this.stdioTransport),this.logger.info("STDIO transport connected successfully")}catch(e){this.logger.error("Error connecting stdio transport",{error:(0,P.getErrorMessage)(e)})}}getCurrentSSEConnection(){return this.currentSSEConnection}setCurrentSSEConnection(e){this.currentSSEConnection=e}getServer(){return this.server}getCurrentGitInstance(){if(!this.workspaceManager)return this.git||void 0
109
- const e=this.workspaceManager.getCurrentContext()
109
+ const e=this.workspaceManager.getCurrentContext("__server__")
110
110
  return"multi-agent"===e.mode&&e.requestId?this.workspaceManager.getCurrentGit():this.git||void 0}getContext(){if(!this.workspaceManager)throw Error("WorkspaceManager not initialized")
111
- return{mainBasePath:this.basePath,alchemyPath:this.alchemyPath,basePath:this.workspaceManager.getCurrentContext().basePath,projectId:this.getProjectId(),git:this.getCurrentGitInstance(),gitBinary:this.gitBinary,apiClient:this.apiClient,workspaceManager:this.workspaceManager,documentFileManager:this.documentFileManager,lockOverrideManager:this.lockOverrideManager,configManager:this.configManager,getNextId:this.getNextId.bind(this),getCurrentBranchContext:this.getCurrentBranchContext.bind(this),syncBranchState:this.syncBranchState.bind(this),switchToMainContext:this.switchToMainContext.bind(this),getCurrentRequestId:this.getCurrentRequestId.bind(this),updateBranchState:this.updateBranchState.bind(this)}}isMainBranch(e){return"main"===e||"master"===e}extractRequestIdFromBranch(e){const t=e.match(/^feature\/req(\d+)-/)
111
+ return{mainBasePath:this.basePath,alchemyPath:this.alchemyPath,basePath:this.workspaceManager.getCurrentContext("__server__").basePath,projectId:this.getProjectId(),git:this.getCurrentGitInstance(),gitBinary:this.gitBinary,currentSessionId:"__server__",apiClient:this.apiClient,workspaceManager:this.workspaceManager,documentFileManager:this.documentFileManager,lockOverrideManager:this.lockOverrideManager,configManager:this.configManager,getNextId:this.getNextId.bind(this),getCurrentBranchContext:this.getCurrentBranchContext.bind(this),syncBranchState:this.syncBranchState.bind(this),switchToMainContext:this.switchToMainContext.bind(this),getCurrentRequestId:this.getCurrentRequestId.bind(this),updateBranchState:this.updateBranchState.bind(this)}}isMainBranch(e){return"main"===e||"master"===e}extractRequestIdFromBranch(e){const t=e.match(/^feature\/req(\d+)-/)
112
112
  return t?"req"+t[1]:null}async getEnhancedContext(){return{...this.getContext(),branchInfo:await this.getCurrentBranchInfo()}}getTokenManager(){return this.tokenManager}getProjectId(){try{return this.projectContext.getProjectId()}catch(e){return this.logger.debug("ProjectContext not initialized, using fallback project ID",{error:(0,P.getErrorMessage)(e)}),"INITIALIZING"}}generateSessionId(){return`session_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,8)}_${process.pid.toString(36)}`}async getActiveWorktrees(){return await this.workspaceManager.listActiveWorkspaces()}async initializeWorkspaceManager(){try{if(this.logger.debug("initializeWorkspaceManager called",{basePath:this.basePath}),!this.git)throw Error("Git must be initialized before WorkspaceManager")
113
113
  this.workspaceManager=(0,E.createWorkspaceManager)(this.basePath,this.logger,this.git,this.metrics,this.apiClient),this.logger.debug("WorkspaceManager created successfully"),this.logger.info("Initialized unified workspace manager",{mode:"multi-agent",basePath:this.basePath})}catch(e){throw this.logger.error("Failed to initialize workspace manager",{error:e}),e}}async switchToRequestContext(e){return this.logger.debug("switchToRequestContext called",{requestId:e,hasWorkspaceManager:!!this.workspaceManager}),this.workspaceManager?this.switchToWorktreeContext(e):{success:!1,message:"Workspace manager not available"}}async switchToWorktreeContext(e){if(this.logger.debug("Using worktree context switching for multi-agent mode",{requestId:e}),!this.workspaceManager)return{success:!1,message:"Workspace manager not available"}
114
114
  try{let t="request-"+e
115
115
  try{this.logger.debug("Attempting to fetch request title from API",{requestId:e})
116
116
  const r=this.apiClient.getRequestClient(),n=await r.getRequest(e)
117
117
  n&&n.title?(t=n.title,this.logger.debug("Successfully fetched request title for worktree",{requestId:e,actualTitle:n.title})):this.logger.warn("Request info found but no title, using fallback",{requestId:e,requestInfo:n?"exists":"null",fallbackTitle:t})}catch(r){this.logger.warn("Failed to fetch request title, using fallback",{requestId:e,fallbackTitle:t,error:(0,P.getErrorMessage)(r),errorStack:r instanceof Error?r.stack:void 0})}const r=this.generateSessionId()
118
- this.logger.info("Creating worktree for request using WorkspaceManager",{requestId:e,requestTitle:t,sessionId:r}),await this.workspaceManager.ensureWorkspaceReady(e)
119
- const n=this.workspaceManager.getCurrentContext()
118
+ this.logger.info("Creating worktree for request using WorkspaceManager",{requestId:e,requestTitle:t,sessionId:r}),await this.workspaceManager.ensureWorkspaceReady(e,"__server__")
119
+ const n=this.workspaceManager.getCurrentContext("__server__")
120
120
  this.git=(0,c.simpleGit)({baseDir:n.basePath,binary:this.gitBinary})
121
121
  try{const t=await w.getCurrentBranch(this.git,this.logger,this.metrics)
122
122
  if(this.logger.info("Workspace Git instance branch status",{requestId:e,currentBranch:t,expectedBranch:n.branchName,workspacePath:n.basePath,isMainBranch:n.isMainBranch}),t!==n.branchName&&!n.isMainBranch){this.logger.warn("Workspace not on expected branch, attempting to switch",{requestId:e,currentBranch:t,expectedBranch:n.branchName})
@@ -124,7 +124,7 @@ const r=await w.switchToBranch(this.git,n.branchName,this.logger,this.metrics)
124
124
  r.success?this.logger.info("Successfully switched workspace to correct branch",{requestId:e,branchName:n.branchName}):this.logger.error("Failed to switch workspace to correct branch",{requestId:e,expectedBranch:n.branchName,error:r.message})}}catch(t){this.logger.error("Failed to verify workspace branch status",{requestId:e,workspacePath:n.basePath,error:t instanceof Error?t.message:t+""})}return this.logger.info("Switched to request context",{requestId:e,workspacePath:n.basePath,branchName:n.branchName}),{success:!0,message:"Switched to workspace for request "+e,worktreePath:n.basePath}}catch(t){const r=(0,P.getErrorMessage)(t)
125
125
  return this.logger.error("Failed to switch to request context",{requestId:e,error:r}),{success:!1,message:"Failed to switch context: "+r}}}async getEffectiveBasePath(e){if(!this.workspaceManager||!e)return this.basePath
126
126
  const t=await this.workspaceManager.getWorkspaceInfo(e)
127
- return t?.path||this.basePath}}exports.McpServer=x
127
+ return t?.path||this.basePath}}exports.McpServer=M
128
128
  const O=new Map},213(e,exports,t){"use strict"
129
129
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
130
130
  const r=t(6183),n=t(3707)
@@ -196,49 +196,52 @@ default:t="open"}else t="open"
196
196
  const n=Array.isArray(e.acceptanceCriteria)?e.acceptanceCriteria.map(r):[]
197
197
  return{id:e.id,title:e.title,description:e.description,type:e.type,status:t,acceptanceCriteria:n,createdAt:e.createdAt,updatedAt:e.updatedAt,...e.projectId?{projectId:e.projectId}:{},...e.completionSummary?{completionSummary:e.completionSummary}:{},...e.completedAt?{completedAt:e.completedAt}:{},...e.metadata?{metadata:e.metadata}:{},...e.lockInfo?{lockInfo:e.lockInfo}:{}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.adaptApiAcceptanceCriterionToDomain=r,exports.adaptApiRequestToDomain=n,exports.adaptApiRequestsToDomain=function(e){return e.map(n)}
198
198
  const o=t(6756)},355(e,exports,t){"use strict"
199
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteTask=async function(e,l,d,u,h){const g=u.child({tool:"complete_task"})
200
- g.info("Completing task",{args:e})
201
- const p=h.startTimer("tool_handler_duration")
202
- try{const{taskId:o,summary:u}=function(e){if(void 0!==e.verificationSteps){const{verificationSteps:t,...r}=e
199
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteTask=async function(e,d,u,h,g){const p=h.child({tool:"complete_task"})
200
+ p.info("Completing task",{args:e})
201
+ const f=g.startTimer("tool_handler_duration")
202
+ try{const o=function(e){if(void 0!==e.verificationSteps){const{verificationSteps:t,...r}=e
203
203
  e=r}try{return r.CompleteTaskSchema.parse(e)}catch(e){if(e instanceof i.ZodError&&e.errors.length>0)throw new n.ValidationError(e.errors[0].message)
204
- throw new n.ValidationError("Invalid input: "+(0,c.getErrorMessage)(e))}}(e),f=l.projectId
205
- if(!f)throw new n.ValidationError("Project ID is required for completing tasks with the new API structure")
206
- h.incrementCounter("complete_task_attempts",1,{taskId:o}),d.setProjectId(f)
207
- const m=d.getTaskClient()
208
- let y
209
- try{const e=await m.getTask(o)
210
- g.info("Raw task response data",{responseData:JSON.stringify(e)}),g.debug("Task response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
211
- const t=(0,s.extractDataFromResponse)(e,{logger:g,operationName:"getTask",throwOnNoData:!0})
212
- y="data"in t?t.data:t,g.info("Current task status: "+y.status,{taskId:o,currentStatus:y.status})}catch(e){if(e instanceof n.ValidationError)throw e
213
- throw new n.NotFoundError(`Task ${o} not found in project ${f}. Please provide a valid task ID.`,{taskId:o,projectId:f,originalError:e})}if("completed"===y.status){const e="Task is already completed."
214
- throw g.warn(e,{taskId:o,currentStatus:y.status}),new n.ValidationError(e)}if("canceled"===y.status){const e="Task is canceled and can not be completed."
215
- throw g.warn(e,{taskId:o,currentStatus:y.status}),new n.ValidationError(e)}if(y.requestId){g.debug("Checking request lock for task operation",{taskId:o,requestId:y.requestId})
216
- try{const e=d.getRequestClient(),{sessionTag:t}=(0,a.getGlobalClientInfo)(),r=await e.getRequestLockStatus(y.requestId)
217
- if(r.isLocked){if(r.lockedBySessionTag!==t){let e=`Request ${y.requestId} is locked by another agent (${r.lockedBySessionTag}). `
218
- throw r.isExpired?e+="Lock has expired but cleanup may be pending. ":e+=`Lock expires in: ${r.timeRemainingFormatted}. `,e+="Only the agent that locked the request can modify its tasks.",new n.ValidationError(e,{taskId:o,requestId:y.requestId,lockedByAgent:r.lockedBySessionTag,currentAgent:t,timeRemainingMs:r.timeRemainingMs,isExpired:r.isExpired})}}else{g.debug("Lock not held, auto-acquiring for task completion",{requestId:y.requestId,sessionTag:t})
219
- const r=await e.lockRequest(y.requestId,t)
220
- if(!r.locked)throw new n.ValidationError(`Failed to acquire lock for request ${y.requestId}. Another agent may have just locked it. Try again shortly.`,{taskId:o,requestId:y.requestId})
221
- g.info("Auto-acquired lock for task completion",{requestId:y.requestId,sessionTag:t,lockedAt:r.lockedAt})}g.info("Request lock validation passed",{taskId:o,requestId:y.requestId,sessionTag:t})}catch(e){if(e instanceof n.ValidationError)throw e
222
- throw g.error("Failed to check request lock status",{taskId:o,requestId:y.requestId,error:(0,c.getErrorMessage)(e)}),new n.ValidationError("Failed to verify request lock status: "+(0,c.getErrorMessage)(e),{taskId:o,requestId:y.requestId})}}else g.debug("Task without requestId: skipping lock check",{taskId:o,hasRequestId:!!y.requestId})
223
- let w=l.git
224
- if(l.workspaceManager){const e=l.workspaceManager.getCurrentContext()
204
+ throw new n.ValidationError("Invalid input: "+(0,c.getErrorMessage)(e))}}(e)
205
+ let h=o.taskId
206
+ const m=o.summary;(0,l.isTaskRef)(h)&&(h=await(0,l.resolveTaskRef)(h,u,p))
207
+ const y=d.projectId
208
+ if(!y)throw new n.ValidationError("Project ID is required for completing tasks with the new API structure")
209
+ g.incrementCounter("complete_task_attempts",1,{taskId:h}),u.setProjectId(y)
210
+ const w=u.getTaskClient()
211
+ let k
212
+ try{const e=await w.getTask(h)
213
+ p.info("Raw task response data",{responseData:JSON.stringify(e)}),p.debug("Task response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
214
+ const t=(0,s.extractDataFromResponse)(e,{logger:p,operationName:"getTask",throwOnNoData:!0})
215
+ k="data"in t?t.data:t,p.info("Current task status: "+k.status,{taskId:h,currentStatus:k.status})}catch(e){if(e instanceof n.ValidationError)throw e
216
+ throw new n.NotFoundError(`Task ${h} not found in project ${y}. Please provide a valid task ID.`,{taskId:h,projectId:y,originalError:e})}if("completed"===k.status){const e="Task is already completed."
217
+ throw p.warn(e,{taskId:h,currentStatus:k.status}),new n.ValidationError(e)}if("canceled"===k.status){const e="Task is canceled and can not be completed."
218
+ throw p.warn(e,{taskId:h,currentStatus:k.status}),new n.ValidationError(e)}if(k.requestId){p.debug("Checking request lock for task operation",{taskId:h,requestId:k.requestId})
219
+ try{const e=u.getRequestClient(),{sessionTag:t}=(0,a.getGlobalClientInfo)(),r=await e.getRequestLockStatus(k.requestId)
220
+ if(r.isLocked){if(r.lockedBySessionTag!==t){let e=`Request ${k.requestId} is locked by another agent (${r.lockedBySessionTag}). `
221
+ throw r.isExpired?e+="Lock has expired but cleanup may be pending. ":e+=`Lock expires in: ${r.timeRemainingFormatted}. `,e+="Only the agent that locked the request can modify its tasks.",new n.ValidationError(e,{taskId:h,requestId:k.requestId,lockedByAgent:r.lockedBySessionTag,currentAgent:t,timeRemainingMs:r.timeRemainingMs,isExpired:r.isExpired})}}else{p.debug("Lock not held, auto-acquiring for task completion",{requestId:k.requestId,sessionTag:t})
222
+ const r=await e.lockRequest(k.requestId,t)
223
+ if(!r.locked)throw new n.ValidationError(`Failed to acquire lock for request ${k.requestId}. Another agent may have just locked it. Try again shortly.`,{taskId:h,requestId:k.requestId})
224
+ p.info("Auto-acquired lock for task completion",{requestId:k.requestId,sessionTag:t,lockedAt:r.lockedAt})}p.info("Request lock validation passed",{taskId:h,requestId:k.requestId,sessionTag:t})}catch(e){if(e instanceof n.ValidationError)throw e
225
+ throw p.error("Failed to check request lock status",{taskId:h,requestId:k.requestId,error:(0,c.getErrorMessage)(e)}),new n.ValidationError("Failed to verify request lock status: "+(0,c.getErrorMessage)(e),{taskId:h,requestId:k.requestId})}}else p.debug("Task without requestId: skipping lock check",{taskId:h,hasRequestId:!!k.requestId})
226
+ let b=d.git
227
+ if(d.workspaceManager){const e=d.workspaceManager.getCurrentContext(d.currentSessionId)
225
228
  if("multi-agent"===e.mode&&e.requestId){const{simpleGit}=t(3807)
226
- w=simpleGit({baseDir:e.basePath,binary:l.gitBinary}),g.debug("Using workspace-aware git instance for task completion",{taskId:o,mode:e.mode,requestId:e.requestId,basePath:e.basePath})}}let k=null
227
- if(w)try{(await w.status()).isClean()||(k=(await w.commit(`Complete task ${o}: ${u}`)).commit,g.info("Created commit for task completion",{taskId:o,commitId:k}))}catch(e){g.warn("Failed to commit changes",{error:(0,c.getErrorMessage)(e)})}let b=null
228
- try{const e=d.getToolRecordClient()
229
- e&&(b={id:(await e.createToolRecord({taskId:o,requestId:y.requestId,projectId:f,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:y.title,completionSummary:u,lastCommit:k,completedAt:(new Date).toISOString()},note:`Completed task: ${u.substring(0,100)}${u.length>100?"...":""}`})).id})}catch(e){g.error("Failed to create tool record for task completion, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:o,requestId:y.requestId})}try{const e=y.metadata||{},t=(new Date).toISOString(),r={status:"completed",metadata:{...e,lastCommit:k,completionSummary:u,completionRecordId:b?.id,completedAt:t}},n=await m.updateTask(o,r)
230
- g.info("Raw task update response data",{responseData:JSON.stringify(n)}),g.debug("Task update response structure",{type:typeof n,isArray:Array.isArray(n),hasData:null!=n,properties:n?Object.keys(n):[],dataPreview:n?JSON.stringify(n).substring(0,200)+"...":"null"}),(0,s.extractDataFromResponse)(n,{logger:g,operationName:"updateTask",defaultValue:{id:o,status:"completed"}}),g.info("Successfully completed task",{taskId:o,recordId:b?.id})
231
- const i=y.requestId
232
- let a=`Task ${o} (${y.title}) has been marked as completed.`
233
- if(b?.id&&(a+=`\n[RECORD:${b.id}]`),k&&(a+="\nCommit: "+k.substring(0,8)),i)try{const e=await m.listTasks({requestId:i})
234
- g.info("Raw tasks list response data",{responseData:JSON.stringify(e)}),g.debug("Tasks list response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
235
- const t=(0,s.extractArrayFromResponse)(e,{logger:g,operationName:"listTasksForProgress",defaultValue:[]}),r=t.length,n=t.filter((e=>"completed"===e.status)).length
236
- g.info("Task progress check",{requestId:i,totalTasks:r,completedTasks:n}),a+=`\n\nTask Progress: ${n}/${r} tasks completed`,n===r&&(a+=`\n\nAll tasks for request ${i} are now completed! You may consider marking the request as completed using the complete-request tool.`)}catch(e){g.warn("Failed to check task progress",{error:(0,c.getErrorMessage)(e),requestId:i})}return p({success:!0}),{content:[{type:"text",text:a}]}}catch(e){throw g.error("Failed to complete task",{error:e instanceof Error?e.stack:e+"",taskId:o}),Error("Failed to complete task: "+(0,c.getErrorMessage)(e))}}catch(t){if(g.error("Failed to complete task",{error:t instanceof Error?t.stack:t+"",args:e}),l.projectId)try{const r=d.getToolRecordClient()
229
+ b=simpleGit({baseDir:e.basePath,binary:d.gitBinary}),p.debug("Using workspace-aware git instance for task completion",{taskId:h,mode:e.mode,requestId:e.requestId,basePath:e.basePath})}}let I=null
230
+ if(b)try{(await b.status()).isClean()||(I=(await b.commit(`Complete task ${h}: ${m}`)).commit,p.info("Created commit for task completion",{taskId:h,commitId:I}))}catch(e){p.warn("Failed to commit changes",{error:(0,c.getErrorMessage)(e)})}let v=null
231
+ try{const e=u.getToolRecordClient()
232
+ e&&(v={id:(await e.createToolRecord({taskId:h,requestId:k.requestId,projectId:y,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:k.title,completionSummary:m,lastCommit:I,completedAt:(new Date).toISOString()},note:`Completed task: ${m.substring(0,100)}${m.length>100?"...":""}`})).id})}catch(e){p.error("Failed to create tool record for task completion, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:h,requestId:k.requestId})}try{const e=k.metadata||{},t=(new Date).toISOString(),r={status:"completed",metadata:{...e,lastCommit:I,completionSummary:m,completionRecordId:v?.id,completedAt:t}},n=await w.updateTask(h,r)
233
+ p.info("Raw task update response data",{responseData:JSON.stringify(n)}),p.debug("Task update response structure",{type:typeof n,isArray:Array.isArray(n),hasData:null!=n,properties:n?Object.keys(n):[],dataPreview:n?JSON.stringify(n).substring(0,200)+"...":"null"}),(0,s.extractDataFromResponse)(n,{logger:p,operationName:"updateTask",defaultValue:{id:h,status:"completed"}}),p.info("Successfully completed task",{taskId:h,recordId:v?.id})
234
+ const o=k.requestId,i=k.requestId
235
+ let a=`Task ${k.sequenceNumber&&i?(0,l.formatTaskRef)(i,k.sequenceNumber):h} (${k.title}) has been marked as completed.`
236
+ if(v?.id&&(a+=`\n[RECORD:${v.id}]`),I&&(a+="\nCommit: "+I.substring(0,8)),o)try{const e=await w.listTasks({requestId:o})
237
+ p.info("Raw tasks list response data",{responseData:JSON.stringify(e)}),p.debug("Tasks list response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
238
+ const t=(0,s.extractArrayFromResponse)(e,{logger:p,operationName:"listTasksForProgress",defaultValue:[]}),r=t.length,n=t.filter((e=>"completed"===e.status)).length
239
+ p.info("Task progress check",{requestId:o,totalTasks:r,completedTasks:n}),a+=`\n\nTask Progress: ${n}/${r} tasks completed`,n===r&&(a+=`\n\nAll tasks for request ${o} are now completed! You may consider marking the request as completed using the complete-request tool.`)}catch(e){p.warn("Failed to check task progress",{error:(0,c.getErrorMessage)(e),requestId:o})}return f({success:!0}),{content:[{type:"text",text:a}]}}catch(e){throw p.error("Failed to complete task",{error:e instanceof Error?e.stack:e+"",taskId:h}),Error("Failed to complete task: "+(0,c.getErrorMessage)(e))}}catch(t){if(p.error("Failed to complete task",{error:t instanceof Error?t.stack:t+"",args:e}),d.projectId)try{const r=u.getToolRecordClient()
237
240
  if(r){const o=t instanceof n.NotFoundError||t instanceof n.ValidationError||t instanceof i.ZodError
238
- await r.createToolRecord({...o?{}:{taskId:e.taskId},projectId:l.projectId,type:"complete-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.summary?.substring(0,100)+(e.summary?.length>100?"...":""),error:(0,c.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",attemptedTaskId:e.taskId,taskIdValidationFailed:o},note:"Failed to complete task "+e.taskId})}}catch(e){g.error("Failed to create failure record for task completion",{error:e instanceof Error?e.message:e+""})}p({success:!1,error:t instanceof Error?t.name:"unknown"})
241
+ await r.createToolRecord({...o?{}:{taskId:e.taskId},projectId:d.projectId,type:"complete-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.summary?.substring(0,100)+(e.summary?.length>100?"...":""),error:(0,c.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",attemptedTaskId:e.taskId,taskIdValidationFailed:o},note:"Failed to complete task "+e.taskId})}}catch(e){p.error("Failed to create failure record for task completion",{error:e instanceof Error?e.message:e+""})}f({success:!1,error:t instanceof Error?t.name:"unknown"})
239
242
  let r=(0,c.getErrorMessage)(t)
240
243
  return t instanceof n.NotFoundError&&(r=`The task ID "${e.taskId}" was not found. Please provide a valid task ID.`),t instanceof o.ConnectionError&&(r="Unable to complete task: Connection to the server failed. Please check your network connection and try again."),t instanceof i.ZodError&&t.errors.length>0&&(r=t.errors[0].message),{content:[{type:"text",text:"Error: "+r}],isError:!0}}}
241
- const r=t(6183),n=t(9860),o=t(5674),s=t(2960),i=t(1569),a=t(5172),c=t(8824)},405(e,exports,t){"use strict"
244
+ const r=t(6183),n=t(9860),o=t(5674),s=t(2960),i=t(1569),a=t(5172),c=t(8824),l=t(4466)},405(e,exports,t){"use strict"
242
245
  var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
243
246
  var o=Object.getOwnPropertyDescriptor(t,r)
244
247
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[]
@@ -274,14 +277,18 @@ if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
274
277
  return o(t,e),t})
275
278
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleTaskOperations=async function(e,t,r,n,o){const s=n.child({tool:"task_operations"})
276
279
  try{e?.list?.filters&&"object"==typeof e.list.filters?(Object.assign(e,e.list.filters),delete e.list):e?.list&&"object"==typeof e.list&&(Object.assign(e,e.list),delete e.list)
277
- const n=a.validateArgs(e,i.TaskOperationsSchema),{taskId:d,operation:u}=n
278
- let h
279
- switch(s.info("Processing task_operations",{taskId:d,operation:u}),u){case"get-info":s.info("Routing to get-task-information handler",{taskId:d}),h=await(0,c.handleGetTaskInformation)({taskId:d},t,r,s,o)
280
+ const n=a.validateArgs(e,i.TaskOperationsSchema),{taskId:h,operation:g}=n
281
+ let p
282
+ switch(s.info("Processing task_operations",{taskId:h,operation:g}),g){case"create":s.info("Routing to create-task handler",{requestId:n.requestId,title:n.title}),p=await(0,u.handleCreateTask)({requestId:n.requestId,title:n.title,description:n.description},t,r,s,o)
280
283
  break
281
- case"list":s.info("Routing to list-tasks handler",{requestId:n.requestId}),h=await(0,l.handleListTasks)({requestId:n.requestId,filters:{status:n.status,limit:n.limit,offset:n.offset,sortBy:n.sortBy,sortDirection:n.sortDirection}},t,r,s,o)
284
+ case"complete":s.info("Routing to complete-task handler",{taskId:h}),p=await(0,c.handleCompleteTask)({taskId:h,summary:n.summary},t,r,s,o)
282
285
  break
283
- default:throw Error("Unknown operation type: "+u)}return s.info("task_operations completed",{taskId:d,operation:u,success:!h.isError}),o.incrementCounter("task_operations_total",1,{operation:u,success:!h.isError}),h}catch(e){return s.error("task_operations failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("task_operations_errors",1),{content:[{type:"text",text:"\u274c **Task Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
284
- const i=t(6183),a=s(t(5967)),c=t(3420),l=t(9863),d=t(8824)},441(e,exports){"use strict"
286
+ case"get-info":s.info("Routing to get-task-information handler",{taskId:h}),p=await(0,l.handleGetTaskInformation)({taskId:h},t,r,s,o)
287
+ break
288
+ case"list":s.info("Routing to list-tasks handler",{requestId:n.requestId}),p=await(0,d.handleListTasks)({requestId:n.requestId,filters:{status:n.status,limit:n.limit,offset:n.offset,sortBy:n.sortBy,sortDirection:n.sortDirection}},t,r,s,o)
289
+ break
290
+ default:throw Error(`Unknown operation: ${g}. Valid operations: create, complete, get-info, list`)}return s.info("task_operations completed",{taskId:h,operation:g,success:!p.isError}),o.incrementCounter("task_operations_total",1,{operation:g,success:!p.isError}),p}catch(e){return s.error("task_operations failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("task_operations_errors",1),{content:[{type:"text",text:"\u274c **Task Operations Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
291
+ const i=t(6183),a=s(t(5967)),c=t(355),l=t(3420),d=t(9863),u=t(76),h=t(8824)},441(e,exports){"use strict"
285
292
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.BAD_REQUEST=exports.INTERNAL_ERROR=exports.NOT_FOUND=exports.FORBIDDEN=exports.UNAUTHORIZED=exports.VALIDATION_ERROR=exports.MCP_PROTOCOL_ERROR=exports.REQUEST_VALIDATION_FAILED=exports.REQUEST_ID_INVALID_FORMAT=exports.REQUEST_NOT_FOUND=exports.CONNECTION_ERROR=exports.SERVICE_UNAVAILABLE=exports.CONNECTION_TIMEOUT=exports.SERVER_ERROR=exports.NETWORK_ERROR=exports.TASK_VALIDATION_FAILED=exports.TASK_ID_INVALID_FORMAT=exports.TASK_NOT_FOUND=void 0,exports.TASK_NOT_FOUND="TASK_NOT_FOUND",exports.TASK_ID_INVALID_FORMAT="TASK_ID_INVALID_FORMAT",exports.TASK_VALIDATION_FAILED="TASK_VALIDATION_FAILED",exports.NETWORK_ERROR="NETWORK_ERROR",exports.SERVER_ERROR="SERVER_ERROR",exports.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",exports.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",exports.CONNECTION_ERROR="CONNECTION_ERROR",exports.REQUEST_NOT_FOUND="REQUEST_NOT_FOUND",exports.REQUEST_ID_INVALID_FORMAT="REQUEST_ID_INVALID_FORMAT",exports.REQUEST_VALIDATION_FAILED="REQUEST_VALIDATION_FAILED",exports.MCP_PROTOCOL_ERROR="MCP_PROTOCOL_ERROR",exports.VALIDATION_ERROR="VALIDATION_ERROR",exports.UNAUTHORIZED="UNAUTHORIZED",exports.FORBIDDEN="FORBIDDEN",exports.NOT_FOUND="NOT_FOUND",exports.INTERNAL_ERROR="INTERNAL_ERROR",exports.BAD_REQUEST="BAD_REQUEST"},446(e,exports,t){"use strict"
286
293
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.LockOverrideManager=void 0,exports.createLockOverrideManager=function(e){return new n(e)}
287
294
  const r=t(6982)
@@ -367,22 +374,23 @@ var t={}
367
374
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
368
375
  return o(t,e),t})
369
376
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQueryHistory=async function(e,r,n,o,s,g){const p=o.child({tool:"query_history"})
370
- try{const o=a.validateArgs(e,i.QueryHistorySchema),{queryType:h}=o
371
- let f
372
- switch(p.info("Processing query_history request",{queryType:h}),h){case"file-history":p.info("Routing to file-history handler",{path:o.fileHistory.path}),f=await(0,c.handleFileHistory)({path:o.fileHistory.path,limit:o.fileHistory.limit,showDiff:o.fileHistory.showDiff,showTraceability:o.fileHistory.showTraceability,branch:o.fileHistory.branch,since:o.fileHistory.since},r,n,p,s)
377
+ try{const h=a.validateArgs(e,i.QueryHistorySchema),{queryType:f}=h
378
+ let m
379
+ switch(p.info("Processing query_history request",{queryType:f}),f){case"file-history":p.info("Routing to file-history handler",{path:h.fileHistory.path}),m=await(0,c.handleFileHistory)({path:h.fileHistory.path,limit:h.fileHistory.limit,showDiff:h.fileHistory.showDiff,showTraceability:h.fileHistory.showTraceability,branch:h.fileHistory.branch,since:h.fileHistory.since},r,n,p,s)
373
380
  break
374
- case"request-file-history":p.info("Routing to request-file-history handler",{requestId:o.requestHistory.requestId}),f=await(0,l.handleRequestFileHistory)({requestId:o.requestHistory.requestId,showDiff:o.requestHistory.showDiff,detailLevel:o.requestHistory.detailLevel,taskId:o.requestHistory.taskId,fileFilter:o.requestHistory.fileFilter},r,n,p,s)
381
+ case"request-file-history":p.info("Routing to request-file-history handler",{requestId:h.requestHistory.requestId}),m=await(0,l.handleRequestFileHistory)({requestId:h.requestHistory.requestId,showDiff:h.requestHistory.showDiff,detailLevel:h.requestHistory.detailLevel,taskId:h.requestHistory.taskId,fileFilter:h.requestHistory.fileFilter},r,n,p,s)
375
382
  break
376
- case"recover":p.info("Routing to file-recover handler",{taskId:o.recover.taskId,path:o.recover.path,commitHash:o.recover.commitHash})
377
- let e=o.recover.commitHash
378
- if(!e){const n=o.recover.path,s=r.basePath||process.cwd(),{resolve:i}=await Promise.resolve().then(t.t.bind(t,6928,23)),a=i(s,n)
379
- try{const{execSync:r}=await Promise.resolve().then(t.t.bind(t,5317,23)),o=r(`git log --format=%H -n 2 -- "${a}"`,{cwd:s,encoding:"utf8"}).trim().split("\n").filter(Boolean)
380
- if(e=o[1]||o[0],!e)return{content:[{type:"text",text:"No previous versions found for "+n}],isError:!0}
381
- p.info("Auto-resolved previous version",{filePath:n,commitHash:e})}catch{return{content:[{type:"text",text:"Could not find previous versions of "+n}],isError:!0}}}f=await(0,d.handleFileRecover)({taskId:o.recover.taskId,path:o.recover.path,commitHash:e,createBackup:o.recover.createBackup},r,n,n.getToolRecordClient(),p,s,g)
383
+ case"recover":p.info("Routing to file-recover handler",{path:h.recover.path,commitHash:h.recover.commitHash})
384
+ let i=h.recover.commitHash
385
+ if(!i){const e=h.recover.path,n=r.workspaceManager?.getCurrentContext(r.currentSessionId)?.basePath||r.basePath||process.cwd(),{resolve:o}=await Promise.resolve().then(t.t.bind(t,6928,23)),s=o(n,e)
386
+ try{const{execSync:r}=await Promise.resolve().then(t.t.bind(t,5317,23)),o=r(`git log --format=%H -n 2 -- "${s}"`,{cwd:n,encoding:"utf8"}).trim().split("\n").filter(Boolean)
387
+ if(i=o[1]||o[0],!i)return{content:[{type:"text",text:"No previous versions found for "+e}],isError:!0}
388
+ p.info("Auto-resolved previous version",{filePath:e,commitHash:i})}catch{return{content:[{type:"text",text:"Could not find previous versions of "+e}],isError:!0}}}m=await(0,d.handleFileRecover)({taskId:e.recover?.taskId||await(async()=>{const{resolveActiveTaskId:e}=await Promise.resolve().then(t.bind(t,3451))
389
+ return await e(r,n,o)||"untracked"})(),path:h.recover.path,commitHash:i,createBackup:h.recover.createBackup},r,n,n.getToolRecordClient(),p,s,g)
382
390
  break
383
- case"blame":p.info("Routing to file-blame handler",{path:o.blame.path,lines:o.blame.lines}),f=await(0,u.handleFileBlame)({path:o.blame.path,lines:o.blame.lines,branch:o.blame.branch},r,n,p,s)
391
+ case"blame":p.info("Routing to file-blame handler",{path:h.blame.path,lines:h.blame.lines}),m=await(0,u.handleFileBlame)({path:h.blame.path,lines:h.blame.lines,branch:h.blame.branch},r,n,p,s)
384
392
  break
385
- default:throw Error("Unknown query type: "+h)}return p.info("query_history request completed",{queryType:h,success:!f.isError}),s.incrementCounter("query_history_total",1,{success:!f.isError,queryType:h}),f}catch(e){return p.error("query_history request failed",{error:e instanceof Error?e.stack:e+""}),s.incrementCounter("query_history_errors",1),{content:[{type:"text",text:"\u274c **Query History Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
393
+ default:throw Error("Unknown query type: "+f)}return p.info("query_history request completed",{queryType:f,success:!m.isError}),s.incrementCounter("query_history_total",1,{success:!m.isError,queryType:f}),m}catch(e){return p.error("query_history request failed",{error:e instanceof Error?e.stack:e+""}),s.incrementCounter("query_history_errors",1),{content:[{type:"text",text:"\u274c **Query History Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
386
394
  const i=t(6183),a=s(t(5967)),c=t(8828),l=t(8317),d=t(4640),u=t(4811),h=t(8824)},1038(e,exports){"use strict"
387
395
  function t(e){let t
388
396
  if("string"==typeof e.metadata&&e.metadata)try{t=JSON.parse(e.metadata)}catch(e){t=void 0}else e.metadata&&"object"==typeof e.metadata&&(t=e.metadata)
@@ -443,21 +451,21 @@ if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
443
451
  return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
444
452
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerApiRoutes=async function(e,r,n,o){const s=n.child({component:"api"}),i=r.getTokenManager(),T=process.env.REMOTE_SERVER_URL||"https://api.alchemylabcode.com",P=new m.AuthenticationManager(i,n.child({component:"auth-manager"})),j=P.getTokenSynchronizer(),R=await P.getTokenString()||void 0
445
453
  n.debug("Token retrieved from authentication manager")
446
- const M=new k.ConnectionStatusManager(T,n.child({component:"connection-status-manager"}),o,{checkIntervalMs:3e4,timeoutMs:5e3}),x=new w.ProjectClient(T,n.child({component:"project-client"}),o,M,R)
447
- j.registerClient(x)
448
- const O=new I.TaskClient(T,n.child({component:"task-client"}),o,x,M,R)
454
+ const x=new k.ConnectionStatusManager(T,n.child({component:"connection-status-manager"}),o,{checkIntervalMs:3e4,timeoutMs:5e3}),M=new w.ProjectClient(T,n.child({component:"project-client"}),o,x,R)
455
+ j.registerClient(M)
456
+ const O=new I.TaskClient(T,n.child({component:"task-client"}),o,M,x,R)
449
457
  j.registerClient(O)
450
- const D=new v.FileOperationsClient(T,n.child({component:"file-client"}),o,x,R,M)
458
+ const D=new v.FileOperationsClient(T,n.child({component:"file-client"}),o,M,R,x)
451
459
  j.registerClient(D)
452
- const $=new C.ProxyClient(T,n.child({component:"proxy-client"}),o,x,R,M)
460
+ const $=new C.ProxyClient(T,n.child({component:"proxy-client"}),o,M,R,x)
453
461
  j.registerClient($)
454
- const A=new _.RequestClient(T,n.child({component:"request-client"}),o,x,R,M)
462
+ const A=new _.RequestClient(T,n.child({component:"request-client"}),o,M,R,x)
455
463
  A.setAuthToken(R),(0,d.isDebugToolsEnabled)()&&n.debug("Explicitly set token on RequestClient",{tokenPresent:!!R}),j.registerClient(A)
456
- const F=new E.DocumentClient(T,n.child({component:"document-client"}),o,x,R,M)
464
+ const F=new E.DocumentClient(T,n.child({component:"document-client"}),o,M,R,x)
457
465
  j.registerClient(F)
458
- const N=new q.ToolRecordClient(T,n.child({component:"tool-record-client"}),o,x,R,M)
466
+ const N=new q.ToolRecordClient(T,n.child({component:"tool-record-client"}),o,M,R,x)
459
467
  j.registerClient(N)
460
- const L=new S.ApiClient(P,x,O,D,A,F,N,$,n.child({component:"api-client"})),z=a.default.Router();(0,h.registerAuthRoutes)(z,{projectClient:x,taskClient:O,fileClient:D,authManager:P,apiClient:L},i,n)
468
+ const L=new S.ApiClient(P,M,O,D,A,F,N,$,n.child({component:"api-client"})),z=a.default.Router();(0,h.registerAuthRoutes)(z,{projectClient:M,taskClient:O,fileClient:D,authManager:P,apiClient:L},i,n)
461
469
  const H=r.getContext();(0,g.registerConfigRoutes)(z,n,H.basePath),e.use("/api",z)
462
470
  const B=e=>{const t=o.startTimer(e)
463
471
  return e=>t(e)},U=(e,t,n)=>{const o=e.query.path||e.body.path
@@ -511,7 +519,7 @@ e({endpoint:"git/status",method:"GET",success:!0}),t.json({success:!0,data:{curr
511
519
  const s=B("api_request_duration"),i=r.getContext(),{message:a,taskId:c}=e.body
512
520
  if(!a)throw(0,u.createValidationError)("Commit message is required")
513
521
  let l=i.git
514
- if(i.workspaceManager){const e=i.workspaceManager.getCurrentContext()
522
+ if(i.workspaceManager){const e=i.workspaceManager.getCurrentContext(i.currentSessionId)
515
523
  if("multi-agent"===e.mode&&e.requestId){if(!e.basePath.includes("/worktrees/")&&!e.basePath.includes("\\worktrees\\"))throw(0,u.createValidationError)(`Multi-agent mode error: Cannot commit from main repo context. Expected worktree path but got: ${e.basePath}. This would commit to main branch instead of request branch.`)
516
524
  const{simpleGit}=t(3807)
517
525
  l=simpleGit(e.basePath)}}if(!l)throw s({endpoint:"git/commit",method:"POST",success:!1,error:"no_git"}),(0,u.createValidationError)("Git is not available for this workspace")
@@ -520,10 +528,10 @@ const d=await l.commit(a)
520
528
  try{await l.revparse(["--abbrev-ref","HEAD"]),await l.revparse(["HEAD"]),await l.revparse(["--show-toplevel"])}catch(e){}s({endpoint:"git/commit",method:"POST",success:!0}),n.json({success:!0,data:{commit:d.commit,author:d.author,summary:d.summary,message:a}})}catch(e){s(e)}})),e.post("/api/sync/projects",(async(e,t,n)=>{try{o.incrementCounter("api_requests_total",1,{endpoint:"sync/projects",method:"POST"})
521
529
  const e=B("api_request_duration")
522
530
  r.getContext(),s.info("Manual project synchronization requested"),s.info("Starting manual project synchronization")
523
- try{await x.syncProjects(),e({endpoint:"sync/projects",method:"POST",success:!0}),t.json({success:!0,data:{message:"Project synchronization completed successfully",timestamp:(new Date).toISOString()}})}catch(r){s.error("Project synchronization failed",{error:r instanceof Error?r.stack:r+""}),e({endpoint:"sync/projects",method:"POST",success:!1}),t.status(500).json({success:!1,error:"Project synchronization failed",message:r instanceof Error?r.message:r+"",timestamp:(new Date).toISOString()})}}catch(e){n(e)}})),e.get("/api/remote/status",(async(e,t,r)=>{try{o.incrementCounter("api_requests_total",1,{endpoint:"remote/status",method:"GET"})
531
+ try{await M.syncProjects(),e({endpoint:"sync/projects",method:"POST",success:!0}),t.json({success:!0,data:{message:"Project synchronization completed successfully",timestamp:(new Date).toISOString()}})}catch(r){s.error("Project synchronization failed",{error:r instanceof Error?r.stack:r+""}),e({endpoint:"sync/projects",method:"POST",success:!1}),t.status(500).json({success:!1,error:"Project synchronization failed",message:r instanceof Error?r.message:r+"",timestamp:(new Date).toISOString()})}}catch(e){n(e)}})),e.get("/api/remote/status",(async(e,t,r)=>{try{o.incrementCounter("api_requests_total",1,{endpoint:"remote/status",method:"GET"})
524
532
  const e=B("api_request_duration")
525
- try{const r=await x.pingDetailed(),n="online"===r.status,o=r.latency
526
- e({endpoint:"remote/status",method:"GET",success:!0,connected:n}),s.info("Remote server status check",{status:n?"ONLINE":"OFFLINE",latencyMs:o}),t.json({success:!0,data:{connected:n,url:T,latency:o,queueStats:{total:0,pending:0,inProgress:0,completed:0,failed:0},isOffline:x.isOffline(),serverTime:(new Date).toISOString()}})}catch(r){e({endpoint:"remote/status",method:"GET",success:!0,connected:!1}),t.json({success:!0,data:{connected:!1,url:T,error:(0,b.getErrorMessage)(r),serverTime:(new Date).toISOString()}})}}catch(e){r(e)}})),e.get("/api/proxy/*",(async(e,t,r)=>{try{const r=e.path.substring(11)
533
+ try{const r=await M.pingDetailed(),n="online"===r.status,o=r.latency
534
+ e({endpoint:"remote/status",method:"GET",success:!0,connected:n}),s.info("Remote server status check",{status:n?"ONLINE":"OFFLINE",latencyMs:o}),t.json({success:!0,data:{connected:n,url:T,latency:o,queueStats:{total:0,pending:0,inProgress:0,completed:0,failed:0},isOffline:M.isOffline(),serverTime:(new Date).toISOString()}})}catch(r){e({endpoint:"remote/status",method:"GET",success:!0,connected:!1}),t.json({success:!0,data:{connected:!1,url:T,error:(0,b.getErrorMessage)(r),serverTime:(new Date).toISOString()}})}}catch(e){r(e)}})),e.get("/api/proxy/*",(async(e,t,r)=>{try{const r=e.path.substring(11)
527
535
  try{const n=await L.proxyGet(r,e.query)
528
536
  t.json(n)}catch(e){if(e instanceof Error&&e.message.includes("ECONNREFUSED"))return t.status(503).json({success:!1,error:"Remote server is unreachable",remotePath:r})
529
537
  throw e}}catch(e){r(e)}})),e.post("/api/proxy/*",G,(async(e,t,r)=>{try{const r=e.path.substring(11)
@@ -656,22 +664,22 @@ if(!n||""===n.trim())return l.info("Empty needle detected, switching to list-all
656
664
  if("string"!=typeof n)throw I.errors.push("Search term (needle) must be a string"),(0,f.createValidationError)("Search term (needle) must be a string")
657
665
  let C
658
666
  if(I.searchDirectory=p||".",p){const{normalizedPath:e,fullPath:r}=m.validateAndNormalizePath(p,t)
659
- C=r}else C=t.basePath
667
+ C=r}else C=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
660
668
  I.resolvedPath=C
661
669
  let _=!1
662
670
  try{_=(await g.default.stat(C)).isFile()}catch(e){const t=`Cannot access path ${C}: ${(0,k.getErrorMessage)(e)}`
663
671
  throw I.errors.push(t),Error(t)}const E=v.maxResults||50,q=v.caseSensitive||!1,S=v.useRegex||!1,T=v.fileExtension,P=v.searchIn||"content"
664
672
  let j=void 0!==v.contextLines?v.contextLines:0
665
673
  if(0>j?j=0:j>10&&(l.warn(`contextLines ${j} exceeds maximum of 10, clamping to 10`),j=10),!_&&!T)throw I.errors.push('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")'),(0,f.createValidationError)('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")')
666
- let R,M=""
667
- if(_)M="*"
668
- else if("*"===T)M="*"
669
- else if(T){let e=T;(e.startsWith("*.")||e.startsWith("*"))&&(e=e.substring(1)),M=e.startsWith(".")?e:"."+e}try{R=S?q?RegExp(n):RegExp(n,"i"):q?RegExp(o(n)):RegExp(o(n),"i")}catch(e){const t=`Invalid ${S?"regex":"search"} pattern: ${(0,k.getErrorMessage)(e)}`
670
- throw I.errors.push(t),(0,f.createValidationError)(t)}if(I.patternInfo={needle:n,regex:R.toString(),caseSensitive:q,fileExtension:T,normalizedExtension:M},!_)try{const e=Date.now(),t=await g.default.readdir(C,{withFileTypes:!0}),r=[],n=[]
674
+ let R,x=""
675
+ if(_)x="*"
676
+ else if("*"===T)x="*"
677
+ else if(T){let e=T;(e.startsWith("*.")||e.startsWith("*"))&&(e=e.substring(1)),x=e.startsWith(".")?e:"."+e}try{R=S?q?RegExp(n):RegExp(n,"i"):q?RegExp(o(n)):RegExp(o(n),"i")}catch(e){const t=`Invalid ${S?"regex":"search"} pattern: ${(0,k.getErrorMessage)(e)}`
678
+ throw I.errors.push(t),(0,f.createValidationError)(t)}if(I.patternInfo={needle:n,regex:R.toString(),caseSensitive:q,fileExtension:T,normalizedExtension:x},!_)try{const e=Date.now(),t=await g.default.readdir(C,{withFileTypes:!0}),r=[],n=[]
671
679
  for(const e of t)e.isDirectory()?r.push(e.name):e.isFile()&&n.push(e.name)
672
680
  I.initialScan={totalEntries:t.length,directories:r,files:n,firstFewFiles:n.slice(0,10),scanTime:Date.now()-e},I.phases.directoryListingTime=I.initialScan.scanTime}catch(e){const t="Failed to scan directory contents: "+(0,k.getErrorMessage)(e)
673
- I.errors.push(t),l.error(t)}const x=_?"file":"directory"
674
- l.info(`Searching for "${n}" in ${x} ${C} (mode: ${P})`,{needle:n,searchTarget:x,path:C,options:{maxResults:E,caseSensitive:q,fileExtension:M,searchIn:P}}),b=Date.now(),I.phases.initializationTime=b-u
681
+ I.errors.push(t),l.error(t)}const M=_?"file":"directory"
682
+ l.info(`Searching for "${n}" in ${M} ${C} (mode: ${P})`,{needle:n,searchTarget:M,path:C,options:{maxResults:E,caseSensitive:q,fileExtension:x,searchIn:P}}),b=Date.now(),I.phases.initializationTime=b-u
675
683
  const O=Date.now()
676
684
  let D=[],$=0,A=0
677
685
  try{const e=await async function(e,t,n,o,s,i){const{maxResults:a,fileExtension:c,searchIn:l,isFile:d,contextLines:u}=n,p=[]
@@ -689,15 +697,15 @@ o.errors.push(r),n.error(r)}return{matches:i,totalFiles:1}}(e,t,l,s,i,u)
689
697
  const f={path:e,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
690
698
  try{const{filesCount:n,fileMatchesCount:c,subdirCount:d,subdirStats:h}=await r(e,t,p,a,o,s,0,f,l,u)
691
699
  return f.filesProcessed=n,f.filesMatched=c,f.subdirectories=d,i.directoryStats.push(f),h&&h.length>0&&i.directoryStats.push(...h),s.info("performLocalSearch completed",{totalFiles:n,matchesFound:p.length,directories:d+1}),{matches:p,totalFiles:n}}catch(t){const r="Error in performLocalSearch: "+(0,k.getErrorMessage)(t)
692
- return f.errors.push(r),i.directoryStats.push(f),i.errors.push(r),s.error(r,{error:t instanceof Error?t.stack:t+"",searchPath:e}),{matches:p,totalFiles:f.filesProcessed}}}(C,R,{maxResults:E,fileExtension:M,searchIn:P,isFile:_,contextLines:j},M,l,I)
700
+ return f.errors.push(r),i.directoryStats.push(f),i.errors.push(r),s.error(r,{error:t instanceof Error?t.stack:t+"",searchPath:e}),{matches:p,totalFiles:f.filesProcessed}}}(C,R,{maxResults:E,fileExtension:x,searchIn:P,isFile:_,contextLines:j},x,l,I)
693
701
  D=e.matches,$=e.totalFiles
694
702
  const t=1e3
695
703
  D.length>0&&D.length<=t?(D.sort(((e,t)=>void 0!==e.modifiedTime&&void 0!==t.modifiedTime?t.modifiedTime-e.modifiedTime:void 0!==e.modifiedTime&&void 0===t.modifiedTime?-1:void 0===e.modifiedTime&&void 0!==t.modifiedTime?1:0)),l.info(`Sorted ${D.length} matches by modification time (newest first)`)):D.length>t&&l.info(`Skipped sorting ${D.length} matches (exceeds hard cap of ${t} for performance)`),A=D.length,D.length>E&&(D=D.slice(0,E),l.info(`Limited results to ${E} (from ${A} total matches)`)),D.forEach((e=>{e.relativePath=function(e,t){const r=h.default.relative(e,t)
696
704
  return r?r===h.default.basename(t)?r:r.startsWith("./")?r.substring(2):r:h.default.basename(t)}(C,e.file)})),l.info(`Local search completed: found ${A||D.length} total matches in ${$} files, returning ${D.length} results`),I.phases.searchTime=Date.now()-O}catch(e){const t="Error during search: "+(0,k.getErrorMessage)(e)
697
705
  I.errors.push(t),l.error(t),I.phases.searchTime=Date.now()-O}I.totalFiles=$,I.totalMatches=D.length,I.endTime=Date.now()
698
706
  let F,N=""
699
- try{if(t.getCurrentBranchContext){const e=await t.getCurrentBranchContext()
700
- e.branch&&(N=e.isMain?` (searched on main branch: ${e.branch})`:` (searched on request branch: ${e.branch}${e.requestId?" for "+e.requestId:""})`)}}catch(e){l.debug("Could not get branch context",{error:e}),N=" (branch context unavailable)"}l.debug("Search diagnostic information",{diagnostic:I})
707
+ try{if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
708
+ e.branchName&&!e.permanentBranch&&(N=e.isMainBranch?` (searched on main branch: ${e.branchName})`:` (searched on request branch: ${e.branchName}${e.requestId?" for "+e.requestId:""})`)}}catch(e){l.debug("Could not get branch context",{error:e}),N=" (branch context unavailable)"}l.debug("Search diagnostic information",{diagnostic:I})
701
709
  const L="content"===P?"content":"filename"===P?"filenames":"content and filenames"
702
710
  if(A>D.length?(F=`Found ${A} results for "${n}" (searching ${L})`,p&&(F+=" in "+p),T&&(F+=" with extension "+T),F+=`${N}. Showing first ${D.length}:\n\n`):(F=`Found ${D.length} results for "${n}" (searching ${L})`,p&&(F+=" in "+p),T&&(F+=" with extension "+T),F+=N+":\n\n"),D.length>0)if(j>0){const{filenameMatches:e,mergedGroups:t}=function(e,t){const r=e.filter((e=>"filename"===e.matchType)),n=e.filter((e=>"content"===e.matchType))
703
711
  if(0===n.length)return{filenameMatches:r,mergedGroups:[]}
@@ -828,7 +836,7 @@ if(r&&!o){const t=r[1]
828
836
  v=!0
829
837
  try{const{sessionTag:r}=(0,h.getGlobalClientInfo)(),o=n.getSessionTagMappingClient(),s=n.getRequestClient(),i=o?o.getMappingByOpencodeSessionId(e.sessionId).then((t=>{t?((0,h.setSessionTag)(t.sessionTag),m.info("Recovered session tag from mapping",{opencodeSessionId:e.sessionId,sessionTag:t.sessionTag})):(o.createOrUpdateMapping(r,e.sessionId).catch((()=>{})),m.info("Registered session tag mapping",{opencodeSessionId:e.sessionId,sessionTag:r}))}),(e=>m.debug("Mapping lookup failed",{error:(0,l.getErrorMessage)(e)}))):Promise.resolve(),a=s.lockRequest?s.lockRequest(t,r).then((e=>{e.locked?m.info("Acquired request lock",{requestId:t,sessionTag:r}):m.warn("Failed to acquire request lock",{requestId:t,sessionTag:r})}),(e=>m.warn("Lock acquisition failed",{error:(0,l.getErrorMessage)(e)}))):Promise.resolve()
830
838
  await Promise.all([i,a])}catch(e){m.warn("Error in session tag mapping / lock acquisition",{error:(0,l.getErrorMessage)(e)})}}}}let q
831
- if(C){const e={context:t,apiClient:n,logger:o,metrics:s,mcpServer:g,cliOrigin:_}
839
+ if(t&&(t.currentSessionId=E||"__unknown__"),C){const e={context:t,apiClient:n,logger:o,metrics:s,mcpServer:g,cliOrigin:_}
832
840
  q=await C.handler(I,e)}else m.info(`Tool ${i} not found, returning negative response`),q={content:[{type:"text",text:`The tool '${i}' does not exist.`}]}
833
841
  return Date.now(),Date.now(),k({tool:i,success:!0}),q}catch(t){m.error("Error executing tool:",{error:t instanceof Error?t.stack:t+"",tool:e.params.name}),s.incrementCounter("tool_errors_total",1,{tool:e.params.name,error:t instanceof Error?t.name:"unknown"})
834
842
  let r="Unknown error"
@@ -850,7 +858,8 @@ var g=t(7280)
850
858
  Object.defineProperty(exports,"logSessionIdentity",{enumerable:!0,get(){return g.logSessionIdentity}})
851
859
  const p=t(7280)
852
860
  t(2462)
853
- const f=t(2245)},1483(e,exports,t){"use strict"
861
+ const f=t(2245)
862
+ i(t(857))},1483(e,exports,t){"use strict"
854
863
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSearchDocuments=async function(e,t,s,i,a){const c=i.child({tool:"search_documents"}),l=a.startTimer("tool_execution_time")
855
864
  try{let i
856
865
  try{i=r.SearchDocumentsSchema.parse(e)}catch(t){if(t instanceof n.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
@@ -1195,7 +1204,7 @@ if(u=e?.requestContextMode,!u){const e=(0,S.getBuiltInAgentConfig)(i)
1195
1204
  u=e?.requestContextMode}}catch{}if(u&&"none"!==u&&!c)return{content:[{type:"text",text:`\u274c Agent '${i}' requires a requestId to be provided.\n\nThis agent has requestContextMode: '${u}' which means it needs to work in the context of a specific request.\n\nPlease provide a requestId when spawning this agent.`}],isError:!0}
1196
1205
  const h=await(0,k.getServerUrl)(t,n)
1197
1206
  r(t,"serverUrl resolved",{serverUrl:h})
1198
- const g=t.basePath
1207
+ const g=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
1199
1208
  if(!g)throw new y.ValidationError("Working directory not available in context")
1200
1209
  const p=s?.sessionId
1201
1210
  let f=""
@@ -1340,18 +1349,22 @@ var t={}
1340
1349
  if(null!=e)for(var r=g(e),n=0;n<r.length;n++)"default"!==r[n]&&p(t,e,r[n])
1341
1350
  return f(t,e),t})
1342
1351
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpawn=n,exports.handleContinue=o,exports.handleCheckStatus=d,exports.handleAbort=u,exports.handleListSessions=h,exports.handleSubagentOperations=async function(e,t,r,s,i,a){const c=r.child({tool:"subagent_operations"}),l=s.startTimer("tool_execution_time")
1343
- try{if(e&&!e.operation&&(e.spawn?e.operation="spawn":e.continue?e.operation="continue":e.readMessages?e.operation="read-messages":e.listSessions?e.operation="list-sessions":e.prompt&&(e.agent||e.description)?e={operation:"spawn",spawn:{agent:e.agent||"coder",prompt:e.prompt,description:e.description||e.prompt.slice(0,60),requestId:e.requestId,allowParallel:e.allowParallel,useExistingSession:e.useExistingSession}}:e.sessionId&&e.prompt&&!e.spawn?e={operation:"continue",sessionId:e.sessionId,continue:{prompt:e.prompt}}:e.sessionId&&(e={operation:"check-status",sessionId:e.sessionId})),e?.spawn&&"string"==typeof e.spawn)try{e.spawn=JSON.parse(e.spawn)}catch{}if(e?.continue&&"string"==typeof e.continue)try{e.continue=JSON.parse(e.continue)}catch{}"spawn"===e?.operation&&e?.prompt&&!e?.spawn&&(e.spawn={agent:e.agent||"coder",prompt:e.prompt,description:e.description||e.prompt.slice(0,60),requestId:e.requestId},delete e.prompt,delete e.agent,delete e.description,delete e.requestId),"continue"===e?.operation&&e?.prompt&&!e?.continue&&(e.continue={prompt:e.prompt},delete e.prompt)
1352
+ try{if(e?.spawn&&"object"==typeof e.spawn){const t=e.spawn
1353
+ e.agent=e.agent||t.agent,e.prompt=e.prompt||t.prompt,e.description=e.description||t.description,e.requestId=e.requestId||t.requestId,e.allowParallel=e.allowParallel??t.allowParallel,e.useExistingSession=e.useExistingSession||t.useExistingSession,delete e.spawn}if(e?.continue&&"object"==typeof e.continue){const t=e.continue
1354
+ e.prompt=e.prompt||t.prompt,delete e.continue}if(e?.readMessages&&"object"==typeof e.readMessages){const t=e.readMessages
1355
+ e.limit=e.limit??t.limit,delete e.readMessages}if(e?.listSessions&&"object"==typeof e.listSessions){const t=e.listSessions
1356
+ e.activeOnly=e.activeOnly??t.activeOnly,e.requestId=e.requestId||t.requestId,e.limit=e.limit??t.limit,e.minTokens=e.minTokens??t.minTokens,e.maxTokens=e.maxTokens??t.maxTokens,e.maxAgeHours=e.maxAgeHours??t.maxAgeHours,delete e.listSessions}!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="spawn":e.prompt&&e.sessionId?e.operation="continue":e.sessionId&&(e.operation="check-status")),e?.operation&&("spawn"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours):"continue"===e.operation?(delete e.agent,delete e.description,delete e.allowParallel,delete e.useExistingSession,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours,delete e.limit):"check-status"===e.operation||"abort"===e.operation?(delete e.agent,delete e.prompt,delete e.description,delete e.requestId,delete e.allowParallel,delete e.useExistingSession,delete e.limit,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours):"read-messages"===e.operation?(delete e.agent,delete e.prompt,delete e.description,delete e.requestId,delete e.allowParallel,delete e.useExistingSession,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours):"list-sessions"===e.operation&&(delete e.sessionId,delete e.agent,delete e.prompt,delete e.description,delete e.allowParallel,delete e.useExistingSession))
1344
1357
  const r=C.validateArgs(e,v.SubagentOperationsSchema),{sessionId:g,operation:p}=r
1345
1358
  let f
1346
- switch(c.info("Processing subagent_operations",{operation:p,sessionId:g}),p){case"spawn":f=await n(r.spawn,t,c,i,a)
1359
+ switch(c.info("Processing subagent_operations",{operation:p,sessionId:g}),p){case"spawn":f=await n({agent:r.agent,prompt:r.prompt,requestId:r.requestId,allowParallel:r.allowParallel,useExistingSession:r.useExistingSession},t,c,i,a)
1347
1360
  break
1348
- case"continue":f=await o(g,r.continue.prompt,t,c,i,void 0,a)
1361
+ case"continue":f=await o(g,r.prompt,t,c,i,void 0,a)
1349
1362
  break
1350
1363
  case"check-status":f=await d(g,t,c,i)
1351
1364
  break
1352
1365
  case"abort":f=await u(g,t,c)
1353
1366
  break
1354
- case"read-messages":const e=r.readMessages?.limit??1
1367
+ case"read-messages":const e=r.limit??1
1355
1368
  f=await async function(e,t,r,n){const o=await(0,k.getServerUrl)(r,n)
1356
1369
  if(!o)throw new y.ValidationError("Could not determine OpenCode server URL")
1357
1370
  n.info("Reading messages from subagent session",{sessionId:e,limit:t})
@@ -1363,7 +1376,7 @@ const i=s.map(((e,t)=>{const r="user"===e.info.role?"USER":"ASSISTANT",n=e.parts
1363
1376
  return`[${t+1}] ${r} (${new Date(e.info.time.created).toLocaleTimeString()}):\n${o}`})).join("\n\n---\n\n")
1364
1377
  return{content:[{type:"text",text:`Session ${e} - Last ${s.length} messages:\n\n${i}`}]}}catch(e){throw Error("Failed to read messages: "+(0,_.getErrorMessage)(e))}}(g,e,t,c)
1365
1378
  break
1366
- case"list-sessions":const s={activeOnly:r.listSessions?.activeOnly,requestId:r.listSessions?.requestId,limit:r.listSessions?.limit,minTokens:r.listSessions?.minTokens,maxTokens:r.listSessions?.maxTokens,maxAgeHours:r.listSessions?.maxAgeHours,parentSessionId:a?.sessionId}
1379
+ case"list-sessions":const s={activeOnly:r.activeOnly,requestId:r.requestId,limit:r.limit,minTokens:r.minTokens,maxTokens:r.maxTokens,maxAgeHours:r.maxAgeHours,parentSessionId:a?.sessionId}
1367
1380
  f=await h(t,c,i,s)
1368
1381
  break
1369
1382
  default:throw new y.ValidationError("Unknown operation: "+p)}return l({success:!0}),s.incrementCounter(`subagent_operations_${p}_success`,1),f}catch(e){return c.error("Subagent operations failed",{error:e instanceof Error?e.stack:e+""}),l({success:!1}),s.incrementCounter("subagent_operations_errors",1),{content:[{type:"text",text:"Subagent operation failed: "+(0,_.getErrorMessage)(e)}],isError:!0}}}
@@ -1522,7 +1535,7 @@ if(g.push("reqId: "+(t||"NONE")),t){const e=await o.proxyGet(`/api/projects/${n.
1522
1535
  g.push(`runs: ${Array.isArray(r)?r.length:0}, withWorktree: ${s?.id||"NONE"}, path: ${s?.worktreePath||s?.worktree_path||"NONE"}`),s&&(h=s.worktreePath||s.worktree_path,c.info("Using test worktree from request test run",{worktreePath:h,reqId:t}))}}}catch(e){c.warn("Failed to resolve test worktree",{error:(0,r.getErrorMessage)(e)})}if(!h)return a({success:!1,error:"no_worktree"}),{content:[{type:"text",text:`No test worktree found.\n\nDiagnostics:\n${g.length>0?g.map((e=>"\u2022 "+e)).join("\n"):"\u2022 No session identity found"}\n\nEnsure this session is linked to a test process and a test run has been created.`}],isError:!0}
1523
1536
  const p=[]
1524
1537
  for(const t of l){c.info("Executing test command",{name:t.name,command:t.command,timeout:t.timeout,cwd:h})
1525
- try{const e=d(t.command,{cwd:h,timeout:1e3*t.timeout,encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"/bin/sh",env:{...u.env,FORCE_COLOR:"0"}})
1538
+ try{const e=d(t.command,{cwd:h,timeout:1e3*t.timeout,encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"win32"===process.platform?"cmd.exe":"/bin/sh",env:{...u.env,FORCE_COLOR:"0"}})
1526
1539
  p.push({name:t.name,command:t.command,exitCode:0,output:e.slice(-4e3),timedOut:!1})}catch(r){const n=!0===r.killed,o=((r.stdout||"")+"\n"+(r.stderr||"")).trim().slice(-4e3),s=r.status??1
1527
1540
  if(p.push({name:t.name,command:t.command,exitCode:s,output:o,timedOut:n}),"setup"===e.commandName)break}}const f=p.every((e=>0===e.exitCode)),m=p.map((e=>{const t=e.timedOut?"\u23f1 TIMEOUT":0===e.exitCode?"\u2705 PASS":`\u274c FAIL (exit ${e.exitCode})`
1528
1541
  return`### ${e.name}: ${t}\n\`\`\`\n$ ${e.command}\n${e.output}\n\`\`\``})).join("\n\n")
@@ -1587,10 +1600,10 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSwitchToMai
1587
1600
  try{if(r.SwitchToMainBranchSchema.parse(e),l.info("Switching to main branch/repository"),!t.workspaceManager)throw(0,n.createServiceError)("WorkspaceManager not available",{phase:"workspace_manager_check"})
1588
1601
  let a=null
1589
1602
  l.info("Checking for requests to unlock")
1590
- try{const{sessionTag:e}=(0,o.getGlobalClientInfo)(),r=t.workspaceManager.getCurrentContext()
1603
+ try{const{sessionTag:e}=(0,o.getGlobalClientInfo)(),r=t.workspaceManager.getCurrentContext(t.currentSessionId)
1591
1604
  if(r.requestId&&"main"!==r.requestId){l.info("Unlocking current request before switching to main",{requestId:r.requestId,sessionTag:e})
1592
1605
  try{const t=await i.unlockRequest(r.requestId,e)
1593
- !1===t.locked?(a=r.requestId,l.info("Successfully unlocked request",{requestId:r.requestId,unlockedAt:t.unlockedAt})):l.warn("Request unlock returned unexpected result",{requestId:r.requestId,result:t})}catch(t){l.warn("Failed to unlock request (continuing with switch to main)",{requestId:r.requestId,sessionTag:e,error:t instanceof Error?t.message:t+""})}}else l.debug("No request context to unlock",{currentRequestId:r.requestId})}catch(e){l.warn("Error during request unlock check (continuing with switch)",{error:(0,s.getErrorMessage)(e)})}const u=await t.workspaceManager.switchToMain()
1606
+ !1===t.locked?(a=r.requestId,l.info("Successfully unlocked request",{requestId:r.requestId,unlockedAt:t.unlockedAt})):l.warn("Request unlock returned unexpected result",{requestId:r.requestId,result:t})}catch(t){l.warn("Failed to unlock request (continuing with switch to main)",{requestId:r.requestId,sessionTag:e,error:t instanceof Error?t.message:t+""})}}else l.debug("No request context to unlock",{currentRequestId:r.requestId})}catch(e){l.warn("Error during request unlock check (continuing with switch)",{error:(0,s.getErrorMessage)(e)})}const u=await t.workspaceManager.switchToMain(t.currentSessionId)
1594
1607
  if(!u.success)throw(0,n.createServiceError)("Failed to switch to main: "+u.message,{error:u.message})
1595
1608
  const h=Date.now()-d
1596
1609
  c.recordValue("switch_to_main_branch_time",h),c.incrementCounter("switch_to_main_branch_success",1)
@@ -1671,57 +1684,58 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
1671
1684
  var t={}
1672
1685
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
1673
1686
  return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
1674
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,t,r,n,o,s,i,f){const m=s.child({tool:"move_files"}),y=Date.now()
1675
- let w,k,b=d.FileOperationPhase.VALIDATION
1676
- const I={toolName:"move-files",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"move-files",metricsPrefix:"move_files",successMessage:"Successfully moved files",failureMessage:"Failed to move files"}
1677
- try{const s=d.validateArgs(e,l.MoveFilesSchema),{taskId:u,operations:h,comment:v}=s
1678
- if(m.info("Moving multiple files and directories",{taskId:u,operationCount:h.length,comment:v}),!h||0===h.length)throw Error("At least one move operation must be specified")
1679
- d.validateTaskIdFormat(u,m,i,I.metricsPrefix)
1680
- const C=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
1681
- m.info("Initial branch context",{initialBranch:C.branch,initialRequestId:C.requestId,isMain:C.isMain})
1682
- const _=[]
1683
- for(const e of h){const{normalizedPath:r,fullPath:n}=d.validateAndNormalizePath(e.source,t),{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(e.destination,t)
1684
- _.push({source:r,destination:o,fullSource:n,fullDestination:s})}b=d.FileOperationPhase.TASK_VALIDATION,i.incrementCounter("move_files_phase",1,{phase:b})
1685
- const E=await d.validateTaskId(u,_[0].source,r,m,i,I.metricsPrefix),q=E?.requestId,S=await d.validateWorkItemStates(u,_[0].source,r,o,t,m,i,I.metricsPrefix),T=await d.autoPromoteTaskStatus(u,E.status,q,S.request?.status,_[0].source,r,o,m,i,I.metricsPrefix)
1686
- T.taskPromoted&&m.info(`Auto-promoted task ${u} (${E.title||"Untitled"}) to in_progress for file operations`,{taskId:u,taskTitle:E.title,previousStatus:E.status,newStatus:T.newTaskStatus,operationCount:h.length}),T.requestPromoted&&m.info(`Auto-promoted request ${q} to in_progress for file operations`,{requestId:q,previousStatus:S.request?.status,newStatus:T.newRequestStatus,triggeringTaskId:u})
1687
- const P=await d.ensureCorrectWorkspaceContext({taskPromoted:T.taskPromoted,requestId:q,context:t,operation:"move-files",logger:m,metrics:i,metricsPrefix:I.metricsPrefix})
1688
- if(!P.success){if(P.isLockConflict)return{content:[{type:"text",text:"\u274c "+P.error}],isError:!0}
1689
- throw Error(P.error)}let j={hadUserMods:!1,userModsCommitHash:void 0}
1690
- if(t.git)try{m.debug("[MOVE-FILES] Checking for user changes before move operations")
1691
- const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"move-files",{requestId:q,taskId:u,workspaceManager:t.workspaceManager},m,i)
1692
- e.userChangesCommitted&&(m.debug("[MOVE-FILES] User changes committed before move operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),m.info("User changes committed before move-files operation",{taskId:u,moveOperationsCount:_.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),j={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){m.debug("[MOVE-FILES] Pre-tool commit failed, continuing with move operations",{error:e instanceof Error?e.message:e+""}),m.warn("Pre-tool user changes commit failed, continuing with move operation",{taskId:u,moveOperationsCount:_.length,error:e instanceof Error?e.message:e+""})}m.debug("[MOVE-FILES] Proceeding with move operations",{operationCount:_.length}),b=d.FileOperationPhase.RECORD_CREATION,i.incrementCounter("move_files_phase",1,{phase:b})
1693
- const{toolRecordId:R,localToolRecordId:M}=await d.createFileOperationRecords(u,q,t.projectId,I.recordType,_[0].source,{operationCount:h.length,operations:_.map((e=>({source:e.source,destination:e.destination}))),userComment:v,hadUserMods:j.hadUserMods,userModsCommitHash:j.userModsCommitHash},r,n,m,i,I.metricsPrefix,f)
1694
- w=R,k=R,b=I.fileOperationPhase,i.incrementCounter("move_files_phase",1,{phase:b})
1695
- const x=[]
1696
- let O=0
1697
- for(const e of _){const t={operation:{source:e.source,destination:e.destination},success:!1}
1687
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,r,n,o,s,i,f,m){const y=i.child({tool:"move_files"}),w=Date.now()
1688
+ let k,b,I=d.FileOperationPhase.VALIDATION
1689
+ const v={toolName:"move-files",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"move-files",metricsPrefix:"move_files",successMessage:"Successfully moved files",failureMessage:"Failed to move files"}
1690
+ try{const u=d.validateArgs(e,l.MoveFilesSchema),{operations:h,comment:C}=u,{resolveActiveTaskId:_}=await Promise.resolve().then(t.bind(t,3451)),E=e.taskId||await _(r,n,i)||"untracked"
1691
+ if(y.info("Moving multiple files and directories",{taskId:E,operationCount:h.length,comment:C}),!h||0===h.length)throw Error("At least one move operation must be specified")
1692
+ d.validateTaskIdFormat(E,y,f,v.metricsPrefix)
1693
+ const q=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
1694
+ y.info("Initial branch context",{initialBranch:q.branch,initialRequestId:q.requestId,isMain:q.isMain})
1695
+ const S=[]
1696
+ for(const e of h){const{normalizedPath:t,fullPath:n}=d.validateAndNormalizePath(e.source,r),{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(e.destination,r)
1697
+ S.push({source:t,destination:o,fullSource:n,fullDestination:s})}I=d.FileOperationPhase.TASK_VALIDATION,f.incrementCounter("move_files_phase",1,{phase:I})
1698
+ const T=await d.validateTaskId(E,S[0].source,n,y,f,v.metricsPrefix),P=T?.requestId,j=await d.validateWorkItemStates(E,S[0].source,n,s,r,y,f,v.metricsPrefix),R=await d.autoPromoteTaskStatus(E,T.status,P,j.request?.status,S[0].source,n,s,y,f,v.metricsPrefix)
1699
+ R.taskPromoted&&y.info(`Auto-promoted task ${E} (${T.title||"Untitled"}) to in_progress for file operations`,{taskId:E,taskTitle:T.title,previousStatus:T.status,newStatus:R.newTaskStatus,operationCount:h.length}),R.requestPromoted&&y.info(`Auto-promoted request ${P} to in_progress for file operations`,{requestId:P,previousStatus:j.request?.status,newStatus:R.newRequestStatus,triggeringTaskId:E})
1700
+ const x=await d.ensureCorrectWorkspaceContext({taskPromoted:R.taskPromoted,requestId:P,context:r,operation:"move-files",logger:y,metrics:f,metricsPrefix:v.metricsPrefix})
1701
+ if(!x.success){if(x.isLockConflict)return{content:[{type:"text",text:"\u274c "+x.error}],isError:!0}
1702
+ throw Error(x.error)}let M={hadUserMods:!1,userModsCommitHash:void 0}
1703
+ if(r.git)try{y.debug("[MOVE-FILES] Checking for user changes before move operations")
1704
+ const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"move-files",{requestId:P,taskId:E,workspaceManager:r.workspaceManager},y,f)
1705
+ e.userChangesCommitted&&(y.debug("[MOVE-FILES] User changes committed before move operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before move-files operation",{taskId:E,moveOperationsCount:S.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),M={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){y.debug("[MOVE-FILES] Pre-tool commit failed, continuing with move operations",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with move operation",{taskId:E,moveOperationsCount:S.length,error:e instanceof Error?e.message:e+""})}y.debug("[MOVE-FILES] Proceeding with move operations",{operationCount:S.length}),I=d.FileOperationPhase.RECORD_CREATION,f.incrementCounter("move_files_phase",1,{phase:I})
1706
+ const{toolRecordId:O,localToolRecordId:D}=await d.createFileOperationRecords(E,P,r.projectId,v.recordType,S[0].source,{operationCount:h.length,operations:S.map((e=>({source:e.source,destination:e.destination}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},n,o,y,f,v.metricsPrefix,m)
1707
+ k=O,b=O,I=v.fileOperationPhase,f.incrementCounter("move_files_phase",1,{phase:I})
1708
+ const $=[]
1709
+ let A=0
1710
+ for(const e of S){const t={operation:{source:e.source,destination:e.destination},success:!1}
1698
1711
  try{try{await a.default.access(e.fullSource)}catch(t){throw Error("Source path not accessible: "+e.source)}const r=(await a.default.stat(e.fullSource)).isDirectory()
1699
1712
  t.isDirectory=r
1700
1713
  const n=c.default.dirname(e.fullDestination)
1701
- try{await a.default.mkdir(n,{recursive:!0})}catch(e){throw Error("Failed to create destination directory: "+n)}try{throw await a.default.access(e.fullDestination),Error("Destination already exists: "+e.destination)}catch(e){if(!(e instanceof Error&&e.message.includes("ENOENT")))throw e}await a.default.rename(e.fullSource,e.fullDestination),t.success=!0,O++,m.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,p.getErrorMessage)(r),m.warn(`Failed to move ${e.source} to ${e.destination}`,{error:t.error})}x.push(t)}const D=Date.now()-y
1702
- i.recordValue("move_files_time",D),i.incrementCounter("move_files_operations_total",h.length),i.incrementCounter("move_files_operations_success",O),i.incrementCounter("move_files_operations_failed",h.length-O),O===h.length?i.incrementCounter("move_files_success",1):O>0?i.incrementCounter("move_files_partial_success",1):i.incrementCounter("move_files_total_failure",1)
1703
- let $=null
1704
- if(O>0){b=d.FileOperationPhase.GIT_COMMIT,i.incrementCounter("move_files_phase",1,{phase:b})
1705
- const e=x.filter((e=>e.success)),r=1===e.length?`Move ${e[0].isDirectory?"directory":"file"} from ${e[0].operation.source} to ${e[0].operation.destination} - ${v}`:`Move ${e.length} ${1===e.length?"item":"items"} - ${v}`
1706
- $=await d.commitToGit(u,_[0].destination,R,M,r,t,m,i,I.metricsPrefix)}b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,i.incrementCounter("move_files_phase",1,{phase:b})
1707
- const A=x.filter((e=>e.success)),F=x.filter((e=>!e.success))
1708
- await d.updateFileOperationRecords(u,w,k,_[0].source,I.recordType,O===h.length?`Successfully moved all ${h.length} items`:`Moved ${O}/${h.length} items successfully`,{status:O===h.length?"completed":"partial_success",commitHash:$?.commitHash,previousCommitHash:$?.previousCommitHash,operationCount:h.length,successCount:O,failureCount:h.length-O,successfulOperations:A.map((e=>({source:e.operation.source,destination:e.operation.destination,isDirectory:e.isDirectory}))),failedOperations:F.map((e=>({source:e.operation.source,destination:e.operation.destination,error:e.error}))),userComment:v,hadUserMods:j.hadUserMods,userModsCommitHash:j.userModsCommitHash},O===h.length?`Successfully moved all ${h.length} items`:`Moved ${O}/${h.length} items successfully`,r,n,m,i,I.metricsPrefix)
1709
- const N=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
1710
- let L=""
1711
- if(O===h.length)L=`Successfully moved all ${h.length} ${1===h.length?"item":"items"}`
1712
- else if(O>0){const e=x.filter((e=>!e.success))
1713
- L=`Successfully moved ${O}/${h.length} items.\n\nFailed operations:\n`+e.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")}else L="All move operations failed:\n"+x.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")
1714
- return $?.commitHash&&(L+="\nCommit: "+$.commitHash.substring(0,8)),N.requestId&&(L+="\nBranch: "+N.requestId),P.lockAcquired&&P.lockedRequestId&&(L+="\n\u{1f512} **Locked request:** "+P.lockedRequestId),{content:[{type:"text",text:L}],isError:0===O}}catch(o){if(e.taskId&&n)try{const r=o instanceof u.NotFoundError||o instanceof u.ValidationError||o instanceof h.ZodError
1715
- await n.createToolRecord({...r?{}:{taskId:e.taskId},projectId:t.projectId,type:"move-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment,error:(0,p.getErrorMessage)(o),errorDetails:o instanceof Error?o.stack:o+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:r},note:"Failed to move files - "+(0,p.getErrorMessage)(o)})}catch(t){m.error("Failed to create failure record for move-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,operationCount:e.operations?.length||0})}const s=Date.now()-y
1716
- if(i.recordValue("move_files_time",s),i.incrementCounter("move_files_errors",1),m.error("Error in move-files operation:",{error:(0,p.getErrorMessage)(o),time:s}),(w||k)&&e.taskId){b=d.FileOperationPhase.RECORD_UPDATE_FAILURE
1717
- try{await d.updateFileOperationRecords(e.taskId,w,k,e.operations?.[0]?.source||"unknown",I.recordType,"Failed to move files",{status:"failed",error:(0,p.getErrorMessage)(o),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment},"Failed to move files",r,n,m,i,I.metricsPrefix)}catch(t){m.error("Failed to update record with failure status",{taskId:e.taskId,recordId:w,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(o,b,m,i,e,I)}}
1714
+ try{await a.default.mkdir(n,{recursive:!0})}catch(e){throw Error("Failed to create destination directory: "+n)}try{throw await a.default.access(e.fullDestination),Error("Destination already exists: "+e.destination)}catch(e){if(!(e instanceof Error&&e.message.includes("ENOENT")))throw e}await a.default.rename(e.fullSource,e.fullDestination),t.success=!0,A++,y.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,p.getErrorMessage)(r),y.warn(`Failed to move ${e.source} to ${e.destination}`,{error:t.error})}$.push(t)}const F=Date.now()-w
1715
+ f.recordValue("move_files_time",F),f.incrementCounter("move_files_operations_total",h.length),f.incrementCounter("move_files_operations_success",A),f.incrementCounter("move_files_operations_failed",h.length-A),A===h.length?f.incrementCounter("move_files_success",1):A>0?f.incrementCounter("move_files_partial_success",1):f.incrementCounter("move_files_total_failure",1)
1716
+ let N=null
1717
+ if(A>0){I=d.FileOperationPhase.GIT_COMMIT,f.incrementCounter("move_files_phase",1,{phase:I})
1718
+ const e=$.filter((e=>e.success)),t=1===e.length?`Move ${e[0].isDirectory?"directory":"file"} from ${e[0].operation.source} to ${e[0].operation.destination} - ${C}`:`Move ${e.length} ${1===e.length?"item":"items"} - ${C}`
1719
+ N=await d.commitToGit(E,S[0].destination,O,D,t,r,y,f,v.metricsPrefix)}I=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,f.incrementCounter("move_files_phase",1,{phase:I})
1720
+ const L=$.filter((e=>e.success)),z=$.filter((e=>!e.success))
1721
+ await d.updateFileOperationRecords(E,k,b,S[0].source,v.recordType,A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,{status:A===h.length?"completed":"partial_success",commitHash:N?.commitHash,previousCommitHash:N?.previousCommitHash,operationCount:h.length,successCount:A,failureCount:h.length-A,successfulOperations:L.map((e=>({source:e.operation.source,destination:e.operation.destination,isDirectory:e.isDirectory}))),failedOperations:z.map((e=>({source:e.operation.source,destination:e.operation.destination,error:e.error}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,n,o,y,f,v.metricsPrefix)
1722
+ const H=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
1723
+ let B=""
1724
+ if(A===h.length)B=`Successfully moved all ${h.length} ${1===h.length?"item":"items"}`
1725
+ else if(A>0){const e=$.filter((e=>!e.success))
1726
+ B=`Successfully moved ${A}/${h.length} items.\n\nFailed operations:\n`+e.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")}else B="All move operations failed:\n"+$.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")
1727
+ if(N?.commitHash&&(B+="\nCommit: "+N.commitHash.substring(0,8)),H.requestId&&(B+="\nBranch: "+H.requestId),x.lockAcquired&&x.lockedRequestId){const e=r.workspaceManager?.getCurrentContext(r.currentSessionId)
1728
+ e?.permanentBranch||(B+="\n\u{1f512} **Locked request:** "+x.lockedRequestId)}return{content:[{type:"text",text:B}],isError:0===A}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
1729
+ await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"move-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment,error:(0,p.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:I,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:"Failed to move files - "+(0,p.getErrorMessage)(t)})}catch(t){y.error("Failed to create failure record for move-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,operationCount:e.operations?.length||0})}const s=Date.now()-w
1730
+ if(f.recordValue("move_files_time",s),f.incrementCounter("move_files_errors",1),y.error("Error in move-files operation:",{error:(0,p.getErrorMessage)(t),time:s}),(k||b)&&e.taskId){I=d.FileOperationPhase.RECORD_UPDATE_FAILURE
1731
+ try{await d.updateFileOperationRecords(e.taskId,k,b,e.operations?.[0]?.source||"unknown",v.recordType,"Failed to move files",{status:"failed",error:(0,p.getErrorMessage)(t),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment},"Failed to move files",n,o,y,f,v.metricsPrefix)}catch(t){y.error("Failed to update record with failure status",{taskId:e.taskId,recordId:k,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(t,I,y,f,e,v)}}
1718
1732
  const a=i(t(1943)),c=i(t(6928)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(1569),g=t(7478),p=t(8824)},2422(module){"use strict"
1719
1733
  module.exports=require("@modelcontextprotocol/sdk/server/sse.js")},2425(e,exports,t){"use strict"
1720
1734
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
1721
1735
  const r=t(6183),n=t(3707)
1722
1736
  exports.def={name:"quick_manage",description:"Move, delete, or create directories. Wraps the change in a request/task workflow that auto-completes.\n\nProvide an array of operations, each with operationType and corresponding data:\n\u2022 create-directory: { createDirectory: { path } }\n\u2022 move-files: { moveFiles: { moves: [{ source, destination }] } }\n\u2022 delete-files: { deleteFiles: { targets: [{ path }] } }\n\nFor read-only operations like get-file-info, use manage_files instead.\n\nRequires: title, description, operations.",schema:r.QuickManageSchema,annotations:{title:"Quick Manage",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"manage",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},2462(e,exports,t){"use strict"
1723
1737
  Object.defineProperty(exports,"__esModule",{value:!0})
1724
- const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),f=t(260),m=t(2283),y=t(4165),w=t(7834),k=t(9373),b=t(6111),I=t(700),v=t(2783),C=t(2601),_=t(1722),E=t(7257),q=t(9230),S=t(5216),T=t(6473),P=t(4921),j=t(8850),R=t(3556),M=t(1391),x=t(6315),O=t(7713),D=t(6252),$=t(213),A=t(7250),F=t(2425),N=t(1540),L=t(5767),z=t(4973),H=t(509),B=t(7613),U=t(3322),G=t(5247),W=t(542);(0,r.registerTool)(n.def),(0,r.registerTool)(o.def),(0,r.registerTool)(s.def),(0,r.registerTool)(i.def),(0,r.registerTool)(a.def),(0,r.registerTool)(c.def),(0,r.registerTool)(l.def),(0,r.registerTool)(d.def),(0,r.registerTool)(u.def),(0,r.registerTool)(h.def),(0,r.registerTool)(g.def),(0,r.registerTool)(p.def),(0,r.registerTool)(f.def),(0,r.registerTool)(m.def),(0,r.registerTool)(y.def),(0,r.registerTool)(w.def),(0,r.registerTool)(k.def),(0,r.registerTool)(b.def),(0,r.registerTool)(I.def),(0,r.registerTool)(v.def),(0,r.registerTool)(C.def),(0,r.registerTool)(_.def),(0,r.registerTool)(E.def),(0,r.registerTool)(q.def),(0,r.registerTool)(S.def),(0,r.registerTool)(T.def),(0,r.registerTool)(P.def),(0,r.registerTool)(j.def),(0,r.registerTool)(R.def),(0,r.registerTool)(M.def),(0,r.registerTool)(x.def),(0,r.registerTool)(O.def),(0,r.registerTool)(D.def),(0,r.registerTool)($.def),(0,r.registerTool)(A.def),(0,r.registerTool)(F.def),(0,r.registerTool)(N.def),(0,r.registerTool)(L.def),(0,r.registerTool)(z.def),(0,r.registerTool)(H.def),(0,r.registerTool)(B.def),(0,r.registerTools)(U.metaDefs),(0,r.registerTools)(G.testingDefs),(0,r.registerTools)(W.debugDefs),(0,t(2245).freezeRegistry)()},2478(e,exports){"use strict"
1738
+ const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),f=t(260),m=t(2283),y=t(4165),w=t(7834),k=t(9373),b=t(6111),I=t(700),v=t(2783),C=t(2601),_=t(1722),E=t(7257),q=t(9230),S=t(6064),T=t(5216),P=t(6473),j=t(4921),R=t(8850),x=t(3556),M=t(1391),O=t(6315),D=t(7713),$=t(6252),A=t(213),F=t(7250),N=t(2425),L=t(1540),z=t(5767),H=t(4973),B=t(509),U=t(7613),G=t(3322),W=t(5247),V=t(8849),J=t(542);(0,r.registerTool)(n.def),(0,r.registerTool)(o.def),(0,r.registerTool)(s.def),(0,r.registerTool)(i.def),(0,r.registerTool)(a.def),(0,r.registerTool)(c.def),(0,r.registerTool)(l.def),(0,r.registerTool)(d.def),(0,r.registerTool)(u.def),(0,r.registerTool)(h.def),(0,r.registerTool)(g.def),(0,r.registerTool)(p.def),(0,r.registerTool)(f.def),(0,r.registerTool)(m.def),(0,r.registerTool)(y.def),(0,r.registerTool)(w.def),(0,r.registerTool)(k.def),(0,r.registerTool)(b.def),(0,r.registerTool)(I.def),(0,r.registerTool)(v.def),(0,r.registerTool)(S.def),(0,r.registerTool)(C.def),(0,r.registerTool)(_.def),(0,r.registerTool)(E.def),(0,r.registerTool)(q.def),(0,r.registerTool)(T.def),(0,r.registerTool)(P.def),(0,r.registerTool)(j.def),(0,r.registerTool)(R.def),(0,r.registerTool)(x.def),(0,r.registerTool)(M.def),(0,r.registerTool)(O.def),(0,r.registerTool)(D.def),(0,r.registerTool)($.def),(0,r.registerTool)(A.def),(0,r.registerTool)(F.def),(0,r.registerTool)(N.def),(0,r.registerTool)(L.def),(0,r.registerTool)(z.def),(0,r.registerTool)(H.def),(0,r.registerTool)(B.def),(0,r.registerTool)(U.def),(0,r.registerTools)(G.metaDefs),(0,r.registerTools)(W.testingDefs),(0,r.registerTools)(V.checkingDefs),(0,r.registerTools)(J.debugDefs),(0,t(2245).freezeRegistry)()},2478(e,exports){"use strict"
1725
1739
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.requestConfig=void 0,exports.areTestsRequiredForCompletion=function(){return exports.requestConfig.requireTestsForCompletion},exports.setTestsRequiredForCompletion=function(e){exports.requestConfig.requireTestsForCompletion=e},exports.getCompletionMode=function(e){return e&&["auto-merge","auto-test-then-merge","manual-review"].includes(e)?e:"auto-merge"},exports.getApprovalMode=function(e){return e&&["none","require-approval"].includes(e)?e:"none"},exports.requestConfig={requireTestsForCompletion:!1}},2537(e,exports,t){"use strict"
1726
1740
  async function r(e,t,r){if(C.has(r)&&_>=t){if(0===t)return 0
1727
1741
  try{return(await y.default.readFile(e,"utf-8")).split("\n").length}catch{return}}}function n(e,t,r){const n="depth"in e,o=n?e:r,s=n?e.isDirectory:e.isDirectory(),a=e.name,c=s?"[\u{1f4c1} DIR]":"[\u{1f4c4} FILE]"
@@ -1797,7 +1811,7 @@ E=`Directory tree for ${C} (${m} levels):\n${l(c(e))}\n\n${t}`,q=d(e)}else E=`Di
1797
1811
  for(const n of e)try{const e=w.default.join(C,n.name).replace(/\\/g,"/"),{fullPath:s}=b.validateAndNormalizePath(e,t),i=await y.default.stat(s),a=n.isFile()?w.default.extname(n.name).toLowerCase():""
1798
1812
  let c
1799
1813
  n.isFile()&&(c=await r(s,i.size,a)),o.push({name:n.name,isDirectory:n.isDirectory(),depth:0,size:i.size,modified:i.mtime,extension:a,lineCount:c})}catch(e){i.debug("Excluding directory entry from listing: "+n.name,{reason:(0,v.getErrorMessage)(e)})}const s=u(o,I),a=s.map((e=>n({name:e.name,isDirectory(){return e.isDirectory},isFile(){return!e.isDirectory}},I,e)))
1800
- E=a.length>0?`Directory listing for ${C}:\n${l(c(s))}\n\n${a.join("\n")}`:`Directory ${C} is empty.`,q=s.length}const S=t.workspaceManager?.getCurrentContext()
1814
+ E=a.length>0?`Directory listing for ${C}:\n${l(c(s))}\n\n${a.join("\n")}`:`Directory ${C} is empty.`,q=s.length}const S=t.workspaceManager?.getCurrentContext(t.currentSessionId)
1801
1815
  E+="\n\nBranch: "+(S?.branchName||"unknown")
1802
1816
  const T=Date.now()-h
1803
1817
  return a.recordValue("list_directory_time",T),a.recordValue("list_directory_entries",q),a.incrementCounter("list_directory_success",1),i.info("Successfully listed directory: "+C,{entryCount:q,levels:m,time:T}),{content:[{type:"text",text:E}]}}catch(e){const t=Date.now()-h
@@ -1932,7 +1946,7 @@ return`${r} ${i}${a} [${e.toUpperCase()}]: ${t}${c}`}))),g=n({logToFile:!1,conso
1932
1946
  exports.default=g},2783(e,exports,t){"use strict"
1933
1947
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
1934
1948
  const r=t(6183),n=t(410)
1935
- exports.def={name:"task_operations",description:"Perform operations on existing tasks.\n\nOperations:\n\u2022 get-info - Get detailed information about a task\n\u2022 list - List and filter tasks for a request\n\nNote: To create a task, use the separate create-task tool. To complete a task, use complete-task.",schema:r.TaskOperationsSchema,annotations:{title:"Task Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleTaskOperations)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},2903(e,exports,t){"use strict"
1949
+ exports.def={name:"task_operations",description:"Perform operations on tasks.\n\nOperations:\n\u2022 create - Create a task under a request (requestId + title + description)\n\u2022 complete - Mark a task as completed (taskId + summary)\n\u2022 get-info - Get detailed information about a task (taskId)\n\u2022 list - List and filter tasks for a request (requestId)\n\nTask IDs use req######+#NN format (e.g. req000005#03).",schema:r.TaskOperationsSchema,annotations:{title:"Task Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleTaskOperations)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},2903(e,exports,t){"use strict"
1936
1950
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
1937
1951
  const r=t(6183),n=t(9442)
1938
1952
  exports.def={name:"replace_in_files",description:'Replace text in multiple files/documents with progressive fuzzy matching in batch operations.\n\nAPI:\n\u2022 operations (required) - Array of file operations\n - path or documentId (required per operation) - Target file or document\n - replacements (required) - Array of {old, new, match_mode?} replacements\n - fuzzy_match (optional) - Override global fuzzy setting for this file\n\u2022 fuzzy_match (optional, default true) - Global fuzzy matching default\n\u2022 comment (required) - Description of changes\n\nSTRUCTURE: Each operation MUST contain a `replacements` array. Do NOT put old/new directly on the operation object.\n\nFUZZY MATCHING (progressive strategies):\n1. exact - Literal match\n2. whitespace_normalized - Collapse/trim whitespace\n3. whitespace_agnostic - Ignore all whitespace\n\nMATCH MODES (per replacement):\n\u2022 \'unique\' (default, safe) - Must find exactly 1 match. Fails with helpful candidates if multiple found.\n\u2022 \'all\' - Replaces all occurrences, returns details for each\n\nRETURNS:\nPer-operation, per-replacement results with line numbers, match types, and success/error details.\n\nEXAMPLES:\n- Single file: {"operations": [{"path": "file.ts", "replacements": [{"old": "oldAPI", "new": "newAPI"}]}], "comment": "Update API"}\n- Multi-file: {"operations": [{"path": "a.ts", "replacements": [...]}, {"path": "b.ts", "replacements": [...]}], "comment": "Refactor"}',schema:r.ReplaceInFilesSchema,annotations:{title:"Replace In Files (Fuzzy Batch)",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},createsRecords:!0,handler(e,t){return(0,n.handleReplaceInFiles)(e,t.context,t.apiClient.getTaskClient(),t.apiClient.getToolRecordClient(),t.apiClient.getRequestClient(),t.logger,t.metrics,t.mcpServer)}}},2960(e,exports){"use strict"
@@ -1987,8 +2001,8 @@ for(const e of h)p.push(r(e,t,0,l))
1987
2001
  for(const e of g)p.push(n(e,t,0,l))
1988
2002
  const f=await Promise.all(p)
1989
2003
  let m=""
1990
- if(t.getCurrentBranchContext)try{const e=await t.getCurrentBranchContext()
1991
- e.branch&&(m=`**Current Branch:** ${e.branch}\n`)}catch(e){i.debug("Could not get branch context",{error:e})}const y=f.filter((e=>e.success)).length,w=f.filter((e=>!e.success)).length,k=f.length
2004
+ if(t.workspaceManager)try{const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
2005
+ e.branchName&&!e.permanentBranch&&(m=`**Current Branch:** ${e.branchName}\n`)}catch(e){i.debug("Could not get branch context",{error:e})}const y=f.filter((e=>e.success)).length,w=f.filter((e=>!e.success)).length,k=f.length
1992
2006
  let b="## Read Files/Documents\n\n"
1993
2007
  m&&(b+=m),b+=`**Total Requests:** ${k} - **Successful:** ${y} - **Failed:** ${w}\n\n`
1994
2008
  for(let e=0;e<f.length;e++){const t=f[e]
@@ -2141,7 +2155,7 @@ if(!t.locked)return{content:[{type:"text",text:`\u274c Failed to acquire lock fo
2141
2155
  d.info("Successfully acquired request lock",{requestId:h,sessionTag:e,lockedAt:t.lockedAt})}catch(t){d.error("Failed to acquire request lock",{requestId:h,sessionTag:e,error:t instanceof Error?t.message:t+""})
2142
2156
  const r=t instanceof Error?t.message:t+""
2143
2157
  return r.includes("already locked")?{content:[{type:"text",text:`\u274c Request ${h} is already locked by another agent. ${r}`}],isError:!0}:{content:[{type:"text",text:`\u274c Failed to acquire lock for request ${h}: ${r}`}],isError:!0}}}}catch(e){return d.error("Error checking/acquiring request lock",{requestId:h,error:(0,i.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c Failed to check request lock status: "+(0,i.getErrorMessage)(e)}],isError:!0}}d.info("Using unified workspace switching",{requestId:h})
2144
- const p=await t.workspaceManager.switchToRequest(h,{isCompleted:"completed"===g.status})
2158
+ const p=await t.workspaceManager.switchToRequest(h,{isCompleted:"completed"===g.status,sessionId:t.currentSessionId})
2145
2159
  if(!p.success){try{const{sessionTag:e}=(0,s.getGlobalClientInfo)()
2146
2160
  d.warn("Workspace switch failed, attempting to release acquired lock",{requestId:h,sessionTag:e,switchError:p.message}),await a.unlockRequest(h,e),d.info("Successfully released lock after workspace switch failure",{requestId:h})}catch(e){d.error("Failed to release lock after workspace switch failure",{requestId:h,unlockError:e instanceof Error?e.message:e+""})}const e=p.message||"Unknown error"
2147
2161
  if(e.includes("does not exist")||e.includes("Branch for request"))return{content:[{type:"text",text:`\u274c Branch for request ${h} does not exist. This can happen if:\n- Request was reverted (branch deleted during revert)\n- Request was completed and branch was cleaned up\n- Branch was manually deleted\n\nUse 'get-request-information' to check the request status.`}],isError:!0}
@@ -2235,57 +2249,58 @@ return t},o(e)},function(e){if(e&&e.__esModule)return e
2235
2249
  var t={}
2236
2250
  if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
2237
2251
  return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
2238
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceStrings=async function(e,t,r,o,s,i,a,c){const y=i.child({tool:"replace_strings"}),w=Date.now()
2239
- let k,b,I=u.FileOperationPhase.VALIDATION
2240
- const v={toolName:"replace-strings",operationName:"replace-string",fileOperationPhase:u.FileOperationPhase.STRING_REPLACEMENT,recordType:"replace-strings",metricsPrefix:"replace_strings",successMessage:"Successfully replaced strings across files and documents",failureMessage:"Failed to replace strings across files and documents"}
2241
- try{const i=u.validateArgs(e,d.ReplaceStringsSchema),{taskId:C,operations:_,comment:E}=i
2242
- if(y.info("Replacing strings across files and documents",{taskId:C,operationCount:_.length,comment:E}),!_||0===_.length)throw new h.ValidationError("At least one operation is required")
2243
- const q=_.filter((e=>e.path)),S=_.filter((e=>e.documentId))
2244
- y.info("Operation breakdown",{fileOperations:q.length,documentOperations:S.length})
2245
- const T=[]
2246
- for(const e of q){const{normalizedPath:r,fullPath:n}=u.validateAndNormalizePath(e.path,t)
2247
- T.push({type:"file",path:r,fullPath:n,replacements:e.replacements,mode:e.mode||"unique"})}const P=[]
2248
- if(S.length>0&&!t.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
2249
- for(const e of S)P.push({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode||"unique"})
2250
- if(P.length>0&&t.apiClient){const e=P.map((e=>e.documentId))
2251
- try{await(0,f.ensureDocumentsNotLocked)(e,t.apiClient,y,a,"replace-strings-documents")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2252
- throw e}}I=u.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("replace_strings_phase",1,{phase:I})
2253
- const j=T.length>0?T[0].path:"document-operation",R=await u.validateTaskId(C,j,r,y,a,v.metricsPrefix),M=R?.requestId
2254
- let x=null
2255
- T.length>0&&M&&(x=await u.validateWorkItemStates(C,T[0].path,r,s,t,y,a,v.metricsPrefix))
2256
- let O={taskPromoted:!1,requestPromoted:!1}
2257
- T.length>0&&M&&x&&(O=await u.autoPromoteTaskStatus(C,R.status,M,x.request?.status,T[0].path,r,s,y,a,v.metricsPrefix),O.taskPromoted&&y.info("Auto-promoted task to in_progress for replace-strings operation",{taskId:C,requestId:M,previousStatus:R.status,newStatus:O.newTaskStatus,triggeringOperation:"replace-strings"}))
2258
- const D=await u.ensureCorrectWorkspaceContext({taskPromoted:O.taskPromoted,requestId:M,context:t,operation:"replace-strings",logger:y,metrics:a,metricsPrefix:v.metricsPrefix})
2259
- if(!D.success){if(D.isLockConflict)return{content:[{type:"text",text:"\u274c "+D.error}],isError:!0}
2260
- throw Error(D.error)}if(T.length>0){y.debug("Re-validating file paths with correct workspace context",{operationCount:T.length,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})
2261
- for(let e=0;e<T.length;e++){const r=T[e],n=q[e],{normalizedPath:o,fullPath:s}=u.validateAndNormalizePath(n.path,t)
2262
- T[e]={...r,path:o,fullPath:s}}}if(P.length>0&&M)try{await(0,g.validateRequestStatusForDocumentOperation)(M,s,y,a,"replace-strings-document")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2263
- throw e}I=u.FileOperationPhase.RECORD_CREATION,a.incrementCounter("replace_strings_phase",1,{phase:I})
2264
- const $=[...T.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...P.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:A}=await u.createFileOperationRecords(C,M,t.projectId,v.recordType,j,{operationCount:_.length,fileOperations:T.length,documentOperations:P.length,operations:$,userComment:E},r,o,y,a,v.metricsPrefix,c)
2265
- if(k=A,b=A,I=v.fileOperationPhase,a.incrementCounter("replace_strings_phase",1,{phase:I}),T.length>0&&t.git)try{y.debug("[REPLACE-STRINGS] Checking for user changes before replace operations")
2266
- const e=await(0,p.commitUserChangesBeforeToolOperation)(t.git,"replace-strings",{requestId:M,taskId:C,workspaceManager:t.workspaceManager},y,a)
2267
- e.userChangesCommitted&&(y.debug("[REPLACE-STRINGS] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before replace-strings operation",{taskId:C,fileOperationsCount:T.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){y.debug("[REPLACE-STRINGS] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:C,fileOperationsCount:T.length,error:e instanceof Error?e.message:e+""})}y.debug("[REPLACE-STRINGS] Proceeding with file operations",{fileCount:T.length})
2268
- const F=[]
2269
- let N=0,L=0
2270
- for(const e of T){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
2252
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceStrings=async function(e,r,o,s,i,a,c,y){const w=a.child({tool:"replace_strings"}),k=Date.now()
2253
+ let b,I,v=u.FileOperationPhase.VALIDATION
2254
+ const C={toolName:"replace-strings",operationName:"replace-string",fileOperationPhase:u.FileOperationPhase.STRING_REPLACEMENT,recordType:"replace-strings",metricsPrefix:"replace_strings",successMessage:"Successfully replaced strings across files and documents",failureMessage:"Failed to replace strings across files and documents"}
2255
+ try{const _=u.validateArgs(e,d.ReplaceStringsSchema),{operations:E,comment:q}=_,{resolveActiveTaskId:S}=await Promise.resolve().then(t.bind(t,3451)),T=e.taskId||await S(r,o,a)||"untracked"
2256
+ if(w.info("Replacing strings across files and documents",{taskId:T,operationCount:E.length,comment:q}),!E||0===E.length)throw new h.ValidationError("At least one operation is required")
2257
+ const P=E.filter((e=>e.path)),j=E.filter((e=>e.documentId))
2258
+ w.info("Operation breakdown",{fileOperations:P.length,documentOperations:j.length})
2259
+ const R=[]
2260
+ for(const e of P){const{normalizedPath:t,fullPath:n}=u.validateAndNormalizePath(e.path,r)
2261
+ R.push({type:"file",path:t,fullPath:n,replacements:e.replacements,mode:e.mode||"unique"})}const x=[]
2262
+ if(j.length>0&&!r.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
2263
+ for(const e of j)x.push({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode||"unique"})
2264
+ if(x.length>0&&r.apiClient){const e=x.map((e=>e.documentId))
2265
+ try{await(0,f.ensureDocumentsNotLocked)(e,r.apiClient,w,c,"replace-strings-documents")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2266
+ throw e}}v=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_strings_phase",1,{phase:v})
2267
+ const M=R.length>0?R[0].path:"document-operation",O=await u.validateTaskId(T,M,o,w,c,C.metricsPrefix),D=O?.requestId
2268
+ let $=null
2269
+ R.length>0&&D&&($=await u.validateWorkItemStates(T,R[0].path,o,i,r,w,c,C.metricsPrefix))
2270
+ let A={taskPromoted:!1,requestPromoted:!1}
2271
+ R.length>0&&D&&$&&(A=await u.autoPromoteTaskStatus(T,O.status,D,$.request?.status,R[0].path,o,i,w,c,C.metricsPrefix),A.taskPromoted&&w.info("Auto-promoted task to in_progress for replace-strings operation",{taskId:T,requestId:D,previousStatus:O.status,newStatus:A.newTaskStatus,triggeringOperation:"replace-strings"}))
2272
+ const F=await u.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:D,context:r,operation:"replace-strings",logger:w,metrics:c,metricsPrefix:C.metricsPrefix})
2273
+ if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
2274
+ throw Error(F.error)}if(R.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:R.length,workspaceBasePath:r.workspaceManager?.getCurrentContext(r.currentSessionId).basePath})
2275
+ for(let e=0;e<R.length;e++){const t=R[e],n=P[e],{normalizedPath:o,fullPath:s}=u.validateAndNormalizePath(n.path,r)
2276
+ R[e]={...t,path:o,fullPath:s}}}if(x.length>0&&D)try{await(0,g.validateRequestStatusForDocumentOperation)(D,i,w,c,"replace-strings-document")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2277
+ throw e}v=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_strings_phase",1,{phase:v})
2278
+ const N=[...R.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...x.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:L}=await u.createFileOperationRecords(T,D,r.projectId,C.recordType,M,{operationCount:E.length,fileOperations:R.length,documentOperations:x.length,operations:N,userComment:q},o,s,w,c,C.metricsPrefix,y)
2279
+ if(b=L,I=L,v=C.fileOperationPhase,c.incrementCounter("replace_strings_phase",1,{phase:v}),R.length>0&&r.git)try{w.debug("[REPLACE-STRINGS] Checking for user changes before replace operations")
2280
+ const e=await(0,p.commitUserChangesBeforeToolOperation)(r.git,"replace-strings",{requestId:D,taskId:T,workspaceManager:r.workspaceManager},w,c)
2281
+ e.userChangesCommitted&&(w.debug("[REPLACE-STRINGS] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before replace-strings operation",{taskId:T,fileOperationsCount:R.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[REPLACE-STRINGS] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:T,fileOperationsCount:R.length,error:e instanceof Error?e.message:e+""})}w.debug("[REPLACE-STRINGS] Proceeding with file operations",{fileCount:R.length})
2282
+ const z=[]
2283
+ let H=0,B=0
2284
+ for(const e of R){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
2271
2285
  try{if(await l.default.access(e.fullPath),!(await l.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
2272
2286
  const r=await l.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await n(r,e.replacements,e.mode)
2273
- t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,o!==r?(await l.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,L++,y.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),N+=t.failedReplacements}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,N+=t.failedReplacements,y.error("File operation failed",{path:e.path,error:t.error})}F.push(t)}for(const e of P){const r={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
2274
- try{const o=await t.documentFileManager.getDocumentAsFile(e.documentId),s=t.documentFileManager.getCachedDocumentInfo(e.documentId)
2275
- r.filename=s?.filename
2287
+ t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,o!==r?(await l.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,B++,w.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,w.error("File operation failed",{path:e.path,error:t.error})}z.push(t)}for(const e of x){const t={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
2288
+ try{const o=await r.documentFileManager.getDocumentAsFile(e.documentId),s=r.documentFileManager.getCachedDocumentInfo(e.documentId)
2289
+ t.filename=s?.filename
2276
2290
  const i=await l.default.readFile(o,"utf8"),{newContent:a,results:c}=await n(i,e.replacements,e.mode)
2277
- r.replacements=c,r.successfulReplacements=c.filter((e=>e.success)).length,r.failedReplacements=c.filter((e=>!e.success)).length,a!==i?(await l.default.writeFile(o,a,"utf8"),t.documentFileManager.markForSync(e.documentId),r.success=!0,L++,y.info("Document updated successfully",{documentId:e.documentId,filename:r.filename,successfulReplacements:r.successfulReplacements,failedReplacements:r.failedReplacements})):0===r.failedReplacements&&(r.success=!0),N+=r.failedReplacements}catch(t){r.error=(0,m.getErrorMessage)(t),r.failedReplacements=e.replacements.length,N+=r.failedReplacements,y.error("Document operation failed",{documentId:e.documentId,error:r.error})}F.push(r)}if(P.length>0)try{for(const e of P){const r=F.find((t=>t.documentId===e.documentId))
2278
- r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){y.warn("Some documents may not have synced properly",{error:e})}const z=await u.handleMultiFileGitCommit(C,T,F,L,{operationType:"Replace strings",toolRecordId:b,successField:"successfulReplacements",logger:y,metrics:a,metricsPrefix:"replace_strings"},t),H=u.processMultiFileOperationResults(F,"successfulReplacements"),{successfulOperations:B,failedOperations:U,totalSuccessfulChanges:G,overallSuccess:W,successfulFiles:V,failedFiles:J}=H
2279
- try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+P[0]?.documentId,status:W?"completed":"failed",error:W?void 0:U+" operations failed",totalOperations:F.length,successfulFiles:V,failedFiles:J,operations:$,totalSuccessfulReplacements:G,totalFailedReplacements:N,operationsWithChanges:L,processingTime:Date.now()-w,userComment:E,...T.length>0&&z.success&&z.commitHash&&{commitHash:z.commitHash,previousCommitHash:z.previousCommitHash||void 0}},note:W?`String replacement completed: ${B}/${F.length} operations successful${T.length>0?" (committed to git)":""}`:`String replacement partially failed: ${U}/${F.length} operations failed`})}catch(e){y.warn("Failed to update tool record",{recordError:e})}u.formatMultiFileToolResponse("String Replacement",{successfulOperations:B,failedOperations:U,totalSuccessfulChanges:G,overallSuccess:W,successfulFiles:V,failedFiles:J},z,D)
2280
- let K="## String Replacement Results\n\n"
2281
- if(t.workspaceManager&&(K+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),K+="**Summary:**\n",K+=`- **Files processed:** ${B+U}\n`,K+=`- **Successful operations:** ${B}\n`,K+=`- **Failed operations:** ${U}\n`,K+=`- **Total replacements:** ${G} successful, ${N} failed\n\n`,z.success&&z.commitHash&&(K+="**Git Commit:**\n",K+=`- **Commit Hash:** ${z.commitHash.substring(0,8)}\n`,K+=`- **Files Committed:** ${z.filesCommitted.length}\n`,z.previousCommitHash&&(K+=`- **Previous Commit:** ${z.previousCommitHash.substring(0,8)}\n`),K+="\n"),D.lockAcquired&&D.lockedRequestId&&(K+=`\u{1f512} **Locked request:** ${D.lockedRequestId}\n\n`),1===F.length){const e=F[0]
2282
- if(K+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?K+=`**File:** ${e.path}\n`:(K+="**Document:** "+e.documentId,e.filename&&(K+=` (${e.filename})`),K+="\n"),e.error?K+=`**Error:** ${e.error}\n`:(K+=`**Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(K+=`, ${e.failedReplacements} failed`),K+="\n"),e.replacements.some((e=>!e.success))){K+="**Failed Replacement Details:**\n"
2283
- for(const t of e.replacements.filter((e=>!e.success)))K+=`- "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}}else{K+="**Summary:**\n",K+=`- **Total Operations:** ${F.length}\n`,K+=`- **Successful:** ${B}\n`,K+=`- **Failed:** ${U}\n`,K+=`- **Total Replacements:** ${G} successful, ${N} failed\n\n`,K+="**Detailed Results:**\n\n"
2284
- for(const e of F){if("file"===e.type?K+=`### File: ${e.path}\n`:(K+="### Document: "+e.documentId,e.filename&&(K+=` (${e.filename})`),K+="\n"),K+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error?K+=`- **Error:** ${e.error}\n`:(K+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(K+=`, ${e.failedReplacements} failed`),K+="\n"),e.replacements.some((e=>!e.success))){K+="- **Failed Replacement Details:**\n"
2285
- for(const t of e.replacements.filter((e=>!e.success)))K+=` - "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}K+="\n"}}P.length>0&&(K+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
2286
- const Y=Date.now()-w
2287
- return y.info("Replace strings operation completed",{duration:Y,success:W,totalOperations:F.length,successfulOperations:B,failedOperations:U}),a.incrementCounter("replace_strings_total",1,{success:W}),{content:[{type:"text",text:K}],isError:!W}}catch(t){const r=Date.now()-w
2288
- if(y.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:I}),b)try{await o.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,m.getErrorMessage)(t),phase:I,duration:r,userComment:e?.comment},note:"String replacement failed: "+(0,m.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("replace_strings_errors",1,{phase:I}),{content:[{type:"text",text:"\u274c **Replace Strings Failed:** "+(0,m.getErrorMessage)(t)}],isError:!0}}}
2291
+ t.replacements=c,t.successfulReplacements=c.filter((e=>e.success)).length,t.failedReplacements=c.filter((e=>!e.success)).length,a!==i?(await l.default.writeFile(o,a,"utf8"),r.documentFileManager.markForSync(e.documentId),t.success=!0,B++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,w.error("Document operation failed",{documentId:e.documentId,error:t.error})}z.push(t)}if(x.length>0)try{for(const e of x){const t=z.find((t=>t.documentId===e.documentId))
2292
+ t?.success&&await r.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const U=await u.handleMultiFileGitCommit(T,R,z,B,{operationType:"Replace strings",toolRecordId:I,successField:"successfulReplacements",logger:w,metrics:c,metricsPrefix:"replace_strings"},r),G=u.processMultiFileOperationResults(z,"successfulReplacements"),{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q}=G
2293
+ try{await s.updateToolRecord(I,{metadata:{path:R.length>0?R[0].path:"document:"+x[0]?.documentId,status:K?"completed":"failed",error:K?void 0:V+" operations failed",totalOperations:z.length,successfulFiles:Y,failedFiles:Q,operations:N,totalSuccessfulReplacements:J,totalFailedReplacements:H,operationsWithChanges:B,processingTime:Date.now()-k,userComment:q,...R.length>0&&U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}},note:K?`String replacement completed: ${W}/${z.length} operations successful${R.length>0?" (committed to git)":""}`:`String replacement partially failed: ${V}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}u.formatMultiFileToolResponse("String Replacement",{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q},U,F)
2294
+ let Z="## String Replacement Results\n\n"
2295
+ if(r.workspaceManager){const e=r.workspaceManager.getCurrentContext(r.currentSessionId)
2296
+ e.permanentBranch||(Z+=`**Branch:** \`${e.branchName}\`\n\n`)}if(Z+="**Summary:**\n",Z+=`- **Files processed:** ${W+V}\n`,Z+=`- **Successful operations:** ${W}\n`,Z+=`- **Failed operations:** ${V}\n`,Z+=`- **Total replacements:** ${J} successful, ${H} failed\n\n`,U.success&&U.commitHash&&(Z+="**Git Commit:**\n",Z+=`- **Commit Hash:** ${U.commitHash.substring(0,8)}\n`,Z+=`- **Files Committed:** ${U.filesCommitted.length}\n`,U.previousCommitHash&&(Z+=`- **Previous Commit:** ${U.previousCommitHash.substring(0,8)}\n`),Z+="\n"),F.lockAcquired&&F.lockedRequestId&&(r.workspaceManager?.getCurrentContext(r.currentSessionId)?.permanentBranch||(Z+=`\u{1f512} **Locked request:** ${F.lockedRequestId}\n\n`)),1===z.length){const e=z[0]
2297
+ if(Z+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?Z+=`**File:** ${e.path}\n`:(Z+="**Document:** "+e.documentId,e.filename&&(Z+=` (${e.filename})`),Z+="\n"),e.error?Z+=`**Error:** ${e.error}\n`:(Z+=`**Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(Z+=`, ${e.failedReplacements} failed`),Z+="\n"),e.replacements.some((e=>!e.success))){Z+="**Failed Replacement Details:**\n"
2298
+ for(const t of e.replacements.filter((e=>!e.success)))Z+=`- "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}}else{Z+="**Summary:**\n",Z+=`- **Total Operations:** ${z.length}\n`,Z+=`- **Successful:** ${W}\n`,Z+=`- **Failed:** ${V}\n`,Z+=`- **Total Replacements:** ${J} successful, ${H} failed\n\n`,Z+="**Detailed Results:**\n\n"
2299
+ for(const e of z){if("file"===e.type?Z+=`### File: ${e.path}\n`:(Z+="### Document: "+e.documentId,e.filename&&(Z+=` (${e.filename})`),Z+="\n"),Z+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error?Z+=`- **Error:** ${e.error}\n`:(Z+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(Z+=`, ${e.failedReplacements} failed`),Z+="\n"),e.replacements.some((e=>!e.success))){Z+="- **Failed Replacement Details:**\n"
2300
+ for(const t of e.replacements.filter((e=>!e.success)))Z+=` - "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}Z+="\n"}}x.length>0&&(Z+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
2301
+ const X=Date.now()-k
2302
+ return w.info("Replace strings operation completed",{duration:X,success:K,totalOperations:z.length,successfulOperations:W,failedOperations:V}),c.incrementCounter("replace_strings_total",1,{success:K}),{content:[{type:"text",text:Z}],isError:!K}}catch(t){const r=Date.now()-k
2303
+ if(w.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),I)try{await s.updateToolRecord(I,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,m.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"String replacement failed: "+(0,m.getErrorMessage)(t)})}catch(e){}return c.incrementCounter("replace_strings_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Replace Strings Failed:** "+(0,m.getErrorMessage)(t)}],isError:!0}}}
2289
2304
  const l=c(t(1943)),d=t(6183),u=a(t(5967)),h=t(9860),g=t(5003),p=t(7478),f=t(9949),m=t(8824)},3322(e,exports,t){"use strict"
2290
2305
  var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
2291
2306
  var o=Object.getOwnPropertyDescriptor(t,r)
@@ -2330,40 +2345,41 @@ var m=t(6539)
2330
2345
  Object.defineProperty(exports,"ClientFactory",{enumerable:!0,get(){return m.ClientFactory}})
2331
2346
  const y=t(6539)
2332
2347
  exports.default={ClientFactory:y.ClientFactory}},3420(e,exports,t){"use strict"
2333
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleGetTaskInformation=async function(e,t,i,a,c){const l=a.child({tool:"get_task_information"})
2334
- l.info("Getting task information",{args:e})
2335
- const d=c.startTimer("tool_handler_duration")
2336
- try{const{taskId:r}=function(e){try{return n.GetTaskInformationSchema.parse(e)}catch(t){throw new o.ValidationError("Invalid input: "+(0,s.getErrorMessage)(t),{args:e,error:t})}}(e),a=t.projectId
2337
- if(!a)throw new o.ValidationError("Project ID is required for getting task information with the new API structure")
2338
- c.incrementCounter("get_task_information_attempts",1,{taskId:r}),i.setProjectId(a)
2339
- const u=i.getTaskClient()
2340
- let h
2341
- l.info("Getting information for task "+r,{taskId:r,projectId:a})
2342
- try{l.debug("Fetching task information",{taskId:r,projectId:a})
2343
- const e=await u.getTask(r)
2344
- l.info("Raw task response data",{taskId:r,responseData:JSON.stringify(e)})
2348
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleGetTaskInformation=async function(e,t,a,c,l){const d=c.child({tool:"get_task_information"})
2349
+ d.info("Getting task information",{args:e})
2350
+ const u=l.startTimer("tool_handler_duration")
2351
+ try{let{taskId:r}=function(e){try{return n.GetTaskInformationSchema.parse(e)}catch(t){throw new o.ValidationError("Invalid input: "+(0,s.getErrorMessage)(t),{args:e,error:t})}}(e);(0,i.isTaskRef)(r)&&(r=await(0,i.resolveTaskRef)(r,a,d))
2352
+ const c=t.projectId
2353
+ if(!c)throw new o.ValidationError("Project ID is required for getting task information with the new API structure")
2354
+ l.incrementCounter("get_task_information_attempts",1,{taskId:r}),a.setProjectId(c)
2355
+ const h=a.getTaskClient()
2356
+ let g
2357
+ d.info("Getting information for task "+r,{taskId:r,projectId:c})
2358
+ try{d.debug("Fetching task information",{taskId:r,projectId:c})
2359
+ const e=await h.getTask(r)
2360
+ d.info("Raw task response data",{taskId:r,responseData:JSON.stringify(e)})
2345
2361
  let t=null
2346
2362
  e&&"object"==typeof e&&(t="success"in e&&"data"in e||"data"in e?e.data:e)
2347
2363
  let n=!1
2348
- if(t&&"object"==typeof t&&(n="description"in t&&!!t.description),t){const e={id:r,title:"Untitled Task",description:"No description available.",status:"pending",projectId:a,requestId:"",createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}
2364
+ if(t&&"object"==typeof t&&(n="description"in t&&!!t.description),t){const e={id:r,title:"Untitled Task",description:"No description available.",status:"pending",projectId:c,requestId:"",createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}
2349
2365
  "id"in t&&t.id&&(e.id=t.id+""),"title"in t&&t.title&&(e.title=t.title+""),"description"in t&&void 0!==t.description&&(null===t.description?e.description="":e.description=t.description+""),"status"in t&&t.status&&(e.status=t.status),"projectId"in t&&t.projectId&&(e.projectId=t.projectId+""),"requestId"in t&&t.requestId&&(e.requestId=t.requestId+""),"createdAt"in t&&t.createdAt&&(e.createdAt=t.createdAt+""),"updatedAt"in t&&t.updatedAt&&(e.updatedAt=t.updatedAt+"")
2350
2366
  const n=e
2351
- "metadata"in t&&t.metadata&&(n.metadata=t.metadata),h=n}else h={id:r,title:"Untitled Task",description:"No description available.",status:"pending",projectId:a,requestId:"",createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}
2352
- l.info("Retrieved task information",{taskId:r,title:h.title,status:h.status})}catch(e){throw new o.NotFoundError(`Task ${r} not found in project ${a}. Please provide a valid task ID.`,{taskId:r,projectId:a,originalError:e})}let g=null
2353
- if(h.requestId)try{const e=i.getRequestClient()
2354
- g=await e.getRequest(h.requestId),l.info("Retrieved parent request information",{taskId:r,requestId:h.requestId})}catch(e){l.warn("Failed to retrieve parent request",{error:(0,s.getErrorMessage)(e),taskId:r,requestId:h.requestId})}const p=e=>{if(!e)return"Unknown date"
2367
+ "metadata"in t&&t.metadata&&(n.metadata=t.metadata),g=n}else g={id:r,title:"Untitled Task",description:"No description available.",status:"pending",projectId:c,requestId:"",createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}
2368
+ d.info("Retrieved task information",{taskId:r,title:g.title,status:g.status})}catch(e){throw new o.NotFoundError(`Task ${r} not found in project ${c}. Please provide a valid task ID.`,{taskId:r,projectId:c,originalError:e})}let p=null
2369
+ if(g.requestId)try{const e=a.getRequestClient()
2370
+ p=await e.getRequest(g.requestId),d.info("Retrieved parent request information",{taskId:r,requestId:g.requestId})}catch(e){d.warn("Failed to retrieve parent request",{error:(0,s.getErrorMessage)(e),taskId:r,requestId:g.requestId})}const f=e=>{if(!e)return"Unknown date"
2355
2371
  try{const t=new Date(e)
2356
- return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return l.warn("Invalid date format: "+e),"Unknown date"}},f=p(h.createdAt),m=p(h.updatedAt)
2357
- let y=`# Task: ${h.title} (${r})\n\n`
2358
- if(y+=`**Status**: ${h.status}\n`,y+=`**Created**: ${f}\n`,y+=`**Updated**: ${m}\n`,h.requestId&&(y+="**Parent Request**: "+h.requestId,y+=g?` (${g.title})\n`:"\n"),h.metadata){const e=h.metadata
2359
- y+="\n## Metadata\n\n",e.lastCommit&&(y+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(y+=`**Completed At**: ${p(e.completedAt)}\n`),e.completionSummary&&(y+=`**Completion Summary**: ${e.completionSummary}\n`)
2372
+ return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return d.warn("Invalid date format: "+e),"Unknown date"}},m=f(g.createdAt),y=f(g.updatedAt),w=g.requestId||g.requestLocalId,k=g.sequenceNumber&&w?(0,i.formatTaskRef)(w,g.sequenceNumber):r
2373
+ let b=`# Task: ${g.title} (${k})\n\n`
2374
+ if(b+=`**Status**: ${g.status}\n`,b+=`**Created**: ${m}\n`,b+=`**Updated**: ${y}\n`,g.requestId&&(b+="**Parent Request**: "+g.requestId,b+=p?` (${p.title})\n`:"\n"),g.metadata){const e=g.metadata
2375
+ b+="\n## Metadata\n\n",e.lastCommit&&(b+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(b+=`**Completed At**: ${f(e.completedAt)}\n`),e.completionSummary&&(b+=`**Completion Summary**: ${e.completionSummary}\n`)
2360
2376
  const t=["lastCommit","completedAt","completionSummary"]
2361
- Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{y+=`**${e}**: ${t}\n`}))}return y+="\n## Description\n\n",h.description&&h.description.trim().length>0?y+=h.description:y+="No description provided.",d({success:!0}),{content:[{type:"text",text:y}]}}catch(n){l.error("Failed to get task information",{error:n instanceof Error?n.stack:n+"",args:e})
2362
- try{const o=i.getToolRecordClient()
2363
- await(0,r.createFailureToolRecord)("get-task-information",n,{args:e},o,l,c,{taskId:e.taskId,projectId:t.projectId,note:"Failed to get task information: "+(0,s.getErrorMessage)(n)})}catch(e){l.warn("Failed to create failure record",{recordError:e instanceof Error?e.message:e+""})}d({success:!1,error:n instanceof Error?n.name:"unknown"})
2364
- let a=(0,s.getErrorMessage)(n)
2365
- return n instanceof o.NotFoundError&&(a=`The task ID "${e.taskId}" was not found. Please provide a valid task ID.`),{content:[{type:"text",text:"Error: "+a}],isError:!0}}}
2366
- const r=t(8616),n=t(6183),o=t(9860),s=t(8824)},3444(e,exports,t){"use strict"
2377
+ Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{b+=`**${e}**: ${t}\n`}))}return b+="\n## Description\n\n",g.description&&g.description.trim().length>0?b+=g.description:b+="No description provided.",u({success:!0}),{content:[{type:"text",text:b}]}}catch(n){d.error("Failed to get task information",{error:n instanceof Error?n.stack:n+"",args:e})
2378
+ try{const o=a.getToolRecordClient()
2379
+ await(0,r.createFailureToolRecord)("get-task-information",n,{args:e},o,d,l,{taskId:e.taskId,projectId:t.projectId,note:"Failed to get task information: "+(0,s.getErrorMessage)(n)})}catch(e){d.warn("Failed to create failure record",{recordError:e instanceof Error?e.message:e+""})}u({success:!1,error:n instanceof Error?n.name:"unknown"})
2380
+ let i=(0,s.getErrorMessage)(n)
2381
+ return n instanceof o.NotFoundError&&(i=`The task ID "${e.taskId}" was not found. Please provide a valid task ID.`),{content:[{type:"text",text:"Error: "+i}],isError:!0}}}
2382
+ const r=t(8616),n=t(6183),o=t(9860),s=t(8824),i=t(4466)},3444(e,exports,t){"use strict"
2367
2383
  var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
2368
2384
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.LogLevel=exports.defaultLogger=exports.isDebugToolsEnabled=exports.getDebugLevelFromEnv=exports.isDebugLoggingEnabled=exports.createEnvLogger=exports.createLogger=void 0
2369
2385
  const n=t(2782)
@@ -2371,7 +2387,21 @@ Object.defineProperty(exports,"createLogger",{enumerable:!0,get(){return n.creat
2371
2387
  const o=r(t(2782))
2372
2388
  exports.defaultLogger=o.default
2373
2389
  const s=t(6540)
2374
- Object.defineProperty(exports,"LogLevel",{enumerable:!0,get(){return s.LogLevel}}),exports.default=o.default},3556(e,exports,t){"use strict"
2390
+ Object.defineProperty(exports,"LogLevel",{enumerable:!0,get(){return s.LogLevel}}),exports.default=o.default},3451(e,exports,t){"use strict"
2391
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.resolveActiveTaskId=async function(e,t,s){const i=e.currentSessionId
2392
+ if(n&&o===i)return n
2393
+ try{if(!i||"__unknown__"===i||"__server__"===i)return
2394
+ const a="getTaskClient"in t?t.getTaskClient():t
2395
+ let c=null
2396
+ if("getTaskClient"in t)c=await r.sessionIdentity.getSessionRequestId(t,s,i)
2397
+ else{const t=e.workspaceManager?.getCurrentContext(i)
2398
+ c=t?.requestId||null}if(!c)return
2399
+ const l=await a.listTasks({requestId:c,status:"in_progress"})
2400
+ if(0===l.length)return
2401
+ const d=l[0].localId||l[0].id
2402
+ return n=d,o=i,d}catch(e){return void s.debug("Could not resolve active task",{error:e+""})}},exports.clearActiveTaskCache=function(){n=null,o=null}
2403
+ const r=t(6688)
2404
+ let n=null,o=null},3556(e,exports,t){"use strict"
2375
2405
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
2376
2406
  const r=t(6183),n=t(8317)
2377
2407
  exports.def={name:"request_file_history",description:"Get file change history for an entire request. Supports summary mode (net diffs) or detailed mode (chronological operations). Can be filtered to specific task. Use query_history tool instead.",schema:r.QueryHistorySchema,annotations:{title:"Request File History",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleRequestFileHistory)(e,t.context,t.apiClient,t.logger,t.metrics)}}},3611(e,exports,t){"use strict"
@@ -2521,12 +2551,12 @@ P?f.warn("File operation completed with partial failures",{requestId:S}):f.info(
2521
2551
  try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${I}${P?" (partial success)":""}`},d,u,h,g),f.info("Task completed successfully",{taskId:T})}catch(e){f.error("Task completion via handleCompleteTask failed, attempting direct status update",{taskId:T,error:e instanceof Error?e.message:e+"",errorStack:e instanceof Error?e.stack:void 0})
2522
2552
  try{await w.updateTaskStatus(T,"completed"),f.info("Task completed via direct updateTaskStatus call",{taskId:T})}catch(e){return f.error("Direct task completion ALSO failed - task may be stuck in in_progress",{taskId:T,error:e instanceof Error?e.message:e+"",errorStack:e instanceof Error?e.stack:void 0,operationType:t,isDocumentOperation:!!C.documentId}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but task completion failed.\n\n**Request:** ${S}\n**Task:** ${T}\n**Issue:** Could not mark task as completed - it remains in 'in_progress' state\n\nThe ${t} operation was successful, but we couldn't automatically complete the task. Please use the complete-task tool manually with taskId: ${T}\n\nError: `+(e instanceof Error?e.message:e+"")}],isError:!0}}}f.debug("Completing request")
2523
2553
  const j=P?`Quick change completed with partial success: ${I}. Some replacements failed - see details below.`:"Quick change completed: "+I,R=P?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
2524
- let M=!1
2554
+ let x=!1
2525
2555
  try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:j,acceptanceEvidence:[{evidence:R}],testVerification:void 0},d,u,h,g,p)
2526
2556
  if(e.isError)f.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text})
2527
- else{try{await y.updateRequest(S,{status:"completed",completionSummary:j}),f.info("Request finalized to completed",{requestId:S})}catch(e){f.warn("Failed to finalize request to completed, may be stuck at ready_for_merge",{requestId:S,error:(0,l.getErrorMessage)(e)})}M=!0,f.info("Request completed successfully",{requestId:S})}}catch(e){f.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!M)try{f.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:j}),M=!0,f.info("Request completed successfully via direct API call",{requestId:S})}catch(e){return f.error("Direct request completion also failed",{requestId:S,error:e instanceof Error?e.message:e+""}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but request completion failed.\n\n**Request:** ${S}\n**Status:** Still in 'in_progress' - please complete manually\n\nThe file operation was successful, but we couldn't automatically complete the request. Please use the complete-request tool manually.`}],isError:!0}}const x=Date.now()-m
2557
+ else{try{await y.updateRequest(S,{status:"completed",completionSummary:j}),f.info("Request finalized to completed",{requestId:S})}catch(e){f.warn("Failed to finalize request to completed, may be stuck at ready_for_merge",{requestId:S,error:(0,l.getErrorMessage)(e)})}x=!0,f.info("Request completed successfully",{requestId:S})}}catch(e){f.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!x)try{f.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:j}),x=!0,f.info("Request completed successfully via direct API call",{requestId:S})}catch(e){return f.error("Direct request completion also failed",{requestId:S,error:e instanceof Error?e.message:e+""}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but request completion failed.\n\n**Request:** ${S}\n**Status:** Still in 'in_progress' - please complete manually\n\nThe file operation was successful, but we couldn't automatically complete the request. Please use the complete-request tool manually.`}],isError:!0}}const M=Date.now()-m
2528
2558
  let O
2529
- return f.info("Quick fix completed",{requestId:S,duration:x,hasPartialFailure:P}),O=P?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${x}ms\n**Status:** Some operations succeeded, some failed\n\nThe successful changes have been applied and automatically merged to main.\n**Active branch:** main\n\n**\u26a0\ufe0f Note:** This quick-fix had partial failures. See operation details below:\n\n`+q:`\u2705 Quick change completed successfully!\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${x}ms\n\nThe change has been applied and automatically merged to main.\n**Active branch:** main`+(q.match(/\[RECORD:trec\d{6}\]/)?.[0]?"\n"+q.match(/\[RECORD:trec\d{6}\]/)?.[0]:""),E&&(O+="\n\n\u{1f4a1} **Recommendation:** You've created several quick-edits in a row. For better traceability and organization, consider creating a proper feature or bugfix request with multiple tasks for your next change."),{content:[{type:"text",text:O}]}}catch(e){if(f.error("Quick change workflow failed after request creation, cleaning up",{requestId:S,error:(0,l.getErrorMessage)(e)}),T)try{await w.updateTaskStatus(T,"canceled"),f.info("Canceled task after workflow failure",{taskId:T})}catch(e){f.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),f.info("Canceled request after workflow failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),f.info("Cleaned up branch/worktree after workflow failure",{requestId:S}))}catch(e){f.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}throw e}}catch(e){const t=Date.now()-m
2559
+ return f.info("Quick fix completed",{requestId:S,duration:M,hasPartialFailure:P}),O=P?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${M}ms\n**Status:** Some operations succeeded, some failed\n\nThe successful changes have been applied and automatically merged to main.\n**Active branch:** main\n\n**\u26a0\ufe0f Note:** This quick-fix had partial failures. See operation details below:\n\n`+q:`\u2705 Quick change completed successfully!\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${M}ms\n\nThe change has been applied and automatically merged to main.\n**Active branch:** main`+(q.match(/\[RECORD:trec\d{6}\]/)?.[0]?"\n"+q.match(/\[RECORD:trec\d{6}\]/)?.[0]:""),E&&(O+="\n\n\u{1f4a1} **Recommendation:** You've created several quick-edits in a row. For better traceability and organization, consider creating a proper feature or bugfix request with multiple tasks for your next change."),{content:[{type:"text",text:O}]}}catch(e){if(f.error("Quick change workflow failed after request creation, cleaning up",{requestId:S,error:(0,l.getErrorMessage)(e)}),T)try{await w.updateTaskStatus(T,"canceled"),f.info("Canceled task after workflow failure",{taskId:T})}catch(e){f.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),f.info("Canceled request after workflow failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),f.info("Cleaned up branch/worktree after workflow failure",{requestId:S}))}catch(e){f.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}throw e}}catch(e){const t=Date.now()-m
2530
2560
  return f.error("Quick change failed",{error:(0,l.getErrorMessage)(e),duration:t}),e instanceof r.ValidationError?{content:[{type:"text",text:"\u274c "+e.message}],isError:!0}:{content:[{type:"text",text:"\u274c Quick change failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
2531
2561
  const r=t(9860),n=t(4079),o=t(9442),s=t(7684),i=t(355),a=t(5715),c=t(7478),l=t(8824)},3807(module){"use strict"
2532
2562
  module.exports=require("simple-git")},3884(e,exports,t){"use strict"
@@ -2606,47 +2636,47 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
2606
2636
  var t={}
2607
2637
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
2608
2638
  return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
2609
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,t,r,n,o,s,i,m,y){const w=i.child({tool:"write_file"}),k=m.startTimer("tool_execution_time"),b=Date.now()
2610
- let I,v,C=d.FileOperationPhase.VALIDATION
2611
- const _={toolName:"write_file",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"write-file",metricsPrefix:"write_file",successMessage:"Successfully wrote content",failureMessage:"Failed to write content"}
2612
- try{const r=d.validateArgs(e,l.WriteFileSchema),{taskId:i,path:f,documentId:E,content:q,format:S,append:T,comment:P}=r,j=!!E,R=!!f
2613
- w.info("Writing content to "+(j?"document":"file"),{taskId:i,filePath:R?f:void 0,documentId:j?E:void 0,contentLength:"string"==typeof q?q.length:JSON.stringify(q).length,format:S,append:T,comment:P})
2614
- let M,x,O,D="",$=!1,A=!1
2615
- const F=R?f:void 0
2616
- if(j){if(t.apiClient)try{await(0,p.ensureDocumentNotLocked)(E,t.apiClient,w,m,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2617
- throw e}if(!t.documentFileManager)throw Error("Document file manager not available")
2618
- D=await t.documentFileManager.getDocumentAsFile(E)
2619
- const e=t.documentFileManager.getCachedDocumentInfo(E)
2620
- O=e?.filename,A=!0,$=!1}C=d.FileOperationPhase.TASK_VALIDATION,m.incrementCounter("write_file_phase",1,{phase:C})
2621
- const N=R?F:"document:"+E,L=await d.validateTaskId(i,N,n,w,m,_.metricsPrefix),z=L?.requestId
2622
- let H=null
2623
- R&&z&&(H=await d.validateWorkItemStates(i,N,n,s,t,w,m,_.metricsPrefix))
2624
- let B={taskPromoted:!1,requestPromoted:!1}
2625
- R&&z&&H&&(B=await d.autoPromoteTaskStatus(i,L.status,z,H.request?.status,N,n,s,w,m,_.metricsPrefix),B.taskPromoted&&w.info("Auto-promoted task to in_progress for file operation",{taskId:i,requestId:z,previousStatus:L.status,newStatus:B.newTaskStatus,triggeringOperation:"write_file"}))
2626
- const U=await d.ensureCorrectWorkspaceContext({taskPromoted:B.taskPromoted,requestId:z,context:t,operation:"write_file",logger:w,metrics:m,metricsPrefix:_.metricsPrefix,requireRequestContext:R})
2627
- if(!U.success){if(U.isLockConflict)return{content:[{type:"text",text:"\u274c "+U.error}],isError:!0}
2628
- throw Error(U.error)}if(U.switched&&w.info("Workspace context successfully established",{requestId:z,branchName:U.branchName,operation:"write_file"}),R&&F){const e=d.validateAndNormalizePath(F,t)
2629
- M=e.normalizedPath,x=e.fullPath,D=x
2630
- try{await c.default.access(x),A=!0}catch{A=!1,$=!0}w.debug("Path validated with correct workspace context",{rawPath:F,normalizedPath:M,fullPath:x,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})}if(j&&z)try{await(0,h.validateRequestStatusForDocumentOperation)(z,s,w,m,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2631
- throw e}C=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("write_file_phase",1,{phase:C})
2632
- const{toolRecordId:G}=await d.createFileOperationRecords(i,z,t.projectId,_.recordType,N,{operationType:j?"document":"file",documentId:j?E:void 0,documentFilename:O,filePath:R?M:void 0,contentLength:"string"==typeof q?q.length:JSON.stringify(q).length,format:S||"text",append:T||!1,wasFileCreated:!A,userComment:P},n,o,w,m,_.metricsPrefix,y)
2633
- let W
2634
- if(I=G,v=G,C=_.fileOperationPhase,m.incrementCounter("write_file_phase",1,{phase:C}),"json"===S)if("string"==typeof q)try{JSON.parse(q),W=q}catch(e){throw new u.ValidationError("Content is not valid JSON")}else W=JSON.stringify(q,null,2)
2635
- else W="string"==typeof q?q:JSON.stringify(q,null,2)
2636
- let V=W
2637
- if(R&&t.git)try{w.debug("[WRITE-FILE] Checking for user changes before write operation")
2638
- const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"write_file",{requestId:t.workspaceManager?.getCurrentContext()?.requestId,taskId:i},w,m)
2639
- e.userChangesCommitted&&(w.debug("[WRITE-FILE] User changes committed before write operation",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before write-file operation",{taskId:i,path:M,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[WRITE-FILE] Pre-tool commit failed, continuing with write",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with write operation",{taskId:i,path:M,error:e instanceof Error?e.message:e+""})}if(!D)throw Error("Target path not properly initialized")
2640
- if(w.debug("[WRITE-FILE] Proceeding with file write operation",{targetPath:D}),T&&A)try{V=await c.default.readFile(D,"utf8")+W}catch(e){w.warn("Failed to read existing content for append",{error:e})}const J=a.default.dirname(D)
2641
- if(await c.default.mkdir(J,{recursive:!0}),await c.default.writeFile(D,V,"utf8"),w.info("Content written successfully",{path:R?M:"document:"+E,finalLength:V.length,append:T,wasCreated:$}),j){t.documentFileManager.markForSync(E)
2642
- try{await t.documentFileManager.syncDocument(E),w.info("Document synced successfully",{documentId:E})}catch(e){w.warn("Failed to sync document immediately",{documentId:E,error:e})}}let K,Y,Q=null
2643
- if(R){if(C=d.FileOperationPhase.GIT_COMMIT,m.incrementCounter("write_file_phase",1,{phase:C}),t.workspaceManager){const e=t.workspaceManager.getCurrentContext()
2644
- Y=e.branchName,w.debug("Retrieved branch name from workspace manager",{branchName:Y,requestId:e.requestId,mode:e.mode,isMainBranch:e.isMainBranch})}try{const e=`${$?"Create":T?"Append to":"Update"} ${M} (${v})`,r=await d.commitToGit(i,M,v,v,e,t,w,m,_.metricsPrefix)
2645
- K=r.commitHash,Q=r.previousCommitHash,w.info("Changes committed to git via shared utility",{path:M,commitMessage:e,commitHash:K?.substring(0,8),previousCommitHash:Q?.substring(0,8),branchName:Y,toolRecordId:v})}catch(e){w.warn("Git operations failed via shared utility",{error:e})}}try{await o.updateToolRecord(v,{metadata:{path:R?M:"document:"+E,status:"completed",finalContentLength:V.length,wasFileCreated:$,wasAppended:T&&A,operationType:j?"document":"file",processingTime:Date.now()-b,userComment:P,...R&&K&&{commitHash:K,previousCommitHash:Q||void 0}},note:"Write operation completed successfully"+(j?" (document synced)":" (committed to git)")})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let Z=`**${$?"Created":T?"Appended to":"Updated"} ${j?`document ${E}${O?` (${O})`:""}`:"file "+M}**\n`
2646
- Z+=`**Content Length:** ${V.length} characters\n`,R&&Y&&(Z+=`**Branch:** ${Y}\n`),U.lockAcquired&&U.lockedRequestId&&(Z+=`**Locked request:** ${U.lockedRequestId}\n`),R&&K&&(Z+=`**Commit Hash:** ${K.substring(0,8)}\n`,Q&&(Z+=`**Previous Commit:** ${Q.substring(0,8)}\n`)),v&&(Z+=`[RECORD:${v}]\n`),j&&(Z+=`\n**Document Update:** The document content has been updated and synced back to the tracking system. You can continue editing using other file modification tools with documentId \`${E}\`.`)
2647
- const X=Date.now()
2648
- return w.info("Write operation completed successfully",{duration:X-b,path:R?M:"document:"+E,contentLength:V.length,wasCreated:$}),k({tool:"write_file",success:!0}),m.incrementCounter("write_file_total",1,{success:!0}),t.workspaceManager?.largeFileWarning&&(Z+=t.workspaceManager.largeFileWarning,t.workspaceManager.largeFileWarning=""),{content:[{type:"text",text:Z}]}}catch(t){const r=Date.now()-b
2649
- if(w.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:C}),v)try{await o.updateToolRecord(v,{metadata:{path:e?.path,status:"failed",error:(0,f.getErrorMessage)(t),phase:C,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return k({tool:"write_file",success:!1}),m.incrementCounter("write_file_errors",1,{phase:C}),{content:[{type:"text",text:"\u274c **Write Operation Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
2639
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,r,n,o,s,i,m,y,w){const k=m.child({tool:"write_file"}),b=y.startTimer("tool_execution_time"),I=Date.now()
2640
+ let v,C,_=d.FileOperationPhase.VALIDATION
2641
+ const E={toolName:"write_file",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"write-file",metricsPrefix:"write_file",successMessage:"Successfully wrote content",failureMessage:"Failed to write content"}
2642
+ try{const n=d.validateArgs(e,l.WriteFileSchema),{path:f,documentId:q,content:S,format:T,append:P,comment:j}=n,{resolveActiveTaskId:R}=await Promise.resolve().then(t.bind(t,3451)),x=e.taskId||await R(r,o,m)||"untracked",M=!!q,O=!!f
2643
+ k.info("Writing content to "+(M?"document":"file"),{taskId:x,filePath:O?f:void 0,documentId:M?q:void 0,contentLength:"string"==typeof S?S.length:JSON.stringify(S).length,format:T,append:P,comment:j})
2644
+ let D,$,A,F="",N=!1,L=!1
2645
+ const z=O?f:void 0
2646
+ if(M){if(r.apiClient)try{await(0,p.ensureDocumentNotLocked)(q,r.apiClient,k,y,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2647
+ throw e}if(!r.documentFileManager)throw Error("Document file manager not available")
2648
+ F=await r.documentFileManager.getDocumentAsFile(q)
2649
+ const e=r.documentFileManager.getCachedDocumentInfo(q)
2650
+ A=e?.filename,L=!0,N=!1}_=d.FileOperationPhase.TASK_VALIDATION,y.incrementCounter("write_file_phase",1,{phase:_})
2651
+ const H=O?z:"document:"+q,B=await d.validateTaskId(x,H,o,k,y,E.metricsPrefix),U=B?.requestId
2652
+ let G=null
2653
+ O&&U&&(G=await d.validateWorkItemStates(x,H,o,i,r,k,y,E.metricsPrefix))
2654
+ let W={taskPromoted:!1,requestPromoted:!1}
2655
+ O&&U&&G&&(W=await d.autoPromoteTaskStatus(x,B.status,U,G.request?.status,H,o,i,k,y,E.metricsPrefix),W.taskPromoted&&k.info("Auto-promoted task to in_progress for file operation",{taskId:x,requestId:U,previousStatus:B.status,newStatus:W.newTaskStatus,triggeringOperation:"write_file"}))
2656
+ const V=await d.ensureCorrectWorkspaceContext({taskPromoted:W.taskPromoted,requestId:U,context:r,operation:"write_file",logger:k,metrics:y,metricsPrefix:E.metricsPrefix,requireRequestContext:O})
2657
+ if(!V.success){if(V.isLockConflict)return{content:[{type:"text",text:"\u274c "+V.error}],isError:!0}
2658
+ throw Error(V.error)}if(V.switched&&k.info("Workspace context successfully established",{requestId:U,branchName:V.branchName,operation:"write_file"}),O&&z){const e=d.validateAndNormalizePath(z,r)
2659
+ D=e.normalizedPath,$=e.fullPath,F=$
2660
+ try{await c.default.access($),L=!0}catch{L=!1,N=!0}k.debug("Path validated with correct workspace context",{rawPath:z,normalizedPath:D,fullPath:$,workspaceBasePath:r.workspaceManager?.getCurrentContext(r.currentSessionId).basePath})}if(M&&U)try{await(0,h.validateRequestStatusForDocumentOperation)(U,i,k,y,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
2661
+ throw e}_=d.FileOperationPhase.RECORD_CREATION,y.incrementCounter("write_file_phase",1,{phase:_})
2662
+ const{toolRecordId:J}=await d.createFileOperationRecords(x,U,r.projectId,E.recordType,H,{operationType:M?"document":"file",documentId:M?q:void 0,documentFilename:A,filePath:O?D:void 0,contentLength:"string"==typeof S?S.length:JSON.stringify(S).length,format:T||"text",append:P||!1,wasFileCreated:!L,userComment:j},o,s,k,y,E.metricsPrefix,w)
2663
+ let K
2664
+ if(v=J,C=J,_=E.fileOperationPhase,y.incrementCounter("write_file_phase",1,{phase:_}),"json"===T)if("string"==typeof S)try{JSON.parse(S),K=S}catch(e){throw new u.ValidationError("Content is not valid JSON")}else K=JSON.stringify(S,null,2)
2665
+ else K="string"==typeof S?S:JSON.stringify(S,null,2)
2666
+ let Y=K
2667
+ if(O&&r.git)try{k.debug("[WRITE-FILE] Checking for user changes before write operation")
2668
+ const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"write_file",{requestId:r.workspaceManager?.getCurrentContext(r.currentSessionId)?.requestId,taskId:x},k,y)
2669
+ e.userChangesCommitted&&(k.debug("[WRITE-FILE] User changes committed before write operation",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),k.info("User changes committed before write-file operation",{taskId:x,path:D,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){k.debug("[WRITE-FILE] Pre-tool commit failed, continuing with write",{error:e instanceof Error?e.message:e+""}),k.warn("Pre-tool user changes commit failed, continuing with write operation",{taskId:x,path:D,error:e instanceof Error?e.message:e+""})}if(!F)throw Error("Target path not properly initialized")
2670
+ if(k.debug("[WRITE-FILE] Proceeding with file write operation",{targetPath:F}),P&&L)try{Y=await c.default.readFile(F,"utf8")+K}catch(e){k.warn("Failed to read existing content for append",{error:e})}const Q=a.default.dirname(F)
2671
+ if(await c.default.mkdir(Q,{recursive:!0}),await c.default.writeFile(F,Y,"utf8"),k.info("Content written successfully",{path:O?D:"document:"+q,finalLength:Y.length,append:P,wasCreated:N}),M){r.documentFileManager.markForSync(q)
2672
+ try{await r.documentFileManager.syncDocument(q),k.info("Document synced successfully",{documentId:q})}catch(e){k.warn("Failed to sync document immediately",{documentId:q,error:e})}}let Z,X,ee=null,te=!1
2673
+ if(O){if(_=d.FileOperationPhase.GIT_COMMIT,y.incrementCounter("write_file_phase",1,{phase:_}),r.workspaceManager){const e=r.workspaceManager.getCurrentContext(r.currentSessionId)
2674
+ X=e.branchName,te=e.permanentBranch,k.debug("Retrieved branch name from workspace manager",{branchName:X,requestId:e.requestId,mode:e.mode,isMainBranch:e.isMainBranch})}try{const e=`${N?"Create":P?"Append to":"Update"} ${D} (${C})`,t=await d.commitToGit(x,D,C,C,e,r,k,y,E.metricsPrefix)
2675
+ Z=t.commitHash,ee=t.previousCommitHash,k.info("Changes committed to git via shared utility",{path:D,commitMessage:e,commitHash:Z?.substring(0,8),previousCommitHash:ee?.substring(0,8),branchName:X,toolRecordId:C})}catch(e){k.warn("Git operations failed via shared utility",{error:e})}}try{await s.updateToolRecord(C,{metadata:{path:O?D:"document:"+q,status:"completed",finalContentLength:Y.length,wasFileCreated:N,wasAppended:P&&L,operationType:M?"document":"file",processingTime:Date.now()-I,userComment:j,...O&&Z&&{commitHash:Z,previousCommitHash:ee||void 0}},note:"Write operation completed successfully"+(M?" (document synced)":" (committed to git)")})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let re=`**${N?"Created":P?"Appended to":"Updated"} ${M?`document ${q}${A?` (${A})`:""}`:"file "+D}**\n`
2676
+ re+=`**Content Length:** ${Y.length} characters\n`,O&&X&&(te||(re+=`**Branch:** ${X}\n`)),V.lockAcquired&&V.lockedRequestId&&!te&&(re+=`**Locked request:** ${V.lockedRequestId}\n`),O&&Z&&(re+=`**Commit Hash:** ${Z.substring(0,8)}\n`,ee&&(re+=`**Previous Commit:** ${ee.substring(0,8)}\n`)),C&&(re+=`[RECORD:${C}]\n`),M&&(re+=`\n**Document Update:** The document content has been updated and synced back to the tracking system. You can continue editing using other file modification tools with documentId \`${q}\`.`)
2677
+ const ne=Date.now()
2678
+ return k.info("Write operation completed successfully",{duration:ne-I,path:O?D:"document:"+q,contentLength:Y.length,wasCreated:N}),b({tool:"write_file",success:!0}),y.incrementCounter("write_file_total",1,{success:!0}),r.workspaceManager?.largeFileWarning&&(re+=r.workspaceManager.largeFileWarning,r.workspaceManager.largeFileWarning=""),{content:[{type:"text",text:re}]}}catch(t){const r=Date.now()-I
2679
+ if(k.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{path:e?.path,status:"failed",error:(0,f.getErrorMessage)(t),phase:_,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return b({tool:"write_file",success:!1}),y.incrementCounter("write_file_errors",1,{phase:_}),{content:[{type:"text",text:"\u274c **Write Operation Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
2650
2680
  const a=i(t(6928)),c=i(t(1943)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824)},4118(e,exports){"use strict"
2651
2681
  Object.defineProperty(exports,"__esModule",{value:!0})},4139(e,exports){"use strict"
2652
2682
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.ALCHEMY_DIR_NAME=exports.TOKEN_DIR_NAME=void 0,exports.TOKEN_DIR_NAME="alchemy-key",exports.ALCHEMY_DIR_NAME=".alchemy_lab"},4165(e,exports,t){"use strict"
@@ -2655,7 +2685,7 @@ const r=t(6183),n=t(4648)
2655
2685
  exports.def={name:"request_operations",description:"Perform operations on existing requests.\n\nOperations:\n\u2022 complete - Begin completion: provide summary, get criteria keys for verification\n\u2022 verify-criteria - Verify acceptance criteria with evidence per key (triggers merge when all verified)\n\u2022 finalize - Approve and merge a request that is ready for review\n\u2022 approve - Approve a pending request so work can begin\n\u2022 revert - Completely revert a completed request, undoing all changes\n\u2022 get-info - Get comprehensive request information\n\u2022 list - List and filter requests\n\u2022 delete-empty - Delete a request that has no tasks (safe cleanup for mistaken or obsolete requests)\n\nCompletion is two-phase: first call complete with a summary, then call verify-criteria with evidence for each criterion key.\n\nNote: To create a new request, use the separate create-request tool.",schema:r.RequestOperationsSchema,annotations:{title:"Request Operations",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},handler(e,t){return(0,n.handleRequestOperations)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},4192(e,exports,t){"use strict"
2656
2686
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseApiClient=void 0
2657
2687
  const r=t(7163)
2658
- exports.BaseApiClient=class{constructor(e,t,n,o,s){this.failureCount=0,this.circuitState="closed",this.circuitResetTimeout=null,this.baseUrl=e,this.logger=t,this.metrics=n,this.authToken=o,this.options={retryAttempts:3,retryDelay:1e3,timeout:1e4,circuitBreakerThreshold:5,circuitBreakerResetTime:3e4,...s},this.logger.debug("BaseApiClient constructor options:",{providedOptions:s?JSON.stringify(s):"undefined",mergedOptions:JSON.stringify(this.options)})
2688
+ exports.BaseApiClient=class{constructor(e,t,n,o,s){this.failureCount=0,this.circuitState="closed",this.circuitResetTimeout=null,this.baseUrl=e,this.logger=t,this.metrics=n,this.authToken=o,this.options={retryAttempts:3,retryDelay:1e3,timeout:1e4,circuitBreakerThreshold:10,circuitBreakerResetTime:1e4,...s},this.logger.debug("BaseApiClient constructor options:",{providedOptions:s?JSON.stringify(s):"undefined",mergedOptions:JSON.stringify(this.options)})
2659
2689
  try{(0,r.debugTokenAccess)(this,"BaseApiClient constructor")}catch(e){}}setAuthToken(e){this.authToken=e||void 0,this.logger.debug("Auth token updated",{hasToken:!!e,tokenLength:e?e.length:0})}getAuthToken(){return this.authToken}async requestWithRetry(e,t,r,n,o){if("open"===this.circuitState)throw this.logger.warn(`Circuit breaker open - rejecting request to ${e} ${t}`),Error("Service unavailable - circuit breaker open")
2660
2690
  const s=t.startsWith("/")?t:"/"+t
2661
2691
  let i=`${this.baseUrl}${s}`
@@ -2672,7 +2702,7 @@ const t={method:e,headers:{...a},signal:AbortSignal.timeout(this.options.timeout
2672
2702
  if("GET"!==e&&void 0!==r&&(t.body=JSON.stringify(r)),this.logger.debug("Request details",{method:e,url:i}),t.headers){const e={}
2673
2703
  Object.entries(t.headers).forEach((([t,r])=>{"authorization"===t.toLowerCase()?e[t]="Bearer [redacted]":e[t]=r})),this.logger.debug("Request headers",{headers:e})}if("GET"!==e&&t.body){const e="string"==typeof t.body?t.body:JSON.stringify(t.body)
2674
2704
  this.logger.debug("Request body",{bodyPreview:e.substring(0,200)+(e.length>200?"...":""),bodyLength:e.length})}const n=await fetch(i,t)
2675
- if(!n.ok){if(this.incrementFailureCount(),this.logger.error("API request failed with status "+n.status,{method:e,url:i,status:n.status,statusText:n.statusText,attempt:l}),401===n.status)throw g({success:!1,status:n.status,retries:l-1}),Error("Authentication failed - invalid or expired token")
2705
+ if(!n.ok){if(500>n.status||this.incrementFailureCount(),this.logger.error("API request failed with status "+n.status,{method:e,url:i,status:n.status,statusText:n.statusText,attempt:l}),401===n.status)throw g({success:!1,status:n.status,retries:l-1}),Error("Authentication failed - invalid or expired token")
2676
2706
  if(429===n.status){const e=n.headers.get("Retry-After"),t=e?1e3*parseInt(e):2*(this.options.retryDelay||1e3)
2677
2707
  if(this.logger.warn(`Rate limited (429), retrying after ${t}ms`,{attempt:l,maxAttempts:d,retryAfter:e}),d>l){await new Promise((e=>setTimeout(e,t)))
2678
2708
  continue}}if(n.status>=500&&d>l){const e=(this.options.retryDelay||1e3)*Math.pow(2,l-1)
@@ -2692,7 +2722,7 @@ return g({success:!0,status:n.status,retries:l-1,standardFormat:!1}),e}if(o&&"ob
2692
2722
  throw this.logger.error("API returned error response",{errorCode:e.error?.code,errorMessage:e.error?.message,statusCode:e.error?.statusCode}),g({success:!1,status:n.status,retries:l-1,errorCode:e.error?.code}),Error(`API error: ${e.error?.code}: ${e.error?.message}`)}if(o&&"object"==typeof o&&"success"in o&&!0===o.success&&"data"in o){const t=o
2693
2723
  return g({success:!0,status:n.status,retries:l-1,standardFormat:!0}),this.logger.debug("API request succeeded with status "+n.status,{method:e,url:i,status:n.status,retries:l-1,hasMetadata:"metadata"in t}),t}return this.logger.warn("Invalid API response format: Unexpected structure",{responseType:typeof o,responseKeys:"object"==typeof o?Object.keys(o):[]}),{success:!0,data:o}}catch(t){if(l>=d)throw this.incrementFailureCount(),this.logger.error(`API request failed after ${l} attempts`,{method:e,url:i,error:t.message||t+"",status:t.status}),g({success:!1,error:!0,retries:l-1}),t
2694
2724
  const r=Math.min((this.options.retryDelay||1e3)*Math.pow(2,l-1),5e3)
2695
- this.logger.warn(`API request failed, retrying in ${r}ms`,{method:e,url:i,error:t.message||t+"",attempt:l,maxAttempts:d}),await new Promise((e=>setTimeout(e,r)))}}throw Error("Unexpected end of requestWithRetry")}incrementFailureCount(){this.failureCount++,this.metrics.setGauge("api_failure_count",this.failureCount),"half-open"!==this.circuitState&&(this.failureCount<this.options.circuitBreakerThreshold||"closed"!==this.circuitState)||this.openCircuit()}resetFailureCount(){const e="closed"!==this.circuitState
2725
+ this.logger.warn(`API request failed, retrying in ${r}ms`,{method:e,url:i,error:t.message||t+"",attempt:l,maxAttempts:d}),await new Promise((e=>setTimeout(e,r)))}}throw Error("Unexpected end of requestWithRetry")}incrementFailureCount(){this.failureCount++,this.metrics.setGauge("api_failure_count",this.failureCount),"half-open"!==this.circuitState?this.failureCount<this.options.circuitBreakerThreshold||"closed"!==this.circuitState||this.openCircuit():this.logger.warn("Half-open probe failed, will retry on next request")}resetFailureCount(){const e="closed"!==this.circuitState
2696
2726
  this.failureCount=0,this.circuitState="closed",this.metrics.setGauge("api_failure_count",0),this.metrics.setGauge("circuit_breaker_open",0),this.circuitResetTimeout&&(clearTimeout(this.circuitResetTimeout),this.circuitResetTimeout=null),e&&this.logger.info("Circuit breaker closed after successful request")}openCircuit(){this.circuitState="open",this.metrics.setGauge("circuit_breaker_open",1),this.logger.warn(`Circuit breaker opened after ${this.failureCount} failures`),this.circuitResetTimeout&&clearTimeout(this.circuitResetTimeout)
2697
2727
  const e=this.options.circuitBreakerResetTime||5e3
2698
2728
  this.circuitResetTimeout=setTimeout((()=>{this.circuitState="half-open",this.logger.info("Circuit breaker half-open, next request will probe")}),e)}async get(e,t,r){return this.requestWithRetry("GET",e,void 0,r,t)}async post(e,t,r){return this.requestWithRetry("POST",e,t,r)}async put(e,t,r){return this.requestWithRetry("PUT",e,t,r)}async delete(e,t){return this.requestWithRetry("DELETE",e,void 0,t)}async patch(e,t,r){return this.requestWithRetry("PATCH",e,t,r)}}},4221(e,exports,t){"use strict"
@@ -2730,7 +2760,7 @@ return d({success:!1,error:"validation_failed"}),{content:[{type:"text",text:"Fa
2730
2760
  return a.blockedByTasks?.length&&(e+="\n**Tasks that must be completed first:**\n",a.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (${t.status})\n`}))),d({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}if(!t.workspaceManager)throw Error("WorkspaceManager not available")
2731
2761
  let g="workspace-manager"
2732
2762
  const p=await e.getRequest(u),f=p?.title||"Request "+u,m="resolving_conflicts"===p?.status
2733
- try{m?(l.info("Merge retry (resolving_conflicts) \u2014 using -X theirs",{requestId:u}),c=await t.workspaceManager.completeRequest(u,f,{skipConflictDetection:!0}),g="retry-theirs"):(c=await t.workspaceManager.completeRequest(u,f),g=c.autoMergeInfo?.strategy||"workspace-manager"),l.info("Merge completed",{requestId:u,mergeCommitHash:c.mergeCommitHash,mergeMethod:g})}catch(r){if(r.conflictInfo){const o=r.conflictInfo,a=o.workingDirectory||t.workspaceManager?.getCurrentContext()?.basePath||process.cwd(),c=(0,n.createConflictResolutionManager)(l,i,a,t.git),h=await c.handleConflicts(o)
2763
+ try{m?(l.info("Merge retry (resolving_conflicts) \u2014 using -X theirs",{requestId:u}),c=await t.workspaceManager.completeRequest(u,f,{skipConflictDetection:!0}),g="retry-theirs"):(c=await t.workspaceManager.completeRequest(u,f),g=c.autoMergeInfo?.strategy||"workspace-manager"),l.info("Merge completed",{requestId:u,mergeCommitHash:c.mergeCommitHash,mergeMethod:g})}catch(r){if(r.conflictInfo){const o=r.conflictInfo,a=o.workingDirectory||t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||process.cwd(),c=(0,n.createConflictResolutionManager)(l,i,a,t.git),h=await c.handleConflicts(o)
2734
2764
  try{await e.updateRequest(u,{status:"resolving_conflicts"}),l.info("Set status to resolving_conflicts",{requestId:u})}catch(e){l.error("Failed to set resolving_conflicts status",{requestId:u,error:(0,s.getErrorMessage)(e)})}return d({success:!1,reason:"merge_conflicts"}),{content:[{type:"text",text:h.userMessage}],isError:!1}}const o=(0,s.getErrorMessage)(r)
2735
2765
  return d({success:!1,error:"merge_failure"}),{content:[{type:"text",text:"Merge failed: "+o}],isError:!0}}try{await i.proxyPost(`/api/projects/${t.projectId}/requests/${u}/finalize-completion`,{summary:p?.completionSummary||"Merged request "+u,acceptanceEvidence:h.map((e=>({evidence:e.evidence}))),mergeResult:{mergeCommitHash:c.mergeCommitHash,mergedFiles:c.mergedFiles,cleanedUp:c.cleanedUp,method:g}})}catch(e){const t=(0,s.getErrorMessage)(e)
2736
2766
  return l.error("CRITICAL: Merge succeeded but server finalization failed",{requestId:u,mergeCommitHash:c.mergeCommitHash,error:t}),d({success:!1,error:"api_update_failed"}),{content:[{type:"text",text:`CRITICAL: Code was merged (commit: ${c.mergeCommitHash.substring(0,8)}) but failed to update server: ${t}`}],isError:!0}}return d({success:!0}),{content:[{type:"text",text:`Request ${u} merged successfully.\nCommit: ${c.mergeCommitHash.substring(0,8)}`}]}}catch(e){const r=(0,s.getErrorMessage)(e)
@@ -2751,7 +2781,38 @@ const s=(n.content||"")+e.content,i={content:s}
2751
2781
  e.name&&(i.filename=e.name.replace(/\.md$/i,"")+".md")
2752
2782
  const a=await r.updateDocument(e.planId,i),c=a.localId||a.id
2753
2783
  return o.info("Plan appended",{planId:c,appendedLength:e.content.length}),{content:[{type:"text",text:`\u2705 **Plan Appended**\n\n**Plan ID:** ${c}\n**Appended:** ${e.content.length} characters\n**Total Length:** ${s.length} characters`}]}}catch(e){return o.error("Failed to append to plan",{error:(0,r.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c **Failed to append to plan:** "+(0,r.getErrorMessage)(e)}],isError:!0}}}
2754
- const r=t(8824)},4465(e,exports,t){"use strict"
2784
+ const r=t(8824)},4425(e,exports,t){"use strict"
2785
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCommands=async function(e,t,s,i,a,c){const l=a.startTimer("tool_execution_time"),d=e.operation||"run"
2786
+ try{const a=await s.proxyGet(`/api/projects/${t.projectId}/check-commands`),u=a?.data||a||[],h=u.filter((e=>e.isActive)),g=u.filter((e=>!e.isActive))
2787
+ if("list"===d){if(0===u.length)return l({success:!0}),{content:[{type:"text",text:'No commands configured for this project yet.\n\nUse `commands({ operation: "add", name: "typecheck", command: "tsc --noEmit" })` to add one.'}]}
2788
+ const e=[]
2789
+ return h.length>0&&(e.push(`## Available Commands (${h.length})\n`),e.push(...h.map((e=>`- **${e.name}**: \`${e.command}\`${e.description?" \u2014 "+e.description:""}`)))),g.length>0&&(e.push(`\n## Pending Approval (${g.length})\n`),e.push(...g.map((e=>`- **${e.name}**: \`${e.command}\` \u2014 \u23f3 waiting for user approval`)))),e.push('\nRun: `commands({ name: "name" })`\nAdd: `commands({ operation: "add", name: "...", command: "..." })`\nRemove: `commands({ operation: "remove", name: "..." })`'),l({success:!0}),{content:[{type:"text",text:e.join("\n")}]}}if("add"===d){if(!e.name?.trim())return l({success:!1,error:"missing_name"}),{content:[{type:"text",text:"Error: `name` is required when adding a command."}],isError:!0}
2790
+ if(!e.command?.trim())return l({success:!1,error:"missing_command"}),{content:[{type:"text",text:"Error: `command` is required when adding a command."}],isError:!0}
2791
+ const r=u.find((t=>t.name.toLowerCase()===e.name.toLowerCase()))
2792
+ if(r)return l({success:!1,error:"duplicate"}),{content:[{type:"text",text:`Command "${e.name}" already exists: \`${r.command}\`${r.isActive?"":" (pending approval)"}`}],isError:!0}
2793
+ try{const r=await s.proxyPost(`/api/projects/${t.projectId}/check-commands`,{name:e.name.trim(),command:e.command.trim(),description:e.description?.trim(),timeout:e.timeout||60}),n=r?.data?.id||r?.id
2794
+ n&&await s.proxyPatch(`/api/projects/${t.projectId}/check-commands/${n}`,{isActive:!1})
2795
+ const a=s.getSessionMessageClient(),c=o.sessionIdentity.getIdentity(),d=c?.sessionId||"unknown"
2796
+ return a&&await a.createQuestion({fromSessionId:d,questionType:"alternatives",question:`Command approval: \`${e.command.trim()}\``,options:[{id:"approve",label:"Approve",description:`Add "${e.name.trim()}" to project commands`},{id:"deny",label:"Deny",description:"Reject this command"}],context:JSON.stringify({type:"command-approval",commandId:n,name:e.name.trim(),command:e.command.trim()}),category:"action-required",priority:"high"}),i.info("Command approval requested",{name:e.name,command:e.command,commandId:n}),l({success:!0}),{content:[{type:"text",text:`Command **${e.name}** (\`${e.command}\`) submitted for user approval.\n\nUse \`commands({ operation: "list" })\` to check status.`}]}}catch(e){return l({success:!1,error:"add_failed"}),{content:[{type:"text",text:"Failed to request command approval: "+(0,n.getErrorMessage)(e)}],isError:!0}}}if("remove"===d){if(!e.name?.trim())return l({success:!1,error:"missing_name"}),{content:[{type:"text",text:"Error: `name` is required when removing a command."}],isError:!0}
2797
+ const r=u.find((t=>t.name.toLowerCase()===e.name.toLowerCase()))
2798
+ if(!r)return l({success:!1,error:"not_found"}),{content:[{type:"text",text:`Command "${e.name}" not found.`}],isError:!0}
2799
+ try{return await s.proxyDelete(`/api/projects/${t.projectId}/check-commands/${r.id}`),i.info("Removed command",{name:r.name,id:r.id}),l({success:!0}),{content:[{type:"text",text:`Removed command **${r.name}**.`}]}}catch(e){return l({success:!1,error:"remove_failed"}),{content:[{type:"text",text:"Failed to remove command: "+(0,n.getErrorMessage)(e)}],isError:!0}}}if(!e.name){const e=h.map((e=>e.name)).join(", ")
2800
+ return l({success:!1,error:"missing_name"}),{content:[{type:"text",text:"Error: `name` is required when running a command.\n\nAvailable commands: "+(e||"(none configured)")}],isError:!0}}const p=h.find((t=>t.name.toLowerCase()===e.name.toLowerCase()))
2801
+ if(!p){const t=h.map((e=>e.name)).join(", ")
2802
+ return l({success:!1,error:"not_found"}),{content:[{type:"text",text:`Command "${e.name}" not found.\n\nAvailable commands: ${t||"(none configured)"}`}],isError:!0}}let f=e.args?`${p.command} ${e.args}`:p.command
2803
+ e.grep&&(f=`${f} 2>&1 | grep -i ${JSON.stringify(e.grep)}`)
2804
+ const m=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
2805
+ i.info("Running command",{name:p.name,command:f,cwd:m})
2806
+ let y="",w="",k=0,b=!1
2807
+ try{y=(0,r.execSync)(f,{cwd:m,timeout:1e3*(p.timeout||60),encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"win32"===process.platform?"cmd.exe":"/bin/sh",env:{...process.env,FORCE_COLOR:"0"}})||""}catch(e){k=e.status??1,y=e.stdout||"",w=e.stderr||"",e.killed&&(b=!0)}const I=8e3,v=4e3
2808
+ y.length>I&&(y="\u2026"+y.slice(-I)),w.length>v&&(w="\u2026"+w.slice(-v))
2809
+ const C=b?"TIMEOUT":null,_=[y,w].filter(Boolean).join("\n")||"(no output)"
2810
+ let E
2811
+ if(c)try{const e=await c.createToolRecord({projectId:t.projectId,type:"run-command",metadata:{name:p.name,command:f,exitCode:k,timedOut:b,status:b?"timeout":0===k?"success":"failed",timestamp:(new Date).toISOString()}})
2812
+ E=e?.id}catch(e){i.debug("Failed to create tool record for command run",{error:(0,n.getErrorMessage)(e)})}l({success:!0})
2813
+ const q=E?`\n[RECORD:${E}]`:""
2814
+ return{content:[{type:"text",text:`## ${p.name}${C?` \u2014 ${C} (killed after ${p.timeout}s)`:""}\n\`\`\`\n$ ${f}\n${_}\n\`\`\`\n\nExit code: ${k}${q}`}]}}catch(e){return l({success:!1,error:"api_error"}),{content:[{type:"text",text:"Failed to run command: "+(0,n.getErrorMessage)(e)}],isError:!0}}}
2815
+ const r=t(5317),n=t(8824),o=t(6688)},4465(e,exports,t){"use strict"
2755
2816
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.SessionTagMappingClient=void 0
2756
2817
  const r=t(7645),n=t(2161)
2757
2818
  class o extends r.ConnectionAwareClient{constructor(e,t,r,n,o,s,i){const a=t.child({component:"session-tag-mapping-client"}),c=s||{isInOfflineMode(){return!1},isOffline(){return!1},setOfflineMode(){},async checkConnectivity(){return!0},getHealthCheckStats(){return{isOffline:!1,consecutiveFailures:0,currentBackoffMs:0,lastCheckTime:0}},cleanup(){}}
@@ -2770,7 +2831,15 @@ if(!t)throw Error("Project ID is required for mapping operations")
2770
2831
  this.logger.debug("Getting mapping by OpenCode session ID",{opencodeSessionId:e,projectId:t})
2771
2832
  try{const r=await this.requestWithRetry("GET",`/api/projects/${t}/session-tag-mappings/by-opencode/${encodeURIComponent(e)}`)
2772
2833
  return(0,n.safeGetResponseData)(r,null,this.logger)}catch(e){if(404===e.statusCode||e.message?.includes("404"))return null
2773
- throw e}}}exports.SessionTagMappingClient=o},4592(e,exports,t){"use strict"
2834
+ throw e}}}exports.SessionTagMappingClient=o},4466(e,exports){"use strict"
2835
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.isTaskRef=function(e){return t.test(e)},exports.formatTaskRef=function(e,t){return`${e}#${t.toString().padStart(2,"0")}`},exports.resolveTaskRef=async function(e,r){const n=e.match(t)
2836
+ if(!n)throw Error(`Invalid task reference: ${e}. Expected format: req######+#NN (e.g. req000005#03)`)
2837
+ const[,o,s]=n,i=parseInt(s,10)
2838
+ if(1>i)throw Error(`Invalid task number in ${e}: must be >= 1`)
2839
+ const a=r.getTaskClient(),c=await a.listTasks({requestId:o,sortBy:"created",sortDirection:"asc"}),l=c.find((e=>e.sequenceNumber===i))||c[i-1]
2840
+ if(!l){const e=c.length
2841
+ throw Error(`Task #${i} not found in request ${o} (${e} task${1===e?"":"s"} exist).`)}return l.localId||l.id}
2842
+ const t=/^(req\d{6})#(\d+)$/},4592(e,exports,t){"use strict"
2774
2843
  var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
2775
2844
  var o=Object.getOwnPropertyDescriptor(t,r)
2776
2845
  o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[]
@@ -2780,7 +2849,9 @@ var t={}
2780
2849
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
2781
2850
  return o(t,e),t})
2782
2851
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handlePlannerOps=async function(e,t,r,n,o,s){const h=r.child({tool:"planner_ops"}),g=n.startTimer("tool_execution_time")
2783
- try{if(e?.request&&"string"==typeof e.request)try{e.request=JSON.parse(e.request)}catch{}"request"===e?.operation&&e?.prompt&&!e?.request&&(e.request={prompt:e.prompt,description:e.description||e.prompt.slice(0,60)},delete e.prompt,delete e.description)
2852
+ try{if(e?.request&&"object"==typeof e.request){const t=e.request
2853
+ e.prompt=e.prompt||t.prompt,e.description=e.description||t.description,delete e.request}if(e?.list&&"object"==typeof e.list){const t=e.list
2854
+ e.activeOnly=e.activeOnly??t.activeOnly,e.limit=e.limit??t.limit,delete e.list}!e?.operation&&e&&(e.prompt?e.operation="request":e.sessionId&&(e.operation="check-status")),e?.operation&&("request"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.limit):"check-status"===e.operation?(delete e.prompt,delete e.description,delete e.activeOnly,delete e.limit):"list"===e.operation&&(delete e.sessionId,delete e.prompt,delete e.description))
2784
2855
  const r=c.validateArgs(e,a.PlannerOpsSchema),{operation:p,sessionId:f}=r
2785
2856
  let m
2786
2857
  switch(h.info("Processing planner_ops",{operation:p,sessionId:f}),p){case"request":{const e=await async function(e,t,r){if(!e)return"ask"
@@ -2798,13 +2869,13 @@ if("ask"===n)return"ask"
2798
2869
  if("interactive"===n)return"interactive"}catch(e){t.warn("Failed to read project metadata for planningMode fallback",{error:(0,l.getErrorMessage)(e)})}return"ask"}catch(e){return t.warn("Failed to read planningMode from workflow, defaulting to ask",{error:(0,l.getErrorMessage)(e)}),"ask"}}(o,h,s)
2799
2870
  if("ask"===e||"interactive"===e){h.info("Returning planner choice pending",{planningMode:e})
2800
2871
  try{const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,t=o?.getSessionMessageClient()
2801
- if(t&&e){const n=await d.sessionIdentity.getParentSessionId(e,o,h),s=r.request.description||r.request.prompt
2802
- await t.createQuestion({fromSessionId:e,toSessionId:n||void 0,questionType:"alternatives",question:"Planning requested: "+s,options:[{id:"auto",label:"Auto Plan",description:"Spawn an autonomous planner agent"},{id:"manual",label:"Manual Plan",description:"Open the interactive plan editor"},{id:"cancel",label:"Skip",description:"Dismiss this planning request"}],context:r.request.prompt,category:"action-required",priority:"high"}),h.info("planner-request: notification created",{fromSessionId:e})}else h.warn("planner-request: skipping notification",{hasClient:!!t,hasCallerSessionId:!!e})}catch(e){h.warn("planner-request: failed to create notification",{error:(0,l.getErrorMessage)(e)})}m={content:[{type:"text",text:"Planning request submitted. The user will choose the planning approach. This is non-blocking \u2014 continue with your other work.\nPLANNER_CHOICE_PENDING|"+JSON.stringify({prompt:r.request.prompt,description:r.request.description})}]}
2872
+ if(t&&e){const n=await d.sessionIdentity.getParentSessionId(e,o,h),s=r.description||r.prompt
2873
+ await t.createQuestion({fromSessionId:e,toSessionId:n||void 0,questionType:"alternatives",question:"Planning requested: "+s,options:[{id:"auto",label:"Auto Plan",description:"Spawn an autonomous planner agent"},{id:"manual",label:"Manual Plan",description:"Open the interactive plan editor"},{id:"cancel",label:"Skip",description:"Dismiss this planning request"}],context:r.prompt,category:"action-required",priority:"high"}),h.info("planner-request: notification created",{fromSessionId:e})}else h.warn("planner-request: skipping notification",{hasClient:!!t,hasCallerSessionId:!!e})}catch(e){h.warn("planner-request: failed to create notification",{error:(0,l.getErrorMessage)(e)})}m={content:[{type:"text",text:"Planning request submitted. The user will choose the planning approach. This is non-blocking \u2014 continue with your other work.\nPLANNER_CHOICE_PENDING|"+JSON.stringify({prompt:r.prompt,description:r.description})}]}
2803
2874
  break}const n="auto-planner"
2804
- if(h.info("Spawning planner",{planningMode:e,agent:n}),m=await(0,u.handleSpawn)({agent:n,prompt:r.request.prompt,title:r.request.description},t,h,o),!m.isError&&m.content.length>0){const t=m.content[0].text
2875
+ if(h.info("Spawning planner",{planningMode:e,agent:n}),m=await(0,u.handleSpawn)({agent:n,prompt:r.prompt,title:r.description},t,h,o),!m.isError&&m.content.length>0){const t=m.content[0].text
2805
2876
  m.content[0].text=`Planning mode: ${e} (agent: ${n}). Planning is running in the background \u2014 continue with your other work.\n${t}`}break}case"check-status":m=await(0,u.handleCheckStatus)(f,t,h,o)
2806
2877
  break
2807
- case"list":const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,[n,a]=await Promise.all([(0,u.handleListSessions)(t,h,o,{activeOnly:r.list?.activeOnly,limit:r.list?.limit,agentType:"auto-planner",parentSessionId:e}),(0,u.handleListSessions)(t,h,o,{activeOnly:r.list?.activeOnly,limit:r.list?.limit,agentType:"planner",parentSessionId:e})]),c=n.content[0]?.text??"",g=a.content[0]?.text??""
2878
+ case"list":const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,[n,a]=await Promise.all([(0,u.handleListSessions)(t,h,o,{activeOnly:r.activeOnly,limit:r.limit,agentType:"auto-planner",parentSessionId:e}),(0,u.handleListSessions)(t,h,o,{activeOnly:r.activeOnly,limit:r.limit,agentType:"planner",parentSessionId:e})]),c=n.content[0]?.text??"",g=a.content[0]?.text??""
2808
2879
  if(c.trim()||g.trim()){const e=[]
2809
2880
  c.trim()&&e.push("## Auto-planner sessions\n"+c),g.trim()&&e.push("## Interactive plan sessions\n"+g),m={content:[{type:"text",text:e.join("\n\n")}]}}else m={content:[{type:"text",text:"No planning sessions found."}]}
2810
2881
  break
@@ -2826,11 +2897,11 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
2826
2897
  var t={}
2827
2898
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
2828
2899
  return o(t,e),t})
2829
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,t,r,n,o,s,g){const p=o.child({tool:"file_recover"}),f=s.startTimer("tool_execution_time"),m=Date.now()
2830
- try{let o
2831
- try{o=i.FileRecoverSchema.parse(e)}catch(t){if(t instanceof a.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
2832
- return p.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{taskId:f,path:y,commitHash:w,createBackup:k}=o
2833
- return p.info("Recovering file to previous version",{taskId:f,filePath:y,commitHash:w,createBackup:k}),await async function(e,t,r,n,o,s,i,a,g,p,f){let m
2900
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,r,n,o,s,g,p){const f=s.child({tool:"file_recover"}),m=g.startTimer("tool_execution_time"),y=Date.now()
2901
+ try{let m
2902
+ try{m=i.FileRecoverSchema.parse(e)}catch(t){if(t instanceof a.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
2903
+ return f.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{path:w,commitHash:k,createBackup:b}=m,{resolveActiveTaskId:I}=await Promise.resolve().then(t.bind(t,3451)),v=e.taskId||await I(r,n,s)||"untracked"
2904
+ return f.info("Recovering file to previous version",{taskId:v,filePath:w,commitHash:k,createBackup:b}),await async function(e,t,r,n,o,s,i,a,g,p,f){let m
2834
2905
  try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:b}=await d.createFileOperationRecords(e,k?.requestId,o.projectId,"file-recover",y,{operationType:"file",filePath:y,commitHash:r,createBackup:n},s.getTaskClient(),i,a,g,"file-recover",f)
2835
2906
  m=b
2836
2907
  let I,v=!1
@@ -2845,29 +2916,32 @@ let E={}
2845
2916
  try{const t=`Recover ${y} from ${r.substring(0,8)}`
2846
2917
  E=await d.commitToGit(e,y,m,m,t,o,a,g,"file-recover"),a.info("Recovery committed via shared utility",{path:y,sourceCommitHash:r,newCommitHash:E.commitHash?.substring(0,8),commitMessage:t})}catch(e){a.warn("Failed to commit recovery via shared utility",{error:e})}if(m)try{await i.updateToolRecord(m,{metadata:{path:y,status:"completed",recoveredLength:_.length,hadBackup:n&&v,backupPath:I,wasFileCreated:!v,processingTime:Date.now()-p,...E.commitHash&&{commitHash:E.commitHash,previousCommitHash:E.previousCommitHash||void 0}},note:"File recovered successfully from "+r.substring(0,8)})}catch(e){a.warn("Failed to update tool record",{recordError:e})}const q=v?"recovered":"created from recovery"
2847
2918
  let S=`\u2705 **File ${q.charAt(0).toUpperCase()+q.slice(1)} Successfully**\n\n`
2848
- return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&I&&(S+=`**Backup created:** ${c.basename(I)}\n`),S+="**Git status:** Recovery committed\n",S+="\u{1f4a1} **Tip:** The file has been restored to its state at the specified commit.",a.info("File recovery completed successfully",{path:y,commitHash:r,duration:Date.now()-p}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(f,y,w,k,t,r,n,p,s,m,g)}catch(e){const t=Date.now()-m
2849
- return p.error("Recovery operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),f({tool:"file_recover",success:!1}),s.incrementCounter("file_recover_errors",1),{content:[{type:"text",text:"\u274c **Recovery Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
2919
+ return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&I&&(S+=`**Backup created:** ${c.basename(I)}\n`),S+="**Git status:** Recovery committed\n",S+="\u{1f4a1} **Tip:** The file has been restored to its state at the specified commit.",a.info("File recovery completed successfully",{path:y,commitHash:r,duration:Date.now()-p}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(v,w,k,b,r,n,o,f,g,y,p)}catch(e){const t=Date.now()-y
2920
+ return f.error("Recovery operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),m({tool:"file_recover",success:!1}),g.incrementCounter("file_recover_errors",1),{content:[{type:"text",text:"\u274c **Recovery Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
2850
2921
  const i=t(6183),a=t(1569),c=s(t(6928)),l=s(t(1943)),d=s(t(5967)),u=t(3922),h=t(8824)},4648(e,exports,t){"use strict"
2851
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,t,u,h,g,p){const f=h.child({tool:"request_operations"})
2852
- try{for(const t of["complete","verifyCriteria","merge","revert","search","list"])if(e&&"string"==typeof e[t])try{e[t]=JSON.parse(e[t])}catch{}"complete"===e?.operation&&e?.summary&&!e?.complete&&(e.complete={summary:e.summary},delete e.summary),"complete"!==e?.operation||e?.complete||e?.summary||(e.complete={summary:""}),"merge"===e?.operation&&e?.verifications&&!e?.merge&&(e.merge={verifications:e.verifications},delete e.verifications),e?.merge&&Array.isArray(e.merge)&&(e.merge={verifications:e.merge}),"verify-criteria"===e?.operation&&(e.operation="merge",e.verifyCriteria&&!e.merge&&(e.merge=e.verifyCriteria,delete e.verifyCriteria)),"finalize"===e?.operation&&(e.operation="merge",e.merge||(e.merge={verifications:[]})),"revert"===e?.operation&&e?.reason&&!e?.revert&&(e.revert={reason:e.reason,confirmDestructive:e.confirmDestructive},delete e.reason,delete e.confirmDestructive),"search"===e?.operation&&e?.query&&!e?.search&&(e.search={query:e.query,searchIn:e.searchIn||"all",filters:e.filters},delete e.query,delete e.searchIn,delete e.filters)
2853
- const m=r.RequestOperationsSchema.parse(e),{requestId:y,operation:w}=m
2854
- switch(f.info("Processing request operation",{requestId:y,operation:w}),w){case"complete":{f.info("Routing to complete-request handler")
2855
- const e={requestId:y,summary:m.complete.summary}
2856
- return await(0,n.handleCompleteRequest)(e,t,u,h,g,p)}case"merge":return f.info("Routing to merge handler"),await(0,l.handleMergeRequest)({requestId:y,verifications:m.merge?.verifications||[]},t,u,h,g,p)
2857
- case"approve":{f.info("Routing to approve-request handler")
2858
- const e={requestId:y}
2859
- return await(0,c.handleApproveRequest)(e,t,u,h,g,p)}case"revert":{f.info("Routing to revert-request handler")
2860
- const e={requestId:y,reason:m.revert.reason,confirmDestructive:m.revert.confirmDestructive}
2861
- return await(0,o.handleRevertRequest)(e,t,u,h,g)}case"get-info":{f.info("Routing to get-request-information handler")
2862
- const e={requestId:y}
2863
- return await(0,s.handleGetRequestInformation)(e,t,u,h,g)}case"list":{f.info("Routing to list-requests handler")
2864
- const e={filters:m.list?.filters}
2865
- return await(0,i.handleListRequests)(e,t,u,h,g)}case"search":{f.info("Routing to search-requests handler")
2866
- const e={search:m.search}
2867
- return await(0,a.handleSearchRequests)(e,t,u,h,g)}case"delete-empty":if(f.info("Routing to delete-empty handler"),!y)return{content:[{type:"text",text:"\u274c **Request Operations Failed:** requestId is required for delete-empty"}],isError:!0}
2868
- try{const e=u.getProxyClient(),r=await e.proxyGet(`/api/projects/${t.projectId}/tasks`,{requestLocalId:y,limit:1}),n=r?.data||r||[]
2869
- return(Array.isArray(n)?n.length:0)>0?{content:[{type:"text",text:`\u274c Cannot delete ${y}: it has tasks. Only empty requests (no tasks created) can be deleted.`}],isError:!0}:(await e.proxyDelete(`/api/projects/${t.projectId}/requests/${y}`),f.info("Empty request deleted",{requestId:y}),{content:[{type:"text",text:`\u2705 Request ${y} deleted (had no tasks).`}]})}catch(e){return{content:[{type:"text",text:"\u274c **Failed to delete request:** "+(0,d.getErrorMessage)(e)}],isError:!0}}default:{const e="Unknown operation type: "+w
2870
- return f.error(e),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+e}],isError:!0}}}}catch(e){return f.error("Request operations failed",{error:e instanceof Error?e.stack:e+""}),g.incrementCounter("request_operations_errors",1),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
2922
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,u,h,g,p,f){const m=g.child({tool:"request_operations"})
2923
+ try{for(const t of["complete","verifyCriteria","merge","revert","search","list"])if(e&&"string"==typeof e[t])try{e[t]=JSON.parse(e[t])}catch{}if("complete"===e?.operation&&e?.summary&&!e?.complete&&(e.complete={summary:e.summary},delete e.summary),"complete"!==e?.operation||e?.complete||e?.summary||(e.complete={summary:""}),"merge"===e?.operation&&e?.verifications&&!e?.merge&&(e.merge={verifications:e.verifications},delete e.verifications),e?.merge&&Array.isArray(e.merge)&&(e.merge={verifications:e.merge}),"verify-criteria"===e?.operation&&(e.operation="merge",e.verifyCriteria&&!e.merge&&(e.merge=e.verifyCriteria,delete e.verifyCriteria)),"finalize"===e?.operation&&(e.operation="merge",e.merge||(e.merge={verifications:[]})),"revert"===e?.operation&&e?.reason&&!e?.revert&&(e.revert={reason:e.reason,confirmDestructive:e.confirmDestructive},delete e.reason,delete e.confirmDestructive),"search"===e?.operation&&e?.query&&!e?.search&&(e.search={query:e.query,searchIn:e.searchIn||"all",filters:e.filters},delete e.query,delete e.searchIn,delete e.filters),e?.operation){const t=e.operation,r=["complete","merge","revert","list","search","approve"],n={complete:"complete",merge:"merge",revert:"revert",list:"list",search:"search",approve:void 0,"get-info":void 0,"delete-empty":void 0}[t]
2924
+ for(const t of r)t!==n&&delete e[t]}const y=r.RequestOperationsSchema.parse(e)
2925
+ let{requestId:w}=y
2926
+ const{operation:k}=y
2927
+ if(!w){const{sessionIdentity:e}=await Promise.resolve().then(t.bind(t,6688)),r=u.currentSessionId
2928
+ if(r&&"__unknown__"!==r&&"__server__"!==r&&(w=await e.getSessionRequestId(h,m,r)||void 0),!w)return{content:[{type:"text",text:`Error: requestId is required for '${k}' and could not be resolved from session`}],isError:!0}}switch(m.info("Processing request operation",{requestId:w,operation:k}),k){case"complete":{m.info("Routing to complete-request handler")
2929
+ const e={requestId:w,summary:y.complete.summary}
2930
+ return await(0,n.handleCompleteRequest)(e,u,h,g,p,f)}case"merge":return m.info("Routing to merge handler"),await(0,l.handleMergeRequest)({requestId:w,verifications:y.merge?.verifications||[]},u,h,g,p,f)
2931
+ case"approve":{m.info("Routing to approve-request handler")
2932
+ const e={requestId:w}
2933
+ return await(0,c.handleApproveRequest)(e,u,h,g,p,f)}case"revert":{m.info("Routing to revert-request handler")
2934
+ const e={requestId:w,reason:y.revert.reason,confirmDestructive:y.revert.confirmDestructive}
2935
+ return await(0,o.handleRevertRequest)(e,u,h,g,p)}case"get-info":{m.info("Routing to get-request-information handler")
2936
+ const e={requestId:w}
2937
+ return await(0,s.handleGetRequestInformation)(e,u,h,g,p)}case"list":{m.info("Routing to list-requests handler")
2938
+ const e={filters:y.list?.filters}
2939
+ return await(0,i.handleListRequests)(e,u,h,g,p)}case"search":{m.info("Routing to search-requests handler")
2940
+ const e={search:y.search}
2941
+ return await(0,a.handleSearchRequests)(e,u,h,g,p)}case"delete-empty":if(m.info("Routing to delete-empty handler"),!w)return{content:[{type:"text",text:"\u274c **Request Operations Failed:** requestId is required for delete-empty"}],isError:!0}
2942
+ try{const e=h.getProxyClient(),t=await e.proxyGet(`/api/projects/${u.projectId}/tasks`,{requestLocalId:w,limit:1}),r=t?.data||t||[]
2943
+ return(Array.isArray(r)?r.length:0)>0?{content:[{type:"text",text:`\u274c Cannot delete ${w}: it has tasks. Only empty requests (no tasks created) can be deleted.`}],isError:!0}:(await e.proxyDelete(`/api/projects/${u.projectId}/requests/${w}`),m.info("Empty request deleted",{requestId:w}),{content:[{type:"text",text:`\u2705 Request ${w} deleted (had no tasks).`}]})}catch(e){return{content:[{type:"text",text:"\u274c **Failed to delete request:** "+(0,d.getErrorMessage)(e)}],isError:!0}}default:{const e="Unknown operation type: "+k
2944
+ return m.error(e),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+e}],isError:!0}}}}catch(e){return m.error("Request operations failed",{error:e instanceof Error?e.stack:e+""}),p.incrementCounter("request_operations_errors",1),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
2871
2945
  const r=t(6183),n=t(5715),o=t(6416),s=t(5434),i=t(8037),a=t(233),c=t(1537),l=t(4306),d=t(8824)},4710(e,exports,t){"use strict"
2872
2946
  var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
2873
2947
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectClient=void 0
@@ -2994,7 +3068,7 @@ return a(t,e),t})
2994
3068
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileBlame=async function(e,t,s,i,a){const c=i.child({tool:"file_blame"}),g=Date.now()
2995
3069
  try{const{path:i,lines:p,branch:f}=e
2996
3070
  c.info("Processing blame request",{filePath:i,lines:p,branch:f})
2997
- const m=t.basePath,y=d.isAbsolute(i)?i:d.join(m,i),w=d.relative(m,y)
3071
+ const m=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath,y=d.isAbsolute(i)?i:d.join(m,i),w=d.relative(m,y)
2998
3072
  try{await u.access(y)}catch{return{content:[{type:"text",text:"\u274c File not found: "+w}],isError:!0}}const k=function(e){if(!e)return null
2999
3073
  if(/^\d+$/.test(e)){const t=parseInt(e,10)
3000
3074
  return{start:t,end:t}}const t=e.match(/^(\d+)-(\d+)$/)
@@ -3077,7 +3151,7 @@ return t.success?(this.logger.info("Successfully removed worktree",{requestId:e.
3077
3151
  return await this.worktreeManager.getWorktreeInfo(t)||null}catch(t){return this.logger.warn("Failed to get worktree info",{requestId:e,error:(0,i.getErrorMessage)(t)}),null}}getMainGit(){return this.mainGit}}},4973(e,exports,t){"use strict"
3078
3152
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3079
3153
  const r=t(6183),n=t(4592)
3080
- exports.def={name:"planner_ops",description:"Request a planning session and check on planner progress.\n\nOperations:\n\u2022 request - Start a planning session for a feature or architecture question\n\u2022 check-status - Check if a planner is busy or idle\n\u2022 list - List planning sessions",schema:r.PlannerOpsSchema,annotations:{title:"Planner Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handlePlannerOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5003(e,exports,t){"use strict"
3154
+ exports.def={name:"planner_ops",description:"Request a planning session and check on planner progress.\n\nAll params are flat (no nested objects). The operation field determines which params apply.\n\nOperations:\n\u2022 request \u2014 prompt required. Optional: description\n\u2022 check-status \u2014 sessionId required\n\u2022 list \u2014 all optional: activeOnly, limit",schema:r.PlannerOpsSchema,annotations:{title:"Planner Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handlePlannerOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5003(e,exports,t){"use strict"
3081
3155
  async function r(e,t,r,s,i){const a=r.child({requestId:e,operation:"request-status-validation"})
3082
3156
  try{a.info("Validating request status for document operation",{requestId:e})
3083
3157
  const r=await t.getRequest(e)
@@ -3327,7 +3401,7 @@ try{await(0,o.createFailureToolRecord)("complete-request",r,{error:s,details:i,r
3327
3401
  const r=t(9860),n=t(1569),o=t(8616),s=t(8824),i=t(5454)},5767(e,exports,t){"use strict"
3328
3402
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3329
3403
  const r=t(6183),n=t(6285)
3330
- exports.def={name:"specialist_ops",description:"Manage your pool of up to 10 specialists. Each has a specialization describing their domain. Reuse specialists via follow-up before spawning new ones.\n\nOperations:\n\u2022 delegate - Spawn a new specialist (include specialization). Abort an idle specialist first if pool is full.\n\u2022 follow-up - Send follow-up instructions to an existing specialist (can update specialization)\n\u2022 check-status - Check if a specialist is busy or idle\n\u2022 list - List specialist sessions with specializations\n\u2022 abort - Cancel a stuck specialist",schema:r.SpecialistOpsSchema,annotations:{title:"Specialist Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSpecialistOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5802(module){"use strict"
3404
+ exports.def={name:"specialist_ops",description:"Manage your pool of up to 10 specialists. Each has a specialization describing their domain. Reuse specialists via follow-up before spawning new ones.\n\nAll params are flat (no nested objects). The operation field determines which params apply.\n\nOperations:\n\u2022 delegate \u2014 prompt + specialization required. Optional: description, requestId\n\u2022 follow-up \u2014 prompt + sessionId required. Optional: specialization (to update focus)\n\u2022 check-status \u2014 sessionId required\n\u2022 list \u2014 all params optional: activeOnly, requestId (filter), limit\n\u2022 abort \u2014 sessionId required",schema:r.SpecialistOpsSchema,annotations:{title:"Specialist Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSpecialistOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5802(module){"use strict"
3331
3405
  module.exports=require("@modelcontextprotocol/sdk/server/stdio.js")},5806(e,exports,t){"use strict"
3332
3406
  function r(){const e=n.z.object({requestId:n.z.string(),summary:n.z.string(),acceptanceEvidence:n.z.array(n.z.object({evidence:n.z.string()}))}),t=n.z.object({testRecords:n.z.array(n.z.string()),coverage:n.z.object({criteriaTestedCount:n.z.number(),totalTestCases:n.z.number()}),criterionCoverage:n.z.array(n.z.object({coverage:n.z.enum(["none","partial","full"]),testRecords:n.z.array(n.z.string())}))})
3333
3407
  return(0,o.areTestsRequiredForCompletion)()?e.extend({testVerification:t}):e}Object.defineProperty(exports,"__esModule",{value:!0}),exports.DynamicCompleteRequestSchema=void 0,exports.getDynamicCompleteRequestSchema=r
@@ -3347,64 +3421,65 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
3347
3421
  var t={}
3348
3422
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3349
3423
  return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
3350
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDeleteFiles=async function(e,t,r,n,o,s){const i=n.child({tool:"delete_files"}),m=Date.now()
3351
- let y,w,k=l.FileOperationPhase.VALIDATION
3352
- const b={toolName:"delete-files",operationName:"delete",fileOperationPhase:l.FileOperationPhase.FILE_WRITE,recordType:"delete-files",metricsPrefix:"delete_files",successMessage:"Successfully deleted files",failureMessage:"Failed to delete files"}
3353
- try{const n=r.getTaskClient(),u=r.getToolRecordClient(),I=r.getRequestClient(),v=l.validateArgs(e,c.DeleteFilesSchema),{taskId:C,paths:_,operations:E,comment:q}=v
3354
- let S=[]
3355
- if(_)S=_.map((e=>({type:"file",target:e})))
3356
- else{if(!E)throw Error("Either paths or operations must be specified")
3357
- S=E.map((e=>{if(e.path)return{type:"file",target:e.path}
3424
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDeleteFiles=async function(e,r,n,o,s,i){const m=o.child({tool:"delete_files"}),y=Date.now()
3425
+ let w,k,b=l.FileOperationPhase.VALIDATION
3426
+ const I={toolName:"delete-files",operationName:"delete",fileOperationPhase:l.FileOperationPhase.FILE_WRITE,recordType:"delete-files",metricsPrefix:"delete_files",successMessage:"Successfully deleted files",failureMessage:"Failed to delete files"}
3427
+ try{const u=n.getTaskClient(),v=n.getToolRecordClient(),C=n.getRequestClient(),_=l.validateArgs(e,c.DeleteFilesSchema),{paths:E,operations:q,comment:S}=_,{resolveActiveTaskId:T}=await Promise.resolve().then(t.bind(t,3451)),P=e.taskId||await T(r,n,o)||"untracked"
3428
+ let j=[]
3429
+ if(E)j=E.map((e=>({type:"file",target:e})))
3430
+ else{if(!q)throw Error("Either paths or operations must be specified")
3431
+ j=q.map((e=>{if(e.path)return{type:"file",target:e.path}
3358
3432
  if(e.documentId)return{type:"document",target:e.documentId}
3359
- throw Error("Invalid operation: neither path nor documentId specified")}))}if(0===S.length)throw Error("At least one file or document must be specified for deletion")
3360
- const T=S.filter((e=>"file"===e.type)),P=S.filter((e=>"document"===e.type)),j=S.length
3361
- i.info("Starting mixed file and document deletion operation",{taskId:C,totalOperations:S.length,fileOperations:T.length,documentOperations:P.length,comment:q}),l.validateTaskIdFormat(C,i,o,b.metricsPrefix)
3362
- const R=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
3363
- i.info("Initial branch context",{initialBranch:R.branch,initialRequestId:R.requestId,isMain:R.isMain})
3364
- const M=[]
3365
- for(const e of T){const{normalizedPath:r,fullPath:n}=l.validateAndNormalizePath(e.target,t)
3366
- M.push({normalized:r,full:n})}k=l.FileOperationPhase.TASK_VALIDATION,o.incrementCounter("delete_files_phase",1,{phase:k})
3367
- const x=M.length>0?M[0].normalized:"document_operations",O=await l.validateTaskId(C,x,n,i,o,b.metricsPrefix),D=O?.requestId,$=await l.validateWorkItemStates(C,x,n,I,t,i,o,b.metricsPrefix),A=await l.autoPromoteTaskStatus(C,O.status,D,$.request?.status,x,n,I,i,o,b.metricsPrefix)
3368
- A.taskPromoted&&i.info(`Auto-promoted task ${C} (${O.title||"Untitled"}) to in_progress for mixed operations`,{taskId:C,taskTitle:O.title,previousStatus:O.status,newStatus:A.newTaskStatus,totalOperations:S.length,fileOperations:T.length,documentOperations:P.length}),A.requestPromoted&&i.info(`Auto-promoted request ${D} to in_progress for file operations`,{requestId:D,previousStatus:$.request?.status,newStatus:A.newRequestStatus,triggeringTaskId:C})
3369
- const F=await l.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:D,context:t,operation:"delete-files",logger:i,metrics:o,metricsPrefix:b.metricsPrefix})
3370
- if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
3371
- throw Error(F.error)}let N={hadUserMods:!1,userModsCommitHash:void 0}
3372
- if(t.git)try{i.debug("[DELETE-FILES] Checking for user changes before mixed delete operations")
3373
- const e=await(0,h.commitUserChangesBeforeToolOperation)(t.git,"delete-files",{requestId:D,taskId:C,workspaceManager:t.workspaceManager},i,o)
3374
- e.userChangesCommitted&&(i.debug("[DELETE-FILES] User changes committed before mixed delete operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),i.info("User changes committed before mixed delete-files operation",{taskId:C,totalOperations:S.length,fileOperations:T.length,documentOperations:P.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),N={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){i.debug("[DELETE-FILES] Pre-tool commit failed, continuing with mixed delete operations",{error:e instanceof Error?e.message:e+""}),i.warn("Pre-tool user changes commit failed, continuing with mixed delete operation",{taskId:C,totalOperations:S.length,fileOperations:T.length,documentOperations:P.length,error:e instanceof Error?e.message:e+""})}i.debug("[DELETE-FILES] Proceeding with mixed delete operations",{totalOperations:S.length,fileDeletes:T.length,documentDeletes:P.length}),k=l.FileOperationPhase.RECORD_CREATION,o.incrementCounter("delete_files_phase",1,{phase:k})
3375
- const{toolRecordId:L,localToolRecordId:z}=await l.createFileOperationRecords(C,D,t.projectId,b.recordType,x,{totalOperations:S.length,fileOperations:T.length,documentOperations:P.length,filePaths:M.map((e=>e.normalized)),documentIds:P.map((e=>e.target)),userComment:q,hadUserMods:N.hadUserMods,userModsCommitHash:N.userModsCommitHash},n,u,i,o,b.metricsPrefix,s)
3376
- y=L,w=L,k=b.fileOperationPhase,o.incrementCounter("delete_files_phase",1,{phase:k})
3377
- const H=[]
3378
- let B=0
3379
- P.length>0&&r.setProjectId(t.projectId)
3380
- for(let e=0;e<M.length;e++){const t=M[e],r={type:"file",path:t.normalized,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
3433
+ throw Error("Invalid operation: neither path nor documentId specified")}))}if(0===j.length)throw Error("At least one file or document must be specified for deletion")
3434
+ const R=j.filter((e=>"file"===e.type)),x=j.filter((e=>"document"===e.type)),M=j.length
3435
+ m.info("Starting mixed file and document deletion operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,comment:S}),l.validateTaskIdFormat(P,m,s,I.metricsPrefix)
3436
+ const O=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
3437
+ m.info("Initial branch context",{initialBranch:O.branch,initialRequestId:O.requestId,isMain:O.isMain})
3438
+ const D=[]
3439
+ for(const e of R){const{normalizedPath:t,fullPath:n}=l.validateAndNormalizePath(e.target,r)
3440
+ D.push({normalized:t,full:n})}b=l.FileOperationPhase.TASK_VALIDATION,s.incrementCounter("delete_files_phase",1,{phase:b})
3441
+ const $=D.length>0?D[0].normalized:"document_operations",A=await l.validateTaskId(P,$,u,m,s,I.metricsPrefix),F=A?.requestId,N=await l.validateWorkItemStates(P,$,u,C,r,m,s,I.metricsPrefix),L=await l.autoPromoteTaskStatus(P,A.status,F,N.request?.status,$,u,C,m,s,I.metricsPrefix)
3442
+ L.taskPromoted&&m.info(`Auto-promoted task ${P} (${A.title||"Untitled"}) to in_progress for mixed operations`,{taskId:P,taskTitle:A.title,previousStatus:A.status,newStatus:L.newTaskStatus,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length}),L.requestPromoted&&m.info(`Auto-promoted request ${F} to in_progress for file operations`,{requestId:F,previousStatus:N.request?.status,newStatus:L.newRequestStatus,triggeringTaskId:P})
3443
+ const z=await l.ensureCorrectWorkspaceContext({taskPromoted:L.taskPromoted,requestId:F,context:r,operation:"delete-files",logger:m,metrics:s,metricsPrefix:I.metricsPrefix})
3444
+ if(!z.success){if(z.isLockConflict)return{content:[{type:"text",text:"\u274c "+z.error}],isError:!0}
3445
+ throw Error(z.error)}let H={hadUserMods:!1,userModsCommitHash:void 0}
3446
+ if(r.git)try{m.debug("[DELETE-FILES] Checking for user changes before mixed delete operations")
3447
+ const e=await(0,h.commitUserChangesBeforeToolOperation)(r.git,"delete-files",{requestId:F,taskId:P,workspaceManager:r.workspaceManager},m,s)
3448
+ e.userChangesCommitted&&(m.debug("[DELETE-FILES] User changes committed before mixed delete operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),m.info("User changes committed before mixed delete-files operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),H={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){m.debug("[DELETE-FILES] Pre-tool commit failed, continuing with mixed delete operations",{error:e instanceof Error?e.message:e+""}),m.warn("Pre-tool user changes commit failed, continuing with mixed delete operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,error:e instanceof Error?e.message:e+""})}m.debug("[DELETE-FILES] Proceeding with mixed delete operations",{totalOperations:j.length,fileDeletes:R.length,documentDeletes:x.length}),b=l.FileOperationPhase.RECORD_CREATION,s.incrementCounter("delete_files_phase",1,{phase:b})
3449
+ const{toolRecordId:B,localToolRecordId:U}=await l.createFileOperationRecords(P,F,r.projectId,I.recordType,$,{totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,filePaths:D.map((e=>e.normalized)),documentIds:x.map((e=>e.target)),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},u,v,m,s,I.metricsPrefix,i)
3450
+ w=B,k=B,b=I.fileOperationPhase,s.incrementCounter("delete_files_phase",1,{phase:b})
3451
+ const G=[]
3452
+ let W=0
3453
+ x.length>0&&n.setProjectId(r.projectId)
3454
+ for(let e=0;e<D.length;e++){const t=D[e],r={type:"file",path:t.normalized,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
3381
3455
  try{try{await a.default.access(t.full)}catch(e){throw Error("File not found: "+t.normalized)}if((await a.default.stat(t.full)).isDirectory())throw Error("Cannot 'delete' a directory: "+t.normalized)
3382
- await a.default.unlink(t.full),r.success=!0,B++,i.info("Successfully deleted file",{path:t.normalized})}catch(e){r.error=(0,f.getErrorMessage)(e),i.warn("Failed to delete file "+t.normalized,{error:r.error})}H.push(r)}const U=P.length>0?r.getDocumentClient():null
3383
- for(const e of P){const t=e.target,n={type:"document",documentId:t,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
3456
+ await a.default.unlink(t.full),r.success=!0,W++,m.info("Successfully deleted file",{path:t.normalized})}catch(e){r.error=(0,f.getErrorMessage)(e),m.warn("Failed to delete file "+t.normalized,{error:r.error})}G.push(r)}const V=x.length>0?n.getDocumentClient():null
3457
+ for(const e of x){const t=e.target,r={type:"document",documentId:t,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
3384
3458
  try{let e
3385
- try{if(e=await U.getDocument(t),n.filename=e.filename,i.info("Document found for archival",{documentId:e.id,filename:e.filename,type:e.type,requestId:e.requestId}),e.requestId)try{await(0,g.validateRequestStatusForDocumentOperation)(e.requestId,I,i,o,"delete-document")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
3386
- throw e}try{await(0,p.ensureDocumentNotLocked)(t,r,i,o,"delete-document-archive")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
3387
- throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,f.getErrorMessage)(e)}`)}const s=await U.archiveDocument(t)
3388
- n.success=!0,n.filename=s.filename,B++,i.info("Document archived successfully",{documentId:s.id,filename:s.filename,archivedAt:s.archived_at})}catch(e){n.error=(0,f.getErrorMessage)(e),i.warn("Failed to delete document "+t,{error:n.error})}H.push(n)}const G=Date.now()-m
3389
- o.recordValue("delete_files_time",G),o.incrementCounter("delete_files_operations_total",j),o.incrementCounter("delete_files_operations_success",B),o.incrementCounter("delete_files_operations_failed",j-B),o.incrementCounter("delete_files_file_operations",T.length),o.incrementCounter("delete_files_document_operations",P.length),B===j?o.incrementCounter("delete_files_success",1):B>0?o.incrementCounter("delete_files_partial_success",1):o.incrementCounter("delete_files_total_failure",1)
3390
- let W=null
3391
- if(B>0){k=l.FileOperationPhase.GIT_COMMIT,o.incrementCounter("delete_files_phase",1,{phase:k})
3392
- const e=H.filter((e=>e.success)),r=e.filter((e=>"file"===e.type)).length,n=e.filter((e=>"document"===e.type)).length
3393
- let s
3394
- s=r>0&&n>0?`Delete ${r} files and ${n} documents - ${q}`:r>0?1===r?"Delete file - "+q:`Delete ${r} files - ${q}`:1===n?"Delete document - "+q:`Delete ${n} documents - ${q}`,W=await l.commitToGit(C,x,L,z,s,t,i,o,b.metricsPrefix)}k=l.FileOperationPhase.RECORD_UPDATE_SUCCESS,o.incrementCounter("delete_files_phase",1,{phase:k})
3395
- const V=H.filter((e=>e.success)),J=H.filter((e=>!e.success))
3396
- await l.updateFileOperationRecords(C,y,w,x,b.recordType,B===j?`Successfully deleted all ${j} operations`:`Deleted ${B}/${j} operations successfully`,{status:B===j?"completed":"partial_success",commitHash:W?.commitHash,previousCommitHash:W?.previousCommitHash,totalOperations:j,fileOperations:T.length,documentOperations:P.length,successCount:B,failureCount:j-B,successfulOperations:V.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename}))),failedOperations:J.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,error:e.error}))),userComment:q,hadUserMods:N.hadUserMods,userModsCommitHash:N.userModsCommitHash},B===j?`Successfully deleted all ${j} operations`:`Deleted ${B}/${j} operations successfully`,n,u,i,o,b.metricsPrefix)
3397
- const K=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
3398
- let Y=""
3399
- if(B===j){const e=V.filter((e=>"file"===e.type)).length,t=V.filter((e=>"document"===e.type)).length
3400
- Y=e>0&&t>0?`Successfully deleted ${e} files and ${t} documents`:e>0?`Successfully deleted all ${e} ${1===e?"file":"files"}`:`Successfully archived all ${t} ${1===t?"document":"documents"}`}else Y=B>0?`Successfully deleted ${B}/${j} operations.\n\nFailed operations:\n`+H.filter((e=>!e.success)).map((e=>{const t="file"===e.type?e.path:`${e.filename||e.documentId} (${e.documentId})`
3401
- return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n"):"All delete operations failed:\n"+H.map((e=>{const t="file"===e.type?e.path:`${e.filename||e.documentId} (${e.documentId})`
3459
+ try{if(e=await V.getDocument(t),r.filename=e.filename,m.info("Document found for archival",{documentId:e.id,filename:e.filename,type:e.type,requestId:e.requestId}),e.requestId)try{await(0,g.validateRequestStatusForDocumentOperation)(e.requestId,C,m,s,"delete-document")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
3460
+ throw e}try{await(0,p.ensureDocumentNotLocked)(t,n,m,s,"delete-document-archive")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
3461
+ throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,f.getErrorMessage)(e)}`)}const o=await V.archiveDocument(t)
3462
+ r.success=!0,r.filename=o.filename,W++,m.info("Document archived successfully",{documentId:o.id,filename:o.filename,archivedAt:o.archived_at})}catch(e){r.error=(0,f.getErrorMessage)(e),m.warn("Failed to delete document "+t,{error:r.error})}G.push(r)}const J=Date.now()-y
3463
+ s.recordValue("delete_files_time",J),s.incrementCounter("delete_files_operations_total",M),s.incrementCounter("delete_files_operations_success",W),s.incrementCounter("delete_files_operations_failed",M-W),s.incrementCounter("delete_files_file_operations",R.length),s.incrementCounter("delete_files_document_operations",x.length),W===M?s.incrementCounter("delete_files_success",1):W>0?s.incrementCounter("delete_files_partial_success",1):s.incrementCounter("delete_files_total_failure",1)
3464
+ let K=null
3465
+ if(W>0){b=l.FileOperationPhase.GIT_COMMIT,s.incrementCounter("delete_files_phase",1,{phase:b})
3466
+ const e=G.filter((e=>e.success)),t=e.filter((e=>"file"===e.type)).length,n=e.filter((e=>"document"===e.type)).length
3467
+ let o
3468
+ o=t>0&&n>0?`Delete ${t} files and ${n} documents - ${S}`:t>0?1===t?"Delete file - "+S:`Delete ${t} files - ${S}`:1===n?"Delete document - "+S:`Delete ${n} documents - ${S}`,K=await l.commitToGit(P,$,B,U,o,r,m,s,I.metricsPrefix)}b=l.FileOperationPhase.RECORD_UPDATE_SUCCESS,s.incrementCounter("delete_files_phase",1,{phase:b})
3469
+ const Y=G.filter((e=>e.success)),Q=G.filter((e=>!e.success))
3470
+ await l.updateFileOperationRecords(P,w,k,$,I.recordType,W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,{status:W===M?"completed":"partial_success",commitHash:K?.commitHash,previousCommitHash:K?.previousCommitHash,totalOperations:M,fileOperations:R.length,documentOperations:x.length,successCount:W,failureCount:M-W,successfulOperations:Y.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename}))),failedOperations:Q.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,error:e.error}))),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,u,v,m,s,I.metricsPrefix)
3471
+ const Z=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
3472
+ let X=""
3473
+ if(W===M){const e=Y.filter((e=>"file"===e.type)).length,t=Y.filter((e=>"document"===e.type)).length
3474
+ X=e>0&&t>0?`Successfully deleted ${e} files and ${t} documents`:e>0?`Successfully deleted all ${e} ${1===e?"file":"files"}`:`Successfully archived all ${t} ${1===t?"document":"documents"}`}else X=W>0?`Successfully deleted ${W}/${M} operations.\n\nFailed operations:\n`+G.filter((e=>!e.success)).map((e=>{const t="file"===e.type?e.path:`${e.filename||e.documentId} (${e.documentId})`
3475
+ return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n"):"All delete operations failed:\n"+G.map((e=>{const t="file"===e.type?e.path:`${e.filename||e.documentId} (${e.documentId})`
3402
3476
  return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n")
3403
- return W?.commitHash&&(Y+="\nCommit: "+W.commitHash.substring(0,8)),K.requestId&&(Y+="\nBranch: "+K.requestId),F.lockAcquired&&F.lockedRequestId&&(Y+="\n\u{1f512} **Locked request:** "+F.lockedRequestId),{content:[{type:"text",text:Y}],isError:0===B}}catch(n){if(e.taskId&&r)try{const o=r.getToolRecordClient(),s=n instanceof d.NotFoundError||n instanceof d.ValidationError||n instanceof u.ZodError
3404
- await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:t.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,f.getErrorMessage)(n),errorDetails:n instanceof Error?n.stack:n+"",phase:k,attemptedTaskId:e.taskId,taskIdValidationFailed:s},note:"Failed to delete files - "+(0,f.getErrorMessage)(n)})}catch(t){i.error("Failed to create failure record for delete-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0})}const s=Date.now()-m
3405
- if(o.recordValue("delete_files_time",s),o.incrementCounter("delete_files_errors",1),i.error("Error in delete-files operation:",{error:(0,f.getErrorMessage)(n),time:s}),(y||w)&&e.taskId){k=l.FileOperationPhase.RECORD_UPDATE_FAILURE
3406
- try{const t=r.getTaskClient(),s=r.getToolRecordClient()
3407
- await l.updateFileOperationRecords(e.taskId,y,w,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",b.recordType,"Failed to delete operations",{status:"failed",error:(0,f.getErrorMessage)(n),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment},"Failed to delete operations",t,s,i,o,b.metricsPrefix)}catch(t){i.error("Failed to update record with failure status",{taskId:e.taskId,recordId:y,error:t instanceof Error?t.message:t+""})}}return l.handleFileOperationError(n,k,i,o,e,b)}}
3477
+ if(K?.commitHash&&(X+="\nCommit: "+K.commitHash.substring(0,8)),Z.requestId&&(X+="\nBranch: "+Z.requestId),z.lockAcquired&&z.lockedRequestId){const e=r.workspaceManager?.getCurrentContext(r.currentSessionId)
3478
+ e?.permanentBranch||(X+="\n\u{1f512} **Locked request:** "+z.lockedRequestId)}return{content:[{type:"text",text:X}],isError:0===W}}catch(t){if(e.taskId&&n)try{const o=n.getToolRecordClient(),s=t instanceof d.NotFoundError||t instanceof d.ValidationError||t instanceof u.ZodError
3479
+ await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:r.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,f.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:s},note:"Failed to delete files - "+(0,f.getErrorMessage)(t)})}catch(t){m.error("Failed to create failure record for delete-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0})}const o=Date.now()-y
3480
+ if(s.recordValue("delete_files_time",o),s.incrementCounter("delete_files_errors",1),m.error("Error in delete-files operation:",{error:(0,f.getErrorMessage)(t),time:o}),(w||k)&&e.taskId){b=l.FileOperationPhase.RECORD_UPDATE_FAILURE
3481
+ try{const r=n.getTaskClient(),o=n.getToolRecordClient()
3482
+ await l.updateFileOperationRecords(e.taskId,w,k,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",I.recordType,"Failed to delete operations",{status:"failed",error:(0,f.getErrorMessage)(t),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment},"Failed to delete operations",r,o,m,s,I.metricsPrefix)}catch(t){m.error("Failed to update record with failure status",{taskId:e.taskId,recordId:w,error:t instanceof Error?t.message:t+""})}}return l.handleFileOperationError(t,b,m,s,e,I)}}
3408
3483
  const a=i(t(1943)),c=t(6183),l=s(t(5967)),d=t(9860),u=t(1569),h=t(7478),g=t(5003),p=t(9949),f=t(8824)},5997(e,exports,t){"use strict"
3409
3484
  var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
3410
3485
  var o=Object.getOwnPropertyDescriptor(t,r)
@@ -3414,13 +3489,16 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
3414
3489
  var t={}
3415
3490
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3416
3491
  return o(t,e),t})
3417
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.DebugMultiAgentTool=void 0,exports.handleDebugMultiAgentStatus=async function(e,r,n){try{const e={environmentVariables:{MULTI_AGENT_MODE:"always enabled",ALCHEMY_LOCK_TIMEOUT:process.env.ALCHEMY_LOCK_TIMEOUT},workspaceManager:{available:!!r.workspaceManager,currentContext:r.workspaceManager?.getCurrentContext()||null,activeWorkspaces:r.workspaceManager?.listActiveWorkspaces()||[]},basePath:r.basePath,alchemyPath:a.join(r.basePath,c.ALCHEMY_DIR_NAME),multiAgentMode:!0,fileSystemChecks:{}},n=a.join(r.basePath,c.ALCHEMY_DIR_NAME),o=a.join(n,"worktrees")
3492
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.DebugMultiAgentTool=void 0,exports.handleDebugMultiAgentStatus=async function(e,r,n){try{const e={environmentVariables:{MULTI_AGENT_MODE:"always enabled",ALCHEMY_LOCK_TIMEOUT:process.env.ALCHEMY_LOCK_TIMEOUT},workspaceManager:{available:!!r.workspaceManager,currentContext:r.workspaceManager?.getCurrentContext(r.currentSessionId)||null,activeWorkspaces:r.workspaceManager?.listActiveWorkspaces()||[]},basePath:r.basePath,alchemyPath:a.join(r.basePath,c.ALCHEMY_DIR_NAME),multiAgentMode:!0,fileSystemChecks:{}},n=a.join(r.basePath,c.ALCHEMY_DIR_NAME),o=a.join(n,"worktrees")
3418
3493
  if(e.fileSystemChecks={alchemyLabExists:i.existsSync(n),worktreeBaseExists:i.existsSync(o),worktreeContents:[]},e.fileSystemChecks.worktreeBaseExists)try{const t=i.readdirSync(o)
3419
3494
  e.fileSystemChecks.worktreeContents=t}catch(t){e.fileSystemChecks.worktreeReadError=(0,l.getErrorMessage)(t)}try{const t=r.workspaceManager.listActiveWorkspaces()
3420
3495
  e.activeWorkspaces=t}catch(t){e.workspaceManagerError=(0,l.getErrorMessage)(t)}try{const n=t(3807)(r.basePath),o=await n.status()
3421
3496
  e.gitStatus={current:o.current,tracking:o.tracking,ahead:o.ahead,behind:o.behind,files:o.files.length}}catch(t){e.gitError=(0,l.getErrorMessage)(t)}return JSON.stringify(e,null,2)}catch(e){return n.error("Error in debug_multi_agent_status",{error:(0,l.getErrorMessage)(e)}),"Error generating debug information: "+(0,l.getErrorMessage)(e)}}
3422
3497
  const i=s(t(9896)),a=s(t(6928)),c=t(4139),l=t(8824)
3423
- exports.DebugMultiAgentTool={name:"debug_multi_agent_status",description:"Check multi-agent mode status, worktree state, and configuration for debugging",inputSchema:{type:"object",properties:{},required:[]}}},6111(e,exports,t){"use strict"
3498
+ exports.DebugMultiAgentTool={name:"debug_multi_agent_status",description:"Check multi-agent mode status, worktree state, and configuration for debugging",inputSchema:{type:"object",properties:{},required:[]}}},6064(e,exports,t){"use strict"
3499
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=exports.TasksSchema=void 0
3500
+ const r=t(1569),n=t(7561)
3501
+ exports.TasksSchema=r.z.object({operation:r.z.enum(["create","done","list"]).describe("Operation to perform:\n\u2022 create - Create a new task (requestId auto-resolved from session)\n\u2022 done - Complete the active (in_progress) task with a summary\n\u2022 list - List tasks for the current request"),title:r.z.string().optional().describe("Task title (required for create)"),description:r.z.string().optional().describe("Task description (required for create)"),summary:r.z.string().optional().describe("Completion summary (required for done)")}),exports.def={name:"subtasks",description:"Manage subtasks for your current request.\n\n\u2022 create { title, description } \u2014 creates a task. First task auto-starts.\n\u2022 done { summary } \u2014 completes the active task. Next pending task auto-starts.\n\u2022 list \u2014 shows all tasks and their status.\n\nNo requestId or taskId needed \u2014 resolved automatically from your session.",schema:exports.TasksSchema,annotations:{title:"Tasks",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleTasks)(e,t.context,t.apiClient,t.logger,t.metrics,t.cliOrigin)}}},6111(e,exports,t){"use strict"
3424
3502
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3425
3503
  const r=t(6183),n=t(5434)
3426
3504
  exports.def={name:"get_request_information",description:"Get comprehensive request information",schema:r.GetRequestInformationSchema,annotations:{title:"Get Request Information",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleGetRequestInformation)(e,t.context,t.apiClient,t.logger,t.metrics)}}},6153(e,exports,t){"use strict"
@@ -3467,22 +3545,18 @@ const n=await this.requestWithRetry("POST","/api/files/recover",t)
3467
3545
  if(!(0,i.safeGetResponseData)(n,null))throw new r.ServiceError("Empty response when recovering file")
3468
3546
  const o=(0,i.safeGetResponseData)(n,{success:!0,path:e.path,commitHash:e.commitHash,backupPath:void 0})
3469
3547
  return this.logger.info("Successfully recovered file "+e.path,{path:o.path,commitHash:o.commitHash,backupPath:o.backupPath}),o}catch(t){throw this.logger.error("Failed to recover file "+e.path,{path:e.path,commitHash:e.commitHash,error:t instanceof Error?t.stack:t+""}),t}}}exports.FileOperationsClient=a},6183(e,exports,t){"use strict"
3470
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranchSchema=exports.PlanWriteSchema=exports.PlanReadSchema=exports.DocumentOperationsSchema=exports.SearchDocumentsSchema=exports.CreateDocumentSchema=exports.ReplaceLinesSchema=exports.InsertLinesSchema=exports.SwitchToRequestBranchSchema=exports.PlannerOpsSchema=exports.SpecialistOpsSchema=exports.SubagentOperationsSchema=exports.TaskOperationsSchema=exports.CompleteTaskSchema=exports.GetTaskInformationSchema=exports.GetRequestInformationSchema=exports.ListRequestsSchema=exports.ListTasksSchema=exports.SearchSchema=exports.QueryHistorySchema=exports.FileRecoverSchema=exports.FileHistorySchema=exports.DeleteFilesSchema=exports.DeleteFileSchema=exports.ReplaceInFilesSchema=exports.ReplaceStringsSchema=exports.ReplaceStringSchema=exports.MoveFilesSchema=exports.CreateDirectorySchema=exports.GetFileInfoSchema=exports.ListDirectorySchema=exports.ReadFilesSchema=exports.ViewAssetSchema=exports.WriteFileSchema=exports.UpdateTaskStatusSchema=exports.CreateTaskSchema=exports.CreateRequestSchema=exports.CompleteRequestSchema=exports.ExecutedTestSchema=exports.TestVerificationSchema=exports.TestDefinitionSchema=exports.AcceptanceCriterionSchema=exports.RecordTypeEnum=exports.EvidenceTypeEnum=exports.CriterionStatusEnum=exports.RequestStatusEnum=exports.TaskStatusEnum=exports.RequestTypeEnum=exports.TestCoverageTypeEnum=exports.CompletionStatusEnum=void 0,exports.UpdateSpecializationSchema=exports.SessionMessageOperationsSchema=exports.ReportTestResultsSchema=exports.ExecuteTestCommandSchema=exports.TestingReferenceSchema=exports.TestingProcessUpdateSchema=exports.TestingProcessCreateSchema=exports.TestingProcessGetSchema=exports.TestingProcessListSchema=exports.MetaReferenceSchema=exports.MetaAgentListSchema=exports.MetaWorkflowRemoveRecipeSchema=exports.MetaWorkflowAddRecipeSchema=exports.MetaHookCreateSchema=exports.MetaHookListSchema=exports.MetaRecipeRemoveHookSchema=exports.MetaRecipeAddHookSchema=exports.MetaRecipeCreateSchema=exports.MetaRecipeGetSchema=exports.MetaRecipeListSchema=exports.MetaWorkflowUpdateSchema=exports.MetaWorkflowCreateSchema=exports.MetaWorkflowGetSchema=exports.MetaWorkflowListSchema=exports.GenerateRequestJournalSchema=exports.QuickManageSchema=exports.QuickReplaceSchema=exports.QuickWriteSchema=exports.RequestOperationsSchema=exports.ManageFilesSchema=exports.ModifyFileSchema=exports.RevertRequestSchema=exports.SwitchToBranchSchema=void 0
3471
- const r=t(1569),n=t(8955),o=r.z.string().refine((e=>!!e&&/^tas\d{6}$/.test(e)),{message:"Task ID must match format: tas###### (e.g. tas000001). If you don't have a task yet, create one first using task_operations with operation 'create'."}),s=r.z.string().refine((e=>!!e&&/^req\d{6}$/.test(e)),{message:"Request ID must match format: req###### (e.g. req000001)"}),i=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^(doc|plan|jour)\d{6}$/.test(e))),{message:"Document ID must match format: doc_[26 alphanumeric] (ULID) or doc######/plan######/jour###### (local ID)"})
3472
- exports.CompletionStatusEnum=r.z.enum(["complete","incomplete","partial"]),exports.TestCoverageTypeEnum=r.z.enum(["unit","e2e","integration","manual"]),exports.RequestTypeEnum=r.z.enum(["feature","bugfix","quick-edit"]),exports.TaskStatusEnum=r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]),exports.RequestStatusEnum=r.z.enum(["open","in_progress","ready_for_review","ready_for_merge","completed","canceled","reverted","conflicted"]),exports.CriterionStatusEnum=r.z.enum(["unverified","verified"]),exports.EvidenceTypeEnum=r.z.enum(["test","manual","other"]),exports.RecordTypeEnum=r.z.enum(["write","modify","blocker","resolution","discovery","test","delete"]),exports.AcceptanceCriterionSchema=r.z.object({description:r.z.string(),status:r.z.enum(["unverified","verified"]).default("unverified"),evidence:r.z.string().nullable().optional(),evidenceType:r.z.enum(["test","manual","other"]).nullable().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.TestDefinitionSchema=r.z.object({id:r.z.string(),description:r.z.string(),status:exports.CompletionStatusEnum,coverageType:exports.TestCoverageTypeEnum,accepts:r.z.array(r.z.string())}),exports.TestVerificationSchema=r.z.object({criteria:r.z.array(r.z.string()),tests:r.z.array(r.z.string()),coverageType:exports.TestCoverageTypeEnum,coverageRatio:r.z.number(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.ExecutedTestSchema=r.z.object({id:r.z.string(),testId:r.z.string(),status:exports.CompletionStatusEnum,results:r.z.string(),coverage:r.z.array(r.z.string()),executedAt:r.z.string()}),exports.CompleteRequestSchema=r.z.object({status:exports.RequestStatusEnum,acceptanceCriteria:r.z.array(exports.AcceptanceCriterionSchema),testVerification:exports.TestVerificationSchema.optional(),completionSummary:r.z.string().optional()}),exports.CreateRequestSchema=r.z.object({title:r.z.string(),type:r.z.enum(["feature","bugfix"]),description:r.z.string(),acceptanceCriteria:r.z.array(r.z.string()),planDocumentId:r.z.string().optional()}),exports.CreateTaskSchema=r.z.object({requestId:s,title:r.z.string(),description:r.z.string()}),exports.UpdateTaskStatusSchema=r.z.object({taskId:o,status:exports.TaskStatusEnum,note:r.z.string()}),exports.WriteFileSchema=r.z.object({taskId:o,path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional(),comment:r.z.string()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}),exports.ViewAssetSchema=r.z.object({filename:r.z.string().describe("The asset filename (e.g., 01JMXYZ.png)")}),exports.ReadFilesSchema=r.z.object({paths:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),lines:r.z.string().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),encoding:r.z.enum(["utf8","utf-8","ascii","binary"]).optional()}),exports.ListDirectorySchema=r.z.object({path:r.z.string(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}),exports.GetFileInfoSchema=r.z.object({path:r.z.string()}),exports.CreateDirectorySchema=r.z.object({path:r.z.string(),taskId:o,comment:r.z.string().optional()}),exports.MoveFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()})),comment:r.z.string()}),exports.ReplaceStringSchema=r.z.object({taskId:o,path:r.z.string(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional(),comment:r.z.string()}),exports.ReplaceStringsSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceInFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1,"old string cannot be empty"),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1,"At least one replacement required"),fuzzy_match:r.z.boolean().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"Either path or documentId is required, but not both"})).min(1,"At least one operation required"),fuzzy_match:r.z.boolean().optional().default(!0),comment:r.z.string()}),exports.DeleteFileSchema=r.z.object({taskId:o,path:r.z.string(),comment:r.z.string()}),exports.DeleteFilesSchema=r.z.object({taskId:o,paths:r.z.array(r.z.string()).optional(),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})).optional(),comment:r.z.string()}).refine((e=>e.paths&&!e.operations||!e.paths&&e.operations),{message:"paths or operations required"}).refine((e=>e.paths?.length||e.operations?.length),{message:"path/operation required"}),exports.FileHistorySchema=r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}),exports.FileRecoverSchema=r.z.object({taskId:o,path:r.z.string(),commitHash:r.z.string(),createBackup:r.z.boolean().default(!0)}),exports.QueryHistorySchema=r.z.object({queryType:r.z.enum(["file-history","request-file-history","recover","blame"],{errorMap(){return{message:"Invalid queryType. Valid options: file-history, request-file-history, recover, blame"}}}),fileHistory:r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}).optional(),requestHistory:r.z.object({requestId:s,detailLevel:r.z.enum(["summary","detailed"]).default("summary"),taskId:o.optional(),showDiff:r.z.boolean().optional(),fileFilter:r.z.string().optional()}).optional(),recover:r.z.object({taskId:o,path:r.z.string(),commitHash:r.z.string().optional(),createBackup:r.z.boolean().default(!0)}).optional(),blame:r.z.object({path:r.z.string(),lines:r.z.string().optional(),branch:r.z.string().optional()}).optional()}).refine((e=>"file-history"===e.queryType?e.fileHistory&&!e.requestHistory&&!e.recover:"request-file-history"===e.queryType?e.requestHistory&&!e.fileHistory&&!e.recover:"recover"===e.queryType?e.recover&&!e.fileHistory&&!e.requestHistory&&!e.blame:"blame"===e.queryType&&e.blame&&!e.fileHistory&&!e.requestHistory&&!e.recover),{message:"Invalid query data"}),exports.SearchSchema=r.z.object({needle:r.z.string().optional(),directory:r.z.string().optional(),options:r.z.object({caseSensitive:r.z.boolean().optional(),fileExtension:r.z.string().optional(),maxResults:r.z.number().optional(),useRegex:r.z.boolean().optional(),searchIn:r.z.enum(["content","filename","both"]).default("content").optional(),contextLines:r.z.number().min(0).max(10).optional(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}).optional()}),exports.ListTasksSchema=r.z.object({requestId:s,filters:r.z.object({status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.ListRequestsSchema=r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["open","in_progress","ready_for_review","completed","canceled"]).optional(),planDocumentId:r.z.string().optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.GetRequestInformationSchema=r.z.object({requestId:s}),exports.GetTaskInformationSchema=r.z.object({taskId:o}),exports.CompleteTaskSchema=r.z.object({taskId:o,summary:r.z.string()}),exports.TaskOperationsSchema=r.z.object({operation:r.z.enum(["get-info","list"]),taskId:o.optional(),requestId:s.optional(),status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).superRefine(((e,t)=>{"get-info"!==e.operation||e.taskId||t.addIssue({code:"custom",message:'taskId is required for get-info. Example: { "operation": "get-info", "taskId": "tas000001" }'}),"list"!==e.operation||e.requestId||t.addIssue({code:"custom",message:'requestId is required for list. Example: { "operation": "list", "requestId": "req000001" }'})}))
3548
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranchSchema=exports.PlanWriteSchema=exports.PlanReadSchema=exports.DocumentOperationsSchema=exports.SearchDocumentsSchema=exports.CreateDocumentSchema=exports.ReplaceLinesSchema=exports.InsertLinesSchema=exports.SwitchToRequestBranchSchema=exports.PlannerOpsSchema=exports.SpecialistOpsSchema=exports.SubagentOperationsSchema=exports.TaskOperationsSchema=exports.CompleteTaskSchema=exports.GetTaskInformationSchema=exports.GetRequestInformationSchema=exports.ListRequestsSchema=exports.ListTasksSchema=exports.SearchSchema=exports.QueryHistorySchema=exports.FileRecoverSchema=exports.FileHistorySchema=exports.DeleteFilesSchema=exports.DeleteFileSchema=exports.ReplaceInFilesSchema=exports.ReplaceStringsSchema=exports.ReplaceStringSchema=exports.MoveFilesSchema=exports.CreateDirectorySchema=exports.GetFileInfoSchema=exports.ListDirectorySchema=exports.ReadFilesSchema=exports.ViewAssetSchema=exports.WriteFileSchema=exports.UpdateTaskStatusSchema=exports.CreateTaskSchema=exports.CreateRequestSchema=exports.CompleteRequestSchema=exports.ExecutedTestSchema=exports.TestVerificationSchema=exports.TestDefinitionSchema=exports.AcceptanceCriterionSchema=exports.RecordTypeEnum=exports.EvidenceTypeEnum=exports.CriterionStatusEnum=exports.RequestStatusEnum=exports.TaskStatusEnum=exports.RequestTypeEnum=exports.TestCoverageTypeEnum=exports.CompletionStatusEnum=void 0,exports.UpdateSpecializationSchema=exports.SessionMessageOperationsSchema=exports.ReportTestResultsSchema=exports.CommandsSchema=exports.ExecuteTestCommandSchema=exports.TestingReferenceSchema=exports.TestingProcessUpdateSchema=exports.TestingProcessCreateSchema=exports.TestingProcessGetSchema=exports.TestingProcessListSchema=exports.MetaReferenceSchema=exports.MetaAgentListSchema=exports.MetaWorkflowRemoveRecipeSchema=exports.MetaWorkflowAddRecipeSchema=exports.MetaHookCreateSchema=exports.MetaHookListSchema=exports.MetaRecipeRemoveHookSchema=exports.MetaRecipeAddHookSchema=exports.MetaRecipeCreateSchema=exports.MetaRecipeGetSchema=exports.MetaRecipeListSchema=exports.MetaWorkflowUpdateSchema=exports.MetaWorkflowCreateSchema=exports.MetaWorkflowGetSchema=exports.MetaWorkflowListSchema=exports.GenerateRequestJournalSchema=exports.QuickManageSchema=exports.QuickReplaceSchema=exports.QuickWriteSchema=exports.RequestOperationsSchema=exports.ManageFilesSchema=exports.ModifyFileSchema=exports.RevertRequestSchema=exports.SwitchToBranchSchema=void 0
3549
+ const r=t(1569),n=t(8955),o=r.z.string().refine((e=>!(!e||!/^tas\d{6}$/.test(e)&&!/^req\d{6}#\d+$/.test(e))),{message:"Task ID must be req######+#NN (e.g. req000005#03) or tas###### format (e.g. tas000001)."}),s=r.z.string().refine((e=>!!e&&/^req\d{6}$/.test(e)),{message:"Request ID must match format: req###### (e.g. req000001)"}),i=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^(doc|plan|jour)\d{6}$/.test(e))),{message:"Document ID must match format: doc_[26 alphanumeric] (ULID) or doc######/plan######/jour###### (local ID)"})
3550
+ exports.CompletionStatusEnum=r.z.enum(["complete","incomplete","partial"]),exports.TestCoverageTypeEnum=r.z.enum(["unit","e2e","integration","manual"]),exports.RequestTypeEnum=r.z.enum(["feature","bugfix","quick-edit"]),exports.TaskStatusEnum=r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]),exports.RequestStatusEnum=r.z.enum(["open","in_progress","ready_for_review","ready_for_merge","completed","canceled","reverted","conflicted"]),exports.CriterionStatusEnum=r.z.enum(["unverified","verified"]),exports.EvidenceTypeEnum=r.z.enum(["test","manual","other"]),exports.RecordTypeEnum=r.z.enum(["write","modify","blocker","resolution","discovery","test","delete"]),exports.AcceptanceCriterionSchema=r.z.object({description:r.z.string(),status:r.z.enum(["unverified","verified"]).default("unverified"),evidence:r.z.string().nullable().optional(),evidenceType:r.z.enum(["test","manual","other"]).nullable().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.TestDefinitionSchema=r.z.object({id:r.z.string(),description:r.z.string(),status:exports.CompletionStatusEnum,coverageType:exports.TestCoverageTypeEnum,accepts:r.z.array(r.z.string())}),exports.TestVerificationSchema=r.z.object({criteria:r.z.array(r.z.string()),tests:r.z.array(r.z.string()),coverageType:exports.TestCoverageTypeEnum,coverageRatio:r.z.number(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.ExecutedTestSchema=r.z.object({id:r.z.string(),testId:r.z.string(),status:exports.CompletionStatusEnum,results:r.z.string(),coverage:r.z.array(r.z.string()),executedAt:r.z.string()}),exports.CompleteRequestSchema=r.z.object({status:exports.RequestStatusEnum,acceptanceCriteria:r.z.array(exports.AcceptanceCriterionSchema),testVerification:exports.TestVerificationSchema.optional(),completionSummary:r.z.string().optional()}),exports.CreateRequestSchema=r.z.object({title:r.z.string(),type:r.z.enum(["feature","bugfix"]),description:r.z.string(),acceptanceCriteria:r.z.array(r.z.string()),planDocumentId:r.z.string().optional()}),exports.CreateTaskSchema=r.z.object({requestId:s,title:r.z.string(),description:r.z.string()}),exports.UpdateTaskStatusSchema=r.z.object({taskId:o,status:exports.TaskStatusEnum,note:r.z.string()}),exports.WriteFileSchema=r.z.object({path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional(),comment:r.z.string()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}),exports.ViewAssetSchema=r.z.object({filename:r.z.string().describe("The asset filename (e.g., 01JMXYZ.png)")}),exports.ReadFilesSchema=r.z.object({paths:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),lines:r.z.string().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),encoding:r.z.enum(["utf8","utf-8","ascii","binary"]).optional()}),exports.ListDirectorySchema=r.z.object({path:r.z.string(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}),exports.GetFileInfoSchema=r.z.object({path:r.z.string()}),exports.CreateDirectorySchema=r.z.object({path:r.z.string(),comment:r.z.string().optional()}),exports.MoveFilesSchema=r.z.object({operations:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()})),comment:r.z.string()}),exports.ReplaceStringSchema=r.z.object({path:r.z.string(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional(),comment:r.z.string()}),exports.ReplaceStringsSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceInFilesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1,"old string cannot be empty"),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1,"At least one replacement required"),fuzzy_match:r.z.boolean().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"Either path or documentId is required, but not both"})).min(1,"At least one operation required"),fuzzy_match:r.z.boolean().optional().default(!0),comment:r.z.string()}),exports.DeleteFileSchema=r.z.object({path:r.z.string(),comment:r.z.string()}),exports.DeleteFilesSchema=r.z.object({paths:r.z.array(r.z.string()).optional(),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})).optional(),comment:r.z.string()}).refine((e=>e.paths&&!e.operations||!e.paths&&e.operations),{message:"paths or operations required"}).refine((e=>e.paths?.length||e.operations?.length),{message:"path/operation required"}),exports.FileHistorySchema=r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}),exports.FileRecoverSchema=r.z.object({path:r.z.string(),commitHash:r.z.string(),createBackup:r.z.boolean().default(!0)}),exports.QueryHistorySchema=r.z.object({queryType:r.z.enum(["file-history","request-file-history","recover","blame"],{errorMap(){return{message:"Invalid queryType. Valid options: file-history, request-file-history, recover, blame"}}}),fileHistory:r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}).optional(),requestHistory:r.z.object({requestId:s,detailLevel:r.z.enum(["summary","detailed"]).default("summary"),taskId:o.optional(),showDiff:r.z.boolean().optional(),fileFilter:r.z.string().optional()}).optional(),recover:r.z.object({path:r.z.string(),commitHash:r.z.string().optional(),createBackup:r.z.boolean().default(!0)}).optional(),blame:r.z.object({path:r.z.string(),lines:r.z.string().optional(),branch:r.z.string().optional()}).optional()}).refine((e=>"file-history"===e.queryType?e.fileHistory&&!e.requestHistory&&!e.recover:"request-file-history"===e.queryType?e.requestHistory&&!e.fileHistory&&!e.recover:"recover"===e.queryType?e.recover&&!e.fileHistory&&!e.requestHistory&&!e.blame:"blame"===e.queryType&&e.blame&&!e.fileHistory&&!e.requestHistory&&!e.recover),{message:"Invalid query data"}),exports.SearchSchema=r.z.object({needle:r.z.string().optional(),directory:r.z.string().optional(),options:r.z.object({caseSensitive:r.z.boolean().optional(),fileExtension:r.z.string().optional(),maxResults:r.z.number().optional(),useRegex:r.z.boolean().optional(),searchIn:r.z.enum(["content","filename","both"]).default("content").optional(),contextLines:r.z.number().min(0).max(10).optional(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}).optional()}),exports.ListTasksSchema=r.z.object({requestId:s,filters:r.z.object({status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.ListRequestsSchema=r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["open","in_progress","ready_for_review","completed","canceled"]).optional(),planDocumentId:r.z.string().optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.GetRequestInformationSchema=r.z.object({requestId:s}),exports.GetTaskInformationSchema=r.z.object({taskId:o}),exports.CompleteTaskSchema=r.z.object({taskId:o,summary:r.z.string()}),exports.TaskOperationsSchema=r.z.object({operation:r.z.enum(["create","complete","get-info","list"]),taskId:o.optional(),requestId:s.optional(),title:r.z.string().optional(),description:r.z.string().optional(),summary:r.z.string().optional(),status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).superRefine(((e,t)=>{"create"!==e.operation||e.requestId||t.addIssue({code:"custom",message:'requestId is required for create. Example: { "operation": "create", "requestId": "req000001", "title": "...", "description": "..." }'}),"create"!==e.operation||e.title||t.addIssue({code:"custom",message:"title is required for create."}),"create"!==e.operation||e.description||t.addIssue({code:"custom",message:"description is required for create."}),"complete"!==e.operation||e.taskId||t.addIssue({code:"custom",message:'taskId is required for complete. Example: { "operation": "complete", "taskId": "req000001#01", "summary": "..." }'}),"complete"!==e.operation||e.summary||t.addIssue({code:"custom",message:"summary is required for complete."}),"get-info"!==e.operation||e.taskId||t.addIssue({code:"custom",message:'taskId is required for get-info. Example: { "operation": "get-info", "taskId": "req000001#01" }'}),"list"!==e.operation||e.requestId||t.addIssue({code:"custom",message:'requestId is required for list. Example: { "operation": "list", "requestId": "req000001" }'})}))
3473
3551
  const a=r.z.string().min(1).describe("OpenCode session ID")
3474
- exports.SubagentOperationsSchema=r.z.object({sessionId:a.optional(),operation:r.z.enum(["spawn","continue","check-status","abort","read-messages","list-sessions"]),spawn:r.z.object({agent:r.z.string().default("work").refine((e=>(0,n.isValidAgent)(e)),{message:"Invalid agent. Check tool description for available agents."}).describe("The subagent type to spawn (see tool description for available agents)"),prompt:r.z.string().min(1).describe("The task/prompt for the subagent to work on"),description:r.z.string().max(60).describe('Brief label for the UI, e.g. "Plan auth refactor" (max 60 chars)'),requestId:r.z.string().regex(/^req\d{6}$/).optional().describe("Optional request ID to associate with the work"),allowParallel:r.z.boolean().default(!1).optional().describe("Allow spawning even if request already has active workers (default: false, will block)"),useExistingSession:r.z.string().optional().describe("Optional existing session ID to send prompt to instead of creating new session")}).optional(),continue:r.z.object({prompt:r.z.string().min(1).describe("New instructions/feedback to send to the subagent")}).optional(),readMessages:r.z.object({limit:r.z.number().min(1).max(50).default(1).describe("Number of recent messages to fetch (default 10, max 50)")}).optional(),listSessions:r.z.object({activeOnly:r.z.boolean().default(!1).describe("Only show sessions that are currently active/busy"),requestId:r.z.string().optional().describe("Find sessions that worked on a specific request"),limit:r.z.number().min(1).max(100).optional().describe("Only show N most recent sessions"),minTokens:r.z.number().min(0).optional().describe("Only show sessions with at least this many tokens"),maxTokens:r.z.number().min(0).optional().describe("Only show sessions with at most this many tokens"),maxAgeHours:r.z.number().min(0).optional().describe("Only show sessions newer than X hours")}).optional()}).refine((e=>{const t=!!e.sessionId,r=!!e.spawn,n=!!e.continue,o=!!e.readMessages
3475
- return"spawn"===e.operation?r&&!n&&!o:"continue"===e.operation?n&&!r&&!o&&t:"check-status"===e.operation||"abort"===e.operation?!r&&!n&&!o&&t:"read-messages"===e.operation?!r&&!n&&t:"list-sessions"===e.operation&&!(r||n||o||t)}),{message:"Invalid operation data: spawn requires spawn object, continue/check-status/abort/read-messages require sessionId"}),exports.SpecialistOpsSchema=r.z.object({operation:r.z.enum(["delegate","follow-up","check-status","list","abort"]),sessionId:a.optional(),delegate:r.z.object({prompt:r.z.string().min(1).describe("Detailed instructions for the specialist"),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars)"),requestId:r.z.string().regex(/^req\d{6}$/).describe("Request ID to associate with the work").optional(),specialization:r.z.string().max(500).describe('Domain description for the specialist (e.g. "Frontend UI components", "Database migrations")')}).optional(),followUp:r.z.object({prompt:r.z.string().min(1).describe("Follow-up instructions or feedback for the specialist"),specialization:r.z.string().max(500).describe("Update the specialist's domain description if their focus has shifted").optional()}).optional(),list:r.z.object({activeOnly:r.z.boolean().default(!1).describe("Only show active/busy specialists"),requestId:r.z.string().optional().describe("Filter to specialists working on a specific request"),limit:r.z.number().min(1).max(100).optional().describe("Max sessions to return")}).optional()}).refine((e=>{const t=!!e.sessionId,r=!!e.delegate,n=!!e.followUp
3476
- return"delegate"===e.operation?r&&!n&&!t:"follow-up"===e.operation?n&&!r&&t:"check-status"===e.operation||"abort"===e.operation?!r&&!n&&t:"list"===e.operation&&!r&&!n&&!t}),{message:"Invalid operation data: delegate requires delegate object, follow-up/check-status/abort require sessionId"}),exports.PlannerOpsSchema=r.z.object({operation:r.z.enum(["request","check-status","list"]),request:r.z.object({prompt:r.z.string().min(1).describe("What to plan \u2014 feature description, architecture question, etc."),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars)")}).optional(),sessionId:a.optional(),list:r.z.object({activeOnly:r.z.boolean().default(!1).describe("Only show active/busy planning sessions"),limit:r.z.number().min(1).max(100).optional().describe("Max sessions to return")}).optional()}).refine((e=>{const t=!!e.request,r=!!e.sessionId
3477
- return"request"===e.operation?t&&!r:"check-status"===e.operation?!t&&r:"list"===e.operation&&!t&&!r}),{message:"Invalid operation data: request requires request object, check-status requires sessionId"}),exports.SwitchToRequestBranchSchema=r.z.object({requestId:s}),exports.InsertLinesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceLinesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.CreateDocumentSchema=r.z.object({requestId:s.optional(),filename:r.z.string().refine((e=>e.toLowerCase().endsWith(".md")),{message:"Filename must end with .md extension"}),content:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"],{errorMap(){return{message:"Document type must be one of: Report, Documentation, Plan, Other"}}}),comment:r.z.string()}),exports.SearchDocumentsSchema=r.z.object({query:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),requestId:s.optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both")}),exports.DocumentOperationsSchema=r.z.object({operation:r.z.enum(["create","search","create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"]),documentId:i.optional(),requestId:s.optional(),filename:r.z.string().optional(),content:r.z.string().optional(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),comment:r.z.string().optional(),query:r.z.string().optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional(),selectedText:r.z.string().optional(),prefixContext:r.z.string().optional(),suffixContext:r.z.string().optional(),lineHint:r.z.number().int().optional(),body:r.z.string().optional(),annotationId:r.z.string().optional()}).superRefine(((e,t)=>{const r=e.operation;["create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"].includes(r)&&!e.documentId&&t.addIssue({code:"custom",message:`documentId is required for '${r}'. Example: { "operation": "${r}", "documentId": "doc000001" }`}),"create"===r&&(e.filename?e.filename.toLowerCase().endsWith(".md")||t.addIssue({code:"custom",message:"Filename must end with .md extension"}):t.addIssue({code:"custom",message:"filename is required for create (must end with .md)"}),e.content||t.addIssue({code:"custom",message:"content is required for create"}),e.type||t.addIssue({code:"custom",message:"type is required for create (Report, Documentation, Plan, or Other)"}),e.comment||t.addIssue({code:"custom",message:"comment is required for create"})),"search"!==r||e.query||t.addIssue({code:"custom",message:'query is required for search. Example: { "operation": "search", "query": "search term" }'}),"get-version"!==r&&"restore-version"!==r||e.versionNumber||t.addIssue({code:"custom",message:`versionNumber is required for '${r}'`}),"create-annotation"===r&&(e.selectedText||t.addIssue({code:"custom",message:"selectedText is required for create-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for create-annotation"})),"reply-to-annotation"===r&&(e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for reply-to-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for reply-to-annotation"})),"resolve-annotation"!==r||e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for resolve-annotation"})}))
3552
+ exports.SubagentOperationsSchema=r.z.object({sessionId:a.optional(),operation:r.z.enum(["spawn","continue","check-status","abort","read-messages","list-sessions"]),prompt:r.z.string().min(1).describe("Instructions for the subagent (required for spawn and continue)").optional(),agent:r.z.string().default("work").refine((e=>(0,n.isValidAgent)(e)),{message:"Invalid agent. Check tool description for available agents."}).describe("The subagent type to spawn (see tool description for available agents)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, spawn only)").optional(),requestId:r.z.string().describe("Request ID \u2014 associates work (spawn) or filters results (list-sessions)").optional(),allowParallel:r.z.boolean().describe("Allow spawning even if request already has active workers (spawn only)").optional(),useExistingSession:r.z.string().describe("Existing session ID to send prompt to instead of creating new session (spawn only)").optional(),limit:r.z.number().min(1).max(100).describe("Max items to return (read-messages: max 50, list-sessions: max 100)").optional(),activeOnly:r.z.boolean().describe("Only show sessions that are currently active/busy (list-sessions only)").optional(),minTokens:r.z.number().min(0).describe("Only show sessions with at least this many tokens (list-sessions only)").optional(),maxTokens:r.z.number().min(0).describe("Only show sessions with at most this many tokens (list-sessions only)").optional(),maxAgeHours:r.z.number().min(0).describe("Only show sessions newer than X hours (list-sessions only)").optional()}).refine((e=>"spawn"===e.operation?!!e.prompt:"continue"===e.operation?!!e.prompt&&!!e.sessionId:"check-status"===e.operation||"abort"===e.operation||"read-messages"===e.operation?!!e.sessionId:"list-sessions"===e.operation),{message:"spawn requires prompt; continue requires prompt+sessionId; check-status/abort/read-messages require sessionId"}),exports.SpecialistOpsSchema=r.z.object({operation:r.z.enum(["delegate","follow-up","check-status","list","abort"]),sessionId:a.optional(),prompt:r.z.string().min(1).describe("Instructions for the specialist (required for delegate and follow-up)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, delegate only)").optional(),specialization:r.z.string().max(500).describe('Domain description (e.g. "Frontend UI components"). Required for delegate, optional update for follow-up').optional(),requestId:r.z.string().describe("Request ID \u2014 associates work (delegate) or filters results (list)").optional(),activeOnly:r.z.boolean().describe("Only show active/busy specialists (list only)").optional(),limit:r.z.number().min(1).max(100).describe("Max sessions to return (list only)").optional()}).refine((e=>"delegate"===e.operation?!!e.prompt&&!!e.specialization&&!e.sessionId:"follow-up"===e.operation?!!e.prompt&&!!e.sessionId:"check-status"===e.operation||"abort"===e.operation?!!e.sessionId:"list"===e.operation),{message:"delegate requires prompt+specialization; follow-up requires prompt+sessionId; check-status/abort require sessionId"}),exports.PlannerOpsSchema=r.z.object({operation:r.z.enum(["request","check-status","list"]),sessionId:a.optional(),prompt:r.z.string().min(1).describe("What to plan \u2014 feature description, architecture question, etc. (required for request)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, request only)").optional(),activeOnly:r.z.boolean().describe("Only show active/busy planning sessions (list only)").optional(),limit:r.z.number().min(1).max(100).describe("Max sessions to return (list only)").optional()}).refine((e=>"request"===e.operation?!!e.prompt:"check-status"===e.operation?!!e.sessionId:"list"===e.operation),{message:"request requires prompt; check-status requires sessionId"}),exports.SwitchToRequestBranchSchema=r.z.object({requestId:s}),exports.InsertLinesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceLinesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.CreateDocumentSchema=r.z.object({requestId:s.optional(),filename:r.z.string().refine((e=>e.toLowerCase().endsWith(".md")),{message:"Filename must end with .md extension"}),content:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"],{errorMap(){return{message:"Document type must be one of: Report, Documentation, Plan, Other"}}}),comment:r.z.string()}),exports.SearchDocumentsSchema=r.z.object({query:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),requestId:s.optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both")}),exports.DocumentOperationsSchema=r.z.object({operation:r.z.enum(["create","search","create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"]),documentId:i.optional(),requestId:s.optional(),filename:r.z.string().optional(),content:r.z.string().optional(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),comment:r.z.string().optional(),query:r.z.string().optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional(),selectedText:r.z.string().optional(),prefixContext:r.z.string().optional(),suffixContext:r.z.string().optional(),lineHint:r.z.number().int().optional(),body:r.z.string().optional(),annotationId:r.z.string().optional()}).superRefine(((e,t)=>{const r=e.operation;["create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"].includes(r)&&!e.documentId&&t.addIssue({code:"custom",message:`documentId is required for '${r}'. Example: { "operation": "${r}", "documentId": "doc000001" }`}),"create"===r&&(e.filename?e.filename.toLowerCase().endsWith(".md")||t.addIssue({code:"custom",message:"Filename must end with .md extension"}):t.addIssue({code:"custom",message:"filename is required for create (must end with .md)"}),e.content||t.addIssue({code:"custom",message:"content is required for create"}),e.type||t.addIssue({code:"custom",message:"type is required for create (Report, Documentation, Plan, or Other)"}),e.comment||t.addIssue({code:"custom",message:"comment is required for create"})),"search"!==r||e.query||t.addIssue({code:"custom",message:'query is required for search. Example: { "operation": "search", "query": "search term" }'}),"get-version"!==r&&"restore-version"!==r||e.versionNumber||t.addIssue({code:"custom",message:`versionNumber is required for '${r}'`}),"create-annotation"===r&&(e.selectedText||t.addIssue({code:"custom",message:"selectedText is required for create-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for create-annotation"})),"reply-to-annotation"===r&&(e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for reply-to-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for reply-to-annotation"})),"resolve-annotation"!==r||e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for resolve-annotation"})}))
3478
3553
  const c=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^plan\d{6}$/.test(e))),{message:"Plan ID must match format: doc_[26 alphanumeric] (ULID) or plan###### (local ID)"})
3479
3554
  exports.PlanReadSchema=r.z.object({operation:r.z.enum(["get","get-active","list","get-history","get-requests"]),planId:c.optional(),searchQuery:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["createdAt","updatedAt","filename"]).default("updatedAt"),sortDirection:r.z.enum(["ASC","DESC"]).default("DESC")}).superRefine(((e,t)=>{["get","get-history","get-requests"].includes(e.operation)&&!e.planId&&t.addIssue({code:"custom",message:`planId is required for '${e.operation}'. Example: { "operation": "${e.operation}", "planId": "plan000001" }`})})),exports.PlanWriteSchema=r.z.object({operation:r.z.enum(["update","append","replace","create-snapshot","restore","set-active"]),planId:c,content:r.z.string().optional(),name:r.z.string().optional().describe("Optional new name for the plan"),old:r.z.string().optional().describe("Text to find in the plan (for replace)"),new:r.z.string().optional().describe("Replacement text (for replace)"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional()}).superRefine(((e,t)=>{const r=e.operation
3480
- "update"!==r&&"append"!==r||e.content||t.addIssue({code:"custom",message:`content is required for '${r}'. Example: { "operation": "${r}", "planId": "plan000001", "content": "..." }`}),"replace"===r&&(e.old||t.addIssue({code:"custom",message:'old is required for replace. Example: { "operation": "replace", "planId": "plan000001", "old": "find this", "new": "replace with" }'}),void 0===e.new&&t.addIssue({code:"custom",message:"new is required for replace"})),"restore"!==r||e.versionNumber||t.addIssue({code:"custom",message:'versionNumber is required for restore. Example: { "operation": "restore", "planId": "plan000001", "versionNumber": 1 }'})})),exports.SwitchToMainBranchSchema=r.z.object({}),exports.SwitchToBranchSchema=r.z.object({branch:r.z.string().optional(),password:r.z.string().optional()}),exports.RevertRequestSchema=r.z.object({requestId:s,reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}),exports.ModifyFileSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),operationType:r.z.enum(["replace-string","insert-lines","replace-lines","delete-string","delete-lines"]),replaceString:r.z.object({replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).optional(),insertLines:r.z.object({insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).optional(),replaceLines:r.z.object({replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).optional(),deleteString:r.z.object({patterns:r.z.array(r.z.string()),mode:r.z.enum(["all","unique"]).optional()}).optional(),deleteLines:r.z.object({lines:r.z.string()}).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}).refine((e=>"replace-string"===e.operationType?e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"insert-lines"===e.operationType?e.insertLines&&!e.replaceString&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"replace-lines"===e.operationType?e.replaceLines&&!e.replaceString&&!e.insertLines&&!e.deleteString&&!e.deleteLines:"delete-string"===e.operationType?e.deleteString&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteLines:"delete-lines"===e.operationType&&e.deleteLines&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString),{message:"Invalid operation data"})),comment:r.z.string()}),exports.ManageFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files","get-file-info"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}))}).optional(),getFileInfo:r.z.object({path:r.z.string()}).optional()}).refine((e=>"create-directory"===e.operationType?e.createDirectory&&!e.moveFiles&&!e.deleteFiles&&!e.getFileInfo:"move-files"===e.operationType?e.moveFiles&&!e.createDirectory&&!e.deleteFiles&&!e.getFileInfo:"delete-files"===e.operationType?e.deleteFiles&&!e.createDirectory&&!e.moveFiles&&!e.getFileInfo:"get-file-info"===e.operationType&&e.getFileInfo&&!e.createDirectory&&!e.moveFiles&&!e.deleteFiles),{message:"Invalid operation data"})),comment:r.z.string()}),exports.RequestOperationsSchema=r.z.object({requestId:s.optional(),operation:r.z.enum(["complete","merge","approve","revert","get-info","list","search","delete-empty"]),complete:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({summary:r.z.string()})).optional(),merge:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({verifications:r.z.array(r.z.object({key:r.z.string().min(2).max(4),evidence:r.z.string().min(1)})).min(1)})).optional(),revert:r.z.object({reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}).optional(),list:r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}).optional(),search:r.z.object({query:r.z.string().min(1),searchIn:r.z.enum(["title","description","criteria","all"]).default("all"),filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0)}).optional()}).optional(),approve:r.z.object({}).optional()}).superRefine(((e,t)=>{const r=!!e.requestId,n=e.operation
3481
- if(["complete","merge","approve","revert","get-info"].includes(n)&&!r)return void t.addIssue({code:"custom",message:`requestId is required for '${n}' operation`})
3482
- const o={complete:{field:"complete",hint:'Provide: { complete: { summary: "..." } }'},merge:{field:"merge",hint:'Provide: { merge: { verifications: [{key: "1a", evidence: "..."}] } }'},revert:{field:"revert",hint:'Provide: { revert: { reason: "..." } }'},search:{field:"search",hint:'Provide: { search: { query: "..." } }'}}[n]
3483
- o&&!e[o.field]&&t.addIssue({code:"custom",message:`'${n}' operation requires '${o.field}' data. ${o.hint}`})})),exports.QuickWriteSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional()}),exports.QuickReplaceSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1),fuzzy_match:r.z.boolean().optional()})).min(1),fuzzy_match:r.z.boolean().optional(),comment:r.z.string().min(1,"Comment describing the change is required")}),exports.QuickManageSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}))}).optional()})).min(1)}),exports.GenerateRequestJournalSchema=r.z.object({requestId:r.z.string().regex(/^req[_\d].+$/,"Invalid request ID format. Expected format: req_[26 chars] or req######")}),exports.MetaWorkflowListSchema=r.z.object({}),exports.MetaWorkflowGetSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to retrieve")}),exports.MetaWorkflowCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the workflow"),shortName:r.z.string().min(1).max(10).describe("Short display name (required, max 10 chars)"),description:r.z.string().optional().describe("Description of what the workflow does"),documentation:r.z.string().optional().describe("Detailed documentation"),defaultAgent:r.z.string().optional().describe("Default agent template to use"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior: auto-merge (default), auto-test-then-merge, or manual-review"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaWorkflowUpdateSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to update"),name:r.z.string().min(1).optional().describe("New name"),shortName:r.z.string().max(10).optional().describe("New short name (max 10 chars)"),description:r.z.string().optional().describe("New description"),documentation:r.z.string().optional().describe("New documentation"),defaultAgent:r.z.string().optional().describe("New default agent"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaRecipeListSchema=r.z.object({}),exports.MetaRecipeGetSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to retrieve")}),exports.MetaRecipeCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the recipe"),description:r.z.string().optional().describe("Description of what the recipe does"),documentation:r.z.string().optional().describe("Detailed documentation")}),exports.MetaRecipeAddHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to add the hook to"),hookId:r.z.string().describe("Hook template ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the recipe (0-based, appended if omitted)")}),exports.MetaRecipeRemoveHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to remove the hook from"),hookId:r.z.string().describe("Hook template ID to remove")}),exports.MetaHookListSchema=r.z.object({}),exports.MetaHookCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the hook"),description:r.z.string().optional().describe("Description of what the hook does"),eventType:r.z.string().describe("Event type that triggers this hook (e.g., session_idle, request_completed, custom:plan_ready)"),category:r.z.enum(["alchemy","session","message","editing","reading","file_management","documents","history","tool"]).default("session").describe("Hook category"),agent:r.z.string().describe("Agent template to execute when hook fires"),promptTemplate:r.z.string().describe("Prompt template with {{variable}} substitution"),condition:r.z.record(r.z.any()).optional().describe("Condition object for filtering when hook fires"),executionMode:r.z.enum(["same_session","sub_agent","background","notification","direct_report"]).default("background").describe("How to execute the hook"),timing:r.z.enum(["before","after"]).default("after").describe("When to fire relative to the event"),maxIterations:r.z.number().int().min(1).optional().describe("Maximum times to fire per session"),emitEvent:r.z.string().optional().describe("Custom event to emit on completion"),emitEventOnCondition:r.z.union([r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}),r.z.array(r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}))]).optional().describe("Conditional event emission based on output")}),exports.MetaWorkflowAddRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to add the recipe to"),recipeId:r.z.string().describe("Recipe ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the workflow (0-based, appended if omitted)")}),exports.MetaWorkflowRemoveRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to remove the recipe from"),recipeId:r.z.string().describe("Recipe ID to remove")}),exports.MetaAgentListSchema=r.z.object({}),exports.MetaReferenceSchema=r.z.object({}),exports.TestingProcessListSchema=r.z.object({}),exports.TestingProcessGetSchema=r.z.object({processId:r.z.string().describe("Test process ID to retrieve")})
3555
+ "update"!==r&&"append"!==r||e.content||t.addIssue({code:"custom",message:`content is required for '${r}'. Example: { "operation": "${r}", "planId": "plan000001", "content": "..." }`}),"replace"===r&&(e.old||t.addIssue({code:"custom",message:'old is required for replace. Example: { "operation": "replace", "planId": "plan000001", "old": "find this", "new": "replace with" }'}),void 0===e.new&&t.addIssue({code:"custom",message:"new is required for replace"})),"restore"!==r||e.versionNumber||t.addIssue({code:"custom",message:'versionNumber is required for restore. Example: { "operation": "restore", "planId": "plan000001", "versionNumber": 1 }'})})),exports.SwitchToMainBranchSchema=r.z.object({}),exports.SwitchToBranchSchema=r.z.object({branch:r.z.string().optional(),password:r.z.string().optional()}),exports.RevertRequestSchema=r.z.object({requestId:s,reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}),exports.ModifyFileSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),operationType:r.z.enum(["replace-string","insert-lines","replace-lines","delete-string","delete-lines"]),replaceString:r.z.object({replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).optional(),insertLines:r.z.object({insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).optional(),replaceLines:r.z.object({replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).optional(),deleteString:r.z.object({patterns:r.z.array(r.z.string()),mode:r.z.enum(["all","unique"]).optional()}).optional(),deleteLines:r.z.object({lines:r.z.string()}).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}).refine((e=>"replace-string"===e.operationType?e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"insert-lines"===e.operationType?e.insertLines&&!e.replaceString&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"replace-lines"===e.operationType?e.replaceLines&&!e.replaceString&&!e.insertLines&&!e.deleteString&&!e.deleteLines:"delete-string"===e.operationType?e.deleteString&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteLines:"delete-lines"===e.operationType&&e.deleteLines&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString),{message:"Invalid operation data"})),comment:r.z.string()}),exports.ManageFilesSchema=r.z.object({operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files","get-file-info"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}))}).optional(),getFileInfo:r.z.object({path:r.z.string()}).optional()}).refine((e=>"create-directory"===e.operationType?e.createDirectory&&!e.moveFiles&&!e.deleteFiles&&!e.getFileInfo:"move-files"===e.operationType?e.moveFiles&&!e.createDirectory&&!e.deleteFiles&&!e.getFileInfo:"delete-files"===e.operationType?e.deleteFiles&&!e.createDirectory&&!e.moveFiles&&!e.getFileInfo:"get-file-info"===e.operationType&&e.getFileInfo&&!e.createDirectory&&!e.moveFiles&&!e.deleteFiles),{message:"Invalid operation data"})),comment:r.z.string()}),exports.RequestOperationsSchema=r.z.object({requestId:s.optional(),operation:r.z.enum(["complete","merge","approve","revert","get-info","list","search","delete-empty"]),complete:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({summary:r.z.string()})).optional(),merge:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({verifications:r.z.array(r.z.object({key:r.z.string().min(2).max(4),evidence:r.z.string().min(1)})).min(1)})).optional(),revert:r.z.object({reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}).optional(),list:r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}).optional(),search:r.z.object({query:r.z.string().min(1),searchIn:r.z.enum(["title","description","criteria","all"]).default("all"),filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0)}).optional()}).optional(),approve:r.z.object({}).optional()}).superRefine(((e,t)=>{e.requestId
3556
+ const r=e.operation,n={complete:{field:"complete",hint:'Provide: { complete: { summary: "..." } }'},merge:{field:"merge",hint:'Provide: { merge: { verifications: [{key: "1a", evidence: "..."}] } }'},revert:{field:"revert",hint:'Provide: { revert: { reason: "..." } }'},search:{field:"search",hint:'Provide: { search: { query: "..." } }'}}[r]
3557
+ n&&!e[n.field]&&t.addIssue({code:"custom",message:`'${r}' operation requires '${n.field}' data. ${n.hint}`})})),exports.QuickWriteSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional()}),exports.QuickReplaceSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1),fuzzy_match:r.z.boolean().optional()})).min(1),fuzzy_match:r.z.boolean().optional(),comment:r.z.string().min(1,"Comment describing the change is required")}),exports.QuickManageSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}))}).optional()})).min(1)}),exports.GenerateRequestJournalSchema=r.z.object({requestId:r.z.string().regex(/^req[_\d].+$/,"Invalid request ID format. Expected format: req_[26 chars] or req######")}),exports.MetaWorkflowListSchema=r.z.object({}),exports.MetaWorkflowGetSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to retrieve")}),exports.MetaWorkflowCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the workflow"),shortName:r.z.string().min(1).max(10).describe("Short display name (required, max 10 chars)"),description:r.z.string().optional().describe("Description of what the workflow does"),documentation:r.z.string().optional().describe("Detailed documentation"),defaultAgent:r.z.string().optional().describe("Default agent template to use"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior: auto-merge (default), auto-test-then-merge, or manual-review"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaWorkflowUpdateSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to update"),name:r.z.string().min(1).optional().describe("New name"),shortName:r.z.string().max(10).optional().describe("New short name (max 10 chars)"),description:r.z.string().optional().describe("New description"),documentation:r.z.string().optional().describe("New documentation"),defaultAgent:r.z.string().optional().describe("New default agent"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaRecipeListSchema=r.z.object({}),exports.MetaRecipeGetSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to retrieve")}),exports.MetaRecipeCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the recipe"),description:r.z.string().optional().describe("Description of what the recipe does"),documentation:r.z.string().optional().describe("Detailed documentation")}),exports.MetaRecipeAddHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to add the hook to"),hookId:r.z.string().describe("Hook template ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the recipe (0-based, appended if omitted)")}),exports.MetaRecipeRemoveHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to remove the hook from"),hookId:r.z.string().describe("Hook template ID to remove")}),exports.MetaHookListSchema=r.z.object({}),exports.MetaHookCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the hook"),description:r.z.string().optional().describe("Description of what the hook does"),eventType:r.z.string().describe("Event type that triggers this hook (e.g., session_idle, request_completed, custom:plan_ready)"),category:r.z.enum(["alchemy","session","message","editing","reading","file_management","documents","history","tool"]).default("session").describe("Hook category"),agent:r.z.string().describe("Agent template to execute when hook fires"),promptTemplate:r.z.string().describe("Prompt template with {{variable}} substitution"),condition:r.z.record(r.z.any()).optional().describe("Condition object for filtering when hook fires"),executionMode:r.z.enum(["same_session","sub_agent","background","notification","direct_report"]).default("background").describe("How to execute the hook"),timing:r.z.enum(["before","after"]).default("after").describe("When to fire relative to the event"),maxIterations:r.z.number().int().min(1).optional().describe("Maximum times to fire per session"),emitEvent:r.z.string().optional().describe("Custom event to emit on completion"),emitEventOnCondition:r.z.union([r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}),r.z.array(r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}))]).optional().describe("Conditional event emission based on output")}),exports.MetaWorkflowAddRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to add the recipe to"),recipeId:r.z.string().describe("Recipe ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the workflow (0-based, appended if omitted)")}),exports.MetaWorkflowRemoveRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to remove the recipe from"),recipeId:r.z.string().describe("Recipe ID to remove")}),exports.MetaAgentListSchema=r.z.object({}),exports.MetaReferenceSchema=r.z.object({}),exports.TestingProcessListSchema=r.z.object({}),exports.TestingProcessGetSchema=r.z.object({processId:r.z.string().describe("Test process ID to retrieve")})
3484
3558
  const l=r.z.object({name:r.z.string().min(1).describe('Command name (e.g., "Build", "Unit Tests")'),command:r.z.string().min(1).describe('Shell command to run (e.g., "npm test")'),required:r.z.boolean().default(!0).describe("If true, failure blocks the request (default: true)"),timeout:r.z.number().int().min(10).max(3600).default(300).describe("Max execution time in seconds (default: 300)")})
3485
- exports.TestingProcessCreateSchema=r.z.object({name:r.z.string().min(1).describe("Name for the test process"),description:r.z.string().optional().describe("Description of what this process verifies"),scope:r.z.string().optional().describe('Path prefix for monorepo scoping (e.g., "packages/api/"). Omit for global.'),setup:r.z.array(r.z.string()).optional().describe('Commands to prepare the environment (e.g., ["ln -s ../../node_modules node_modules"])'),commands:r.z.array(l).min(1).describe("Test commands to execute in order"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingProcessUpdateSchema=r.z.object({processId:r.z.string().describe("Test process ID to update"),name:r.z.string().min(1).optional().describe("New name"),description:r.z.string().optional().describe("New description"),scope:r.z.string().nullable().optional().describe("New scope (null to remove)"),isActive:r.z.boolean().optional().describe("Enable or disable the process"),setup:r.z.array(r.z.string()).optional().describe("New setup commands (replaces existing)"),commands:r.z.array(l).optional().describe("New test commands (replaces existing)"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingReferenceSchema=r.z.object({}),exports.ExecuteTestCommandSchema=r.z.object({processId:r.z.string().describe("Test process ID containing the command"),commandName:r.z.string().describe('Name of the test command to run, or "setup" to run all setup commands in sequence')}),exports.ReportTestResultsSchema=r.z.object({status:r.z.enum(["passed","failed","error"]).describe("Overall result"),results:r.z.object({commands:r.z.array(r.z.object({name:r.z.string().describe("Command name"),status:r.z.enum(["passed","failed","skipped","error"]).describe("Command result"),output:r.z.string().optional().describe("Relevant output snippet"),diagnosis:r.z.string().optional().describe("Why it failed, if applicable")})).describe("Per-command results"),summary:r.z.string().describe("Brief overall summary"),acceptanceCriteria:r.z.array(r.z.object({criterion:r.z.string().describe("The acceptance criterion text"),status:r.z.enum(["verified","unverified","unclear"]),evidence:r.z.string().describe("How verified, or why not")})).optional().describe("AC verification results, if applicable")}).describe("Structured test results")}),exports.SessionMessageOperationsSchema=r.z.object({operation:r.z.enum(["send","reply","list","get","offer-handoff"]),type:r.z.enum(["question","report"]).optional().describe("Message type to send (required for send)"),toSessionId:r.z.string().optional().describe('Target session ID, or "parent" to auto-resolve to parent session (omit for broadcast questions)'),questionType:r.z.enum(["free-form","alternatives"]).optional().describe('Type of question (required for send type="question")'),questionContent:r.z.object({question:r.z.string().min(1).describe("The question text"),context:r.z.string().optional().describe("Additional context"),options:r.z.array(r.z.object({id:r.z.string(),label:r.z.string(),description:r.z.string().optional()})).optional().describe("Options for alternatives questions"),allowMultiple:r.z.boolean().optional().describe("Allow selecting multiple options")}).optional().describe('Question content (required for send type="question")'),priority:r.z.enum(["low","normal","high"]).optional().describe("Question priority"),expiresInHours:r.z.number().optional().describe("Question expiry in hours"),status:r.z.enum(["success","partial","failure","blocked"]).optional().describe('Report status (required for send type="report")'),summary:r.z.string().optional().describe('Report summary (required for send type="report")'),details:r.z.string().optional().describe("Report details"),finish:r.z.boolean().optional().describe("Release request associations after report"),messageCode:r.z.string().optional().describe("Message code (required for reply and get operations)"),respondedBySessionId:r.z.string().optional().describe("Session ID answering the question"),text:r.z.string().optional().describe("Text answer for free-form questions"),selectedOptions:r.z.array(r.z.string()).optional().describe("Selected option IDs for alternatives"),notes:r.z.string().optional().describe("Additional notes"),list:r.z.object({sessionId:r.z.string().optional().describe("Filter by session ID (auto-discovered if omitted)"),messageType:r.z.enum(["question","report","all"]).default("all").describe("Filter by message type"),direction:r.z.enum(["incoming","outgoing","all"]).default("all"),status:r.z.enum(["pending","answered","expired","success","partial","failure","blocked","all"]).default("all").describe("Filter by status"),readStatus:r.z.enum(["unread","read","acknowledged","all"]).default("all").describe("Filter by read status (reports only)"),limit:r.z.number().min(1).max(100).default(50),offset:r.z.number().min(0).default(0)}).optional().describe('List filters (operation: "list" only)'),offerHandoff:r.z.object({summary:r.z.string().describe("Summary of what was planned/created"),requestIds:r.z.array(r.z.string()).describe("Request IDs that were created from the plan")}).optional().describe('Handoff offer details (operation: "offer-handoff" only)')}).refine((e=>"send"===e.operation?!!e.type:"reply"===e.operation?!!e.messageCode:"list"===e.operation||("get"===e.operation?!!e.messageCode:"offer-handoff"===e.operation)),{message:"Invalid operation data: send requires type, reply requires messageCode, get requires messageCode"}),exports.UpdateSpecializationSchema=r.z.object({specialization:r.z.string().min(1).max(500).describe("Your updated specialization summary \u2014 a concise description of your accumulated domain expertise")})},6252(e,exports,t){"use strict"
3559
+ exports.TestingProcessCreateSchema=r.z.object({name:r.z.string().min(1).describe("Name for the test process"),description:r.z.string().optional().describe("Description of what this process verifies"),scope:r.z.string().optional().describe('Path prefix for monorepo scoping (e.g., "packages/api/"). Omit for global.'),setup:r.z.array(r.z.string()).optional().describe('Commands to prepare the environment (e.g., ["ln -s ../../node_modules node_modules"])'),commands:r.z.array(l).min(1).describe("Test commands to execute in order"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingProcessUpdateSchema=r.z.object({processId:r.z.string().describe("Test process ID to update"),name:r.z.string().min(1).optional().describe("New name"),description:r.z.string().optional().describe("New description"),scope:r.z.string().nullable().optional().describe("New scope (null to remove)"),isActive:r.z.boolean().optional().describe("Enable or disable the process"),setup:r.z.array(r.z.string()).optional().describe("New setup commands (replaces existing)"),commands:r.z.array(l).optional().describe("New test commands (replaces existing)"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingReferenceSchema=r.z.object({}),exports.ExecuteTestCommandSchema=r.z.object({processId:r.z.string().describe("Test process ID containing the command"),commandName:r.z.string().describe('Name of the test command to run, or "setup" to run all setup commands in sequence')}),exports.CommandsSchema=r.z.object({operation:r.z.enum(["run","list","add","remove"]).default("run").describe('"run" to execute a command, "list" to see available commands, "add" to register a new command, "remove" to delete one'),name:r.z.string().optional().describe('Command name (required for "run", "add", and "remove")'),args:r.z.string().optional().describe('Additional arguments appended to the base command (optional, for "run")'),grep:r.z.string().optional().describe('Filter output through grep (optional, for "run"). Pipes command output through grep -i with this pattern.'),command:r.z.string().optional().describe('Shell command to register (required for "add", e.g. "tsc --noEmit")'),description:r.z.string().optional().describe('What this command verifies (optional, for "add")'),timeout:r.z.number().optional().describe('Timeout in seconds (optional, for "add", default 60)')}),exports.ReportTestResultsSchema=r.z.object({status:r.z.enum(["passed","failed","error"]).describe("Overall result"),results:r.z.object({commands:r.z.array(r.z.object({name:r.z.string().describe("Command name"),status:r.z.enum(["passed","failed","skipped","error"]).describe("Command result"),output:r.z.string().optional().describe("Relevant output snippet"),diagnosis:r.z.string().optional().describe("Why it failed, if applicable")})).describe("Per-command results"),summary:r.z.string().describe("Brief overall summary"),acceptanceCriteria:r.z.array(r.z.object({criterion:r.z.string().describe("The acceptance criterion text"),status:r.z.enum(["verified","unverified","unclear"]),evidence:r.z.string().describe("How verified, or why not")})).optional().describe("AC verification results, if applicable")}).describe("Structured test results")}),exports.SessionMessageOperationsSchema=r.z.object({operation:r.z.enum(["send","reply","list","get","offer-handoff"]),type:r.z.enum(["question","report"]).optional().describe("Message type to send (required for send)"),toSessionId:r.z.string().optional().describe('Target session ID, or "parent" to auto-resolve to parent session (omit for broadcast questions)'),questionType:r.z.enum(["free-form","alternatives"]).optional().describe('Type of question (required for send type="question")'),questionContent:r.z.object({question:r.z.string().min(1).describe("The question text"),context:r.z.string().optional().describe("Additional context"),options:r.z.array(r.z.object({id:r.z.string(),label:r.z.string(),description:r.z.string().optional()})).optional().describe("Options for alternatives questions"),allowMultiple:r.z.boolean().optional().describe("Allow selecting multiple options")}).optional().describe('Question content (required for send type="question")'),priority:r.z.enum(["low","normal","high"]).optional().describe("Question priority"),expiresInHours:r.z.number().optional().describe("Question expiry in hours"),status:r.z.enum(["success","partial","failure","blocked"]).optional().describe('Report status (required for send type="report")'),summary:r.z.string().optional().describe('Report summary (required for send type="report")'),details:r.z.string().optional().describe("Report details"),finish:r.z.boolean().optional().describe("Release request associations after report"),messageCode:r.z.string().optional().describe("Message code (required for reply and get operations)"),respondedBySessionId:r.z.string().optional().describe("Session ID answering the question"),text:r.z.string().optional().describe("Text answer for free-form questions"),selectedOptions:r.z.array(r.z.string()).optional().describe("Selected option IDs for alternatives"),notes:r.z.string().optional().describe("Additional notes"),list:r.z.object({sessionId:r.z.string().optional().describe("Filter by session ID (auto-discovered if omitted)"),messageType:r.z.enum(["question","report","all"]).default("all").describe("Filter by message type"),direction:r.z.enum(["incoming","outgoing","all"]).default("all"),status:r.z.enum(["pending","answered","expired","success","partial","failure","blocked","all"]).default("all").describe("Filter by status"),readStatus:r.z.enum(["unread","read","acknowledged","all"]).default("all").describe("Filter by read status (reports only)"),limit:r.z.number().min(1).max(100).default(50),offset:r.z.number().min(0).default(0)}).optional().describe('List filters (operation: "list" only)'),offerHandoff:r.z.object({summary:r.z.string().describe("Summary of what was planned/created"),requestIds:r.z.array(r.z.string()).describe("Request IDs that were created from the plan")}).optional().describe('Handoff offer details (operation: "offer-handoff" only)')}).refine((e=>"send"===e.operation?!!e.type:"reply"===e.operation?!!e.messageCode:"list"===e.operation||("get"===e.operation?!!e.messageCode:"offer-handoff"===e.operation)),{message:"Invalid operation data: send requires type, reply requires messageCode, get requires messageCode"}),exports.UpdateSpecializationSchema=r.z.object({specialization:r.z.string().min(1).max(500).describe("Your updated specialization summary \u2014 a concise description of your accumulated domain expertise")})},6252(e,exports,t){"use strict"
3486
3560
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
3487
3561
  const r=t(6183),n=t(405)
3488
3562
  exports.def={name:"plan_write",description:"Modify project plans.\n\nOperations:\n\u2022 update - Update plan content\n\u2022 append - Append content to an existing plan\n\u2022 replace - Find and replace text within a plan\n\u2022 create-snapshot - Create a version snapshot\n\u2022 restore - Restore to a previous version",schema:r.PlanWriteSchema,annotations:{title:"Plan Write",readOnlyHint:!1,destructiveHint:!1},handler(e,t){return(0,n.handlePlanWrite)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},6261(module){"use strict"
@@ -3496,12 +3570,14 @@ var t={}
3496
3570
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
3497
3571
  return o(t,e),t})
3498
3572
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,p){const f=n.child({tool:"specialist_ops"}),m=o.startTimer("tool_execution_time")
3499
- try{if(!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="delegate":e.prompt&&e.sessionId?e.operation="follow-up":e.sessionId&&(e.operation="check-status")),e?.followUp&&"string"==typeof e.followUp)try{e.followUp=JSON.parse(e.followUp)}catch{}if(e?.delegate&&"string"==typeof e.delegate)try{e.delegate=JSON.parse(e.delegate)}catch{}if("string"==typeof e?.delegate){const t=e.delegate
3500
- e.delegate={prompt:e.prompt||t,description:e.description||t.slice(0,60),specialization:e.specialization||"general",requestId:e.requestId},e.operation=e.operation||"delegate",delete e.prompt,delete e.description,delete e.specialization,delete e.requestId}"follow-up"===e?.operation&&e?.prompt&&!e?.followUp&&(e.followUp={prompt:e.prompt,specialization:e.specialization},delete e.prompt,e.specialization&&delete e.specialization),"delegate"===e?.operation&&e?.prompt&&!e?.delegate&&(e.delegate={prompt:e.prompt,description:e.description||e.prompt.slice(0,60),specialization:e.specialization||"general",requestId:e.requestId},delete e.prompt,delete e.description,delete e.specialization,delete e.requestId)
3573
+ try{if(e?.delegate&&"object"==typeof e.delegate){const t=e.delegate
3574
+ e.prompt=e.prompt||t.prompt,e.description=e.description||t.description,e.specialization=e.specialization||t.specialization,e.requestId=e.requestId||t.requestId,delete e.delegate}if(e?.followUp&&"object"==typeof e.followUp){const t=e.followUp
3575
+ e.prompt=e.prompt||t.prompt,e.specialization=e.specialization||t.specialization,delete e.followUp}if(e?.list&&"object"==typeof e.list){const t=e.list
3576
+ e.activeOnly=e.activeOnly??t.activeOnly,e.requestId=e.requestId||t.requestId,e.limit=e.limit??t.limit,delete e.list}!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="delegate":e.prompt&&e.sessionId?e.operation="follow-up":e.sessionId&&(e.operation="check-status")),e?.operation&&("delegate"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.limit):"follow-up"===e.operation?(delete e.description,delete e.activeOnly,delete e.limit):"check-status"===e.operation||"abort"===e.operation?(delete e.prompt,delete e.description,delete e.specialization,delete e.requestId,delete e.activeOnly,delete e.limit):"list"===e.operation&&(delete e.sessionId,delete e.prompt,delete e.description,delete e.specialization))
3501
3577
  const n=c.validateArgs(e,a.SpecialistOpsSchema),{operation:y,sessionId:w}=n
3502
3578
  let k
3503
- switch(f.info("Processing specialist_ops",{operation:y,sessionId:w}),y){case"delegate":{const e=n.delegate,o=10,i=p?.sessionId||g.sessionIdentity.getIdentity()?.sessionId
3504
- if(i&&s){const e=await async function(e,t,r,n,o){n.info("enforcePoolLimit called",{parentSessionId:e,maxPoolSize:t})
3579
+ switch(f.info("Processing specialist_ops",{operation:y,sessionId:w}),y){case"delegate":{const e=10,o=p?.sessionId||g.sessionIdentity.getIdentity()?.sessionId
3580
+ if(o&&s){const t=await async function(e,t,r,n,o){n.info("enforcePoolLimit called",{parentSessionId:e,maxPoolSize:t})
3505
3581
  const s=await(0,h.getServerUrl)(r,n)
3506
3582
  if(s)try{const r=await fetch(s.replace(/\/$/,"")+"/session")
3507
3583
  if(!r.ok)return
@@ -3514,31 +3590,31 @@ return"specialist"===t?.agentType&&"archived"!==t?.status}))
3514
3590
  if(n.info("Pool check: specialist count",{specialistCount:h.length,maxPoolSize:t}),h.length<t)return
3515
3591
  const g=h.map((e=>{const t=l[e.id],r=u[e.id]?.type||"idle",n=t?.specialization||"(none)"
3516
3592
  return` \u2022 ${e.id} \u2014 ${n} [${r}]`})).join("\n")
3517
- return{content:[{type:"text",text:`\u274c Specialist pool is full (${h.length}/${t}).\nAbort an idle specialist first with \`specialist_ops abort\`, then delegate again.\n\nCurrent pool:\n`+g}],isError:!0}}catch(e){return void n.warn("Pool limit check failed, allowing spawn",{error:(0,l.getErrorMessage)(e)})}}(i,o,r,f,s)
3518
- if(e){k=e
3519
- break}}let a=e.description
3520
- const c=await Promise.resolve().then(t.t.bind(t,9896,23)),m=e=>c.appendFileSync("/tmp/specialist-name-debug.log",`${(new Date).toISOString()} ${e}\n`)
3521
- if(i)try{const e=await(0,h.getServerUrl)(r,f)
3522
- if(m(`serverUrl=${e}, parentId=${i}`),e){const t=await fetch(e.replace(/\/$/,"")+"/session")
3523
- if(m("session fetch status="+t.status),t.ok){const e=(await t.json()).filter((e=>(e.parentId||e.parentID)===i)).map((e=>e.title||""))
3524
- m(`siblings=${e.length}: ${e.join(", ")}`)
3593
+ return{content:[{type:"text",text:`\u274c Specialist pool is full (${h.length}/${t}).\nAbort an idle specialist first with \`specialist_ops abort\`, then delegate again.\n\nCurrent pool:\n`+g}],isError:!0}}catch(e){return void n.warn("Pool limit check failed, allowing spawn",{error:(0,l.getErrorMessage)(e)})}}(o,e,r,f,s)
3594
+ if(t){k=t
3595
+ break}}let i=n.description||n.prompt.slice(0,60)
3596
+ const a=await Promise.resolve().then(t.t.bind(t,9896,23)),c=e=>a.appendFileSync(t(6928).join(t(857).tmpdir(),"specialist-name-debug.log"),`${(new Date).toISOString()} ${e}\n`)
3597
+ if(o)try{const e=await(0,h.getServerUrl)(r,f)
3598
+ if(c(`serverUrl=${e}, parentId=${o}`),e){const t=await fetch(e.replace(/\/$/,"")+"/session")
3599
+ if(c("session fetch status="+t.status),t.ok){const e=(await t.json()).filter((e=>(e.parentId||e.parentID)===o)).map((e=>e.title||""))
3600
+ c(`siblings=${e.length}: ${e.join(", ")}`)
3525
3601
  const r=(0,d.pickSpecialistName)(e)
3526
- a=r,m("picked name: "+r)}}else m("no serverUrl")}catch(e){m("error: "+(e instanceof Error?e.message:e+""))}else m("no parentId")
3527
- const y=e.requestId,w=y?`Working on request ${y}.\n\n${e.prompt}`:e.prompt
3528
- k=await(0,u.handleSpawn)({agent:"specialist",prompt:w,title:a,specialization:e.specialization},r,f,s,p)
3602
+ i=r,c("picked name: "+r)}}else c("no serverUrl")}catch(e){c("error: "+(e instanceof Error?e.message:e+""))}else c("no parentId")
3603
+ const m=n.requestId,y=m?`Working on request ${m}.\n\n${n.prompt}`:n.prompt
3604
+ k=await(0,u.handleSpawn)({agent:"specialist",prompt:y,title:i,specialization:n.specialization},r,f,s,p)
3529
3605
  break}case"follow-up":{const e=await(0,h.getServerUrl)(r,f)
3530
3606
  if(e)try{const t=await fetch(e.replace(/\/$/,"")+"/session/status")
3531
3607
  if(t.ok){const e=await t.json(),r=e[w]?.type
3532
3608
  if(r&&"idle"!==r&&"prompting"!==r){k={content:[{type:"text",text:`\u274c Specialist ${w} is currently busy (status: ${r}).\nUse \`delegate\` to spawn a new specialist instead.`}],isError:!0}
3533
- break}}}catch{}k=await(0,u.handleContinue)(w,n.followUp.prompt,r,f,s,"specialist",p)
3534
- const t=n.followUp.specialization
3609
+ break}}}catch{}k=await(0,u.handleContinue)(w,n.prompt,r,f,s,"specialist",p)
3610
+ const t=n.specialization
3535
3611
  if(t&&s)try{const e=s.getCLISessionClient()
3536
3612
  e&&(await e.createOrUpdateSession({externalSessionId:w,specialization:t}),k.content[0].text+="\nSpecialization updated to: "+t)}catch{}break}case"check-status":k=await(0,u.handleCheckStatus)(w,r,f,s)
3537
3613
  break
3538
3614
  case"abort":if(k=await(0,u.handleAbort)(w,r,f),!k.isError&&s)try{const e=s.getCLISessionClient()
3539
3615
  e&&await e.createOrUpdateSession({externalSessionId:w,status:"archived"})}catch{}break
3540
3616
  case"list":{const e=p?.sessionId||g.sessionIdentity.getIdentity()?.sessionId
3541
- k=await(0,u.handleListSessions)(r,f,s,{activeOnly:n.list?.activeOnly,requestId:n.list?.requestId,limit:n.list?.limit,agentType:"specialist",parentSessionId:e})
3617
+ k=await(0,u.handleListSessions)(r,f,s,{activeOnly:n.activeOnly,requestId:n.requestId,limit:n.limit,agentType:"specialist",parentSessionId:e})
3542
3618
  break}default:throw new i.ValidationError("Unknown operation: "+y)}return m({success:!0}),o.incrementCounter(`specialist_ops_${y}_success`,1),k}catch(e){return f.error("Specialist ops failed",{error:e instanceof Error?e.stack:e+""}),m({success:!1}),o.incrementCounter("specialist_ops_errors",1),{content:[{type:"text",text:"Specialist operation failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
3543
3619
  const i=t(9860),a=t(6183),c=s(t(5967)),l=t(8824),d=t(9089),u=t(1725),h=t(7617),g=t(6688)},6315(e,exports,t){"use strict"
3544
3620
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
@@ -3621,58 +3697,59 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
3621
3697
  var t={}
3622
3698
  if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
3623
3699
  return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
3624
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleInsertLines=async function(e,t,n,o,s,i,a,m){const y=i.child({tool:"insert_lines"}),w=Date.now()
3625
- let k,b,I=d.FileOperationPhase.VALIDATION
3626
- const v={toolName:"insert-lines",operationName:"insert-lines",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"insert-lines",metricsPrefix:"insert_lines",successMessage:"Successfully inserted lines into files and documents",failureMessage:"Failed to insert lines into files and documents"}
3627
- try{const i=d.validateArgs(e,l.InsertLinesSchema),{taskId:C,operations:_,comment:E}=i
3628
- if(y.info("Inserting lines into files and documents",{taskId:C,operationCount:_.length,comment:E}),!_||0===_.length)throw new u.ValidationError("At least one operation is required")
3629
- const q=_.filter((e=>e.path)),S=_.filter((e=>e.documentId))
3630
- y.info("Operation breakdown",{fileOperations:q.length,documentOperations:S.length})
3631
- const T=[]
3632
- for(const e of q){const{normalizedPath:r,fullPath:n}=d.validateAndNormalizePath(e.path,t)
3633
- T.push({type:"file",path:r,fullPath:n,insertions:e.insertions})}const P=[]
3634
- if(S.length>0&&!t.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
3635
- for(const e of S)P.push({type:"document",documentId:e.documentId,insertions:e.insertions})
3636
- if(P.length>0&&t.apiClient){const e=P.map((e=>e.documentId))
3637
- try{await(0,p.ensureDocumentsNotLocked)(e,t.apiClient,y,a,"insert-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3638
- throw e}}I=d.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("insert_lines_phase",1,{phase:I})
3639
- const j=T.length>0?T[0].path:"document-operation",R=await d.validateTaskId(C,j,n,y,a,v.metricsPrefix),M=R?.requestId
3640
- let x=null
3641
- T.length>0&&M&&(x=await d.validateWorkItemStates(C,T[0].path,n,s,t,y,a,v.metricsPrefix))
3642
- let O={taskPromoted:!1,requestPromoted:!1}
3643
- T.length>0&&M&&x&&(O=await d.autoPromoteTaskStatus(C,R.status,M,x.request?.status,T[0].path,n,s,y,a,v.metricsPrefix),O.taskPromoted&&y.info("Auto-promoted task to in_progress for insert-lines operation",{taskId:C,requestId:M,previousStatus:R.status,newStatus:O.newTaskStatus,triggeringOperation:"insert-lines"}))
3644
- const D=await d.ensureCorrectWorkspaceContext({taskPromoted:O.taskPromoted,requestId:M,context:t,operation:"insert-lines",logger:y,metrics:a,metricsPrefix:v.metricsPrefix})
3645
- if(!D.success){if(D.isLockConflict)return{content:[{type:"text",text:"\u274c "+D.error}],isError:!0}
3646
- throw Error(D.error)}if(T.length>0){y.debug("Re-validating file paths with correct workspace context",{operationCount:T.length,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})
3647
- for(let e=0;e<T.length;e++){const r=T[e],n=q[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(n.path,t)
3648
- T[e]={...r,path:o,fullPath:s}}}if(P.length>0&&M)try{await(0,h.validateRequestStatusForDocumentOperation)(M,s,y,a,"insert-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3649
- throw e}I=d.FileOperationPhase.RECORD_CREATION,a.incrementCounter("insert_lines_phase",1,{phase:I})
3650
- const $=[...T.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...P.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:A}=await d.createFileOperationRecords(C,M,t.projectId,v.recordType,j,{operationCount:_.length,fileOperations:T.length,documentOperations:P.length,operations:$,userComment:E},n,o,y,a,v.metricsPrefix,m)
3651
- if(k=A,b=A,I=v.fileOperationPhase,a.incrementCounter("insert_lines_phase",1,{phase:I}),T.length>0&&t.git)try{y.debug("[INSERT-LINES] Checking for user changes before insert operations")
3652
- const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"insert-lines",{requestId:M,taskId:C,workspaceManager:t.workspaceManager},y,a)
3653
- e.userChangesCommitted&&(y.debug("[INSERT-LINES] User changes committed before insert operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before insert-lines operation",{taskId:C,fileOperationsCount:T.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){y.debug("[INSERT-LINES] Pre-tool commit failed, continuing with insertions",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with insert operation",{taskId:C,fileOperationsCount:T.length,error:e instanceof Error?e.message:e+""})}y.debug("[INSERT-LINES] Proceeding with file operations",{fileCount:T.length})
3654
- const F=[]
3655
- let N=0,L=0,z=0
3656
- for(const e of T){const t={type:"file",path:e.path,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
3700
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleInsertLines=async function(e,n,o,s,i,a,m,y){const w=a.child({tool:"insert_lines"}),k=Date.now()
3701
+ let b,I,v=d.FileOperationPhase.VALIDATION
3702
+ const C={toolName:"insert-lines",operationName:"insert-lines",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"insert-lines",metricsPrefix:"insert_lines",successMessage:"Successfully inserted lines into files and documents",failureMessage:"Failed to insert lines into files and documents"}
3703
+ try{const _=d.validateArgs(e,l.InsertLinesSchema),{operations:E,comment:q}=_,{resolveActiveTaskId:S}=await Promise.resolve().then(t.bind(t,3451)),T=e.taskId||await S(n,o,a)||"untracked"
3704
+ if(w.info("Inserting lines into files and documents",{taskId:T,operationCount:E.length,comment:q}),!E||0===E.length)throw new u.ValidationError("At least one operation is required")
3705
+ const P=E.filter((e=>e.path)),j=E.filter((e=>e.documentId))
3706
+ w.info("Operation breakdown",{fileOperations:P.length,documentOperations:j.length})
3707
+ const R=[]
3708
+ for(const e of P){const{normalizedPath:t,fullPath:r}=d.validateAndNormalizePath(e.path,n)
3709
+ R.push({type:"file",path:t,fullPath:r,insertions:e.insertions})}const x=[]
3710
+ if(j.length>0&&!n.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
3711
+ for(const e of j)x.push({type:"document",documentId:e.documentId,insertions:e.insertions})
3712
+ if(x.length>0&&n.apiClient){const e=x.map((e=>e.documentId))
3713
+ try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,w,m,"insert-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3714
+ throw e}}v=d.FileOperationPhase.TASK_VALIDATION,m.incrementCounter("insert_lines_phase",1,{phase:v})
3715
+ const M=R.length>0?R[0].path:"document-operation",O=await d.validateTaskId(T,M,o,w,m,C.metricsPrefix),D=O?.requestId
3716
+ let $=null
3717
+ R.length>0&&D&&($=await d.validateWorkItemStates(T,R[0].path,o,i,n,w,m,C.metricsPrefix))
3718
+ let A={taskPromoted:!1,requestPromoted:!1}
3719
+ R.length>0&&D&&$&&(A=await d.autoPromoteTaskStatus(T,O.status,D,$.request?.status,R[0].path,o,i,w,m,C.metricsPrefix),A.taskPromoted&&w.info("Auto-promoted task to in_progress for insert-lines operation",{taskId:T,requestId:D,previousStatus:O.status,newStatus:A.newTaskStatus,triggeringOperation:"insert-lines"}))
3720
+ const F=await d.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:D,context:n,operation:"insert-lines",logger:w,metrics:m,metricsPrefix:C.metricsPrefix})
3721
+ if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
3722
+ throw Error(F.error)}if(R.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:R.length,workspaceBasePath:n.workspaceManager?.getCurrentContext(n.currentSessionId).basePath})
3723
+ for(let e=0;e<R.length;e++){const t=R[e],r=P[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(r.path,n)
3724
+ R[e]={...t,path:o,fullPath:s}}}if(x.length>0&&D)try{await(0,h.validateRequestStatusForDocumentOperation)(D,i,w,m,"insert-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3725
+ throw e}v=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("insert_lines_phase",1,{phase:v})
3726
+ const N=[...R.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...x.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:L}=await d.createFileOperationRecords(T,D,n.projectId,C.recordType,M,{operationCount:E.length,fileOperations:R.length,documentOperations:x.length,operations:N,userComment:q},o,s,w,m,C.metricsPrefix,y)
3727
+ if(b=L,I=L,v=C.fileOperationPhase,m.incrementCounter("insert_lines_phase",1,{phase:v}),R.length>0&&n.git)try{w.debug("[INSERT-LINES] Checking for user changes before insert operations")
3728
+ const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"insert-lines",{requestId:D,taskId:T,workspaceManager:n.workspaceManager},w,m)
3729
+ e.userChangesCommitted&&(w.debug("[INSERT-LINES] User changes committed before insert operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before insert-lines operation",{taskId:T,fileOperationsCount:R.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[INSERT-LINES] Pre-tool commit failed, continuing with insertions",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with insert operation",{taskId:T,fileOperationsCount:R.length,error:e instanceof Error?e.message:e+""})}w.debug("[INSERT-LINES] Proceeding with file operations",{fileCount:R.length})
3730
+ const z=[]
3731
+ let H=0,B=0,U=0
3732
+ for(const e of R){const t={type:"file",path:e.path,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
3657
3733
  try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
3658
3734
  const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.insertions)
3659
- t.insertions=s,t.successfulInsertions=s.filter((e=>e.success)).length,t.failedInsertions=s.filter((e=>!e.success)).length,t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulInsertions>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,z++,y.info("File updated successfully",{path:e.path,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),N+=t.failedInsertions,L+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedInsertions=e.insertions.length,N+=t.failedInsertions,y.error("File operation failed",{path:e.path,error:t.error})}F.push(t)}for(const e of P){const n={type:"document",documentId:e.documentId,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
3660
- try{const o=await t.documentFileManager.getDocumentAsFile(e.documentId),s=t.documentFileManager.getCachedDocumentInfo(e.documentId)
3661
- n.filename=s?.filename
3735
+ t.insertions=s,t.successfulInsertions=s.filter((e=>e.success)).length,t.failedInsertions=s.filter((e=>!e.success)).length,t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulInsertions>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,U++,w.info("File updated successfully",{path:e.path,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedInsertions=e.insertions.length,H+=t.failedInsertions,w.error("File operation failed",{path:e.path,error:t.error})}z.push(t)}for(const e of x){const t={type:"document",documentId:e.documentId,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
3736
+ try{const o=await n.documentFileManager.getDocumentAsFile(e.documentId),s=n.documentFileManager.getCachedDocumentInfo(e.documentId)
3737
+ t.filename=s?.filename
3662
3738
  const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.insertions)
3663
- n.insertions=l,n.successfulInsertions=l.filter((e=>e.success)).length,n.failedInsertions=l.filter((e=>!e.success)).length,n.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&n.successfulInsertions>0?(await c.default.writeFile(o,a,"utf8"),t.documentFileManager.markForSync(e.documentId),n.success=!0,z++,y.info("Document updated successfully",{documentId:e.documentId,filename:n.filename,successfulInsertions:n.successfulInsertions,failedInsertions:n.failedInsertions,linesAdded:n.totalLinesAdded})):0===n.failedInsertions&&(n.success=!0),N+=n.failedInsertions,L+=n.totalLinesAdded}catch(t){n.error=(0,f.getErrorMessage)(t),n.failedInsertions=e.insertions.length,N+=n.failedInsertions,y.error("Document operation failed",{documentId:e.documentId,error:n.error})}F.push(n)}if(P.length>0)try{for(const e of P){const r=F.find((t=>t.documentId===e.documentId))
3664
- r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){y.warn("Some documents may not have synced properly",{error:e})}const H=await d.handleMultiFileGitCommit(C,T,F,z,{operationType:"Insert lines",toolRecordId:b,successField:"successfulInsertions",logger:y,metrics:a,metricsPrefix:"insert_lines"},t),B=d.processMultiFileOperationResults(F,"successfulInsertions"),{successfulOperations:U,failedOperations:G,totalSuccessfulChanges:W,overallSuccess:V,successfulFiles:J,failedFiles:K}=B
3665
- try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+P[0]?.documentId,status:V?"completed":"failed",error:V?void 0:G+" operations failed",totalOperations:F.length,successfulFiles:J,failedFiles:K,operations:$,totalSuccessfulInsertions:W,totalFailedInsertions:N,totalLinesAdded:L,operationsWithChanges:z,processingTime:Date.now()-w,userComment:E,...T.length>0&&H.success&&H.commitHash&&{commitHash:H.commitHash,previousCommitHash:H.previousCommitHash||void 0}},note:V?`Line insertion completed: ${U}/${F.length} operations successful${T.length>0?" (committed to git)":""}`:`Line insertion partially failed: ${G}/${F.length} operations failed`})}catch(e){y.warn("Failed to update tool record",{recordError:e})}let Y="## Line Insertion Results\n\n"
3666
- if(t.workspaceManager&&(Y+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Y+="**Summary:**\n",Y+=`- **Files processed:** ${U+G}\n`,Y+=`- **Successful operations:** ${U}\n`,Y+=`- **Failed operations:** ${G}\n`,Y+=`- **Total insertions:** ${W} successful, ${N} failed\n`,Y+=`- **Total Lines Added:** ${L}\n`,Y+="\n",H.success&&H.commitHash&&(Y+="**Git Commit:**\n",Y+=`- **Commit Hash:** ${H.commitHash.substring(0,8)}\n`,Y+=`- **Files Committed:** ${H.filesCommitted.length}\n`,H.previousCommitHash&&(Y+=`- **Previous Commit:** ${H.previousCommitHash.substring(0,8)}\n`),Y+="\n"),D.lockAcquired&&D.lockedRequestId&&(Y+=`\u{1f512} **Locked request:** ${D.lockedRequestId}\n\n`),1===F.length){const e=F[0]
3667
- if(Y+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?Y+=`**File:** ${e.path}\n`:(Y+="**Document:** "+e.documentId,e.filename&&(Y+=` (${e.filename})`),Y+="\n"),e.error?Y+=`**Error:** ${e.error}\n`:(Y+=`**Insertions:** ${e.successfulInsertions} successful`,e.failedInsertions>0&&(Y+=`, ${e.failedInsertions} failed`),Y+="\n",Y+=`**Lines Added:** ${e.totalLinesAdded}\n`),e.insertions.some((e=>!e.success))){Y+="**Failed Insertion Details:**\n"
3739
+ t.insertions=l,t.successfulInsertions=l.filter((e=>e.success)).length,t.failedInsertions=l.filter((e=>!e.success)).length,t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulInsertions>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,U++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedInsertions=e.insertions.length,H+=t.failedInsertions,w.error("Document operation failed",{documentId:e.documentId,error:t.error})}z.push(t)}if(x.length>0)try{for(const e of x){const t=z.find((t=>t.documentId===e.documentId))
3740
+ t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const G=await d.handleMultiFileGitCommit(T,R,z,U,{operationType:"Insert lines",toolRecordId:I,successField:"successfulInsertions",logger:w,metrics:m,metricsPrefix:"insert_lines"},n),W=d.processMultiFileOperationResults(z,"successfulInsertions"),{successfulOperations:V,failedOperations:J,totalSuccessfulChanges:K,overallSuccess:Y,successfulFiles:Q,failedFiles:Z}=W
3741
+ try{await s.updateToolRecord(I,{metadata:{path:R.length>0?R[0].path:"document:"+x[0]?.documentId,status:Y?"completed":"failed",error:Y?void 0:J+" operations failed",totalOperations:z.length,successfulFiles:Q,failedFiles:Z,operations:N,totalSuccessfulInsertions:K,totalFailedInsertions:H,totalLinesAdded:B,operationsWithChanges:U,processingTime:Date.now()-k,userComment:q,...R.length>0&&G.success&&G.commitHash&&{commitHash:G.commitHash,previousCommitHash:G.previousCommitHash||void 0}},note:Y?`Line insertion completed: ${V}/${z.length} operations successful${R.length>0?" (committed to git)":""}`:`Line insertion partially failed: ${J}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let X="## Line Insertion Results\n\n"
3742
+ if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
3743
+ e.permanentBranch||(X+=`**Branch:** \`${e.branchName}\`\n\n`)}if(X+="**Summary:**\n",X+=`- **Files processed:** ${V+J}\n`,X+=`- **Successful operations:** ${V}\n`,X+=`- **Failed operations:** ${J}\n`,X+=`- **Total insertions:** ${K} successful, ${H} failed\n`,X+=`- **Total Lines Added:** ${B}\n`,X+="\n",G.success&&G.commitHash&&(X+="**Git Commit:**\n",X+=`- **Commit Hash:** ${G.commitHash.substring(0,8)}\n`,X+=`- **Files Committed:** ${G.filesCommitted.length}\n`,G.previousCommitHash&&(X+=`- **Previous Commit:** ${G.previousCommitHash.substring(0,8)}\n`),X+="\n"),F.lockAcquired&&F.lockedRequestId&&(n.workspaceManager?.getCurrentContext(n.currentSessionId)?.permanentBranch||(X+=`\u{1f512} **Locked request:** ${F.lockedRequestId}\n\n`)),1===z.length){const e=z[0]
3744
+ if(X+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?X+=`**File:** ${e.path}\n`:(X+="**Document:** "+e.documentId,e.filename&&(X+=` (${e.filename})`),X+="\n"),e.error?X+=`**Error:** ${e.error}\n`:(X+=`**Insertions:** ${e.successfulInsertions} successful`,e.failedInsertions>0&&(X+=`, ${e.failedInsertions} failed`),X+="\n",X+=`**Lines Added:** ${e.totalLinesAdded}\n`),e.insertions.some((e=>!e.success))){X+="**Failed Insertion Details:**\n"
3668
3745
  for(const t of e.insertions.filter((e=>!e.success))){const e="between"===t.type?`between lines ${t.afterLine} and ${t.beforeLine}`:`${t.type} line ${t.line}`
3669
- Y+=`- ${t.type} insertion ${e}: ${t.error}\n`}}}else{Y+="**Summary:**\n",Y+=`- **Total Operations:** ${F.length}\n`,Y+=`- **Successful:** ${U}\n`,Y+=`- **Failed:** ${G}\n`,Y+=`- **Total Insertions:** ${W} successful, ${N} failed\n`,Y+=`- **Total Lines Added:** ${L}\n\n`,Y+="**Detailed Results:**\n\n"
3670
- for(const e of F){if("file"===e.type?Y+=`### File: ${e.path}\n`:(Y+="### Document: "+e.documentId,e.filename&&(Y+=` (${e.filename})`),Y+="\n"),Y+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error?Y+=`- **Error:** ${e.error}\n`:(Y+=`- **Insertions:** ${e.successfulInsertions} successful`,e.failedInsertions>0&&(Y+=`, ${e.failedInsertions} failed`),Y+="\n",Y+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.insertions.some((e=>!e.success))){Y+="- **Failed Insertion Details:**\n"
3746
+ X+=`- ${t.type} insertion ${e}: ${t.error}\n`}}}else{X+="**Summary:**\n",X+=`- **Total Operations:** ${z.length}\n`,X+=`- **Successful:** ${V}\n`,X+=`- **Failed:** ${J}\n`,X+=`- **Total Insertions:** ${K} successful, ${H} failed\n`,X+=`- **Total Lines Added:** ${B}\n\n`,X+="**Detailed Results:**\n\n"
3747
+ for(const e of z){if("file"===e.type?X+=`### File: ${e.path}\n`:(X+="### Document: "+e.documentId,e.filename&&(X+=` (${e.filename})`),X+="\n"),X+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error?X+=`- **Error:** ${e.error}\n`:(X+=`- **Insertions:** ${e.successfulInsertions} successful`,e.failedInsertions>0&&(X+=`, ${e.failedInsertions} failed`),X+="\n",X+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.insertions.some((e=>!e.success))){X+="- **Failed Insertion Details:**\n"
3671
3748
  for(const t of e.insertions.filter((e=>!e.success))){const e="between"===t.type?`between lines ${t.afterLine} and ${t.beforeLine}`:`${t.type} line ${t.line}`
3672
- Y+=` - ${t.type} insertion ${e}: ${t.error}\n`}}Y+="\n"}}P.length>0&&(Y+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
3673
- const Q=Date.now()-w
3674
- return y.info("Insert lines operation completed",{duration:Q,success:V,totalOperations:F.length,successfulOperations:U,failedOperations:G}),a.incrementCounter("insert_lines_total",1,{success:V}),{content:[{type:"text",text:Y}],isError:!V}}catch(t){const r=Date.now()-w
3675
- if(y.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:I}),b)try{await o.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,f.getErrorMessage)(t),phase:I,duration:r,userComment:e?.comment},note:"Line insertion failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("insert_lines_errors",1,{phase:I}),{content:[{type:"text",text:"\u274c **Insert Lines Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
3749
+ X+=` - ${t.type} insertion ${e}: ${t.error}\n`}}X+="\n"}}x.length>0&&(X+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
3750
+ const ee=Date.now()-k
3751
+ return w.info("Insert lines operation completed",{duration:ee,success:Y,totalOperations:z.length,successfulOperations:V,failedOperations:J}),m.incrementCounter("insert_lines_total",1,{success:Y}),{content:[{type:"text",text:X}],isError:!Y}}catch(t){const r=Date.now()-k
3752
+ if(w.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),I)try{await s.updateToolRecord(I,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,f.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"Line insertion failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return m.incrementCounter("insert_lines_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Insert Lines Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
3676
3753
  const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824),m=t(3255)},6539(e,exports,t){"use strict"
3677
3754
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientFactory=void 0
3678
3755
  const r=t(1253),n=t(5681),o=t(6595),s=t(3895),i=t(6848),a=t(6153),c=t(4710),l=t(6975),d=t(1887),u=t(1666),h=t(8824),g=t(9884),p=t(2968),f=t(922)
@@ -3698,10 +3775,10 @@ const{ProjectRegistry,ProjectFileSystem,ProjectSynchronizer}=await t.e(478).then
3698
3775
  _.setProjectSynchronizer(n),m.info("ProjectSynchronizer created and connected to ProjectClient")}catch(e){const t="Failed to create required ProjectSynchronizer components: "+(0,h.getErrorMessage)(e)
3699
3776
  throw m.error(t,{error:e instanceof Error?e.stack:e+""}),Error(t)}const R=new o.ApiClient(I,_,E,q,S,T,P,j,m)
3700
3777
  m.info("API client initialized with specialized clients"),v?(R.setAuthToken(v),m.info("Auth token set on ApiClient during creation",{hasToken:!0,tokenLength:v.length})):m.warn("No auth token available during ApiClient creation",{info:"Client will need to authenticate before making requests"})
3701
- const M=b.verifyAllClients()
3702
- M.success?m.info("Token consistency verified across all clients"):m.error(`Token inconsistency detected in ${M.failedClients.length} clients: ${M.failedClients.join(", ")}`)
3703
- const x=R.getAuthToken()
3704
- return v&&!x?(m.error("CRITICAL: ApiClient token was not set properly!"),R.setAuthToken(v)):x&&m.info("ApiClient token verified",{tokenLength:x.length,matches:x===v}),m.info("API client creation completed successfully"),R}}},6540(e,exports){"use strict"
3778
+ const x=b.verifyAllClients()
3779
+ x.success?m.info("Token consistency verified across all clients"):m.error(`Token inconsistency detected in ${x.failedClients.length} clients: ${x.failedClients.join(", ")}`)
3780
+ const M=R.getAuthToken()
3781
+ return v&&!M?(m.error("CRITICAL: ApiClient token was not set properly!"),R.setAuthToken(v)):M&&m.info("ApiClient token verified",{tokenLength:M.length,matches:M===v}),m.info("API client creation completed successfully"),R}}},6540(e,exports){"use strict"
3705
3782
  var t
3706
3783
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.LogLevel=void 0,function(e){e.ERROR="error",e.WARN="warn",e.INFO="info",e.DEBUG="debug"}(t||(exports.LogLevel=t={}))},6552(e,exports,t){"use strict"
3707
3784
  async function r(){const e=new o.StdioServerTransport,t=(0,l.setupParentProcessDetection)((()=>{k.info("Parent process gone or orphan detected. Shutting down."),process.exit(0)}))
@@ -3773,56 +3850,57 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
3773
3850
  var t={}
3774
3851
  if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
3775
3852
  return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
3776
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceLines=async function(e,t,n,o,s,i,a,m){const w=i.child({tool:"replace_lines"}),k=Date.now()
3777
- let b,I,v=d.FileOperationPhase.VALIDATION
3778
- const C={toolName:"replace-lines",operationName:"replace-lines",fileOperationPhase:d.FileOperationPhase.STRING_REPLACEMENT,recordType:"replace-lines",metricsPrefix:"replace_lines",successMessage:"Successfully replaced lines in files and documents",failureMessage:"Failed to replace lines in files and documents"}
3779
- try{const i=d.validateArgs(e,l.ReplaceLinesSchema),{taskId:_,operations:E,comment:q}=i
3780
- if(w.info("Replacing lines in files and documents",{taskId:_,operationCount:E.length,comment:q}),!E||0===E.length)throw new u.ValidationError("At least one operation is required")
3781
- const S=E.filter((e=>e.path)),T=E.filter((e=>e.documentId))
3782
- w.info("Operation breakdown",{fileOperations:S.length,documentOperations:T.length})
3783
- const P=[]
3784
- for(const e of S){const{normalizedPath:r,fullPath:n}=d.validateAndNormalizePath(e.path,t)
3785
- P.push({type:"file",path:r,fullPath:n,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})}const j=[]
3786
- if(T.length>0&&!t.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
3787
- for(const e of T)j.push({type:"document",documentId:e.documentId,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})
3788
- if(j.length>0&&t.apiClient){const e=j.map((e=>e.documentId))
3789
- try{await(0,p.ensureDocumentsNotLocked)(e,t.apiClient,w,a,"replace-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3790
- throw e}}v=d.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("replace_lines_phase",1,{phase:v})
3791
- const R=P.length>0?P[0].path:"document-operation",M=await d.validateTaskId(_,R,n,w,a,C.metricsPrefix),x=M?.requestId
3792
- let O=null
3793
- P.length>0&&x&&(O=await d.validateWorkItemStates(_,P[0].path,n,s,t,w,a,C.metricsPrefix))
3794
- let D={taskPromoted:!1,requestPromoted:!1}
3795
- P.length>0&&x&&O&&(D=await d.autoPromoteTaskStatus(_,M.status,x,O.request?.status,P[0].path,n,s,w,a,C.metricsPrefix),D.taskPromoted&&w.info("Auto-promoted task to in_progress for replace-lines operation",{taskId:_,requestId:x,previousStatus:M.status,newStatus:D.newTaskStatus,triggeringOperation:"replace-lines"}))
3796
- const $=await d.ensureCorrectWorkspaceContext({taskPromoted:D.taskPromoted,requestId:x,context:t,operation:"replace-lines",logger:w,metrics:a,metricsPrefix:C.metricsPrefix})
3797
- if(!$.success){if($.isLockConflict)return{content:[{type:"text",text:"\u274c "+$.error}],isError:!0}
3798
- throw Error($.error)}if(P.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:P.length,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})
3799
- for(let e=0;e<P.length;e++){const r=P[e],n=S[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(n.path,t)
3800
- P[e]={...r,path:o,fullPath:s}}}if(j.length>0&&x)try{await(0,h.validateRequestStatusForDocumentOperation)(x,s,w,a,"replace-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3801
- throw e}v=d.FileOperationPhase.RECORD_CREATION,a.incrementCounter("replace_lines_phase",1,{phase:v})
3802
- const A=[...P.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...j.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:F}=await d.createFileOperationRecords(_,x,t.projectId,C.recordType,R,{operationCount:E.length,fileOperations:P.length,documentOperations:j.length,operations:A,userComment:q},n,o,w,a,C.metricsPrefix,m)
3803
- if(b=F,I=F,v=C.fileOperationPhase,a.incrementCounter("replace_lines_phase",1,{phase:v}),P.length>0&&t.git)try{w.debug("[REPLACE-LINES] Checking for user changes before replace operations")
3804
- const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"replace-lines",{requestId:x,taskId:_,workspaceManager:t.workspaceManager},w,a)
3805
- e.userChangesCommitted&&(w.debug("[REPLACE-LINES] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before replace-lines operation",{taskId:_,fileOperationsCount:P.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[REPLACE-LINES] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:_,fileOperationsCount:P.length,error:e instanceof Error?e.message:e+""})}w.debug("[REPLACE-LINES] Proceeding with file operations",{fileCount:P.length})
3806
- const N=[]
3807
- let L=0,z=0,H=0,B=0
3808
- for(const e of P){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
3853
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceLines=async function(e,n,o,s,i,a,m,w){const k=a.child({tool:"replace_lines"}),b=Date.now()
3854
+ let I,v,C=d.FileOperationPhase.VALIDATION
3855
+ const _={toolName:"replace-lines",operationName:"replace-lines",fileOperationPhase:d.FileOperationPhase.STRING_REPLACEMENT,recordType:"replace-lines",metricsPrefix:"replace_lines",successMessage:"Successfully replaced lines in files and documents",failureMessage:"Failed to replace lines in files and documents"}
3856
+ try{const E=d.validateArgs(e,l.ReplaceLinesSchema),{operations:q,comment:S}=E,{resolveActiveTaskId:T}=await Promise.resolve().then(t.bind(t,3451)),P=e.taskId||await T(n,o,a)||"untracked"
3857
+ if(k.info("Replacing lines in files and documents",{taskId:P,operationCount:q.length,comment:S}),!q||0===q.length)throw new u.ValidationError("At least one operation is required")
3858
+ const j=q.filter((e=>e.path)),R=q.filter((e=>e.documentId))
3859
+ k.info("Operation breakdown",{fileOperations:j.length,documentOperations:R.length})
3860
+ const x=[]
3861
+ for(const e of j){const{normalizedPath:t,fullPath:r}=d.validateAndNormalizePath(e.path,n)
3862
+ x.push({type:"file",path:t,fullPath:r,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})}const M=[]
3863
+ if(R.length>0&&!n.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
3864
+ for(const e of R)M.push({type:"document",documentId:e.documentId,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})
3865
+ if(M.length>0&&n.apiClient){const e=M.map((e=>e.documentId))
3866
+ try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,k,m,"replace-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3867
+ throw e}}C=d.FileOperationPhase.TASK_VALIDATION,m.incrementCounter("replace_lines_phase",1,{phase:C})
3868
+ const O=x.length>0?x[0].path:"document-operation",D=await d.validateTaskId(P,O,o,k,m,_.metricsPrefix),$=D?.requestId
3869
+ let A=null
3870
+ x.length>0&&$&&(A=await d.validateWorkItemStates(P,x[0].path,o,i,n,k,m,_.metricsPrefix))
3871
+ let F={taskPromoted:!1,requestPromoted:!1}
3872
+ x.length>0&&$&&A&&(F=await d.autoPromoteTaskStatus(P,D.status,$,A.request?.status,x[0].path,o,i,k,m,_.metricsPrefix),F.taskPromoted&&k.info("Auto-promoted task to in_progress for replace-lines operation",{taskId:P,requestId:$,previousStatus:D.status,newStatus:F.newTaskStatus,triggeringOperation:"replace-lines"}))
3873
+ const N=await d.ensureCorrectWorkspaceContext({taskPromoted:F.taskPromoted,requestId:$,context:n,operation:"replace-lines",logger:k,metrics:m,metricsPrefix:_.metricsPrefix})
3874
+ if(!N.success){if(N.isLockConflict)return{content:[{type:"text",text:"\u274c "+N.error}],isError:!0}
3875
+ throw Error(N.error)}if(x.length>0){k.debug("Re-validating file paths with correct workspace context",{operationCount:x.length,workspaceBasePath:n.workspaceManager?.getCurrentContext(n.currentSessionId).basePath})
3876
+ for(let e=0;e<x.length;e++){const t=x[e],r=j[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(r.path,n)
3877
+ x[e]={...t,path:o,fullPath:s}}}if(M.length>0&&$)try{await(0,h.validateRequestStatusForDocumentOperation)($,i,k,m,"replace-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
3878
+ throw e}C=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("replace_lines_phase",1,{phase:C})
3879
+ const L=[...x.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:z}=await d.createFileOperationRecords(P,$,n.projectId,_.recordType,O,{operationCount:q.length,fileOperations:x.length,documentOperations:M.length,operations:L,userComment:S},o,s,k,m,_.metricsPrefix,w)
3880
+ if(I=z,v=z,C=_.fileOperationPhase,m.incrementCounter("replace_lines_phase",1,{phase:C}),x.length>0&&n.git)try{k.debug("[REPLACE-LINES] Checking for user changes before replace operations")
3881
+ const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"replace-lines",{requestId:$,taskId:P,workspaceManager:n.workspaceManager},k,m)
3882
+ e.userChangesCommitted&&(k.debug("[REPLACE-LINES] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),k.info("User changes committed before replace-lines operation",{taskId:P,fileOperationsCount:x.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){k.debug("[REPLACE-LINES] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),k.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:P,fileOperationsCount:x.length,error:e instanceof Error?e.message:e+""})}k.debug("[REPLACE-LINES] Proceeding with file operations",{fileCount:x.length})
3883
+ const H=[]
3884
+ let B=0,U=0,G=0,W=0
3885
+ for(const e of x){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
3809
3886
  try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
3810
3887
  const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.replacements)
3811
- t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,t.totalLinesReplaced=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulReplacements>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,B++,w.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),L+=t.failedReplacements,z+=t.totalLinesReplaced,H+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedReplacements=e.replacements.length,L+=t.failedReplacements,w.error("File operation failed",{path:e.path,error:t.error})}N.push(t)}for(const e of j){const n={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
3812
- try{const o=await t.documentFileManager.getDocumentAsFile(e.documentId),s=t.documentFileManager.getCachedDocumentInfo(e.documentId)
3813
- n.filename=s?.filename
3888
+ t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,t.totalLinesReplaced=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulReplacements>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,W++,k.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedReplacements=e.replacements.length,B+=t.failedReplacements,k.error("File operation failed",{path:e.path,error:t.error})}H.push(t)}for(const e of M){const t={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
3889
+ try{const o=await n.documentFileManager.getDocumentAsFile(e.documentId),s=n.documentFileManager.getCachedDocumentInfo(e.documentId)
3890
+ t.filename=s?.filename
3814
3891
  const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.replacements)
3815
- n.replacements=l,n.successfulReplacements=l.filter((e=>e.success)).length,n.failedReplacements=l.filter((e=>!e.success)).length,n.totalLinesReplaced=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),n.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&n.successfulReplacements>0?(await c.default.writeFile(o,a,"utf8"),t.documentFileManager.markForSync(e.documentId),n.success=!0,B++,w.info("Document updated successfully",{documentId:e.documentId,filename:n.filename,successfulReplacements:n.successfulReplacements,failedReplacements:n.failedReplacements,linesReplaced:n.totalLinesReplaced,linesAdded:n.totalLinesAdded})):0===n.failedReplacements&&(n.success=!0),L+=n.failedReplacements,z+=n.totalLinesReplaced,H+=n.totalLinesAdded}catch(t){n.error=(0,f.getErrorMessage)(t),n.failedReplacements=e.replacements.length,L+=n.failedReplacements,w.error("Document operation failed",{documentId:e.documentId,error:n.error})}N.push(n)}if(j.length>0)try{for(const e of j){const r=N.find((t=>t.documentId===e.documentId))
3816
- r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const U=await d.handleMultiFileGitCommit(_,P,N,B,{operationType:"Replace lines",toolRecordId:I,successField:"successfulReplacements",logger:w,metrics:a,metricsPrefix:"replace_lines"},t),G=d.processMultiFileOperationResults(N,"successfulReplacements"),{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q}=G
3817
- try{await o.updateToolRecord(I,{metadata:{path:P.length>0?P[0].path:"document:"+j[0]?.documentId,status:K?"completed":"failed",error:K?void 0:V+" operations failed",totalOperations:N.length,successfulFiles:Y,failedFiles:Q,operations:A,totalSuccessfulReplacements:J,totalFailedReplacements:L,totalLinesReplaced:z,totalLinesAdded:H,operationsWithChanges:B,processingTime:Date.now()-k,userComment:q,...P.length>0&&U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}},note:K?`Line replacement completed: ${W}/${N.length} operations successful${P.length>0?" (committed to git)":""}`:`Line replacement partially failed: ${V}/${N.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let Z="## Line Replacement Results\n\n"
3818
- if(t.workspaceManager&&(Z+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Z+="**Summary:**\n",Z+=`- **Files processed:** ${W+V}\n`,Z+=`- **Successful operations:** ${W}\n`,Z+=`- **Failed operations:** ${V}\n`,Z+=`- **Total replacements:** ${J} successful, ${L} failed\n`,Z+=`- **Total Lines Replaced:** ${z}\n`,H>0&&(Z+=`- **Total Lines Added:** ${H}\n`),Z+="\n",U.success&&U.commitHash&&(Z+="**Git Commit:**\n",Z+=`- **Commit Hash:** ${U.commitHash.substring(0,8)}\n`,Z+=`- **Files Committed:** ${U.filesCommitted.length}\n`,U.previousCommitHash&&(Z+=`- **Previous Commit:** ${U.previousCommitHash.substring(0,8)}\n`),Z+="\n"),$.lockAcquired&&$.lockedRequestId&&(Z+=`\u{1f512} **Locked request:** ${$.lockedRequestId}\n\n`),1===N.length){const e=N[0]
3819
- if(Z+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?Z+=`**File:** ${e.path}\n`:(Z+="**Document:** "+e.documentId,e.filename&&(Z+=` (${e.filename})`),Z+="\n"),e.error?Z+=`**Error:** ${e.error}\n`:(Z+=`**Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(Z+=`, ${e.failedReplacements} failed`),Z+="\n",Z+=`**Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(Z+=`**Lines Added:** ${e.totalLinesAdded}\n`)),e.replacements.some((e=>!e.success))){Z+="**Failed Replacement Details:**\n"
3820
- for(const t of e.replacements.filter((e=>!e.success)))Z+=`- Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}}else{Z+="**Summary:**\n",Z+=`- **Total Operations:** ${N.length}\n`,Z+=`- **Successful:** ${W}\n`,Z+=`- **Failed:** ${V}\n`,Z+=`- **Total Replacements:** ${J} successful, ${L} failed\n`,Z+=`- **Total Lines Replaced:** ${z}\n`,H>0&&(Z+=`- **Total Lines Added:** ${H}\n`),Z+="\n",Z+="**Detailed Results:**\n\n"
3821
- for(const e of N){if("file"===e.type?Z+=`### File: ${e.path}\n`:(Z+="### Document: "+e.documentId,e.filename&&(Z+=` (${e.filename})`),Z+="\n"),Z+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error&&(Z+=`- **Error:** ${e.error}\n`),Z+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(Z+=`, ${e.failedReplacements} failed`),Z+="\n",Z+=`- **Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(Z+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.replacements.some((e=>!e.success))){Z+="- **Failed Replacement Details:**\n"
3822
- for(const t of e.replacements.filter((e=>!e.success)))Z+=` - Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}Z+="\n"}}j.length>0&&(Z+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
3823
- const X=Date.now()-k
3824
- return w.info("Replace lines operation completed",{duration:X,success:K,totalOperations:N.length,successfulOperations:W,failedOperations:V}),a.incrementCounter("replace_lines_total",1,{success:K}),{content:[{type:"text",text:Z}],isError:!K}}catch(t){const r=Date.now()-k
3825
- if(w.error("Replace lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),I)try{await o.updateToolRecord(I,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,f.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"Line replacement failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("replace_lines_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Replace Lines Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
3892
+ t.replacements=l,t.successfulReplacements=l.filter((e=>e.success)).length,t.failedReplacements=l.filter((e=>!e.success)).length,t.totalLinesReplaced=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulReplacements>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,W++,k.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedReplacements=e.replacements.length,B+=t.failedReplacements,k.error("Document operation failed",{documentId:e.documentId,error:t.error})}H.push(t)}if(M.length>0)try{for(const e of M){const t=H.find((t=>t.documentId===e.documentId))
3893
+ t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){k.warn("Some documents may not have synced properly",{error:e})}const V=await d.handleMultiFileGitCommit(P,x,H,W,{operationType:"Replace lines",toolRecordId:v,successField:"successfulReplacements",logger:k,metrics:m,metricsPrefix:"replace_lines"},n),J=d.processMultiFileOperationResults(H,"successfulReplacements"),{successfulOperations:K,failedOperations:Y,totalSuccessfulChanges:Q,overallSuccess:Z,successfulFiles:X,failedFiles:ee}=J
3894
+ try{await s.updateToolRecord(v,{metadata:{path:x.length>0?x[0].path:"document:"+M[0]?.documentId,status:Z?"completed":"failed",error:Z?void 0:Y+" operations failed",totalOperations:H.length,successfulFiles:X,failedFiles:ee,operations:L,totalSuccessfulReplacements:Q,totalFailedReplacements:B,totalLinesReplaced:U,totalLinesAdded:G,operationsWithChanges:W,processingTime:Date.now()-b,userComment:S,...x.length>0&&V.success&&V.commitHash&&{commitHash:V.commitHash,previousCommitHash:V.previousCommitHash||void 0}},note:Z?`Line replacement completed: ${K}/${H.length} operations successful${x.length>0?" (committed to git)":""}`:`Line replacement partially failed: ${Y}/${H.length} operations failed`})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let te="## Line Replacement Results\n\n"
3895
+ if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
3896
+ e.permanentBranch||(te+=`**Branch:** \`${e.branchName}\`\n\n`)}if(te+="**Summary:**\n",te+=`- **Files processed:** ${K+Y}\n`,te+=`- **Successful operations:** ${K}\n`,te+=`- **Failed operations:** ${Y}\n`,te+=`- **Total replacements:** ${Q} successful, ${B} failed\n`,te+=`- **Total Lines Replaced:** ${U}\n`,G>0&&(te+=`- **Total Lines Added:** ${G}\n`),te+="\n",V.success&&V.commitHash&&(te+="**Git Commit:**\n",te+=`- **Commit Hash:** ${V.commitHash.substring(0,8)}\n`,te+=`- **Files Committed:** ${V.filesCommitted.length}\n`,V.previousCommitHash&&(te+=`- **Previous Commit:** ${V.previousCommitHash.substring(0,8)}\n`),te+="\n"),N.lockAcquired&&N.lockedRequestId&&(n.workspaceManager?.getCurrentContext(n.currentSessionId)?.permanentBranch||(te+=`\u{1f512} **Locked request:** ${N.lockedRequestId}\n\n`)),1===H.length){const e=H[0]
3897
+ if(te+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?te+=`**File:** ${e.path}\n`:(te+="**Document:** "+e.documentId,e.filename&&(te+=` (${e.filename})`),te+="\n"),e.error?te+=`**Error:** ${e.error}\n`:(te+=`**Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(te+=`, ${e.failedReplacements} failed`),te+="\n",te+=`**Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(te+=`**Lines Added:** ${e.totalLinesAdded}\n`)),e.replacements.some((e=>!e.success))){te+="**Failed Replacement Details:**\n"
3898
+ for(const t of e.replacements.filter((e=>!e.success)))te+=`- Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}}else{te+="**Summary:**\n",te+=`- **Total Operations:** ${H.length}\n`,te+=`- **Successful:** ${K}\n`,te+=`- **Failed:** ${Y}\n`,te+=`- **Total Replacements:** ${Q} successful, ${B} failed\n`,te+=`- **Total Lines Replaced:** ${U}\n`,G>0&&(te+=`- **Total Lines Added:** ${G}\n`),te+="\n",te+="**Detailed Results:**\n\n"
3899
+ for(const e of H){if("file"===e.type?te+=`### File: ${e.path}\n`:(te+="### Document: "+e.documentId,e.filename&&(te+=` (${e.filename})`),te+="\n"),te+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error&&(te+=`- **Error:** ${e.error}\n`),te+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(te+=`, ${e.failedReplacements} failed`),te+="\n",te+=`- **Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(te+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.replacements.some((e=>!e.success))){te+="- **Failed Replacement Details:**\n"
3900
+ for(const t of e.replacements.filter((e=>!e.success)))te+=` - Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}te+="\n"}}M.length>0&&(te+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
3901
+ const re=Date.now()-b
3902
+ return k.info("Replace lines operation completed",{duration:re,success:Z,totalOperations:H.length,successfulOperations:K,failedOperations:Y}),m.incrementCounter("replace_lines_total",1,{success:Z}),{content:[{type:"text",text:te}],isError:!Z}}catch(t){const r=Date.now()-b
3903
+ if(k.error("Replace lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:C}),v)try{await s.updateToolRecord(v,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,f.getErrorMessage)(t),phase:C,duration:r,userComment:e?.comment},note:"Line replacement failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return m.incrementCounter("replace_lines_errors",1,{phase:C}),{content:[{type:"text",text:"\u274c **Replace Lines Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
3826
3904
  const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824),m=t(3255),y=t(9470)},6688(e,exports,t){"use strict"
3827
3905
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.sessionIdentity=void 0
3828
3906
  const r=t(9896),n=t(6928)
@@ -3908,8 +3986,8 @@ r.setProjectId(y)
3908
3986
  try{const P=await f.getTask(g)
3909
3987
  s.info("Raw task response data",{responseDataType:typeof P,isArray:Array.isArray(P),hasData:null!=P,properties:P&&"object"==typeof P?Object.keys(P):[]}),w=(0,l.extractDataFromResponse)(P,{logger:s,operationName:"getTask",defaultValue:{id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}),s.info("Found task: "+w.title)}catch(j){s.warn("Could not fetch task information: "+(0,u.getErrorMessage)(j)),w={id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}let k=[]
3910
3988
  try{const R=await m.getToolRecordsByTaskId(g)
3911
- if(s.info("Raw records response data",{responseDataType:typeof R,isArray:Array.isArray(R),hasData:null!=R,properties:R&&"object"==typeof R?Object.keys(R):[]}),k=(0,l.extractArrayFromResponse)(R,{logger:s,operationName:"searchRecords",defaultValue:[]}),k.length>0&&s.info("First record summary:",{id:k[0].id,type:k[0].type,hasMetadata:!!k[0].metadata,hasCommitHash:!!k[0].metadata?.commitHash}),s.info(`Extracted ${k.length} records for task ${g}`),k.length>0){const M={}
3912
- k.forEach((e=>{M[e.type]=(M[e.type]||0)+1})),s.info("Record type distribution:",M)}}catch(x){s.warn("Error fetching records for task "+g,{error:(0,u.getErrorMessage)(x)}),k=[]}if(0===k.length)return h({success:!0,recordCount:0}),{content:[{type:"text",text:`No records found for task ${g}.`}]}
3989
+ if(s.info("Raw records response data",{responseDataType:typeof R,isArray:Array.isArray(R),hasData:null!=R,properties:R&&"object"==typeof R?Object.keys(R):[]}),k=(0,l.extractArrayFromResponse)(R,{logger:s,operationName:"searchRecords",defaultValue:[]}),k.length>0&&s.info("First record summary:",{id:k[0].id,type:k[0].type,hasMetadata:!!k[0].metadata,hasCommitHash:!!k[0].metadata?.commitHash}),s.info(`Extracted ${k.length} records for task ${g}`),k.length>0){const x={}
3990
+ k.forEach((e=>{x[e.type]=(x[e.type]||0)+1})),s.info("Record type distribution:",x)}}catch(M){s.warn("Error fetching records for task "+g,{error:(0,u.getErrorMessage)(M)}),k=[]}if(0===k.length)return h({success:!0,recordCount:0}),{content:[{type:"text",text:`No records found for task ${g}.`}]}
3913
3991
  function b(e){const t=new Map,r=new Map,n=[]
3914
3992
  for(const o of e)if("move-file"===o.type&&o.metadata){const e=o.metadata.source||o.metadata.oldPath,s=o.metadata.destination||o.metadata.newPath
3915
3993
  if(e&&s){const i={source:e,destination:s,recordId:o.id,timestamp:o.createdAt,type:"move-file"}
@@ -4006,9 +4084,9 @@ let S=0,T=!1
4006
4084
  if(p){for(const Te of _.values())Te.hasDiff&&Te.diffText&&(S+=Te.diffText.split("\n").length)
4007
4085
  T=S>q,s.info(`Total diff size: ${S} lines (limit: ${q} lines)`),s.info(`Diffs ${T?"will be limited":"will be shown"} based on size`)}if(E+="## Summary\n",E+=`- **Files Modified**: ${C.size}\n`,E+=`- **Total File Operations**: ${v.length}\n`,E+="- **What's Shown**: For existing files, comparing state before task started with final state.\n",E+=" For files created during task, showing the entire file as created.\n",T?(E+=`- **Diff Display**: Limited (total diff size of ${S} lines exceeds limit of ${q} lines)\n`,E+=" Use file-history tool with individual files to see detailed changes\n\n"):E+=`- **Diff Display**: ${p?"Enabled":"Disabled"} (use showDiff=${!p} to ${p?"hide":"show"} diffs)\n\n`,I.allMoves.length>0){E+="## Move Operations\n\n",E+=`Detected ${I.allMoves.length} file move operation(s):\n\n`
4008
4086
  for(const Pe of I.allMoves)E+=`- **${Pe.source}** \u2192 **${Pe.destination}**\n`,E+=` - Operation: ${Pe.type}\n`,E+=` - Timestamp: ${new Date(Pe.timestamp).toLocaleString()}\n`,E+=` - Record ID: ${Pe.recordId}\n\n`}E+="## Modified Files\n\n"
4009
- for(const[je,Re]of _.entries()){const{normalizedPath:Me,fullPath:xe}=d.validateAndNormalizePath(je,t)
4087
+ for(const[je,Re]of _.entries()){const{normalizedPath:xe,fullPath:Me}=d.validateAndNormalizePath(je,t)
4010
4088
  let Oe=!1
4011
- try{await a.access(xe),Oe=!0}catch{}E+=`### ${je} ${Oe?"":"(Deleted)"}\n\n`
4089
+ try{await a.access(Me),Oe=!0}catch{}E+=`### ${je} ${Oe?"":"(Deleted)"}\n\n`
4012
4090
  const De=new Date(Re.firstChange.timestamp).toLocaleString(),$e=new Date(Re.lastChange.timestamp).toLocaleString()
4013
4091
  E+=`**First Change**: ${De}\n`,E+=`**Last Change**: ${$e}\n`,"pre-task"===Re.firstChange.status&&Re.firstChange.commitHash?E+=`**Pre-Task Commit**: ${Re.firstChange.commitHash.substring(0,8)}\n`:Re.firstChange.commitHash&&(E+=`**File Created During Task**: ${Re.firstChange.commitHash.substring(0,8)}\n`),Re.lastChange.commitHash&&(E+=`**Final Commit**: ${Re.lastChange.commitHash.substring(0,8)}\n`)
4014
4092
  const Ae=I.sourceToMove.get(je),Fe=I.destToMove.get(je)
@@ -4141,11 +4219,11 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
4141
4219
  var t={}
4142
4220
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
4143
4221
  return o(t,e),t})
4144
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=function(e,t,r={}){try{const n=a.join(process.env.HOME||"/tmp",".alchemy_lab"),o=a.join(n,"session-identity.log")
4222
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=function(e,t,r={}){try{const n=a.join(c.homedir(),".alchemy_lab"),o=a.join(n,"session-identity.log")
4145
4223
  i.existsSync(n)||i.mkdirSync(n,{recursive:!0})
4146
- const s=(new Date).toISOString(),c=Object.keys(r).length?" "+JSON.stringify(r):""
4147
- i.appendFileSync(o,`[${s}] ${e} | ${t}${c}\n`)}catch(e){}}
4148
- const i=s(t(9896)),a=s(t(6928))},7334(e,exports,t){"use strict"
4224
+ const s=(new Date).toISOString(),l=Object.keys(r).length?" "+JSON.stringify(r):""
4225
+ i.appendFileSync(o,`[${s}] ${e} | ${t}${l}\n`)}catch(e){}}
4226
+ const i=s(t(9896)),a=s(t(6928)),c=s(t(857))},7334(e,exports,t){"use strict"
4149
4227
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateRequest=async function(e,t,c,l,d,u,h){const g=l.child({tool:"create_request"})
4150
4228
  g.info("Creating new request",{args:e})
4151
4229
  const p=d.startTimer("tool_handler_duration")
@@ -4198,35 +4276,35 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
4198
4276
  var t={}
4199
4277
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
4200
4278
  return o(t,e),t})
4201
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,t,r,n,o,s,h,g){const p=s.child({tool:"modify_file"})
4202
- try{const s=a.validateArgs(e,i.ModifyFileSchema),{taskId:u,operations:f,comment:m}=s
4203
- p.info("Processing modify-file operations",{taskId:u,operationCount:f.length,comment:m})
4204
- const y=[],w=[],k=[],b=[],I=[]
4205
- for(const e of f){const t={path:e.path,documentId:e.documentId}
4206
- switch(e.operationType){case"replace-string":y.push({...t,replacements:e.replaceString.replacements,mode:e.replaceString.mode})
4279
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,r,n,o,s,h,g,p){const f=h.child({tool:"modify_file"})
4280
+ try{const u=a.validateArgs(e,i.ModifyFileSchema),{operations:m,comment:y}=u,{resolveActiveTaskId:w}=await Promise.resolve().then(t.bind(t,3451)),k=e.taskId||await w(r,n,h)||"untracked"
4281
+ f.info("Processing modify-file operations",{taskId:k,operationCount:m.length,comment:y})
4282
+ const b=[],I=[],v=[],C=[],_=[]
4283
+ for(const e of m){const t={path:e.path,documentId:e.documentId}
4284
+ switch(e.operationType){case"replace-string":b.push({...t,replacements:e.replaceString.replacements,mode:e.replaceString.mode})
4207
4285
  break
4208
- case"insert-lines":w.push({...t,insertions:e.insertLines.insertions})
4286
+ case"insert-lines":I.push({...t,insertions:e.insertLines.insertions})
4209
4287
  break
4210
- case"replace-lines":k.push({...t,replacements:e.replaceLines.replacements})
4288
+ case"replace-lines":v.push({...t,replacements:e.replaceLines.replacements})
4211
4289
  break
4212
- case"delete-string":b.push({...t,replacements:e.deleteString.patterns.map((e=>({old_str:e,new_str:""}))),mode:e.deleteString.mode||"all"})
4290
+ case"delete-string":C.push({...t,replacements:e.deleteString.patterns.map((e=>({old_str:e,new_str:""}))),mode:e.deleteString.mode||"all"})
4213
4291
  break
4214
- case"delete-lines":I.push({...t,lines:e.deleteLines.lines})}}const v=[]
4215
- if(y.length>0){p.info("Routing to replace-strings handler",{operationCount:y.length})
4216
- const e=await(0,c.handleReplaceStrings)({taskId:u,operations:y,comment:m+" [via modify-file: replace-string]"},t,r,n,o,p,h,g)
4217
- v.push({type:"replace-string",result:e})}if(w.length>0){p.info("Routing to insert-lines handler",{operationCount:w.length})
4218
- const e=await(0,l.handleInsertLines)({taskId:u,operations:w,comment:m+" [via modify-file: insert-lines]"},t,r,n,o,p,h,g)
4219
- v.push({type:"insert-lines",result:e})}if(k.length>0){p.info("Routing to replace-lines handler",{operationCount:k.length})
4220
- const e=await(0,d.handleReplaceLines)({taskId:u,operations:k,comment:m+" [via modify-file: replace-lines]"},t,r,n,o,p,h,g)
4221
- v.push({type:"replace-lines",result:e})}if(b.length>0){p.info("Routing delete-string to replace-strings handler",{operationCount:b.length})
4222
- const e=await(0,c.handleReplaceStrings)({taskId:u,operations:b,comment:m+" [via modify-file: delete-string]"},t,r,n,o,p,h,g)
4223
- v.push({type:"delete-string",result:e})}if(I.length>0){p.info("Processing delete-lines operations",{operationCount:I.length})
4224
- const e=I.map((e=>({path:e.path,documentId:e.documentId,replacements:[{lines:e.lines,content:[]}]}))),s=await(0,d.handleReplaceLines)({taskId:u,operations:e,comment:m+" [via modify-file: delete-lines]"},t,r,n,o,p,h,g)
4225
- v.push({type:"delete-lines",result:s})}const C=v.some((e=>e.result.isError)),_=v.filter((e=>!e.result.isError)).length,E=v.filter((e=>e.result.isError)).length
4226
- let q="## Modify File Results\n\n"
4227
- q+="**Summary:**\n",q+=`- **Total operation types:** ${v.length}\n`,q+=`- **Successful:** ${_}\n`,q+=`- **Failed:** ${E}\n\n`
4228
- for(const{type:e,result:t}of v)q+=`### ${e} operations\n`,q+=t.content[0].text+"\n\n"
4229
- return p.info("Modify-file operations completed",{totalOperationTypes:v.length,successCount:_,errorCount:E}),h.incrementCounter("modify_file_total",1,{success:!C}),{content:[{type:"text",text:q}],isError:C}}catch(e){return p.error("Modify-file operation failed",{error:e instanceof Error?e.stack:e+""}),h.incrementCounter("modify_file_errors",1),{content:[{type:"text",text:"\u274c **Modify File Failed:** "+(0,u.getErrorMessage)(e)}],isError:!0}}}
4292
+ case"delete-lines":_.push({...t,lines:e.deleteLines.lines})}}const E=[]
4293
+ if(b.length>0){f.info("Routing to replace-strings handler",{operationCount:b.length})
4294
+ const e=await(0,c.handleReplaceStrings)({taskId:k,operations:b,comment:y+" [via modify-file: replace-string]"},r,n,o,s,f,g,p)
4295
+ E.push({type:"replace-string",result:e})}if(I.length>0){f.info("Routing to insert-lines handler",{operationCount:I.length})
4296
+ const e=await(0,l.handleInsertLines)({taskId:k,operations:I,comment:y+" [via modify-file: insert-lines]"},r,n,o,s,f,g,p)
4297
+ E.push({type:"insert-lines",result:e})}if(v.length>0){f.info("Routing to replace-lines handler",{operationCount:v.length})
4298
+ const e=await(0,d.handleReplaceLines)({taskId:k,operations:v,comment:y+" [via modify-file: replace-lines]"},r,n,o,s,f,g,p)
4299
+ E.push({type:"replace-lines",result:e})}if(C.length>0){f.info("Routing delete-string to replace-strings handler",{operationCount:C.length})
4300
+ const e=await(0,c.handleReplaceStrings)({taskId:k,operations:C,comment:y+" [via modify-file: delete-string]"},r,n,o,s,f,g,p)
4301
+ E.push({type:"delete-string",result:e})}if(_.length>0){f.info("Processing delete-lines operations",{operationCount:_.length})
4302
+ const e=_.map((e=>({path:e.path,documentId:e.documentId,replacements:[{lines:e.lines,content:[]}]}))),t=await(0,d.handleReplaceLines)({taskId:k,operations:e,comment:y+" [via modify-file: delete-lines]"},r,n,o,s,f,g,p)
4303
+ E.push({type:"delete-lines",result:t})}const q=E.some((e=>e.result.isError)),S=E.filter((e=>!e.result.isError)).length,T=E.filter((e=>e.result.isError)).length
4304
+ let P="## Modify File Results\n\n"
4305
+ P+="**Summary:**\n",P+=`- **Total operation types:** ${E.length}\n`,P+=`- **Successful:** ${S}\n`,P+=`- **Failed:** ${T}\n\n`
4306
+ for(const{type:e,result:t}of E)P+=`### ${e} operations\n`,P+=t.content[0].text+"\n\n"
4307
+ return f.info("Modify-file operations completed",{totalOperationTypes:E.length,successCount:S,errorCount:T}),g.incrementCounter("modify_file_total",1,{success:!q}),{content:[{type:"text",text:P}],isError:q}}catch(e){return f.error("Modify-file operation failed",{error:e instanceof Error?e.stack:e+""}),g.incrementCounter("modify_file_errors",1),{content:[{type:"text",text:"\u274c **Modify File Failed:** "+(0,u.getErrorMessage)(e)}],isError:!0}}}
4230
4308
  const i=t(6183),a=s(t(5967)),c=t(3306),l=t(6486),d=t(6651),u=t(8824)},7478(e,exports,t){"use strict"
4231
4309
  async function r(e,t,r){const n=r.startTimer("git_get_current_branch_duration")
4232
4310
  try{const o=(await e.status()).current
@@ -4341,7 +4419,7 @@ throw n.error("Failed to commit user changes",{requestId:t,error:i,uncommittedFi
4341
4419
  try{let c=Date.now()
4342
4420
  o.debug("Checking for user changes before tool operation",{toolName:r})
4343
4421
  let l=e
4344
- if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext()
4422
+ if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
4345
4423
  if("multi-agent"===e.mode&&e.requestId){const{simpleGit}=t(3807)
4346
4424
  l=simpleGit(e.basePath),o.debug("Using worktree git instance for user changes",{requestId:e.requestId,basePath:e.basePath,toolName:r})}}if(Date.now(),n.workspaceManager?.workspaceKnownClean)return o.debug("Skipping uncommitted changes check - workspace known to be clean",{toolName:r,requestId:n.requestId}),n.workspaceManager.workspaceKnownClean=!1,i({success:!0,reason:"known_clean"}),{userChangesCommitted:!1}
4347
4425
  c=Date.now()
@@ -4363,7 +4441,45 @@ const t=e.reduce(((e,t)=>e+t.sizeMB),0)
4363
4441
  let r=`\n\n\u26a0\ufe0f **Performance Warning**: Large untracked files detected (${Math.round(t)} MB total) that may slow git operations:\n`
4364
4442
  for(const t of e.slice(0,5))r+=`- \`${t.path}\` (${t.sizeMB} MB)\n`
4365
4443
  return e.length>5&&(r+=`- ... and ${e.length-5} more large files\n`),r+="\nConsider adding these to `.gitignore` or moving them outside the repository.",r}
4366
- const h=t(3444),g=t(9860),p=t(3922),f=t(8824),m=u(t(9896)),y=u(t(6928))},7575(e,exports){"use strict"
4444
+ const h=t(3444),g=t(9860),p=t(3922),f=t(8824),m=u(t(9896)),y=u(t(6928))
4445
+ t(857)},7561(e,exports,t){"use strict"
4446
+ async function r(e,t){const r=e.getTaskClient(),n=await r.listTasks({requestId:t,status:"in_progress"})
4447
+ if(0===n.length)return null
4448
+ const o=n[0]
4449
+ return{taskId:o.localId||o.id,title:o.title,sequenceNumber:o.sequenceNumber}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleTasks=async function(e,t,i,a,c,l){const d=a.child({tool:"tasks"}),{operation:u}=e
4450
+ try{const c=t.projectId
4451
+ if(!c)throw Error("Project ID not available")
4452
+ i.setProjectId(c)
4453
+ const h=await async function(e,t,r,o){const s=o?.sessionId||e.currentSessionId
4454
+ if(!s||"__unknown__"===s||"__server__"===s)throw Error("Cannot resolve request: no session identity available")
4455
+ const i=await n.sessionIdentity.getSessionRequestId(t,r,s)
4456
+ if(!i)throw Error("No request associated with session "+s)
4457
+ return i}(t,i,a,l)
4458
+ switch(u){case"create":{const{title:t,description:n}=e
4459
+ if(!t)return{content:[{type:"text",text:"Error: title is required for create"}],isError:!0}
4460
+ if(!n)return{content:[{type:"text",text:"Error: description is required for create"}],isError:!0}
4461
+ const s=i.getTaskClient(),a=await s.createTask({requestId:h,projectId:c,title:t,description:n}),l=a.localId||a.id,u=await r(i,h)
4462
+ let g=!1
4463
+ if(!u)try{await s.updateTaskStatus(l,"in_progress"),g=!0}catch(e){d.debug("Could not auto-start task",{taskId:l,error:(0,o.getErrorMessage)(e)})}const p=a.sequenceNumber??null
4464
+ let f=p?`Created #${p}: ${t}`:`Created ${l}: ${t}`
4465
+ return g&&(f+=" (started)"),{content:[{type:"text",text:f}]}}case"done":{const{summary:t}=e
4466
+ if(!t)return{content:[{type:"text",text:"Error: summary is required for done"}],isError:!0}
4467
+ const n=await r(i,h)
4468
+ if(!n)return{content:[{type:"text",text:"No active (in_progress) task to complete."}],isError:!0}
4469
+ const a=i.getTaskClient()
4470
+ await a.updateTaskStatus(n.taskId,"completed"),(0,s.clearActiveTaskCache)()
4471
+ const c=await async function(e,t){const r=e.getTaskClient(),n=await r.listTasks({requestId:t,status:"pending",sortBy:"created",sortDirection:"asc"})
4472
+ if(0===n.length)return null
4473
+ const o=n[0]
4474
+ return{taskId:o.localId||o.id,title:o.title,sequenceNumber:o.sequenceNumber}}(i,h),l=n.sequenceNumber
4475
+ let u=l?`Completed #${l}: ${n.title}`:`Completed ${n.taskId}: ${n.title}`
4476
+ if(c)try{await a.updateTaskStatus(c.taskId,"in_progress")
4477
+ const e=c.sequenceNumber
4478
+ u+=e?`\nStarted #${e}: ${c.title}`:`\nStarted ${c.taskId}: ${c.title}`}catch(e){d.debug("Could not auto-start next task",{taskId:c.taskId,error:(0,o.getErrorMessage)(e)})}else u+="\nAll tasks completed."
4479
+ return{content:[{type:"text",text:u}]}}case"list":{const e=i.getTaskClient(),t=await e.listTasks({requestId:h,sortBy:"created",sortDirection:"asc"})
4480
+ return 0===t.length?{content:[{type:"text",text:"No tasks."}]}:{content:[{type:"text",text:t.map(((e,t)=>{const r=e.sequenceNumber??t+1
4481
+ return`[${"in_progress"===e.status?"\u25b6 in_progress":e.status}] #${r}: ${e.title}`})).join("\n")}]}}default:return{content:[{type:"text",text:"Unknown operation: "+u}],isError:!0}}}catch(e){return d.error("tasks operation failed",{operation:u,error:(0,o.getErrorMessage)(e)}),{content:[{type:"text",text:"Error: "+(0,o.getErrorMessage)(e)}],isError:!0}}}
4482
+ const n=t(6688),o=t(8824),s=t(3451)},7575(e,exports){"use strict"
4367
4483
  var t
4368
4484
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.FileOperationPhase=exports.RequestLockError=void 0,exports.RequestLockError=class extends Error{constructor(e,t,r,n){super(e),this.requestId=t,this.lockedByAgent=r,this.lockedAt=n,this.name="RequestLockError"}},function(e){e.VALIDATION="validation",e.TASK_VALIDATION="task_validation",e.RECORD_CREATION="record_creation",e.FILE_WRITE="file_write",e.STRING_REPLACEMENT="string_replacement",e.GIT_COMMIT="git_commit",e.RECORD_UPDATE_SUCCESS="record_update_success",e.RECORD_UPDATE_FAILURE="record_update_failure"}(t||(exports.FileOperationPhase=t={}))},7609(e,exports,t){"use strict"
4369
4485
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleUpdatePlan=async function(e,t,n,o){const s=o.child({tool:"plan_operations",operation:"update"})
@@ -4394,8 +4510,8 @@ let a=!1,c=Date.now()
4394
4510
  try{n.syncBranchState&&await n.syncBranchState(),Date.now(),c=Date.now()
4395
4511
  const e=n.getCurrentBranchContext?await n.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
4396
4512
  if(Date.now(),e.requestId===r)return o.debug("Already in correct request context",{requestId:r,currentBranch:e.branch}),{switched:!1,branchName:e.branch||void 0,message:`Already in request ${r} context`,lockAcquired:!1}
4397
- if(n.workspaceManager){o.debug("Using WorkspaceManager for request context switching",{requestId:r,currentMode:n.workspaceManager.getCurrentContext().mode})
4398
- try{if("multi-agent"===n.workspaceManager.getCurrentContext().mode)if(o.debug("Multi-agent mode: checking request lock before auto-switch",{requestId:r}),n.apiClient)try{const e=n.apiClient.getRequestClient(),{sessionTag:t}=(0,h.getGlobalClientInfo)()
4513
+ if(n.workspaceManager){o.debug("Using WorkspaceManager for request context switching",{requestId:r,currentMode:n.workspaceManager.getCurrentContext(n.currentSessionId).mode})
4514
+ try{if("multi-agent"===n.workspaceManager.getCurrentContext(n.currentSessionId).mode)if(o.debug("Multi-agent mode: checking request lock before auto-switch",{requestId:r}),n.apiClient)try{const e=n.apiClient.getRequestClient(),{sessionTag:t}=(0,h.getGlobalClientInfo)()
4399
4515
  c=Date.now()
4400
4516
  const s=await e.getRequestLockStatus(r)
4401
4517
  if(Date.now(),s.isLocked&&s.lockedBySessionTag!==t){o.warn("Auto-switch blocked by request lock",{requestId:r,lockedByAgent:s.lockedBySessionTag,currentAgent:t,lockedAt:s.lockedAt})
@@ -4405,16 +4521,16 @@ t.lockOverride.enabled&&(e+=`\n\n**To take over this request (only if safe to do
4405
4521
  const n=await e.lockRequest(r,t)
4406
4522
  if(Date.now(),!n.locked){const e=`Failed to acquire lock for request ${r} during auto-switch`
4407
4523
  throw o.warn("Auto-switch lock acquisition failed",{requestId:r}),Error(e)}o.info("Successfully acquired lock for auto-switch",{requestId:r,sessionTag:t,lockedAt:n.lockedAt}),a=!0}}catch(e){throw o.error("Lock check/acquisition failed during auto-switch",{requestId:r,error:e instanceof Error?e.message:e+""}),e}else o.warn("Multi-agent mode but no API client available for locking",{requestId:r})
4408
- o.debug("Ensuring workspace is ready for file operations",{requestId:r,reason:"first-file-operation"}),c=Date.now(),await n.workspaceManager.ensureWorkspaceReady(r),Date.now()
4409
- const e=n.workspaceManager.getCurrentContext()
4524
+ o.debug("Ensuring workspace is ready for file operations",{requestId:r,reason:"first-file-operation"}),c=Date.now(),await n.workspaceManager.ensureWorkspaceReady(r,n.currentSessionId),Date.now()
4525
+ const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
4410
4526
  if(e.basePath&&(n.git=(0,d.simpleGit)(e.basePath),o.info("Updated git instance to worktree path",{requestId:r,gitWorkingDirectory:e.basePath,mode:e.mode,branchName:e.branchName})),e.requestId!==r){const t=`Workspace switch validation failed. Expected requestId: ${r}, but got: ${e.requestId}`
4411
- throw o.error("Post-switch context validation failed",{requestId:r,expectedRequestId:r,actualRequestId:e.requestId,actualBasePath:e.basePath,mode:e.mode}),Error(t)}o.info("Workspace is ready via WorkspaceManager",{requestId:r,mode:n.workspaceManager.getCurrentContext().mode,workflow:"hybrid-creation-lazy-worktree",validation:"context_validated"})
4527
+ throw o.error("Post-switch context validation failed",{requestId:r,expectedRequestId:r,actualRequestId:e.requestId,actualBasePath:e.basePath,mode:e.mode}),Error(t)}o.info("Workspace is ready via WorkspaceManager",{requestId:r,mode:n.workspaceManager.getCurrentContext(n.currentSessionId).mode,workflow:"hybrid-creation-lazy-worktree",validation:"context_validated"})
4412
4528
  try{const{findLargeUntrackedFiles:s,formatLargeFileWarning:i}=await Promise.resolve().then(t.t.bind(t,7478,23)),a=await s(e.basePath)
4413
4529
  if(a.length>0){const e=i(a)
4414
- n.workspaceManager.largeFileWarning=e,o.warn("Large untracked files detected",{requestId:r,fileCount:a.length,files:a.map((e=>({path:e.path,sizeMB:e.sizeMB})))})}}catch(e){o.debug("Large file check failed",{error:e})}return s.incrementCounter(i+"_auto_context_switch_success",1),{switched:!0,branchName:n.workspaceManager.getCurrentContext().branchName,message:"Workspace ready for request "+r,lockAcquired:a,lockedRequestId:a?r:void 0}}catch(e){if(e instanceof p.RequestLockError)throw o.warn("Auto-switch blocked by request lock, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
4530
+ n.workspaceManager.largeFileWarning=e,o.warn("Large untracked files detected",{requestId:r,fileCount:a.length,files:a.map((e=>({path:e.path,sizeMB:e.sizeMB})))})}}catch(e){o.debug("Large file check failed",{error:e})}return s.incrementCounter(i+"_auto_context_switch_success",1),{switched:!0,branchName:n.workspaceManager.getCurrentContext(n.currentSessionId).branchName,message:"Workspace ready for request "+r,lockAcquired:a,lockedRequestId:a?r:void 0}}catch(e){if(e instanceof p.RequestLockError)throw o.warn("Auto-switch blocked by request lock, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
4415
4531
  return o.error("Error switching to request context",{requestId:r,error:(0,g.getErrorMessage)(e)}),s.incrementCounter(i+"_auto_context_switch_error",1),{switched:!1,message:"Context switch error: "+(0,g.getErrorMessage)(e)}}}return o.error("WorkspaceManager not available - this should not happen",{requestId:r}),{switched:!1,message:"WorkspaceManager not available"}}catch(e){if(e instanceof p.RequestLockError)throw o.warn("Auto-switch blocked by request lock, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
4416
4532
  return o.error("Error during auto-switch to request branch",{requestId:r,error:(0,g.getErrorMessage)(e)}),s.incrementCounter(i+"_auto_branch_switch_error",1),{switched:!1,message:"Error during switch: "+(0,g.getErrorMessage)(e)}}}function s(e,t,r,n){if(!e.workspaceManager)return n.debug("No workspace manager available, skipping context validation",{operation:r,requestId:t}),{isValid:!0}
4417
- const o=e.workspaceManager.getCurrentContext()
4533
+ const o=e.workspaceManager.getCurrentContext(e.currentSessionId)
4418
4534
  if(!t)return n.debug("File operation without requestId in multi-agent mode",{operation:r,currentContext:o.requestId,mode:o.mode,basePath:o.basePath}),{isValid:!0}
4419
4535
  if(o.requestId!==t){const e=`Workspace context mismatch for ${r}. Expected requestId: ${t}, but current context is: ${o.requestId}. This suggests workspace switching failed or didn't occur. Current basePath: ${o.basePath}, branch: ${o.branchName}`
4420
4536
  return n.error("Workspace context validation failed - context mismatch",{operation:r,expectedRequestId:t,currentRequestId:o.requestId,currentBasePath:o.basePath,currentBranchName:o.branchName,currentIsMainBranch:o.isMainBranch,mode:o.mode,issue:"request_id_mismatch"}),{isValid:!1,errorMessage:e}}if(o.isMainBranch&&t){const e=`File operation ${r} attempted with requestId ${t} but workspace is still in main branch (${o.branchName}). This indicates workspace switching to request context failed.`
@@ -4462,7 +4578,7 @@ if(e.switched&&a.info(`Auto-switched to request workspace during ${i} operation`
4462
4578
  if(!t.isValid)return a.error("Workspace context validation failed for "+i,{requestId:r,operation:i,error:t.errorMessage}),{success:!1,switched:e.switched,branchName:e.branchName,error:t.errorMessage,lockAcquired:e.lockAcquired,lockedRequestId:e.lockedRequestId}}return a.debug("Workspace context successfully ensured for "+i,{requestId:r,operation:i,switched:e.switched,branchName:e.branchName}),{success:!0,switched:e.switched,branchName:e.branchName,lockAcquired:e.lockAcquired,lockedRequestId:e.lockedRequestId}}catch(e){const t=(0,g.getErrorMessage)(e)
4463
4579
  return e instanceof p.RequestLockError?(a.warn(i+" operation blocked by request lock",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,operation:i}),{success:!1,switched:!1,error:e.message,isLockConflict:!0}):(a.error("Error ensuring workspace context for "+i,{requestId:r,operation:i,error:t}),{success:!1,switched:!1,error:t})}}
4464
4580
  const d=t(3807),u=l(t(7478)),h=t(5172),g=t(8824),p=t(7575)
4465
- l(t(9896)),l(t(6928))},7634(e,exports,t){"use strict"
4581
+ l(t(9896)),l(t(6928)),l(t(857))},7634(e,exports,t){"use strict"
4466
4582
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.RequestLockManager=exports.WorktreeManager=void 0
4467
4583
  var r=t(1502)
4468
4584
  Object.defineProperty(exports,"WorktreeManager",{enumerable:!0,get(){return r.WorktreeManager}})
@@ -4471,9 +4587,10 @@ Object.defineProperty(exports,"RequestLockManager",{enumerable:!0,get(){return n
4471
4587
  var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
4472
4588
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.MultiAgentWorkspaceManager=void 0
4473
4589
  const n=r(t(6928)),o=t(3807),s=t(7634),i=t(8824),a=t(7075),c=t(1387),l=t(4968)
4474
- class d{getSession(e){const t=e||d.DEFAULT_SESSION
4590
+ class d{getSession(e){e||this.logger.warn("getSession called without sessionId \u2014 using __default__. This may cause cross-session contamination.",{stack:Error().stack?.split("\n").slice(1,4).join(" <- ")})
4591
+ const t=e||d.DEFAULT_SESSION
4475
4592
  let r=this.sessions.get(t)
4476
- return r||(r={requestId:null,worktreePath:null,git:this.mainGit,readonlyBranchCheckDone:!1,workspaceKnownClean:!1,largeFileWarning:""},this.sessions.set(t,r)),r}constructor(e,t,r,n,o){this.basePath=e,this.logger=t,this.mainGit=r,this.metrics=n,this.workspaceStates=new Map,this.sessions=new Map,this.apiClient=o
4593
+ return r||(r={requestId:null,worktreePath:null,git:this.mainGit,readonlyBranchCheckDone:!1,workspaceKnownClean:!1,largeFileWarning:"",permanentBranch:!1},this.sessions.set(t,r)),r}constructor(e,t,r,n,o){this.basePath=e,this.logger=t,this.mainGit=r,this.metrics=n,this.workspaceStates=new Map,this.sessions=new Map,this.apiClient=o
4477
4594
  const i=a.ConflictResolutionUtils.initializeDetectors(r,t)
4478
4595
  this.conflictDetector=i.conflictDetector,this.safetyAnalyzer=i.safetyAnalyzer,this.conflictResolver=i.conflictResolver,this.worktreeManager=new s.WorktreeManager(e,t,n),this.gitAdapter=new l.WorktreeGitAdapter(r,this.worktreeManager,this.conflictDetector,t,n),this.requestProcessor=new c.WorkspaceRequestProcessor(this.gitAdapter,this.conflictDetector,this.safetyAnalyzer,this.conflictResolver,t),this.initializeWorktreeManager(),this.initializeFromEnv()}async initializeFromEnv(){const e=process.env.ALCHEMY_INITIAL_BRANCH
4479
4596
  if(!e)return
@@ -4482,8 +4599,8 @@ if(!t)return void this.logger.warn("ALCHEMY_INITIAL_BRANCH set but not a request
4482
4599
  const r=t[1]
4483
4600
  this.logger.info("ALCHEMY_INITIAL_BRANCH set, switching to worktree",{initialBranch:e,requestId:r})
4484
4601
  try{await this.ensureWorkspaceReady(r)
4485
- const e=this.getSession()
4486
- e.readonlyBranchCheckDone=!0,this.logger.info("Successfully switched to worktree from ALCHEMY_INITIAL_BRANCH",{requestId:r,worktreePath:e.worktreePath})}catch(t){this.logger.warn("Failed to switch to worktree from ALCHEMY_INITIAL_BRANCH",{initialBranch:e,requestId:r,error:(0,i.getErrorMessage)(t)})}}hasExactConflictMarkers(e){return!(!e||!e.trim())&&[/^\s*<{7}(?:\s|$)/m,/^\s*={7}(?:\s|$)/m,/^\s*>{7}(?:\s|$)/m].some((t=>t.test(e)))}async initializeWorktreeManager(){try{await this.worktreeManager.initialize(),this.logger.debug("Initialized multi-agent workspace manager with worktrees")}catch(e){throw this.logger.error("Failed to initialize worktree manager",{error:e}),e}}setTaskCreator(e){this.taskCreator=e}async initializeRequest(e,t){const r=Date.now(),n=a.WorkspaceValidation.validateRequestId(e)
4602
+ const e=this.getSession("__init__")
4603
+ e.readonlyBranchCheckDone=!0,e.permanentBranch=!0,this.logger.info("Successfully switched to worktree from ALCHEMY_INITIAL_BRANCH",{requestId:r,worktreePath:e.worktreePath})}catch(t){this.logger.warn("Failed to switch to worktree from ALCHEMY_INITIAL_BRANCH",{initialBranch:e,requestId:r,error:(0,i.getErrorMessage)(t)})}}hasExactConflictMarkers(e){return!(!e||!e.trim())&&[/^\s*<{7}(?:\s|$)/m,/^\s*={7}(?:\s|$)/m,/^\s*>{7}(?:\s|$)/m].some((t=>t.test(e)))}async initializeWorktreeManager(){try{await this.worktreeManager.initialize(),this.logger.debug("Initialized multi-agent workspace manager with worktrees")}catch(e){throw this.logger.error("Failed to initialize worktree manager",{error:e}),e}}setTaskCreator(e){this.taskCreator=e}async initializeRequest(e,t){const r=Date.now(),n=a.WorkspaceValidation.validateRequestId(e)
4487
4604
  if(!n.isValid)throw Error("Invalid request ID: "+n.errors.join(", "))
4488
4605
  const o=n.sanitized
4489
4606
  try{this.workspaceStates.set(o,"initialized")
@@ -4541,7 +4658,7 @@ const r=t.sanitized
4541
4658
  try{for(const[e,t]of this.sessions)t.requestId===r&&(t.requestId=null,t.worktreePath=null,t.git=this.mainGit)
4542
4659
  const e=await this.worktreeManager.removeWorktree(r,!1)
4543
4660
  if(!e.success)throw Error(e.message||"Failed to remove worktree")
4544
- this.logger.info("Successfully cancelled request",{requestId:r})}catch(e){throw this.logger.error("Failed to cancel request",{requestId:r,error:(0,i.getErrorMessage)(e)}),e}}getCurrentContext(e){const t=this.getSession(e),r={requestId:t.requestId,basePath:t.worktreePath||this.basePath,branchName:t.requestId?"requests/"+t.requestId:"main",isMainBranch:!t.requestId,mode:"multi-agent"}
4661
+ this.logger.info("Successfully cancelled request",{requestId:r})}catch(e){throw this.logger.error("Failed to cancel request",{requestId:r,error:(0,i.getErrorMessage)(e)}),e}}getCurrentContext(e){const t=this.getSession(e),r={requestId:t.requestId,basePath:t.worktreePath||this.basePath,branchName:t.requestId?"requests/"+t.requestId:"main",isMainBranch:!t.requestId,mode:"multi-agent",permanentBranch:t.permanentBranch}
4545
4662
  return this.logger.debug("getCurrentContext returning",{context:r,sessionId:e}),r}resetCurrentContext(e){const t=this.getSession(e)
4546
4663
  t.requestId&&this.logger.info("Resetting workspace context (session switch)",{prevRequestId:t.requestId,prevWorktreePath:t.worktreePath,sessionId:e}),t.requestId=null,t.worktreePath=null,t.git=this.mainGit,t.readonlyBranchCheckDone=!1}async getWorkspaceInfo(e){try{const t=a.WorkspaceValidation.validateRequestId(e)
4547
4664
  if(!t.isValid)return null
@@ -4551,7 +4668,7 @@ return t?t[1]:null}convertWorktreeInfoToWorkspaceInfo(e){return{requestId:e.requ
4551
4668
  return this.worktreeManager.getWorktreeInfo(t)}catch(t){return void this.logger.warn("Failed to get worktree info",{requestId:e,error:(0,i.getErrorMessage)(t)})}}getMainGit(){return this.gitAdapter.getMainGit()}getCurrentGit(e){return this.getSession(e).git}get readonlyBranchCheckDone(){return this.getSession().readonlyBranchCheckDone}set readonlyBranchCheckDone(e){this.getSession().readonlyBranchCheckDone=e}get workspaceKnownClean(){return this.getSession().workspaceKnownClean}set workspaceKnownClean(e){this.getSession().workspaceKnownClean=e}get largeFileWarning(){return this.getSession().largeFileWarning}set largeFileWarning(e){this.getSession().largeFileWarning=e}async ensureReadonlyBranchIfNeeded(e,r,n,o){const s=this.getSession(o)
4552
4669
  if(s.readonlyBranchCheckDone)return
4553
4670
  if(s.readonlyBranchCheckDone=!0,o&&n)try{const{sessionIdentity:e}=await Promise.resolve().then(t.bind(t,6688)),r=await e.getSessionRequestId(n,this.logger,o)
4554
- if(r)return await this.ensureWorkspaceReady(r,o),void this.logger.info("ensureReadonlyBranchIfNeeded: workspace ready from session DB lookup",{requestId:r,sessionId:o})}catch(e){this.logger.warn("ensureReadonlyBranchIfNeeded: session DB lookup failed, falling back to env var",{error:(0,i.getErrorMessage)(e)})}const a=process.env.ALCHEMY_INITIAL_BRANCH
4671
+ if(r)return await this.ensureWorkspaceReady(r,o),s.permanentBranch=!0,void this.logger.info("ensureReadonlyBranchIfNeeded: workspace ready from session DB lookup",{requestId:r,sessionId:o,permanentBranch:!0})}catch(e){this.logger.warn("ensureReadonlyBranchIfNeeded: session DB lookup failed, falling back to env var",{error:(0,i.getErrorMessage)(e)})}const a=process.env.ALCHEMY_INITIAL_BRANCH
4555
4672
  if(a){const e=a.match(/^requests\/(.+)$/)
4556
4673
  if(e){const t=e[1]
4557
4674
  try{await this.ensureWorkspaceReady(t,o),this.logger.info("ensureReadonlyBranchIfNeeded: workspace ready from env var",{requestId:t})}catch(e){this.logger.warn("ensureReadonlyBranchIfNeeded: failed to ensure workspace",{requestId:t,error:(0,i.getErrorMessage)(e)})}}}}isActiveForAnySession(e){for(const[,t]of this.sessions)if(t.requestId===e)return!0
@@ -4573,30 +4690,30 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
4573
4690
  var t={}
4574
4691
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
4575
4692
  return o(t,e),t})
4576
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,t,r,n,o,s,g,p,f){const m=g.child({tool:"manage_files"})
4577
- try{const h=a.validateArgs(e,i.ManageFilesSchema),{taskId:g,operations:y,comment:w}=h
4578
- m.info("Processing manage-files operations",{taskId:g,operationCount:y.length,comment:w})
4579
- const k=[],b=[],I=[],v=[]
4580
- for(const e of y)switch(e.operationType){case"create-directory":k.push({path:e.createDirectory.path})
4693
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,r,n,o,s,g,p,f,m){const y=p.child({tool:"manage_files"})
4694
+ try{const h=a.validateArgs(e,i.ManageFilesSchema),{operations:w,comment:k}=h,{resolveActiveTaskId:b}=await Promise.resolve().then(t.bind(t,3451)),I=e.taskId||await b(r,g,p)||"untracked"
4695
+ y.info("Processing manage-files operations",{taskId:I,operationCount:w.length,comment:k})
4696
+ const v=[],C=[],_=[],E=[]
4697
+ for(const e of w)switch(e.operationType){case"create-directory":v.push({path:e.createDirectory.path})
4581
4698
  break
4582
- case"move-files":for(const t of e.moveFiles.moves)b.push(t)
4699
+ case"move-files":for(const t of e.moveFiles.moves)C.push(t)
4583
4700
  break
4584
- case"delete-files":I.push(...e.deleteFiles.targets)
4701
+ case"delete-files":_.push(...e.deleteFiles.targets)
4585
4702
  break
4586
- case"get-file-info":v.push({path:e.getFileInfo.path})}const C=[]
4587
- for(const e of k){m.info("Routing to create-directory handler",{path:e.path})
4588
- const s=await(0,c.handleCreateDirectory)({taskId:g,path:e.path,comment:w+" [via manage-files: create-directory]"},t,r,n,o,m,p,f)
4589
- C.push({type:"create-directory",result:s})}if(b.length>0){m.info("Routing to move-files handler",{operationCount:b.length})
4590
- const e=await(0,l.handleMoveFiles)({taskId:g,operations:b,comment:w+" [via manage-files: move-files]"},t,r,n,o,m,p,f)
4591
- C.push({type:"move-files",result:e})}if(I.length>0){m.info("Routing to delete-files handler",{operationCount:I.length})
4592
- const e=await(0,u.handleDeleteFiles)({taskId:g,operations:I,comment:w+" [via manage-files: delete-files]"},t,s,m,p,f)
4593
- C.push({type:"delete-files",result:e})}for(const e of v){m.info("Routing to get-file-info handler",{path:e.path})
4594
- const r=await(0,d.handleGetFileInfo)({path:e.path},t,m,p)
4595
- C.push({type:"get-file-info",result:r})}const _=C.some((e=>e.result.isError)),E=C.filter((e=>!e.result.isError)).length,q=C.filter((e=>e.result.isError)).length
4596
- let S="## Manage Files Results\n\n"
4597
- S+="**Summary:**\n",S+=`- **Total operation types:** ${C.length}\n`,S+=`- **Successful:** ${E}\n`,S+=`- **Failed:** ${q}\n\n`
4598
- for(const{type:e,result:t}of C)S+=`### ${e} operations\n`,S+=t.content[0].text+"\n\n"
4599
- return m.info("Manage-files operations completed",{totalOperationTypes:C.length,successCount:E,errorCount:q}),p.incrementCounter("manage_files_total",1,{success:!_}),{content:[{type:"text",text:S}],isError:_}}catch(e){return m.error("Manage-files operation failed",{error:e instanceof Error?e.stack:e+""}),p.incrementCounter("manage_files_errors",1),{content:[{type:"text",text:"\u274c **Manage Files Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
4703
+ case"get-file-info":E.push({path:e.getFileInfo.path})}const q=[]
4704
+ for(const e of v){y.info("Routing to create-directory handler",{path:e.path})
4705
+ const t=await(0,c.handleCreateDirectory)({taskId:I,path:e.path,comment:k+" [via manage-files: create-directory]"},r,n,o,s,y,f,m)
4706
+ q.push({type:"create-directory",result:t})}if(C.length>0){y.info("Routing to move-files handler",{operationCount:C.length})
4707
+ const e=await(0,l.handleMoveFiles)({taskId:I,operations:C,comment:k+" [via manage-files: move-files]"},r,n,o,s,y,f,m)
4708
+ q.push({type:"move-files",result:e})}if(_.length>0){y.info("Routing to delete-files handler",{operationCount:_.length})
4709
+ const e=await(0,u.handleDeleteFiles)({taskId:I,operations:_,comment:k+" [via manage-files: delete-files]"},r,g,y,f,m)
4710
+ q.push({type:"delete-files",result:e})}for(const e of E){y.info("Routing to get-file-info handler",{path:e.path})
4711
+ const t=await(0,d.handleGetFileInfo)({path:e.path},r,y,f)
4712
+ q.push({type:"get-file-info",result:t})}const S=q.some((e=>e.result.isError)),T=q.filter((e=>!e.result.isError)).length,P=q.filter((e=>e.result.isError)).length
4713
+ let j="## Manage Files Results\n\n"
4714
+ j+="**Summary:**\n",j+=`- **Total operation types:** ${q.length}\n`,j+=`- **Successful:** ${T}\n`,j+=`- **Failed:** ${P}\n\n`
4715
+ for(const{type:e,result:t}of q)j+=`### ${e} operations\n`,j+=t.content[0].text+"\n\n"
4716
+ return y.info("Manage-files operations completed",{totalOperationTypes:q.length,successCount:T,errorCount:P}),f.incrementCounter("manage_files_total",1,{success:!S}),{content:[{type:"text",text:j}],isError:S}}catch(e){return y.error("Manage-files operation failed",{error:e instanceof Error?e.stack:e+""}),f.incrementCounter("manage_files_errors",1),{content:[{type:"text",text:"\u274c **Manage Files Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
4600
4717
  const i=t(6183),a=s(t(5967)),c=t(8309),l=t(2414),d=t(3628),u=t(5992),h=t(8824)},7713(e,exports,t){"use strict"
4601
4718
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
4602
4719
  const r=t(6183),n=t(5303)
@@ -4631,7 +4748,7 @@ return t?.success&&t[c]>0})).map((e=>e.path)).filter((e=>e))
4631
4748
  if(0===n.length)return l.debug("No files to commit to Git"),{filesCommitted:[],success:!0}
4632
4749
  l.info("Staging modified files for git commit",{files:n,count:n.length,operationType:s})
4633
4750
  let d=o.git
4634
- if(o.workspaceManager){const t=o.workspaceManager.getCurrentContext()
4751
+ if(o.workspaceManager){const t=o.workspaceManager.getCurrentContext(o.currentSessionId)
4635
4752
  "multi-agent"===t.mode&&t.requestId&&(d=(0,a.simpleGit)(t.basePath),l.debug("Using WorkspaceManager git instance for multi-file commit",{taskId:e,mode:t.mode,requestId:t.requestId,basePath:t.basePath,branchName:t.branchName,filesCount:n.length}))}if(!d)return l.debug("No git repository available, skipping commit"),{filesCommitted:[],success:!0}
4636
4753
  let g=null
4637
4754
  try{g=(await d.revparse(["HEAD"])).trim()}catch(e){l.warn("Failed to get current commit hash",{error:e})}for(const e of n)await d.add(e)
@@ -4644,13 +4761,13 @@ l.debug("createFileOperationRecords called",{taskId:e,requestId:t,projectId:n||"
4644
4761
  try{const a=await r(e,t,n,o,s,i,c,l,u,h)
4645
4762
  return p=a.recordId,f=a.localRecordId,l.info("Created tool record for file operation: "+o,{taskId:e,path:s,toolRecordId:p,localToolRecordId:f}),{toolRecordId:p,localToolRecordId:f}}catch(r){throw l.error("Failed to create tool record for file operation: "+o,{error:(0,d.getErrorMessage)(r),errorStack:r instanceof Error?r.stack:void 0,taskId:e,requestId:t,projectId:n||"<empty>",projectIdType:typeof n,path:s}),u.recordValue(h+"_record_creation_time",Date.now()-g),u.incrementCounter(h+"_record_creation_error",1),r}},exports.updateFileOperationRecords=async function(e,t,r,o,s,i,a,c,l,u,h,g,p){try{t&&h.info("Task record update skipped (task records removed): "+t,{taskId:e,path:o}),r&&await n(r,o,s,a,c,u,h,g,p)}catch(t){h.warn("Error updating tool record for operation: "+s,{error:(0,d.getErrorMessage)(t),taskId:e,normalizedPath:o,toolRecordId:r})}},exports.checkAndCommitUserMods=async function(e,t,r,n,o){if(!t.git)return{hadUserMods:!1}
4646
4763
  try{let s=t.git
4647
- if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext()
4764
+ if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
4648
4765
  "multi-agent"===e.mode&&e.requestId&&(s=(0,a.simpleGit)(e.basePath))}if((await s.diff(["--name-only","HEAD","--",e])).trim().length>0){r.info(`File ${e} has uncommitted changes, preserving user modifications`),await s.add(e)
4649
4766
  const t=await s.commit("[USER-MODS] Preserve user modifications before tool operation: "+e)
4650
4767
  return r.info("Created user modifications commit",{filePath:e,userModsCommitHash:t.commit}),n.incrementCounter(o+"_user_mods_commits_created",1),{hadUserMods:!0,userModsCommitHash:t.commit}}return{hadUserMods:!1}}catch(t){return r.warn("Failed to check/preserve user modifications for "+e,{error:(0,d.getErrorMessage)(t)}),n.incrementCounter(o+"_user_mods_check_failures",1),{hadUserMods:!1}}},exports.commitToGit=async function(e,t,r,n,o,s,i,c,u){const h=Date.now()
4651
4768
  let g,p=null
4652
4769
  try{let f=s.git
4653
- if(s.workspaceManager){const t=s.workspaceManager.getCurrentContext()
4770
+ if(s.workspaceManager){const t=s.workspaceManager.getCurrentContext(s.currentSessionId)
4654
4771
  if("multi-agent"===t.mode&&t.requestId){if(!t.basePath.includes("/worktrees/")&&!t.basePath.includes("\\worktrees\\"))throw i.error("CRITICAL BUG: Multi-agent mode but basePath is not a worktree path",{taskId:e,requestId:t.requestId,basePath:t.basePath,expectedPattern:"should contain /worktrees/ or \\worktrees\\",issue:"workspace_context_incorrect"}),Error(`Multi-agent mode context error: basePath '${t.basePath}' is not a worktree path. This will cause commits to go to main branch instead of the request branch.`)
4655
4772
  f=(0,a.simpleGit)(t.basePath),i.debug("Using WorkspaceManager git instance for commit",{taskId:e,mode:t.mode,requestId:t.requestId,basePath:t.basePath,branchName:t.branchName,worktreeValidated:!0})}}if(f){i.info("commitToGit called with:",{taskId:e,recordId:r,localRecordId:n,hasLocalRecordId:!!n,localRecordIdType:typeof n,normalizedPath:t})
4656
4773
  let a=!1,m=""
@@ -4750,17 +4867,17 @@ var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:
4750
4867
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateArgs=function(e,t){if(e&&"object"==typeof e)for(const t of Object.keys(e)){const r=e[t]
4751
4868
  if("string"==typeof r&&(r.startsWith("[")||r.startsWith("{")))try{e[t]=JSON.parse(r)}catch{}}try{return t.parse(e)}catch(e){if(e instanceof o.z.ZodError){const t=e.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")
4752
4869
  throw(0,s.createValidationError)("Invalid arguments: "+t)}throw e}},exports.validateAndNormalizePath=function(e,t){let r=e.replace(/\\/g,"/")
4753
- const o=function(e){return e.workspaceManager?e.workspaceManager.getCurrentContext().basePath:e.basePath}(t)
4870
+ const o=function(e){return e.workspaceManager?e.workspaceManager.getCurrentContext(e.currentSessionId).basePath:e.basePath}(t)
4754
4871
  if(n.default.isAbsolute(r)){const e=n.default.normalize(r)
4755
4872
  if(e.startsWith(o))r=n.default.relative(o,e),r=r.replace(/\\/g,"/")
4756
4873
  else{const i=t.basePath
4757
- if(!i||!e.startsWith(i)){const r=t.workspaceManager?.getCurrentContext()?.mode||"unknown",n=t.workspaceManager?.getCurrentContext()?.requestId||"none"
4874
+ if(!i||!e.startsWith(i)){const r=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.mode||"unknown",n=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.requestId||"none"
4758
4875
  throw(0,s.createValidationError)(`File path is outside the allowed directory\n Requested path (absolute): ${e}\n Allowed base (current workspace): ${o}\n Allowed base (main repo): ${i||"N/A"}\n Workspace mode: ${r}\n Current request: ${n}\n Note: Use relative paths (e.g., 'src/file.txt') instead of absolute paths`)}r=n.default.relative(i,e),r=r.replace(/\\/g,"/")}}if(function(e){const t=e.replace(/\\/g,"/").replace(/^\//g,"")
4759
4876
  for(const e of i)if(t===e||t.startsWith(e+"/"))return!0
4760
4877
  for(const e of a)if(t===e||t.endsWith("/"+e))return!0
4761
4878
  return!1}(r))throw(0,s.createValidationError)(`Access to '${r}' is not allowed - this directory contains system files`)
4762
4879
  const c=n.default.resolve(o,r)
4763
- if(!c.startsWith(o)){const e=t.workspaceManager?.getCurrentContext()?.mode||"unknown",n=t.workspaceManager?.getCurrentContext()?.requestId||"none"
4880
+ if(!c.startsWith(o)){const e=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.mode||"unknown",n=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.requestId||"none"
4764
4881
  throw(0,s.createValidationError)(`File path is outside the allowed directory\n Requested path: ${r}\n Resolved to: ${c}\n Allowed base: ${o}\n Workspace mode: ${e}\n Current request: `+n)}return{normalizedPath:r,fullPath:c}},exports.validateTaskIdFormat=function(e,t,r,n){e&&/^tas\d{6}$/.test(e)||(t.warn("Invalid task ID format provided",{taskId:e}),r.incrementCounter(n+"_invalid_task_format",1))}
4765
4882
  const n=r(t(6928)),o=t(1569),s=t(9860),i=[t(4139).ALCHEMY_DIR_NAME,".opencode",".git"],a=[".mcp-server.lock"]},8309(e,exports,t){"use strict"
4766
4883
  var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
@@ -4771,33 +4888,33 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
4771
4888
  var t={}
4772
4889
  if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
4773
4890
  return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
4774
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,t,r,n,o,s,i,p){const f=s.child({tool:"create_directory"}),m=Date.now()
4775
- let y,w,k=d.FileOperationPhase.VALIDATION
4776
- const b={toolName:"create-directory",operationName:"create",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"create-directory",metricsPrefix:"create_directory",successMessage:"Successfully created directory {path}",failureMessage:"Failed to create directory {path}"}
4777
- try{const s=d.validateArgs(e,l.CreateDirectorySchema),{taskId:u,path:h,comment:g}=s
4778
- f.info("Creating directory: "+h,{taskId:u,path:h,comment:g}),d.validateTaskIdFormat(u,f,i,b.metricsPrefix),t.getCurrentBranchContext&&await t.getCurrentBranchContext()
4779
- const{normalizedPath:I,fullPath:v}=d.validateAndNormalizePath(h,t)
4780
- k=d.FileOperationPhase.TASK_VALIDATION,i.incrementCounter("create_directory_phase",1,{phase:k})
4781
- const C=await d.validateTaskId(u,I,r,f,i,b.metricsPrefix),_=C?.requestId,E=await d.validateWorkItemStates(u,I,r,o,t,f,i,b.metricsPrefix),q=await d.autoPromoteTaskStatus(u,C.status,_,E.request?.status,I,r,o,f,i,b.metricsPrefix)
4782
- q.taskPromoted&&f.info(`Auto-promoted task ${u} (${C.title||"Untitled"}) to in_progress for file operation`,{taskId:u,taskTitle:C.title,previousStatus:C.status,newStatus:q.newTaskStatus,path:I}),q.requestPromoted&&f.info(`Auto-promoted request ${_} to in_progress for file operation`,{requestId:_,previousStatus:E.request?.status,newStatus:q.newRequestStatus,triggeringTaskId:u})
4783
- const S=await d.ensureCorrectWorkspaceContext({taskPromoted:q.taskPromoted,requestId:_,context:t,operation:"create-directory",logger:f,metrics:i,metricsPrefix:b.metricsPrefix})
4784
- if(!S.success){if(S.isLockConflict)return{content:[{type:"text",text:"\u274c "+S.error}],isError:!0}
4785
- throw Error(S.error)}let T=!1
4786
- try{T=(await a.default.stat(v)).isDirectory()}catch{T=!1}k=d.FileOperationPhase.RECORD_CREATION,i.incrementCounter("create_directory_phase",1,{phase:k})
4787
- const{toolRecordId:P,localToolRecordId:j}=await d.createFileOperationRecords(u,_,t.projectId,b.recordType,I,{directoryExists:T,userComment:g},r,n,f,i,b.metricsPrefix,p)
4788
- y=P,w=P,k=b.fileOperationPhase,i.incrementCounter("create_directory_phase",1,{phase:k})
4789
- let R=T
4790
- if(!T){await a.default.mkdir(v,{recursive:!0}),f.info("Successfully created directory "+I)
4791
- try{const e=c.default.join(v,".gitkeep")
4792
- await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),R=!0,f.info("Created .gitkeep file for Git tracking")}catch(e){f.warn("Failed to create .gitkeep file",{error:e instanceof Error?e.message:e+""}),R=!1}}const M=Date.now()-m
4793
- i.recordValue("create_directory_time",M),i.incrementCounter("create_directory_success",1),k=d.FileOperationPhase.GIT_COMMIT,i.incrementCounter("create_directory_phase",1,{phase:k})
4794
- const x=`Create directory: ${I} - ${g||"Create directory"}`,O=!T&&R?I+"/.gitkeep":I,D=await d.commitToGit(u,O,P,j,x,t,f,i,b.metricsPrefix)
4795
- k=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,i.incrementCounter("create_directory_phase",1,{phase:k}),await d.updateFileOperationRecords(u,y,w,I,b.recordType,`Successfully ${T?"verified":"created"} directory: ${I}`,{status:"completed",commitHash:D.commitHash,previousCommitHash:D.previousCommitHash,directoryExists:T,isDirectory:!0,userComment:g},`Successfully ${T?"verified":"created"} directory: ${I}`,r,n,f,i,b.metricsPrefix)
4796
- const $=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
4797
- return{content:[{type:"text",text:T?"Directory already exists":`Successfully created directory${D.commitHash?"\nCommit: "+D.commitHash.substring(0,8):""}${$.requestId?"\nBranch: "+$.requestId:""}${S.lockAcquired&&S.lockedRequestId?"\n\u{1f512} **Locked request:** "+S.lockedRequestId:""}`}]}}catch(o){if(e.taskId&&n)try{const r=o instanceof u.NotFoundError||o instanceof u.ValidationError||o instanceof h.ZodError
4798
- await n.createToolRecord({...r?{}:{taskId:e.taskId},projectId:t.projectId,type:"create-directory",metadata:{status:"failed",timestamp:(new Date).toISOString(),path:e.path,userComment:e.comment,error:(0,g.getErrorMessage)(o),errorDetails:o instanceof Error?o.stack:o+"",phase:k,attemptedTaskId:e.taskId,taskIdValidationFailed:r},note:`Failed to create directory ${e.path} - ${(0,g.getErrorMessage)(o)}`})}catch(t){f.error("Failed to create failure record for create directory operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,path:e.path})}const s=Date.now()-m
4799
- if(i.recordValue("create_directory_time",s),i.incrementCounter("create_directory_errors",1),f.error("Error creating directory:",{error:(0,g.getErrorMessage)(o),time:s}),(y||w)&&e.taskId){k=d.FileOperationPhase.RECORD_UPDATE_FAILURE
4800
- try{await d.updateFileOperationRecords(e.taskId,y,w,e.path,b.recordType,"Failed to create directory "+e.path,{status:"failed",error:(0,g.getErrorMessage)(o),userComment:e.comment},"Failed to create directory "+e.path,r,n,f,i,b.metricsPrefix)}catch(t){f.error("Failed to update record with failure status",{taskId:e.taskId,recordId:y,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(o,k,f,i,e,b)}}
4891
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,r,n,o,s,i,p,f){const m=i.child({tool:"create_directory"}),y=Date.now()
4892
+ let w,k,b=d.FileOperationPhase.VALIDATION
4893
+ const I={toolName:"create-directory",operationName:"create",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"create-directory",metricsPrefix:"create_directory",successMessage:"Successfully created directory {path}",failureMessage:"Failed to create directory {path}"}
4894
+ try{const u=d.validateArgs(e,l.CreateDirectorySchema),{path:h,comment:g}=u,{resolveActiveTaskId:v}=await Promise.resolve().then(t.bind(t,3451)),C=e.taskId||await v(r,n,i)||"untracked"
4895
+ m.info("Creating directory: "+h,{taskId:C,path:h,comment:g}),d.validateTaskIdFormat(C,m,p,I.metricsPrefix),r.getCurrentBranchContext&&await r.getCurrentBranchContext()
4896
+ const{normalizedPath:_,fullPath:E}=d.validateAndNormalizePath(h,r)
4897
+ b=d.FileOperationPhase.TASK_VALIDATION,p.incrementCounter("create_directory_phase",1,{phase:b})
4898
+ const q=await d.validateTaskId(C,_,n,m,p,I.metricsPrefix),S=q?.requestId,T=await d.validateWorkItemStates(C,_,n,s,r,m,p,I.metricsPrefix),P=await d.autoPromoteTaskStatus(C,q.status,S,T.request?.status,_,n,s,m,p,I.metricsPrefix)
4899
+ P.taskPromoted&&m.info(`Auto-promoted task ${C} (${q.title||"Untitled"}) to in_progress for file operation`,{taskId:C,taskTitle:q.title,previousStatus:q.status,newStatus:P.newTaskStatus,path:_}),P.requestPromoted&&m.info(`Auto-promoted request ${S} to in_progress for file operation`,{requestId:S,previousStatus:T.request?.status,newStatus:P.newRequestStatus,triggeringTaskId:C})
4900
+ const j=await d.ensureCorrectWorkspaceContext({taskPromoted:P.taskPromoted,requestId:S,context:r,operation:"create-directory",logger:m,metrics:p,metricsPrefix:I.metricsPrefix})
4901
+ if(!j.success){if(j.isLockConflict)return{content:[{type:"text",text:"\u274c "+j.error}],isError:!0}
4902
+ throw Error(j.error)}let R=!1
4903
+ try{R=(await a.default.stat(E)).isDirectory()}catch{R=!1}b=d.FileOperationPhase.RECORD_CREATION,p.incrementCounter("create_directory_phase",1,{phase:b})
4904
+ const{toolRecordId:x,localToolRecordId:M}=await d.createFileOperationRecords(C,S,r.projectId,I.recordType,_,{directoryExists:R,userComment:g},n,o,m,p,I.metricsPrefix,f)
4905
+ w=x,k=x,b=I.fileOperationPhase,p.incrementCounter("create_directory_phase",1,{phase:b})
4906
+ let O=R
4907
+ if(!R){await a.default.mkdir(E,{recursive:!0}),m.info("Successfully created directory "+_)
4908
+ try{const e=c.default.join(E,".gitkeep")
4909
+ await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),O=!0,m.info("Created .gitkeep file for Git tracking")}catch(e){m.warn("Failed to create .gitkeep file",{error:e instanceof Error?e.message:e+""}),O=!1}}const D=Date.now()-y
4910
+ p.recordValue("create_directory_time",D),p.incrementCounter("create_directory_success",1),b=d.FileOperationPhase.GIT_COMMIT,p.incrementCounter("create_directory_phase",1,{phase:b})
4911
+ const $=`Create directory: ${_} - ${g||"Create directory"}`,A=!R&&O?_+"/.gitkeep":_,F=await d.commitToGit(C,A,x,M,$,r,m,p,I.metricsPrefix)
4912
+ b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,p.incrementCounter("create_directory_phase",1,{phase:b}),await d.updateFileOperationRecords(C,w,k,_,I.recordType,`Successfully ${R?"verified":"created"} directory: ${_}`,{status:"completed",commitHash:F.commitHash,previousCommitHash:F.previousCommitHash,directoryExists:R,isDirectory:!0,userComment:g},`Successfully ${R?"verified":"created"} directory: ${_}`,n,o,m,p,I.metricsPrefix)
4913
+ const N=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
4914
+ return{content:[{type:"text",text:R?"Directory already exists":`Successfully created directory${F.commitHash?"\nCommit: "+F.commitHash.substring(0,8):""}${N.requestId&&!N.permanentBranch?"\nBranch: "+N.requestId:""}${j.lockAcquired&&j.lockedRequestId&&!N.permanentBranch?"\n\u{1f512} **Locked request:** "+j.lockedRequestId:""}`}]}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
4915
+ await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"create-directory",metadata:{status:"failed",timestamp:(new Date).toISOString(),path:e.path,userComment:e.comment,error:(0,g.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:`Failed to create directory ${e.path} - ${(0,g.getErrorMessage)(t)}`})}catch(t){m.error("Failed to create failure record for create directory operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,path:e.path})}const s=Date.now()-y
4916
+ if(p.recordValue("create_directory_time",s),p.incrementCounter("create_directory_errors",1),m.error("Error creating directory:",{error:(0,g.getErrorMessage)(t),time:s}),(w||k)&&e.taskId){b=d.FileOperationPhase.RECORD_UPDATE_FAILURE
4917
+ try{await d.updateFileOperationRecords(e.taskId,w,k,e.path,I.recordType,"Failed to create directory "+e.path,{status:"failed",error:(0,g.getErrorMessage)(t),userComment:e.comment},"Failed to create directory "+e.path,n,o,m,p,I.metricsPrefix)}catch(t){m.error("Failed to update record with failure status",{taskId:e.taskId,recordId:w,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(t,b,m,p,e,I)}}
4801
4918
  const a=i(t(1943)),c=i(t(6928)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(1569),g=t(8824)},8317(e,exports,t){"use strict"
4802
4919
  function r(e){const t=[]
4803
4920
  return"write-file"===e.type&&e.metadata?.path?t.push(e.metadata.path):"replace-in-files"===e.type&&e.metadata?.operations?e.metadata.operations.forEach((e=>{e.path&&t.push(e.path)})):"move-files"===e.type&&e.metadata?.successfulOperations?e.metadata.successfulOperations.forEach((e=>{e.destination&&t.push(e.destination)})):"delete-files"===e.type&&e.metadata?.paths?t.push(...e.metadata.paths):"manage-files"===e.type&&e.metadata?.operations&&e.metadata.operations.forEach((e=>{e.createDirectory?.path&&t.push(e.createDirectory.path),e.moveFiles?.moves&&e.moveFiles.moves.forEach((e=>{e.destination&&t.push(e.destination)})),e.deleteFiles?.targets&&e.deleteFiles.targets.forEach((e=>{e.path&&t.push(e.path)}))})),[...new Set(t)]}function n(e){switch(e){case"write-file":return"\u{1f4dd} Write File"
@@ -5042,7 +5159,19 @@ let r=0,n=0
5042
5159
  for(const t of e)t.startsWith("+")&&!t.startsWith("+++")&&r++,t.startsWith("-")&&!t.startsWith("---")&&n++
5043
5160
  I+=`\n**Changes:**${r>0||n>0?` (Added ${r} lines, removed ${n} lines)`:""}\n\`\`\`diff\n${t.diff}\n\`\`\`\n`}I+="\n"}return I+="\u{1f4a1} **Tips:**\n",I+="- Use `file-recover` with a commit hash to restore the file to a previous version\n",I+='- Use `{"branch": "main"}` to see only main branch history\n',I+='- Use `{"branch": "req123456"}` to see only request branch history\n\n',d.info("Branch-aware file history retrieved successfully",{path:m,versions:b.length,targetBranch:s,currentBranch:k.branch,duration:Date.now()-p}),u.incrementCounter("file_history_total",1,{success:!0,type:"file",mode:s?"single-branch":"combined"}),{content:[{type:"text",text:I}]}}catch(e){throw e}}(a,y,w,k,b,v,t,n,i,s,m))}catch(e){const t=Date.now()-m
5044
5161
  return i.error("File/Document history operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),a({tool:"file_history",success:!1}),s.incrementCounter("file_history_errors",1),{content:[{type:"text",text:"\u274c **History Operation Failed:** "+(0,p.getErrorMessage)(e)}],isError:!0}}}
5045
- const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),p=t(8824),f=a(t(5967)),m=a(t(7478)),{getCurrentBranch:y}=m},8850(e,exports,t){"use strict"
5162
+ const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),p=t(8824),f=a(t(5967)),m=a(t(7478)),{getCurrentBranch:y}=m},8849(e,exports,t){"use strict"
5163
+ var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
5164
+ var o=Object.getOwnPropertyDescriptor(t,r)
5165
+ o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[]
5166
+ for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
5167
+ return t},r(e)},function(e){if(e&&e.__esModule)return e
5168
+ var t={}
5169
+ if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
5170
+ return o(t,e),t})
5171
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkingDefs=void 0
5172
+ const i=s(t(6183)),a=t(4425)
5173
+ var c
5174
+ exports.checkingDefs=[{name:"commands",description:'Manage and run project commands (typecheck, lint, build, etc.) to verify your work. Operations: "list" to see available commands, "run" to execute one by name, "add" to register a new command for this project.',schema:i.CommandsSchema,annotations:{title:"Commands",readOnlyHint:!1},createsRecords:!0,handler:(c=a.handleCommands,(e,t)=>c(e,t.context,t.apiClient,t.logger,t.metrics,t.apiClient?.getToolRecordClient?.()))}]},8850(e,exports,t){"use strict"
5046
5175
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
5047
5176
  const r=t(6183),n=t(6891)
5048
5177
  exports.def={name:"task_file_history",description:"See all file changes made during a task. Use query_history tool instead.",schema:r.QueryHistorySchema,annotations:{title:"Task File History",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleTaskFileHistory)(e,t.context,t.apiClient,t.logger,t.metrics)}}},8851(e,exports,t){"use strict"
@@ -5339,51 +5468,51 @@ return t},o(e)},function(e){if(e&&e.__esModule)return e
5339
5468
  var t={}
5340
5469
  if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
5341
5470
  return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
5342
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceInFiles=async function(e,t,r,o,s,i,a,c){const b=i.child({tool:"replace_in_files"}),I=Date.now()
5343
- let v,C=u.FileOperationPhase.VALIDATION
5471
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceInFiles=async function(e,r,o,s,i,a,c,b){const I=a.child({tool:"replace_in_files"}),v=Date.now()
5472
+ let C,_=u.FileOperationPhase.VALIDATION
5344
5473
  try{if(e&&"string"==typeof e.operations)try{e.operations=JSON.parse(e.operations)}catch{}if(e&&Array.isArray(e.operations))for(const t of e.operations)t.old&&t.new&&!t.replacements&&(t.replacements=[{old:t.old,new:t.new,match_mode:t.match_mode}],delete t.old,delete t.new,delete t.match_mode)
5345
- const i=u.validateArgs(e,d.ReplaceInFilesSchema),{taskId:_,operations:E,fuzzy_match:q=!0,comment:S}=i
5346
- b.info("Replace in files batch operation",{taskId:_,operationCount:E.length,totalReplacements:E.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:q,comment:S})
5347
- const T=E.filter((e=>e.documentId)).map((e=>e.documentId))
5348
- if(T.length>0&&t.apiClient)try{await(0,m.ensureDocumentsNotLocked)(T,t.apiClient,b,a,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
5349
- throw e}C=u.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("replace_in_files_phase",1,{phase:C})
5350
- const P=E[0],j=P.documentId?"document:"+P.documentId:P.path
5351
- let R=Date.now()
5352
- const M=await u.validateTaskId(_,j,r,b,a,"replace_in_files")
5474
+ const E=u.validateArgs(e,d.ReplaceInFilesSchema),{resolveActiveTaskId:q}=await Promise.resolve().then(t.bind(t,3451)),S=e.taskId||await q(r,o,a)||"untracked",{operations:T,fuzzy_match:P=!0,comment:j}=E
5475
+ I.info("Replace in files batch operation",{taskId:S,operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,comment:j})
5476
+ const R=T.filter((e=>e.documentId)).map((e=>e.documentId))
5477
+ if(R.length>0&&r.apiClient)try{await(0,m.ensureDocumentsNotLocked)(R,r.apiClient,I,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
5478
+ throw e}_=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
5479
+ const x=T[0],M=x.documentId?"document:"+x.documentId:x.path
5480
+ let O=Date.now()
5481
+ const D=await u.validateTaskId(S,M,o,I,c,"replace_in_files")
5353
5482
  Date.now()
5354
- const x=M?.requestId,O=E.some((e=>e.path))
5355
- let D=!1
5356
- if(O&&x){R=Date.now()
5357
- const e=await u.validateWorkItemStates(_,j,r,s,t,b,a,"replace_in_files")
5358
- Date.now(),R=Date.now()
5359
- const n=await u.autoPromoteTaskStatus(_,M.status,x,e.request?.status,j,r,s,b,a,"replace_in_files")
5360
- n.taskPromoted&&b.info("Auto-promoted task to in_progress",{taskId:_,requestId:x,previousStatus:M.status,newStatus:n.newTaskStatus}),Date.now(),R=Date.now()
5361
- const o=await u.ensureCorrectWorkspaceContext({taskPromoted:n.taskPromoted,requestId:x,context:t,operation:"replace_in_files",logger:b,metrics:a,metricsPrefix:"replace_in_files"})
5362
- if(!o.success){if(o.isLockConflict)return{content:[{type:"text",text:"\u274c "+o.error}],isError:!0}
5363
- throw Error(o.error)}Date.now(),D=!0}if(T.length>0&&x)try{await(0,p.validateRequestStatusForDocumentOperation)(x,s,b,a,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
5364
- throw e}R=Date.now()
5365
- const $=new Map
5366
- if(b.info("\u{1f50d} Starting external edit detection",{hasFileOperations:O,hasGit:!!t.git,operationCount:E.length}),O&&t.git)for(const e of E)if(e.path&&!e.documentId)try{const r=u.validateAndNormalizePath(e.path,t),n=await l.default.readFile(r.fullPath,"utf8"),o=void 0!==e.fuzzy_match?e.fuzzy_match:q,s=[]
5483
+ const $=D?.requestId,A=T.some((e=>e.path))
5484
+ let F=!1
5485
+ if(A&&$){O=Date.now()
5486
+ const e=await u.validateWorkItemStates(S,M,o,i,r,I,c,"replace_in_files")
5487
+ Date.now(),O=Date.now()
5488
+ const t=await u.autoPromoteTaskStatus(S,D.status,$,e.request?.status,M,o,i,I,c,"replace_in_files")
5489
+ t.taskPromoted&&I.info("Auto-promoted task to in_progress",{taskId:S,requestId:$,previousStatus:D.status,newStatus:t.newTaskStatus}),Date.now(),O=Date.now()
5490
+ const n=await u.ensureCorrectWorkspaceContext({taskPromoted:t.taskPromoted,requestId:$,context:r,operation:"replace_in_files",logger:I,metrics:c,metricsPrefix:"replace_in_files"})
5491
+ if(!n.success){if(n.isLockConflict)return{content:[{type:"text",text:"\u274c "+n.error}],isError:!0}
5492
+ throw Error(n.error)}Date.now(),F=!0}if(R.length>0&&$)try{await(0,p.validateRequestStatusForDocumentOperation)($,i,I,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
5493
+ throw e}O=Date.now()
5494
+ const N=new Map
5495
+ if(I.info("\u{1f50d} Starting external edit detection",{hasFileOperations:A,hasGit:!!r.git,operationCount:T.length}),A&&r.git)for(const e of T)if(e.path&&!e.documentId)try{const t=u.validateAndNormalizePath(e.path,r),n=await l.default.readFile(t.fullPath,"utf8"),o=void 0!==e.fuzzy_match?e.fuzzy_match:P,s=[]
5367
5496
  for(const t of e.replacements){const r=(0,h.findMatches)(n,t.old,o,100,e.path)
5368
- s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,r.fullPath)
5369
- b.info("\u{1f50d} Checking for external edits",{path:r.normalizedPath,affectedLines:o.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),matchCount:s.length})
5370
- const i=await(0,w.detectExternalEdits)(t.git,o,b)
5371
- b.info("\u{1f50d} External edit detection result",{path:r.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?($.set(e.path,{message:i.message,debugInfo:i.debugInfo}),b.warn("\u26a0\ufe0f External edits detected before auto-commit",{path:r.normalizedPath,conflictingLines:i.conflictingLines})):(i.debugInfo&&$.set(e.path,{message:"",debugInfo:i.debugInfo}),b.info("\u2705 No external edit conflicts detected",{path:r.normalizedPath}))}else b.info("\u2139\ufe0f No matches found for external edit detection",{path:r.normalizedPath}),$.set(e.path,{message:"",debugInfo:{detectionRan:!1,reason:"No matches found - patterns not found in file",affectedRegion:"none",uncommittedChanges:"not checked",overlapDetected:!1}})}catch(t){b.warn("Failed to check for external edits before auto-commit",{path:e.path,error:(0,k.getErrorMessage)(t)})}if(Date.now(),R=Date.now(),O&&t.git)try{b.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
5372
- const e=await(0,f.commitUserChangesBeforeToolOperation)(t.git,"replace_in_files",{requestId:x,taskId:_,workspaceManager:t.workspaceManager},b,a)
5373
- e.userChangesCommitted&&(b.debug("[REPLACE-IN-FILES] User changes committed",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),b.info("User changes committed before batch operation",{taskId:_,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){b.warn("Pre-tool user changes commit failed",{taskId:_,error:e instanceof Error?e.message:e+""})}Date.now(),R=Date.now(),C=u.FileOperationPhase.RECORD_CREATION,a.incrementCounter("replace_in_files_phase",1,{phase:C})
5374
- const{toolRecordId:A}=await u.createFileOperationRecords(_,x,t.projectId,"replace-in-files",j,{operationCount:E.length,totalReplacements:E.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:q,userComment:S},r,o,b,a,"replace_in_files",c)
5375
- v=A,Date.now(),R=Date.now(),C=u.FileOperationPhase.STRING_REPLACEMENT,a.incrementCounter("replace_in_files_phase",1,{phase:C})
5376
- const F=[],N=[]
5377
- for(const e of E){const r=e.path?$.get(e.path):void 0,o=await n(e,q,t,0,0,r?.message,r?.debugInfo)
5378
- F.push(o),o.successfulReplacements>0&&"file"===o.type&&o.path&&N.push(o.path)}Date.now(),R=Date.now()
5379
- const L=E.filter((e=>e.path&&!e.documentId)).map((e=>({path:e.path}))),z=await u.handleMultiFileGitCommit(_,L,F,N.length,{operationType:"Replace in files",toolRecordId:A||v||"unknown",successField:"successfulReplacements",logger:b,metrics:a,metricsPrefix:"replace_in_files"},t),H=z.commitHash
5497
+ s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,t.fullPath)
5498
+ I.info("\u{1f50d} Checking for external edits",{path:t.normalizedPath,affectedLines:o.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),matchCount:s.length})
5499
+ const i=await(0,w.detectExternalEdits)(r.git,o,I)
5500
+ I.info("\u{1f50d} External edit detection result",{path:t.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?(N.set(e.path,{message:i.message,debugInfo:i.debugInfo}),I.warn("\u26a0\ufe0f External edits detected before auto-commit",{path:t.normalizedPath,conflictingLines:i.conflictingLines})):(i.debugInfo&&N.set(e.path,{message:"",debugInfo:i.debugInfo}),I.info("\u2705 No external edit conflicts detected",{path:t.normalizedPath}))}else I.info("\u2139\ufe0f No matches found for external edit detection",{path:t.normalizedPath}),N.set(e.path,{message:"",debugInfo:{detectionRan:!1,reason:"No matches found - patterns not found in file",affectedRegion:"none",uncommittedChanges:"not checked",overlapDetected:!1}})}catch(t){I.warn("Failed to check for external edits before auto-commit",{path:e.path,error:(0,k.getErrorMessage)(t)})}if(Date.now(),O=Date.now(),A&&r.git)try{I.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
5501
+ const e=await(0,f.commitUserChangesBeforeToolOperation)(r.git,"replace_in_files",{requestId:$,taskId:S,workspaceManager:r.workspaceManager},I,c)
5502
+ e.userChangesCommitted&&(I.debug("[REPLACE-IN-FILES] User changes committed",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),I.info("User changes committed before batch operation",{taskId:S,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){I.warn("Pre-tool user changes commit failed",{taskId:S,error:e instanceof Error?e.message:e+""})}Date.now(),O=Date.now(),_=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
5503
+ const{toolRecordId:L}=await u.createFileOperationRecords(S,$,r.projectId,"replace-in-files",M,{operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,userComment:j},o,s,I,c,"replace_in_files",b)
5504
+ C=L,Date.now(),O=Date.now(),_=u.FileOperationPhase.STRING_REPLACEMENT,c.incrementCounter("replace_in_files_phase",1,{phase:_})
5505
+ const z=[],H=[]
5506
+ for(const e of T){const t=e.path?N.get(e.path):void 0,o=await n(e,P,r,0,0,t?.message,t?.debugInfo)
5507
+ z.push(o),o.successfulReplacements>0&&"file"===o.type&&o.path&&H.push(o.path)}Date.now(),O=Date.now()
5508
+ const B=T.filter((e=>e.path&&!e.documentId)).map((e=>({path:e.path}))),U=await u.handleMultiFileGitCommit(S,B,z,H.length,{operationType:"Replace in files",toolRecordId:L||C||"unknown",successField:"successfulReplacements",logger:I,metrics:c,metricsPrefix:"replace_in_files"},r),G=U.commitHash
5380
5509
  Date.now(),Date.now()
5381
- const B=F.filter((e=>e.success)).length,U=F.length-B,G=F.reduce(((e,t)=>e+t.successfulReplacements),0),W=F.reduce(((e,t)=>e+t.failedReplacements),0),V=F.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,replacements:e.replacements.map((e=>({old_str:e.old,new_str:e.new,success:e.success,error:e.error,matchesFound:e.matchesFound,matchType:e.matchType,lines:e.lines})))}))),J=F.filter((e=>e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements}))),K=F.filter((e=>!e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,error:e.error,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements})))
5382
- await o.updateToolRecord(v,{metadata:{path:j,status:0===U?"completed":"partial",operationCount:E.length,operations:V,successfulFiles:J,failedFiles:K,successfulReplacements:G,failedReplacements:W,processingTime:Date.now()-I,userComment:S,...z.success&&z.commitHash&&{commitHash:z.commitHash,previousCommitHash:z.previousCommitHash||void 0}}})
5383
- const Y=await async function(e,t,r,n,o,s){const i=e.filter((e=>e.success)).length,a=e.length-i,c=e.filter((e=>!e.success&&!e.error&&e.successfulReplacements>0)).length
5510
+ const W=z.filter((e=>e.success)).length,V=z.length-W,J=z.reduce(((e,t)=>e+t.successfulReplacements),0),K=z.reduce(((e,t)=>e+t.failedReplacements),0),Y=z.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,replacements:e.replacements.map((e=>({old_str:e.old,new_str:e.new,success:e.success,error:e.error,matchesFound:e.matchesFound,matchType:e.matchType,lines:e.lines})))}))),Q=z.filter((e=>e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements}))),Z=z.filter((e=>!e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,error:e.error,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements})))
5511
+ await s.updateToolRecord(C,{metadata:{path:M,status:0===V?"completed":"partial",operationCount:T.length,operations:Y,successfulFiles:Q,failedFiles:Z,successfulReplacements:J,failedReplacements:K,processingTime:Date.now()-v,userComment:j,...U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}}})
5512
+ const X=await async function(e,t,r,n,o,s){const i=e.filter((e=>e.success)).length,a=e.length-i,c=e.filter((e=>!e.success&&!e.error&&e.successfulReplacements>0)).length
5384
5513
  let l="## Replace In Files - Batch Results\n\n"
5385
- if(o.getCurrentBranchContext)try{const e=await o.getCurrentBranchContext()
5386
- e.branch&&(l+=`**Current Branch:** ${e.branch}\n\n`)}catch(e){}l+="**Summary:**\n",l+=`- **Files/Documents:** ${e.length} total`,l+=c>0?` (\u2705 ${i} fully succeeded, \u26a0\ufe0f ${c} partial, \u274c ${a-c} failed)\n`:` (\u2705 ${i} successful, \u274c ${a} failed)\n`,l+=`- **Replacements:** ${r+n} total (\u2705 ${r} successful, \u274c ${n} failed)\n`,t&&(l+=`- **Git Commit:** ${t.substring(0,8)}\n`),s&&(l+=`[RECORD:${s}]\n`),l+="\n---\n\n"
5514
+ if(o.workspaceManager)try{const e=o.workspaceManager.getCurrentContext(o.currentSessionId)
5515
+ e.branchName&&!e.permanentBranch&&(l+=`**Current Branch:** ${e.branchName}\n\n`)}catch(e){}l+="**Summary:**\n",l+=`- **Files/Documents:** ${e.length} total`,l+=c>0?` (\u2705 ${i} fully succeeded, \u26a0\ufe0f ${c} partial, \u274c ${a-c} failed)\n`:` (\u2705 ${i} successful, \u274c ${a} failed)\n`,l+=`- **Replacements:** ${r+n} total (\u2705 ${r} successful, \u274c ${n} failed)\n`,t&&(l+=`- **Git Commit:** ${t.substring(0,8)}\n`),s&&(l+=`[RECORD:${s}]\n`),l+="\n---\n\n"
5387
5516
  for(let t=0;t<e.length;t++){const r=e[t],n="document"===r.type?""+(r.filename||r.documentId):r.path
5388
5517
  l+=`### ${"document"===r.type?"DOC":"FILE"} ${n}\n\n`,r.error?(l+="- **Status:** \u274c Failed\n",l+="- **File Modified:** No\n",l+=`- **Error:** ${r.error}\n\n`):r.success?(l+="- **Status:** \u2705 Success\n",l+="- **File Modified:** Yes\n",l+=`- **Replacements:** ${r.successfulReplacements} successful\n`):(r.successfulReplacements>0?(l+="- **Status:** \u26a0\ufe0f Partial Success\n",l+="- **File Modified:** Yes (partial changes applied)\n"):(l+="- **Status:** \u274c Failed\n",l+="- **File Modified:** No\n"),l+=`- **Replacements:** ${r.successfulReplacements} successful, ${r.failedReplacements} failed\n`),r.externalEditWarning&&(l+=`\n${r.externalEditWarning}\n`)
5389
5518
  const o=r.replacements.filter((e=>e.success))
@@ -5391,9 +5520,9 @@ if(o.length>0){l+="\n**Successful Replacements:**\n"
5391
5520
  for(const e of o)l+=`- \u2705 \`${e.old.substring(0,40)}${e.old.length>40?"...":""}\` \u2192 \`${e.new.substring(0,40)}${e.new.length>40?"...":""}\``,e.matchesFound&&(l+=` (${e.matchesFound} occurrence${e.matchesFound>1?"s":""})`),e.lines&&e.lines.length>0&&3>=e.lines.length?l+=` at line${e.lines.length>1?"s":""} ${e.lines.join(", ")}`:e.lines&&e.lines.length>3&&(l+=` at ${e.lines.length} locations`),l+="\n"}const s=r.replacements.filter((e=>!e.success))
5392
5521
  if(s.length>0){l+="\n**Failed Replacement Details:**\n"
5393
5522
  for(const e of s)l+=`- \u274c \`${e.old.substring(0,40)}${e.old.length>40?"...":""}\` \u2192 \`${e.new.substring(0,40)}${e.new.length>40?"...":""}\`: ${e.error}\n`,e.details&&e.details.length>0&&(l+=" **Candidates found:**\n",l+=e.details.slice(0,5).map((e=>` - Line ${e.line}: \`${e.actually_matched.substring(0,40)}${e.actually_matched.length>40?"...":""}\` (${e.match_type})`)).join("\n")+"\n",e.details.length>5&&(l+=` ... and ${e.details.length-5} more matches\n`)),e.similarMatches&&e.similarMatches.length>0&&(l+=" **Did you mean? (Similar matches found):**\n",l+=e.similarMatches.map((e=>` - Line ${e.line}: \`${e.text.substring(0,60)}${e.text.length>60?"...":""}\` (${e.reason}, similarity: ${(100*e.similarity).toFixed(0)}%)`)).join("\n")+"\n")}l+="\n"}const d=e.filter((e=>"document"===e.type&&(e.success||e.successfulReplacements>0)))
5394
- return d.length>0&&(l+=`\n**Document Changes:** ${d.length} modified document(s) synced back to tracking system.\n`),o.workspaceManager?.largeFileWarning&&(l+=o.workspaceManager.largeFileWarning,o.workspaceManager.largeFileWarning=""),l}(F,H,G,W,t,v)
5395
- return{content:[{type:"text",text:Y}],isError:0===G}}catch(e){const t=Date.now()-I
5396
- if(b.error("Replace in files batch operation failed",{error:e instanceof Error?e.stack:e+"",duration:t,phase:C}),v)try{await o.updateToolRecord(v,{metadata:{status:"failed",error:(0,k.getErrorMessage)(e),phase:C,duration:t}})}catch(e){}return a.incrementCounter("replace_in_files_errors",1,{phase:C}),{content:[{type:"text",text:"\u274c **Replace In Files Failed:** "+(0,k.getErrorMessage)(e)}],isError:!0}}}
5523
+ return d.length>0&&(l+=`\n**Document Changes:** ${d.length} modified document(s) synced back to tracking system.\n`),o.workspaceManager?.largeFileWarning&&(l+=o.workspaceManager.largeFileWarning,o.workspaceManager.largeFileWarning=""),l}(z,G,J,K,r,C)
5524
+ return{content:[{type:"text",text:X}],isError:0===J}}catch(e){const t=Date.now()-v
5525
+ if(I.error("Replace in files batch operation failed",{error:e instanceof Error?e.stack:e+"",duration:t,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{status:"failed",error:(0,k.getErrorMessage)(e),phase:_,duration:t}})}catch(e){}return c.incrementCounter("replace_in_files_errors",1,{phase:_}),{content:[{type:"text",text:"\u274c **Replace In Files Failed:** "+(0,k.getErrorMessage)(e)}],isError:!0}}},c(t(857))
5397
5526
  const l=c(t(1943)),d=(a(t(9896)),a(t(6928)),c(t(6982)),t(6183)),u=a(t(5967)),h=t(3626),g=t(9860),p=t(5003),f=t(7478),m=t(9949),y=t(9947),w=t(1318),k=t(8824)},9470(e,exports){"use strict"
5398
5527
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseLineSpec=function(e){if(!e||""===e.trim())throw Error("Line specification cannot be empty")
5399
5528
  const t=e.trim()
@@ -5453,30 +5582,31 @@ o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(
5453
5582
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.UnauthorizedError=exports.McpProtocolError=exports.FileOperationError=exports.ServiceError=exports.DatabaseError=exports.AuthorizationError=exports.AuthenticationError=exports.ValidationError=exports.NotFoundError=exports.AppError=exports.ErrorUtils=exports.ERROR_TYPE_PROPERTIES=exports.isRetryableError=exports.errorToResponse=exports.isAppError=exports.createMcpProtocolError=exports.createFileOperationError=exports.createServiceError=exports.createDatabaseError=exports.createAuthorizationError=exports.createAuthenticationError=exports.createValidationError=exports.createNotFoundError=exports.createAppError=exports.createErrorResponse=void 0
5454
5583
  const o=t(8625)
5455
5584
  Object.defineProperty(exports,"createErrorResponse",{enumerable:!0,get(){return o.createErrorResponse}}),Object.defineProperty(exports,"createAppError",{enumerable:!0,get(){return o.createAppError}}),Object.defineProperty(exports,"createNotFoundError",{enumerable:!0,get(){return o.createNotFoundError}}),Object.defineProperty(exports,"createValidationError",{enumerable:!0,get(){return o.createValidationError}}),Object.defineProperty(exports,"createAuthenticationError",{enumerable:!0,get(){return o.createAuthenticationError}}),Object.defineProperty(exports,"createAuthorizationError",{enumerable:!0,get(){return o.createAuthorizationError}}),Object.defineProperty(exports,"createDatabaseError",{enumerable:!0,get(){return o.createDatabaseError}}),Object.defineProperty(exports,"createServiceError",{enumerable:!0,get(){return o.createServiceError}}),Object.defineProperty(exports,"createFileOperationError",{enumerable:!0,get(){return o.createFileOperationError}}),Object.defineProperty(exports,"createMcpProtocolError",{enumerable:!0,get(){return o.createMcpProtocolError}}),Object.defineProperty(exports,"isAppError",{enumerable:!0,get(){return o.isAppError}}),Object.defineProperty(exports,"errorToResponse",{enumerable:!0,get(){return o.errorToResponse}}),Object.defineProperty(exports,"isRetryableError",{enumerable:!0,get(){return o.isRetryableError}}),Object.defineProperty(exports,"ERROR_TYPE_PROPERTIES",{enumerable:!0,get(){return o.ERROR_TYPE_PROPERTIES}}),Object.defineProperty(exports,"ErrorUtils",{enumerable:!0,get(){return o.ErrorUtils}}),Object.defineProperty(exports,"AppError",{enumerable:!0,get(){}}),Object.defineProperty(exports,"NotFoundError",{enumerable:!0,get(){return o.NotFoundError}}),Object.defineProperty(exports,"ValidationError",{enumerable:!0,get(){return o.ValidationError}}),Object.defineProperty(exports,"AuthenticationError",{enumerable:!0,get(){return o.AuthenticationError}}),Object.defineProperty(exports,"AuthorizationError",{enumerable:!0,get(){return o.AuthorizationError}}),Object.defineProperty(exports,"DatabaseError",{enumerable:!0,get(){return o.DatabaseError}}),Object.defineProperty(exports,"ServiceError",{enumerable:!0,get(){return o.ServiceError}}),Object.defineProperty(exports,"FileOperationError",{enumerable:!0,get(){return o.FileOperationError}}),Object.defineProperty(exports,"McpProtocolError",{enumerable:!0,get(){return o.McpProtocolError}}),Object.defineProperty(exports,"UnauthorizedError",{enumerable:!0,get(){return o.UnauthorizedError}}),n(t(441),exports)},9863(e,exports,t){"use strict"
5456
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListTasks=async function(e,t,s,i,a){const c=i.child({tool:"list_tasks"})
5457
- c.info("Listing tasks",{args:e})
5458
- const l=a.startTimer("tool_handler_duration")
5459
- try{const{requestId:i,filters:d}=function(e){try{const t=r.ListTasksSchema.parse(e),{requestId:n}=t,o=t.filters||{},s={}
5585
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListTasks=async function(e,t,i,a,c){const l=a.child({tool:"list_tasks"})
5586
+ l.info("Listing tasks",{args:e})
5587
+ const d=c.startTimer("tool_handler_duration")
5588
+ try{const{requestId:a,filters:u}=function(e){try{const t=r.ListTasksSchema.parse(e),{requestId:n}=t,o=t.filters||{},s={}
5460
5589
  if(o.status&&void 0!==o.status){const e=o.status+""
5461
5590
  "undefined"!==e&&(s.status=e)}s.limit=o.limit??20,s.offset=o.offset??0,s.sortBy="created"===o.sortBy?"created_at":(o.sortBy,"updated_at")
5462
5591
  const i=o.sortDirection??"desc"
5463
- return s.sortDirection="asc"===i||"desc"===i?i:"desc",{requestId:n,filters:s}}catch(t){throw new n.ValidationError("Invalid input: "+(0,o.getErrorMessage)(t),{args:e,error:t})}}(e),u=t.projectId
5464
- if(!u)throw new n.ValidationError("Project ID is required for listing tasks with the new API structure")
5465
- a.incrementCounter("list_tasks_attempts",1,{hasRequestId:!!i,hasFilters:Object.keys(d).length>0}),s.setProjectId(u)
5466
- const h=s.getTaskClient(),g=d
5467
- i&&(g.requestId=i),c.info("Listing tasks with filters",{projectId:u,taskFilters:g})
5468
- const p=await h.listTasks(g)
5469
- c.info("Raw tasks response data",{responseData:JSON.stringify(p)}),c.info("Tasks response structure",{type:typeof p,isArray:Array.isArray(p),hasData:null!=p,properties:p?Object.keys(p):[],dataPreview:p?JSON.stringify(p).substring(0,200)+"...":"null"})
5470
- let f=[]
5471
- p&&"object"==typeof p?"success"in p&&"data"in p?Array.isArray(p.data)?(f=p.data,c.info("Extracted tasks from success/data wrapper",{count:f.length})):p.data&&"object"==typeof p.data&&(f=[p.data],c.info("Extracted single task from success/data wrapper")):"data"in p?Array.isArray(p.data)?(f=p.data,c.info("Extracted tasks from data wrapper",{count:f.length})):p.data&&"object"==typeof p.data&&(f=[p.data],c.info("Extracted single task from data wrapper")):Array.isArray(p)?(f=p,c.info("Tasks response is direct array",{count:f.length})):(f=[p],c.info("Tasks response is single object")):(c.warn("Unexpected response format, using empty array",{responseType:typeof p}),f=[])
5472
- const m=f
5473
- if(c.info(`Retrieved ${m.length} tasks`,{count:m.length,requestId:i,projectId:u}),0===m.length){let e=""
5474
- return e=i?`No tasks found for request ${i}.`:`No tasks found for project ${u} with the specified filters.`,l({success:!0,taskCount:0}),{content:[{type:"text",text:e}]}}const y=m.map((e=>`**[${e.id}]** ${e.title}\nStatus: ${e.status}\nCreated: ${new Date(e.createdAt).toLocaleString()}\nUpdated: ${new Date(e.updatedAt).toLocaleString()}`)).join("\n\n")
5475
- let w
5476
- return w=i?`Found ${m.length} task${1===m.length?"":"s"} for request ${i}:`:`Found ${m.length} task${1===m.length?"":"s"} for project ${u}:`,l({success:!0,taskCount:m.length}),{content:[{type:"text",text:`${w}\n\n${y}`}]}}catch(t){c.error("Failed to list tasks",{error:t instanceof Error?t.stack:t+"",args:e}),l({success:!1,error:t instanceof Error?t.name:"unknown"})
5592
+ return s.sortDirection="asc"===i||"desc"===i?i:"desc",{requestId:n,filters:s}}catch(t){throw new n.ValidationError("Invalid input: "+(0,o.getErrorMessage)(t),{args:e,error:t})}}(e),h=t.projectId
5593
+ if(!h)throw new n.ValidationError("Project ID is required for listing tasks with the new API structure")
5594
+ c.incrementCounter("list_tasks_attempts",1,{hasRequestId:!!a,hasFilters:Object.keys(u).length>0}),i.setProjectId(h)
5595
+ const g=i.getTaskClient(),p=u
5596
+ a&&(p.requestId=a),l.info("Listing tasks with filters",{projectId:h,taskFilters:p})
5597
+ const f=await g.listTasks(p)
5598
+ l.info("Raw tasks response data",{responseData:JSON.stringify(f)}),l.info("Tasks response structure",{type:typeof f,isArray:Array.isArray(f),hasData:null!=f,properties:f?Object.keys(f):[],dataPreview:f?JSON.stringify(f).substring(0,200)+"...":"null"})
5599
+ let m=[]
5600
+ f&&"object"==typeof f?"success"in f&&"data"in f?Array.isArray(f.data)?(m=f.data,l.info("Extracted tasks from success/data wrapper",{count:m.length})):f.data&&"object"==typeof f.data&&(m=[f.data],l.info("Extracted single task from success/data wrapper")):"data"in f?Array.isArray(f.data)?(m=f.data,l.info("Extracted tasks from data wrapper",{count:m.length})):f.data&&"object"==typeof f.data&&(m=[f.data],l.info("Extracted single task from data wrapper")):Array.isArray(f)?(m=f,l.info("Tasks response is direct array",{count:m.length})):(m=[f],l.info("Tasks response is single object")):(l.warn("Unexpected response format, using empty array",{responseType:typeof f}),m=[])
5601
+ const y=m
5602
+ if(l.info(`Retrieved ${y.length} tasks`,{count:y.length,requestId:a,projectId:h}),0===y.length){let e=""
5603
+ return e=a?`No tasks found for request ${a}.`:`No tasks found for project ${h} with the specified filters.`,d({success:!0,taskCount:0}),{content:[{type:"text",text:e}]}}const w=y.map(((e,t)=>{const r=e.sequenceNumber??t+1
5604
+ return`**[${a?(0,s.formatTaskRef)(a,r):e.localId||e.id}]** ${e.title}\nStatus: ${e.status}\nCreated: ${new Date(e.createdAt).toLocaleString()}\nUpdated: ${new Date(e.updatedAt).toLocaleString()}`})).join("\n\n")
5605
+ let k
5606
+ return k=a?`Found ${y.length} task${1===y.length?"":"s"} for request ${a}:`:`Found ${y.length} task${1===y.length?"":"s"} for project ${h}:`,d({success:!0,taskCount:y.length}),{content:[{type:"text",text:`${k}\n\n${w}`}]}}catch(t){l.error("Failed to list tasks",{error:t instanceof Error?t.stack:t+"",args:e}),d({success:!1,error:t instanceof Error?t.name:"unknown"})
5477
5607
  let r=(0,o.getErrorMessage)(t)
5478
5608
  return t instanceof n.NotFoundError&&(r=`The request ID "${e.requestId}" was not found. Please provide a valid request ID.`),{content:[{type:"text",text:"Error: "+r}],isError:!0}}}
5479
- const r=t(6183),n=t(9860),o=t(8824)},9884(e,exports,t){"use strict"
5609
+ const r=t(6183),n=t(9860),o=t(8824),s=t(4466)},9884(e,exports,t){"use strict"
5480
5610
  Object.defineProperty(exports,"__esModule",{value:!0}),exports.DocumentClient=void 0
5481
5611
  const r=t(7645),n=t(2161),o=t(9949),s=t(9860),i=t(8824)
5482
5612
  class a extends r.ConnectionAwareClient{constructor(e,t,r,n,o,s,i,a){const c=t.child({component:"document-client"}),l=s||{isInOfflineMode(){return!1},isOffline(){return!1},setOfflineMode(){},async checkConnectivity(){return!0},getHealthCheckStats(){return{isOffline:!1,consecutiveFailures:0,currentBackoffMs:0,lastCheckTime:0}},cleanup(){}}