alchemylab 1.0.4 → 1.0.5
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/939.js +1 -1
- package/dist/cli.js +730 -670
- package/dist/http-server.js +169 -188
- package/dist/index.js +522 -541
- package/dist/mcp-direct.js +733 -752
- package/dist/plugins/hooks/plugin.js +2 -0
- package/package.json +2 -2
- package/dist/plugins/anthropic-auth.js +0 -399
- package/dist/plugins/auto-journal.js +0 -83
- package/dist/plugins/hooks/condition-evaluator.js +0 -109
- package/dist/plugins/hooks/dedup-utils.js +0 -66
- package/dist/plugins/hooks/hook-utils.js +0 -85
- package/dist/plugins/notify-parent.js +0 -95
package/dist/mcp-direct.js
CHANGED
|
@@ -12,30 +12,30 @@ u.info("Using project ID from context",{projectId:l}),c.incrementCounter("create
|
|
|
12
12
|
try{const e=i.getRequestClient(),t=await e.getRequest(a.requestId)
|
|
13
13
|
u.info("Raw request verification response data",{responseData:JSON.stringify(t)})
|
|
14
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"
|
|
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
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
|
|
17
|
+
const f=i.getTaskClient()
|
|
18
18
|
u.info("Creating task with project context",{projectId:l})
|
|
19
|
-
const
|
|
20
|
-
u.info("Task input prepared",{taskInput:JSON.stringify(
|
|
21
|
-
const m=await
|
|
19
|
+
const p={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(p)}),u.info("Creating task via task client",{projectId:l,requestId:a.requestId,title:a.title})
|
|
21
|
+
const m=await f.createTask(p)
|
|
22
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:
|
|
23
|
+
const y=(0,o.extractDataFromResponse)(m,{logger:u,operationName:"createTask",defaultValue:{id:"tas"+Date.now().toString().substring(5,11),title:p.title,description:p.description,status:"pending",requestId:p.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||p.title,I=w.description||p.description,v=w.status||"pending",C=w.requestId||p.requestId
|
|
24
24
|
let _,E="unknown"
|
|
25
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
26
|
try{const e=i.getToolRecordClient()
|
|
27
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
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
|
|
29
|
+
let q=`Created Task ${k}: ${b}`
|
|
30
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
31
|
else{const n=i.getToolRecordClient()
|
|
32
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
33
|
let o=(0,s.getErrorMessage)(r),c=""
|
|
34
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
35
|
const r=t(6183),n=t(9860),o=t(2960),s=t(8824)},184(e,exports,t){function r(e,t,r,n,o={}){const s=d.default.resolve(e)
|
|
36
|
-
if(
|
|
36
|
+
if(D.has(s))return t.child({component:"mcp-server-registry"}).debug("Using existing server for path",{path:s}),D.get(s)
|
|
37
37
|
const i=new $(s,t,r,n,o)
|
|
38
|
-
return
|
|
38
|
+
return D.set(s,i),i}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
39
39
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
40
40
|
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=[]
|
|
41
41
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -44,9 +44,9 @@ var t={}
|
|
|
44
44
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
45
45
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
46
46
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.McpServer=void 0,exports.resetStdoutWrite=function(){process.stdout.write=O},exports.getMcpServer=r,exports.createServer=function(e,t,n,o,s={}){return r(e,t,n,o,s)}
|
|
47
|
-
const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),
|
|
48
|
-
!(0,
|
|
49
|
-
class ${constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.clientInfo=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.multiAgentMode=o.multiAgentMode||!1,this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,multiAgentMode:o.multiAgentMode||!1,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,b.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
|
|
47
|
+
const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),f=t(3444),p=t(7660),m=t(1253),y=t(5172),w=t(7976),k=i(t(7478)),b=t(4139),I=new Set,v=t(9860),C=t(1472),_=t(3328),E=t(8955),q=t(3217),S=t(8411),T=t(5278),M=t(446),R=t(9060),P=t(8824),x=(0,f.createLogger)({serviceName:"stdout-capture",console:!1,logToFile:!1}),O=process.stdout.write,j=process.argv.includes("--stdio")||"true"===process.env.MCP_DIRECT_MODE
|
|
48
|
+
!(0,f.isDebugToolsEnabled)()||j&&"true"!==process.env.DEBUG_STDOUT_CAPTURE||(process.stdout.write=function(e){try{return(0,f.isDebugToolsEnabled)()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()&&"string"==typeof e&&!e.trim().startsWith('{"jsonrpc":"2.0"')&&e.trim().length>0&&x.debug("Stdout output",{content:e.substring(0,100),length:e.length}),O.call(process.stdout,e)}catch(e){return x.error("Error in safeStdoutWrite",{error:e+""}),!0}})
|
|
49
|
+
class ${constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.clientInfo=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.multiAgentMode=o.multiAgentMode||!1,this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,multiAgentMode:o.multiAgentMode||!1,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,b.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 p.ProjectContext(e,t),this.tokenManager=new m.TokenManager(t,e,{remoteServerUrl:n}),this.lockOverrideManager=new M.LockOverrideManager(t),this.configManager=new R.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:{}}}}),this.metrics.incrementCounter("mcp_server_init_started",1),this.interceptConnectMethod(),this.logger.info("Starting initialization for server instance"),this.initializationPromise=this.initialize()}get branchState(){if(!this.workspaceManager)return{currentBranch:null,activeRequestId:null,isOnMainBranch:!0}
|
|
50
50
|
const e=this.workspaceManager.getCurrentContext()
|
|
51
51
|
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}
|
|
52
52
|
const e=this.workspaceManager.getCurrentContext()
|
|
@@ -166,7 +166,7 @@ try{const t=await k.getCurrentBranch(this.git,this.logger,this.metrics)
|
|
|
166
166
|
return this.logger.info("Single-agent Git instance branch status",{requestId:e,currentBranch:t,expectedBranch:n.branchName,basePath:n.basePath}),{success:!0,message:`Switched to request ${e} context`}}catch(t){return this.logger.warn("Branch verification failed but continuing",{requestId:e,error:t instanceof Error?t.message:t+""}),{success:!0,message:`Switched to request ${e} context (branch verification warning)`}}}catch(t){return this.logger.error("Failed to switch to single-agent request context",{requestId:e,error:(0,P.getErrorMessage)(t)}),{success:!1,message:"Failed to switch to request context: "+(0,P.getErrorMessage)(t)}}}async getEffectiveBasePath(e){if(!this.multiAgentMode||!this.workspaceManager||!e)return this.basePath
|
|
167
167
|
const t=await this.workspaceManager.getWorkspaceInfo(e)
|
|
168
168
|
return t?.path||this.basePath}}exports.McpServer=$
|
|
169
|
-
const
|
|
169
|
+
const D=new Map},213(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
170
170
|
const r=t(6183),n=t(3707)
|
|
171
171
|
exports.def={name:"quick_write",description:"Create or update a file or document. Wraps the change in a request/task workflow that auto-completes.\n\nUse 'path' for filesystem files or 'documentId' for tracked documents.\nSet append:true to add content to existing content.\n\nRequires: title, description, path/documentId, content.",schema:r.QuickWriteSchema,annotations:{title:"Quick Write",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"write",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},233(e,exports,t){function r(e,t){const r=e.toLowerCase().indexOf(t.toLowerCase())
|
|
172
172
|
return-1===r?e:`${e.substring(0,r)}**${e.substring(r,r+t.length)}**${e.substring(r+t.length)}`}function n(e,t,r){const n=e.toLowerCase().indexOf(t)
|
|
@@ -184,12 +184,12 @@ case"quick-edit":return"\u26a1"
|
|
|
184
184
|
default:return"\u{1f4e6}"}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSearchRequests=async function(e,t,c,l,d){const u=l.child({tool:"search_requests"}),h=d.startTimer("tool_execution_time")
|
|
185
185
|
try{const{query:a,searchIn:l="all",filters:g={}}=e.search||e
|
|
186
186
|
if(!a||0===a.trim().length)throw new i.ValidationError("Search query is required")
|
|
187
|
-
const
|
|
188
|
-
if(!
|
|
189
|
-
u.info("Searching requests",{query:a,searchIn:l,filters:g,projectId:
|
|
190
|
-
const
|
|
191
|
-
g.status&&(
|
|
192
|
-
const m=c.getRequestClient(),y=await m.listRequests(
|
|
187
|
+
const f=t.projectId
|
|
188
|
+
if(!f)throw new i.ValidationError("Project ID is required for searching requests")
|
|
189
|
+
u.info("Searching requests",{query:a,searchIn:l,filters:g,projectId:f})
|
|
190
|
+
const p={limit:g.limit||100,offset:g.offset||0,sortBy:"updated_at",sortDirection:"desc"}
|
|
191
|
+
g.status&&(p.status=g.status),g.type&&(p.type=g.type),g.dateFrom&&(p.dateFrom=g.dateFrom),g.dateTo&&(p.dateTo=g.dateTo),c.setProjectId(f)
|
|
192
|
+
const m=c.getRequestClient(),y=await m.listRequests(p)
|
|
193
193
|
u.debug("Fetched requests for search",{count:y.length})
|
|
194
194
|
const w=[],k=a.toLowerCase()
|
|
195
195
|
for(const e of y){const t=[]
|
|
@@ -222,12 +222,18 @@ case"ready_for_review":t="ready_for_review"
|
|
|
222
222
|
break
|
|
223
223
|
case"pending_approval":case o.RequestStatus.PENDING_APPROVAL:t="pending_approval"
|
|
224
224
|
break
|
|
225
|
+
case"pending_verification":t="ready_for_review"
|
|
226
|
+
break
|
|
227
|
+
case"ready_for_merge":t="ready_for_merge"
|
|
228
|
+
break
|
|
229
|
+
case"resolving_conflicts":t="resolving_conflicts"
|
|
230
|
+
break
|
|
225
231
|
default:t="open"}else t="open"
|
|
226
232
|
const n=Array.isArray(e.acceptanceCriteria)?e.acceptanceCriteria.map(r):[]
|
|
227
233
|
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)}
|
|
228
|
-
const o=t(6756)},355(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteTask=async function(e,d,u,h,g){const
|
|
229
|
-
|
|
230
|
-
const
|
|
234
|
+
const o=t(6756)},355(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteTask=async function(e,d,u,h,g){const f=h.child({tool:"complete_task"})
|
|
235
|
+
f.info("Completing task",{args:e})
|
|
236
|
+
const p=g.startTimer("tool_handler_duration")
|
|
231
237
|
try{const{taskId:o,summary:h}=function(e){if(void 0!==e.verificationSteps){const{verificationSteps:t,...r}=e
|
|
232
238
|
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)
|
|
233
239
|
throw new n.ValidationError("Invalid input: "+(0,l.getErrorMessage)(e))}}(e),m=d.projectId
|
|
@@ -236,35 +242,35 @@ g.incrementCounter("complete_task_attempts",1,{taskId:o}),u.setProjectId(m)
|
|
|
236
242
|
const y=u.getTaskClient()
|
|
237
243
|
let w
|
|
238
244
|
try{const e=await y.getTask(o)
|
|
239
|
-
|
|
240
|
-
const t=(0,s.extractDataFromResponse)(e,{logger:
|
|
241
|
-
w="data"in t?t.data:t,
|
|
245
|
+
f.info("Raw task response data",{responseData:JSON.stringify(e)}),f.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"})
|
|
246
|
+
const t=(0,s.extractDataFromResponse)(e,{logger:f,operationName:"getTask",throwOnNoData:!0})
|
|
247
|
+
w="data"in t?t.data:t,f.info("Current task status: "+w.status,{taskId:o,currentStatus:w.status})}catch(e){if(e instanceof n.ValidationError)throw e
|
|
242
248
|
throw new n.NotFoundError(`Task ${o} not found in project ${m}. Please provide a valid task ID.`,{taskId:o,projectId:m,originalError:e})}if("completed"===w.status){const e="Task is already completed."
|
|
243
|
-
throw
|
|
244
|
-
throw
|
|
249
|
+
throw f.warn(e,{taskId:o,currentStatus:w.status}),new n.ValidationError(e)}if("canceled"===w.status){const e="Task is canceled and can not be completed."
|
|
250
|
+
throw f.warn(e,{taskId:o,currentStatus:w.status}),new n.ValidationError(e)}if(d.multiAgentMode&&w.requestId){f.debug("Multi-agent mode: checking request lock for task operation",{taskId:o,requestId:w.requestId})
|
|
245
251
|
try{const e=u.getRequestClient(),{sessionTag:t}=(0,a.getGlobalClientInfo)(),r=await e.getRequestLockStatus(w.requestId)
|
|
246
252
|
if(r.isLocked){if(r.lockedBySessionTag!==t){let e=`Request ${w.requestId} is locked by another agent (${r.lockedBySessionTag}). `
|
|
247
|
-
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:w.requestId,lockedByAgent:r.lockedBySessionTag,currentAgent:t,timeRemainingMs:r.timeRemainingMs,isExpired:r.isExpired})}}else{
|
|
253
|
+
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:w.requestId,lockedByAgent:r.lockedBySessionTag,currentAgent:t,timeRemainingMs:r.timeRemainingMs,isExpired:r.isExpired})}}else{f.debug("Lock not held, auto-acquiring for task completion",{requestId:w.requestId,sessionTag:t})
|
|
248
254
|
const r=await e.lockRequest(w.requestId,t)
|
|
249
255
|
if(!r.locked)throw new n.ValidationError(`Failed to acquire lock for request ${w.requestId}. Another agent may have just locked it. Try again shortly.`,{taskId:o,requestId:w.requestId})
|
|
250
|
-
|
|
251
|
-
throw
|
|
256
|
+
f.info("Auto-acquired lock for task completion",{requestId:w.requestId,sessionTag:t,lockedAt:r.lockedAt})}f.info("Request lock validation passed",{taskId:o,requestId:w.requestId,sessionTag:t})}catch(e){if(e instanceof n.ValidationError)throw e
|
|
257
|
+
throw f.error("Failed to check request lock status",{taskId:o,requestId:w.requestId,error:(0,l.getErrorMessage)(e)}),new n.ValidationError("Failed to verify request lock status: "+(0,l.getErrorMessage)(e),{taskId:o,requestId:w.requestId})}}else f.debug("Single-agent mode or task without requestId: skipping lock check",{taskId:o,isMultiAgent:(0,c.isMultiAgentModeEnabled)(),hasRequestId:!!w.requestId})
|
|
252
258
|
let k=d.git
|
|
253
259
|
if(d.workspaceManager){const e=d.workspaceManager.getCurrentContext()
|
|
254
260
|
if("multi-agent"===e.mode&&e.requestId){const{simpleGit}=t(3807)
|
|
255
|
-
k=simpleGit({baseDir:e.basePath,binary:d.gitBinary}),
|
|
256
|
-
if(k)try{(await k.status()).isClean()||(b=(await k.commit(`Complete task ${o}: ${h}`)).commit,
|
|
261
|
+
k=simpleGit({baseDir:e.basePath,binary:d.gitBinary}),f.debug("Using workspace-aware git instance for task completion",{taskId:o,mode:e.mode,requestId:e.requestId,basePath:e.basePath})}}let b=null
|
|
262
|
+
if(k)try{(await k.status()).isClean()||(b=(await k.commit(`Complete task ${o}: ${h}`)).commit,f.info("Created commit for task completion",{taskId:o,commitId:b}))}catch(e){f.warn("Failed to commit changes",{error:(0,l.getErrorMessage)(e)})}let I=null
|
|
257
263
|
try{const e=u.getToolRecordClient()
|
|
258
|
-
e&&(I={id:(await e.createToolRecord({taskId:o,requestId:w.requestId,projectId:m,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:w.title,completionSummary:h,lastCommit:b,completedAt:(new Date).toISOString()},note:`Completed task: ${h.substring(0,100)}${h.length>100?"...":""}`})).id})}catch(e){
|
|
259
|
-
|
|
264
|
+
e&&(I={id:(await e.createToolRecord({taskId:o,requestId:w.requestId,projectId:m,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:w.title,completionSummary:h,lastCommit:b,completedAt:(new Date).toISOString()},note:`Completed task: ${h.substring(0,100)}${h.length>100?"...":""}`})).id})}catch(e){f.error("Failed to create tool record for task completion, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:o,requestId:w.requestId})}try{const e=w.metadata||{},t=(new Date).toISOString(),r={status:"completed",metadata:{...e,lastCommit:b,completionSummary:h,completionRecordId:I?.id,completedAt:t}},n=await y.updateTask(o,r)
|
|
265
|
+
f.info("Raw task update response data",{responseData:JSON.stringify(n)}),f.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:f,operationName:"updateTask",defaultValue:{id:o,status:"completed"}}),f.info("Successfully completed task",{taskId:o,recordId:I?.id})
|
|
260
266
|
const i=w.requestId
|
|
261
|
-
let a=`Task ${o} has been marked as completed.`
|
|
267
|
+
let a=`Task ${o} (${w.title}) has been marked as completed.`
|
|
262
268
|
if(I?.id&&(a+=`\n[RECORD:${I.id}]`),b&&(a+="\nCommit: "+b.substring(0,8)),i)try{const e=await y.listTasks({requestId:i})
|
|
263
|
-
|
|
264
|
-
const t=(0,s.extractArrayFromResponse)(e,{logger:
|
|
265
|
-
|
|
269
|
+
f.info("Raw tasks list response data",{responseData:JSON.stringify(e)}),f.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"})
|
|
270
|
+
const t=(0,s.extractArrayFromResponse)(e,{logger:f,operationName:"listTasksForProgress",defaultValue:[]}),r=t.length,n=t.filter((e=>"completed"===e.status)).length
|
|
271
|
+
f.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){f.warn("Failed to check task progress",{error:(0,l.getErrorMessage)(e),requestId:i})}return p({success:!0}),{content:[{type:"text",text:a}]}}catch(e){throw f.error("Failed to complete task",{error:e instanceof Error?e.stack:e+"",taskId:o}),Error("Failed to complete task: "+(0,l.getErrorMessage)(e))}}catch(t){if(f.error("Failed to complete task",{error:t instanceof Error?t.stack:t+"",args:e}),d.projectId)try{const r=u.getToolRecordClient()
|
|
266
272
|
if(r){const o=t instanceof n.NotFoundError||t instanceof n.ValidationError||t instanceof i.ZodError
|
|
267
|
-
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,l.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",attemptedTaskId:e.taskId,taskIdValidationFailed:o},note:"Failed to complete task "+e.taskId})}}catch(e){
|
|
273
|
+
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,l.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",attemptedTaskId:e.taskId,taskIdValidationFailed:o},note:"Failed to complete task "+e.taskId})}}catch(e){f.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"})
|
|
268
274
|
let r=(0,l.getErrorMessage)(t)
|
|
269
275
|
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}}}
|
|
270
276
|
const r=t(6183),n=t(9860),o=t(5674),s=t(2960),i=t(1569),a=t(5172),c=t(5218),l=t(8824)},405(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
@@ -276,19 +282,21 @@ var t={}
|
|
|
276
282
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
277
283
|
return o(t,e),t})
|
|
278
284
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handlePlanWrite=async function(e,t,r,n,o){const s=n.child({tool:"plan_write"})
|
|
279
|
-
try{const n=
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
return o.incrementCounter("plan_write_total",1,{operation:"
|
|
284
|
-
return o.incrementCounter("plan_write_total",1,{operation:"
|
|
285
|
-
return o.incrementCounter("plan_write_total",1,{operation:"
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
if(!
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
285
|
+
try{const n=["update","append","replace","createSnapshot","restore","setActive"]
|
|
286
|
+
for(const t of n)e?.[t]&&"object"==typeof e[t]&&(Object.assign(e,e[t]),delete e[t])
|
|
287
|
+
const u=a.validateArgs(e,i.PlanWriteSchema),{operation:h,planId:g}=u
|
|
288
|
+
switch(s.info("Processing plan_write",{operation:h}),h){case"update":{const e=await(0,c.handleUpdatePlan)({planId:g,content:u.content,name:u.name},t,r,s,o)
|
|
289
|
+
return o.incrementCounter("plan_write_total",1,{operation:"update",success:!e.isError}),e}case"append":{const e=await(0,l.handleAppendPlan)({planId:g,content:u.content,name:u.name},r,s,o)
|
|
290
|
+
return o.incrementCounter("plan_write_total",1,{operation:"append",success:!e.isError}),e}case"replace":{const e=await(0,d.handleReplacePlan)({planId:g,old:u.old,new:u.new,name:u.name},r,s,o)
|
|
291
|
+
return o.incrementCounter("plan_write_total",1,{operation:"replace",success:!e.isError}),e}case"create-snapshot":{const{versionLabel:e,changeSummary:t}=u,n=r.getDocumentClient(),s=await n.createVersionSnapshot(g,e,t)
|
|
292
|
+
return o.incrementCounter("plan_write_total",1,{operation:"create-snapshot",success:!0}),{content:[{type:"text",text:`\u2705 **Plan Snapshot Created**\n\n**Plan:** ${g}\n**Version:** ${s.versionNumber}\n**Label:** ${e||"None"}\n**Summary:** ${t||"None"}\n**Created:** `+new Date(s.createdAt).toLocaleString()}]}}case"restore":{const{versionNumber:e}=u,t=r.getDocumentClient(),n=await t.restoreToVersion(g,e)
|
|
293
|
+
return o.incrementCounter("plan_write_total",1,{operation:"restore",success:!0}),{content:[{type:"text",text:`\u2705 **Plan Restored**\n\n**Plan:** ${g}\n**Restored to Version:** ${e}\n**Filename:** ${n.filename}\n\nThe plan has been successfully restored to version ${e}.`}]}}case"set-active":{const e=t.projectId
|
|
294
|
+
if(!e)return{content:[{type:"text",text:"\u274c No project context available."}],isError:!0}
|
|
295
|
+
const n=r.getDocumentClient(),s=await n.getDocument(g)
|
|
296
|
+
if(!s)return{content:[{type:"text",text:"\u274c Plan not found: "+g}],isError:!0}
|
|
297
|
+
if("Plan"!==s.type)return{content:[{type:"text",text:`\u274c Document ${g} is not a Plan (type: ${s.type}).`}],isError:!0}
|
|
298
|
+
const i=r.getProjectClient()
|
|
299
|
+
return await i.updateProject(e,{activePlanId:g}),o.incrementCounter("plan_write_total",1,{operation:"set-active",success:!0}),{content:[{type:"text",text:`\u2705 **Active Plan Updated**\n\n**Plan:** ${s.localId||s.id}\n**Filename:** ${s.filename}\n**Project:** ${e}\n\nThis plan is now the active project plan.`}]}}default:throw Error("Unknown plan_write operation: "+h)}}catch(e){return s.error("plan_write failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("plan_write_errors",1),{content:[{type:"text",text:"\u274c **Plan Write Failed:** "+(0,u.getErrorMessage)(e)}],isError:!0}}}
|
|
292
300
|
const i=t(6183),a=s(t(5967)),c=t(7609),l=t(4419),d=t(2352),u=t(8824)},410(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
293
301
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
294
302
|
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=[]
|
|
@@ -298,11 +306,12 @@ var t={}
|
|
|
298
306
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
299
307
|
return o(t,e),t})
|
|
300
308
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleTaskOperations=async function(e,t,r,n,o){const s=n.child({tool:"task_operations"})
|
|
301
|
-
try{
|
|
309
|
+
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)
|
|
310
|
+
const n=a.validateArgs(e,i.TaskOperationsSchema),{taskId:d,operation:u}=n
|
|
302
311
|
let h
|
|
303
312
|
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)
|
|
304
313
|
break
|
|
305
|
-
case"list":s.info("Routing to list-tasks handler",{requestId:n.requestId}),h=await(0,l.handleListTasks)({requestId:n.requestId,filters:n.
|
|
314
|
+
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)
|
|
306
315
|
break
|
|
307
316
|
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}}}
|
|
308
317
|
const i=t(6183),a=s(t(5967)),c=t(3420),l=t(9863),d=t(8824)},441(e,exports){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){Object.defineProperty(exports,"__esModule",{value:!0}),exports.LockOverrideManager=void 0,exports.createLockOverrideManager=function(e){return new n(e)}
|
|
@@ -381,23 +390,23 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
381
390
|
var t={}
|
|
382
391
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
383
392
|
return o(t,e),t})
|
|
384
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQueryHistory=async function(e,r,n,o,s,g){const
|
|
393
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQueryHistory=async function(e,r,n,o,s,g){const f=o.child({tool:"query_history"})
|
|
385
394
|
try{const o=a.validateArgs(e,i.QueryHistorySchema),{queryType:h}=o
|
|
386
|
-
let
|
|
387
|
-
switch(
|
|
395
|
+
let p
|
|
396
|
+
switch(f.info("Processing query_history request",{queryType:h}),h){case"file-history":f.info("Routing to file-history handler",{path:o.fileHistory.path}),p=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,f,s)
|
|
388
397
|
break
|
|
389
|
-
case"request-file-history":
|
|
398
|
+
case"request-file-history":f.info("Routing to request-file-history handler",{requestId:o.requestHistory.requestId}),p=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,f,s)
|
|
390
399
|
break
|
|
391
|
-
case"recover":
|
|
400
|
+
case"recover":f.info("Routing to file-recover handler",{taskId:o.recover.taskId,path:o.recover.path,commitHash:o.recover.commitHash})
|
|
392
401
|
let e=o.recover.commitHash
|
|
393
402
|
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)
|
|
394
403
|
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)
|
|
395
404
|
if(e=o[1]||o[0],!e)return{content:[{type:"text",text:"No previous versions found for "+n}],isError:!0}
|
|
396
|
-
|
|
405
|
+
f.info("Auto-resolved previous version",{filePath:n,commitHash:e})}catch{return{content:[{type:"text",text:"Could not find previous versions of "+n}],isError:!0}}}p=await(0,d.handleFileRecover)({taskId:o.recover.taskId,path:o.recover.path,commitHash:e,createBackup:o.recover.createBackup},r,n,n.getToolRecordClient(),f,s,g)
|
|
397
406
|
break
|
|
398
|
-
case"blame":
|
|
407
|
+
case"blame":f.info("Routing to file-blame handler",{path:o.blame.path,lines:o.blame.lines}),p=await(0,u.handleFileBlame)({path:o.blame.path,lines:o.blame.lines,branch:o.blame.branch},r,n,f,s)
|
|
399
408
|
break
|
|
400
|
-
default:throw Error("Unknown query type: "+h)}return
|
|
409
|
+
default:throw Error("Unknown query type: "+h)}return f.info("query_history request completed",{queryType:h,success:!p.isError}),s.incrementCounter("query_history_total",1,{success:!p.isError,queryType:h}),p}catch(e){return f.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}}}
|
|
401
410
|
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){function t(e){let t
|
|
402
411
|
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)
|
|
403
412
|
return{id:e.id,localId:e.local_id||e.localId,taskId:e.task_id||e.taskId||void 0,requestId:e.request_id||e.requestId||void 0,projectId:e.project_id||e.projectId||e.id,type:e.type,metadata:t,note:e.note||void 0,createdAt:e.created_at||e.createdAt||"",updatedAt:e.updated_at||e.updatedAt||""}}function r(e){let t=null
|
|
@@ -503,9 +512,9 @@ const t=this.remoteServerUrl+"/auth/validate"
|
|
|
503
512
|
this.logger.debug("Making token validation request",{validationUrl:t})
|
|
504
513
|
const r=await fetch(t,{method:"GET",headers:{Authorization:"Bearer "+e.token,"Content-Type":"application/json"},signal:AbortSignal.timeout(1e4)})
|
|
505
514
|
if(r.ok){const e=await r.json()
|
|
506
|
-
return this.logger.info("Token validation successful",{status:e.status||"unknown",username:e.username||"unknown"}),!0}return this.logger.info("Token validation failed - token may be invalid or expired",{status:r.status,statusText:r.statusText}),this.invalidateCache(),!1}catch(e){return e instanceof Error&&"AbortError"===e.name?(this.logger.info("Token validation request timed out - assuming offline or server unavailable"),!0):(this.logger.info("Token validation request failed",{error:(0,c.getErrorMessage)(e)}),!0)}}async hasValidAndWorkingToken(){return!!await this.hasValidToken()&&await this.validateTokenWithRemoteServer()}async isGoogleOAuthAvailable(){return await this.authFlow.isGoogleOAuthAvailable()}async startGoogleOAuthFlow(){return await this.authFlow.startGoogleOAuthFlow()}async startGoogleOAuthPolling(e,t,r,n,o){return await this.authFlow.startGoogleOAuthPolling(e,t,r,n,o)}}},1281(e,exports,t){async function r(e,t,o,s,i,a,c,l,d,u=0){let
|
|
515
|
+
return this.logger.info("Token validation successful",{status:e.status||"unknown",username:e.username||"unknown"}),!0}return this.logger.info("Token validation failed - token may be invalid or expired",{status:r.status,statusText:r.statusText}),this.invalidateCache(),!1}catch(e){return e instanceof Error&&"AbortError"===e.name?(this.logger.info("Token validation request timed out - assuming offline or server unavailable"),!0):(this.logger.info("Token validation request failed",{error:(0,c.getErrorMessage)(e)}),!0)}}async hasValidAndWorkingToken(){return!!await this.hasValidToken()&&await this.validateTokenWithRemoteServer()}async isGoogleOAuthAvailable(){return await this.authFlow.isGoogleOAuthAvailable()}async startGoogleOAuthFlow(){return await this.authFlow.startGoogleOAuthFlow()}async startGoogleOAuthPolling(e,t,r,n,o){return await this.authFlow.startGoogleOAuthPolling(e,t,r,n,o)}}},1281(e,exports,t){async function r(e,t,o,s,i,a,c,l,d,u=0){let f=0,p=0,m=0
|
|
507
516
|
const y=[]
|
|
508
|
-
if(o.length>=I||c>10)return a.debug("Stopping search in directory - hard cap or depth limit reached",{dir:e,matchesCount:o.length,hardCap:I,depth:c}),{filesCount:
|
|
517
|
+
if(o.length>=I||c>10)return a.debug("Stopping search in directory - hard cap or depth limit reached",{dir:e,matchesCount:o.length,hardCap:I,depth:c}),{filesCount:f,fileMatchesCount:p,subdirCount:m,subdirStats:y}
|
|
509
518
|
try{const w=await g.default.readdir(e,{withFileTypes:!0}),v=[],C=[]
|
|
510
519
|
for(const t of w){const r=h.default.join(e,t.name)
|
|
511
520
|
if(t.isDirectory()){if(b.includes(t.name)||t.name.startsWith(".")){a.debug("Skipping excluded directory: "+t.name)
|
|
@@ -514,15 +523,15 @@ continue}v.push({entry:t,fullPath:r})}}if(v.length>0){const e=[]
|
|
|
514
523
|
for(let t=0;t<v.length;t+=16)e.push(v.slice(t,t+16))
|
|
515
524
|
for(const r of e){if(o.length>=I)break
|
|
516
525
|
const e=await Promise.all(r.map((({entry:e,fullPath:r})=>n(r,t,0,o,l,d,e.name,u))))
|
|
517
|
-
for(const t of e){
|
|
518
|
-
for(const e of t.matches){if(o.length>=I)return{filesCount:
|
|
526
|
+
for(const t of e){f++,t.hasMatches&&p++
|
|
527
|
+
for(const e of t.matches){if(o.length>=I)return{filesCount:f,fileMatchesCount:p,subdirCount:m,subdirStats:y}
|
|
519
528
|
o.push(e)}}}}for(const{entry:e,fullPath:n}of C){if(o.length>=I)break
|
|
520
529
|
m++
|
|
521
530
|
const e={path:n,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
|
|
522
531
|
try{const l=await r(n,t,o,s,i,a,c+1,e,d,u)
|
|
523
|
-
|
|
532
|
+
f+=l.filesCount,p+=l.fileMatchesCount,e.filesProcessed=l.filesCount,e.filesMatched=l.fileMatchesCount,e.subdirectories=l.subdirCount,y.push(e),l.subdirStats&&l.subdirStats.length>0&&y.push(...l.subdirStats)}catch(t){const r=`Error processing subdirectory ${n}: ${(0,k.getErrorMessage)(t)}`
|
|
524
533
|
e.errors.push(r),y.push(e),a.error(r)}}}catch(t){const r=`Error searching directory ${e}: ${(0,k.getErrorMessage)(t)}`
|
|
525
|
-
l.errors.push(r),a.warn(r)}return{filesCount:
|
|
534
|
+
l.errors.push(r),a.warn(r)}return{filesCount:f,fileMatchesCount:p,subdirCount:m,subdirStats:y}}async function n(e,t,r,n,o,s,i,a=0){const c=[]
|
|
526
535
|
let l,d=!1
|
|
527
536
|
const u=async()=>{if(void 0===l)try{const t=await g.default.stat(e)
|
|
528
537
|
l=t.mtime.getTime()}catch(e){l=void 0}return l}
|
|
@@ -555,31 +564,31 @@ if(null!=e)for(var r=a(e),n=0;n<r.length;n++)"default"!==r[n]&&c(t,e,r[n])
|
|
|
555
564
|
return l(t,e),t}),u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
556
565
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSearch=async function(e,t,n,a,c){const l=a.child({tool:"search"}),d=c.startTimer("tool_execution_time"),u=Date.now()
|
|
557
566
|
let b=0
|
|
558
|
-
const I={searchDirectory:"",resolvedPath:"",patternInfo:{needle:"",regex:"",caseSensitive:!1,fileExtension:"",normalizedExtension:""},environmentInfo:{platform:process.platform,nodeVersion:process.version,hostname:
|
|
559
|
-
try{const{needle:n,directory:
|
|
560
|
-
if(!n||""===n.trim())return l.info("Empty needle detected, switching to list-all mode"),await(0,w.handleListDirectory)({path:
|
|
561
|
-
if("string"!=typeof n)throw I.errors.push("Search term (needle) must be a string"),(0,
|
|
567
|
+
const I={searchDirectory:"",resolvedPath:"",patternInfo:{needle:"",regex:"",caseSensitive:!1,fileExtension:"",normalizedExtension:""},environmentInfo:{platform:process.platform,nodeVersion:process.version,hostname:f.default.hostname(),username:f.default.userInfo().username,workingDirectory:process.cwd(),contextBasePath:t?.basePath||"unknown"},startTime:u,endTime:0,phases:{initializationTime:0,searchTime:0,directoryListingTime:0},totalFiles:0,totalMatches:0,directoryStats:[],errors:[]}
|
|
568
|
+
try{const{needle:n,directory:f,options:v={}}=e
|
|
569
|
+
if(!n||""===n.trim())return l.info("Empty needle detected, switching to list-all mode"),await(0,w.handleListDirectory)({path:f||".",levels:v.levels||1,sortBy:v.sortBy||"name"},t,a,c)
|
|
570
|
+
if("string"!=typeof n)throw I.errors.push("Search term (needle) must be a string"),(0,p.createValidationError)("Search term (needle) must be a string")
|
|
562
571
|
let C
|
|
563
|
-
if(I.searchDirectory=
|
|
572
|
+
if(I.searchDirectory=f||".",f){const{normalizedPath:e,fullPath:r}=m.validateAndNormalizePath(f,t)
|
|
564
573
|
C=r}else C=t.basePath
|
|
565
574
|
I.resolvedPath=C
|
|
566
575
|
let _=!1
|
|
567
576
|
try{_=(await g.default.stat(C)).isFile()}catch(e){const t=`Cannot access path ${C}: ${(0,k.getErrorMessage)(e)}`
|
|
568
577
|
throw I.errors.push(t),Error(t)}const E=v.maxResults||50,q=v.caseSensitive||!1,S=v.useRegex||!1,T=v.fileExtension,M=v.searchIn||"content"
|
|
569
578
|
let R=void 0!==v.contextLines?v.contextLines:0
|
|
570
|
-
if(0>R?R=0:R>10&&(l.warn(`contextLines ${R} exceeds maximum of 10, clamping to 10`),R=10),!_&&!T)throw I.errors.push('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")'),(0,
|
|
579
|
+
if(0>R?R=0:R>10&&(l.warn(`contextLines ${R} exceeds maximum of 10, clamping to 10`),R=10),!_&&!T)throw I.errors.push('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")'),(0,p.createValidationError)('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")')
|
|
571
580
|
let P,x=""
|
|
572
581
|
if(_)x="*"
|
|
573
582
|
else if("*"===T)x="*"
|
|
574
583
|
else if(T){let e=T;(e.startsWith("*.")||e.startsWith("*"))&&(e=e.substring(1)),x=e.startsWith(".")?e:"."+e}try{P=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)}`
|
|
575
|
-
throw I.errors.push(t),(0,
|
|
584
|
+
throw I.errors.push(t),(0,p.createValidationError)(t)}if(I.patternInfo={needle:n,regex:P.toString(),caseSensitive:q,fileExtension:T,normalizedExtension:x},!_)try{const e=Date.now(),t=await g.default.readdir(C,{withFileTypes:!0}),r=[],n=[]
|
|
576
585
|
for(const e of t)e.isDirectory()?r.push(e.name):e.isFile()&&n.push(e.name)
|
|
577
586
|
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)
|
|
578
587
|
I.errors.push(t),l.error(t)}const O=_?"file":"directory"
|
|
579
588
|
l.info(`Searching for "${n}" in ${O} ${C} (mode: ${M})`,{needle:n,searchTarget:O,path:C,options:{maxResults:E,caseSensitive:q,fileExtension:x,searchIn:M}}),b=Date.now(),I.phases.initializationTime=b-u
|
|
580
589
|
const j=Date.now()
|
|
581
|
-
let $=[],
|
|
582
|
-
try{const e=await async function(e,t,n,o,s,i){const{maxResults:a,fileExtension:c,searchIn:l,isFile:d,contextLines:u}=n,
|
|
590
|
+
let $=[],D=0,A=0
|
|
591
|
+
try{const e=await async function(e,t,n,o,s,i){const{maxResults:a,fileExtension:c,searchIn:l,isFile:d,contextLines:u}=n,f=[]
|
|
583
592
|
if(s.info("performLocalSearch started",{searchPath:e,pattern:t.toString(),options:n}),d)return await async function(e,t,r,n,o,s=0){const i=[],a=h.default.basename(e)
|
|
584
593
|
let c
|
|
585
594
|
n.info("Searching single file: "+e,{searchIn:r})
|
|
@@ -591,20 +600,20 @@ t.contextBefore=r.slice(e,n).map((e=>(0,y.truncate)(e.trim(),120)))
|
|
|
591
600
|
const o=Math.min(r.length,n+1+s)
|
|
592
601
|
t.contextAfter=r.slice(n+1,o).map((e=>(0,y.truncate)(e.trim(),120)))}i.push(t)}n.info(`Found ${i.filter((e=>"content"===e.matchType)).length} content matches`)}catch(t){const r=`Error reading file ${e}: ${(0,k.getErrorMessage)(t)}`
|
|
593
602
|
o.errors.push(r),n.error(r)}return{matches:i,totalFiles:1}}(e,t,l,s,i,u)
|
|
594
|
-
const
|
|
595
|
-
try{const{filesCount:n,fileMatchesCount:c,subdirCount:d,subdirStats:h}=await r(e,t,
|
|
596
|
-
return
|
|
597
|
-
return
|
|
598
|
-
$=e.matches,
|
|
603
|
+
const p={path:e,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
|
|
604
|
+
try{const{filesCount:n,fileMatchesCount:c,subdirCount:d,subdirStats:h}=await r(e,t,f,a,o,s,0,p,l,u)
|
|
605
|
+
return p.filesProcessed=n,p.filesMatched=c,p.subdirectories=d,i.directoryStats.push(p),h&&h.length>0&&i.directoryStats.push(...h),s.info("performLocalSearch completed",{totalFiles:n,matchesFound:f.length,directories:d+1}),{matches:f,totalFiles:n}}catch(t){const r="Error in performLocalSearch: "+(0,k.getErrorMessage)(t)
|
|
606
|
+
return p.errors.push(r),i.directoryStats.push(p),i.errors.push(r),s.error(r,{error:t instanceof Error?t.stack:t+"",searchPath:e}),{matches:f,totalFiles:p.filesProcessed}}}(C,P,{maxResults:E,fileExtension:x,searchIn:M,isFile:_,contextLines:R},x,l,I)
|
|
607
|
+
$=e.matches,D=e.totalFiles
|
|
599
608
|
const t=1e3
|
|
600
|
-
$.length>0&&$.length<=t?($.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 ${$.length} matches by modification time (newest first)`)):$.length>t&&l.info(`Skipped sorting ${$.length} matches (exceeds hard cap of ${t} for performance)`),
|
|
601
|
-
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 ${
|
|
602
|
-
I.errors.push(t),l.error(t),I.phases.searchTime=Date.now()-j}I.totalFiles=
|
|
609
|
+
$.length>0&&$.length<=t?($.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 ${$.length} matches by modification time (newest first)`)):$.length>t&&l.info(`Skipped sorting ${$.length} matches (exceeds hard cap of ${t} for performance)`),A=$.length,$.length>E&&($=$.slice(0,E),l.info(`Limited results to ${E} (from ${A} total matches)`)),$.forEach((e=>{e.relativePath=function(e,t){const r=h.default.relative(e,t)
|
|
610
|
+
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||$.length} total matches in ${D} files, returning ${$.length} results`),I.phases.searchTime=Date.now()-j}catch(e){const t="Error during search: "+(0,k.getErrorMessage)(e)
|
|
611
|
+
I.errors.push(t),l.error(t),I.phases.searchTime=Date.now()-j}I.totalFiles=D,I.totalMatches=$.length,I.endTime=Date.now()
|
|
603
612
|
let F,N=""
|
|
604
613
|
try{if(t.getCurrentBranchContext){const e=await t.getCurrentBranchContext()
|
|
605
614
|
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})
|
|
606
615
|
const L="content"===M?"content":"filename"===M?"filenames":"content and filenames"
|
|
607
|
-
if(
|
|
616
|
+
if(A>$.length?(F=`Found ${A} results for "${n}" (searching ${L})`,f&&(F+=" in "+f),T&&(F+=" with extension "+T),F+=`${N}. Showing first ${$.length}:\n\n`):(F=`Found ${$.length} results for "${n}" (searching ${L})`,f&&(F+=" in "+f),T&&(F+=" with extension "+T),F+=N+":\n\n"),$.length>0)if(R>0){const{filenameMatches:e,mergedGroups:t}=function(e,t){const r=e.filter((e=>"filename"===e.matchType)),n=e.filter((e=>"content"===e.matchType))
|
|
608
617
|
if(0===n.length)return{filenameMatches:r,mergedGroups:[]}
|
|
609
618
|
const o=new Map
|
|
610
619
|
for(const e of n){const t=o.get(e.file)||[]
|
|
@@ -628,7 +637,7 @@ else F+="No matches found."
|
|
|
628
637
|
return d({success:!0}),{content:[{type:"text",text:F}]}}catch(t){l.error("Search failed",{args:e,error:t instanceof Error?t.stack:t+""}),I.errors.push((0,k.getErrorMessage)(t)),I.endTime=Date.now(),l.debug("Search diagnostic information on error",{diagnostic:I})
|
|
629
638
|
let r="Search failed: "+(0,k.getErrorMessage)(t)
|
|
630
639
|
return d({success:!1,error:t instanceof Error?t.name:"unknown"}),{content:[{type:"text",text:r}],isError:!0}}}
|
|
631
|
-
const h=u(t(6928)),g=u(t(1943)),
|
|
640
|
+
const h=u(t(6928)),g=u(t(1943)),f=u(t(857)),p=t(9860),m=d(t(5967)),y=t(5967),w=t(2537),k=t(8824),b=["node_modules"],I=1e4,v=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore"]),C=1048576},1318(e,exports,t){async function r(e,t,r){try{const r=(await e.revparse(["--show-toplevel"])).trim(),n=c.default.isAbsolute(t)?t:c.default.resolve(t)
|
|
632
641
|
return c.default.relative(r,n)}catch(e){return r.warn("Failed to get repo-relative path, using original",{filePath:t,error:(0,l.getErrorMessage)(e)}),t}}function n(e){return/\(trec\d{6}\)/.test(e)}async function o(e,t,n,o,s){try{const i=await r(e,t,s),a=await e.raw(["log","-1","--pretty=format:%H|%s",`-L${n},${o}:${i}`])
|
|
633
642
|
if(!a||""===a.trim())return null
|
|
634
643
|
const c=a.trim().split("\n")[0],[l,...d]=c.split("|"),u=d.join("|")
|
|
@@ -645,12 +654,12 @@ for(const e of r){const r=e.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/)
|
|
|
645
654
|
if(r){const e=parseInt(r[3],10),n=r[4]?parseInt(r[4],10):1,o=e+n-1
|
|
646
655
|
n>0&&t.push({start:e,end:o})}}return t}(s)
|
|
647
656
|
return{ranges:i,diff:s}}catch(e){return n.warn("Failed to get uncommitted changes",{filePath:t,error:(0,l.getErrorMessage)(e)}),{ranges:[],diff:""}}}(e,t.path,i),d=c.ranges,u=c.diff,h=await async function(e,t,n){try{const o=await r(e,t,n),s=await e.log({file:o,maxCount:1})
|
|
648
|
-
return s.latest?.message||null}catch(e){return null}}(e,t.path,i),g=!!h&&n(h),
|
|
657
|
+
return s.latest?.message||null}catch(e){return null}}(e,t.path,i),g=!!h&&n(h),f=t.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),p=d.map((e=>`${e.start}-${e.end}`)).join(", ")||"none",m=u?u.substring(0,300):"no diff"
|
|
649
658
|
if(0===d.length){const r=[]
|
|
650
659
|
for(const s of t.lineRanges){const a=await o(e,t.path,s.start,s.end,i)
|
|
651
|
-
a&&(n(a.message)||r.push({range:`${s.start}-${s.end}`,commit:a}))}if(r.length>0){const e=r.map((e=>`Lines ${e.range}: ${e.commit.hash.substring(0,8)} - ${e.commit.message}`)).join("; "),n=[`\u26a0\ufe0f Warning: Lines ${
|
|
652
|
-
return{hasExternalEdits:!0,conflictingLines:t.lineRanges.flatMap((e=>Array.from({length:e.end-e.start+1},((t,r)=>e.start+r)))),message:n,debugInfo:{detectionRan:!0,affectedRegion:
|
|
653
|
-
return 0===w.length?{hasExternalEdits:!1,conflictingLines:[],message:"File has uncommitted changes, but they do not conflict with this operation.",debugInfo:{detectionRan:!0,affectedRegion:
|
|
660
|
+
a&&(n(a.message)||r.push({range:`${s.start}-${s.end}`,commit:a}))}if(r.length>0){const e=r.map((e=>`Lines ${e.range}: ${e.commit.hash.substring(0,8)} - ${e.commit.message}`)).join("; "),n=[`\u26a0\ufe0f Warning: Lines ${f} were last modified by external commits (not alchemy).`,"","Commit details: "+e,"\nThese changes may have been made manually or by another tool.\nReview recent commits before proceeding."].join("\n")
|
|
661
|
+
return{hasExternalEdits:!0,conflictingLines:t.lineRanges.flatMap((e=>Array.from({length:e.end-e.start+1},((t,r)=>e.start+r)))),message:n,debugInfo:{detectionRan:!0,affectedRegion:f,uncommittedChanges:"none",lastCommit:r[0].commit.message,wasLastCommitAlchemy:!1,diffPreview:e,overlapDetected:!0}}}return{hasExternalEdits:!1,conflictingLines:[],debugInfo:{detectionRan:!0,affectedRegion:f,uncommittedChanges:"none",lastCommit:h,wasLastCommitAlchemy:g,diffPreview:"no uncommitted changes, last commits from alchemy",overlapDetected:!1}}}const y={path:t.path,lineRanges:d,totalLines:d.reduce(((e,t)=>e+(t.end-t.start+1)),0),operationType:"modification"},w=(0,a.getOverlappingLines)(t,y)
|
|
662
|
+
return 0===w.length?{hasExternalEdits:!1,conflictingLines:[],message:"File has uncommitted changes, but they do not conflict with this operation.",debugInfo:{detectionRan:!0,affectedRegion:f,uncommittedChanges:p,lastCommit:h,wasLastCommitAlchemy:g,diffPreview:m,overlapDetected:!1}}:{hasExternalEdits:!0,conflictingLines:w,message:["\u26a0\ufe0f Warning: File has uncommitted changes in lines you're about to modify.\n","Affected lines: "+f,"Conflicting lines: "+s(w),"",g?"Last commit was by alchemy, but file has been edited since.":"Last commit was NOT from alchemy - these may be manual edits.","\nReview the changes before proceeding."].join("\n"),details:{totalExternalChanges:y.totalLines,overlappingChanges:w.length,changedLineRanges:d},debugInfo:{detectionRan:!0,affectedRegion:f,uncommittedChanges:p,lastCommit:h,wasLastCommitAlchemy:g,diffPreview:m,overlapDetected:!0}}}catch(e){return i.error("Failed to detect external edits",{path:t.path,error:(0,l.getErrorMessage)(e)}),{hasExternalEdits:!1,conflictingLines:[],message:"Unable to check for external edits (Git error). Proceeding with caution."}}},exports.hasUncommittedChanges=async function(e,t){try{return(await e.status([t])).files.some((e=>e.path===t))}catch(e){return!1}}
|
|
654
663
|
const a=t(9947),c=i(t(6928)),l=t(8824)},1387(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.WorkspaceRequestProcessor=void 0
|
|
655
664
|
const r=t(7075),n=t(5964),o=t(8824)
|
|
656
665
|
exports.WorkspaceRequestProcessor=class{constructor(e,t,r,n,o){this.gitAdapter=e,this.conflictDetector=t,this.safetyAnalyzer=r,this.conflictResolver=n,this.logger=o}async completeRequest(e,t,s){const i=r.WorkspaceValidation.validateRequestId(e)
|
|
@@ -703,31 +712,31 @@ const y=!!i,w=async()=>{if(!y)return!0
|
|
|
703
712
|
try{return await i.hasValidToken()}catch(e){return m.error("Error checking authentication status",{error:(0,l.getErrorMessage)(e)}),!1}},k=async()=>{const e=(0,c.areTestsRequiredForCompletion)(),t=await w()
|
|
704
713
|
m.info(`Generating tools list with testsRequired=${e}, authenticated=${t}`)
|
|
705
714
|
const r={testsRequired:e,authenticated:t}
|
|
706
|
-
return(0,
|
|
715
|
+
return(0,p.generateVisibleToolsList)(r)}
|
|
707
716
|
let b=k(),I=[]
|
|
708
717
|
b.then((e=>{I=e})).catch((e=>{m.error("Error generating initial tools list",{error:(0,l.getErrorMessage)(e)}),I=[]})),e.setRequestHandler(a.ListToolsRequestSchema,(async()=>{try{return I=await k(),{tools:I}}catch(e){return m.error("Error generating tools list",{error:(0,l.getErrorMessage)(e)}),{tools:[]}}}))
|
|
709
718
|
let v=!1
|
|
710
|
-
e.setRequestHandler(a.CallToolRequestSchema,(async e=>{try{const{name:i,arguments:a={},_meta:c}=e.params;(0,
|
|
719
|
+
e.setRequestHandler(a.CallToolRequestSchema,(async e=>{try{const{name:i,arguments:a={},_meta:c}=e.params;(0,f.logSessionIdentity)(i,"_meta-debug",{has_meta:!!c,sessionId:c?.sessionId||null,messageId:c?.messageId||null,paramKeys:Object.keys(e.params)}),m.info("Tool call received: "+i,{tool:i}),s.incrementCounter("tool_calls_total",1,{tool:i})
|
|
711
720
|
const k=s.startTimer("tool_execution_time")
|
|
712
721
|
Date.now()
|
|
713
722
|
let b=Date.now()
|
|
714
723
|
const I=r(a)
|
|
715
724
|
if(Date.now(),b=Date.now(),y){const e=await w()
|
|
716
|
-
if(Date.now(),!e)return m.warn("Unauthenticated tool call attempt",{tool:i}),{content:[{type:"text",text:"Authentication required. Please run 'alchemylab setup' to authenticate and configure your project."}],isError:!0}}const C=(0,
|
|
725
|
+
if(Date.now(),!e)return m.warn("Unauthenticated tool call attempt",{tool:i}),{content:[{type:"text",text:"Authentication required. Please run 'alchemylab setup' to authenticate and configure your project."}],isError:!0}}const C=(0,p.getToolByName)(i)
|
|
717
726
|
if(b=Date.now(),n?(n.setOptions({createRecords:C?.createsRecords??!1}),m.info(`Setting record creation for tool ${i}: ${C?.createsRecords??!1}`)):m.debug(`No API client available for tool ${i} (minimal mode)`),Date.now(),b=Date.now(),t?.workspaceManager&&!t.workspaceManager.readonlyBranchCheckDone)try{const e=await(0,d.getServerUrl)(t,m)
|
|
718
727
|
e&&n&&await t.workspaceManager.ensureReadonlyBranchIfNeeded(e,i,n,c?.sessionId)}catch(e){m.debug("Error during readonly branch check",{error:(0,l.getErrorMessage)(e)})}let _,E
|
|
719
728
|
if(Date.now(),Date.now(),b=Date.now(),C&&!C.readOnly)if(c?.sessionId){const e=c.sessionId,r=c.messageId,n=u.sessionIdentity.getIdentity()
|
|
720
|
-
if(n)n.sessionId!==e&&((0,
|
|
729
|
+
if(n)n.sessionId!==e&&((0,f.logSessionIdentity)(i,"_meta-session-switch",{prevSessionId:n.sessionId,prevAgentType:n.agentType,newSessionId:e}),u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:n.serverUrl}))
|
|
721
730
|
else{const r=await(0,d.getServerUrl)(t,m)
|
|
722
|
-
u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:r||""}),u.sessionIdentity.markDiscoveryAttempted()}_={providerId:"opencode",sessionId:e,messageId:r,createdAt:(new Date).toISOString()},(0,
|
|
731
|
+
u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:r||""}),u.sessionIdentity.markDiscoveryAttempted()}_={providerId:"opencode",sessionId:e,messageId:r,createdAt:(new Date).toISOString()},(0,f.logSessionIdentity)(i,"_meta",{sessionId:e,messageId:r})}else{const e=u.sessionIdentity.getIdentity()
|
|
723
732
|
if(e){let t,r=!1
|
|
724
733
|
try{t=await(0,d.findMessageIdForTool)(e.serverUrl,e.sessionId,i)}catch{r=!0}if(t)_=u.sessionIdentity.buildCliOrigin(t)
|
|
725
734
|
else if(r)_=u.sessionIdentity.buildCliOrigin()
|
|
726
735
|
else{m.info("Session identity mismatch: tool call not found in cached session, re-discovering",{prevSessionId:e.sessionId,prevAgentType:e.agentType,tool:i}),u.sessionIdentity.reset()
|
|
727
736
|
try{const t=await(0,d.getAndStoreSessionId)(e.serverUrl,m,i)
|
|
728
|
-
t?(u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:t.sessionId,serverUrl:e.serverUrl}),(0,
|
|
737
|
+
t?(u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:t.sessionId,serverUrl:e.serverUrl}),(0,f.logSessionIdentity)(i,"re-discovery",{sessionId:t.sessionId,messageId:t.messageId}),_=u.sessionIdentity.buildCliOrigin(t.messageId)):(u.sessionIdentity.setIdentity(e),_=u.sessionIdentity.buildCliOrigin(),m.info("Re-discovery found no other session, keeping current identity",{sessionId:e.sessionId})),u.sessionIdentity.markDiscoveryAttempted()}catch(t){u.sessionIdentity.setIdentity(e),_=u.sessionIdentity.buildCliOrigin(),u.sessionIdentity.markDiscoveryAttempted(),m.warn("Re-discovery failed, keeping current identity (may be stale)",{error:(0,l.getErrorMessage)(t),tool:i,sessionId:e.sessionId})}}}else if(!u.sessionIdentity.hasDiscoveryBeenAttempted())try{const e=await(0,d.getServerUrl)(t,m)
|
|
729
738
|
if(e){const t=await(0,d.getAndStoreSessionId)(e,m,i)
|
|
730
|
-
t&&(u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:t.sessionId,serverUrl:e}),(0,
|
|
739
|
+
t&&(u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:t.sessionId,serverUrl:e}),(0,f.logSessionIdentity)(i,"http-discovery",{sessionId:t.sessionId,messageId:t.messageId}),_=u.sessionIdentity.buildCliOrigin(t.messageId))}u.sessionIdentity.markDiscoveryAttempted()}catch(e){u.sessionIdentity.markDiscoveryAttempted(),(0,f.logSessionIdentity)(i,"discovery-failed",{error:(0,l.getErrorMessage)(e)}),m.debug("cliOrigin discovery failed",{error:(0,l.getErrorMessage)(e),tool:i})}}if(u.sessionIdentity.setCurrentCallOrigin(_),!v&&n){const e=u.sessionIdentity.getIdentity(),t=process.env.ALCHEMY_INITIAL_BRANCH
|
|
731
740
|
if(e?.sessionId&&t){const r=t.match(/^requests\/(.+)$/),o="1"===process.env.ALCHEMY_ALLOW_PARALLEL
|
|
732
741
|
if(r&&!o){const t=r[1]
|
|
733
742
|
v=!0
|
|
@@ -752,13 +761,13 @@ const a=t(9150),c=t(2478),l=t(8824),d=t(7617),u=t(6688),h=t(5172)
|
|
|
752
761
|
i(t(9896)),i(t(6928))
|
|
753
762
|
var g=t(7280)
|
|
754
763
|
Object.defineProperty(exports,"logSessionIdentity",{enumerable:!0,get(){return g.logSessionIdentity}})
|
|
755
|
-
const
|
|
764
|
+
const f=t(7280)
|
|
756
765
|
t(2462)
|
|
757
|
-
const
|
|
766
|
+
const p=t(2245)},1483(e,exports,t){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")
|
|
758
767
|
try{let i
|
|
759
768
|
try{i=r.SearchDocumentsSchema.parse(e)}catch(t){if(t instanceof n.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
760
|
-
return c.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,dateFrom:g,dateTo:
|
|
761
|
-
c.info("Searching documents",{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,searchIn:
|
|
769
|
+
return c.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,dateFrom:g,dateTo:f,searchIn:p}=i
|
|
770
|
+
c.info("Searching documents",{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,searchIn:p})
|
|
762
771
|
const m=t.projectId
|
|
763
772
|
if(!m){const e="Project ID is required. Make sure you are in a project context."
|
|
764
773
|
return c.warn("No project context"),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}s.setProjectId(m)
|
|
@@ -767,11 +776,11 @@ try{const e={limit:h||100,offset:0,sortBy:"updatedAt",sortDirection:"desc",searc
|
|
|
767
776
|
l&&(e.type=l),d&&(e.requestId=d),c.debug("Fetching documents with filters",{filters:e})
|
|
768
777
|
let t=await y.listDocuments(e)
|
|
769
778
|
if(g){const e=new Date(g)
|
|
770
|
-
t=t.filter((t=>new Date(t.createdAt)>=e))}if(
|
|
779
|
+
t=t.filter((t=>new Date(t.createdAt)>=e))}if(f){const e=new Date(f)
|
|
771
780
|
t=t.filter((t=>new Date(t.createdAt)<=e))}c.info(`Fetched and filtered ${t.length} documents for search`)
|
|
772
781
|
const r=[],n=a.toLowerCase()
|
|
773
782
|
for(const e of t){let t,o=null
|
|
774
|
-
if("filename"!==
|
|
783
|
+
if("filename"!==p&&"both"!==p||!e.filename.toLowerCase().includes(n)||(o="filename",t=e.filename),("content"===p||"both"===p)&&e.content&&e.content.toLowerCase().includes(n)){o="content"
|
|
775
784
|
const r=e.content.split("\n")
|
|
776
785
|
for(let e=0;e<r.length;e++)if(r[e].toLowerCase().includes(n)){const n=Math.max(0,e-1),o=Math.min(r.length-1,e+1)
|
|
777
786
|
t=r.slice(n,o+1).map(((t,r)=>n+r===e?"> "+t.trim():" "+t.trim())).join("\n")
|
|
@@ -849,16 +858,16 @@ try{let i
|
|
|
849
858
|
try{i=r.CreateDocumentSchema.parse(e)}catch(t){if(t instanceof n.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
850
859
|
return d.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{requestId:a,filename:c,content:u,type:h,comment:g}=i
|
|
851
860
|
d.info("Creating new document",{requestId:a||"standalone",filename:c,contentLength:u.length,type:h,comment:g})
|
|
852
|
-
const
|
|
853
|
-
if(!
|
|
861
|
+
const f=t.projectId
|
|
862
|
+
if(!f){const e="Project ID is required. Make sure you are in a project context."
|
|
854
863
|
return d.warn("No project context"),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}if(!c.toLowerCase().endsWith(".md")){const e="Filename must end with .md extension: "+c
|
|
855
|
-
return d.warn("Invalid filename extension",{filename:c}),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}try{s.setProjectId(
|
|
864
|
+
return d.warn("Invalid filename extension",{filename:c}),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}try{s.setProjectId(f)
|
|
856
865
|
const e=s.getDocumentClient(),t=a?{requestId:a}:{},r=(await e.listDocuments(t)).find((e=>e.filename===c&&!e.archived))
|
|
857
866
|
if(r){const e=`\u274c A document with filename "${c}" already exists ${a?"for this request":"in this project"}.\n\n**Existing Document ID:** ${r.id}\n**Created:** ${r.createdAt}\n\nPlease either:\n- Use a different filename\n- Delete or archive the existing document first\n- Use write_file with documentId "${r.id}" to update the existing document`
|
|
858
867
|
return d.warn("Duplicate filename detected",{filename:c,requestId:a||"standalone",existingDocId:r.id}),{content:[{type:"text",text:e}],isError:!0}}const n=await e.createDocument(a,{filename:c,content:u,type:h,...l&&{cliOrigin:l}})
|
|
859
868
|
d.info("Document created successfully",{documentId:n.id,filename:n.filename,requestId:a||"standalone"})
|
|
860
869
|
try{const e=s.getToolRecordClient()
|
|
861
|
-
await e.createToolRecord({type:"create-document",projectId:
|
|
870
|
+
await e.createToolRecord({type:"create-document",projectId:f,metadata:{documentId:n.id,filename:n.filename,type:n.type,contentLength:u.length,requestId:a,projectId:f},note:g})}catch(e){d.warn("Failed to create tool record",{recordError:e})}const o=a?`**Request:** ${a}\n`:"**Standalone:** Yes (not tied to a request)\n"
|
|
862
871
|
return{content:[{type:"text",text:`\u2705 Document created successfully!\n\n**Document ID:** ${n.id}\n**Filename:** ${n.filename}\n**Type:** ${n.type}\n**Size:** ${u.length} characters\n`+o+`**Created:** ${n.createdAt}\n\n`+`The document is now stored in the tracking system and can be edited using standard file modification tools by referencing its document ID (${n.id}) instead of a file path.\n\n**Examples:**\n`+`- \`replace_string\` with \`documentId: "${n.id}"\`\n`+`- \`write_file\` with \`documentId: "${n.id}"\`\n`+`- \`file_history\` with \`documentId: "${n.id}"\``}]}}catch(e){const t="Failed to create document: "+(0,o.getErrorMessage)(e)
|
|
863
872
|
return d.error("Failed to create document",{error:e}),{content:[{type:"text",text:"\u274c "+t}],isError:!0}}}catch(e){return d.error("Unexpected error in create document",{error:e}),{content:[{type:"text",text:"\u274c Unexpected error: "+(0,o.getErrorMessage)(e)}],isError:!0}}finally{u({tool:"create_document"})}}
|
|
864
873
|
const r=t(6183),n=t(1569),o=t(8824)},1599(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.SessionRequestAssociationClient=void 0
|
|
@@ -904,11 +913,10 @@ this.logger.debug("Retrieved main branch hash via direct rev-parse",{branch:n,co
|
|
|
904
913
|
try{if(i=await this.git.revparse(["HEAD"]),!/^[a-f0-9]{40}$/i.test(i))throw Error("Invalid HEAD commit hash format: "+i)
|
|
905
914
|
this.logger.warn("Used HEAD as fallback for main branch commit hash",{originalBranch:n,fallbackCommit:i.substring(0,8)+"..."})}catch(e){throw Error(`Failed to get commit hash for branch '${n}' and HEAD fallback failed: ${e instanceof Error?e.message:e+""}`)}}return this.logger.info("Main branch commit hash detection completed",{selectedBranch:n,detectionMethod:o,commitHashShort:i.substring(0,8)+"...",currentBranchContext:t,validFormat:/^[a-f0-9]{40}$/i.test(i),strategy:"context-aware-detection"}),i}catch(e){throw this.logger.error("Failed to get main branch commit hash",{error:(0,n.getErrorMessage)(e),stack:e instanceof Error?e.stack:void 0}),Error("Failed to get main branch commit hash: "+(0,n.getErrorMessage)(e))}}hasExactConflictMarkers(e){return!(!e||!e.trim())&&[/^\s*<{7}(?:\s|$)/m,/^\s*={7}(?:\s|$)/m,/^\s*>{7}(?:\s|$)/m].some((t=>t.test(e)))}async handleConflicts(e){const{requestId:t}=e
|
|
906
915
|
this.logger.info("Starting conflict resolution workflow",{requestId:t,conflictedFiles:e.conflictedFiles.length,mode:e.mode})
|
|
907
|
-
try{await this.
|
|
908
|
-
const r=await this.writeConflictMarkersToFiles(e)
|
|
916
|
+
try{const r=await this.writeConflictMarkersToFiles(e)
|
|
909
917
|
this.logger.info("Wrote conflict markers to files",{requestId:t,filesWritten:r})
|
|
910
918
|
const n=await this.createConflictResolutionTask(e)
|
|
911
|
-
return this.logger.info("Created conflict resolution task",{requestId:t,taskId:n}),{statusUpdated:!
|
|
919
|
+
return this.logger.info("Created conflict resolution task",{requestId:t,taskId:n}),{statusUpdated:!1,taskCreated:!0,taskId:n,conflictFilesWritten:r,userMessage:this.generateConflictResolutionMessage(e,n)}}catch(e){return this.logger.error("Conflict resolution workflow failed",{requestId:t,error:(0,n.getErrorMessage)(e)}),{statusUpdated:!1,taskCreated:!1,conflictFilesWritten:0,userMessage:"Conflict resolution workflow failed: "+(0,n.getErrorMessage)(e)}}}async updateRequestStatus(e,t){const r=this.apiClient.getRequestClient(),n={status:t}
|
|
912
920
|
this.logger.info("Updating request status",{requestId:e,status:t}),await r.updateRequest(e,n)}async runStructuredMergeTree(e){const t="git merge-tree --write-tree --name-only main requests/"+e
|
|
913
921
|
this.logger.debug("Running structured merge-tree command",{requestId:e,command:t,cwd:this.workingDirectory})
|
|
914
922
|
try{const r=await(0,c.execAsync)(t,{cwd:this.workingDirectory}),n=r.stdout.trim().split("\n").filter((e=>e.trim()))
|
|
@@ -952,7 +960,7 @@ if(!r)throw Error("Project ID is required for task creation but not available")
|
|
|
952
960
|
const o=`**Merge conflicts detected during request completion.**\n\n## Conflicted Files:\n${e.conflictedFiles.map((e=>"- "+e.path)).join("\n")}\n\n## Resolution Instructions:\n1. **Review the conflict markers** in the files above\n2. **Resolve conflicts using standard file editing tools**:\n - Use \`write-file\` to replace entire file content with resolved version\n - Use \`replace-string\` for targeted conflict resolution\n - Remove ALL conflict markers: \`<<<<<<<\`, \`=======\`, \`>>>>>>>\`\n3. **Ensure no conflict markers remain** in any file\n4. **Test your resolution** if applicable\n5. **Try completing the request again** when conflicts are resolved\n\n## Conflict Details:\n- **Detection Method**: ${e.detectionMethod}\n- **Mode**: ${e.mode}\n- **Summary**: ${e.summary}\n\n${e.safetyAnalysis?`\n## Auto-Merge Analysis:\n- **Attempted**: ${e.autoMergeAttempted?"Yes":"No"}\n- **Safe for auto-merge**: ${e.safetyAnalysis.isSafe?"Yes":"No"}\n- **Reason**: ${e.safetyAnalysis.reason}\n${e.safetyAnalysis.failureReasons.length>0?"- **Issues**: "+e.safetyAnalysis.failureReasons.join(", "):""}\n`:""}\n\n## Next Steps:\n1. Resolve the conflicts in the files listed above\n2. Call \`complete-request\` again with the same requestId\n3. The system will detect the resolution and complete the merge\n\n**Note**: The request status has been set to 'conflicted' and will remain so until conflicts are resolved.`
|
|
953
961
|
let s
|
|
954
962
|
try{s=await this.getCurrentMainCommitHash(),this.logger.info("Storing main branch commit hash for conflict tracking",{requestId:e.requestId,mainCommitHash:s.substring(0,8)+"..."})}catch(t){this.logger.warn("Could not get main branch commit hash, conflict re-detection will be disabled",{requestId:e.requestId,error:(0,n.getErrorMessage)(t)})}const i={requestId:e.requestId,projectId:r,title:t,description:o,metadata:{conflictedFiles:e.conflictedFiles.map((e=>e.path)),detectionTime:(new Date).toISOString(),mainBranchCommitHash:s,detectionMethod:e.detectionMethod,mode:e.mode,originalRequestId:e.requestId,safetyAnalysis:e.safetyAnalysis,conflictType:"merge-conflicts"}},a=this.apiClient.getTaskClient()
|
|
955
|
-
return(await a.createTask(i)).id}generateConflictResolutionMessage(e,t){return`## \u26a0\ufe0f Merge Conflicts Detected\n\nRequest **${e.requestId}** has merge conflicts that need to be resolved before completion.\n\n### Status Update:\n- **
|
|
963
|
+
return(await a.createTask(i)).id}generateConflictResolutionMessage(e,t){return`## \u26a0\ufe0f Merge Conflicts Detected\n\nRequest **${e.requestId}** has merge conflicts that need to be resolved before completion.\n\n### Status Update:\n- **Conflict Resolution Task**: Created task \`${t}\`\n- **Files with Conflicts**: ${e.conflictedFiles.length} files\n\n### Conflicted Files:\n${e.conflictedFiles.map((e=>`- \`${e.path}\``)).join("\n")}\n\n### What Happened:\n${e.summary}\n\n### How to Resolve:\n1. **Use standard file editing tools** to resolve conflicts:\n - \`write-file\` to replace entire file content\n - \`replace-string\` for targeted edits\n - Remove all \`<<<<<<<\`, \`=======\`, \`>>>>>>>\` markers\n\n2. **Ensure all conflict markers are removed** from all files\n\n3. **Complete the conflict resolution task** when done\n\n4. **Call \`merge\` again** with the same requestId to merge to main\n\n**Note**: You can use any file editing approach. Remove all conflict markers, complete the task, then call merge.`}async validateConflictsResolved(e){const t=[]
|
|
956
964
|
for(const r of e.conflictedFiles)try{const e=i.default.resolve(this.workingDirectory,r.path)
|
|
957
965
|
if(a.default.existsSync(e)){const n=a.default.readFileSync(e,"utf8")
|
|
958
966
|
this.hasExactConflictMarkers(n)&&t.push(r.path)}}catch(e){this.logger.warn("Failed to check conflict resolution in file",{filePath:r.path,error:(0,n.getErrorMessage)(e)}),t.push(r.path)}return{resolved:0===t.length,remainingConflicts:t}}async hasMainBranchChanged(e){try{const t=this.apiClient.getTaskClient(),r=await t.listTasks({requestId:e})
|
|
@@ -1090,11 +1098,11 @@ if(h=e?.requestContextMode,!h){const e=(0,T.getBuiltInAgentConfig)(a)
|
|
|
1090
1098
|
h=e?.requestContextMode}}catch{}if(h&&"none"!==h&&!l)return{content:[{type:"text",text:`\u274c Agent '${a}' requires a requestId to be provided.\n\nThis agent has requestContextMode: '${h}' which means it needs to work in the context of a specific request.\n\nPlease provide a requestId when spawning this agent.`}],isError:!0}
|
|
1091
1099
|
const g=await(0,b.getServerUrl)(t,o)
|
|
1092
1100
|
r(t,"serverUrl resolved",{serverUrl:g})
|
|
1093
|
-
const
|
|
1094
|
-
if(!
|
|
1095
|
-
const
|
|
1101
|
+
const f=t.basePath
|
|
1102
|
+
if(!f)throw new w.ValidationError("Working directory not available in context")
|
|
1103
|
+
const p=(0,I.getCachedSession)()
|
|
1096
1104
|
let m
|
|
1097
|
-
if(g)try{m=i?.sessionId||
|
|
1105
|
+
if(g)try{m=i?.sessionId||p?.sessionId||await(0,b.discoverParentSessionId)(g,o)}catch{}let y=""
|
|
1098
1106
|
if(s&&l)try{const e=s.getSessionRequestAssociationClient()
|
|
1099
1107
|
if(e){const t=await e.getSessionsForRequest(l,!0),r=m?t.filter((e=>e.opencodeSessionId!==m)):t
|
|
1100
1108
|
if(r.length>0){const e=r.map((e=>e.opencodeSessionId)).join(", ")
|
|
@@ -1110,7 +1118,7 @@ if(r.data?.defaultModel){const[t,...n]=r.data.defaultModel.split("/")
|
|
|
1110
1118
|
e={providerID:t,modelID:n.join("/")}}}}catch{}const t=`${g.replace(/\/$/,"")}/session/${_}/message`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:[{type:"text",text:q}],...a?{agent:a}:{},...e?{model:e}:{}})})
|
|
1111
1119
|
if(!r.ok){const e=await r.text().catch((()=>"Unknown error"))
|
|
1112
1120
|
throw Error(`Failed to send to existing session: ${r.status} ${e}`)}o.info("Prompt sent to existing session",{sessionId:_,agent:a})}catch(e){throw Error("Failed to use existing session: "+(0,E.getErrorMessage)(e))}}else{if(S=!0,r(t,"Creating session via HTTP and spawning CLI"),!g)throw Error("Cannot spawn subagent: no server URL available")
|
|
1113
|
-
const i=m||
|
|
1121
|
+
const i=m||p?.sessionId||await(0,b.discoverParentSessionId)(g,o);(0,v.logSessionIdentity)("subagent_operations.spawn",m?"early-discovery":p?"_meta":"http-discovery",{parentSessionId:i}),r(t,"Parent session discovered",{parentSessionId:i})
|
|
1114
1122
|
const u=g.replace(/\/$/,"")+"/session",h=e.title?e.title:l?`[${l}] ${c.slice(0,40)}${c.length>40?"...":""}`:`${c.slice(0,50)}${c.length>50?"...":""}`,y=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parentID:i,title:h})})
|
|
1115
1123
|
if(!y.ok)throw Error("Failed to create session: "+y.status)
|
|
1116
1124
|
const w=await y.json()
|
|
@@ -1124,22 +1132,22 @@ if(i){const e=await n.createOrUpdateSession({externalSessionId:i,providerId:"ope
|
|
|
1124
1132
|
o=e.id,c=e.workflowId,r(t,"Registered parent session in DB",{parentSessionId:i,parentDbId:o,parentWorkflowId:c})}const l=await n.createOrUpdateSession({externalSessionId:P,providerId:"opencode",parentSessionId:o||null,title:h,status:"active",agentType:a,specialization:e.specialization,workflowId:c||void 0})
|
|
1125
1133
|
r(t,"Registered child session in DB",{childSessionId:P,childDbId:l.id,parentDbId:o})}catch(e){r(t,"Failed to register sessions in DB",{error:(0,E.getErrorMessage)(e)}),o.warn("Failed to register sessions in alchemy DB",{error:(0,E.getErrorMessage)(e)})}})()
|
|
1126
1134
|
let O
|
|
1127
|
-
r(t,"Starting model resolution",{agent:a,cwd:
|
|
1135
|
+
r(t,"Starting model resolution",{agent:a,cwd:f})
|
|
1128
1136
|
try{r(t,"Fetching agent config from action server",{agent:a,url:`http://localhost:${R}/api/agents/by-name/${a}`})
|
|
1129
1137
|
const e=await n(a)
|
|
1130
1138
|
if(r(t,"Agent config result",{agent:a,agentConfig:e||"null",hasConfig:!!e}),e){const n=e.preferredProvider||"inherit",o=e.preferredModelTier||"same"
|
|
1131
1139
|
r(t,"Agent preferences",{agent:a,preferredProvider:n,preferredTier:o,rawProvider:e.preferredProvider,rawTier:e.preferredModelTier})
|
|
1132
|
-
const s=(0,M.resolveAgentModel)(
|
|
1140
|
+
const s=(0,M.resolveAgentModel)(f,n,o)
|
|
1133
1141
|
r(t,"Model resolution result",{agent:a,result:s}),s.resolved?(O=s.fullModel,r(t,"Resolved agent model",{agent:a,model:O,preferredProvider:n,preferredTier:o})):r(t,"Model resolution fallback",{agent:a,reason:s.reason})}else{const e=(0,T.getBuiltInAgentConfig)(a)
|
|
1134
1142
|
if(r(t,"No API agent config, checking built-in defaults",{agent:a,builtInConfig:e||"null"}),e){const n=e.preferredProvider||"inherit",o=e.preferredModelTier||"same"
|
|
1135
1143
|
r(t,"Using built-in agent preferences",{agent:a,preferredProvider:n,preferredTier:o})
|
|
1136
|
-
const s=(0,M.resolveAgentModel)(
|
|
1144
|
+
const s=(0,M.resolveAgentModel)(f,n,o)
|
|
1137
1145
|
r(t,"Built-in model resolution result",{agent:a,result:s}),s.resolved&&(O=s.fullModel,r(t,"Resolved built-in agent model",{agent:a,model:O,preferredProvider:n,preferredTier:o}))}else r(t,"No built-in config found - using default model",{agent:a})}}catch(e){r(t,"Error resolving agent model",{agent:a,error:(0,E.getErrorMessage)(e)})}try{const e=await async function(){try{const e=`http://localhost:${R}/api/project-settings`,t=await fetch(e)
|
|
1138
1146
|
if(t.ok){const e=await t.json()
|
|
1139
1147
|
return e?.data?.defaultModel||null}}catch{}return null}()
|
|
1140
1148
|
if(e)if(O){const o=await n(a)
|
|
1141
1149
|
"same"===(o?.preferredModelTier||"same")&&(O=e,r(t,"Applied user default model (same tier)",{agent:a,userDefaultModel:e}))}else O=e,r(t,"Using user default model (no agent resolution)",{agent:a,userDefaultModel:e})}catch(e){r(t,"Failed to fetch user default model",{error:(0,E.getErrorMessage)(e)})}r(t,"Final resolved model before spawn",{agent:a,resolvedModel:O||"undefined (will use default)"}),await x
|
|
1142
|
-
const j=(0,k.spawnDetachedSubagent)({agent:a,prompt:q,cwd:
|
|
1150
|
+
const j=(0,k.spawnDetachedSubagent)({agent:a,prompt:q,cwd:f,sessionId:P,model:O,initialBranch:C,allowParallel:d,serverUrl:g})
|
|
1143
1151
|
if(!j.success)throw Error("Failed to spawn subagent: "+j.error)
|
|
1144
1152
|
_=P,r(t,"CLI spawn successful with pre-created session",{sessionId:P,pid:j.pid,parentSessionId:i}),o.info("Background subagent spawned via CLI with pre-created session",{agent:a,requestId:l,sessionId:P,pid:j.pid,parentSessionId:i})}if(s&&l&&_&&"unknown"!==_&&"spawning"!==_)try{const e=s.getSessionRequestAssociationClient()
|
|
1145
1153
|
if(e&&(e.createAssociation(_,l).then((()=>o.info("Created session-request association",{sessionId:_,requestId:l}))).catch((e=>o.warn("Failed to create session-request association",{error:(0,E.getErrorMessage)(e),sessionId:_,requestId:l}))),"coder"===a)){const e=s.getRequestClient()
|
|
@@ -1177,12 +1185,12 @@ if(!s)throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
|
1177
1185
|
n.info("Checking status of subagent session",{sessionId:e})
|
|
1178
1186
|
try{const c=`${s.replace(/\/$/,"")}/session/${e}`,u=await fetch(c)
|
|
1179
1187
|
if(!u.ok)return{content:[{type:"text",text:`Session ${e} not found or has exited.`}],isError:!0}
|
|
1180
|
-
const h=await u.json(),g=`${s.replace(/\/$/,"")}/session/${e}/message`,
|
|
1181
|
-
let
|
|
1182
|
-
if(
|
|
1183
|
-
for(const t of e)"assistant"===t.info.role&&t.info.tokens&&(
|
|
1188
|
+
const h=await u.json(),g=`${s.replace(/\/$/,"")}/session/${e}/message`,f=await fetch(g)
|
|
1189
|
+
let p={input:0,output:0,reasoning:0},m="",y=l(null,h.time.updated)
|
|
1190
|
+
if(f.ok){const e=await f.json()
|
|
1191
|
+
for(const t of e)"assistant"===t.info.role&&t.info.tokens&&(p.input+=t.info.tokens.input||0,p.output+=t.info.tokens.output||0,p.reasoning+=t.info.tokens.reasoning||0)
|
|
1184
1192
|
const t=a(e)
|
|
1185
|
-
y=l(t.lastActivityTime,h.time.updated),t.current&&(m+="\nCurrent: "+t.current),t.recent.length>0&&(m+="\nRecent: "+t.recent.join(", "))}const w=Date.now()-h.time.created,k=y.status,b=y.isReady,I=
|
|
1193
|
+
y=l(t.lastActivityTime,h.time.updated),t.current&&(m+="\nCurrent: "+t.current),t.recent.length>0&&(m+="\nRecent: "+t.recent.join(", "))}const w=Date.now()-h.time.created,k=y.status,b=y.isReady,I=p.input+p.output+p.reasoning
|
|
1186
1194
|
let v="",C="",_=null
|
|
1187
1195
|
if(o)try{const t=o.getSessionRequestAssociationClient()
|
|
1188
1196
|
if(t){const r=await t.getActiveRequestsForSession(e,!1)
|
|
@@ -1197,7 +1205,7 @@ if(e.trim())return d(e)}try{const t=n(`git log main --merges --oneline -n 50 --g
|
|
|
1197
1205
|
if(t){const e=t.split("\n")[0].split(" ")[0],o=n(`git diff ${e}^1...${e} --numstat`,{cwd:r,encoding:"utf8"})
|
|
1198
1206
|
if(o.trim())return{...d(o),merged:!0}}}catch{}return null}catch{return null}}(_,r.basePath)
|
|
1199
1207
|
if(e){const t=e.additions+e.deletions,r=e.merged?" (merged)":""
|
|
1200
|
-
v=`\nDiff vs main (${_}): +${e.additions}/-${e.deletions} lines (${t} total) in ${e.files} file${1!==e.files?"s":""}${r}`}}return{content:[{type:"text",text:`Session ${e}\nTitle: ${h.title||"Untitled"}\nStatus: ${k} (${y.detail})\nReady for input: ${b?"Yes":"No"}\nAge: ${i(w)}\nTokens: ${I.toLocaleString()} (in: ${
|
|
1208
|
+
v=`\nDiff vs main (${_}): +${e.additions}/-${e.deletions} lines (${t} total) in ${e.files} file${1!==e.files?"s":""}${r}`}}return{content:[{type:"text",text:`Session ${e}\nTitle: ${h.title||"Untitled"}\nStatus: ${k} (${y.detail})\nReady for input: ${b?"Yes":"No"}\nAge: ${i(w)}\nTokens: ${I.toLocaleString()} (in: ${p.input.toLocaleString()}, out: ${p.output.toLocaleString()}${p.reasoning>0?", reasoning: "+p.reasoning.toLocaleString():""})${m}${C}${v}`}]}}catch(e){throw Error("Failed to check session status: "+(0,E.getErrorMessage)(e))}}async function h(e,t,r){const n=await(0,b.getServerUrl)(t,r)
|
|
1201
1209
|
if(!n)throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
1202
1210
|
r.info("Aborting subagent session",{sessionId:e})
|
|
1203
1211
|
try{const t=`${n.replace(/\/$/,"")}/session/${e}/abort`,o=await fetch(t,{method:"POST"})
|
|
@@ -1207,11 +1215,11 @@ if(!g)throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
|
1207
1215
|
t.info("Listing sessions",{filters:n})
|
|
1208
1216
|
try{const e=g.replace(/\/$/,"")+"/session",t=await fetch(e)
|
|
1209
1217
|
if(!t.ok)throw Error("Failed to fetch sessions: "+t.status)
|
|
1210
|
-
let
|
|
1211
|
-
if(0===
|
|
1212
|
-
n.parentSessionId&&(
|
|
1213
|
-
const
|
|
1214
|
-
let w=
|
|
1218
|
+
let f=await t.json()
|
|
1219
|
+
if(0===f.length)return{content:[{type:"text",text:"No sessions found."}]}
|
|
1220
|
+
n.parentSessionId&&(f=f.filter((e=>(e.parentId||e.parentID)===n.parentSessionId))),f.sort(((e,t)=>t.time.created-e.time.created))
|
|
1221
|
+
const p=g.replace(/\/$/,"")+"/session/status",m=await fetch(p),y=m.ok?await m.json():{}
|
|
1222
|
+
let w=f
|
|
1215
1223
|
if(o&&(w=w.filter((e=>"idle"!==(y[e.id]?.type||"idle")))),void 0!==h){const e=36e5*h,t=Date.now()-e
|
|
1216
1224
|
w=w.filter((e=>e.time.created>=t))}if(0===w.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
|
|
1217
1225
|
let k={}
|
|
@@ -1219,10 +1227,10 @@ if(r)try{const e=r.getCLISessionClient()
|
|
|
1219
1227
|
e&&(k=await e.batchEnrich(w.map((e=>e.id))))}catch{}const b=g.replace(/\/$/,""),I=await Promise.allSettled(w.map((e=>fetch(`${b}/session/${e.id}/message`).then((e=>e.ok?e.json():[])).catch((()=>[]))))),v=[]
|
|
1220
1228
|
for(let e=0;e<w.length;e++){const t=w[e],r=Date.now()-t.time.created
|
|
1221
1229
|
let o=0,i=null,c=[],h=l(null,t.time.updated)
|
|
1222
|
-
const g=I[e],
|
|
1223
|
-
for(const e of
|
|
1224
|
-
if(
|
|
1225
|
-
h=l(e.lastActivityTime,t.time.updated),i=e.current||null,c=e.recent}const
|
|
1230
|
+
const g=I[e],f="fulfilled"===g.status?g.value:[]
|
|
1231
|
+
for(const e of f)"assistant"===e.info.role&&e.info.tokens&&(o+=(e.info.tokens.input||0)+(e.info.tokens.output||0)+(e.info.tokens.reasoning||0))
|
|
1232
|
+
if(f.length>0){const e=a(f)
|
|
1233
|
+
h=l(e.lastActivityTime,t.time.updated),i=e.current||null,c=e.recent}const p=h.status
|
|
1226
1234
|
if(void 0!==d&&d>o)continue
|
|
1227
1235
|
if(void 0!==u&&o>u)continue
|
|
1228
1236
|
const m=k[t.id]
|
|
@@ -1235,31 +1243,31 @@ b.push(...e,...t)
|
|
|
1235
1243
|
const r=[]
|
|
1236
1244
|
e.length>0&&r.push("active: "+e.join(", ")),t.length>0&&r.push("prev: "+t.join(", ")),r.length>0&&(y=` [${r.join(" | ")}]`)}if(s&&!b.includes(s))continue
|
|
1237
1245
|
const C=t.title||"Untitled",_=C.length>50?C.slice(0,47)+"...":C
|
|
1238
|
-
v.push({id:t.id,title:_,status:
|
|
1246
|
+
v.push({id:t.id,title:_,status:p,age:r,totalTokens:o,requestsInfo:y,allRequestIds:b,statusDetail:h.detail,specialization:m?.specialization??null,currentAction:i,recentActions:c})}if(0===v.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
|
|
1239
1247
|
const C=c?v.slice(0,c):v,_=C.map((e=>{const t=e.specialization?"\n Specialization: "+e.specialization:"",r=e.currentAction?"\n Current: "+e.currentAction:"",n=e.recentActions.length>0?"\n Recent: "+e.recentActions.join(", "):""
|
|
1240
1248
|
return`\u2022 ${e.id}\n ${e.title}${t}\n Status: ${e.status} (${e.statusDetail}) | Age: ${i(e.age)} | ${e.totalTokens.toLocaleString()} tokens${e.requestsInfo}${r}${n}`})),E=c&&v.length>c?` (showing ${c} of ${v.length})`:""
|
|
1241
|
-
return{content:[{type:"text",text:`Found ${C.length} session${1!==C.length?"s":""}${E}:\n\n${_.join("\n\n")}`}]}}catch(e){throw Error("Failed to list sessions: "+(0,E.getErrorMessage)(e))}}var p
|
|
1249
|
+
return{content:[{type:"text",text:`Found ${C.length} session${1!==C.length?"s":""}${E}:\n\n${_.join("\n\n")}`}]}}catch(e){throw Error("Failed to list sessions: "+(0,E.getErrorMessage)(e))}}var f,p=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
1242
1250
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
1243
|
-
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]}),m=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),y=this&&this.__importStar||(
|
|
1251
|
+
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]}),m=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),y=this&&this.__importStar||(f=function(e){return f=Object.getOwnPropertyNames||function(e){var t=[]
|
|
1244
1252
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
1245
|
-
return t},
|
|
1253
|
+
return t},f(e)},function(e){if(e&&e.__esModule)return e
|
|
1246
1254
|
var t={}
|
|
1247
|
-
if(null!=e)for(var r=
|
|
1255
|
+
if(null!=e)for(var r=f(e),n=0;n<r.length;n++)"default"!==r[n]&&p(t,e,r[n])
|
|
1248
1256
|
return m(t,e),t})
|
|
1249
1257
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpawn=o,exports.handleContinue=s,exports.handleCheckStatus=u,exports.handleAbort=h,exports.handleListSessions=g,exports.handleSubagentOperations=async function(e,t,r,n,i,a){const c=r.child({tool:"subagent_operations"}),l=n.startTimer("tool_execution_time")
|
|
1250
1258
|
try{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})),"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)
|
|
1251
|
-
const r=_.validateArgs(e,C.SubagentOperationsSchema),{sessionId:d,operation:
|
|
1252
|
-
let
|
|
1253
|
-
switch(c.info("Processing subagent_operations",{operation:
|
|
1259
|
+
const r=_.validateArgs(e,C.SubagentOperationsSchema),{sessionId:d,operation:f}=r
|
|
1260
|
+
let p
|
|
1261
|
+
switch(c.info("Processing subagent_operations",{operation:f,sessionId:d}),f){case"spawn":p=await o(r.spawn,t,c,i,a)
|
|
1254
1262
|
break
|
|
1255
|
-
case"continue":
|
|
1263
|
+
case"continue":p=await s(d,r.continue.prompt,t,c,i,void 0,a)
|
|
1256
1264
|
break
|
|
1257
|
-
case"check-status":
|
|
1265
|
+
case"check-status":p=await u(d,t,c,i)
|
|
1258
1266
|
break
|
|
1259
|
-
case"abort":
|
|
1267
|
+
case"abort":p=await h(d,t,c)
|
|
1260
1268
|
break
|
|
1261
1269
|
case"read-messages":const e=r.readMessages?.limit??1
|
|
1262
|
-
|
|
1270
|
+
p=await async function(e,t,r,n){const o=await(0,b.getServerUrl)(r,n)
|
|
1263
1271
|
if(!o)throw new w.ValidationError("Could not determine OpenCode server URL")
|
|
1264
1272
|
n.info("Reading messages from subagent session",{sessionId:e,limit:t})
|
|
1265
1273
|
try{const r=`${o.replace(/\/$/,"")}/session/${e}/message?limit=${t}`,n=await fetch(r)
|
|
@@ -1271,9 +1279,9 @@ return`[${t+1}] ${r} (${new Date(e.info.time.created).toLocaleTimeString()}):\n$
|
|
|
1271
1279
|
return{content:[{type:"text",text:`Session ${e} - Last ${s.length} messages:\n\n${i}`}]}}catch(e){throw Error("Failed to read messages: "+(0,E.getErrorMessage)(e))}}(d,e,t,c)
|
|
1272
1280
|
break
|
|
1273
1281
|
case"list-sessions":const n={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||(0,I.getCachedSession)()?.sessionId}
|
|
1274
|
-
|
|
1282
|
+
p=await g(t,c,i,n)
|
|
1275
1283
|
break
|
|
1276
|
-
default:throw new w.ValidationError("Unknown operation: "+
|
|
1284
|
+
default:throw new w.ValidationError("Unknown operation: "+f)}return l({success:!0}),n.incrementCounter(`subagent_operations_${f}_success`,1),p}catch(e){return c.error("Subagent operations failed",{error:e instanceof Error?e.stack:e+""}),l({success:!1}),n.incrementCounter("subagent_operations_errors",1),{content:[{type:"text",text:"Subagent operation failed: "+(0,E.getErrorMessage)(e)}],isError:!0}}}
|
|
1277
1285
|
const w=t(9860),k=t(8035),b=t(7617),I=t(715),v=t(7280),C=t(6183),_=y(t(5967)),E=t(8824),q=t(9896),S=t(6928),T=t(8955),M=t(5671),R=3456,P=6e4,x=3e5},1791(e,exports,t){function r(e,t){return t.info("Creating project context middleware",{projectId:e}),(t,r,n)=>{"GET"===t.method&&(t.query.projectId=e),["POST","PATCH","PUT"].includes(t.method)&&t.body&&(t.body.projectId=e),n()}}var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1278
1286
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectContext=void 0,exports.projectContextMiddleware=r
|
|
1279
1287
|
const o=n(t(9896)),s=n(t(6928)),i=t(4139),a=t(4055),c=t(8824)
|
|
@@ -1421,20 +1429,22 @@ try{const{sessionIdentity:e}=await Promise.resolve().then(t.bind(t,6688)),r=e.ge
|
|
|
1421
1429
|
if(g.push("session: "+(r?.sessionId||"NONE")),r?.sessionId){const t=await e.getSessionRequestId(o,s)
|
|
1422
1430
|
if(g.push("reqId: "+(t||"NONE")),t){const e=await o.proxyGet(`/api/projects/${n.projectId}/requests/${t}/test-runs`),r=e?.data||e||[],s=Array.isArray(r)?r.find((e=>e.worktreePath||e.worktree_path)):null
|
|
1423
1431
|
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}
|
|
1424
|
-
const
|
|
1432
|
+
const f=[]
|
|
1425
1433
|
for(const t of l){c.info("Executing test command",{name:t.name,command:t.command,timeout:t.timeout,cwd:h})
|
|
1426
1434
|
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"}})
|
|
1427
|
-
|
|
1428
|
-
if(
|
|
1435
|
+
f.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
|
|
1436
|
+
if(f.push({name:t.name,command:t.command,exitCode:s,output:o,timedOut:n}),"setup"===e.commandName)break}}const p=f.every((e=>0===e.exitCode)),m=f.map((e=>{const t=e.timedOut?"\u23f1 TIMEOUT":0===e.exitCode?"\u2705 PASS":`\u274c FAIL (exit ${e.exitCode})`
|
|
1429
1437
|
return`### ${e.name}: ${t}\n\`\`\`\n$ ${e.command}\n${e.output}\n\`\`\``})).join("\n\n")
|
|
1430
|
-
return a({success:!0}),{content:[{type:"text",text:`## ${"setup"===e.commandName?"Setup":e.commandName} \u2014 ${
|
|
1438
|
+
return a({success:!0}),{content:[{type:"text",text:`## ${"setup"===e.commandName?"Setup":e.commandName} \u2014 ${p?"PASSED":"FAILED"}\n\n${m}`}]}}catch(e){return a({success:!1,error:"execution_error"}),{content:[{type:"text",text:"Failed to execute test command: "+(0,r.getErrorMessage)(e)}],isError:!0}}},exports.handleReportTestResults=async function(e,o,s,i,a){const c=a.startTimer("tool_execution_time")
|
|
1431
1439
|
try{const{sessionIdentity:l}=await Promise.resolve().then(t.bind(t,6688)),d=await l.getSessionRequestId(s,i)
|
|
1432
1440
|
if(!d)return c({success:!1,error:"no_request_association"}),{content:[{type:"text",text:"Cannot report test results: this session is not associated with a request."}],isError:!0}
|
|
1433
|
-
const u=await s.proxyGet(`/api/projects/${o.projectId}/requests/${d}/test-runs`),h=u?.data||u||[],g=Array.isArray(h)?h:[],
|
|
1434
|
-
if(!
|
|
1435
|
-
const f
|
|
1436
|
-
await s.proxyPatch(`/api/projects/${o.projectId}/test-runs/${
|
|
1437
|
-
const m="passed"===e.status?"\u2705":"failed"===e.status?"\u274c":"\u26a0\ufe0f"
|
|
1441
|
+
const u=await s.proxyGet(`/api/projects/${o.projectId}/requests/${d}/test-runs`),h=u?.data||u||[],g=Array.isArray(h)?h:[],f=g.find((e=>"pending"===e.status||"running"===e.status))||g[0]
|
|
1442
|
+
if(!f)return c({success:!1,error:"no_test_run"}),{content:[{type:"text",text:`No test run found for request ${d}.`}],isError:!0}
|
|
1443
|
+
const p=f.id
|
|
1444
|
+
await s.proxyPatch(`/api/projects/${o.projectId}/test-runs/${p}`,{status:e.status,results:e.results})
|
|
1445
|
+
const m="passed"===e.status?"\u2705":"failed"===e.status?"\u274c":"\u26a0\ufe0f"
|
|
1446
|
+
try{const t=s.getRequestClient()
|
|
1447
|
+
"passed"===e.status?(await t.updateRequest(d,{status:"ready_for_merge"}),i.info("Tests passed, set request to ready_for_merge",{requestId:d})):(await t.updateRequest(d,{status:"in_progress"}),i.info("Tests failed, set request back to in_progress",{requestId:d}))}catch(e){i.warn("Failed to update request status after test results",{requestId:d,error:(0,r.getErrorMessage)(e)})}const y="passed"===e.status?"\n\nAll tests passed \u2014 the coder can now call `merge` to merge this request.":"\n\nTests failed \u2014 the coder should fix the issues and call `complete` again.",w=`${m} Test run ${e.status} for request ${d}\n\n${e.results.summary}${y}`
|
|
1438
1448
|
try{const t=await(0,n.handleSessionMessageOperations)({operation:"send",type:"report",status:"passed"===e.status?"success":"failure",summary:w,details:e.results.commands?.map((e=>`${"passed"===e.status?"\u2705":"\u274c"} ${e.name}: ${e.status}${e.diagnosis?" - "+e.diagnosis:""}`)).join("\n"),finish:!0},o,i,a,s),r=t?.content?.[0]?.text||"unknown",l=t?.isError
|
|
1439
1449
|
return c({success:!0}),{content:[{type:"text",text:`Test run for request ${d} reported as **${e.status}**.${l?" Parent notification FAILED: "+r:" Parent session notified."}\n\n${e.results.summary}`}]}}catch(t){return c({success:!0}),{content:[{type:"text",text:`Test run for request ${d} reported as **${e.status}** but failed to notify parent: ${(0,r.getErrorMessage)(t)}\n\n${e.results.summary}`}]}}}catch(e){return c({success:!1,error:"api_error"}),{content:[{type:"text",text:"Failed to report test results: "+(0,r.getErrorMessage)(e)}],isError:!0}}},exports.handleTestingReference=async function(e,t,r,n,o){return o.startTimer("tool_execution_time")({success:!0}),{content:[{type:"text",text:'# Test Process Design Guide\n\n## Overview\n\nA test process defines how to verify code changes for a project. It consists of:\n- **Setup**: Commands to prepare the environment (install deps, link node_modules, etc.) \u2014 runs once per worktree\n- **Commands**: The actual test commands (build, lint, test, etc.) \u2014 the verification steps\n\n## Command Properties\n\n- **name**: Human-readable name (e.g., "Build", "Unit Tests")\n- **command**: Shell command to run (e.g., `npm test`)\n- **required** (default: true): If a required command fails, the request won\'t be merged\n- **timeout** (default: 300s): Maximum execution time. Exit code 0 = pass, non-zero = fail.\n\n## Scope (Monorepo Support)\n\nSet `scope` to a path prefix to limit when a process runs:\n- `scope: "packages/api/"` \u2192 only runs when files under packages/api/ change\n- `scope: null` \u2192 runs for all changes (global process)\n\nMultiple active processes per project are supported.\n\n## Common Patterns\n\n### Node.js / TypeScript\n```json\n{\n "setup": ["ln -s ../../node_modules node_modules"],\n "commands": [\n { "name": "Build", "command": "npm run build" },\n { "name": "Lint", "command": "npm run lint", "required": false },\n { "name": "Unit Tests", "command": "npm test" }\n ]\n}\n```\n\n### Python\n```json\n{\n "setup": ["pip install -e \'.[dev]\'"],\n "commands": [\n { "name": "Type Check", "command": "mypy src/" },\n { "name": "Lint", "command": "ruff check .", "required": false },\n { "name": "Tests", "command": "pytest" }\n ]\n}\n```\n\n### Go\n```json\n{\n "setup": ["go mod download"],\n "commands": [\n { "name": "Build", "command": "go build ./..." },\n { "name": "Vet", "command": "go vet ./...", "required": false },\n { "name": "Tests", "command": "go test ./..." }\n ]\n}\n```\n\n### Rust\n```json\n{\n "setup": ["cargo fetch"],\n "commands": [\n { "name": "Build", "command": "cargo build" },\n { "name": "Clippy", "command": "cargo clippy -- -D warnings", "required": false },\n { "name": "Tests", "command": "cargo test" }\n ]\n}\n```\n\n## Project Analysis Checklist\n\nWhen setting up testing for a new project, check for:\n1. **package.json** \u2192 Node.js/TypeScript (check "scripts" for test/build/lint commands)\n2. **Cargo.toml** \u2192 Rust\n3. **go.mod** \u2192 Go\n4. **pyproject.toml** / **requirements.txt** \u2192 Python\n5. **Makefile** \u2192 Custom build system (check for test/build targets)\n6. **.github/workflows/** \u2192 Existing CI configuration (great source of test commands)\n7. **.gitlab-ci.yml** \u2192 GitLab CI\n8. **tsconfig.json** \u2192 TypeScript type checking\n9. **.eslintrc** / **biome.json** \u2192 Linting configuration\n10. **vitest.config.ts** / **jest.config.ts** / **pytest.ini** \u2192 Test framework configuration'}]}}
|
|
1440
1450
|
const r=t(8824),n=t(9072)},2085(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.getRequestTimelineForFile=async function(e,t,s,i){let a=`# File History: ${t}\n\n`
|
|
@@ -1546,7 +1556,7 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
1546
1556
|
var t={}
|
|
1547
1557
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
1548
1558
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1549
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,t,r,n,o,s,i,
|
|
1559
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,t,r,n,o,s,i,p){const m=s.child({tool:"move_files"}),y=Date.now()
|
|
1550
1560
|
let w,k,b=d.FileOperationPhase.VALIDATION
|
|
1551
1561
|
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"}
|
|
1552
1562
|
try{const s=d.validateArgs(e,l.MoveFilesSchema),{taskId:u,operations:h,comment:v}=s
|
|
@@ -1565,7 +1575,7 @@ throw Error(M.error)}let R={hadUserMods:!1,userModsCommitHash:void 0}
|
|
|
1565
1575
|
if(t.git)try{m.debug("[MOVE-FILES] Checking for user changes before move operations")
|
|
1566
1576
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"move-files",{requestId:q,taskId:u,workspaceManager:t.workspaceManager},m,i)
|
|
1567
1577
|
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}),R={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})
|
|
1568
|
-
const{toolRecordId:P,localToolRecordId:x}=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:R.hadUserMods,userModsCommitHash:R.userModsCommitHash},r,n,m,i,I.metricsPrefix,
|
|
1578
|
+
const{toolRecordId:P,localToolRecordId:x}=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:R.hadUserMods,userModsCommitHash:R.userModsCommitHash},r,n,m,i,I.metricsPrefix,p)
|
|
1569
1579
|
w=P,k=P,b=I.fileOperationPhase,i.incrementCounter("move_files_phase",1,{phase:b})
|
|
1570
1580
|
const O=[]
|
|
1571
1581
|
let j=0
|
|
@@ -1573,27 +1583,27 @@ for(const e of _){const t={operation:{source:e.source,destination:e.destination}
|
|
|
1573
1583
|
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()
|
|
1574
1584
|
t.isDirectory=r
|
|
1575
1585
|
const n=c.default.dirname(e.fullDestination)
|
|
1576
|
-
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,j++,m.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,
|
|
1586
|
+
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,j++,m.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,f.getErrorMessage)(r),m.warn(`Failed to move ${e.source} to ${e.destination}`,{error:t.error})}O.push(t)}const $=Date.now()-y
|
|
1577
1587
|
i.recordValue("move_files_time",$),i.incrementCounter("move_files_operations_total",h.length),i.incrementCounter("move_files_operations_success",j),i.incrementCounter("move_files_operations_failed",h.length-j),j===h.length?i.incrementCounter("move_files_success",1):j>0?i.incrementCounter("move_files_partial_success",1):i.incrementCounter("move_files_total_failure",1)
|
|
1578
|
-
let
|
|
1588
|
+
let D=null
|
|
1579
1589
|
if(j>0){b=d.FileOperationPhase.GIT_COMMIT,i.incrementCounter("move_files_phase",1,{phase:b})
|
|
1580
1590
|
const e=O.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}`
|
|
1581
|
-
|
|
1582
|
-
const
|
|
1583
|
-
await d.updateFileOperationRecords(u,w,k,_[0].source,I.recordType,j===h.length?`Successfully moved all ${h.length} items`:`Moved ${j}/${h.length} items successfully`,{status:j===h.length?"completed":"partial_success",commitHash:
|
|
1591
|
+
D=await d.commitToGit(u,_[0].destination,P,x,r,t,m,i,I.metricsPrefix)}b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,i.incrementCounter("move_files_phase",1,{phase:b})
|
|
1592
|
+
const A=O.filter((e=>e.success)),F=O.filter((e=>!e.success))
|
|
1593
|
+
await d.updateFileOperationRecords(u,w,k,_[0].source,I.recordType,j===h.length?`Successfully moved all ${h.length} items`:`Moved ${j}/${h.length} items successfully`,{status:j===h.length?"completed":"partial_success",commitHash:D?.commitHash,previousCommitHash:D?.previousCommitHash,operationCount:h.length,successCount:j,failureCount:h.length-j,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:R.hadUserMods,userModsCommitHash:R.userModsCommitHash},j===h.length?`Successfully moved all ${h.length} items`:`Moved ${j}/${h.length} items successfully`,r,n,m,i,I.metricsPrefix)
|
|
1584
1594
|
const N=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
1585
1595
|
let L=""
|
|
1586
1596
|
if(j===h.length)L=`Successfully moved all ${h.length} ${1===h.length?"item":"items"}`
|
|
1587
1597
|
else if(j>0){const e=O.filter((e=>!e.success))
|
|
1588
1598
|
L=`Successfully moved ${j}/${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"+O.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")
|
|
1589
|
-
return
|
|
1590
|
-
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,
|
|
1591
|
-
if(i.recordValue("move_files_time",s),i.incrementCounter("move_files_errors",1),m.error("Error in move-files operation:",{error:(0,
|
|
1592
|
-
try{await d.updateFileOperationRecords(e.taskId,w,k,e.operations?.[0]?.source||"unknown",I.recordType,"Failed to move files",{status:"failed",error:(0,
|
|
1593
|
-
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),
|
|
1599
|
+
return D?.commitHash&&(L+="\nCommit: "+D.commitHash.substring(0,8)),N.requestId&&(L+="\nBranch: "+N.requestId),M.lockAcquired&&M.lockedRequestId&&(L+="\n\u{1f512} **Locked request:** "+M.lockedRequestId),{content:[{type:"text",text:L}],isError:0===j}}catch(o){if(e.taskId&&n)try{const r=o instanceof u.NotFoundError||o instanceof u.ValidationError||o instanceof h.ZodError
|
|
1600
|
+
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,f.getErrorMessage)(o),errorDetails:o instanceof Error?o.stack:o+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:r},note:"Failed to move files - "+(0,f.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
|
|
1601
|
+
if(i.recordValue("move_files_time",s),i.incrementCounter("move_files_errors",1),m.error("Error in move-files operation:",{error:(0,f.getErrorMessage)(o),time:s}),(w||k)&&e.taskId){b=d.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
1602
|
+
try{await d.updateFileOperationRecords(e.taskId,w,k,e.operations?.[0]?.source||"unknown",I.recordType,"Failed to move files",{status:"failed",error:(0,f.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)}}
|
|
1603
|
+
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),f=t(8824)},2422(module){module.exports=require("@modelcontextprotocol/sdk/server/sse.js")},2425(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
1594
1604
|
const r=t(6183),n=t(3707)
|
|
1595
1605
|
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){Object.defineProperty(exports,"__esModule",{value:!0})
|
|
1596
|
-
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),
|
|
1606
|
+
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),f=t(4805),p=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),M=t(4921),R=t(8850),P=t(3556),x=t(1391),O=t(6315),j=t(7713),$=t(6252),D=t(213),A=t(7250),F=t(2425),N=t(1540),L=t(5767),z=t(4973),B=t(7613),H=t(3322),W=t(5247),U=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)(f.def),(0,r.registerTool)(p.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)(M.def),(0,r.registerTool)(R.def),(0,r.registerTool)(P.def),(0,r.registerTool)(x.def),(0,r.registerTool)(O.def),(0,r.registerTool)(j.def),(0,r.registerTool)($.def),(0,r.registerTool)(D.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)(B.def),(0,r.registerTools)(H.metaDefs),(0,r.registerTools)(W.testingDefs),(0,r.registerTools)(U.debugDefs),(0,t(2245).freezeRegistry)()},2478(e,exports){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){async function r(e,t,r){if(C.has(r)&&_>=t){if(0===t)return 0
|
|
1597
1607
|
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]"
|
|
1598
1608
|
let l=""
|
|
1599
1609
|
if(s||void 0===o?.lineCount||(l=` (${i(o.lineCount)} lines)`),s&&o?.subtreeTotals){const{files:e,lines:t}=o.subtreeTotals
|
|
@@ -1616,10 +1626,10 @@ let t=e,r=0
|
|
|
1616
1626
|
for(;t>=1024&&4>r;)t/=1024,r++
|
|
1617
1627
|
return`${0===r?t.toString():t.toFixed(10>t?1:0)}${["bytes","KB","MB","GB","TB"][r]}`}(o.size)})`)}return`${c} ${a}${l}`}async function o(e,t,n=0,s,i,l){if(n>=s)return[]
|
|
1618
1628
|
try{const{fullPath:d}=b.validateAndNormalizePath(e,t),h=await y.default.readdir(d,{withFileTypes:!0}),g=[]
|
|
1619
|
-
for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=b.validateAndNormalizePath(u,t),
|
|
1629
|
+
for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=b.validateAndNormalizePath(u,t),f=await y.default.stat(h),p=d.isFile()?w.default.extname(d.name).toLowerCase():""
|
|
1620
1630
|
let m
|
|
1621
|
-
d.isFile()&&(m=await r(h,
|
|
1622
|
-
const k={name:d.name,isDirectory:d.isDirectory(),depth:n,size:
|
|
1631
|
+
d.isFile()&&(m=await r(h,f.size,p))
|
|
1632
|
+
const k={name:d.name,isDirectory:d.isDirectory(),depth:n,size:f.size,modified:f.mtime,extension:p,lineCount:m}
|
|
1623
1633
|
d.isDirectory()&&(s-1>n?(k.children=await o(u,t,n+1,s,i,l),k.children&&k.children.length>0&&(k.subtreeTotals=c(k.children))):k.subtreeTotals=await a(u,t,l)),g.push(k)}catch(e){l.debug("Excluding entry from tree: "+d.name,{reason:(0,v.getErrorMessage)(e)})}return u(g,i)}catch(t){return l.debug(`Failed to build tree for ${e}:`,{error:(0,v.getErrorMessage)(t)}),[]}}function s(e,t="name",r=""){if(0===e.length)return""
|
|
1624
1634
|
const o=[]
|
|
1625
1635
|
return e.forEach(((i,a)=>{const c=a===e.length-1,l=c?"\u2514\u2500\u2500 ":"\u251c\u2500\u2500 ",d=n(i,t),u=i.isDirectory?"/":""
|
|
@@ -1645,21 +1655,21 @@ case"type":const o=e.extension||"",s=r.extension||""
|
|
|
1645
1655
|
return o!==s?o.localeCompare(s):e.name.localeCompare(r.name)
|
|
1646
1656
|
default:return e.name.localeCompare(r.name)}}))}var h,g=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
1647
1657
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
1648
|
-
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]}),
|
|
1658
|
+
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]}),f=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),p=this&&this.__importStar||(h=function(e){return h=Object.getOwnPropertyNames||function(e){var t=[]
|
|
1649
1659
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
1650
1660
|
return t},h(e)},function(e){if(e&&e.__esModule)return e
|
|
1651
1661
|
var t={}
|
|
1652
1662
|
if(null!=e)for(var r=h(e),n=0;n<r.length;n++)"default"!==r[n]&&g(t,e,r[n])
|
|
1653
|
-
return
|
|
1663
|
+
return f(t,e),t}),m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1654
1664
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListDirectory=async function(e,t,i,a){const h=Date.now()
|
|
1655
1665
|
let g=b.FileOperationPhase.VALIDATION
|
|
1656
1666
|
b.FileOperationPhase.FILE_WRITE
|
|
1657
|
-
try{const
|
|
1658
|
-
i.info("Listing directory: "+
|
|
1659
|
-
const{normalizedPath:C,fullPath:_}=b.validateAndNormalizePath(
|
|
1667
|
+
try{const f=b.validateArgs(e,k.ListDirectorySchema),{path:p,levels:m=1,sortBy:I="name"}=f
|
|
1668
|
+
i.info("Listing directory: "+p)
|
|
1669
|
+
const{normalizedPath:C,fullPath:_}=b.validateAndNormalizePath(p,t)
|
|
1660
1670
|
g=b.FileOperationPhase.FILE_WRITE
|
|
1661
|
-
try{if(!(await y.default.stat(_)).isDirectory())return{content:[{type:"text",text:"Path is not a directory: "+
|
|
1662
|
-
await y.default.access(_,y.default.constants.R_OK)}catch(e){return e instanceof Error&&"ENOENT"===e.code?{content:[{type:"text",text:"Directory does not exist: "+
|
|
1671
|
+
try{if(!(await y.default.stat(_)).isDirectory())return{content:[{type:"text",text:"Path is not a directory: "+p}],isError:!0}
|
|
1672
|
+
await y.default.access(_,y.default.constants.R_OK)}catch(e){return e instanceof Error&&"ENOENT"===e.code?{content:[{type:"text",text:"Directory does not exist: "+p}],isError:!0}:e instanceof Error&&"EACCES"===e.code?{content:[{type:"text",text:"Directory not accessible: "+p}],isError:!0}:{content:[{type:"text",text:"Cannot access directory: "+p}],isError:!0}}let E,q
|
|
1663
1673
|
if(m>1){i.info(`Building tree structure for: ${C} (levels: ${m}, sortBy: ${I})`)
|
|
1664
1674
|
const e=await o(C,t,0,m,I,i)
|
|
1665
1675
|
if(e.length>0){const t=s(e,I)
|
|
@@ -1672,7 +1682,7 @@ E+="\n\nBranch: "+(S?.branchName||"unknown")
|
|
|
1672
1682
|
const T=Date.now()-h
|
|
1673
1683
|
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
|
|
1674
1684
|
return a.recordValue("list_directory_time",t),a.incrementCounter("list_directory_errors",1),i.error("Error listing directory:",{error:(0,v.getErrorMessage)(e),time:t}),{content:[{type:"text",text:(0,v.getErrorMessage)(e)}],isError:!0}}}
|
|
1675
|
-
const y=m(t(1943)),w=m(t(6928)),k=t(6183),b=
|
|
1685
|
+
const y=m(t(1943)),w=m(t(6928)),k=t(6183),b=p(t(5967)),I=t(3253),v=t(8824),C=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore",".config",".conf",".ini",".cfg"]),_=1048576},2601(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
1676
1686
|
const r=t(6183),n=t(76)
|
|
1677
1687
|
exports.def={name:"create_task",description:"Create a new task under an existing request.",schema:r.CreateTaskSchema,annotations:{title:"Create Task",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleCreateTask)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},2690(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.SessionMessageClient=void 0
|
|
1678
1688
|
const r=t(7645),n=t(2161)
|
|
@@ -1725,12 +1735,12 @@ if(!r())return t.level=(0,l.isDevBuild)()?c.LogLevel.INFO:c.LogLevel.ERROR,t.log
|
|
|
1725
1735
|
if("true"===process.env.DEBUG_LOGGING?.toLowerCase()){t.level=c.LogLevel.DEBUG,t.logToFile=!0
|
|
1726
1736
|
const r=e||process.cwd()
|
|
1727
1737
|
t.logFilePath=i.default.join(r,"logs","debug.log")}const n=process.env.DEBUG_LEVEL?.toLowerCase()
|
|
1728
|
-
return n&&Object.values(c.LogLevel).includes(n)&&(t.level=n),t}(e.baseDir),...e},{level:o=c.LogLevel.INFO,serviceName:g="mcp-service",logToFile:
|
|
1729
|
-
if(console&&m.push(new s.default.transports.Console({format:d,stderrLevels:["error","warn","info","debug"]})),
|
|
1730
|
-
a.default.existsSync(t)||a.default.mkdirSync(t,{recursive:!0})}(
|
|
1738
|
+
return n&&Object.values(c.LogLevel).includes(n)&&(t.level=n),t}(e.baseDir),...e},{level:o=c.LogLevel.INFO,serviceName:g="mcp-service",logToFile:f=!1,logFilePath:p="./logs/app.log",console=!0}=t,m=[]
|
|
1739
|
+
if(console&&m.push(new s.default.transports.Console({format:d,stderrLevels:["error","warn","info","debug"]})),f){!function(e){const t=i.default.dirname(e)
|
|
1740
|
+
a.default.existsSync(t)||a.default.mkdirSync(t,{recursive:!0})}(p)
|
|
1731
1741
|
const e=o===c.LogLevel.DEBUG&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()
|
|
1732
|
-
m.push(new s.default.transports.File({filename:
|
|
1733
|
-
return o===c.LogLevel.DEBUG&&
|
|
1742
|
+
m.push(new s.default.transports.File({filename:p,format:e?h:u}))}const y=s.default.createLogger({level:o,defaultMeta:{service:g},transports:m})
|
|
1743
|
+
return o===c.LogLevel.DEBUG&&f&&r()&&y.info("Enhanced logging initialized",{level:o,serviceName:g,logToFile:f,logFilePath:p,debugLogging:process.env.DEBUG_LOGGING}),{error(e,t){y.error(e,t)},warn(e,t){y.warn(e,t)},info(e,t){y.info(e,t)},debug(e,t){y.debug(e,t)},child(e){const r=y.child(e)
|
|
1734
1744
|
return{error(e,t){r.error(e,t)},warn(e,t){r.warn(e,t)},info(e,t){r.info(e,t)},debug(e,t){r.debug(e,t)},child(e){return n({...t,serviceName:`${g}:${e.component||"nested"}`})}}}}}var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1735
1745
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.createLogger=n,exports.createEnvLogger=function(e={}){return n(e)},exports.isDebugToolsEnabled=r,exports.isDebugLoggingEnabled=function(){return!!r()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()},exports.getDebugLevelFromEnv=function(){if(!r())return c.LogLevel.INFO
|
|
1736
1746
|
const e=process.env.DEBUG_LEVEL?.toLowerCase()
|
|
@@ -1762,14 +1772,14 @@ const a="binary"!==n?i.split("\n").length:void 0
|
|
|
1762
1772
|
if(e.lines&&"binary"!==n){const t=(0,g.parseLineSpec)(e.lines)
|
|
1763
1773
|
i=(0,g.extractLines)(i,t).text}const c="binary"!==n?i.split("\n").length:void 0
|
|
1764
1774
|
return{type:"file",path:r,content:i,success:!0,lineCount:c,totalLines:a,size:s.size,originalRequest:e}}catch(t){let r
|
|
1765
|
-
return r=t instanceof Error&&"ENOENT"===t.code?"File not found: "+e.path:(0,
|
|
1775
|
+
return r=t instanceof Error&&"ENOENT"===t.code?"File not found: "+e.path:(0,f.getErrorMessage)(t),{type:"file",path:e.path,content:"",success:!1,error:r,originalRequest:e}}}async function n(e,t,r,n){try{if(!t.documentFileManager)return{type:"document",documentId:e.documentId,content:"",success:!1,error:"Document file manager not available"}
|
|
1766
1776
|
const r=await t.documentFileManager.getDocumentAsFile(e.documentId),o=t.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
1767
1777
|
let s
|
|
1768
1778
|
s="binary"===n?(await l.default.readFile(r)).toString("base64"):await l.default.readFile(r,n)
|
|
1769
1779
|
const i="binary"!==n?s.split("\n").length:void 0
|
|
1770
1780
|
if(e.lines&&"binary"!==n){const t=(0,g.parseLineSpec)(e.lines)
|
|
1771
1781
|
s=(0,g.extractLines)(s,t).text}const a="binary"!==n?s.split("\n").length:void 0,c=await l.default.stat(r)
|
|
1772
|
-
return{type:"document",documentId:e.documentId,filename:o?.filename,content:s,success:!0,lineCount:a,totalLines:i,size:c.size,originalRequest:e}}catch(t){return{type:"document",documentId:e.documentId,content:"",success:!1,error:(0,
|
|
1782
|
+
return{type:"document",documentId:e.documentId,filename:o?.filename,content:s,success:!0,lineCount:a,totalLines:i,size:c.size,originalRequest:e}}catch(t){return{type:"document",documentId:e.documentId,content:"",success:!1,error:(0,f.getErrorMessage)(t),originalRequest:e}}}var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
1773
1783
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
1774
1784
|
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]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[]
|
|
1775
1785
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -1786,20 +1796,20 @@ i.info("Reading multiple files and documents",{totalRequests:c.length,encoding:l
|
|
|
1786
1796
|
const h=[],g=[]
|
|
1787
1797
|
for(const e of c)e.path?h.push({type:"file",path:e.path,lines:e.lines}):e.documentId&&g.push({type:"document",documentId:e.documentId,lines:e.lines})
|
|
1788
1798
|
i.info("Request breakdown",{fileRequests:h.length,documentRequests:g.length})
|
|
1789
|
-
const
|
|
1790
|
-
for(const e of h)
|
|
1791
|
-
for(const e of g)
|
|
1792
|
-
const
|
|
1799
|
+
const f=[]
|
|
1800
|
+
for(const e of h)f.push(r(e,t,0,l))
|
|
1801
|
+
for(const e of g)f.push(n(e,t,0,l))
|
|
1802
|
+
const p=await Promise.all(f)
|
|
1793
1803
|
let m=""
|
|
1794
1804
|
if(t.getCurrentBranchContext)try{const e=await t.getCurrentBranchContext()
|
|
1795
|
-
e.branch&&(m=`**Current Branch:** ${e.branch}\n`)}catch(e){i.debug("Could not get branch context",{error:e})}const y=
|
|
1805
|
+
e.branch&&(m=`**Current Branch:** ${e.branch}\n`)}catch(e){i.debug("Could not get branch context",{error:e})}const y=p.filter((e=>e.success)).length,w=p.filter((e=>!e.success)).length,k=p.length
|
|
1796
1806
|
let b="## Read Files/Documents\n\n"
|
|
1797
1807
|
m&&(b+=m),b+=`**Total Requests:** ${k} - **Successful:** ${y} - **Failed:** ${w}\n\n`
|
|
1798
|
-
for(let e=0;e<
|
|
1808
|
+
for(let e=0;e<p.length;e++){const t=p[e]
|
|
1799
1809
|
"file"===t.type?b+=`File ${e+1}: ${t.path}\n`:(b+=`Document ${e+1}: ${t.documentId}`,t.filename&&(b+=` (${t.filename})`),b+="\n"),t.success?(b+="**Status:** Success\n",t.lineCount&&t.totalLines&&(b+=`Lines Read / Total Lines ${t.lineCount} / ${t.totalLines}\n`),t.originalRequest?.lines&&t.totalLines&&(b+=`**Lines:** ${t.originalRequest.lines}\n`),b+=`\n**Content:**\n\`\`\`\n${t.content}\n\`\`\`\n`):(b+="**Status:** Failed\n",b+=`**Error:** ${t.error}\n`),b+="\n"}const I=0===w
|
|
1800
1810
|
return i.info("Multiple file/document read completed",{duration:Date.now()-a,totalRequests:k,successfulReads:y,failedReads:w,success:I}),s.incrementCounter("read_files_total",1,{success:I}),{content:[{type:"text",text:b}],isError:!I}}catch(e){const t=Date.now()-a
|
|
1801
|
-
return i.error("Read multiple files operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),s.incrementCounter("read_files_errors",1),{content:[{type:"text",text:"\u274c **Read Operation Failed:** "+(0,
|
|
1802
|
-
const l=c(t(1943)),d=t(6183),u=t(1569),h=a(t(5967)),g=t(9470),
|
|
1811
|
+
return i.error("Read multiple files operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),s.incrementCounter("read_files_errors",1),{content:[{type:"text",text:"\u274c **Read Operation Failed:** "+(0,f.getErrorMessage)(e)}],isError:!0}}}
|
|
1812
|
+
const l=c(t(1943)),d=t(6183),u=t(1569),h=a(t(5967)),g=t(9470),f=t(8824)},2968(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.TaskClient=void 0
|
|
1803
1813
|
const r=t(8824),n=t(7645),o=t(2161),s=t(5172)
|
|
1804
1814
|
class i extends n.ConnectionAwareClient{async createTask(e){if(this.logger.debug("Creating task",{taskInput:e}),!e.projectId){const t=this.projectClient.getProjectId()
|
|
1805
1815
|
if(!t)throw this.logger.error("No project ID available for task creation"),Error("Project ID is required for task creation")
|
|
@@ -1874,17 +1884,17 @@ return n.info(`Task ID ${e} validated successfully`,{taskId:e,requestId:o.reques
|
|
|
1874
1884
|
if(c.includes("404")||c.toLowerCase().includes("not found")||c.toLowerCase().includes("task not found"))throw n.error(`Task ID ${e} does not exist (404 Not Found)`,{taskId:e,path:t,error:c}),i.incrementCounter(a+"_task_not_found",1),new o.NotFoundError(`Task ${e} not found in project. Please provide a valid task ID.`,{taskId:e,path:t,originalError:r})
|
|
1875
1885
|
throw n.error("Could not validate task ID "+e,{taskId:e,path:t,error:c}),i.incrementCounter(a+"_task_validation_error",1),new o.ValidationError(`Could not validate task ${e}: ${c}`,{taskId:e,path:t,originalError:r})}},exports.createReopenGuidanceMessage=r,exports.validateWorkItemStates=async function(e,t,n,a,c,l,d,u){try{const h=await n.getTask(e)
|
|
1876
1886
|
if(l.info("Validating work item states for task "+e,{taskId:e,taskStatus:h.status,requestId:h.requestId,path:t}),l.info("STRICT VALIDATION - Task details",{taskId:e,taskStatus:h.status,requestId:h.requestId,taskTitle:h.title,path:t,timestamp:(new Date).toISOString()}),"completed"===h.status||"canceled"===h.status||"reverted"===h.status){const n=r(e,h.requestId,h.status)
|
|
1877
|
-
throw l.error(`STRICT VALIDATION - File operation blocked on ${h.status} task`,{taskId:e,taskStatus:h.status,path:t,errorMessage:n}),d.incrementCounter(`${u}_blocked_${h.status}_task`,1),new o.ValidationError(n,{taskId:e,taskStatus:h.status,path:t,reason:"task_"+h.status})}let g,
|
|
1887
|
+
throw l.error(`STRICT VALIDATION - File operation blocked on ${h.status} task`,{taskId:e,taskStatus:h.status,path:t,errorMessage:n}),d.incrementCounter(`${u}_blocked_${h.status}_task`,1),new o.ValidationError(n,{taskId:e,taskStatus:h.status,path:t,reason:"task_"+h.status})}let g,f
|
|
1878
1888
|
if(h.requestId)try{if(g=await a.getRequest(h.requestId),l.info("Validating request status for "+h.requestId,{requestId:h.requestId,requestStatus:g.status,taskId:e,path:t}),l.info("STRICT VALIDATION - Request details",{requestId:h.requestId,requestStatus:g.status,requestTitle:g.title,taskId:e,path:t,timestamp:(new Date).toISOString()}),"pending_approval"===g.status||"ready_for_review"===g.status||"completed"===g.status||"canceled"===g.status){const n=r(e,h.requestId,h.status,g.status)
|
|
1879
1889
|
throw l.error(`STRICT VALIDATION - File operation blocked on ${g.status} request`,{taskId:e,requestId:h.requestId,requestStatus:g.status,path:t,errorMessage:n}),d.incrementCounter(`${u}_blocked_${g.status}_request`,1),new o.ValidationError(n,{taskId:e,requestId:h.requestId,requestStatus:g.status,path:t,reason:"request_"+g.status})}}catch(r){if(r instanceof o.ValidationError)throw r
|
|
1880
1890
|
const n=(0,s.getErrorMessage)(r)
|
|
1881
1891
|
l.warn("Could not validate request status for "+h.requestId,{taskId:e,requestId:h.requestId,error:n,path:t}),d.incrementCounter(u+"_request_validation_warning",1)}if(l.info("Work item state validation passed",{taskId:e,taskStatus:h.status,requestId:h.requestId,requestStatus:g?.status,path:t}),h.requestId){const r=c.workspaceManager
|
|
1882
|
-
if("multi-agent"===r?.getCurrentContext().mode)l.debug("Skipping branch switching in multi-agent mode - worktrees handle branch isolation",{taskId:e,requestId:h.requestId,mode:"multi-agent",reason:"worktree_isolation"}),
|
|
1883
|
-
else try{
|
|
1892
|
+
if("multi-agent"===r?.getCurrentContext().mode)l.debug("Skipping branch switching in multi-agent mode - worktrees handle branch isolation",{taskId:e,requestId:h.requestId,mode:"multi-agent",reason:"worktree_isolation"}),f={switched:!1,message:"Branch switching skipped in multi-agent mode (using worktrees)"}
|
|
1893
|
+
else try{f=await(0,i.ensureCorrectBranch)(h.requestId,e,t,c,l,d,u),f.switched&&l.info("Automatically switched to feature branch for file operation",{taskId:e,requestId:h.requestId,branchName:f.branchName,filePath:t})}catch(r){l.warn("Error during automatic branch switching",{taskId:e,requestId:h.requestId,filePath:t,error:(0,s.getErrorMessage)(r)}),f={switched:!1,message:"Branch switching error: "+(0,s.getErrorMessage)(r)}}}return d.incrementCounter(u+"_state_validation_success",1),{task:h,request:g,branchSwitch:f}}catch(r){if(r instanceof o.ValidationError)throw r
|
|
1884
1894
|
const n=(0,s.getErrorMessage)(r)
|
|
1885
|
-
throw l.error("Could not validate work item states for task "+e,{taskId:e,path:t,error:n}),d.incrementCounter(u+"_state_validation_error",1),new o.ValidationError("Could not validate work item states: "+n,{taskId:e,path:t,originalError:r})}},exports.autoPromoteTaskStatus=async function(e,t,r,o,i,a,c,l,d,u){try{let s,h,g=!1,
|
|
1895
|
+
throw l.error("Could not validate work item states for task "+e,{taskId:e,path:t,error:n}),d.incrementCounter(u+"_state_validation_error",1),new o.ValidationError("Could not validate work item states: "+n,{taskId:e,path:t,originalError:r})}},exports.autoPromoteTaskStatus=async function(e,t,r,o,i,a,c,l,d,u){try{let s,h,g=!1,f=!1
|
|
1886
1896
|
if("pending"===t&&(l.info(`Auto-promoting task ${e} from pending to in_progress`,{taskId:e,currentStatus:t,path:i}),await a.updateTaskStatus(e,"in_progress"),l.info(`Successfully auto-promoted task ${e} to in_progress`,{taskId:e,previousStatus:t,newStatus:"in_progress",path:i}),d.incrementCounter(u+"_auto_promotion_success",1),g=!0,s="in_progress",r&&o)){const t=await n(r,o,e,"in_progress",c,l,d,u)
|
|
1887
|
-
|
|
1897
|
+
f=t.promoted,h=t.newStatus}return{taskPromoted:g,newTaskStatus:s,requestPromoted:f,newRequestStatus:h}}catch(r){const n=(0,s.getErrorMessage)(r)
|
|
1888
1898
|
return l.warn(`Failed to auto-promote task ${e} from pending to in_progress`,{taskId:e,currentStatus:t,error:n,path:i}),d.incrementCounter(u+"_auto_promotion_failure",1),{taskPromoted:!1,requestPromoted:!1}}},exports.autoPromoteRequestStatus=n,exports.validateRequestCompletionEligibility=async function(e,t,r,n,i){try{const s=await t.listTasks({requestId:e})
|
|
1889
1899
|
if(r.info("Validating request completion eligibility for "+e,{requestId:e,totalTasks:s.length}),0===s.length){r.warn(`Request ${e} has no tasks - cannot be completed`,{requestId:e})
|
|
1890
1900
|
const t=`Cannot complete request ${e} - no tasks found. Create tasks for this request before attempting completion.`
|
|
@@ -1910,7 +1920,7 @@ d.info("Generating journal for request",{requestId:c})
|
|
|
1910
1920
|
const h=t.projectId
|
|
1911
1921
|
if(!h)throw(0,n.createValidationError)("Project ID is required. Make sure you are in a project context.")
|
|
1912
1922
|
o.setProjectId(h),d.info("Fetching request data, tasks, and file history in parallel")
|
|
1913
|
-
const g=o.getRequestClient(),
|
|
1923
|
+
const g=o.getRequestClient(),f=o.getTaskClient(),p=o.getToolRecordClient(),[m,y,w]=await Promise.all([g.getRequest(c),f.listTasks({requestId:c}),p.getToolRecordsByRequestId(c).catch((e=>(d.warn("Failed to fetch tool records",{error:e+""}),[])))]),k=(0,s.extractDataFromResponse)(m,{logger:d,operationName:"getRequest",throwOnNoData:!0}),b="data"in k?k.data:k,I={id:b.id||c,title:b.title||"Unknown Request",description:b.description||"No description available",status:b.status||"unknown",type:b.type||"unknown",acceptanceCriteria:b.acceptanceCriteria||[],createdAt:b.createdAt||(new Date).toISOString(),updatedAt:b.updatedAt||(new Date).toISOString(),completedAt:b.completedAt},v=(0,s.extractDataFromResponse)(y,{logger:d,operationName:"listTasks",throwOnNoData:!1}),C=(Array.isArray(v)?v:"data"in v?v.data:[]).map((e=>({id:e.id,title:e.title||"Untitled Task",description:e.description||"No description",status:e.status||"unknown",createdAt:e.createdAt||(new Date).toISOString(),completedAt:e.metadata?.completedAt})))
|
|
1914
1924
|
d.info(`Fetched request, ${C.length} tasks, ${w.length} tool records`)
|
|
1915
1925
|
const _=await async function(e){const t=new Map,n=[],o=e.filter((e=>["write-file","replace-in-files","move-files","delete-files","manage-files"].includes(e.type))).sort(((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()))
|
|
1916
1926
|
for(const e of o){const o=r(e),s=e.metadata?.comment||e.metadata?.userComment||"No comment"
|
|
@@ -1944,14 +1954,14 @@ d.info("Successfully acquired request lock",{requestId:h,sessionTag:e,lockedAt:t
|
|
|
1944
1954
|
const r=t instanceof Error?t.message:t+""
|
|
1945
1955
|
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}}}else d.debug("Single-agent mode: skipping request locking",{requestId:h})
|
|
1946
1956
|
d.info("Using unified workspace switching",{requestId:h})
|
|
1947
|
-
const
|
|
1948
|
-
if(!
|
|
1949
|
-
d.warn("Workspace switch failed, attempting to release acquired lock",{requestId:h,sessionTag:e,switchError:
|
|
1957
|
+
const f=await t.workspaceManager.switchToRequest(h,{isCompleted:"completed"===g.status})
|
|
1958
|
+
if(!f.success){if(t.multiAgentMode)try{const{sessionTag:e}=(0,s.getGlobalClientInfo)()
|
|
1959
|
+
d.warn("Workspace switch failed, attempting to release acquired lock",{requestId:h,sessionTag:e,switchError:f.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=f.message||"Unknown error"
|
|
1950
1960
|
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}
|
|
1951
|
-
throw(0,o.createServiceError)(`Failed to switch to request ${h}: ${e}`,{requestId:h,error:e})}const
|
|
1952
|
-
l.recordValue("switch_to_request_branch_time",
|
|
1953
|
-
const m=["Successfully switched to branch: "+(
|
|
1954
|
-
return t.multiAgentMode&&m.push("\u{1f512} **Locked request:** "+h),d.info("Successfully switched to request workspace",{requestId:h,mode:
|
|
1961
|
+
throw(0,o.createServiceError)(`Failed to switch to request ${h}: ${e}`,{requestId:h,error:e})}const p=Date.now()-u
|
|
1962
|
+
l.recordValue("switch_to_request_branch_time",p),l.incrementCounter("switch_to_request_branch_success",1)
|
|
1963
|
+
const m=["Successfully switched to branch: "+(f.newContext?.branchName||"unknown"),"**Previous branch:** "+(f.previousContext?.branchName||"unknown")]
|
|
1964
|
+
return t.multiAgentMode&&m.push("\u{1f512} **Locked request:** "+h),d.info("Successfully switched to request workspace",{requestId:h,mode:f.newContext?.mode,branch:f.newContext?.branchName,duration:p}),{content:[{type:"text",text:m.join("\n")}]}}catch(t){const r=Date.now()-u
|
|
1955
1965
|
if(l.recordValue("switch_to_request_branch_time",r),l.incrementCounter("switch_to_request_branch_error",1),d.error("Failed to switch to request branch",{requestId:e.requestId,error:(0,i.getErrorMessage)(t),duration:r}),t instanceof o.ValidationError||t instanceof o.NotFoundError)return{content:[{type:"text",text:"\u274c "+t.message}],isError:!0}
|
|
1956
1966
|
throw t}}
|
|
1957
1967
|
const n=t(6183),o=t(9860),s=t(5172),i=t(8824)},3217(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.MultiAgentWorkspaceManager=exports.SingleAgentWorkspaceManager=void 0,exports.createWorkspaceManager=function(e,t,o,s,i,a){return t?new n.MultiAgentWorkspaceManager(e,o,s,i,a):new r.SingleAgentWorkspaceManager(e,o,s,i)}
|
|
@@ -2034,7 +2044,7 @@ T.push({type:"file",path:r,fullPath:n,replacements:e.replacements,mode:e.mode||"
|
|
|
2034
2044
|
if(S.length>0&&!t.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
2035
2045
|
for(const e of S)M.push({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode||"unique"})
|
|
2036
2046
|
if(M.length>0&&t.apiClient){const e=M.map((e=>e.documentId))
|
|
2037
|
-
try{await(0,
|
|
2047
|
+
try{await(0,p.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}
|
|
2038
2048
|
throw e}}I=u.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("replace_strings_phase",1,{phase:I})
|
|
2039
2049
|
const R=T.length>0?T[0].path:"document-operation",P=await u.validateTaskId(C,R,r,y,a,v.metricsPrefix),x=P?.requestId
|
|
2040
2050
|
let O=null
|
|
@@ -2047,9 +2057,9 @@ throw Error($.error)}if(T.length>0){y.debug("Re-validating file paths with corre
|
|
|
2047
2057
|
for(let e=0;e<T.length;e++){const r=T[e],n=q[e],{normalizedPath:o,fullPath:s}=u.validateAndNormalizePath(n.path,t)
|
|
2048
2058
|
T[e]={...r,path:o,fullPath:s}}}if(M.length>0&&x)try{await(0,g.validateRequestStatusForDocumentOperation)(x,s,y,a,"replace-strings-document")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2049
2059
|
throw e}I=u.FileOperationPhase.RECORD_CREATION,a.incrementCounter("replace_strings_phase",1,{phase:I})
|
|
2050
|
-
const
|
|
2051
|
-
if(k=
|
|
2052
|
-
const e=await(0,
|
|
2060
|
+
const D=[...T.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:A}=await u.createFileOperationRecords(C,x,t.projectId,v.recordType,R,{operationCount:_.length,fileOperations:T.length,documentOperations:M.length,operations:D,userComment:E},r,o,y,a,v.metricsPrefix,c)
|
|
2061
|
+
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")
|
|
2062
|
+
const e=await(0,f.commitUserChangesBeforeToolOperation)(t.git,"replace-strings",{requestId:x,taskId:C,workspaceManager:t.workspaceManager},y,a)
|
|
2053
2063
|
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})
|
|
2054
2064
|
const F=[]
|
|
2055
2065
|
let N=0,L=0
|
|
@@ -2061,18 +2071,18 @@ try{const o=await t.documentFileManager.getDocumentAsFile(e.documentId),s=t.docu
|
|
|
2061
2071
|
r.filename=s?.filename
|
|
2062
2072
|
const i=await l.default.readFile(o,"utf8"),{newContent:a,results:c}=await n(i,e.replacements,e.mode)
|
|
2063
2073
|
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(M.length>0)try{for(const e of M){const r=F.find((t=>t.documentId===e.documentId))
|
|
2064
|
-
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),B=u.processMultiFileOperationResults(F,"successfulReplacements"),{successfulOperations:H,failedOperations:
|
|
2065
|
-
try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+M[0]?.documentId,status:G?"completed":"failed",error:G?void 0:
|
|
2074
|
+
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),B=u.processMultiFileOperationResults(F,"successfulReplacements"),{successfulOperations:H,failedOperations:W,totalSuccessfulChanges:U,overallSuccess:G,successfulFiles:V,failedFiles:J}=B
|
|
2075
|
+
try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+M[0]?.documentId,status:G?"completed":"failed",error:G?void 0:W+" operations failed",totalOperations:F.length,successfulFiles:V,failedFiles:J,operations:D,totalSuccessfulReplacements:U,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:G?`String replacement completed: ${H}/${F.length} operations successful${T.length>0?" (committed to git)":""}`:`String replacement partially failed: ${W}/${F.length} operations failed`})}catch(e){y.warn("Failed to update tool record",{recordError:e})}u.formatMultiFileToolResponse("String Replacement",{successfulOperations:H,failedOperations:W,totalSuccessfulChanges:U,overallSuccess:G,successfulFiles:V,failedFiles:J},z,$)
|
|
2066
2076
|
let K="## String Replacement Results\n\n"
|
|
2067
|
-
if(t.workspaceManager&&(K+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),K+="**Summary:**\n",K+=`- **Files processed:** ${H+
|
|
2077
|
+
if(t.workspaceManager&&(K+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),K+="**Summary:**\n",K+=`- **Files processed:** ${H+W}\n`,K+=`- **Successful operations:** ${H}\n`,K+=`- **Failed operations:** ${W}\n`,K+=`- **Total replacements:** ${U} 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"),$.lockAcquired&&$.lockedRequestId&&(K+=`\u{1f512} **Locked request:** ${$.lockedRequestId}\n\n`),1===F.length){const e=F[0]
|
|
2068
2078
|
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"
|
|
2069
|
-
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:** ${H}\n`,K+=`- **Failed:** ${
|
|
2079
|
+
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:** ${H}\n`,K+=`- **Failed:** ${W}\n`,K+=`- **Total Replacements:** ${U} successful, ${N} failed\n\n`,K+="**Detailed Results:**\n\n"
|
|
2070
2080
|
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"
|
|
2071
2081
|
for(const t of e.replacements.filter((e=>!e.success)))K+=` - "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}K+="\n"}}M.length>0&&(K+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
2072
2082
|
const Y=Date.now()-w
|
|
2073
|
-
return y.info("Replace strings operation completed",{duration:Y,success:G,totalOperations:F.length,successfulOperations:H,failedOperations:
|
|
2083
|
+
return y.info("Replace strings operation completed",{duration:Y,success:G,totalOperations:F.length,successfulOperations:H,failedOperations:W}),a.incrementCounter("replace_strings_total",1,{success:G}),{content:[{type:"text",text:K}],isError:!G}}catch(t){const r=Date.now()-w
|
|
2074
2084
|
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}}}
|
|
2075
|
-
const l=c(t(1943)),d=t(6183),u=a(t(5967)),h=t(9860),g=t(5003),
|
|
2085
|
+
const l=c(t(1943)),d=t(6183),u=a(t(5967)),h=t(9860),g=t(5003),f=t(7478),p=t(9949),m=t(8824)},3322(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
2076
2086
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
2077
2087
|
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=[]
|
|
2078
2088
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -2106,10 +2116,10 @@ var h=t(4192)
|
|
|
2106
2116
|
Object.defineProperty(exports,"BaseApiClient",{enumerable:!0,get(){return h.BaseApiClient}})
|
|
2107
2117
|
var g=t(1599)
|
|
2108
2118
|
Object.defineProperty(exports,"SessionRequestAssociationClient",{enumerable:!0,get(){return g.SessionRequestAssociationClient}})
|
|
2109
|
-
var
|
|
2110
|
-
Object.defineProperty(exports,"SessionTagMappingClient",{enumerable:!0,get(){return
|
|
2111
|
-
var
|
|
2112
|
-
Object.defineProperty(exports,"CLISessionClient",{enumerable:!0,get(){return
|
|
2119
|
+
var f=t(4465)
|
|
2120
|
+
Object.defineProperty(exports,"SessionTagMappingClient",{enumerable:!0,get(){return f.SessionTagMappingClient}})
|
|
2121
|
+
var p=t(5187)
|
|
2122
|
+
Object.defineProperty(exports,"CLISessionClient",{enumerable:!0,get(){return p.CLISessionClient}})
|
|
2113
2123
|
var m=t(6539)
|
|
2114
2124
|
Object.defineProperty(exports,"ClientFactory",{enumerable:!0,get(){return m.ClientFactory}})
|
|
2115
2125
|
const y=t(6539)
|
|
@@ -2134,12 +2144,12 @@ const n=e
|
|
|
2134
2144
|
"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()}
|
|
2135
2145
|
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
|
|
2136
2146
|
if(h.requestId)try{const e=i.getRequestClient()
|
|
2137
|
-
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
|
|
2147
|
+
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 f=e=>{if(!e)return"Unknown date"
|
|
2138
2148
|
try{const t=new Date(e)
|
|
2139
|
-
return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return l.warn("Invalid date format: "+e),"Unknown date"}},f
|
|
2149
|
+
return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return l.warn("Invalid date format: "+e),"Unknown date"}},p=f(h.createdAt),m=f(h.updatedAt)
|
|
2140
2150
|
let y=`# Task: ${h.title} (${r})\n\n`
|
|
2141
|
-
if(y+=`**Status**: ${h.status}\n`,y+=`**Created**: ${
|
|
2142
|
-
y+="\n## Metadata\n\n",e.lastCommit&&(y+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(y+=`**Completed At**: ${
|
|
2151
|
+
if(y+=`**Status**: ${h.status}\n`,y+=`**Created**: ${p}\n`,y+=`**Updated**: ${m}\n`,h.requestId&&(y+="**Parent Request**: "+h.requestId,y+=g?` (${g.title})\n`:"\n"),h.metadata){const e=h.metadata
|
|
2152
|
+
y+="\n## Metadata\n\n",e.lastCommit&&(y+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(y+=`**Completed At**: ${f(e.completedAt)}\n`),e.completionSummary&&(y+=`**Completion Summary**: ${e.completionSummary}\n`)
|
|
2143
2153
|
const t=["lastCommit","completedAt","completionSummary"]
|
|
2144
2154
|
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})
|
|
2145
2155
|
try{const o=i.getToolRecordClient()
|
|
@@ -2155,31 +2165,7 @@ exports.defaultLogger=o.default
|
|
|
2155
2165
|
const s=t(6540)
|
|
2156
2166
|
Object.defineProperty(exports,"LogLevel",{enumerable:!0,get(){return s.LogLevel}}),exports.default=o.default},3556(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
2157
2167
|
const r=t(6183),n=t(8317)
|
|
2158
|
-
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)}}},
|
|
2159
|
-
try{const{requestId:n}=e
|
|
2160
|
-
if(!n)throw(0,r.createValidationError)("Request ID is required")
|
|
2161
|
-
let o,c
|
|
2162
|
-
d.info("Starting request finalization",{requestId:n})
|
|
2163
|
-
try{const e=await a.proxyPost(`/api/projects/${t.projectId}/requests/${n}/validate-completion`,{})
|
|
2164
|
-
o=e?.data||e}catch(e){const t=(0,i.getErrorMessage)(e)
|
|
2165
|
-
return d.error("Server validation failed",{requestId:n,error:t}),u({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate finalization: "+t}],isError:!0}}if(!o.canComplete){let e=`Cannot finalize request ${n}: ${o.reason}\n`
|
|
2166
|
-
return o.blockedByTasks?.length&&(e+="\n**Tasks that must be completed first:**\n",o.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (${t.status})\n`}))),u({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}if(!t.workspaceManager)throw Error("WorkspaceManager not available for request finalization")
|
|
2167
|
-
let l="workspace-manager"
|
|
2168
|
-
try{const e=a.getRequestClient(),r=await e.getRequest(n),o=r?.title||"Request "+n
|
|
2169
|
-
if("conflicted"===r?.status){d.info("Request is conflicted, attempting fast-path merge",{requestId:n})
|
|
2170
|
-
const e=t.workspaceManager.getCurrentContext()
|
|
2171
|
-
let r=e?.basePath||process.cwd()
|
|
2172
|
-
if("multi-agent"===e?.mode)try{const e=await t.workspaceManager.getWorktreeInfo(n)
|
|
2173
|
-
e?.worktreePath&&(r=e.worktreePath)}catch{}const i=(0,s.createConflictResolutionManager)(d,a,r,t.git),h=await i.validateMarkersRemoved(n)
|
|
2174
|
-
if(!h.resolved)return u({success:!1,reason:"conflicts_unresolved"}),{content:[{type:"text",text:`## \u26a0\ufe0f Conflicts Still Need Resolution\n\nConflict markers still exist in:\n\n${h.remainingConflicts.map((e=>`- \`${e}\``)).join("\n")}\n\nRemove all conflict markers and try again.`}]}
|
|
2175
|
-
const g=await i.hasMainBranchChanged(n)
|
|
2176
|
-
g.hasChanged&&g.canDetermine?(d.info("Main branch changed since conflict detection, using full merge",{requestId:n,originalHash:g.originalHash?.substring(0,8),currentHash:g.currentHash?.substring(0,8)}),c=await t.workspaceManager.completeRequest(n,o),l=c.autoMergeInfo?.strategy||"main-changed-remerge"):(c=await t.workspaceManager.completeRequest(n,o,{skipConflictDetection:!0}),l="conflict-fast-path",d.info("Conflict fast-path merge completed",{requestId:n,mergeCommitHash:c.mergeCommitHash}))}else c=await t.workspaceManager.completeRequest(n,o),l=c.autoMergeInfo?.strategy||"workspace-manager",d.info("Merge completed",{requestId:n,mergeCommitHash:c.mergeCommitHash,cleanedUp:c.cleanedUp})}catch(e){if(e.conflictInfo){const r=e.conflictInfo,n=r.workingDirectory||t.workspaceManager?.getCurrentContext()?.basePath||process.cwd(),o=(0,s.createConflictResolutionManager)(d,a,n,t.git),i=await o.handleConflicts(r)
|
|
2177
|
-
return u({success:!1,reason:"merge_conflicts"}),{content:[{type:"text",text:i.userMessage}],isError:!1}}const r=(0,i.getErrorMessage)(e)
|
|
2178
|
-
return u({success:!1,error:"merge_failure"}),{content:[{type:"text",text:"Request finalization failed during merge: "+r}],isError:!0}}try{await a.proxyPost(`/api/projects/${t.projectId}/requests/${n}/finalize-completion`,{summary:"Finalized request "+n,acceptanceEvidence:[{evidence:"Finalized after review"}],mergeResult:{mergeCommitHash:c.mergeCommitHash,mergedFiles:c.mergedFiles,cleanedUp:c.cleanedUp,method:l}})}catch(e){const t=(0,i.getErrorMessage)(e)
|
|
2179
|
-
return d.error("CRITICAL: Merge succeeded but server finalization failed",{requestId:n,mergeCommitHash:c.mergeCommitHash,error:t}),u({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 state: ${t}`}],isError:!0}}return u({success:!0}),{content:[{type:"text",text:"Request finalized: "+n}]}}catch(r){let s="An unexpected error occurred"
|
|
2180
|
-
r instanceof n.ZodError?s=r.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", "):r instanceof Error&&(s=r.message),d.error("Finalize request failed",{error:s})
|
|
2181
|
-
try{await(0,o.createFailureToolRecord)("complete-request",r,{error:s,requestId:e?.requestId},a.getToolRecordClient(),d,l,{requestId:e?.requestId,projectId:t.projectId,note:"Failed to finalize request"})}catch{}return u({success:!1,error:r instanceof Error?r.name:"unknown"}),{content:[{type:"text",text:"Error: "+s}],isError:!0}}}
|
|
2182
|
-
const r=t(9860),n=t(1569),o=t(8616),s=t(1651),i=t(8824)},3626(e,exports,t){function r(e){if(!e)return!1
|
|
2168
|
+
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)}}},3626(e,exports,t){function r(e){if(!e)return!1
|
|
2183
2169
|
const t=e.toLowerCase().replace(/^\./,"")
|
|
2184
2170
|
return u.has(t)}function n(e,t){if(r(t)){const t=e.match(/^([ \t]*)(.*?)\s*$/)
|
|
2185
2171
|
if(!t)return e
|
|
@@ -2218,30 +2204,30 @@ if(i.length>h)break
|
|
|
2218
2204
|
if(i===l){c.push({line:s+1,actuallyMatched:o,matchType:"whitespace_normalized",startPos:r,endPos:t})
|
|
2219
2205
|
break}}}o+=i.length+1}return c}const g=t.trim()[0]
|
|
2220
2206
|
if(!g)return c
|
|
2221
|
-
let
|
|
2222
|
-
for(;;){if(
|
|
2223
|
-
throw Error(`Fuzzy matching timed out after ${r}ms (limit: ${o}ms).\nPattern length: ${t.length} chars, Content length: ${e.length} chars.\nSuggestions:\n 1. Ensure whitespace in pattern matches file exactly (use exact match)\n 2. Break down large replacements into smaller chunks\n 3. Use a text editor to verify the exact text including hidden characters`)}
|
|
2224
|
-
const r=e.indexOf(g,
|
|
2207
|
+
let f=0,p=0
|
|
2208
|
+
for(;;){if(p%100==0&&Date.now()-d>o){const r=Date.now()-d
|
|
2209
|
+
throw Error(`Fuzzy matching timed out after ${r}ms (limit: ${o}ms).\nPattern length: ${t.length} chars, Content length: ${e.length} chars.\nSuggestions:\n 1. Ensure whitespace in pattern matches file exactly (use exact match)\n 2. Break down large replacements into smaller chunks\n 3. Use a text editor to verify the exact text including hidden characters`)}p++
|
|
2210
|
+
const r=e.indexOf(g,f)
|
|
2225
2211
|
if(-1===r)break
|
|
2226
2212
|
let i=r+t.length
|
|
2227
2213
|
const u=Math.min(Math.floor(.5*t.length),200),h=Math.min(r+t.length+u,e.length),m=l.length
|
|
2228
2214
|
let y=!1
|
|
2229
2215
|
for(let t=i;h>=t;t++){const o=e.substring(r,t),i=n(o,a)
|
|
2230
2216
|
if(i.length>m)break
|
|
2231
|
-
if(i===l){c.push({line:s(e,r),actuallyMatched:o,matchType:"whitespace_normalized",startPos:r,endPos:t}),
|
|
2232
|
-
break}}y||(
|
|
2217
|
+
if(i===l){c.push({line:s(e,r),actuallyMatched:o,matchType:"whitespace_normalized",startPos:r,endPos:t}),f=t,y=!0
|
|
2218
|
+
break}}y||(f=r+1)}return c}(e,t,c,u),h.length>0)return h}catch(e){if(e instanceof Error&&e.message.includes("timed out"))throw e}return h=function(e,t,n=100,a){if(r(a))return[]
|
|
2233
2219
|
const c=[],l=o(t),d=Date.now()
|
|
2234
2220
|
if(t.length>500)return i(e,t)
|
|
2235
2221
|
if(!l)return c
|
|
2236
2222
|
const u=t.replace(/\s/g,"")[0],h=l.length
|
|
2237
|
-
let g=0,
|
|
2238
|
-
for(;;){if(
|
|
2239
|
-
throw Error(`Fuzzy matching timed out after ${r}ms (limit: ${n}ms).\nPattern length: ${t.length} chars, Content length: ${e.length} chars.\nSuggestions:\n 1. Ensure whitespace in pattern matches file exactly (use exact match)\n 2. Break down large replacements into smaller chunks\n 3. Use a text editor to verify the exact text including hidden characters`)}
|
|
2223
|
+
let g=0,f=0
|
|
2224
|
+
for(;;){if(f%100==0&&Date.now()-d>n){const r=Date.now()-d
|
|
2225
|
+
throw Error(`Fuzzy matching timed out after ${r}ms (limit: ${n}ms).\nPattern length: ${t.length} chars, Content length: ${e.length} chars.\nSuggestions:\n 1. Ensure whitespace in pattern matches file exactly (use exact match)\n 2. Break down large replacements into smaller chunks\n 3. Use a text editor to verify the exact text including hidden characters`)}f++
|
|
2240
2226
|
const r=e.indexOf(u,g)
|
|
2241
2227
|
if(-1===r)break
|
|
2242
|
-
const i=r+h,a=Math.min(t.length,300),
|
|
2228
|
+
const i=r+h,a=Math.min(t.length,300),p=Math.min(r+h+a,e.length)
|
|
2243
2229
|
let m=!1
|
|
2244
|
-
for(let t=i;
|
|
2230
|
+
for(let t=i;p>=t;t++){const n=e.substring(r,t),i=o(n)
|
|
2245
2231
|
if(i.length>h)break
|
|
2246
2232
|
if(i===l){c.push({line:s(e,r),actuallyMatched:n,matchType:"whitespace_agnostic",startPos:r,endPos:t}),g=t,m=!0
|
|
2247
2233
|
break}}m||(g=r+1)}return c}(e,t,c,u),h},exports.replaceMatch=a,exports.replaceMatches=function(e,t,r){const n=[...t].sort(((e,t)=>t.startPos-e.startPos))
|
|
@@ -2268,45 +2254,45 @@ let i=u.FileOperationPhase.VALIDATION
|
|
|
2268
2254
|
const a={toolName:"get-file-info",operationName:"read",fileOperationPhase:u.FileOperationPhase.FILE_WRITE,recordType:"write",metricsPrefix:"get_file_info",successMessage:"Successfully retrieved info for {path}",failureMessage:"Failed to retrieve info for {path}"}
|
|
2269
2255
|
try{const a=u.validateArgs(e,d.GetFileInfoSchema),{path:h}=a
|
|
2270
2256
|
n.info("Getting file info: "+h)
|
|
2271
|
-
const{normalizedPath:
|
|
2257
|
+
const{normalizedPath:p,fullPath:m}=u.validateAndNormalizePath(h,t)
|
|
2272
2258
|
i=u.FileOperationPhase.FILE_WRITE
|
|
2273
|
-
try{await c.default.access(m)}catch(e){throw Error("Path not accessible: "+h)}const y=await c.default.stat(m),w=y.isFile()?l.default.extname(m).slice(1):"",k={path:
|
|
2259
|
+
try{await c.default.access(m)}catch(e){throw Error("Path not accessible: "+h)}const y=await c.default.stat(m),w=y.isFile()?l.default.extname(m).slice(1):"",k={path:p,type:y.isDirectory()?"directory":"file",size:y.size,sizeFormatted:(f=y.size,u.formatFileSize(f)),created:r(y.birthtime),modified:r(y.mtime),accessed:r(y.atime),permissions:(g=y.mode,(511&g).toString(8)),isDirectory:y.isDirectory(),isFile:y.isFile(),isSymbolicLink:y.isSymbolicLink(),extension:w},b=["File Information for: "+p,"Type: "+k.type,`Size: ${k.sizeFormatted} (${k.size} bytes)`,"Created: "+k.created,"Modified: "+k.modified,"Accessed: "+k.accessed,"Permissions: "+k.permissions,"Is Directory: "+k.isDirectory,"Is File: "+k.isFile,"Is Symbolic Link: "+k.isSymbolicLink]
|
|
2274
2260
|
k.isFile&&w&&b.push("Extension: "+w)
|
|
2275
2261
|
const I=Date.now()-s
|
|
2276
|
-
return o.recordValue("get_file_info_time",I),o.incrementCounter("get_file_info_success",1),n.info("Successfully retrieved file info: "+
|
|
2277
|
-
return o.recordValue("get_file_info_time",r),o.incrementCounter("get_file_info_errors",1),n.error("Error getting file info:",{error:(0,h.getErrorMessage)(t),time:r}),u.handleFileOperationError(t,i,n,o,e,a)}var g,
|
|
2278
|
-
const c=a(t(1943)),l=a(t(6928)),d=t(6183),u=i(t(5967)),h=t(8824)},3707(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQuickChange=async function(e,t,d,u,h,g,
|
|
2262
|
+
return o.recordValue("get_file_info_time",I),o.incrementCounter("get_file_info_success",1),n.info("Successfully retrieved file info: "+p,{type:k.type,size:k.size,time:I}),{content:[{type:"text",text:b.join("\n")}]}}catch(t){const r=Date.now()-s
|
|
2263
|
+
return o.recordValue("get_file_info_time",r),o.incrementCounter("get_file_info_errors",1),n.error("Error getting file info:",{error:(0,h.getErrorMessage)(t),time:r}),u.handleFileOperationError(t,i,n,o,e,a)}var g,f}
|
|
2264
|
+
const c=a(t(1943)),l=a(t(6928)),d=t(6183),u=i(t(5967)),h=t(8824)},3707(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQuickChange=async function(e,t,d,u,h,g,f){const p=h.child({tool:"quick_edit"}),m=Date.now()
|
|
2279
2265
|
try{const y=u.getRequestClient(),w=u.getTaskClient(),k=u.getFileClient(),b=u.getToolRecordClient(),{title:I,description:v,...C}=e,_=e.comment||I
|
|
2280
|
-
|
|
2266
|
+
p.info("Starting quick_edit workflow",{title:I,operationType:t})
|
|
2281
2267
|
let E=!1
|
|
2282
2268
|
try{const e=await y.listRequests({limit:2,sortBy:"created_at",sortDirection:"desc"})
|
|
2283
|
-
e&&2===e.length&&e.every((e=>"quick-edit"===e.type))&&(E=!0,
|
|
2269
|
+
e&&2===e.length&&e.every((e=>"quick-edit"===e.type))&&(E=!0,p.info("Detected two consecutive quick-edits, will recommend normal request"))}catch(e){p.warn("Could not check recent requests for recommendation",{error:e})}p.debug("Creating quick_edit request")
|
|
2284
2270
|
const q=await y.createRequest({title:I,description:v,type:"quick-edit",acceptanceCriteria:["Quick change completed successfully"]})
|
|
2285
2271
|
if(!q||!q.id)throw Error("Failed to create request")
|
|
2286
2272
|
const S=q.id
|
|
2287
2273
|
let T
|
|
2288
|
-
|
|
2289
|
-
try{if(
|
|
2290
|
-
e.userChangesCommitted?
|
|
2291
|
-
|
|
2274
|
+
p.info("Created request",{requestId:S})
|
|
2275
|
+
try{if(p.debug("Checking for uncommitted user changes before quick-edit branch creation"),d.git)try{const e=await(0,c.commitUserChangesBeforeToolOperation)(d.git,"quick-fix",{requestId:S,taskId:void 0,workspaceManager:d.workspaceManager},h,g)
|
|
2276
|
+
e.userChangesCommitted?p.info("Committed user changes to main before quick-edit branch creation",{requestId:S,commitHash:e.commitHash?.substring(0,8)}):p.debug("No uncommitted changes found, proceeding with quick-edit")}catch(e){p.warn("Failed to commit user changes before quick-edit, proceeding anyway",{requestId:S,error:e instanceof Error?e.message:e+""})}else p.debug("No git instance available, skipping uncommitted changes check")
|
|
2277
|
+
p.debug("Creating task")
|
|
2292
2278
|
const e=await w.createTask({requestId:S,projectId:d.projectId,title:`Execute ${t} operation`,description:"Quick change: "+I})
|
|
2293
2279
|
if(!e||!e.id)throw Error("Failed to create task")
|
|
2294
2280
|
let l
|
|
2295
|
-
if(T=e.id,
|
|
2296
|
-
else if("replace"===t)l=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,b,y,h,g,
|
|
2281
|
+
if(T=e.id,p.info("Created task",{taskId:T}),p.debug("Executing file operation",{operationType:t}),"write"===t)l=await(0,n.handleWriteFile)({taskId:T,...C,comment:_},d,k,w,b,y,h,g,f)
|
|
2282
|
+
else if("replace"===t)l=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,b,y,h,g,f)
|
|
2297
2283
|
else{if("manage"!==t)throw new r.ValidationError("Unsupported operation type: "+t)
|
|
2298
|
-
l=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||I},d,w,b,y,u,h,g,
|
|
2299
|
-
try{await w.updateTaskStatus(T,"canceled"),
|
|
2300
|
-
q?
|
|
2301
|
-
try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${I}${q?" (partial success)":""}`},d,u,h,g),
|
|
2302
|
-
try{await w.updateTaskStatus(T,"completed"),
|
|
2284
|
+
l=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||I},d,w,b,y,u,h,g,f)}if(l.isError){p.error("File operation failed, cleaning up request and task",{requestId:S,taskId:T})
|
|
2285
|
+
try{await w.updateTaskStatus(T,"canceled"),p.info("Canceled task after operation failure",{taskId:T})}catch(e){p.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),p.info("Canceled request after operation failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),p.info("Cleaned up branch/worktree after operation failure",{requestId:S}))}catch(e){p.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}return{content:[{type:"text",text:`\u274c Quick change failed during ${t} operation:\n\n${l.content[0].text}\n\nThe request (${S}) and task have been canceled and cleaned up.`}],isError:!0}}const v=l.content[0].text,q=v.includes("\u26a0\ufe0f Partial Success")||v.includes("\u274c Failed")||v.includes("\u274c 0 successful")
|
|
2286
|
+
q?p.warn("File operation completed with partial failures",{requestId:S}):p.info("File operation completed successfully"),p.debug("Completing task")
|
|
2287
|
+
try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${I}${q?" (partial success)":""}`},d,u,h,g),p.info("Task completed successfully",{taskId:T})}catch(e){p.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})
|
|
2288
|
+
try{await w.updateTaskStatus(T,"completed"),p.info("Task completed via direct updateTaskStatus call",{taskId:T})}catch(e){return p.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}}}p.debug("Completing request")
|
|
2303
2289
|
const M=q?`Quick change completed with partial success: ${I}. Some replacements failed - see details below.`:"Quick change completed: "+I,R=q?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
|
|
2304
2290
|
let P=!1
|
|
2305
|
-
try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:M,acceptanceEvidence:[{evidence:R}],testVerification:void 0},d,u,h,g,
|
|
2306
|
-
e.isError?
|
|
2291
|
+
try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:M,acceptanceEvidence:[{evidence:R}],testVerification:void 0},d,u,h,g,f)
|
|
2292
|
+
e.isError?p.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text}):(P=!0,p.info("Request completed successfully via handleCompleteRequest",{requestId:S}))}catch(e){p.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!P)try{p.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:M}),P=!0,p.info("Request completed successfully via direct API call",{requestId:S})}catch(e){return p.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
|
|
2307
2293
|
let O
|
|
2308
|
-
return
|
|
2309
|
-
return
|
|
2294
|
+
return p.info("Quick fix completed",{requestId:S,duration:x,hasPartialFailure:q}),O=q?`\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`+v:`\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`+(v.match(/\[RECORD:trec\d{6}\]/)?.[0]?"\n"+v.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(p.error("Quick change workflow failed after request creation, cleaning up",{requestId:S,error:(0,l.getErrorMessage)(e)}),T)try{await w.updateTaskStatus(T,"canceled"),p.info("Canceled task after workflow failure",{taskId:T})}catch(e){p.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),p.info("Canceled request after workflow failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),p.info("Cleaned up branch/worktree after workflow failure",{requestId:S}))}catch(e){p.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
|
|
2295
|
+
return p.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}}}
|
|
2310
2296
|
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){module.exports=require("simple-git")},3895(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.AuthenticationManager=void 0
|
|
2311
2297
|
const r=t(6848)
|
|
2312
2298
|
exports.AuthenticationManager=class{constructor(e,t,n){this.cachedToken=null,this.tokenRefreshPromise=null,this.tokenManager=e,this.logger=t.child({component:"auth-manager"}),this.tokenSynchronizer=n||new r.ClientTokenSynchronizer(t)}async setToken(e){try{this.logger.info("Storing authentication token",{username:e.username,expiresAt:e.expiresAt,userId:e.userId}),await this.tokenManager.storeToken(e),this.cachedToken=e,this.tokenSynchronizer.updateToken(e.token),this.logger.info("Authentication token stored and synchronized to all clients")}catch(e){throw this.logger.error("Failed to store authentication token",{error:e instanceof Error?e.stack:e+""}),Error("Failed to store authentication token")}}async setTokenString(e){try{this.logger.info("Setting token string directly")
|
|
@@ -2368,47 +2354,47 @@ return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModu
|
|
|
2368
2354
|
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()
|
|
2369
2355
|
let I,v,C=d.FileOperationPhase.VALIDATION
|
|
2370
2356
|
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"}
|
|
2371
|
-
try{const r=d.validateArgs(e,l.WriteFileSchema),{taskId:i,path:
|
|
2372
|
-
w.info("Writing content to "+(R?"document":"file"),{taskId:i,filePath:P?
|
|
2373
|
-
let x,O,j,$="",
|
|
2374
|
-
const F=P?
|
|
2375
|
-
if(R){if(t.apiClient)try{await(0,
|
|
2357
|
+
try{const r=d.validateArgs(e,l.WriteFileSchema),{taskId:i,path:p,documentId:E,content:q,format:S,append:T,comment:M}=r,R=!!E,P=!!p
|
|
2358
|
+
w.info("Writing content to "+(R?"document":"file"),{taskId:i,filePath:P?p:void 0,documentId:R?E:void 0,contentLength:"string"==typeof q?q.length:JSON.stringify(q).length,format:S,append:T,comment:M})
|
|
2359
|
+
let x,O,j,$="",D=!1,A=!1
|
|
2360
|
+
const F=P?p:void 0
|
|
2361
|
+
if(R){if(t.apiClient)try{await(0,f.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}
|
|
2376
2362
|
throw e}if(!t.documentFileManager)throw Error("Document file manager not available")
|
|
2377
2363
|
$=await t.documentFileManager.getDocumentAsFile(E)
|
|
2378
2364
|
const e=t.documentFileManager.getCachedDocumentInfo(E)
|
|
2379
|
-
j=e?.filename,
|
|
2365
|
+
j=e?.filename,A=!0,D=!1}C=d.FileOperationPhase.TASK_VALIDATION,m.incrementCounter("write_file_phase",1,{phase:C})
|
|
2380
2366
|
const N=P?F:"document:"+E,L=await d.validateTaskId(i,N,n,w,m,_.metricsPrefix),z=L?.requestId
|
|
2381
2367
|
let B=null
|
|
2382
2368
|
P&&z&&(B=await d.validateWorkItemStates(i,N,n,s,t,w,m,_.metricsPrefix))
|
|
2383
2369
|
let H={taskPromoted:!1,requestPromoted:!1}
|
|
2384
2370
|
P&&z&&B&&(H=await d.autoPromoteTaskStatus(i,L.status,z,B.request?.status,N,n,s,w,m,_.metricsPrefix),H.taskPromoted&&w.info("Auto-promoted task to in_progress for file operation",{taskId:i,requestId:z,previousStatus:L.status,newStatus:H.newTaskStatus,triggeringOperation:"write_file"}))
|
|
2385
|
-
const
|
|
2386
|
-
if(!
|
|
2387
|
-
throw Error(
|
|
2371
|
+
const W=await d.ensureCorrectWorkspaceContext({taskPromoted:H.taskPromoted,requestId:z,context:t,operation:"write_file",logger:w,metrics:m,metricsPrefix:_.metricsPrefix,requireRequestContext:P})
|
|
2372
|
+
if(!W.success){if(W.isLockConflict)return{content:[{type:"text",text:"\u274c "+W.error}],isError:!0}
|
|
2373
|
+
throw Error(W.error)}if(W.switched&&w.info("Workspace context successfully established",{requestId:z,branchName:W.branchName,operation:"write_file"}),P&&F){const e=d.validateAndNormalizePath(F,t)
|
|
2388
2374
|
x=e.normalizedPath,O=e.fullPath,$=O
|
|
2389
|
-
try{await c.default.access(O),
|
|
2375
|
+
try{await c.default.access(O),A=!0}catch{A=!1,D=!0}w.debug("Path validated with correct workspace context",{rawPath:F,normalizedPath:x,fullPath:O,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})}if(R&&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}
|
|
2390
2376
|
throw e}C=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("write_file_phase",1,{phase:C})
|
|
2391
|
-
const{toolRecordId:
|
|
2377
|
+
const{toolRecordId:U}=await d.createFileOperationRecords(i,z,t.projectId,_.recordType,N,{operationType:R?"document":"file",documentId:R?E:void 0,documentFilename:j,filePath:P?x:void 0,contentLength:"string"==typeof q?q.length:JSON.stringify(q).length,format:S||"text",append:T||!1,wasFileCreated:!A,userComment:M},n,o,w,m,_.metricsPrefix,y)
|
|
2392
2378
|
let G
|
|
2393
|
-
if(I=
|
|
2379
|
+
if(I=U,v=U,C=_.fileOperationPhase,m.incrementCounter("write_file_phase",1,{phase:C}),"json"===S)if("string"==typeof q)try{JSON.parse(q),G=q}catch(e){throw new u.ValidationError("Content is not valid JSON")}else G=JSON.stringify(q,null,2)
|
|
2394
2380
|
else G="string"==typeof q?q:JSON.stringify(q,null,2)
|
|
2395
2381
|
let V=G
|
|
2396
2382
|
if(P&&t.git)try{w.debug("[WRITE-FILE] Checking for user changes before write operation")
|
|
2397
2383
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"write_file",{requestId:t.workspaceManager?.getCurrentContext()?.requestId,taskId:i},w,m)
|
|
2398
2384
|
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:x,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:x,error:e instanceof Error?e.message:e+""})}if(!$)throw Error("Target path not properly initialized")
|
|
2399
|
-
if(w.debug("[WRITE-FILE] Proceeding with file write operation",{targetPath:$}),T&&
|
|
2400
|
-
if(await c.default.mkdir(J,{recursive:!0}),await c.default.writeFile($,V,"utf8"),w.info("Content written successfully",{path:P?x:"document:"+E,finalLength:V.length,append:T,wasCreated:
|
|
2385
|
+
if(w.debug("[WRITE-FILE] Proceeding with file write operation",{targetPath:$}),T&&A)try{V=await c.default.readFile($,"utf8")+G}catch(e){w.warn("Failed to read existing content for append",{error:e})}const J=a.default.dirname($)
|
|
2386
|
+
if(await c.default.mkdir(J,{recursive:!0}),await c.default.writeFile($,V,"utf8"),w.info("Content written successfully",{path:P?x:"document:"+E,finalLength:V.length,append:T,wasCreated:D}),R){t.documentFileManager.markForSync(E)
|
|
2401
2387
|
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
|
|
2402
2388
|
if(P){if(C=d.FileOperationPhase.GIT_COMMIT,m.incrementCounter("write_file_phase",1,{phase:C}),t.workspaceManager){const e=t.workspaceManager.getCurrentContext()
|
|
2403
|
-
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=`${
|
|
2404
|
-
K=r.commitHash,Q=r.previousCommitHash,w.info("Changes committed to git via shared utility",{path:x,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:P?x:"document:"+E,status:"completed",finalContentLength:V.length,wasFileCreated:
|
|
2405
|
-
Z+=`**Content Length:** ${V.length} characters\n`,P&&Y&&(Z+=`**Branch:** ${Y}\n`),
|
|
2389
|
+
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=`${D?"Create":T?"Append to":"Update"} ${x} (${v})`,r=await d.commitToGit(i,x,v,v,e,t,w,m,_.metricsPrefix)
|
|
2390
|
+
K=r.commitHash,Q=r.previousCommitHash,w.info("Changes committed to git via shared utility",{path:x,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:P?x:"document:"+E,status:"completed",finalContentLength:V.length,wasFileCreated:D,wasAppended:T&&A,operationType:R?"document":"file",processingTime:Date.now()-b,userComment:M,...P&&K&&{commitHash:K,previousCommitHash:Q||void 0}},note:"Write operation completed successfully"+(R?" (document synced)":" (committed to git)")})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let Z=`**${D?"Created":T?"Appended to":"Updated"} ${R?`document ${E}${j?` (${j})`:""}`:"file "+x}**\n`
|
|
2391
|
+
Z+=`**Content Length:** ${V.length} characters\n`,P&&Y&&(Z+=`**Branch:** ${Y}\n`),W.lockAcquired&&W.lockedRequestId&&(Z+=`**Locked request:** ${W.lockedRequestId}\n`),P&&K&&(Z+=`**Commit Hash:** ${K.substring(0,8)}\n`,Q&&(Z+=`**Previous Commit:** ${Q.substring(0,8)}\n`)),v&&(Z+=`[RECORD:${v}]\n`),R&&(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}\`.`)
|
|
2406
2392
|
const X=Date.now()
|
|
2407
|
-
return w.info("Write operation completed successfully",{duration:X-b,path:P?x:"document:"+E,contentLength:V.length,wasCreated:
|
|
2408
|
-
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,
|
|
2409
|
-
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),
|
|
2393
|
+
return w.info("Write operation completed successfully",{duration:X-b,path:P?x:"document:"+E,contentLength:V.length,wasCreated:D}),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
|
|
2394
|
+
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,p.getErrorMessage)(t),phase:C,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,p.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,p.getErrorMessage)(t)}],isError:!0}}}
|
|
2395
|
+
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),f=t(9949),p=t(8824)},4139(e,exports){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){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
2410
2396
|
const r=t(6183),n=t(4648)
|
|
2411
|
-
exports.def={name:"request_operations",description:"Perform operations on existing requests.\n\nOperations:\n\u2022 complete -
|
|
2397
|
+
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\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){Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseApiClient=void 0
|
|
2412
2398
|
const r=t(7163)
|
|
2413
2399
|
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)})
|
|
2414
2400
|
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")
|
|
@@ -2467,9 +2453,28 @@ if(!c.startsWith(s+a.sep))return{content:[{type:"text",text:"\u274c Invalid file
|
|
|
2467
2453
|
try{await i.access(c)}catch{return{content:[{type:"text",text:"\u274c Asset not found: "+r}],isError:!0}}const u=a.extname(r).toLowerCase().slice(1),h=d[u]
|
|
2468
2454
|
if(!h)return{content:[{type:"text",text:"\u274c Unsupported image type: ."+u}],isError:!0}
|
|
2469
2455
|
if("svg"===u)return{content:[{type:"text",text:`**Asset: ${r}**\n\n\`\`\`svg\n${await i.readFile(c,"utf-8")}\n\`\`\``}]}
|
|
2470
|
-
const g=await i.readFile(c),
|
|
2471
|
-
return o.info("Asset viewed",{filename:r,size:g.length}),{content:[{type:"text",text:`**Asset: ${r}** (${(g.length/1024).toFixed(1)} KB)`},{type:"image",data:
|
|
2472
|
-
const i=s(t(1943)),a=s(t(6928)),c=t(8824),l=t(4139),d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"}},
|
|
2456
|
+
const g=await i.readFile(c),f=g.toString("base64")
|
|
2457
|
+
return o.info("Asset viewed",{filename:r,size:g.length}),{content:[{type:"text",text:`**Asset: ${r}** (${(g.length/1024).toFixed(1)} KB)`},{type:"image",data:f,mimeType:h}]}}catch(e){return o.error("Failed to view asset",{error:(0,c.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c **Failed to view asset:** "+(0,c.getErrorMessage)(e)}],isError:!0}}}
|
|
2458
|
+
const i=s(t(1943)),a=s(t(6928)),c=t(8824),l=t(4139),d={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"}},4306(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMergeRequest=async function(e,t,i,a,c){const l=a.child({tool:"merge_request"}),d=c.startTimer("tool_execution_time"),{requestId:u,verifications:h}=e
|
|
2459
|
+
try{if(!u)throw(0,r.createValidationError)("requestId is required")
|
|
2460
|
+
l.info("Starting merge request",{requestId:u,verificationCount:h.length})
|
|
2461
|
+
const e=i.getRequestClient(),o=await e.getRequest(u)
|
|
2462
|
+
if("ready_for_review"===o?.status)return d({success:!1,reason:"testing_in_progress"}),{content:[{type:"text",text:`STOP: Cannot merge request ${u} \u2014 testing is in progress. Wait for tests to complete. The request will be moved to ready_for_merge when tests pass.`}],isError:!0}
|
|
2463
|
+
if(h.length>0)try{await i.proxyPost(`/api/projects/${t.projectId}/requests/${u}/verify-criteria`,{verifications:h}),l.info("Criteria verified",{requestId:u,count:h.length})}catch(e){const t=(0,s.getErrorMessage)(e)
|
|
2464
|
+
l.warn("Criteria verification failed, continuing with merge",{requestId:u,error:t})}let a,c
|
|
2465
|
+
try{const e=await i.proxyPost(`/api/projects/${t.projectId}/requests/${u}/validate-completion`,{})
|
|
2466
|
+
a=e?.data||e}catch(e){const t=(0,s.getErrorMessage)(e)
|
|
2467
|
+
return d({success:!1,error:"validation_failed"}),{content:[{type:"text",text:"Failed to validate merge: "+t}],isError:!0}}if(!a.canComplete){let e=`Cannot merge request ${u}: ${a.reason}\n`
|
|
2468
|
+
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")
|
|
2469
|
+
let g="workspace-manager"
|
|
2470
|
+
const f=await e.getRequest(u),p=f?.title||"Request "+u,m="resolving_conflicts"===f?.status
|
|
2471
|
+
try{m?(l.info("Merge retry (resolving_conflicts) \u2014 using -X theirs",{requestId:u}),c=await t.workspaceManager.completeRequest(u,p,{skipConflictDetection:!0}),g="retry-theirs"):(c=await t.workspaceManager.completeRequest(u,p),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)
|
|
2472
|
+
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)
|
|
2473
|
+
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:f?.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)
|
|
2474
|
+
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)
|
|
2475
|
+
l.error("Merge request failed",{error:r})
|
|
2476
|
+
try{await(0,o.createFailureToolRecord)("merge-request",e,{error:r,requestId:u},i.getToolRecordClient(),l,c,{requestId:u,projectId:t.projectId,note:"Failed to merge request"})}catch{}return d({success:!1,error:e instanceof Error?e.name:"unknown"}),{content:[{type:"text",text:"Error: "+r}],isError:!0}}}
|
|
2477
|
+
const r=t(9860),n=t(1651),o=t(8616),s=t(8824)},4394(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.getOrCreateHealthCheckManager=function(e,t,o,s={}){const i=e.endsWith("/")?e.slice(0,-1):e,a=n.get(i)
|
|
2473
2478
|
if(a)return t.debug("Reusing existing HealthCheckManager instance",{baseUrl:i,totalInstances:n.size}),a
|
|
2474
2479
|
t.info("Creating new HealthCheckManager instance",{baseUrl:i,totalInstancesBefore:n.size})
|
|
2475
2480
|
const c=new r.HealthCheckManager(i,t,o,{checkIntervalMs:s.checkIntervalMs||3e4,timeoutMs:s.timeoutMs||5e3,retryCount:s.retryCount||2,onOfflineCallback:s.onOfflineCallback,onOnlineCallback:s.onOnlineCallback})
|
|
@@ -2510,9 +2515,9 @@ if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
|
2510
2515
|
return o(t,e),t})
|
|
2511
2516
|
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")
|
|
2512
2517
|
try{"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)
|
|
2513
|
-
const r=c.validateArgs(e,a.PlannerOpsSchema),{operation:
|
|
2518
|
+
const r=c.validateArgs(e,a.PlannerOpsSchema),{operation:f,sessionId:p}=r
|
|
2514
2519
|
let m
|
|
2515
|
-
switch(h.info("Processing planner_ops",{operation:
|
|
2520
|
+
switch(h.info("Processing planner_ops",{operation:f,sessionId:p}),f){case"request":{const e=await async function(e,t,r){if(!e)return"ask"
|
|
2516
2521
|
try{const n=r?.sessionId||d.sessionIdentity.getIdentity()?.sessionId
|
|
2517
2522
|
if(!n)return"ask"
|
|
2518
2523
|
const o=e.getCLISessionClient()
|
|
@@ -2531,13 +2536,13 @@ if(t&&e){const n=await d.sessionIdentity.getParentSessionId(e,o,h),s=r.request.d
|
|
|
2531
2536
|
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})}]}
|
|
2532
2537
|
break}const n="auto-planner"
|
|
2533
2538
|
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
|
|
2534
|
-
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)(
|
|
2539
|
+
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)(p,t,h,o)
|
|
2535
2540
|
break
|
|
2536
2541
|
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??""
|
|
2537
2542
|
if(c.trim()||g.trim()){const e=[]
|
|
2538
2543
|
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."}]}
|
|
2539
2544
|
break
|
|
2540
|
-
default:throw new i.ValidationError("Unknown operation: "+
|
|
2545
|
+
default:throw new i.ValidationError("Unknown operation: "+f)}return g({success:!0}),n.incrementCounter(`planner_ops_${f}_success`,1),m}catch(e){return h.error("Planner ops failed",{error:e instanceof Error?e.stack:e+""}),g({success:!1}),n.incrementCounter("planner_ops_errors",1),{content:[{type:"text",text:"Planner operation failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
|
|
2541
2546
|
const i=t(9860),a=t(6183),c=s(t(5967)),l=t(8824),d=t(6688),u=t(1725)},4600(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.execAsync=async function(e,t={}){return new Promise(((n,o)=>{const[s,...i]=e.split(" "),a=(0,r.spawn)(s,i,{cwd:t.cwd||process.cwd(),stdio:["pipe","pipe","pipe"]})
|
|
2542
2547
|
let c="",l=""
|
|
2543
2548
|
a.stdout?.on("data",(e=>{c+=e.toString()})),a.stderr?.on("data",(e=>{l+=e.toString()})),a.on("close",(e=>{n({stdout:c,stderr:l,exitCode:e||0})})),a.on("error",(t=>{o(Error(`Command failed: ${e}\nError: ${t.message}`))})),t.timeout&&setTimeout((()=>{a.kill(),o(Error("Command timed out: "+e))}),t.timeout)}))}
|
|
@@ -2551,12 +2556,12 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
2551
2556
|
var t={}
|
|
2552
2557
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2553
2558
|
return o(t,e),t})
|
|
2554
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,t,r,n,o,s,g){const
|
|
2559
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,t,r,n,o,s,g){const f=o.child({tool:"file_recover"}),p=s.startTimer("tool_execution_time"),m=Date.now()
|
|
2555
2560
|
try{let o
|
|
2556
2561
|
try{o=i.FileRecoverSchema.parse(e)}catch(t){if(t instanceof a.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
2557
|
-
return
|
|
2558
|
-
return
|
|
2559
|
-
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",
|
|
2562
|
+
return f.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{taskId:p,path:y,commitHash:w,createBackup:k}=o
|
|
2563
|
+
return f.info("Recovering file to previous version",{taskId:p,filePath:y,commitHash:w,createBackup:k}),await async function(e,t,r,n,o,s,i,a,g,f,p){let m
|
|
2564
|
+
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",p)
|
|
2560
2565
|
m=b
|
|
2561
2566
|
let I,v=!1
|
|
2562
2567
|
try{await l.access(w),v=!0,n&&(I=`${w}.backup-${(new Date).toISOString().replace(/[:.]/g,"-")}`,await l.copyFile(w,I),a.info("Created backup",{originalPath:w,backupPath:I}))}catch{v=!1}const C=o.git
|
|
@@ -2568,32 +2573,29 @@ if(t.includes("does not exist")||t.includes("not found")||t.includes("Path"))thr
|
|
|
2568
2573
|
throw Error(`Failed to retrieve file '${y}' from commit '${r}': ${t}`)}await l.writeFile(w,_,"utf8")
|
|
2569
2574
|
let E={}
|
|
2570
2575
|
try{const t=`Recover ${y} from ${r.substring(0,8)}`
|
|
2571
|
-
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()-
|
|
2576
|
+
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()-f,...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"
|
|
2572
2577
|
let S=`\u2705 **File ${q.charAt(0).toUpperCase()+q.slice(1)} Successfully**\n\n`
|
|
2573
|
-
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()-
|
|
2574
|
-
return
|
|
2575
|
-
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){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,t,u,h,g,
|
|
2576
|
-
try{"complete"===e?.operation&&e?.summary&&!e?.complete&&(e.complete={summary:e.summary,
|
|
2577
|
-
const d=e
|
|
2578
|
-
|
|
2579
|
-
const
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
const e=
|
|
2592
|
-
return
|
|
2593
|
-
const e={
|
|
2594
|
-
return await(0,a.handleSearchRequests)(e,t,u,h,g)}default:{const e="Unknown operation type: "+w
|
|
2595
|
-
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}}}
|
|
2596
|
-
const r=t(6183),n=t(5715),o=t(6416),s=t(5434),i=t(8037),a=t(233),c=t(3596),l=t(1537),d=t(8824)},4710(e,exports,t){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2578
|
+
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()-f}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(p,y,w,k,t,r,n,f,s,m,g)}catch(e){const t=Date.now()-m
|
|
2579
|
+
return f.error("Recovery operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),p({tool:"file_recover",success:!1}),s.incrementCounter("file_recover_errors",1),{content:[{type:"text",text:"\u274c **Recovery Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
|
|
2580
|
+
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){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,t,u,h,g,f){const p=h.child({tool:"request_operations"})
|
|
2581
|
+
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)
|
|
2582
|
+
const d=r.RequestOperationsSchema.parse(e),{requestId:m,operation:y}=d
|
|
2583
|
+
switch(p.info("Processing request operation",{requestId:m,operation:y}),y){case"complete":{p.info("Routing to complete-request handler")
|
|
2584
|
+
const e={requestId:m,summary:d.complete.summary}
|
|
2585
|
+
return await(0,n.handleCompleteRequest)(e,t,u,h,g,f)}case"merge":return p.info("Routing to merge handler"),await(0,l.handleMergeRequest)({requestId:m,verifications:d.merge?.verifications||[]},t,u,h,g,f)
|
|
2586
|
+
case"approve":{p.info("Routing to approve-request handler")
|
|
2587
|
+
const e={requestId:m}
|
|
2588
|
+
return await(0,c.handleApproveRequest)(e,t,u,h,g,f)}case"revert":{p.info("Routing to revert-request handler")
|
|
2589
|
+
const e={requestId:m,reason:d.revert.reason,confirmDestructive:d.revert.confirmDestructive}
|
|
2590
|
+
return await(0,o.handleRevertRequest)(e,t,u,h,g)}case"get-info":{p.info("Routing to get-request-information handler")
|
|
2591
|
+
const e={requestId:m}
|
|
2592
|
+
return await(0,s.handleGetRequestInformation)(e,t,u,h,g)}case"list":{p.info("Routing to list-requests handler")
|
|
2593
|
+
const e={filters:d.list?.filters}
|
|
2594
|
+
return await(0,i.handleListRequests)(e,t,u,h,g)}case"search":{p.info("Routing to search-requests handler")
|
|
2595
|
+
const e={search:d.search}
|
|
2596
|
+
return await(0,a.handleSearchRequests)(e,t,u,h,g)}default:{const e="Unknown operation type: "+y
|
|
2597
|
+
return p.error(e),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+e}],isError:!0}}}}catch(e){return p.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}}}
|
|
2598
|
+
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){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2597
2599
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectClient=void 0
|
|
2598
2600
|
const n=r(t(9896)),o=r(t(6928)),s=t(7645),i=t(2161),a=t(1058),c=t(8824)
|
|
2599
2601
|
class l extends s.ConnectionAwareClient{isOffline(){return!!this.connectionStatusManager&&this.connectionStatusManager.isOffline()}isOnline(){return!this.isOffline()}setProjectSynchronizer(e){this.logger.info("Setting ProjectSynchronizer on ProjectClient"),this.projectSynchronizer=e}getProjectSynchronizer(){return this.projectSynchronizer}async fetchProject(e){return this.getProject(e)}async pingDetailed(){this.logger.debug("Pinging remote server")
|
|
@@ -2713,17 +2715,17 @@ var t={}
|
|
|
2713
2715
|
if(null!=e)for(var r=s(e),n=0;n<r.length;n++)"default"!==r[n]&&i(t,e,r[n])
|
|
2714
2716
|
return a(t,e),t})
|
|
2715
2717
|
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()
|
|
2716
|
-
try{const{path:i,lines:
|
|
2717
|
-
c.info("Processing blame request",{filePath:i,lines:
|
|
2718
|
+
try{const{path:i,lines:f,branch:p}=e
|
|
2719
|
+
c.info("Processing blame request",{filePath:i,lines:f,branch:p})
|
|
2718
2720
|
const m=t.basePath,y=d.isAbsolute(i)?i:d.join(m,i),w=d.relative(m,y)
|
|
2719
2721
|
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
|
|
2720
2722
|
if(/^\d+$/.test(e)){const t=parseInt(e,10)
|
|
2721
2723
|
return{start:t,end:t}}const t=e.match(/^(\d+)-(\d+)$/)
|
|
2722
2724
|
if(t)return{start:parseInt(t[1],10),end:parseInt(t[2],10)}
|
|
2723
2725
|
if(e.match(/^(\d+(?:,\d+)+)$/)){const t=e.split(",").map((e=>parseInt(e,10)))
|
|
2724
|
-
return{start:Math.min(...t),end:Math.max(...t)}}return null}(
|
|
2726
|
+
return{start:Math.min(...t),end:Math.max(...t)}}return null}(f),b=["blame","--porcelain"]
|
|
2725
2727
|
let I
|
|
2726
|
-
k&&b.push(`-L${k.start},${k.end}`),
|
|
2728
|
+
k&&b.push(`-L${k.start},${k.end}`),p&&b.push(p),b.push("--",w),c.debug("Executing git blame",{args:b})
|
|
2727
2729
|
try{if(!t.git)throw Error("Git context not available")
|
|
2728
2730
|
I=await t.git.raw(b)}catch(e){const t=(0,h.getErrorMessage)(e)
|
|
2729
2731
|
return c.error("Git blame failed",{error:t}),{content:[{type:"text",text:"\u274c Git blame failed: "+t}],isError:!0}}const v=function(e){const t=[],r=e.split("\n")
|
|
@@ -2798,7 +2800,7 @@ const r=t(6183),n=t(4592)
|
|
|
2798
2800
|
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){async function r(e,t,r,s,i){const a=r.child({requestId:e,operation:"request-status-validation"})
|
|
2799
2801
|
try{a.info("Validating request status for document operation",{requestId:e})
|
|
2800
2802
|
const r=await t.getRequest(e)
|
|
2801
|
-
if(a.info("Request status retrieved",{requestId:e,status:r.status}),"completed"
|
|
2803
|
+
if(a.info("Request status retrieved",{requestId:e,status:r.status}),["completed","canceled","pending_approval","ready_for_review","ready_for_merge","reverted"].includes(r.status)){const t=r.status.replace(/_/g," "),o=`\u274c **Document operations are not allowed on ${t} requests.**\n\n**Request:** ${e}\n**Status:** ${r.status}\n\n**Reason:** Once a request is ${t}, its associated documents become read-only to maintain audit trail integrity.\n\n**What you can do:**\n- Create a new request for additional changes\n- Use the revert-request tool if you need to make corrections\n- Contact your administrator if you believe this is an error`
|
|
2802
2804
|
a.warn("Document operation blocked on terminal request",{requestId:e,requestStatus:r.status,reason:"completed"===r.status?"request_completed":"request_canceled"})
|
|
2803
2805
|
const c="completed"===r.status?i+"_blocked_completed_request":i+"_blocked_canceled_request"
|
|
2804
2806
|
throw s.incrementCounter(c,1),new n.ValidationError(o,{requestId:e,requestStatus:r.status,reason:"request_completed"})}return a.info("Request status validation passed",{requestId:e,status:r.status}),r}catch(t){if(t instanceof n.ValidationError)throw t
|
|
@@ -2928,48 +2930,57 @@ var t={}
|
|
|
2928
2930
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2929
2931
|
return o(t,e),t})
|
|
2930
2932
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handlePlanRead=async function(e,t,r,n,o){const s=n.child({tool:"plan_read"})
|
|
2931
|
-
try{
|
|
2932
|
-
|
|
2933
|
-
|
|
2934
|
-
return o.incrementCounter("plan_read_total",1,{operation:"
|
|
2933
|
+
try{e?.get?.planId&&!e.planId&&(e.planId=e.get.planId,delete e.get),e?.getHistory?.planId&&!e.planId&&(e.planId=e.getHistory.planId,delete e.getHistory),e?.getRequests?.planId&&!e.planId&&(e.planId=e.getRequests.planId,delete e.getRequests),e?.list&&!e.searchQuery&&(Object.assign(e,e.list),delete e.list)
|
|
2934
|
+
const n=a.validateArgs(e,i.PlanReadSchema),{operation:d,planId:u}=n
|
|
2935
|
+
switch(s.info("Processing plan_read",{operation:d}),d){case"get":{const e=await(0,c.handleGetPlan)({planId:u},t,r,s,o)
|
|
2936
|
+
return o.incrementCounter("plan_read_total",1,{operation:"get",success:!e.isError}),e}case"list":{const e=await(0,l.handleListPlans)({searchQuery:n.searchQuery,limit:n.limit,offset:n.offset,sortBy:n.sortBy,sortDirection:n.sortDirection},t,r,s,o)
|
|
2937
|
+
return o.incrementCounter("plan_read_total",1,{operation:"list",success:!e.isError}),e}case"get-history":{const e=r.getDocumentClient(),t=await e.getVersionHistory(u)
|
|
2935
2938
|
o.incrementCounter("plan_read_total",1,{operation:"get-history",success:!0})
|
|
2936
|
-
let
|
|
2937
|
-
|
|
2938
|
-
let
|
|
2939
|
-
return
|
|
2939
|
+
let n=""
|
|
2940
|
+
t.snapshots&&t.snapshots.length>0?(n="### Version Snapshots\n\n",t.snapshots.forEach((e=>{n+=`**Version ${e.versionNumber}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.versionLabel&&(n+=` Label: ${e.versionLabel}\n`),e.changeSummary&&(n+=` Summary: ${e.changeSummary}\n`),n+="\n"}))):n="### Version Snapshots\n\nNo version snapshots created yet.\n\n"
|
|
2941
|
+
let s=""
|
|
2942
|
+
return t.changeHistory&&t.changeHistory.length>0?(s="### Recent Changes\n\n",t.changeHistory.slice(0,10).forEach((e=>{s+=`**${e.toolName}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.createdBy&&(s+=` By: ${e.createdBy}\n`),s+="\n"}))):s="### Recent Changes\n\nNo changes recorded.\n",{content:[{type:"text",text:`## Version History for ${u}\n\n${n}${s}`}]}}case"get-active":{const e=r.getProjectClient(),n=t.projectId
|
|
2940
2943
|
if(!n)return{content:[{type:"text",text:"\u274c No project context available."}],isError:!0}
|
|
2941
2944
|
const i=await e.getProject(n)
|
|
2942
2945
|
if(!i||!i.activePlanId)return o.incrementCounter("plan_read_total",1,{operation:"get-active",success:!0}),{content:[{type:"text",text:"No active plan set for this project. Use `plan_write` with `set-active` to designate one, or create a new plan."}]}
|
|
2943
2946
|
const a=await(0,c.handleGetPlan)({planId:i.activePlanId},t,r,s,o)
|
|
2944
|
-
return o.incrementCounter("plan_read_total",1,{operation:"get-active",success:!a.isError}),!a.isError&&a.content.length>0&&(a.content[0].text="\u{1f4cc} **Active Project Plan**\n\n"+a.content[0].text),a}case"get-requests":{const
|
|
2945
|
-
if(o.incrementCounter("plan_read_total",1,{operation:"get-requests",success:!0}),!
|
|
2946
|
-
let
|
|
2947
|
-
for(const e of
|
|
2948
|
-
return{content:[{type:"text",text:
|
|
2949
|
-
const i=t(6183),a=s(t(5967)),c=t(8800),l=t(8391),d=t(8824)},5317(module){module.exports=require("child_process")},5434(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleGetRequestInformation=async function(e,t,
|
|
2947
|
+
return o.incrementCounter("plan_read_total",1,{operation:"get-active",success:!a.isError}),!a.isError&&a.content.length>0&&(a.content[0].text="\u{1f4cc} **Active Project Plan**\n\n"+a.content[0].text),a}case"get-requests":{const e=r.getRequestClient(),t=await e.listRequests({planDocumentId:u})
|
|
2948
|
+
if(o.incrementCounter("plan_read_total",1,{operation:"get-requests",success:!0}),!t||0===t.length)return{content:[{type:"text",text:`No requests linked to plan ${u}.`}]}
|
|
2949
|
+
let n=`## Requests Linked to ${u} (${t.length})\n\n`
|
|
2950
|
+
for(const e of t)n+=`**${e.localId||e.id}** \u2014 ${e.title}\n`,n+=` Status: ${e.status} | Type: ${e.type}\n`,n+=` Updated: ${new Date(e.updatedAt).toLocaleString()}\n\n`
|
|
2951
|
+
return{content:[{type:"text",text:n}]}}default:throw Error("Unknown plan_read operation: "+d)}}catch(e){return s.error("plan_read failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("plan_read_errors",1),{content:[{type:"text",text:"\u274c **Plan Read Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
|
|
2952
|
+
const i=t(6183),a=s(t(5967)),c=t(8800),l=t(8391),d=t(8824)},5317(module){module.exports=require("child_process")},5434(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleGetRequestInformation=async function(e,t,a,c,l){const d=c.child({tool:"get_request_information"}),u=l.startTimer("tool_execution_time")
|
|
2950
2953
|
try{const{requestId:t}=e
|
|
2951
2954
|
if(!t)throw new r.ValidationError("Request ID is required")
|
|
2952
2955
|
if(!/^req\d{6}$/.test(t))throw new r.ValidationError(`Invalid request ID format: ${t}. Expected format: req######`)
|
|
2953
|
-
|
|
2954
|
-
const n=
|
|
2955
|
-
|
|
2956
|
-
const
|
|
2957
|
-
|
|
2958
|
-
const
|
|
2959
|
-
|
|
2960
|
-
const p={pending:0,in_progress:0,blocked:0,ready_for_review:0,completed:0,reverted:0,total:
|
|
2961
|
-
|
|
2956
|
+
d.info("Getting information for request "+t)
|
|
2957
|
+
const n=a.getRequestClient(),s=a.getTaskClient(),[c,l]=await Promise.all([n.getRequest(t),s.listTasks({requestId:t})])
|
|
2958
|
+
d.info("Raw request response data",{responseData:JSON.stringify(c)}),d.debug("Request response structure",{type:typeof c,isArray:Array.isArray(c),hasData:null!=c,properties:c?Object.keys(c):[],dataPreview:c?JSON.stringify(c).substring(0,200)+"...":"null"})
|
|
2959
|
+
const h=(0,o.extractDataFromResponse)(c,{logger:d,operationName:"getRequestInformation",throwOnNoData:!0}),g="data"in h?h.data:h
|
|
2960
|
+
d.info("Successfully extracted request data using data extraction utility"),d.info("Raw tasks response data",{responseData:JSON.stringify(l)}),d.debug("Tasks response structure",{type:typeof l,isArray:Array.isArray(l),hasData:null!=l,properties:l?Object.keys(l):[],dataPreview:l?JSON.stringify(l).substring(0,200)+"...":"null"})
|
|
2961
|
+
const f=(0,o.extractArrayFromResponse)(l,{logger:d,operationName:"listTasksForRequest",defaultValue:[]})
|
|
2962
|
+
d.info(`Successfully extracted ${f.length} tasks using data extraction utility`)
|
|
2963
|
+
const p={pending:0,in_progress:0,blocked:0,ready_for_review:0,completed:0,reverted:0,total:f.length}
|
|
2964
|
+
f.forEach((e=>{const t=e.status
|
|
2962
2965
|
t in p&&p[t]++}))
|
|
2963
|
-
const
|
|
2964
|
-
|
|
2965
|
-
t in
|
|
2966
|
-
let
|
|
2967
|
-
const
|
|
2968
|
-
let
|
|
2969
|
-
return
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2966
|
+
const m=g.acceptanceCriteria||[],y={unverified:0,partial:0,verified:0,partially_verified:0,total:m.length}
|
|
2967
|
+
m.forEach((e=>{const t=e.status||"unverified"
|
|
2968
|
+
t in y&&y[t]++}))
|
|
2969
|
+
let w=g.testVerification||null
|
|
2970
|
+
const k=g.title,b=g.type
|
|
2971
|
+
let I=`# ${"feature"===b?"Feature":"quick-edit"===b?"Quick Edit":"Bug Fix"} Request: ${k} (${t})\nStatus: ${g.status}\nCreated: ${new Date(g.createdAt).toLocaleString()}\nUpdated: ${new Date(g.updatedAt).toLocaleString()}\n\n## Description\n${g.description||"_No description provided._"}\n\n## Progress Summary\n- Tasks: ${p.completed}/${p.total} completed (${Math.round(p.completed/p.total*100)||0}%)\n- Acceptance Criteria: ${y.verified}/${y.total} verified (${Math.round(y.verified/y.total*100)||0}%)\n`
|
|
2972
|
+
return I+=`\n## Task Status\n- Pending: ${p.pending}\n- In Progress: ${p.in_progress}\n- Blocked: ${p.blocked}\n- Ready for Review: ${p.ready_for_review}\n- Completed: ${p.completed}\n- Reverted: ${p.reverted}\n`,I+="\n## Tasks\n",0===f.length?I+="No tasks found for this request.\n":f.forEach((e=>{I+=`**[${e.id}]** ${e.title} (Status: ${e.status})\n`})),d.info(`Added task listing with ${f.length} tasks`),I+="\n## Acceptance Criteria\n",I+=(0,i.formatCriteriaWithHashes)(m)+"\n","ready_for_review"===g.status&&m.some((e=>"verified"!==e.status))&&(I+="\n> **Status: ready_for_review** \u2014 Use the merge operation to verify criteria and merge to main.\n"),w&&(I+=`\n## Test Coverage\n- Test Cases: ${w.totalTestCases||0}\n- Criteria Tested: ${w.criteriaTestedCount||0}/${y.total}\n`,w.criterionCoverage&&Array.isArray(w.criterionCoverage)&&(I+="\n### Detailed Test Coverage:\n",w.criterionCoverage.forEach((e=>{I+=`- Criterion ${e.criterionId}: ${e.coverage} coverage\n`})))),g.recentActivity&&Array.isArray(g.recentActivity)&&(I+="\n## Recent Activity\n",g.recentActivity.slice(0,5).forEach((e=>{const t=new Date(e.timestamp).toLocaleString()
|
|
2973
|
+
I+=`- ${t}: ${e.description}\n`}))),u({success:!0}),{content:[{type:"text",text:I}]}}catch(t){return d.error("Error getting request information",{args:e,error:t instanceof Error?t.stack:t+""}),u({success:!1,error:t instanceof Error?t.name:"unknown"}),t instanceof n.ConnectionError?{content:[{type:"text",text:"Unable to get request information: Connection to the server failed. Please check your network connection and try again."}],isError:!0}:{content:[{type:"text",text:"Error getting request information: "+(0,s.getErrorMessage)(t)}],isError:!0}}}
|
|
2974
|
+
const r=t(9860),n=t(5674),o=t(2960),s=t(8824),i=t(5454)},5454(e,exports){function t(e,t){let r=0
|
|
2975
|
+
for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t)|0
|
|
2976
|
+
return`${t+1}${String.fromCharCode(97+Math.abs(r)%26)}`}function r(e){const r=new Map
|
|
2977
|
+
for(let n=0;n<e.length;n++){const o=t(e[n].id,n)
|
|
2978
|
+
r.set(o,e[n])}return r}function n(e){if(0===e.length)return"No acceptance criteria defined."
|
|
2979
|
+
const t=r(e),n=[]
|
|
2980
|
+
for(const[e,r]of t){const t=(r.status||"unverified").toUpperCase()
|
|
2981
|
+
n.push(`[${e}] [${t}] ${r.description}`)}return n.join("\n")}function o(e){const t=r(e),o=[]
|
|
2982
|
+
for(const[e,r]of t)o.push(` {"key": "${e}", "evidence": "<your evidence for: ${r.description}>"}`)
|
|
2983
|
+
return`Use the merge operation with evidence for each criterion:\n\n${n(e)}\n\nExample call:\n{\n "operation": "merge",\n "requestId": "<requestId>",\n "merge": {\n "verifications": [\n${o.join(",\n")}\n ]\n }\n}`}Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatEvidenceInstructions=exports.formatCriteriaWithHashes=exports.buildCriteriaHashMap=exports.criterionHash=void 0,exports.criterionShortKey=t,exports.buildCriteriaKeyMap=r,exports.formatCriteriaWithKeys=n,exports.formatVerifyInstructions=o,exports.criterionHash=t,exports.buildCriteriaHashMap=r,exports.formatCriteriaWithHashes=n,exports.formatEvidenceInstructions=o},5459(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
2973
2984
|
const r=t(6183),n=t(2414)
|
|
2974
2985
|
exports.def={name:"move_files",description:"Move or rename multiple files and directories in a single operation. Requires a taskId and a comment explaining the purpose of the modifications. All operations are processed sequentially and committed together. If any operation fails, the tool reports which operations succeeded and which failed.",schema:r.MoveFilesSchema,annotations:{title:"Move or Rename Multiple Files",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},hidden:!0,createsRecords:!0,handler(e,t){return(0,n.handleMoveFiles)(e,t.context,t.apiClient.getTaskClient(),t.apiClient.getToolRecordClient(),t.apiClient.getRequestClient(),t.logger,t.metrics,t.mcpServer)}}},5626(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
2975
2986
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
@@ -2980,35 +2991,37 @@ var t={}
|
|
|
2980
2991
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2981
2992
|
return o(t,e),t})
|
|
2982
2993
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDocumentOperations=async function(e,t,r,n,o,s,u){const h=n.child({tool:"document_operations"})
|
|
2983
|
-
try{const n=
|
|
2984
|
-
|
|
2985
|
-
const
|
|
2994
|
+
try{const n=["create","search","createSnapshot","getHistory","getVersion","restoreVersion","listAnnotations","createAnnotation","replyToAnnotation","resolveAnnotation"]
|
|
2995
|
+
for(const t of n)e?.[t]&&"object"==typeof e[t]&&(Object.assign(e,e[t]),delete e[t])
|
|
2996
|
+
const d=a.validateArgs(e,i.DocumentOperationsSchema),{operation:g}=d,f=d.documentId
|
|
2997
|
+
switch(h.info("Processing document_operations",{operation:g}),g){case"create":{h.info("Routing to create-document handler")
|
|
2998
|
+
const e=await(0,c.handleCreateDocument)({requestId:d.requestId,filename:d.filename,content:d.content,type:d.type,comment:d.comment},t,r,h,o,s,u)
|
|
2986
2999
|
return o.incrementCounter("document_operations_total",1,{operation:"create",success:!e.isError}),e}case"search":{h.info("Routing to search-documents handler")
|
|
2987
|
-
const e=await(0,l.handleSearchDocuments)(
|
|
3000
|
+
const e=await(0,l.handleSearchDocuments)({query:d.query,type:d.type,requestId:d.requestId,includeArchived:d.includeArchived,maxResults:d.maxResults,dateFrom:d.dateFrom,dateTo:d.dateTo,searchIn:d.searchIn},t,r,h,o,s)
|
|
2988
3001
|
return o.incrementCounter("document_operations_total",1,{operation:"search",success:!e.isError}),e}case"create-snapshot":{h.info("Creating version snapshot")
|
|
2989
|
-
const{
|
|
2990
|
-
return o.incrementCounter("document_operations_total",1,{operation:"create-snapshot",success:!0}),{content:[{type:"text",text:`\u2705 **Version Snapshot Created**\n\n**Document:** ${
|
|
2991
|
-
const
|
|
2992
|
-
h.info("Version history data received",{hasSnapshots:!!
|
|
2993
|
-
let
|
|
2994
|
-
|
|
2995
|
-
let
|
|
2996
|
-
return
|
|
2997
|
-
const
|
|
2998
|
-
return o.incrementCounter("document_operations_total",1,{operation:"get-version",success:!0}),{content:[{type:"text",text:`## Version ${
|
|
2999
|
-
const
|
|
3000
|
-
return o.incrementCounter("document_operations_total",1,{operation:"restore-version",success:!0}),{content:[{type:"text",text:`\u2705 **Document Restored**\n\n**Document:** ${
|
|
3001
|
-
const
|
|
3002
|
-
if(o.incrementCounter("document_operations_total",1,{operation:"list-annotations",success:!0}),!
|
|
3003
|
-
let
|
|
3004
|
-
for(const e of
|
|
3005
|
-
for(const t of e.replies)
|
|
3006
|
-
const
|
|
3007
|
-
return o.incrementCounter("document_operations_total",1,{operation:"create-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Annotation Created**\n\n**ID:** ${
|
|
3008
|
-
const
|
|
3009
|
-
return o.incrementCounter("document_operations_total",1,{operation:"reply-to-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Reply Added**\n\n**Reply ID:** ${
|
|
3010
|
-
const
|
|
3011
|
-
return await
|
|
3002
|
+
const{versionLabel:e,changeSummary:t}=d,n=r.getDocumentClient(),s=await n.createVersionSnapshot(f,e,t)
|
|
3003
|
+
return o.incrementCounter("document_operations_total",1,{operation:"create-snapshot",success:!0}),{content:[{type:"text",text:`\u2705 **Version Snapshot Created**\n\n**Document:** ${f}\n**Version:** ${s.versionNumber}\n**Label:** ${e||"None"}\n**Summary:** ${t||"None"}\n**Created:** `+new Date(s.createdAt).toLocaleString()}]}}case"get-history":{h.info("Retrieving version history")
|
|
3004
|
+
const e=r.getDocumentClient(),t=await e.getVersionHistory(f)
|
|
3005
|
+
h.info("Version history data received",{hasSnapshots:!!t.snapshots,snapshotCount:t.snapshots?.length||0,hasChangeHistory:!!t.changeHistory,changeCount:t.changeHistory?.length||0,keys:Object.keys(t)}),o.incrementCounter("document_operations_total",1,{operation:"get-history",success:!0})
|
|
3006
|
+
let n=""
|
|
3007
|
+
t.snapshots&&t.snapshots.length>0?(n="### \u{1f4da} Version Snapshots\n\n",t.snapshots.forEach((e=>{n+=`**Version ${e.versionNumber}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.versionLabel&&(n+=` Label: ${e.versionLabel}\n`),e.changeSummary&&(n+=` Summary: ${e.changeSummary}\n`),n+="\n"}))):n="### \u{1f4da} Version Snapshots\n\nNo version snapshots created yet.\n\n"
|
|
3008
|
+
let s=""
|
|
3009
|
+
return t.changeHistory&&t.changeHistory.length>0?(s="### \u{1f4dd} Recent Changes\n\n",t.changeHistory.slice(0,10).forEach((e=>{s+=`**${e.toolName}** - ${new Date(e.createdAt).toLocaleString()}\n`,e.createdBy&&(s+=` By: ${e.createdBy}\n`),s+="\n"}))):s="### \u{1f4dd} Recent Changes\n\nNo changes recorded.\n",{content:[{type:"text",text:`## Version History for ${f}\n\n${n}${s}`}]}}case"get-version":{h.info("Retrieving specific version")
|
|
3010
|
+
const e=r.getDocumentClient(),t=await e.getVersion(f,d.versionNumber)
|
|
3011
|
+
return o.incrementCounter("document_operations_total",1,{operation:"get-version",success:!0}),{content:[{type:"text",text:`## Version ${d.versionNumber} of ${f}\n\n**Created:** ${new Date(t.createdAt).toLocaleString()}\n**Label:** ${t.versionLabel||"None"}\n**Summary:** ${t.changeSummary||"None"}\n\n### Content:\n\n\`\`\`\n${t.content}\n\`\`\``}]}}case"restore-version":{h.info("Restoring to version")
|
|
3012
|
+
const e=r.getDocumentClient(),t=await e.restoreToVersion(f,d.versionNumber)
|
|
3013
|
+
return o.incrementCounter("document_operations_total",1,{operation:"restore-version",success:!0}),{content:[{type:"text",text:`\u2705 **Document Restored**\n\n**Document:** ${f}\n**Restored to Version:** ${d.versionNumber}\n**Filename:** ${t.filename}\n\nThe document has been successfully restored to version ${d.versionNumber}.`}]}}case"list-annotations":{h.info("Listing annotations")
|
|
3014
|
+
const e=r.getDocumentClient(),t=await e.listAnnotations(f)
|
|
3015
|
+
if(o.incrementCounter("document_operations_total",1,{operation:"list-annotations",success:!0}),!t||0===t.length)return{content:[{type:"text",text:`No annotations found on document ${f}.`}]}
|
|
3016
|
+
let n=`## Annotations on ${f} (${t.length})\n\n`
|
|
3017
|
+
for(const e of t){if(n+=`### ${"resolved"===e.status?"\u2705":"\u{1f4ac}"} ${e.id} [${e.status}]\n`,n+=`> "${e.anchor?.selectedText?.substring(0,80)||""}"\n\n`,n+=e.body+"\n",e.createdByAgent&&(n+=`*By agent: ${e.createdByAgent}*\n`),e.replies&&e.replies.length>0){n+=`\n**Replies (${e.replies.length}):**\n`
|
|
3018
|
+
for(const t of e.replies)n+="- "+t.body,t.createdByAgent&&(n+=` *(${t.createdByAgent})*`),n+="\n"}n+="\n---\n\n"}return{content:[{type:"text",text:n}]}}case"create-annotation":{h.info("Creating annotation")
|
|
3019
|
+
const e=d.selectedText,t=d.body,{prefixContext:n,suffixContext:s,lineHint:i}=d,a=r.getDocumentClient(),c=u?"agent":void 0,l=u?.sessionId,g=await a.createAnnotation(f,{selectedText:e,prefixContext:n,suffixContext:s,lineHint:i,body:t,createdByAgent:c,createdBySessionId:l})
|
|
3020
|
+
return o.incrementCounter("document_operations_total",1,{operation:"create-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Annotation Created**\n\n**ID:** ${g.id}\n**Document:** ${f}\n**Selected text:** "${e.substring(0,60)}"\n**Comment:** `+t}]}}case"reply-to-annotation":{h.info("Replying to annotation")
|
|
3021
|
+
const e=d.annotationId,t=d.body,n=r.getDocumentClient(),s=await n.replyToAnnotation(f,e,{body:t,createdByAgent:u?"agent":void 0,createdBySessionId:u?.sessionId})
|
|
3022
|
+
return o.incrementCounter("document_operations_total",1,{operation:"reply-to-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Reply Added**\n\n**Reply ID:** ${s.id}\n**Annotation:** ${e}\n**Body:** `+t}]}}case"resolve-annotation":{h.info("Resolving annotation")
|
|
3023
|
+
const e=d.annotationId,t=r.getDocumentClient()
|
|
3024
|
+
return await t.resolveAnnotation(f,e,u?"agent":void 0),o.incrementCounter("document_operations_total",1,{operation:"resolve-annotation",success:!0}),{content:[{type:"text",text:`\u2705 **Annotation Resolved**\n\n**Annotation:** ${e}\n**Status:** resolved`}]}}default:throw Error("Unknown operation type: "+g)}}catch(e){return h.error("document_operations failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("document_operations_errors",1),{content:[{type:"text",text:"\u274c **Document Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
|
|
3012
3025
|
const i=t(6183),a=s(t(5967)),c=t(1572),l=t(1483),d=t(8824)},5671(e,exports,t){function r(e){const[t,...r]=e.split("/")
|
|
3013
3026
|
return{provider:t||"anthropic",modelId:r.join("/")||e}}function n(e){const t={anthropic:!1,openai:!1}
|
|
3014
3027
|
try{const n=(0,a.join)(e,"opencode.json")
|
|
@@ -3029,10 +3042,10 @@ let h,g=0
|
|
|
3029
3042
|
if("one_down"===n&&(g=1),"two_down"===n&&(g=2),i===s.provider)h=u+g
|
|
3030
3043
|
else{const e=l.length>1?u/(l.length-1):0
|
|
3031
3044
|
h=Math.round(e*(d.length-1))+g}h=Math.min(h,d.length-1),h=Math.max(h,0)
|
|
3032
|
-
const
|
|
3033
|
-
let
|
|
3045
|
+
const f=d[h]
|
|
3046
|
+
let p
|
|
3034
3047
|
var m,y
|
|
3035
|
-
return i===s.provider?(m=a,y=p
|
|
3048
|
+
return i===s.provider?(m=a,y=f,p=s.modelId.replace(m,y)):p=f,{provider:i,modelId:p,fullModel:`${i}/${p}`,resolved:!0}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseModelString=r,exports.getAvailableProviders=n,exports.getMainSessionModel=o,exports.resolveModelTier=s,exports.resolveAgentModel=function(e,t="inherit",i="same"){const a=o(e)
|
|
3036
3049
|
if(!a)return{provider:"anthropic",modelId:"claude-sonnet-4-5",fullModel:"anthropic/claude-sonnet-4-5",resolved:!1,reason:"Could not determine main session model, using default"}
|
|
3037
3050
|
if("inherit"===t&&"same"===i){const e=r(a)
|
|
3038
3051
|
return{provider:e.provider,modelId:e.modelId,fullModel:a,resolved:!0}}return s(a,t,i,n(e))}
|
|
@@ -3055,55 +3068,25 @@ if(t){const e=Date.now()-t
|
|
|
3055
3068
|
try{this.metrics.observeHistogram("offline_duration_ms",e,{reconnection_type:"manual"}),this.logger.info(`System was offline for ${Math.round(e/1e3)} seconds before manual reconnection`)}catch(e){this.logger.warn("Error observing histogram for offline duration on manual reconnection",{error:e instanceof Error?e.message:e+""})}}}}catch(e){this.logger.warn("Error calculating offline duration during manual mode change",{error:(0,s.getErrorMessage)(e)})}this.notifyOnlineStatus()}else!t&&e&&(this.logger.info("Manually setting connection mode to OFFLINE"),this.safeSetGauge("connection_status",0),this.safeSetGauge("last_connection_failure_timestamp",Date.now()),this.safeIncrementCounter("manual_disconnections",1),process.nextTick((()=>{exports.eventBus.emit(exports.EVENTS.OFFLINE,{timestamp:(new Date).toISOString()})})))}isOffline(){return this.isInOfflineMode()}async checkConnectivity(){return this.logger.debug("Explicit connectivity check requested"),this.healthCheckManager.requestHealthCheck()}getHealthCheckStats(){const e=this.healthCheckManager.getStats()
|
|
3056
3069
|
return{isOffline:this.isInOfflineMode(),consecutiveFailures:e.consecutiveFailures,currentBackoffMs:e.currentBackoffMs,lastCheckTime:e.lastCheckTime}}cleanup(){this.logger.debug("Cleaning up connection status manager resources"),this.healthCheckManager.stopHealthChecks(),exports.eventBus.removeAllListeners(exports.EVENTS.ONLINE),exports.eventBus.removeAllListeners(exports.EVENTS.OFFLINE)}}},5692(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3057
3070
|
const r=t(6183),n=t(2965)
|
|
3058
|
-
exports.def={name:"read_files",description:'Read the contents of multiple files and documents with flexible line selection.\n\nLINE SELECTION (string format):\n- Single line: "lines": "5"\n- Multiple lines: "lines": "1,3,7,10"\n- Range: "lines": "5-15"\n- Entire file: omit "lines" parameter\n\nEXAMPLES:\n- Read first 10 lines: {"path": "file.txt", "lines": "1-10"}\n- Read specific lines: {"path": "file.txt", "lines": "1,5,25"}\n- Read line 42 only: {"path": "file.txt", "lines": "42"}\n- Read entire file: {"path": "file.txt"}\n\nSupports both filesystem files (using \'path\') and tracked documents (using \'documentId\'). More efficient than reading files one by one. Failed reads won\'t stop the entire operation.',schema:r.ReadFilesSchema,annotations:{title:"Read Files/Documents",readOnlyHint:!0},readOnly:!0,handler(e,t){return(0,n.handleReadFiles)(e,t.context,t.logger,t.metrics)}}},5715(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteRequest=async function(e,t,l,d,u,h
|
|
3059
|
-
try{const{requestId:o,summary:s
|
|
3071
|
+
exports.def={name:"read_files",description:'Read the contents of multiple files and documents with flexible line selection.\n\nLINE SELECTION (string format):\n- Single line: "lines": "5"\n- Multiple lines: "lines": "1,3,7,10"\n- Range: "lines": "5-15"\n- Entire file: omit "lines" parameter\n\nEXAMPLES:\n- Read first 10 lines: {"path": "file.txt", "lines": "1-10"}\n- Read specific lines: {"path": "file.txt", "lines": "1,5,25"}\n- Read line 42 only: {"path": "file.txt", "lines": "42"}\n- Read entire file: {"path": "file.txt"}\n\nSupports both filesystem files (using \'path\') and tracked documents (using \'documentId\'). More efficient than reading files one by one. Failed reads won\'t stop the entire operation.',schema:r.ReadFilesSchema,annotations:{title:"Read Files/Documents",readOnlyHint:!0},readOnly:!0,handler(e,t){return(0,n.handleReadFiles)(e,t.context,t.logger,t.metrics)}}},5715(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteRequest=async function(e,t,c,l,d,u,h){const g=l.child({tool:"complete_request"}),f=d.startTimer("tool_execution_time")
|
|
3072
|
+
try{const{requestId:o,summary:s}=e
|
|
3060
3073
|
if(!o)throw(0,r.createValidationError)("Request ID is required")
|
|
3061
3074
|
if(!s)throw(0,r.createValidationError)("Summary is required")
|
|
3062
|
-
|
|
3063
|
-
const h
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
let
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
return
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
let
|
|
3074
|
-
|
|
3075
|
-
return
|
|
3076
|
-
|
|
3077
|
-
return f({success:!1,error:"no_tasks_completion_failure"}),{content:[{type:"text",text:"Failed to complete request with no tasks: "+t}],isError:!0}}}let k={merged:!1,deleted:!1,method:"",message:""}
|
|
3078
|
-
if("revert-removal"===y.mergeStrategy&&y.revertInfo){if(p.info("Using revert removal strategy",{requestId:o,revertCommitHash:y.revertInfo.revertCommitHash.substring(0,8)}),t.git&&y.revertInfo.revertCommitHash){const e=await(0,a.hasMainChangedSinceRevert)(t.git,y.revertInfo.revertCommitHash,p,u)
|
|
3079
|
-
if(e.hasChanged)return f({success:!1,reason:"main_changed_since_revert"}),{content:[{type:"text",text:`Cannot re-complete reverted request: Main branch has changed since revert\n\n${e.message}\n\nCreate a new request to implement the desired changes.`}],isError:!0}}try{const e=(await t.git.raw(["rev-parse",y.revertInfo.revertCommitHash+"^"])).trim()
|
|
3080
|
-
await t.git.reset(["--hard",e])
|
|
3081
|
-
const r=await t.git.revparse(["HEAD"])
|
|
3082
|
-
if(r.trim()!==e)throw Error(`Git reset verification failed: expected ${e.substring(0,8)}, got ${r.substring(0,8)}`)
|
|
3083
|
-
w={mergeCommitHash:r.trim(),mergedFiles:[],cleanedUp:!1},k={merged:!0,deleted:!1,method:"revert-removal",message:"Removed revert commit "+y.revertInfo.revertCommitHash.substring(0,8)},p.info("Revert removal succeeded",{requestId:o,newHead:r.trim().substring(0,8)})}catch(e){const t=(0,c.getErrorMessage)(e)
|
|
3084
|
-
return f({success:!1,reason:"revert_removal_failed"}),{content:[{type:"text",text:"Failed to re-complete reverted request: "+t}],isError:!0}}}const b=l.getRequestClient(),I=await b.getRequest(o)
|
|
3085
|
-
if(!w&&"conflicted"===I?.status){p.info("Request is conflicted, attempting fast-path merge",{requestId:o})
|
|
3086
|
-
const e=t.workspaceManager?.getCurrentContext()
|
|
3087
|
-
let r=e?.basePath||process.cwd()
|
|
3088
|
-
if("multi-agent"===e?.mode&&t.workspaceManager)try{const e=await t.workspaceManager.getWorktreeInfo(o)
|
|
3089
|
-
e?.worktreePath&&(r=e.worktreePath)}catch{}const n=(0,i.createConflictResolutionManager)(p,l,r,t.git),s=await n.validateMarkersRemoved(o)
|
|
3090
|
-
if(!s.resolved)return{content:[{type:"text",text:`## \u26a0\ufe0f Conflicts Still Need Resolution\n\nConflict markers still exist in:\n\n${s.remainingConflicts.map((e=>`- \`${e}\``)).join("\n")}\n\nRemove all conflict markers and try again.`}]}
|
|
3091
|
-
const a=await n.hasMainBranchChanged(o)
|
|
3092
|
-
if(a.hasChanged&&a.canDetermine)p.info("Main branch changed since conflict detection, skipping fast-path",{requestId:o,originalHash:a.originalHash?.substring(0,8),currentHash:a.currentHash?.substring(0,8)})
|
|
3093
|
-
else try{const e=await async function(e,t,r){r.info("Executing branch-version merge for resolved conflicts",{requestId:e})
|
|
3094
|
-
try{return await t.completeRequest(e,"Request "+e,{skipConflictDetection:!0})}catch(t){throw r.warn("Branch-version merge failed",{requestId:e,error:(0,c.getErrorMessage)(t)}),t}}(o,t.workspaceManager,p)
|
|
3095
|
-
w=e,k={merged:!0,deleted:e.cleanedUp,method:"conflict-fast-path",message:"Fast-path branch-version merge after conflict resolution"}}catch(e){const t=(0,c.getErrorMessage)(e)
|
|
3096
|
-
return f({success:!1,reason:"conflict_fast_path_failed"}),{content:[{type:"text",text:"Fast-path merge failed: "+t}],isError:!0}}}if(!w){if(p.info("Normal merge via WorkspaceManager",{requestId:o}),!t.workspaceManager)return f({success:!1,error:"no_workspace_manager"}),{content:[{type:"text",text:"WorkspaceManager not available for request completion"}],isError:!0}
|
|
3097
|
-
const e=t.workspaceManager.getCurrentContext()
|
|
3098
|
-
if(!e.requestId||e.requestId!==o)try{await t.workspaceManager.ensureWorkspaceReady(o)}catch(e){return f({success:!1,error:"workspace_switch_failed"}),{content:[{type:"text",text:`Cannot complete request ${o}: ${(0,c.getErrorMessage)(e)}`}],isError:!0}}try{w=await t.workspaceManager.completeRequest(o,"Request "+o),k={merged:!0,deleted:w.cleanedUp,method:w.autoMergeInfo?.strategy||"workspace-manager",message:w.autoMergeInfo?.wasAutoMerged?"Auto-merged using "+w.autoMergeInfo.strategy:"Merged via WorkspaceManager"}}catch(e){if(e.conflictInfo){const r=e.conflictInfo,n=r.workingDirectory||t.workspaceManager.getCurrentContext()?.basePath||process.cwd(),s=(0,i.createConflictResolutionManager)(p,l,n,t.git)
|
|
3099
|
-
let a
|
|
3100
|
-
if("conflicted"===I?.status)try{a=await s.updateConflictResolution(o,r)}catch{a=await s.handleConflicts(r)}else a=await s.handleConflicts(r)
|
|
3101
|
-
return f({success:!1,reason:"merge_conflicts_handled"}),{content:[{type:"text",text:a.userMessage}],isError:!1}}const r=(0,c.getErrorMessage)(e)
|
|
3102
|
-
return f({success:!1,error:"merge_failure"}),{content:[{type:"text",text:"Request completion failed during merge: "+r}],isError:!0}}}try{await l.proxyPost(`/api/projects/${t.projectId}/requests/${o}/finalize-completion`,{summary:s,acceptanceEvidence:d,mergeResult:{mergeCommitHash:w.mergeCommitHash,mergedFiles:w.mergedFiles,cleanedUp:w.cleanedUp,method:k.method}})}catch(e){const t=(0,c.getErrorMessage)(e)
|
|
3103
|
-
return p.error("CRITICAL: Merge succeeded but server finalization failed",{requestId:o,mergeCommitHash:w.mergeCommitHash,error:t}),f({success:!1,error:"api_update_failed"}),{content:[{type:"text",text:`CRITICAL: Code was successfully merged (commit: ${w.mergeCommitHash.substring(0,8)}) but failed to update request status: ${t}`}],isError:!0}}return f({success:!0}),{content:[{type:"text",text:"Request completed: "+o}]}}catch(r){let n="An unexpected error occurred",i=""
|
|
3104
|
-
r instanceof o.ZodError?(n="Validation error",i=r.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")):r instanceof Error?(n=r.message,i=r.stack||""):i=r+"",p.error("Complete request failed",{error:n,details:i})
|
|
3105
|
-
try{await(0,s.createFailureToolRecord)("complete-request",r,{error:n,details:i,requestId:e?.requestId},l.getToolRecordClient(),p,u,{requestId:e?.requestId,projectId:t.projectId,note:"Failed to complete request"})}catch{}return f({success:!1,error:r instanceof Error?r.name:"unknown"}),{content:[{type:"text",text:"Error: "+n}],isError:!0}}}
|
|
3106
|
-
const r=t(9860),n=t(715),o=t(1569),s=t(8616),i=t(1651),a=t(7478),c=t(8824)},5767(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3075
|
+
g.info("Starting request completion",{requestId:o})
|
|
3076
|
+
const l=h?.sessionId||(0,n.getCachedSession)()?.sessionId
|
|
3077
|
+
let d
|
|
3078
|
+
try{const e=await c.proxyPost(`/api/projects/${t.projectId}/requests/${o}/validate-completion`,{sessionId:l})
|
|
3079
|
+
d=e?.data||e}catch(e){const t=(0,i.getErrorMessage)(e)
|
|
3080
|
+
return g.error("Server validation failed",{requestId:o,error:t}),f({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate completion: "+t}],isError:!0}}if(!d.canComplete){let e=`Cannot complete request ${o}: ${d.reason}\n`
|
|
3081
|
+
return d.blockedByTasks&&d.blockedByTasks.length>0&&(e+="\n**Tasks that must be completed or canceled first:**\n",d.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (Status: ${t.status})\n`}))),d.lifoViolation&&(e+="\n**Requests that must be re-completed first (LIFO order):**\n",d.lifoViolation.blockingRequests.forEach(((t,r)=>{e+=`${r+1}. **${t.requestId}** - ${t.title} (Status: ${t.status})\n`}))),f({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}const u=c.getRequestClient(),p="auto-test-then-merge"===d.completionMode,m=p?"ready_for_review":"ready_for_merge"
|
|
3082
|
+
try{await u.updateRequest(o,{status:m,completionSummary:s})}catch(e){const t=(0,i.getErrorMessage)(e)
|
|
3083
|
+
return f({success:!1,error:"status_transition_failed"}),{content:[{type:"text",text:"Failed to transition request: "+t}],isError:!0}}let y
|
|
3084
|
+
try{y=await u.getRequest(o)}catch(e){const t=(0,i.getErrorMessage)(e)
|
|
3085
|
+
return f({success:!1,error:"fetch_request_failed"}),{content:[{type:"text",text:"Failed to fetch request criteria: "+t}],isError:!0}}const w=y?.acceptanceCriteria||[]
|
|
3086
|
+
return f({success:!0}),p?{content:[{type:"text",text:`Request ${o} moved to ready_for_review. Testing is active \u2014 a notification has been created for the user to choose testing mode. Do NOT call merge or any other tool. Your work is done. Stop here and wait.`}]}:0===w.length?{content:[{type:"text",text:`Request ${o} is ready. No acceptance criteria defined \u2014 call merge directly.`}]}:{content:[{type:"text",text:`Request ${o} completion started (${m}).\n\n## Next Step: Verify & Merge\n\n${(0,a.formatVerifyInstructions)(w)}\n\nUse the merge operation with your verification evidence to merge to main.`}]}}catch(r){let n="An unexpected error occurred",i=""
|
|
3087
|
+
r instanceof o.ZodError?(n="Validation error",i=r.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")):r instanceof Error?(n=r.message,i=r.stack||""):i=r+"",g.error("Complete request failed",{error:n,details:i})
|
|
3088
|
+
try{await(0,s.createFailureToolRecord)("complete-request",r,{error:n,details:i,requestId:e?.requestId},c.getToolRecordClient(),g,d,{requestId:e?.requestId,projectId:t.projectId,note:"Failed to complete request"})}catch{}return d.startTimer("tool_execution_time")({success:!1,error:r instanceof Error?r.name:"unknown"}),{content:[{type:"text",text:"Error: "+n}],isError:!0}}}
|
|
3089
|
+
const r=t(9860),n=t(715),o=t(1569),s=t(8616),i=t(8824),a=t(5454)},5767(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3107
3090
|
const r=t(6183),n=t(6285)
|
|
3108
3091
|
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){module.exports=require("@modelcontextprotocol/sdk/server/stdio.js")},5806(e,exports,t){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())}))})
|
|
3109
3092
|
return(0,o.areTestsRequiredForCompletion)()?e.extend({testVerification:t}):e}Object.defineProperty(exports,"__esModule",{value:!0}),exports.DynamicCompleteRequestSchema=void 0,exports.getDynamicCompleteRequestSchema=r
|
|
@@ -3137,9 +3120,9 @@ i.info("Initial branch context",{initialBranch:P.branch,initialRequestId:P.reque
|
|
|
3137
3120
|
const x=[]
|
|
3138
3121
|
for(const e of T){const{normalizedPath:r,fullPath:n}=l.validateAndNormalizePath(e.target,t)
|
|
3139
3122
|
x.push({normalized:r,full:n})}k=l.FileOperationPhase.TASK_VALIDATION,o.incrementCounter("delete_files_phase",1,{phase:k})
|
|
3140
|
-
const O=x.length>0?x[0].normalized:"document_operations",j=await l.validateTaskId(C,O,n,i,o,b.metricsPrefix),$=j?.requestId,
|
|
3141
|
-
|
|
3142
|
-
const F=await l.ensureCorrectWorkspaceContext({taskPromoted:
|
|
3123
|
+
const O=x.length>0?x[0].normalized:"document_operations",j=await l.validateTaskId(C,O,n,i,o,b.metricsPrefix),$=j?.requestId,D=await l.validateWorkItemStates(C,O,n,I,t,i,o,b.metricsPrefix),A=await l.autoPromoteTaskStatus(C,j.status,$,D.request?.status,O,n,I,i,o,b.metricsPrefix)
|
|
3124
|
+
A.taskPromoted&&i.info(`Auto-promoted task ${C} (${j.title||"Untitled"}) to in_progress for mixed operations`,{taskId:C,taskTitle:j.title,previousStatus:j.status,newStatus:A.newTaskStatus,totalOperations:S.length,fileOperations:T.length,documentOperations:M.length}),A.requestPromoted&&i.info(`Auto-promoted request ${$} to in_progress for file operations`,{requestId:$,previousStatus:D.request?.status,newStatus:A.newRequestStatus,triggeringTaskId:C})
|
|
3125
|
+
const F=await l.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:$,context:t,operation:"delete-files",logger:i,metrics:o,metricsPrefix:b.metricsPrefix})
|
|
3143
3126
|
if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
|
|
3144
3127
|
throw Error(F.error)}let N={hadUserMods:!1,userModsCommitHash:void 0}
|
|
3145
3128
|
if(t.git)try{i.debug("[DELETE-FILES] Checking for user changes before mixed delete operations")
|
|
@@ -3152,14 +3135,14 @@ let H=0
|
|
|
3152
3135
|
M.length>0&&r.setProjectId(t.projectId)
|
|
3153
3136
|
for(let e=0;e<x.length;e++){const t=x[e],r={type:"file",path:t.normalized,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
3154
3137
|
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)
|
|
3155
|
-
await a.default.unlink(t.full),r.success=!0,H++,i.info("Successfully deleted file",{path:t.normalized})}catch(e){r.error=(0,
|
|
3138
|
+
await a.default.unlink(t.full),r.success=!0,H++,i.info("Successfully deleted file",{path:t.normalized})}catch(e){r.error=(0,p.getErrorMessage)(e),i.warn("Failed to delete file "+t.normalized,{error:r.error})}B.push(r)}const W=M.length>0?r.getDocumentClient():null
|
|
3156
3139
|
for(const e of M){const t=e.target,n={type:"document",documentId:t,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
3157
3140
|
try{let e
|
|
3158
|
-
try{if(e=await
|
|
3159
|
-
throw e}try{await(0,
|
|
3160
|
-
throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,
|
|
3161
|
-
n.success=!0,n.filename=s.filename,H++,i.info("Document archived successfully",{documentId:s.id,filename:s.filename,archivedAt:s.archived_at})}catch(e){n.error=(0,
|
|
3162
|
-
o.recordValue("delete_files_time",
|
|
3141
|
+
try{if(e=await W.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)
|
|
3142
|
+
throw e}try{await(0,f.ensureDocumentNotLocked)(t,r,i,o,"delete-document-archive")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
|
|
3143
|
+
throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,p.getErrorMessage)(e)}`)}const s=await W.archiveDocument(t)
|
|
3144
|
+
n.success=!0,n.filename=s.filename,H++,i.info("Document archived successfully",{documentId:s.id,filename:s.filename,archivedAt:s.archived_at})}catch(e){n.error=(0,p.getErrorMessage)(e),i.warn("Failed to delete document "+t,{error:n.error})}B.push(n)}const U=Date.now()-m
|
|
3145
|
+
o.recordValue("delete_files_time",U),o.incrementCounter("delete_files_operations_total",R),o.incrementCounter("delete_files_operations_success",H),o.incrementCounter("delete_files_operations_failed",R-H),o.incrementCounter("delete_files_file_operations",T.length),o.incrementCounter("delete_files_document_operations",M.length),H===R?o.incrementCounter("delete_files_success",1):H>0?o.incrementCounter("delete_files_partial_success",1):o.incrementCounter("delete_files_total_failure",1)
|
|
3163
3146
|
let G=null
|
|
3164
3147
|
if(H>0){k=l.FileOperationPhase.GIT_COMMIT,o.incrementCounter("delete_files_phase",1,{phase:k})
|
|
3165
3148
|
const e=B.filter((e=>e.success)),r=e.filter((e=>"file"===e.type)).length,n=e.filter((e=>"document"===e.type)).length
|
|
@@ -3174,11 +3157,11 @@ Y=e>0&&t>0?`Successfully deleted ${e} files and ${t} documents`:e>0?`Successfull
|
|
|
3174
3157
|
return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n"):"All delete operations failed:\n"+B.map((e=>{const t="file"===e.type?e.path:`${e.filename||e.documentId} (${e.documentId})`
|
|
3175
3158
|
return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n")
|
|
3176
3159
|
return G?.commitHash&&(Y+="\nCommit: "+G.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===H}}catch(n){if(e.taskId&&r)try{const o=r.getToolRecordClient(),s=n instanceof d.NotFoundError||n instanceof d.ValidationError||n instanceof u.ZodError
|
|
3177
|
-
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,
|
|
3178
|
-
if(o.recordValue("delete_files_time",s),o.incrementCounter("delete_files_errors",1),i.error("Error in delete-files operation:",{error:(0,
|
|
3160
|
+
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,p.getErrorMessage)(n),errorDetails:n instanceof Error?n.stack:n+"",phase:k,attemptedTaskId:e.taskId,taskIdValidationFailed:s},note:"Failed to delete files - "+(0,p.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
|
|
3161
|
+
if(o.recordValue("delete_files_time",s),o.incrementCounter("delete_files_errors",1),i.error("Error in delete-files operation:",{error:(0,p.getErrorMessage)(n),time:s}),(y||w)&&e.taskId){k=l.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
3179
3162
|
try{const t=r.getTaskClient(),s=r.getToolRecordClient()
|
|
3180
|
-
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,
|
|
3181
|
-
const a=i(t(1943)),c=t(6183),l=s(t(5967)),d=t(9860),u=t(1569),h=t(7478),g=t(5003),
|
|
3163
|
+
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,p.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)}}
|
|
3164
|
+
const a=i(t(1943)),c=t(6183),l=s(t(5967)),d=t(9860),u=t(1569),h=t(7478),g=t(5003),f=t(9949),p=t(8824)},5997(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
3182
3165
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
3183
3166
|
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=[]
|
|
3184
3167
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -3237,21 +3220,19 @@ const n=await this.requestWithRetry("POST","/api/files/recover",t)
|
|
|
3237
3220
|
if(!(0,i.safeGetResponseData)(n,null))throw new r.ServiceError("Empty response when recovering file")
|
|
3238
3221
|
const o=(0,i.safeGetResponseData)(n,{success:!0,path:e.path,commitHash:e.commitHash,backupPath:void 0})
|
|
3239
3222
|
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){Object.defineProperty(exports,"__esModule",{value:!0}),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.ReplaceInFileSchema=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.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=exports.SwitchToMainBranchSchema=void 0
|
|
3240
|
-
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)"}),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)"})
|
|
3241
|
-
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","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.ReplaceInFileSchema=exports.ReplaceInFilesSchema,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({
|
|
3242
|
-
return"get-info"===e.operation?!t&&r&&!n:"list"===e.operation&&!r&&n}),{message:"Invalid operation data"})
|
|
3223
|
+
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)"})
|
|
3224
|
+
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.ReplaceInFileSchema=exports.ReplaceInFilesSchema,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" }'})}))
|
|
3243
3225
|
const a=r.z.string().min(1).describe("OpenCode session ID")
|
|
3244
3226
|
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
|
|
3245
3227
|
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(100).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(100).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
|
|
3246
3228
|
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
|
|
3247
|
-
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"]),
|
|
3229
|
+
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"})}))
|
|
3248
3230
|
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)"})
|
|
3249
|
-
exports.PlanReadSchema=r.z.object({operation:r.z.enum(["get","get-active","list","get-history","get-requests"]),
|
|
3250
|
-
|
|
3251
|
-
if(
|
|
3252
|
-
const
|
|
3253
|
-
|
|
3254
|
-
return"complete"===e.operation?t&&!r&&!n&&!o&&!s&&!i&&a:"finalize"===e.operation?!t&&!n&&!o&&!s&&!i&&a:"approve"===e.operation?!t&&!r&&!o&&!s&&!i&&a:"revert"===e.operation?o&&!t&&!r&&!n&&!s&&!i&&a:"get-info"===e.operation?!t&&!r&&!n&&!o&&!s&&!i&&a:"list"===e.operation?!(t||r||n||o||i):"search"===e.operation&&i&&!t&&!r&&!n&&!o&&!s}),{message:"Invalid operation data"}),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")})
|
|
3231
|
+
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
|
|
3232
|
+
"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"]),complete:r.z.object({summary:r.z.string()}).optional(),merge: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
|
|
3233
|
+
if(["complete","merge","approve","revert","get-info"].includes(n)&&!r)return void t.addIssue({code:"custom",message:`requestId is required for '${n}' operation`})
|
|
3234
|
+
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]
|
|
3235
|
+
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")})
|
|
3255
3236
|
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)")})
|
|
3256
3237
|
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"})},6252(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3257
3238
|
const r=t(6183),n=t(405)
|
|
@@ -3263,13 +3244,13 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3263
3244
|
var t={}
|
|
3264
3245
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3265
3246
|
return o(t,e),t})
|
|
3266
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,
|
|
3247
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,p){const m=n.child({tool:"specialist_ops"}),y=o.startTimer("tool_execution_time")
|
|
3267
3248
|
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")),"string"==typeof e?.delegate){const t=e.delegate
|
|
3268
3249
|
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)
|
|
3269
3250
|
const n=c.validateArgs(e,a.SpecialistOpsSchema),{operation:w,sessionId:k}=n
|
|
3270
3251
|
let b
|
|
3271
3252
|
switch(m.info("Processing specialist_ops",{operation:w,sessionId:k}),w){case"delegate":{const e=n.delegate,o=10
|
|
3272
|
-
let i=
|
|
3253
|
+
let i=p?.sessionId||f.sessionIdentity.getIdentity()?.sessionId
|
|
3273
3254
|
if(!i){const e=await(0,h.getServerUrl)(r,m)
|
|
3274
3255
|
if(e)try{i=(0,g.getCachedSession)()?.sessionId||await(0,h.discoverParentSessionId)(e,m)}catch{}}if(i&&s){const e=await async function(e,t,r,n,o){n.info("enforcePoolLimit called",{parentSessionId:e,maxPoolSize:t})
|
|
3275
3256
|
const s=await(0,h.getServerUrl)(r,n)
|
|
@@ -3295,23 +3276,23 @@ y(`siblings=${e.length}: ${e.join(", ")}`)
|
|
|
3295
3276
|
const r=(0,d.pickSpecialistName)(e)
|
|
3296
3277
|
a=r,y("picked name: "+r)}}else y("no serverUrl")}catch(e){y("error: "+(e instanceof Error?e.message:e+""))}else y("no parentId")
|
|
3297
3278
|
const w=e.requestId,k=w?`Working on request ${w}.\n\n${e.prompt}`:e.prompt
|
|
3298
|
-
b=await(0,u.handleSpawn)({agent:"specialist",prompt:k,title:a,specialization:e.specialization},r,m,s,
|
|
3279
|
+
b=await(0,u.handleSpawn)({agent:"specialist",prompt:k,title:a,specialization:e.specialization},r,m,s,p)
|
|
3299
3280
|
break}case"follow-up":{const e=await(0,h.getServerUrl)(r,m)
|
|
3300
3281
|
if(e)try{const t=await fetch(e.replace(/\/$/,"")+"/session/status")
|
|
3301
3282
|
if(t.ok){const e=await t.json(),r=e[k]?.type
|
|
3302
3283
|
if(r&&"idle"!==r&&"prompting"!==r){b={content:[{type:"text",text:`\u274c Specialist ${k} is currently busy (status: ${r}).\nUse \`delegate\` to spawn a new specialist instead.`}],isError:!0}
|
|
3303
|
-
break}}}catch{}b=await(0,u.handleContinue)(k,n.followUp.prompt,r,m,s,"specialist",
|
|
3284
|
+
break}}}catch{}b=await(0,u.handleContinue)(k,n.followUp.prompt,r,m,s,"specialist",p)
|
|
3304
3285
|
const t=n.followUp.specialization
|
|
3305
3286
|
if(t&&s)try{const e=s.getCLISessionClient()
|
|
3306
3287
|
e&&(await e.createOrUpdateSession({externalSessionId:k,specialization:t}),b.content[0].text+="\nSpecialization updated to: "+t)}catch{}break}case"check-status":b=await(0,u.handleCheckStatus)(k,r,m,s)
|
|
3307
3288
|
break
|
|
3308
3289
|
case"abort":if(b=await(0,u.handleAbort)(k,r,m),!b.isError&&s)try{const e=s.getCLISessionClient()
|
|
3309
3290
|
e&&await e.createOrUpdateSession({externalSessionId:k,status:"archived"})}catch{}break
|
|
3310
|
-
case"list":{let e=
|
|
3291
|
+
case"list":{let e=p?.sessionId||f.sessionIdentity.getIdentity()?.sessionId
|
|
3311
3292
|
if(!e){const t=await(0,h.getServerUrl)(r,m)
|
|
3312
3293
|
if(t)try{e=(0,g.getCachedSession)()?.sessionId||await(0,h.discoverParentSessionId)(t,m)}catch{}}b=await(0,u.handleListSessions)(r,m,s,{activeOnly:n.list?.activeOnly,requestId:n.list?.requestId,limit:n.list?.limit,agentType:"specialist",parentSessionId:e})
|
|
3313
3294
|
break}default:throw new i.ValidationError("Unknown operation: "+w)}return y({success:!0}),o.incrementCounter(`specialist_ops_${w}_success`,1),b}catch(e){return m.error("Specialist ops failed",{error:e instanceof Error?e.stack:e+""}),y({success:!1}),o.incrementCounter("specialist_ops_errors",1),{content:[{type:"text",text:"Specialist operation failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
|
|
3314
|
-
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(715),
|
|
3295
|
+
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(715),f=t(6688)},6315(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3315
3296
|
const r=t(6183),n=t(2982)
|
|
3316
3297
|
exports.def={name:"generate_request_journal",description:"Fetch comprehensive data about a request for writing a journal entry.\n\nReturns structured data including:\n\u2022 Request details (title, description, type, status, acceptance criteria)\n\u2022 All tasks with descriptions and status\n\u2022 File changes summary (files modified, operations performed)\n\u2022 Chronological operation history\n\nUse this data to write a narrative journal entry and save it as:\nJOURNAL-{requestId}.md using document-operations (create).",schema:r.GenerateRequestJournalSchema,annotations:{title:"Generate Request Journal",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0},readOnly:!0,hidden(){return"journal"!==process.env.ALCHEMY_MODE},handler(e,t){return(0,n.handleGenerateRequestJournal)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},6416(e,exports,t){var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
3317
3298
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
@@ -3322,17 +3303,17 @@ var t={}
|
|
|
3322
3303
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3323
3304
|
return o(t,e),t})
|
|
3324
3305
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRevertRequest=async function(e,t,r,n,o){const s=n.child({tool:"revert_request"}),h=o.startTimer("tool_execution_time")
|
|
3325
|
-
try{const n=i.RevertRequestSchema.parse(e),{requestId:d,reason:g,confirmDestructive:
|
|
3326
|
-
if(s.info("Starting revert/cancel process",{requestId:d,reason:g}),!
|
|
3327
|
-
let
|
|
3306
|
+
try{const n=i.RevertRequestSchema.parse(e),{requestId:d,reason:g,confirmDestructive:f}=n
|
|
3307
|
+
if(s.info("Starting revert/cancel process",{requestId:d,reason:g}),!f)return h({success:!1,reason:"confirmation_required"}),{content:[{type:"text",text:"Error: This operation requires confirmation. Set confirmDestructive: true to proceed.\n\nThis tool will:\n- **For open/in_progress requests:** Cancel the request (no git changes)\n- **For completed requests:** Revert using git (affects git history)\n\nBoth operations make the request read-only and block further tool use."}],isError:!0}
|
|
3308
|
+
let p
|
|
3328
3309
|
try{const e=await r.proxyPost(`/api/projects/${t.projectId}/requests/${d}/validate-revert`,{})
|
|
3329
|
-
|
|
3330
|
-
return s.error("Server validation failed",{requestId:d,error:t}),h({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate revert: "+t}],isError:!0}}if(s.info("Server validation result",{requestId:d,canRevert:
|
|
3331
|
-
return
|
|
3332
|
-
try{return await r.proxyPost(`/api/projects/${t.projectId}/requests/${d}/finalize-revert`,{reason:g,operationType:"cancel"}),h({success:!0}),{content:[{type:"text",text:`Successfully canceled request ${d}.\n\nOperation: Cancel (no git changes)\nTasks updated: ${
|
|
3310
|
+
p=e?.data||e}catch(e){const t=(0,u.getErrorMessage)(e)
|
|
3311
|
+
return s.error("Server validation failed",{requestId:d,error:t}),h({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate revert: "+t}],isError:!0}}if(s.info("Server validation result",{requestId:d,canRevert:p.canRevert,operationType:p.operationType,mergeCommitHash:p.mergeCommitHash?.substring(0,8),reason:p.reason}),!p.canRevert){let e=`Cannot revert request ${d}: ${p.reason}\n`
|
|
3312
|
+
return p.lifoViolation?.blockingRequests?.length&&(e+="\n**Requests that must be reverted first (in reverse order):**\n",p.lifoViolation.blockingRequests.forEach(((t,r)=>{e+=`${r+1}. **${t.requestId}** - ${t.title} (${t.status})\n`})),e+="\n**Why:** Requests must be reverted in reverse order (LIFO) to maintain safe git history.\n",e+="Revert the above request(s) first, then retry this one."),h({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}if("cancel"===p.operationType){s.info("Cancel operation \u2014 delegating to server",{requestId:d})
|
|
3313
|
+
try{return await r.proxyPost(`/api/projects/${t.projectId}/requests/${d}/finalize-revert`,{reason:g,operationType:"cancel"}),h({success:!0}),{content:[{type:"text",text:`Successfully canceled request ${d}.\n\nOperation: Cancel (no git changes)\nTasks updated: ${p.tasksToUpdate.length} task(s) marked as canceled\nReason: ${g}`}]}}catch(e){const t=(0,u.getErrorMessage)(e)
|
|
3333
3314
|
return h({success:!1,error:"cancel_finalization_failed"}),{content:[{type:"text",text:"Failed to cancel request: "+t}],isError:!0}}}if(s.info("Revert operation \u2014 performing git revert",{requestId:d}),!t.git)throw(0,a.createServiceError)("Git repository not available for revert",{requestId:d})
|
|
3334
3315
|
t.syncBranchState&&await t.syncBranchState()
|
|
3335
|
-
let m=
|
|
3316
|
+
let m=p.mergeCommitHash
|
|
3336
3317
|
if(!m){s.info("No merge commit hash from server, searching git log",{requestId:d})
|
|
3337
3318
|
const e=await async function(e,t,r){try{const r=t.workspaceManager.getMainGit(),n=await r.raw(["log","--merges","--format=%H %s","HEAD"]),o=n.trim()?n.trim().split("\n").map((e=>{const t=e.indexOf(" ")
|
|
3338
3319
|
return-1===t?{hash:e,message:""}:{hash:e.substring(0,t),message:e.substring(t+1)}})):[],s=c.generateMergeMessagePatterns(e)
|
|
@@ -3348,7 +3329,7 @@ try{s.info("Executing git revert",{mergeCommitHash:m.substring(0,8)}),await y.ra
|
|
|
3348
3329
|
const e=await(0,l.verifyGitStateConsistency)(y,k,s,`revert-request-${d}-verification`)
|
|
3349
3330
|
e.consistent||s.error("Git state inconsistency after revert",{issues:e.issues}),s.info("Git revert completed",{requestId:d,originalMergeCommit:m.substring(0,8),revertCommitHash:k.substring(0,8)})}catch(e){const t=(0,u.getErrorMessage)(e)
|
|
3350
3331
|
return s.error("Git revert failed",{requestId:d,error:t}),h({success:!1,error:"git_revert_failed"}),{content:[{type:"text",text:"Git revert failed: "+t}],isError:!0}}try{await r.proxyPost(`/api/projects/${t.projectId}/requests/${d}/finalize-revert`,{reason:g,operationType:"revert",revertCommitHash:k,originalMergeCommitHash:m})}catch(e){const t=(0,u.getErrorMessage)(e)
|
|
3351
|
-
return s.error("CRITICAL: Git revert succeeded but server finalization failed",{requestId:d,revertCommitHash:k,error:t}),h({success:!1,error:"finalization_failed"}),{content:[{type:"text",text:`CRITICAL: Git revert succeeded (commit: ${k.substring(0,8)}) but failed to update server state: ${t}`}],isError:!0}}return h({success:!0}),{content:[{type:"text",text:`Successfully reverted request ${d}.\n\nOperation: Revert (git revert of merge commit)\nTasks updated: ${
|
|
3332
|
+
return s.error("CRITICAL: Git revert succeeded but server finalization failed",{requestId:d,revertCommitHash:k,error:t}),h({success:!1,error:"finalization_failed"}),{content:[{type:"text",text:`CRITICAL: Git revert succeeded (commit: ${k.substring(0,8)}) but failed to update server state: ${t}`}],isError:!0}}return h({success:!0}),{content:[{type:"text",text:`Successfully reverted request ${d}.\n\nOperation: Revert (git revert of merge commit)\nTasks updated: ${p.tasksToUpdate.length} task(s) marked as reverted\nReason: ${g}\n\nYou can re-complete the request if the revert was a mistake.`}]}}catch(n){if(n instanceof a.ValidationError||n instanceof a.NotFoundError)return s.warn("Revert validation failed",{error:n.message,requestId:e.requestId}),h({success:!1,error:"validation"}),{content:[{type:"text",text:"Error: "+n.message}],isError:!0}
|
|
3352
3333
|
if(n instanceof d.ZodError)return h({success:!1,error:"zod_validation"}),{content:[{type:"text",text:"Validation error: "+n.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")}],isError:!0}
|
|
3353
3334
|
if(t.projectId&&e.requestId)try{const o=r.getToolRecordClient()
|
|
3354
3335
|
await o.createToolRecord({requestId:e.requestId,projectId:t.projectId,type:"revert-request",metadata:{status:"failed",timestamp:(new Date).toISOString(),reason:e.reason,error:(0,u.getErrorMessage)(n)},note:"Failed to revert request: "+(0,u.getErrorMessage)(n)})}catch{}return s.error("Revert request failed",{error:(0,u.getErrorMessage)(n),requestId:e.requestId}),h({success:!1,error:n instanceof Error?n.name:"unknown"}),{content:[{type:"text",text:"Failed to revert request: "+(0,u.getErrorMessage)(n)}],isError:!0}}}
|
|
@@ -3369,7 +3350,7 @@ break
|
|
|
3369
3350
|
case"between":if(void 0===e.afterLine||void 0===e.beforeLine)throw Error("Both afterLine and beforeLine are required for between insertion")
|
|
3370
3351
|
n=(0,m.insertBetweenLines)(r,e.afterLine,e.beforeLine,e.content)
|
|
3371
3352
|
break
|
|
3372
|
-
default:throw Error("Unknown insertion type: "+e.type)}r=n.newContent,t.success=!0,t.linesAdded=n.linesAdded,t.insertionPoint=n.insertionPoint,o+=n.linesAdded}catch(e){t.error=(0,
|
|
3353
|
+
default:throw Error("Unknown insertion type: "+e.type)}r=n.newContent,t.success=!0,t.linesAdded=n.linesAdded,t.insertionPoint=n.insertionPoint,o+=n.linesAdded}catch(e){t.error=(0,p.getErrorMessage)(e)}n.push(t)}return{newContent:r,results:n}}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
3373
3354
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
3374
3355
|
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=[]
|
|
3375
3356
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -3390,7 +3371,7 @@ T.push({type:"file",path:r,fullPath:n,insertions:e.insertions})}const M=[]
|
|
|
3390
3371
|
if(S.length>0&&!t.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
3391
3372
|
for(const e of S)M.push({type:"document",documentId:e.documentId,insertions:e.insertions})
|
|
3392
3373
|
if(M.length>0&&t.apiClient){const e=M.map((e=>e.documentId))
|
|
3393
|
-
try{await(0,
|
|
3374
|
+
try{await(0,f.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}
|
|
3394
3375
|
throw e}}I=d.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("insert_lines_phase",1,{phase:I})
|
|
3395
3376
|
const R=T.length>0?T[0].path:"document-operation",P=await d.validateTaskId(C,R,n,y,a,v.metricsPrefix),x=P?.requestId
|
|
3396
3377
|
let O=null
|
|
@@ -3403,8 +3384,8 @@ throw Error($.error)}if(T.length>0){y.debug("Re-validating file paths with corre
|
|
|
3403
3384
|
for(let e=0;e<T.length;e++){const r=T[e],n=q[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(n.path,t)
|
|
3404
3385
|
T[e]={...r,path:o,fullPath:s}}}if(M.length>0&&x)try{await(0,h.validateRequestStatusForDocumentOperation)(x,s,y,a,"insert-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3405
3386
|
throw e}I=d.FileOperationPhase.RECORD_CREATION,a.incrementCounter("insert_lines_phase",1,{phase:I})
|
|
3406
|
-
const
|
|
3407
|
-
if(k=
|
|
3387
|
+
const D=[...T.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...M.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:A}=await d.createFileOperationRecords(C,x,t.projectId,v.recordType,R,{operationCount:_.length,fileOperations:T.length,documentOperations:M.length,operations:D,userComment:E},n,o,y,a,v.metricsPrefix,m)
|
|
3388
|
+
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")
|
|
3408
3389
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"insert-lines",{requestId:x,taskId:C,workspaceManager:t.workspaceManager},y,a)
|
|
3409
3390
|
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})
|
|
3410
3391
|
const F=[]
|
|
@@ -3412,31 +3393,31 @@ let N=0,L=0,z=0
|
|
|
3412
3393
|
for(const e of T){const t={type:"file",path:e.path,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
|
|
3413
3394
|
try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
|
|
3414
3395
|
const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.insertions)
|
|
3415
|
-
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,
|
|
3396
|
+
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,p.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 M){const n={type:"document",documentId:e.documentId,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
|
|
3416
3397
|
try{const o=await t.documentFileManager.getDocumentAsFile(e.documentId),s=t.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
3417
3398
|
n.filename=s?.filename
|
|
3418
3399
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.insertions)
|
|
3419
|
-
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,
|
|
3420
|
-
r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){y.warn("Some documents may not have synced properly",{error:e})}const B=await d.handleMultiFileGitCommit(C,T,F,z,{operationType:"Insert lines",toolRecordId:b,successField:"successfulInsertions",logger:y,metrics:a,metricsPrefix:"insert_lines"},t),H=d.processMultiFileOperationResults(F,"successfulInsertions"),{successfulOperations:
|
|
3421
|
-
try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+M[0]?.documentId,status:V?"completed":"failed",error:V?void 0:
|
|
3422
|
-
if(t.workspaceManager&&(Y+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Y+="**Summary:**\n",Y+=`- **Files processed:** ${U
|
|
3400
|
+
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,p.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(M.length>0)try{for(const e of M){const r=F.find((t=>t.documentId===e.documentId))
|
|
3401
|
+
r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){y.warn("Some documents may not have synced properly",{error:e})}const B=await d.handleMultiFileGitCommit(C,T,F,z,{operationType:"Insert lines",toolRecordId:b,successField:"successfulInsertions",logger:y,metrics:a,metricsPrefix:"insert_lines"},t),H=d.processMultiFileOperationResults(F,"successfulInsertions"),{successfulOperations:W,failedOperations:U,totalSuccessfulChanges:G,overallSuccess:V,successfulFiles:J,failedFiles:K}=H
|
|
3402
|
+
try{await o.updateToolRecord(b,{metadata:{path:T.length>0?T[0].path:"document:"+M[0]?.documentId,status:V?"completed":"failed",error:V?void 0:U+" operations failed",totalOperations:F.length,successfulFiles:J,failedFiles:K,operations:D,totalSuccessfulInsertions:G,totalFailedInsertions:N,totalLinesAdded:L,operationsWithChanges:z,processingTime:Date.now()-w,userComment:E,...T.length>0&&B.success&&B.commitHash&&{commitHash:B.commitHash,previousCommitHash:B.previousCommitHash||void 0}},note:V?`Line insertion completed: ${W}/${F.length} operations successful${T.length>0?" (committed to git)":""}`:`Line insertion partially failed: ${U}/${F.length} operations failed`})}catch(e){y.warn("Failed to update tool record",{recordError:e})}let Y="## Line Insertion Results\n\n"
|
|
3403
|
+
if(t.workspaceManager&&(Y+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Y+="**Summary:**\n",Y+=`- **Files processed:** ${W+U}\n`,Y+=`- **Successful operations:** ${W}\n`,Y+=`- **Failed operations:** ${U}\n`,Y+=`- **Total insertions:** ${G} successful, ${N} failed\n`,Y+=`- **Total Lines Added:** ${L}\n`,Y+="\n",B.success&&B.commitHash&&(Y+="**Git Commit:**\n",Y+=`- **Commit Hash:** ${B.commitHash.substring(0,8)}\n`,Y+=`- **Files Committed:** ${B.filesCommitted.length}\n`,B.previousCommitHash&&(Y+=`- **Previous Commit:** ${B.previousCommitHash.substring(0,8)}\n`),Y+="\n"),$.lockAcquired&&$.lockedRequestId&&(Y+=`\u{1f512} **Locked request:** ${$.lockedRequestId}\n\n`),1===F.length){const e=F[0]
|
|
3423
3404
|
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"
|
|
3424
3405
|
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}`
|
|
3425
|
-
Y+=`- ${t.type} insertion ${e}: ${t.error}\n`}}}else{Y+="**Summary:**\n",Y+=`- **Total Operations:** ${F.length}\n`,Y+=`- **Successful:** ${
|
|
3406
|
+
Y+=`- ${t.type} insertion ${e}: ${t.error}\n`}}}else{Y+="**Summary:**\n",Y+=`- **Total Operations:** ${F.length}\n`,Y+=`- **Successful:** ${W}\n`,Y+=`- **Failed:** ${U}\n`,Y+=`- **Total Insertions:** ${G} successful, ${N} failed\n`,Y+=`- **Total Lines Added:** ${L}\n\n`,Y+="**Detailed Results:**\n\n"
|
|
3426
3407
|
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"
|
|
3427
3408
|
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}`
|
|
3428
3409
|
Y+=` - ${t.type} insertion ${e}: ${t.error}\n`}}Y+="\n"}}M.length>0&&(Y+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3429
3410
|
const Q=Date.now()-w
|
|
3430
|
-
return y.info("Insert lines operation completed",{duration:Q,success:V,totalOperations:F.length,successfulOperations:
|
|
3431
|
-
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,
|
|
3432
|
-
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),
|
|
3433
|
-
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),
|
|
3411
|
+
return y.info("Insert lines operation completed",{duration:Q,success:V,totalOperations:F.length,successfulOperations:W,failedOperations:U}),a.incrementCounter("insert_lines_total",1,{success:V}),{content:[{type:"text",text:Y}],isError:!V}}catch(t){const r=Date.now()-w
|
|
3412
|
+
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,p.getErrorMessage)(t),phase:I,duration:r,userComment:e?.comment},note:"Line insertion failed: "+(0,p.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("insert_lines_errors",1,{phase:I}),{content:[{type:"text",text:"\u274c **Insert Lines Failed:** "+(0,p.getErrorMessage)(t)}],isError:!0}}}
|
|
3413
|
+
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),f=t(9949),p=t(8824),m=t(3255)},6539(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientFactory=void 0
|
|
3414
|
+
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),f=t(2968),p=t(922)
|
|
3434
3415
|
exports.ClientFactory=class{static async createClient(e,m,y,w={}){(m=m.child({component:"client-factory"})).info("Creating API client with components")
|
|
3435
3416
|
const k=w.tokenManager||new r.TokenManager(m,w.workingDir||process.cwd())
|
|
3436
3417
|
await k.initialize()
|
|
3437
3418
|
const b=w.tokenSynchronizer||new i.ClientTokenSynchronizer(m),I=new s.AuthenticationManager(k,m,b),v=await I.getTokenString(),C=w.connectionStatusManager||new n.ConnectionStatusManager(e,m,y,{alchemyPath:w.alchemyPath,checkIntervalMs:w.offlineCheckIntervalMs,timeoutMs:w.timeout,retryCount:w.retryAttempts}),_=new c.ProjectClient(e,m,y,C,v||void 0,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3438
3419
|
b.registerClient(_),w.alchemyPath&&_.setAlchemyPath(w.alchemyPath)
|
|
3439
|
-
const E=new
|
|
3420
|
+
const E=new f.TaskClient(e,m,y,_,C,v||void 0,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3440
3421
|
b.registerClient(E)
|
|
3441
3422
|
const q=new a.FileOperationsClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3442
3423
|
b.registerClient(q),m.info("RequestClient constructor received token: "+(v?"present":"missing"))
|
|
@@ -3444,7 +3425,7 @@ const S=new u.RequestClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts
|
|
|
3444
3425
|
b.registerClient(S),m.info("RequestClient post-constructor token: "+(S.getAuthToken()?"present":"missing"))
|
|
3445
3426
|
const T=new g.DocumentClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3446
3427
|
b.registerClient(T)
|
|
3447
|
-
const M=new
|
|
3428
|
+
const M=new p.ToolRecordClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3448
3429
|
b.registerClient(M)
|
|
3449
3430
|
const R=new d.ProxyClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3450
3431
|
if(b.registerClient(R),!w.alchemyPath)throw Error("alchemyPath is required for ProjectSynchronizer creation. Cannot create API client without project synchronization capabilities.")
|
|
@@ -3462,7 +3443,7 @@ if(E)try{await E.connectStdio(),(0,a.isDebugToolsEnabled)()&&b.info("Connected s
|
|
|
3462
3443
|
throw b.error("Failed to connect stdio transport",{errorDetails:t}),e}else b.error("No global server instance available to connect transport")
|
|
3463
3444
|
return{transport:e,shutdownHandler:t}}var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3464
3445
|
Object.defineProperty(exports,"__esModule",{value:!0})
|
|
3465
|
-
const o=t(5802),s=n(t(6928)),i=t(184),a=t(3444),c=t(1152),l=t(8851),d=t(8411),u=n(t(9896)),h=t(4139),g=t(5218),
|
|
3446
|
+
const o=t(5802),s=n(t(6928)),i=t(184),a=t(3444),c=t(1152),l=t(8851),d=t(8411),u=n(t(9896)),h=t(4139),g=t(5218),f=t(8824),p=t(9939),m=t(7960),y=process.argv.slice(2),w=y[0]||process.cwd(),k=s.default.resolve(w)
|
|
3466
3447
|
console.error("\n=== MCP STARTUP DIAGNOSTICS ==="),console.error("Script path (process.argv[1]):",process.argv[1]),console.error("Base directory:",k),console.error("ENABLE_DEBUG_TOOLS env:",process.env.ENABLE_DEBUG_TOOLS),console.error("DEBUG_LOGGING env:",process.env.DEBUG_LOGGING),console.error("isDevBuild():",(0,m.isDevBuild)()),console.error("isDebugToolsEnabled():",(0,a.isDebugToolsEnabled)()),console.error("===============================\n")
|
|
3467
3448
|
const b=(0,a.createEnvLogger)({serviceName:"direct-mcp-server",console:!0,baseDir:k});(0,a.isDebugToolsEnabled)()?b.info("MCP Direct server initializing",{baseDir:k,debugLogging:process.env.DEBUG_LOGGING,debugLevel:process.env.DEBUG_LEVEL,pid:process.pid}):b.info("MCP Direct server starting"),console.log=function(...e){console.error("[LOG]",...e)},console.info=function(...e){console.error("[INFO]",...e)},console.warn=function(...e){console.error("[WARN]",...e)},process.on("uncaughtException",(e=>{if(b.error("UNCAUGHT EXCEPTION: "+e,{stack:e.stack||"No stack available"}),E)try{E.cleanupSSEConnection()}catch(e){b.error("Error during cleanup after uncaught exception: "+e)}setTimeout((()=>process.exit(1)),500)})),process.on("unhandledRejection",(e=>{b.error("UNHANDLED REJECTION: "+e,{stack:e instanceof Error?e.stack:"No stack available"})})),process.on("exit",(e=>{b.info("Process exiting with code: "+e)}))
|
|
3468
3449
|
const I=process.stdout.write
|
|
@@ -3474,7 +3455,7 @@ const _=global.__serverInitialized
|
|
|
3474
3455
|
void 0===_?(global.__serverInitialized=!1,(0,a.isDebugToolsEnabled)()&&b.info("FIRST RUN: Setting global.__serverInitialized to false")):(0,a.isDebugToolsEnabled)()&&b.info("REUSE: global.__serverInitialized is already "+global.__serverInitialized)
|
|
3475
3456
|
let E=null
|
|
3476
3457
|
const q=(0,g.isMultiAgentModeEnabled)(k)
|
|
3477
|
-
try{(0,d.acquireProcessLock)(k,q)||(b.error(`Process lock acquisition failed for ${k}. Another instance may be running.`),b.error("This instance will exit to prevent duplicate initialization"),process.exit(1)),(0,a.isDebugToolsEnabled)()&&(q?b.info("Multi-agent mode enabled - allowing concurrent access to "+k):b.info("Successfully acquired process lock for "+k))}catch(e){b.error("Lock acquisition threw exception",{error:(0,
|
|
3458
|
+
try{(0,d.acquireProcessLock)(k,q)||(b.error(`Process lock acquisition failed for ${k}. Another instance may be running.`),b.error("This instance will exit to prevent duplicate initialization"),process.exit(1)),(0,a.isDebugToolsEnabled)()&&(q?b.info("Multi-agent mode enabled - allowing concurrent access to "+k):b.info("Successfully acquired process lock for "+k))}catch(e){b.error("Lock acquisition threw exception",{error:(0,f.getErrorMessage)(e),stack:e instanceof Error?e.stack:void 0}),b.error("Cannot continue without lock in single-agent mode"),process.exit(1)}(0,a.isDebugToolsEnabled)()&&(b.info("============================================================"),b.info(`PROCESS START: PID=${process.pid}, TIME=${(new Date).toISOString()}`),b.info("BASE DIR: "+k),b.info("ALCHEMY PATH: "+s.default.join(k,h.ALCHEMY_DIR_NAME)),b.info("PROJECT PATH: "+s.default.join(k,h.ALCHEMY_DIR_NAME+"/project.json")),b.info("MULTI-AGENT MODE: "+q),b.info("MCP client information will be captured during protocol initialization")),b.info("Starting MCP server"),(0,a.isDebugToolsEnabled)()&&(b.info("============================================================"),b.info("Base directory: "+k),b.info("Remote server URL: "+C),b.info("Node version: "+process.version),b.info("Current working directory: "+process.cwd()),b.info("ALLOWED_DIRECTORIES env var: not used (single working directory mode)"),b.info("Server already initialized: "+(_?"YES":"NO"))),_&&((0,a.isDebugToolsEnabled)()&&(b.info("Server already initialized globally, reusing existing server instance"),b.info("Reconnecting stdio to existing server...")),r().catch((e=>{const t=e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:e+""
|
|
3478
3459
|
b.error("Failed to connect stdio transport to existing server",{errorDetails:t}),process.exit(1)})))
|
|
3479
3460
|
try{const e=u.default.existsSync(k)
|
|
3480
3461
|
if((0,a.isDebugToolsEnabled)()&&b.info("Base directory exists: "+e),e&&(0,a.isDebugToolsEnabled)()){const e=u.default.statSync(k)
|
|
@@ -3482,7 +3463,7 @@ b.info(`Directory stats: isDirectory=${e.isDirectory()}, mode=${e.mode.toString(
|
|
|
3482
3463
|
if(!u.default.existsSync(S))try{u.default.mkdirSync(S,{recursive:!0}),(0,a.isDebugToolsEnabled)()&&b.info("Created alchemy lab directory: "+S)}catch(e){b.error("Failed to create alchemy lab directory: "+e)}try{(async function(){try{C=await async function(){if(process.env.REMOTE_SERVER_URL)return process.env.REMOTE_SERVER_URL
|
|
3483
3464
|
try{const{createConfigManager:e}=await Promise.resolve().then(t.t.bind(t,9060,23)),r=e(b),n=await r.getInstallationConfig()
|
|
3484
3465
|
if(n.remoteServerUrl)return(0,a.isDebugToolsEnabled)()&&b.info("Loaded REMOTE_SERVER_URL from installation config",{remoteServerUrl:n.remoteServerUrl}),n.remoteServerUrl}catch(e){(0,a.isDebugToolsEnabled)()&&b.debug("Could not read REMOTE_SERVER_URL from installation config",{error:e instanceof Error?e.message:"Unknown error"})}return"https://api.alchemylabcode.com"}()
|
|
3485
|
-
try{const e=await(0,
|
|
3466
|
+
try{const e=await(0,p.syncPlugins)(k,(0,m.isDevBuild)(),b)
|
|
3486
3467
|
e.synced.length>0&&b.info("Synced plugins on startup",{synced:e.synced}),e.errors.length>0&&b.warn("Some plugins failed to sync",{errors:e.errors})}catch(e){b.warn("Plugin sync failed",{error:e instanceof Error?e.message:"Unknown error"})}(0,a.isDebugToolsEnabled)()&&(b.info("Creating MCP server with base dir: "+k),b.info("Using remote server URL: "+C))
|
|
3487
3468
|
const e=await(0,i.createServer)(k,b,v,C,{multiAgentMode:(0,g.isMultiAgentModeEnabled)(k)})
|
|
3488
3469
|
E=e,global.__serverInitialized=!0,(0,a.isDebugToolsEnabled)()&&b.info("MCP server created successfully")
|
|
@@ -3517,7 +3498,7 @@ const n=[],o=[...t].sort(((e,t)=>{const r=e=>"number"==typeof e?e:Array.isArray(
|
|
|
3517
3498
|
return r(t.lines)-r(e.lines)}))
|
|
3518
3499
|
for(const e of o){const t={lines:e.lines,success:!1}
|
|
3519
3500
|
try{const n=(0,m.replaceLines)(r,e.lines,e.content)
|
|
3520
|
-
r=n.newContent,t.success=!0,t.linesReplaced=n.linesReplaced,t.linesAdded=n.linesAdded,t.startLine=n.startLine,t.endLine=n.endLine}catch(e){t.error=(0,
|
|
3501
|
+
r=n.newContent,t.success=!0,t.linesReplaced=n.linesReplaced,t.linesAdded=n.linesAdded,t.startLine=n.startLine,t.endLine=n.endLine}catch(e){t.error=(0,p.getErrorMessage)(e)}n.push(t)}return{newContent:r,results:n}}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
3521
3502
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
3522
3503
|
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=[]
|
|
3523
3504
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -3538,20 +3519,20 @@ M.push({type:"file",path:r,fullPath:n,replacements:e.replacements.map((e=>({line
|
|
|
3538
3519
|
if(T.length>0&&!t.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
3539
3520
|
for(const e of T)R.push({type:"document",documentId:e.documentId,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})
|
|
3540
3521
|
if(R.length>0&&t.apiClient){const e=R.map((e=>e.documentId))
|
|
3541
|
-
try{await(0,
|
|
3522
|
+
try{await(0,f.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}
|
|
3542
3523
|
throw e}}v=d.FileOperationPhase.TASK_VALIDATION,a.incrementCounter("replace_lines_phase",1,{phase:v})
|
|
3543
3524
|
const P=M.length>0?M[0].path:"document-operation",x=await d.validateTaskId(_,P,n,w,a,C.metricsPrefix),O=x?.requestId
|
|
3544
3525
|
let j=null
|
|
3545
3526
|
M.length>0&&O&&(j=await d.validateWorkItemStates(_,M[0].path,n,s,t,w,a,C.metricsPrefix))
|
|
3546
3527
|
let $={taskPromoted:!1,requestPromoted:!1}
|
|
3547
3528
|
M.length>0&&O&&j&&($=await d.autoPromoteTaskStatus(_,x.status,O,j.request?.status,M[0].path,n,s,w,a,C.metricsPrefix),$.taskPromoted&&w.info("Auto-promoted task to in_progress for replace-lines operation",{taskId:_,requestId:O,previousStatus:x.status,newStatus:$.newTaskStatus,triggeringOperation:"replace-lines"}))
|
|
3548
|
-
const
|
|
3549
|
-
if(!
|
|
3550
|
-
throw Error(
|
|
3529
|
+
const D=await d.ensureCorrectWorkspaceContext({taskPromoted:$.taskPromoted,requestId:O,context:t,operation:"replace-lines",logger:w,metrics:a,metricsPrefix:C.metricsPrefix})
|
|
3530
|
+
if(!D.success){if(D.isLockConflict)return{content:[{type:"text",text:"\u274c "+D.error}],isError:!0}
|
|
3531
|
+
throw Error(D.error)}if(M.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:M.length,workspaceBasePath:t.workspaceManager?.getCurrentContext().basePath})
|
|
3551
3532
|
for(let e=0;e<M.length;e++){const r=M[e],n=S[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(n.path,t)
|
|
3552
3533
|
M[e]={...r,path:o,fullPath:s}}}if(R.length>0&&O)try{await(0,h.validateRequestStatusForDocumentOperation)(O,s,w,a,"replace-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3553
3534
|
throw e}v=d.FileOperationPhase.RECORD_CREATION,a.incrementCounter("replace_lines_phase",1,{phase:v})
|
|
3554
|
-
const
|
|
3535
|
+
const A=[...M.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...R.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:F}=await d.createFileOperationRecords(_,O,t.projectId,C.recordType,P,{operationCount:E.length,fileOperations:M.length,documentOperations:R.length,operations:A,userComment:q},n,o,w,a,C.metricsPrefix,m)
|
|
3555
3536
|
if(b=F,I=F,v=C.fileOperationPhase,a.incrementCounter("replace_lines_phase",1,{phase:v}),M.length>0&&t.git)try{w.debug("[REPLACE-LINES] Checking for user changes before replace operations")
|
|
3556
3537
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(t.git,"replace-lines",{requestId:O,taskId:_,workspaceManager:t.workspaceManager},w,a)
|
|
3557
3538
|
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:M.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:M.length,error:e instanceof Error?e.message:e+""})}w.debug("[REPLACE-LINES] Proceeding with file operations",{fileCount:M.length})
|
|
@@ -3560,22 +3541,22 @@ let L=0,z=0,B=0,H=0
|
|
|
3560
3541
|
for(const e of M){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
|
|
3561
3542
|
try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
|
|
3562
3543
|
const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.replacements)
|
|
3563
|
-
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,H++,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,B+=t.totalLinesAdded}catch(r){t.error=(0,
|
|
3544
|
+
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,H++,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,B+=t.totalLinesAdded}catch(r){t.error=(0,p.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 R){const n={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
|
|
3564
3545
|
try{const o=await t.documentFileManager.getDocumentAsFile(e.documentId),s=t.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
3565
3546
|
n.filename=s?.filename
|
|
3566
3547
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.replacements)
|
|
3567
|
-
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,H++,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,B+=n.totalLinesAdded}catch(t){n.error=(0,
|
|
3568
|
-
r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const
|
|
3569
|
-
try{await o.updateToolRecord(I,{metadata:{path:M.length>0?M[0].path:"document:"+R[0]?.documentId,status:K?"completed":"failed",error:K?void 0:V+" operations failed",totalOperations:N.length,successfulFiles:Y,failedFiles:Q,operations:
|
|
3570
|
-
if(t.workspaceManager&&(Z+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Z+="**Summary:**\n",Z+=`- **Files processed:** ${G+V}\n`,Z+=`- **Successful operations:** ${G}\n`,Z+=`- **Failed operations:** ${V}\n`,Z+=`- **Total replacements:** ${J} successful, ${L} failed\n`,Z+=`- **Total Lines Replaced:** ${z}\n`,B>0&&(Z+=`- **Total Lines Added:** ${B}\n`),Z+="\n",
|
|
3548
|
+
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,H++,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,B+=n.totalLinesAdded}catch(t){n.error=(0,p.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(R.length>0)try{for(const e of R){const r=N.find((t=>t.documentId===e.documentId))
|
|
3549
|
+
r?.success&&await t.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const W=await d.handleMultiFileGitCommit(_,M,N,H,{operationType:"Replace lines",toolRecordId:I,successField:"successfulReplacements",logger:w,metrics:a,metricsPrefix:"replace_lines"},t),U=d.processMultiFileOperationResults(N,"successfulReplacements"),{successfulOperations:G,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q}=U
|
|
3550
|
+
try{await o.updateToolRecord(I,{metadata:{path:M.length>0?M[0].path:"document:"+R[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:B,operationsWithChanges:H,processingTime:Date.now()-k,userComment:q,...M.length>0&&W.success&&W.commitHash&&{commitHash:W.commitHash,previousCommitHash:W.previousCommitHash||void 0}},note:K?`Line replacement completed: ${G}/${N.length} operations successful${M.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"
|
|
3551
|
+
if(t.workspaceManager&&(Z+=`**Branch:** \`${t.workspaceManager.getCurrentContext().branchName}\`\n\n`),Z+="**Summary:**\n",Z+=`- **Files processed:** ${G+V}\n`,Z+=`- **Successful operations:** ${G}\n`,Z+=`- **Failed operations:** ${V}\n`,Z+=`- **Total replacements:** ${J} successful, ${L} failed\n`,Z+=`- **Total Lines Replaced:** ${z}\n`,B>0&&(Z+=`- **Total Lines Added:** ${B}\n`),Z+="\n",W.success&&W.commitHash&&(Z+="**Git Commit:**\n",Z+=`- **Commit Hash:** ${W.commitHash.substring(0,8)}\n`,Z+=`- **Files Committed:** ${W.filesCommitted.length}\n`,W.previousCommitHash&&(Z+=`- **Previous Commit:** ${W.previousCommitHash.substring(0,8)}\n`),Z+="\n"),D.lockAcquired&&D.lockedRequestId&&(Z+=`\u{1f512} **Locked request:** ${D.lockedRequestId}\n\n`),1===N.length){const e=N[0]
|
|
3571
3552
|
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"
|
|
3572
3553
|
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:** ${G}\n`,Z+=`- **Failed:** ${V}\n`,Z+=`- **Total Replacements:** ${J} successful, ${L} failed\n`,Z+=`- **Total Lines Replaced:** ${z}\n`,B>0&&(Z+=`- **Total Lines Added:** ${B}\n`),Z+="\n",Z+="**Detailed Results:**\n\n"
|
|
3573
3554
|
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"
|
|
3574
3555
|
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"}}R.length>0&&(Z+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3575
3556
|
const X=Date.now()-k
|
|
3576
3557
|
return w.info("Replace lines operation completed",{duration:X,success:K,totalOperations:N.length,successfulOperations:G,failedOperations:V}),a.incrementCounter("replace_lines_total",1,{success:K}),{content:[{type:"text",text:Z}],isError:!K}}catch(t){const r=Date.now()-k
|
|
3577
|
-
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,
|
|
3578
|
-
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),
|
|
3558
|
+
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,p.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"Line replacement failed: "+(0,p.getErrorMessage)(t)})}catch(e){}return a.incrementCounter("replace_lines_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Replace Lines Failed:** "+(0,p.getErrorMessage)(t)}],isError:!0}}}
|
|
3559
|
+
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),f=t(9949),p=t(8824),m=t(3255),y=t(9470)},6688(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.sessionIdentity=void 0
|
|
3579
3560
|
const r=t(9896),n=t(6928)
|
|
3580
3561
|
exports.sessionIdentity=new class{constructor(){this.discoveryAttempted=!1,this.parentCache=new Map}setIdentity(e){const t=this.identity
|
|
3581
3562
|
this.identity=e,this.log("setIdentity",{sessionId:e.sessionId,serverUrl:e.serverUrl,agentType:e.agentType||null,prevSessionId:t?.sessionId||null,changed:t?.sessionId!==e.sessionId})}getIdentity(){return this.identity}updateIdentity(e){if(this.identity){const t={...this.identity}
|
|
@@ -3622,14 +3603,14 @@ var t={}
|
|
|
3622
3603
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3623
3604
|
return o(t,e),t})
|
|
3624
3605
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleTaskFileHistory=async function(e,t,r,n,o){const s=n.child({tool:"task_file_history"}),h=o.startTimer("tool_execution_time")
|
|
3625
|
-
try{const{taskId:g,showDiff:
|
|
3606
|
+
try{const{taskId:g,showDiff:f=!1}=e
|
|
3626
3607
|
if(!g)throw(0,i.createValidationError)("Task ID is required")
|
|
3627
3608
|
if(!/^tas\d{6}$/.test(g))throw(0,i.createValidationError)(`Invalid task ID format: ${g}. Expected format: tas######`)
|
|
3628
|
-
s.info("Getting file changes for task "+g,{showDiff:
|
|
3629
|
-
const
|
|
3609
|
+
s.info("Getting file changes for task "+g,{showDiff:f})
|
|
3610
|
+
const p=r.getTaskClient(),m=r.getToolRecordClient(),y=t.projectId
|
|
3630
3611
|
let w
|
|
3631
3612
|
r.setProjectId(y)
|
|
3632
|
-
try{const M=await
|
|
3613
|
+
try{const M=await p.getTask(g)
|
|
3633
3614
|
s.info("Raw task response data",{responseDataType:typeof M,isArray:Array.isArray(M),hasData:null!=M,properties:M&&"object"==typeof M?Object.keys(M):[]}),w=(0,l.extractDataFromResponse)(M,{logger:s,operationName:"getTask",defaultValue:{id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}),s.info("Found task: "+w.title)}catch(R){s.warn("Could not fetch task information: "+(0,u.getErrorMessage)(R)),w={id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}let k=[]
|
|
3634
3615
|
try{const P=await m.getToolRecordsByTaskId(g)
|
|
3635
3616
|
if(s.info("Raw records response data",{responseDataType:typeof P,isArray:Array.isArray(P),hasData:null!=P,properties:P&&"object"==typeof P?Object.keys(P):[]}),k=(0,l.extractArrayFromResponse)(P,{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={}
|
|
@@ -3681,62 +3662,62 @@ n&&n.push({filePath:r,recordId:e.id,type:"replace-in-files",timestamp:e.createdA
|
|
|
3681
3662
|
C.has(t)||C.set(t,[])
|
|
3682
3663
|
const r=C.get(t)
|
|
3683
3664
|
r&&r.push({filePath:t,recordId:e.id,type:e.type,timestamp:e.createdAt,commitHash:e.metadata.commitHash,status:e.metadata.status||"",record:e})})),s.info(`Grouped records by file path. Found ${C.size} unique files.`)
|
|
3684
|
-
for(const[$,
|
|
3665
|
+
for(const[$,D]of C.entries())D.sort(((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime())),s.info(`File ${$} has ${D.length} records.`),s.info("Records with commit hashes: "+D.filter((e=>e.commitHash)).length)
|
|
3685
3666
|
const _=new Map
|
|
3686
|
-
for(const[
|
|
3667
|
+
for(const[A,F]of C.entries()){s.info(`Processing file: ${A} (${F.length} records)`)
|
|
3687
3668
|
const N=new Map
|
|
3688
3669
|
F.forEach((e=>{e.recordId&&e.record?.metadata?.status&&(N.has(e.recordId)||N.set(e.recordId,[]),N.get(e.recordId)?.push(e.record.metadata.status))})),N.forEach(((e,t)=>{s.info(`Record ${t} status updates: ${e.join(" -> ")}`)}))
|
|
3689
3670
|
const L=F.filter((e=>e.commitHash))
|
|
3690
|
-
if(s.info(`Found ${L.length} records with commit hash for ${
|
|
3691
|
-
try{if(t.git){const J={file:
|
|
3692
|
-
if(K&&K.all&&K.all.length>0){s.info(`Found ${K.all.length} commits for ${
|
|
3693
|
-
const Y=K.all.map((e=>({filePath:
|
|
3671
|
+
if(s.info(`Found ${L.length} records with commit hash for ${A}`),0===L.length){s.info(`No commit hashes found in record metadata for ${A}, trying git log`)
|
|
3672
|
+
try{if(t.git){const J={file:A,n:10},K=await t.git.log(J)
|
|
3673
|
+
if(K&&K.all&&K.all.length>0){s.info(`Found ${K.all.length} commits for ${A} using git log`)
|
|
3674
|
+
const Y=K.all.map((e=>({filePath:A,recordId:"git-"+e.hash.substring(0,8),type:"git-commit",timestamp:new Date(e.date).toISOString(),commitHash:e.hash,status:"completed",record:{id:"git-"+e.hash.substring(0,8),type:"git-commit",content:e.message,createdAt:new Date(e.date).toISOString(),metadata:{commitHash:e.hash}}})))
|
|
3694
3675
|
if(Y.length>0){const Q=Y.length>1?Y[Y.length-1]:Y[0],Z=Y[0],X=1===Y.length
|
|
3695
|
-
s.info(X?`Using single git commit for ${
|
|
3676
|
+
s.info(X?`Using single git commit for ${A}: ${Z.commitHash?Z.commitHash.substring(0,8):"unknown"}`:`Using git commits for ${A}: ${Q.commitHash?Q.commitHash.substring(0,8):"unknown"} to ${Z.commitHash?Z.commitHash.substring(0,8):"unknown"}`)
|
|
3696
3677
|
let ee=""
|
|
3697
|
-
try{if(X)try{const te=[`${Z.commitHash}:${
|
|
3698
|
-
re&&re.trim().length>0?(ee=re.split("\n").map((e=>"+"+e)).join("\n"),_.set(
|
|
3699
|
-
ee=await t.git.diff(oe),_.set(
|
|
3678
|
+
try{if(X)try{const te=[`${Z.commitHash}:${A}`],re=await t.git.show(te)
|
|
3679
|
+
re&&re.trim().length>0?(ee=re.split("\n").map((e=>"+"+e)).join("\n"),_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!0,diffText:ee})):_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!1,diffText:"File exists in git history but has no content"})}catch(ne){s.warn("Error getting file content for "+A,{error:ne instanceof Error?ne.message:ne+""}),_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!1,diffText:"Error getting file content from git"})}else{const oe=[`${Q.commitHash}..${Z.commitHash}`,"--",A]
|
|
3680
|
+
ee=await t.git.diff(oe),_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!(!ee||0>=ee.trim().length),diffText:ee||"No changes detected in git diff"})}}catch(se){s.warn("Error generating diff for "+A,{error:se instanceof Error?se.message:se+""}),_.set(A,{firstChange:Q,lastChange:Z,hasDiff:!0,diffText:"Error generating diff, but git history is available"})}continue}}else s.info("No git history found for "+A)}}catch(ie){s.warn("Error getting git history for "+A,{error:(0,u.getErrorMessage)(ie)})}_.set(A,{firstChange:F[0],lastChange:F[F.length-1],hasDiff:!1,diffText:"No commit hashes available for this file"})
|
|
3700
3681
|
continue}const z=L[0],B=L[L.length-1]
|
|
3701
3682
|
s.info(`First commit: ${z.commitHash?z.commitHash:"unknown"}, Last commit: ${B.commitHash?B.commitHash:"unknown"}`)
|
|
3702
|
-
let H=null,
|
|
3703
|
-
if(t.git&&z.commitHash)try{H=await(0,c.findPreviousCommit)(t.git,
|
|
3704
|
-
if(s.info(`Using ${
|
|
3705
|
-
s.info(`Getting new file content using git show: ${B.commitHash?B.commitHash.substring(0,8):"unknown"}:${
|
|
3683
|
+
let H=null,W=!1
|
|
3684
|
+
if(t.git&&z.commitHash)try{H=await(0,c.findPreviousCommit)(t.git,A,z.commitHash),H?(W=!0,s.info(`Found previous commit: ${H} for ${A}`)):s.info(`No previous commit found for ${A}, likely a new file`)}catch(ae){s.warn("Error finding previous commit for "+A,{error:(0,u.getErrorMessage)(ae)})}const U=W&&H?{...z,commitHash:H,status:"pre-task"}:z
|
|
3685
|
+
if(s.info(`Using ${W?"pre-task":"first task"} commit as baseline for ${A}: ${U.commitHash}`),s.info(`Last commit for ${A}: ${B.commitHash}`),s.info("Commits are "+(U.commitHash===B.commitHash?"identical":"different")),z.commitHash===B.commitHash&&!W){if(f&&!W&&t.git&&B.commitHash)try{const ce=[`${B.commitHash}:${A}`]
|
|
3686
|
+
s.info(`Getting new file content using git show: ${B.commitHash?B.commitHash.substring(0,8):"unknown"}:${A}`)
|
|
3706
3687
|
const le=await t.git.show(ce)
|
|
3707
3688
|
if(le&&le.trim().length>0){let de=""
|
|
3708
3689
|
const ue=le.split("\n")
|
|
3709
3690
|
for(const he of ue)de+=`+${he}\n`
|
|
3710
|
-
_.set(
|
|
3711
|
-
continue}}catch(ge){s.warn("Error getting new file content for "+
|
|
3712
|
-
continue}if(z.commitHash===B.commitHash&&
|
|
3691
|
+
_.set(A,{firstChange:U,lastChange:B,hasDiff:!0,diffText:de}),s.info(`Formatted new file content as diff, ${ue.length} lines`)
|
|
3692
|
+
continue}}catch(ge){s.warn("Error getting new file content for "+A,{error:(0,u.getErrorMessage)(ge)})}_.set(A,{firstChange:U,lastChange:B,hasDiff:!1,diffText:"Only one commit available for this file"})
|
|
3693
|
+
continue}if(z.commitHash===B.commitHash&&W){if(H===z.commitHash){_.set(A,{firstChange:U,lastChange:B,hasDiff:!1,diffText:"No changes detected"})
|
|
3713
3694
|
continue}s.info("Special case: First and last task commits are the same, but pre-task commit is different")}let G="",V=!1
|
|
3714
|
-
if(
|
|
3715
|
-
continue}let
|
|
3716
|
-
if("pre-task"===
|
|
3717
|
-
try{const me=await t.git.show([`${
|
|
3718
|
-
if(me!==ye&&(V=!0,G="Changes detected through direct content comparison (not visible in standard diff)",
|
|
3719
|
-
Math.abs(we.length-ke.length)>0&&(G+=`\n\nLine count changed: ${we.length} \u2192 ${ke.length}`),me.includes("\0")||ye.includes("\0")?G+="\n\nBinary content detected - changes not displayed":me.replace(/\s+/g,"")===ye.replace(/\s+/g,"")&&(G+="\n\nWhitespace-only changes detected")}}catch(be){s.warn("Error in direct file comparison: "+(be instanceof Error?be.message:be+""))}}s.info(`Diff generation result for ${
|
|
3720
|
-
s.info(`Trying fallback to show file content using git show: ${B.commitHash?B.commitHash.substring(0,8):"unknown"}:${
|
|
3695
|
+
if(f||"pre-task"!==U.status){try{if(t.git){try{await t.git.show([`${B.commitHash}:${A}`])}catch(pe){s.warn(`File ${A} does not exist in commit ${B.commitHash}, might be deleted or moved`),G="File was deleted or moved from this location during the task",V=!0,_.set(A,{firstChange:U,lastChange:B,hasDiff:V,diffText:G})
|
|
3696
|
+
continue}let fe
|
|
3697
|
+
if("pre-task"===U.status?(fe=[`${U.commitHash}..${B.commitHash}`,"--",A],s.info(`Comparing pre-task commit with final commit: ${U.commitHash?U.commitHash.substring(0,8):"unknown"}..${B.commitHash?B.commitHash.substring(0,8):"unknown"} for ${A}`)):(fe=["4b825dc642cb6eb9a060e54bf8d69288fbee4904.."+B.commitHash,"--",A],s.info(`File created during task, showing full file diff using empty tree object: ${B.commitHash?B.commitHash.substring(0,8):"unknown"} for ${A}`)),G=await t.git.diff(fe),V=!!G&&G.trim().length>0,!V&&U.commitHash!==B.commitHash){s.info("No diff found between commits but commits are different, trying direct file content comparison")
|
|
3698
|
+
try{const me=await t.git.show([`${U.commitHash}:${A}`]),ye=await t.git.show([`${B.commitHash}:${A}`])
|
|
3699
|
+
if(me!==ye&&(V=!0,G="Changes detected through direct content comparison (not visible in standard diff)",f)){const we=me.split("\n"),ke=ye.split("\n")
|
|
3700
|
+
Math.abs(we.length-ke.length)>0&&(G+=`\n\nLine count changed: ${we.length} \u2192 ${ke.length}`),me.includes("\0")||ye.includes("\0")?G+="\n\nBinary content detected - changes not displayed":me.replace(/\s+/g,"")===ye.replace(/\s+/g,"")&&(G+="\n\nWhitespace-only changes detected")}}catch(be){s.warn("Error in direct file comparison: "+(be instanceof Error?be.message:be+""))}}s.info(`Diff generation result for ${A}: hasDiff=${V}, length=${G.length}`)}}catch(Ie){if(s.warn("Error getting diff for "+A,{error:(0,u.getErrorMessage)(Ie),firstCommit:z.commitHash||"unknown",lastCommit:B.commitHash||"unknown"}),G="Error getting diff: "+(0,u.getErrorMessage)(Ie),"pre-task"!==z.status&&t.git)try{const ve=[`${B.commitHash}:${A}`]
|
|
3701
|
+
s.info(`Trying fallback to show file content using git show: ${B.commitHash?B.commitHash.substring(0,8):"unknown"}:${A}`)
|
|
3721
3702
|
const Ce=await t.git.show(ve)
|
|
3722
|
-
if(Ce&&Ce.trim().length>0){if(
|
|
3703
|
+
if(Ce&&Ce.trim().length>0){if(f){let _e=""
|
|
3723
3704
|
const Ee=Ce.split("\n")
|
|
3724
3705
|
for(const qe of Ee)_e+=`+${qe}\n`
|
|
3725
3706
|
G=_e}else G="File created during this task. Content:\n"+Ce
|
|
3726
|
-
V=!0,s.info("Fallback succeeded, got file content of length "+Ce.length)}}catch(Se){s.warn("Fallback also failed for "+
|
|
3707
|
+
V=!0,s.info("Fallback succeeded, got file content of length "+Ce.length)}}catch(Se){s.warn("Fallback also failed for "+A,{error:Se instanceof Error?Se.message:Se+""})}}_.set(A,{firstChange:U,lastChange:B,hasDiff:V,diffText:G||"No changes detected between commits"})}else V=U.commitHash!==B.commitHash,G=V?"File has changes":"No changes detected between commits",_.set(A,{firstChange:U,lastChange:B,hasDiff:V,diffText:G})}let E=`# File Changes for Task: ${g}\n\n`
|
|
3727
3708
|
w&&"object"==typeof w&&(E+="## Task Information\n",E+=`- **Title**: ${w.title||"Unknown"}\n`,E+=`- **Status**: ${w.status||"Unknown"}\n`,E+=`- **Description**: ${w.description||"No description"}\n\n`)
|
|
3728
3709
|
const q=3e3
|
|
3729
3710
|
let S=0,T=!1
|
|
3730
|
-
if(
|
|
3731
|
-
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**: ${
|
|
3711
|
+
if(f){for(const Te of _.values())Te.hasDiff&&Te.diffText&&(S+=Te.diffText.split("\n").length)
|
|
3712
|
+
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**: ${f?"Enabled":"Disabled"} (use showDiff=${!f} to ${f?"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`
|
|
3732
3713
|
for(const Me of I.allMoves)E+=`- **${Me.source}** \u2192 **${Me.destination}**\n`,E+=` - Operation: ${Me.type}\n`,E+=` - Timestamp: ${new Date(Me.timestamp).toLocaleString()}\n`,E+=` - Record ID: ${Me.recordId}\n\n`}E+="## Modified Files\n\n"
|
|
3733
3714
|
for(const[Re,Pe]of _.entries()){const{normalizedPath:xe,fullPath:Oe}=d.validateAndNormalizePath(Re,t)
|
|
3734
3715
|
let je=!1
|
|
3735
3716
|
try{await a.access(Oe),je=!0}catch{}E+=`### ${Re} ${je?"":"(Deleted)"}\n\n`
|
|
3736
|
-
const $e=new Date(Pe.firstChange.timestamp).toLocaleString(),
|
|
3737
|
-
E+=`**First Change**: ${$e}\n`,E+=`**Last Change**: ${
|
|
3738
|
-
const
|
|
3739
|
-
|
|
3717
|
+
const $e=new Date(Pe.firstChange.timestamp).toLocaleString(),De=new Date(Pe.lastChange.timestamp).toLocaleString()
|
|
3718
|
+
E+=`**First Change**: ${$e}\n`,E+=`**Last Change**: ${De}\n`,"pre-task"===Pe.firstChange.status&&Pe.firstChange.commitHash?E+=`**Pre-Task Commit**: ${Pe.firstChange.commitHash.substring(0,8)}\n`:Pe.firstChange.commitHash&&(E+=`**File Created During Task**: ${Pe.firstChange.commitHash.substring(0,8)}\n`),Pe.lastChange.commitHash&&(E+=`**Final Commit**: ${Pe.lastChange.commitHash.substring(0,8)}\n`)
|
|
3719
|
+
const Ae=I.sourceToMove.get(Re),Fe=I.destToMove.get(Re)
|
|
3720
|
+
Ae?E+=`**\u2139\ufe0f Move Operation**: This file was moved TO **${Ae.destination}**\n`:Fe&&(E+=`**\u2139\ufe0f Move Operation**: This file was moved FROM **${Fe.source}**\n`),f&&!T?Pe.hasDiff?(E+="\n**Changes**:\n",E+="```diff\n",E+=Pe.diffText,E+="\n```\n\n"):E+=`\n**Note**: ${Pe.diffText}\n\n`:T&&Pe.hasDiff?(E+=`\n**Note**: File has changes (${Pe.diffText?Pe.diffText.split("\n").length:0} lines). `,E+=`Compare ${Pe.firstChange.commitHash?Pe.firstChange.commitHash.substring(0,8):"unknown"}..${Pe.lastChange.commitHash?Pe.lastChange.commitHash.substring(0,8):"unknown"} to see changes.\n\n`):Pe.hasDiff?E+="\n**Note**: File has changes. Use showDiff=true to see the diff.\n\n":E+=`\n**Note**: ${Pe.diffText}\n\n`,E+="---\n\n"}return h({success:!0,fileCount:C.size}),{content:[{type:"text",text:E}]}}catch(Ne){return s.error("Error in task file history tool",{error:Ne instanceof Error?Ne.stack:Ne+""}),h({success:!1,error:Ne instanceof Error?Ne.name:"unknown"}),{content:[{type:"text",text:"Error: "+(0,u.getErrorMessage)(Ne)}],isError:!0}}}
|
|
3740
3721
|
const i=t(9860),a=s(t(1943)),c=t(9671),l=t(2960),d=s(t(5967)),u=t(8824)},6928(module){module.exports=require("path")},6975(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectClientAdapter=void 0
|
|
3741
3722
|
const r=t(1058)
|
|
3742
3723
|
exports.ProjectClientAdapter=class{constructor(e,t){this.client=e,this.logger=t.child({component:"project-client-adapter"}),this.logger.info("ProjectClientAdapter initialized")}isOnline(){return!this.client.isOffline()}async fetchProject(e){try{return this.logger.debug("ProjectClientAdapter.fetchProject called",{projectId:e}),await this.client.getProject(e)}catch(t){return this.logger.error("Error in ProjectClientAdapter.fetchProject",{projectId:e,error:t instanceof Error?t.stack:t+""}),null}}async createProject(e){try{this.logger.debug("ProjectClientAdapter.createProject called",{projectName:e.name,projectId:e.id}),this.logger.info("Creating project via adapter",{name:e.name,id:e.id,description:e.description?.substring(0,50)})
|
|
@@ -3858,10 +3839,10 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentit
|
|
|
3858
3839
|
i.existsSync(n)||i.mkdirSync(n,{recursive:!0})
|
|
3859
3840
|
const s=(new Date).toISOString(),c=Object.keys(r).length?" "+JSON.stringify(r):""
|
|
3860
3841
|
i.appendFileSync(o,`[${s}] ${e} | ${t}${c}\n`)}catch(e){}}
|
|
3861
|
-
const i=s(t(9896)),a=s(t(6928))},7334(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateRequest=async function(e,t,l,d,u,h,g){const
|
|
3862
|
-
|
|
3863
|
-
const
|
|
3864
|
-
try{const d=function(e){try{return r.CreateRequestSchema.parse(e)}catch(e){if(e instanceof s.ZodError&&e.errors.length>0)throw new n.ValidationError(e.errors[0].message)
|
|
3842
|
+
const i=s(t(9896)),a=s(t(6928))},7334(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateRequest=async function(e,t,l,d,u,h,g){const f=d.child({tool:"create_request"})
|
|
3843
|
+
f.info("Creating new request",{args:e})
|
|
3844
|
+
const p=u.startTimer("tool_handler_duration")
|
|
3845
|
+
try{if(e&&"string"==typeof e.acceptanceCriteria)try{e.acceptanceCriteria=JSON.parse(e.acceptanceCriteria)}catch{}const d=function(e){try{return r.CreateRequestSchema.parse(e)}catch(e){if(e instanceof s.ZodError&&e.errors.length>0)throw new n.ValidationError(e.errors[0].message)
|
|
3865
3846
|
throw new n.ValidationError("Invalid input: "+(0,i.getErrorMessage)(e))}}(e)
|
|
3866
3847
|
u.incrementCounter("create_request_attempts",1,{type:d.type,criteriaCounts:d.acceptanceCriteria.length})
|
|
3867
3848
|
const m=t.projectId
|
|
@@ -3874,22 +3855,22 @@ if(e){const t=l.getCLISessionClient()
|
|
|
3874
3855
|
if(t){const r=await t.getByExternalId(e)
|
|
3875
3856
|
if(r?.workflowId){const e=await l.proxyGet("/api/workflows/"+r.workflowId),t=e?.data||e
|
|
3876
3857
|
t?.approvalMode&&(w=(0,a.getApprovalMode)(t.approvalMode))}}}if("none"===w)try{const e=await l.proxyGet("/api/projects/"+m),t=e?.data||e,r=t?.metadata?.defaultApprovalMode
|
|
3877
|
-
r&&(w=(0,a.getApprovalMode)(r))}catch(e){
|
|
3878
|
-
|
|
3858
|
+
r&&(w=(0,a.getApprovalMode)(r))}catch(e){f.warn("Failed to read project metadata for approvalMode fallback",{error:(0,i.getErrorMessage)(e)})}}catch(e){f.warn("Failed to resolve approval mode, using default",{error:(0,i.getErrorMessage)(e)})}const k="require-approval"===w&&"quick-edit"!==d.type?"pending_approval":"open",b={title:d.title,description:d.description,type:d.type,acceptanceCriteria:d.acceptanceCriteria,status:k,...d.planDocumentId&&{planDocumentId:d.planDocumentId},...g&&{cliOrigin:g}}
|
|
3859
|
+
f.info("Creating request via request client",{projectId:m,title:d.title,type:d.type,criteriaCount:d.acceptanceCriteria.length})
|
|
3879
3860
|
const I=await y.createRequest(b)
|
|
3880
|
-
|
|
3881
|
-
const v=(0,o.extractDataFromResponse)(I,{logger:
|
|
3861
|
+
f.debug("Create request response structure",{type:typeof I,isArray:Array.isArray(I),hasData:null!=I,properties:I?Object.keys(I):[],dataPreview:I?JSON.stringify(I).substring(0,200)+"...":"null"})
|
|
3862
|
+
const v=(0,o.extractDataFromResponse)(I,{logger:f,operationName:"createRequest",throwOnNoData:!0}),C="data"in v?v.data:v
|
|
3882
3863
|
let _,E={created:!1}
|
|
3883
|
-
if(h?.workspaceManager)try{await h.workspaceManager.initializeRequest(C.id,C.title),E={created:!0,branchName:"requests/"+C.id,message:"Branch created successfully"},
|
|
3884
|
-
|
|
3864
|
+
if(h?.workspaceManager)try{await h.workspaceManager.initializeRequest(C.id,C.title),E={created:!0,branchName:"requests/"+C.id,message:"Branch created successfully"},f.info("Request branch initialized successfully",{requestId:C.id,branchName:E.branchName,title:C.title})}catch(e){f.warn("Failed to initialize request branch, will retry on first operation",{requestId:C.id,error:(0,i.getErrorMessage)(e)})}else"quick-edit"===d.type?f.info("Quick-edit request - skipping branch creation, will work directly on main",{requestId:C.id}):f.debug("No workspace manager available, branch creation deferred",{requestId:C.id})
|
|
3865
|
+
f.info("Request created successfully",{requestId:C.id,title:C.title,branchCreated:E.created,branchName:E.branchName})
|
|
3885
3866
|
try{const e=l.getToolRecordClient()
|
|
3886
3867
|
if(e){const t=await e.createToolRecord({requestId:C.id,projectId:m,type:"create-request",metadata:{status:"completed",timestamp:(new Date).toISOString(),requestType:C.type,requestTitle:C.title,requestDescription:C.description,criteriaCount:C.acceptanceCriteria.length,branchCreated:E.created,branchName:E.created?E.branchName:null},note:`Created request "${C.title}" of type ${C.type}${E.created?" with branch "+E.branchName:" - branch will be created on first file operation"}`})
|
|
3887
|
-
_=t?.id}}catch(e){
|
|
3868
|
+
_=t?.id}}catch(e){f.warn("Failed to create tool record for request creation",{error:(0,i.getErrorMessage)(e),requestId:C.id})}p({success:!0,type:d.type,hasProjectId:!0}),f.info("Request created successfully",{requestId:C.id,title:C.title,type:C.type,projectId:m})
|
|
3888
3869
|
const q=C.localId||C.id
|
|
3889
3870
|
let S="pending_approval"===k?`Created Request ${q} (pending approval)`:"Created Request "+q
|
|
3890
|
-
return _&&(S+=`\n[RECORD:${_}]`),{content:[{type:"text",text:S}]}}catch(r){if(
|
|
3871
|
+
return _&&(S+=`\n[RECORD:${_}]`),{content:[{type:"text",text:S}]}}catch(r){if(f.error("Failed to create request",{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 requests")||r.message.includes("disabled due to tier limits")))f.info("Skipping tool record creation for disabled project error",{projectId:t.projectId,error:r.message})
|
|
3891
3872
|
else{const n=l.getToolRecordClient()
|
|
3892
|
-
n&&await n.createToolRecord({projectId:t.projectId,type:"create-request",metadata:{status:"failed",timestamp:(new Date).toISOString(),requestTitle:e.title,requestType:e.type,requestDescription:e.description?.substring(0,100)+(e.description?.length>100?"...":""),criteriaCount:e.acceptanceCriteria?e.acceptanceCriteria.length:0,branchCreated:!1,branchName:null,error:(0,i.getErrorMessage)(r),errorDetails:r instanceof Error?r.stack:r+""},note:"Failed to create request: "+e.title})}}catch(e){
|
|
3873
|
+
n&&await n.createToolRecord({projectId:t.projectId,type:"create-request",metadata:{status:"failed",timestamp:(new Date).toISOString(),requestTitle:e.title,requestType:e.type,requestDescription:e.description?.substring(0,100)+(e.description?.length>100?"...":""),criteriaCount:e.acceptanceCriteria?e.acceptanceCriteria.length:0,branchCreated:!1,branchName:null,error:(0,i.getErrorMessage)(r),errorDetails:r instanceof Error?r.stack:r+""},note:"Failed to create request: "+e.title})}}catch(e){f.error("Failed to create failure record for request creation",{error:e instanceof Error?e.message:e+""})}if(p({success:!1,error:r instanceof Error?r.name:"unknown"}),r instanceof s.ZodError&&r.errors.length>0){const e=r.errors[0]
|
|
3893
3874
|
let t=e.message
|
|
3894
3875
|
return e.path.includes("acceptanceCriteria")&&(t=`Acceptance criteria: ${t}. Please provide a list of criteria descriptions.`),{content:[{type:"text",text:"Error: "+t}],isError:!0}}let n=(0,i.getErrorMessage)(r),o="Unable to create request. Please check your input and try again."
|
|
3895
3876
|
return(n.includes("Project cannot accept new requests")||n.includes("Project is inactive due to tier limits"))&&(o="This project is currently inactive due to tier limits. Only your oldest projects can accept new requests. Please use an active project or upgrade your tier for more simultaneous projects."),{content:[{type:"text",text:`Error: ${n}\n\n${o}`}],isError:!0}}}
|
|
@@ -3904,11 +3885,11 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3904
3885
|
var t={}
|
|
3905
3886
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3906
3887
|
return o(t,e),t})
|
|
3907
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,t,r,n,o,s,h,g){const
|
|
3908
|
-
try{const s=a.validateArgs(e,i.ModifyFileSchema),{taskId:u,operations:
|
|
3909
|
-
|
|
3888
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,t,r,n,o,s,h,g){const f=s.child({tool:"modify_file"})
|
|
3889
|
+
try{const s=a.validateArgs(e,i.ModifyFileSchema),{taskId:u,operations:p,comment:m}=s
|
|
3890
|
+
f.info("Processing modify-file operations",{taskId:u,operationCount:p.length,comment:m})
|
|
3910
3891
|
const y=[],w=[],k=[],b=[],I=[]
|
|
3911
|
-
for(const e of
|
|
3892
|
+
for(const e of p){const t={path:e.path,documentId:e.documentId}
|
|
3912
3893
|
switch(e.operationType){case"replace-string":y.push({...t,replacements:e.replaceString.replacements,mode:e.replaceString.mode})
|
|
3913
3894
|
break
|
|
3914
3895
|
case"insert-lines":w.push({...t,insertions:e.insertLines.insertions})
|
|
@@ -3918,40 +3899,40 @@ break
|
|
|
3918
3899
|
case"delete-string":b.push({...t,replacements:e.deleteString.patterns.map((e=>({old_str:e,new_str:""}))),mode:e.deleteString.mode||"all"})
|
|
3919
3900
|
break
|
|
3920
3901
|
case"delete-lines":I.push({...t,lines:e.deleteLines.lines})}}const v=[]
|
|
3921
|
-
if(y.length>0){
|
|
3922
|
-
const e=await(0,c.handleReplaceStrings)({taskId:u,operations:y,comment:m+" [via modify-file: replace-string]"},t,r,n,o,
|
|
3923
|
-
v.push({type:"replace-string",result:e})}if(w.length>0){
|
|
3924
|
-
const e=await(0,l.handleInsertLines)({taskId:u,operations:w,comment:m+" [via modify-file: insert-lines]"},t,r,n,o,
|
|
3925
|
-
v.push({type:"insert-lines",result:e})}if(k.length>0){
|
|
3926
|
-
const e=await(0,d.handleReplaceLines)({taskId:u,operations:k,comment:m+" [via modify-file: replace-lines]"},t,r,n,o,
|
|
3927
|
-
v.push({type:"replace-lines",result:e})}if(b.length>0){
|
|
3928
|
-
const e=await(0,c.handleReplaceStrings)({taskId:u,operations:b,comment:m+" [via modify-file: delete-string]"},t,r,n,o,
|
|
3929
|
-
v.push({type:"delete-string",result:e})}if(I.length>0){
|
|
3930
|
-
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,
|
|
3902
|
+
if(y.length>0){f.info("Routing to replace-strings handler",{operationCount:y.length})
|
|
3903
|
+
const e=await(0,c.handleReplaceStrings)({taskId:u,operations:y,comment:m+" [via modify-file: replace-string]"},t,r,n,o,f,h,g)
|
|
3904
|
+
v.push({type:"replace-string",result:e})}if(w.length>0){f.info("Routing to insert-lines handler",{operationCount:w.length})
|
|
3905
|
+
const e=await(0,l.handleInsertLines)({taskId:u,operations:w,comment:m+" [via modify-file: insert-lines]"},t,r,n,o,f,h,g)
|
|
3906
|
+
v.push({type:"insert-lines",result:e})}if(k.length>0){f.info("Routing to replace-lines handler",{operationCount:k.length})
|
|
3907
|
+
const e=await(0,d.handleReplaceLines)({taskId:u,operations:k,comment:m+" [via modify-file: replace-lines]"},t,r,n,o,f,h,g)
|
|
3908
|
+
v.push({type:"replace-lines",result:e})}if(b.length>0){f.info("Routing delete-string to replace-strings handler",{operationCount:b.length})
|
|
3909
|
+
const e=await(0,c.handleReplaceStrings)({taskId:u,operations:b,comment:m+" [via modify-file: delete-string]"},t,r,n,o,f,h,g)
|
|
3910
|
+
v.push({type:"delete-string",result:e})}if(I.length>0){f.info("Processing delete-lines operations",{operationCount:I.length})
|
|
3911
|
+
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,f,h,g)
|
|
3931
3912
|
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
|
|
3932
3913
|
let q="## Modify File Results\n\n"
|
|
3933
3914
|
q+="**Summary:**\n",q+=`- **Total operation types:** ${v.length}\n`,q+=`- **Successful:** ${_}\n`,q+=`- **Failed:** ${E}\n\n`
|
|
3934
3915
|
for(const{type:e,result:t}of v)q+=`### ${e} operations\n`,q+=t.content[0].text+"\n\n"
|
|
3935
|
-
return
|
|
3916
|
+
return f.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 f.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}}}
|
|
3936
3917
|
const i=t(6183),a=s(t(5967)),c=t(3306),l=t(6486),d=t(6651),u=t(8824)},7478(e,exports,t){async function r(e,t,r){const n=r.startTimer("git_get_current_branch_duration")
|
|
3937
3918
|
try{const o=(await e.status()).current
|
|
3938
3919
|
if(!o)throw new g.ValidationError("Repository is in detached HEAD state or branch detection failed")
|
|
3939
|
-
return t.debug("Retrieved current branch",{branch:o}),r.incrementCounter("git_get_current_branch_success",1),n({success:!0}),o}catch(e){const o=(0,
|
|
3920
|
+
return t.debug("Retrieved current branch",{branch:o}),r.incrementCounter("git_get_current_branch_success",1),n({success:!0}),o}catch(e){const o=(0,p.getErrorMessage)(e)
|
|
3940
3921
|
throw t.error("Failed to get current branch",{error:o}),r.incrementCounter("git_get_current_branch_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to get current branch: "+o)}}async function n(e,t,r,n){const o=n.startTimer("git_branch_exists_duration")
|
|
3941
3922
|
try{const s=(await e.branch(["-l"])).all.includes(t)
|
|
3942
|
-
return r.debug("Checked branch existence",{branchName:t,exists:s}),n.incrementCounter("git_branch_exists_check",1,{exists:s.toString()}),o({success:!0}),s}catch(e){const s=(0,
|
|
3923
|
+
return r.debug("Checked branch existence",{branchName:t,exists:s}),n.incrementCounter("git_branch_exists_check",1,{exists:s.toString()}),o({success:!0}),s}catch(e){const s=(0,p.getErrorMessage)(e)
|
|
3943
3924
|
return r.error("Failed to check branch existence",{branchName:t,error:s}),n.incrementCounter("git_branch_exists_failure",1),o({success:!1,error:e instanceof Error?e.name:"unknown"}),!1}}async function o(e,t,o,s){const i=s.startTimer("git_switch_branch_duration")
|
|
3944
3925
|
try{const a=await r(e,o,s)
|
|
3945
3926
|
if(a===t)return o.debug("Already on target branch",{branchName:t}),s.incrementCounter("git_switch_branch_noop",1),i({success:!0,reason:"already_on_branch"}),{success:!0,branchName:t,previousBranch:a,message:`Already on branch '${t}'`}
|
|
3946
3927
|
if(!await n(e,t,o,s)){const e=`Branch '${t}' does not exist`
|
|
3947
3928
|
throw o.error(e),s.incrementCounter("git_switch_branch_not_found",1),i({success:!1,reason:"branch_not_found"}),new g.ValidationError(e)}await e.checkout(t)
|
|
3948
3929
|
const c=await e.revparse(["HEAD"])
|
|
3949
|
-
return o.info("Switched to branch",{branchName:t,previousBranch:a,commitHash:c.substring(0,8)}),s.incrementCounter("git_switch_branch_success",1),i({success:!0}),{success:!0,branchName:t,previousBranch:a,commitHash:c,message:`Switched from '${a}' to '${t}'`}}catch(e){const r=(0,
|
|
3930
|
+
return o.info("Switched to branch",{branchName:t,previousBranch:a,commitHash:c.substring(0,8)}),s.incrementCounter("git_switch_branch_success",1),i({success:!0}),{success:!0,branchName:t,previousBranch:a,commitHash:c,message:`Switched from '${a}' to '${t}'`}}catch(e){const r=(0,p.getErrorMessage)(e)
|
|
3950
3931
|
throw o.error("Failed to switch branch",{branchName:t,error:r}),s.incrementCounter("git_switch_branch_failure",1),i({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError(`Failed to switch to branch '${t}': ${r}`)}}async function s(e,t,r){const n=r.startTimer("git_repository_status_duration")
|
|
3951
3932
|
try{let o,s=!0
|
|
3952
3933
|
try{o=await e.status()}catch(e){return s=!1,t.warn("Not a git repository or git not available"),r.incrementCounter("git_repository_status_not_git",1),n({success:!0,reason:"not_git_repo"}),{isGitRepository:!1,currentBranch:"",isClean:!1,hasMainBranch:!1,hasMasterBranch:!1,defaultBranch:"",uncommittedChanges:[],branches:[]}}const i=o.current||"",a=0===o.files.length,c=o.files.map((e=>e.path)),l=await e.branch(["-l"]),d=l.all.map((e=>({name:e,isCurrentBranch:e===i}))),u=l.all.includes("main"),h=l.all.includes("master")
|
|
3953
3934
|
let g=""
|
|
3954
|
-
return u?g="main":h?g="master":d.length>0&&(g=d[0].name),t.debug("Retrieved repository status",{currentBranch:i,isClean:a,hasMainBranch:u,hasMasterBranch:h,defaultBranch:g,branchCount:d.length,uncommittedCount:c.length}),r.incrementCounter("git_repository_status_success",1),n({success:!0}),{isGitRepository:s,currentBranch:i,isClean:a,hasMainBranch:u,hasMasterBranch:h,defaultBranch:g,uncommittedChanges:c,branches:d}}catch(e){const o=(0,
|
|
3935
|
+
return u?g="main":h?g="master":d.length>0&&(g=d[0].name),t.debug("Retrieved repository status",{currentBranch:i,isClean:a,hasMainBranch:u,hasMasterBranch:h,defaultBranch:g,branchCount:d.length,uncommittedCount:c.length}),r.incrementCounter("git_repository_status_success",1),n({success:!0}),{isGitRepository:s,currentBranch:i,isClean:a,hasMainBranch:u,hasMasterBranch:h,defaultBranch:g,uncommittedChanges:c,branches:d}}catch(e){const o=(0,p.getErrorMessage)(e)
|
|
3955
3936
|
throw t.error("Failed to get repository status",{error:o}),r.incrementCounter("git_repository_status_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to get repository status: "+o)}}function i(e){return"requests/"+e}async function a(e,t,r){const n=r.startTimer("git_uncommitted_changes_check_duration")
|
|
3956
3937
|
try{t.debug("Starting uncommitted changes check"),t.debug("Checking for uncommitted changes before merge"),Date.now()
|
|
3957
3938
|
const o=await e.status()
|
|
@@ -3963,7 +3944,7 @@ t.debug("Uncommitted changes summary",{hasChanges:l,totalFiles:c,staged:s.length
|
|
|
3963
3944
|
let d=""
|
|
3964
3945
|
if(l){const e=[]
|
|
3965
3946
|
s.length>0&&e.push(s.length+" staged file(s)"),i.length>0&&e.push(i.length+" unstaged file(s)"),a.length>0&&e.push(a.length+" untracked file(s)"),d=`Found ${c} uncommitted change(s): ${e.join(", ")}`}else d="No uncommitted changes detected"
|
|
3966
|
-
return(0,h.isDebugToolsEnabled)()&&t.debug("Summary",{summary:d}),t.debug("Uncommitted changes check completed",{hasChanges:l,staged:s.length,unstaged:i.length,untracked:a.length,total:c,summary:d}),r.incrementCounter("git_uncommitted_changes_check_success",1),r.recordValue("git_uncommitted_changes_total_files",c),n({success:!0}),{hasChanges:l,stagedFiles:s,unstagedFiles:i,untrackedFiles:a,totalFiles:c,summary:d}}catch(e){const o=(0,
|
|
3947
|
+
return(0,h.isDebugToolsEnabled)()&&t.debug("Summary",{summary:d}),t.debug("Uncommitted changes check completed",{hasChanges:l,staged:s.length,unstaged:i.length,untracked:a.length,total:c,summary:d}),r.incrementCounter("git_uncommitted_changes_check_success",1),r.recordValue("git_uncommitted_changes_total_files",c),n({success:!0}),{hasChanges:l,stagedFiles:s,unstagedFiles:i,untrackedFiles:a,totalFiles:c,summary:d}}catch(e){const o=(0,p.getErrorMessage)(e)
|
|
3967
3948
|
throw t.error("Failed to check uncommitted changes",{error:o}),r.incrementCounter("git_uncommitted_changes_check_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to check uncommitted changes: "+o)}}var c,l=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
3968
3949
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
3969
3950
|
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]}),d=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),u=this&&this.__importStar||(c=function(e){return c=Object.getOwnPropertyNames||function(e){var t=[]
|
|
@@ -3977,42 +3958,42 @@ try{if(await n(e,t,s,i)){const e=`Branch '${t}' already exists`
|
|
|
3977
3958
|
return s.warn(e),i.incrementCounter("git_create_branch_already_exists",1),c({success:!1,reason:"already_exists"}),{success:!1,branchName:t,message:e}}const l=await r(e,s,i)
|
|
3978
3959
|
await e.checkoutBranch(t,o)
|
|
3979
3960
|
const d=await e.revparse(["HEAD"]),u=a||l
|
|
3980
|
-
return await e.checkout(u),s.info("Created new branch",{branchName:t,fromBranch:o,currentBranch:l,returnedToBranch:u,commitHash:d.substring(0,8)}),i.incrementCounter("git_create_branch_success",1),c({success:!0}),{success:!0,branchName:t,previousBranch:l,commitHash:d,message:`Created branch '${t}' from '${o}'`}}catch(e){const r=(0,
|
|
3961
|
+
return await e.checkout(u),s.info("Created new branch",{branchName:t,fromBranch:o,currentBranch:l,returnedToBranch:u,commitHash:d.substring(0,8)}),i.incrementCounter("git_create_branch_success",1),c({success:!0}),{success:!0,branchName:t,previousBranch:l,commitHash:d,message:`Created branch '${t}' from '${o}'`}}catch(e){const r=(0,p.getErrorMessage)(e)
|
|
3981
3962
|
throw s.error("Failed to create branch",{branchName:t,fromBranch:o,error:r}),i.incrementCounter("git_create_branch_failure",1),c({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError(`Failed to create branch '${t}': ${r}`)}},exports.switchToBranch=o,exports.mergeBranch=async function(e,t,s,i,a,c){const l=a.startTimer("git_merge_branch_duration")
|
|
3982
3963
|
try{const d=await r(e,i,a)
|
|
3983
3964
|
if(d!==s&&await o(e,s,i,a),!await n(e,t,i,a)){const e=`Source branch '${t}' does not exist`
|
|
3984
3965
|
throw i.error(e),a.incrementCounter("git_merge_branch_source_not_found",1),l({success:!1,reason:"source_not_found"}),new g.ValidationError(e)}const u=c?["--no-ff","-m",c,t]:["--no-ff",t],h=(await e.merge(u),await e.revparse(["HEAD"]))
|
|
3985
|
-
return i.info("Successfully merged branch",{sourceBranch:t,targetBranch:s,commitHash:h.substring(0,8),mergeMessage:c||"default merge message"}),a.incrementCounter("git_merge_branch_success",1),l({success:!0}),{success:!0,branchName:s,previousBranch:d,commitHash:h,message:`Merged '${t}' into '${s}'`}}catch(e){const r=(0,
|
|
3966
|
+
return i.info("Successfully merged branch",{sourceBranch:t,targetBranch:s,commitHash:h.substring(0,8),mergeMessage:c||"default merge message"}),a.incrementCounter("git_merge_branch_success",1),l({success:!0}),{success:!0,branchName:s,previousBranch:d,commitHash:h,message:`Merged '${t}' into '${s}'`}}catch(e){const r=(0,p.getErrorMessage)(e)
|
|
3986
3967
|
throw i.error("Failed to merge branch",{sourceBranch:t,targetBranch:s,error:r}),a.incrementCounter("git_merge_branch_failure",1),l({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError(`Failed to merge '${t}' into '${s}': ${r}`)}},exports.deleteBranch=async function(e,t,o=!1,s,i){const a=i.startTimer("git_delete_branch_duration")
|
|
3987
3968
|
try{const c=await r(e,s,i)
|
|
3988
3969
|
if(c===t){const e=`Cannot delete current branch '${t}'`
|
|
3989
3970
|
throw s.error(e),i.incrementCounter("git_delete_branch_current_branch",1),a({success:!1,reason:"current_branch"}),new g.ValidationError(e)}if("main"===t||"master"===t){const e=`Cannot delete protected branch '${t}'`
|
|
3990
3971
|
throw s.error(e),i.incrementCounter("git_delete_branch_protected",1),a({success:!1,reason:"protected_branch"}),new g.ValidationError(e)}if(!await n(e,t,s,i)){const e=`Branch '${t}' does not exist`
|
|
3991
3972
|
return s.warn(e),i.incrementCounter("git_delete_branch_not_found",1),a({success:!1,reason:"not_found"}),{success:!1,branchName:t,message:e}}const l=o?["-D",t]:["-d",t]
|
|
3992
|
-
return await e.branch(l),s.info("Deleted branch",{branchName:t,force:o,currentBranch:c}),i.incrementCounter("git_delete_branch_success",1),a({success:!0}),{success:!0,branchName:t,previousBranch:c,message:`Deleted branch '${t}'${o?" (forced)":""}`}}catch(e){const r=(0,
|
|
3973
|
+
return await e.branch(l),s.info("Deleted branch",{branchName:t,force:o,currentBranch:c}),i.incrementCounter("git_delete_branch_success",1),a({success:!0}),{success:!0,branchName:t,previousBranch:c,message:`Deleted branch '${t}'${o?" (forced)":""}`}}catch(e){const r=(0,p.getErrorMessage)(e)
|
|
3993
3974
|
throw s.error("Failed to delete branch",{branchName:t,force:o,error:r}),i.incrementCounter("git_delete_branch_failure",1),a({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError(`Failed to delete branch '${t}': ${r}`)}},exports.getRepositoryStatus=s,exports.validateGitRepository=async function(e,t,r){const n=r.startTimer("git_validate_repository_duration")
|
|
3994
3975
|
try{const o=await s(e,t,r)
|
|
3995
|
-
return o.isGitRepository?(o.currentBranch||(t.warn("Git repository in detached HEAD state"),r.incrementCounter("git_validate_repository_detached_head",1)),o.isClean||(t.warn("Git repository has uncommitted changes",{count:o.uncommittedChanges.length,files:o.uncommittedChanges.slice(0,5)}),r.incrementCounter("git_validate_repository_dirty",1)),o.defaultBranch||(t.warn("No default branch found in git repository"),r.incrementCounter("git_validate_repository_no_default_branch",1)),t.info("Git repository validation completed",{currentBranch:o.currentBranch,isClean:o.isClean,defaultBranch:o.defaultBranch,branchCount:o.branches.length}),r.incrementCounter("git_validate_repository_success",1),n({success:!0}),o):(t.warn("Git repository validation failed: not a git repository"),r.incrementCounter("git_validate_repository_not_git",1),n({success:!1,reason:"not_git_repo"}),o)}catch(e){const o=(0,
|
|
3976
|
+
return o.isGitRepository?(o.currentBranch||(t.warn("Git repository in detached HEAD state"),r.incrementCounter("git_validate_repository_detached_head",1)),o.isClean||(t.warn("Git repository has uncommitted changes",{count:o.uncommittedChanges.length,files:o.uncommittedChanges.slice(0,5)}),r.incrementCounter("git_validate_repository_dirty",1)),o.defaultBranch||(t.warn("No default branch found in git repository"),r.incrementCounter("git_validate_repository_no_default_branch",1)),t.info("Git repository validation completed",{currentBranch:o.currentBranch,isClean:o.isClean,defaultBranch:o.defaultBranch,branchCount:o.branches.length}),r.incrementCounter("git_validate_repository_success",1),n({success:!0}),o):(t.warn("Git repository validation failed: not a git repository"),r.incrementCounter("git_validate_repository_not_git",1),n({success:!1,reason:"not_git_repo"}),o)}catch(e){const o=(0,p.getErrorMessage)(e)
|
|
3996
3977
|
throw t.error("Git repository validation failed",{error:o}),r.incrementCounter("git_validate_repository_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Git repository validation failed: "+o)}},exports.sanitizeBranchName=function(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").substring(0,50)},exports.generateRequestBranchName=i,exports.generateMergeMessagePatterns=function(e){const t=i(e)
|
|
3997
3978
|
return[`Merge ${t}-`,"Merge "+t,`Merge ${t}-.*\\(resolved conflicts\\)`,`Merge ${t} \\(resolved conflicts\\)`]},exports.parseRequestIdFromBranchName=function(e){const t=e.match(/^feature\/(req\d{6})-/)
|
|
3998
3979
|
return t?t[1]:null},exports.switchToDefaultBranch=async function(e,t,r){const n=r.startTimer("git_switch_to_default_duration")
|
|
3999
3980
|
try{const i=await s(e,t,r)
|
|
4000
3981
|
if(!i.defaultBranch){const e="No default branch found"
|
|
4001
3982
|
return t.warn(e),r.incrementCounter("git_switch_to_default_no_branch",1),n({success:!1,reason:"no_default_branch"}),{success:!1,branchName:"",message:e}}const a=await o(e,i.defaultBranch,t,r)
|
|
4002
|
-
return a.success?(t.info("Switched to default branch",{defaultBranch:i.defaultBranch,previousBranch:a.previousBranch}),r.incrementCounter("git_switch_to_default_success",1),n({success:!0})):(r.incrementCounter("git_switch_to_default_failed",1),n({success:!1,reason:"switch_failed"})),a}catch(e){const o=(0,
|
|
3983
|
+
return a.success?(t.info("Switched to default branch",{defaultBranch:i.defaultBranch,previousBranch:a.previousBranch}),r.incrementCounter("git_switch_to_default_success",1),n({success:!0})):(r.incrementCounter("git_switch_to_default_failed",1),n({success:!1,reason:"switch_failed"})),a}catch(e){const o=(0,p.getErrorMessage)(e)
|
|
4003
3984
|
throw t.error("Failed to switch to default branch",{error:o}),r.incrementCounter("git_switch_to_default_error",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to switch to default branch: "+o)}},exports.ensureRepositoryReady=async function(e,t,r){const n=r.startTimer("git_ensure_repository_ready_duration")
|
|
4004
3985
|
try{const o=await s(e,t,r),i=[]
|
|
4005
3986
|
o.isGitRepository||i.push("Not a git repository"),o.currentBranch||i.push("Repository is in detached HEAD state"),o.defaultBranch||i.push("No default branch (main/master) found")
|
|
4006
3987
|
const a=0===i.length
|
|
4007
|
-
return t.debug("Repository readiness check completed",{ready:a,issueCount:i.length,issues:i}),r.incrementCounter("git_ensure_repository_ready_check",1,{ready:a.toString()}),n({success:!0,ready:a.toString()}),{ready:a,status:o,issues:i}}catch(e){const o=(0,
|
|
3988
|
+
return t.debug("Repository readiness check completed",{ready:a,issueCount:i.length,issues:i}),r.incrementCounter("git_ensure_repository_ready_check",1,{ready:a.toString()}),n({success:!0,ready:a.toString()}),{ready:a,status:o,issues:i}}catch(e){const o=(0,p.getErrorMessage)(e)
|
|
4008
3989
|
return t.error("Failed to check repository readiness",{error:o}),r.incrementCounter("git_ensure_repository_ready_failure",1),n({success:!1,error:e instanceof Error?e.name:"unknown"}),{ready:!1,status:{isGitRepository:!1,currentBranch:"",isClean:!1,hasMainBranch:!1,hasMasterBranch:!1,defaultBranch:"",uncommittedChanges:[],branches:[]},issues:["Repository check failed: "+o]}}},exports.hasMainChangedSinceRevert=async function(e,t,r,n){const o=n.startTimer("git_check_main_changed_since_revert")
|
|
4009
3990
|
try{r.debug("Starting main branch change detection",{providedRevertCommitHash:t.substring(0,8),fullRevertCommitHash:t})
|
|
4010
3991
|
const n=await e.revparse(["HEAD"])
|
|
4011
3992
|
r.debug("Git state captured",{currentMainHash:n.substring(0,8),fullCurrentMainHash:n,revertCommitHash:t.substring(0,8),fullRevertCommitHash:t,hashesMatch:n===t})
|
|
4012
3993
|
try{const t=await e.revparse(["--abbrev-ref","HEAD"]),n=await e.status(),o=await e.log(["--oneline","-5"])
|
|
4013
|
-
r.debug("Additional git context",{currentBranch:t,gitStatus:{ahead:n.ahead,behind:n.behind,current:n.current,tracking:n.tracking,staged:n.staged.length,modified:n.modified.length},recentCommits:o.all.map((e=>({hash:e.hash.substring(0,8),message:e.message})))})}catch(e){r.warn("Failed to gather additional git context",{error:e instanceof Error?e.message:e+""})}const s=await(0,
|
|
3994
|
+
r.debug("Additional git context",{currentBranch:t,gitStatus:{ahead:n.ahead,behind:n.behind,current:n.current,tracking:n.tracking,staged:n.staged.length,modified:n.modified.length},recentCommits:o.all.map((e=>({hash:e.hash.substring(0,8),message:e.message})))})}catch(e){r.warn("Failed to gather additional git context",{error:e instanceof Error?e.message:e+""})}const s=await(0,f.validateCommitHash)(e,t,r,"hasMainChangedSinceRevert-revert-validation")
|
|
4014
3995
|
if(!s.valid)throw r.error("Revert commit validation failed",{revertCommitHash:t.substring(0,8),error:s.error}),Error(`Revert commit ${t.substring(0,8)} not found or not reachable: ${s.error}`)
|
|
4015
|
-
const i=await(0,
|
|
3996
|
+
const i=await(0,f.validateCommitHash)(e,n,r,"hasMainChangedSinceRevert-head-validation")
|
|
4016
3997
|
if(!i.valid)throw r.error("Current HEAD validation failed",{currentMainHash:n.substring(0,8),error:i.error}),Error(`Current HEAD ${n.substring(0,8)} validation failed: ${i.error}`)
|
|
4017
3998
|
if(n===t)return r.info("Main branch unchanged since revert - exact hash match",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),fullHashMatch:!0}),o({success:!0,changed:"false"}),{hasChanged:!1,currentMainHash:n,revertCommitHash:t,commitsSinceRevert:0,message:"Main branch has not changed since revert"}
|
|
4018
3999
|
r.debug("Hash comparison shows difference, checking ancestor relationship",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),hashesEqual:!1})
|
|
@@ -4020,10 +4001,10 @@ let a=!1,c=0,l=null
|
|
|
4020
4001
|
for(let n=1;3>=n;n++)try{r.debug("Checking ancestor relationship with merge-base",{revertCommitHash:t.substring(0,8),currentHead:"HEAD",attempt:n}),n>1&&(await new Promise((e=>setTimeout(e,100))),r.debug("Retry attempt after delay",{attempt:n,delay:100})),await e.raw(["merge-base","--is-ancestor",t,"HEAD"]),r.debug("Revert commit is ancestor of HEAD, counting commits between them",{attempt:n})
|
|
4021
4002
|
const o=await e.raw(["rev-list","--count",t+"..HEAD"])
|
|
4022
4003
|
c=parseInt(o.trim(),10),a=!0
|
|
4023
|
-
break}catch(e){l=e,r.debug("Ancestor check attempt failed",{attempt:n,error:(0,
|
|
4004
|
+
break}catch(e){l=e,r.debug("Ancestor check attempt failed",{attempt:n,error:(0,p.getErrorMessage)(e)}),3===n&&r.debug("All ancestor check attempts failed, treating as non-ancestor")}if(a){try{const n=await e.raw(["rev-list","--oneline",t+"..HEAD"])
|
|
4024
4005
|
r.debug("Commits found between revert and HEAD",{count:c,commits:n.trim().split("\n").filter((e=>e.length>0))})}catch(e){r.warn("Could not list commits between revert and HEAD",{error:e instanceof Error?e.message:e+""})}return r.info("Main branch has changed since revert - ancestor relationship confirmed",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),commitsSinceRevert:c,isAncestor:!0}),o({success:!0,changed:"true"}),{hasChanged:!0,currentMainHash:n,revertCommitHash:t,commitsSinceRevert:c,message:`Main branch has ${c} new commit${c>1?"s":""} since revert`}}r.warn("Revert commit is not an ancestor of current HEAD after retries - investigating relationship",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),lastAncestorError:l instanceof Error?l.message:l+"",attempts:3})
|
|
4025
4006
|
try{const o=await e.raw(["merge-base",t,"HEAD"])
|
|
4026
|
-
r.debug("Merge base found between revert commit and HEAD",{mergeBase:o.trim().substring(0,8),revertCommitHash:t.substring(0,8),currentMainHash:n.substring(0,8)})}catch(e){r.warn("Could not find merge base",{error:e instanceof Error?e.message:e+""})}try{await e.raw(["merge-base","--is-ancestor","HEAD",t]),r.error("CRITICAL: Current HEAD is ancestor of revert commit - possible git state corruption or incorrect revert hash",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),implication:"This suggests the stored revert commit hash may be incorrect or from a different branch state"})}catch(e){r.debug("HEAD is not ancestor of revert commit either - commits may be on divergent paths",{error:e instanceof Error?e.message:e+""})}return o({success:!0,changed:"unknown"}),{hasChanged:!0,currentMainHash:n,revertCommitHash:t,commitsSinceRevert:-1,message:"Cannot determine relationship between revert commit and current HEAD - assuming changed for safety. This may indicate a stored revert commit hash issue."}}catch(e){const n=(0,
|
|
4007
|
+
r.debug("Merge base found between revert commit and HEAD",{mergeBase:o.trim().substring(0,8),revertCommitHash:t.substring(0,8),currentMainHash:n.substring(0,8)})}catch(e){r.warn("Could not find merge base",{error:e instanceof Error?e.message:e+""})}try{await e.raw(["merge-base","--is-ancestor","HEAD",t]),r.error("CRITICAL: Current HEAD is ancestor of revert commit - possible git state corruption or incorrect revert hash",{currentMainHash:n.substring(0,8),revertCommitHash:t.substring(0,8),implication:"This suggests the stored revert commit hash may be incorrect or from a different branch state"})}catch(e){r.debug("HEAD is not ancestor of revert commit either - commits may be on divergent paths",{error:e instanceof Error?e.message:e+""})}return o({success:!0,changed:"unknown"}),{hasChanged:!0,currentMainHash:n,revertCommitHash:t,commitsSinceRevert:-1,message:"Cannot determine relationship between revert commit and current HEAD - assuming changed for safety. This may indicate a stored revert commit hash issue."}}catch(e){const n=(0,p.getErrorMessage)(e)
|
|
4027
4008
|
throw r.error("Failed to check if main changed since revert",{revertCommitHash:t.substring(0,8),error:n}),o({success:!1,error:e instanceof Error?e.name:"unknown"}),Error("Failed to check main branch changes: "+n)}},exports.findRevertCommitHash=async function(e,t,r){try{r.debug("Searching for revert commit hash in tool records",{requestId:e})
|
|
4028
4009
|
const n=await t.getToolRecordsByRequestId(e,"revert-request")
|
|
4029
4010
|
if(n.sort(((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime())),!n||0===n.length)return r.debug("No revert tool records found for request",{requestId:e}),{found:!1,message:"No revert operations found for this request"}
|
|
@@ -4032,7 +4013,7 @@ for(const t of n)if(r.debug("Examining tool record",{requestId:e,recordId:t.id,r
|
|
|
4032
4013
|
r.debug("Found potential revert commit hash, validating...",{requestId:e,revertCommitHash:o.substring(0,8),fullRevertCommitHash:o,revertType:n,recordId:t.id,revertedAt:t.createdAt})
|
|
4033
4014
|
try{if(!/^[a-f0-9]{40}$/i.test(o)){r.warn("Invalid commit hash format found in tool record",{requestId:e,invalidHash:o,recordId:t.id,format:"Expected 40-character hex string"})
|
|
4034
4015
|
continue}return r.info("Found valid revert commit hash from tool records",{requestId:e,revertCommitHash:o.substring(0,8),fullRevertCommitHash:o,revertType:n,recordId:t.id,revertedAt:t.createdAt,hashFormat:"valid"}),{found:!0,revertCommitHash:o,revertType:n,revertedAt:t.createdAt,message:`Found ${n} revert commit from ${t.createdAt}`}}catch(n){r.warn("Revert commit hash validation failed, trying next record",{requestId:e,revertCommitHash:o.substring(0,8),recordId:t.id,error:n instanceof Error?n.message:n+""})
|
|
4035
|
-
continue}}return r.warn("Found revert tool records but none have completed status with commit hash",{requestId:e,recordCount:n.length,records:n.map((e=>({type:e.type,status:e.metadata?.status,hasCommitHash:!!e.metadata?.revertCommitHash})))}),{found:!1,message:"Found revert records but none were completed successfully"}}catch(t){const n=(0,
|
|
4016
|
+
continue}}return r.warn("Found revert tool records but none have completed status with commit hash",{requestId:e,recordCount:n.length,records:n.map((e=>({type:e.type,status:e.metadata?.status,hasCommitHash:!!e.metadata?.revertCommitHash})))}),{found:!1,message:"Found revert records but none were completed successfully"}}catch(t){const n=(0,p.getErrorMessage)(t)
|
|
4036
4017
|
return r.error("Failed to find revert commit hash from tool records",{requestId:e,error:n}),{found:!1,message:"Failed to search tool records: "+n}}},exports.checkUncommittedChanges=a,exports.commitUserChanges=async function(e,t,r,n,o){const s=o.startTimer("git_commit_user_changes_duration")
|
|
4037
4018
|
try{if(!r.hasChanges)throw new g.ValidationError("No uncommitted changes to commit")
|
|
4038
4019
|
n.debug("Starting user changes commit process",{staged:r.stagedFiles.length,unstaged:r.unstagedFiles.length,untracked:r.untrackedFiles.length,total:r.totalFiles}),n.info("Committing user changes before merge",{requestId:t,staged:r.stagedFiles.length,unstaged:r.unstagedFiles.length,untracked:r.untrackedFiles.length,total:r.totalFiles})
|
|
@@ -4041,7 +4022,7 @@ i.length>0?(n.debug("Staging files",{files:i.slice(0,10),total:i.length}),await
|
|
|
4041
4022
|
const a=`chore: commit user changes before merging request ${t}\n\n${r.summary}\n\nThis commit preserves user modifications made during the request lifecycle\nbefore proceeding with the branch merge operation.`
|
|
4042
4023
|
n.debug("Commit message",{message:a.split("\n")[0]}),n.debug("Creating commit"),await e.commit(a)
|
|
4043
4024
|
const c=await e.revparse(["HEAD"])
|
|
4044
|
-
return n.debug("Commit created successfully",{commitHash:c.substring(0,8),filesCommitted:r.totalFiles}),n.info("Successfully committed user changes",{requestId:t,commitHash:c.substring(0,8),filesCommitted:r.totalFiles,message:a.split("\n")[0]}),o.incrementCounter("git_commit_user_changes_success",1),o.recordValue("git_commit_user_changes_files",r.totalFiles),s({success:!0}),{commitHash:c,message:a,filesCommitted:r.totalFiles}}catch(e){const i=(0,
|
|
4025
|
+
return n.debug("Commit created successfully",{commitHash:c.substring(0,8),filesCommitted:r.totalFiles}),n.info("Successfully committed user changes",{requestId:t,commitHash:c.substring(0,8),filesCommitted:r.totalFiles,message:a.split("\n")[0]}),o.incrementCounter("git_commit_user_changes_success",1),o.recordValue("git_commit_user_changes_files",r.totalFiles),s({success:!0}),{commitHash:c,message:a,filesCommitted:r.totalFiles}}catch(e){const i=(0,p.getErrorMessage)(e)
|
|
4045
4026
|
throw n.error("Failed to commit user changes",{requestId:t,error:i,uncommittedFiles:r.totalFiles}),o.incrementCounter("git_commit_user_changes_failure",1),s({success:!1,error:e instanceof Error?e.name:"unknown"}),new g.ValidationError("Failed to commit user changes: "+i)}},exports.commitUserChangesBeforeToolOperation=async function(e,r,n,o,s){const i=s.startTimer("git_pre_tool_user_changes_duration")
|
|
4046
4027
|
try{let c=Date.now()
|
|
4047
4028
|
o.debug("Checking for user changes before tool operation",{toolName:r})
|
|
@@ -4058,8 +4039,8 @@ const h=`${u}\n\n${{...d,summary:`User changes detected before ${r}: ${d.summary
|
|
|
4058
4039
|
o.debug("Committing user changes with message",{firstLine:h.split("\n")[0]})
|
|
4059
4040
|
const g=[...d.unstagedFiles,...d.untrackedFiles]
|
|
4060
4041
|
c=Date.now(),g.length>0&&(o.debug("Staging files before tool operation",{files:g.slice(0,10),total:g.length}),await l.add(g)),Date.now(),c=Date.now(),await l.commit(h),Date.now()
|
|
4061
|
-
const
|
|
4062
|
-
return o.debug("User changes committed successfully before tool",{commitHash:
|
|
4042
|
+
const f=await l.revparse(["HEAD"])
|
|
4043
|
+
return o.debug("User changes committed successfully before tool",{commitHash:f.substring(0,8),filesCommitted:d.totalFiles,toolName:r}),o.info("Successfully committed user changes before tool operation",{toolName:r,requestId:n.requestId,taskId:n.taskId,commitHash:f.substring(0,8),filesCommitted:d.totalFiles}),s.incrementCounter("git_pre_tool_user_changes_committed",1),s.recordValue("git_pre_tool_user_changes_files",d.totalFiles),i({success:!0,reason:"changes_committed"}),{userChangesCommitted:!0,commitHash:f,filesCommitted:d.totalFiles}}catch(e){const t=(0,p.getErrorMessage)(e)
|
|
4063
4044
|
return o.debug("Failed to commit user changes before tool",{toolName:r,error:t}),o.warn("Failed to commit user changes before tool operation",{toolName:r,requestId:n.requestId,taskId:n.taskId,error:t}),s.incrementCounter("git_pre_tool_user_changes_failed",1),i({success:!1,error:e instanceof Error?e.name:"unknown"}),{userChangesCommitted:!1}}},exports.findLargeUntrackedFiles=async function(e,r=104857600){const n=[]
|
|
4064
4045
|
try{const o=t(3807).simpleGit(e),s=(await o.status()).not_added||[]
|
|
4065
4046
|
for(const t of s)try{const o=y.join(e,t),s=m.statSync(o)
|
|
@@ -4068,7 +4049,7 @@ const t=e.reduce(((e,t)=>e+t.sizeMB),0)
|
|
|
4068
4049
|
let r=`\n\n\u26a0\ufe0f **Performance Warning**: Large untracked files detected (${Math.round(t)} MB total) that may slow git operations:\n`
|
|
4069
4050
|
for(const t of e.slice(0,5))r+=`- \`${t.path}\` (${t.sizeMB} MB)\n`
|
|
4070
4051
|
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}
|
|
4071
|
-
const h=t(3444),g=t(9860),
|
|
4052
|
+
const h=t(3444),g=t(9860),f=t(3922),p=t(8824),m=u(t(9896)),y=u(t(6928))},7575(e,exports){var t
|
|
4072
4053
|
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){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleUpdatePlan=async function(e,t,n,o){const s=o.child({tool:"plan_operations",operation:"update"})
|
|
4073
4054
|
try{const t=n.getDocumentClient(),r=await t.getDocument(e.planId)
|
|
4074
4055
|
if(!r)return{content:[{type:"text",text:"\u274c Plan not found: "+e.planId}],isError:!0}
|
|
@@ -4088,7 +4069,7 @@ try{const n=e.replace(/\/$/,"")+"/session",o=await fetch(n)
|
|
|
4088
4069
|
if(!o.ok)return void i.warn("Failed to get session list",{status:o.status})
|
|
4089
4070
|
const a=await o.json(),c=a.sort(((e,t)=>t.time.updated-e.time.updated)),l=e.replace(/\/$/,"")+"/session/status",d=await fetch(l)
|
|
4090
4071
|
if(!d.ok)return void i.warn("Failed to get session status",{status:d.status})
|
|
4091
|
-
const u=await d.json(),h=c.filter((e=>"busy"===u[e.id]?.type)),g=5,
|
|
4072
|
+
const u=await d.json(),h=c.filter((e=>"busy"===u[e.id]?.type)),g=5,f=c.slice(0,g),p=new Set(h.map((e=>e.id))),m=[...h,...f.filter((e=>!p.has(e.id)))]
|
|
4092
4073
|
let y=null
|
|
4093
4074
|
const w=[]
|
|
4094
4075
|
for(const n of m)try{const o=`${e.replace(/\/$/,"")}/session/${n.id}/message?limit=50`,a=await fetch(o)
|
|
@@ -4136,33 +4117,33 @@ try{if(!t.git)return r.debug("No git repository available"),n.incrementCounter("
|
|
|
4136
4117
|
const s=await u.getRepositoryStatus(t.git,r,n),i=s.branches.filter((t=>t.name==="requests/"+e)),a=i.length>0,c=a?i[0].name:void 0,l=i.map((e=>e.name))
|
|
4137
4118
|
return r.debug("Searched for feature branch",{requestId:e,found:a,branchName:c,matchingBranches:l.length,totalBranches:s.branches.length}),n.incrementCounter("find_feature_branch_success",1,{found:a.toString()}),o({success:!0,found:a.toString()}),{found:a,branchName:c,allBranches:l}}catch(t){const s=(0,g.getErrorMessage)(t)
|
|
4138
4119
|
return r.warn("Failed to find feature branch for request",{requestId:e,error:s}),n.incrementCounter("find_feature_branch_failure",1),o({success:!1,error:t instanceof Error?t.name:"unknown"}),{found:!1}}}async function o(e,o,s,i,a,c){if(!o||!s.git)return{switched:!1,message:"No branch switch needed"}
|
|
4139
|
-
let l=!1,
|
|
4140
|
-
try{s.syncBranchState&&await s.syncBranchState(),Date.now(),
|
|
4120
|
+
let l=!1,p=Date.now()
|
|
4121
|
+
try{s.syncBranchState&&await s.syncBranchState(),Date.now(),p=Date.now()
|
|
4141
4122
|
const e=s.getCurrentBranchContext?await s.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
4142
4123
|
if(Date.now(),e.requestId===o)return i.debug("Already in correct request context",{requestId:o,currentBranch:e.branch}),{switched:!1,branchName:e.branch||void 0,message:`Already in request ${o} context`,lockAcquired:!1}
|
|
4143
4124
|
if(s.workspaceManager){i.debug("Using WorkspaceManager for request context switching",{requestId:o,currentMode:s.workspaceManager.getCurrentContext().mode})
|
|
4144
4125
|
try{if("multi-agent"===s.workspaceManager.getCurrentContext().mode)if(i.debug("Multi-agent mode: checking request lock before auto-switch",{requestId:o}),s.apiClient)try{const e=s.apiClient.getRequestClient(),{sessionTag:t}=(0,h.getGlobalClientInfo)()
|
|
4145
|
-
|
|
4126
|
+
p=Date.now()
|
|
4146
4127
|
const r=await e.getRequestLockStatus(o)
|
|
4147
4128
|
if(Date.now(),r.isLocked&&r.lockedBySessionTag!==t){i.warn("Auto-switch blocked by request lock",{requestId:o,lockedByAgent:r.lockedBySessionTag,currentAgent:t,lockedAt:r.lockedAt})
|
|
4148
4129
|
let e=`Request ${o} is currently locked by another agent (${r.lockedBySessionTag}).\n\nLocked since: ${r.lockedAt||"unknown"}\n\nIn multi-agent mode, only one agent can work on a request at a time. Please wait for the other agent to complete their work or contact an administrator if the lock appears stale.`
|
|
4149
4130
|
if(s.lockOverrideManager&&s.configManager)try{const t=await s.configManager.getEffectiveConfig(s.mainBasePath)
|
|
4150
|
-
t.lockOverride.enabled&&(e+=`\n\n**To take over this request (only if safe to do so), use switch_to_branch with password: \`${s.lockOverrideManager.generatePassword(o,t.lockOverride.passwordValidityMinutes)}\` (valid for ${t.lockOverride.passwordValidityMinutes} minutes)**`)}catch(e){i.warn("Failed to check lock override config",{error:e})}throw new
|
|
4131
|
+
t.lockOverride.enabled&&(e+=`\n\n**To take over this request (only if safe to do so), use switch_to_branch with password: \`${s.lockOverrideManager.generatePassword(o,t.lockOverride.passwordValidityMinutes)}\` (valid for ${t.lockOverride.passwordValidityMinutes} minutes)**`)}catch(e){i.warn("Failed to check lock override config",{error:e})}throw new f.RequestLockError(e,o,r.lockedBySessionTag,r.lockedAt)}if(!r.isLocked){p=Date.now(),i.debug("Acquiring lock for auto-switch",{requestId:o,sessionTag:t})
|
|
4151
4132
|
const r=await e.lockRequest(o,t)
|
|
4152
4133
|
if(Date.now(),!r.locked){const e=`Failed to acquire lock for request ${o} during auto-switch`
|
|
4153
4134
|
throw i.warn("Auto-switch lock acquisition failed",{requestId:o}),Error(e)}i.info("Successfully acquired lock for auto-switch",{requestId:o,sessionTag:t,lockedAt:r.lockedAt}),l=!0}}catch(e){throw i.error("Lock check/acquisition failed during auto-switch",{requestId:o,error:e instanceof Error?e.message:e+""}),e}else i.warn("Multi-agent mode but no API client available for locking",{requestId:o})
|
|
4154
|
-
i.debug("Ensuring workspace is ready for file operations",{requestId:o,reason:"first-file-operation"}),
|
|
4135
|
+
i.debug("Ensuring workspace is ready for file operations",{requestId:o,reason:"first-file-operation"}),p=Date.now(),await s.workspaceManager.ensureWorkspaceReady(o),Date.now()
|
|
4155
4136
|
const e=s.workspaceManager.getCurrentContext()
|
|
4156
4137
|
if(e.basePath&&(s.git=(0,d.simpleGit)(e.basePath),i.info("Updated git instance to worktree path",{requestId:o,gitWorkingDirectory:e.basePath,mode:e.mode,branchName:e.branchName})),e.requestId!==o){const t=`Workspace switch validation failed. Expected requestId: ${o}, but got: ${e.requestId}`
|
|
4157
4138
|
throw i.error("Post-switch context validation failed",{requestId:o,expectedRequestId:o,actualRequestId:e.requestId,actualBasePath:e.basePath,mode:e.mode}),Error(t)}i.info("Workspace is ready via WorkspaceManager",{requestId:o,mode:s.workspaceManager.getCurrentContext().mode,workflow:"hybrid-creation-lazy-worktree",validation:"context_validated"})
|
|
4158
4139
|
try{const{findLargeUntrackedFiles:r,formatLargeFileWarning:n}=await Promise.resolve().then(t.t.bind(t,7478,23)),a=await r(e.basePath)
|
|
4159
4140
|
if(a.length>0){const e=n(a)
|
|
4160
|
-
s.workspaceManager.largeFileWarning=e,i.warn("Large untracked files detected",{requestId:o,fileCount:a.length,files:a.map((e=>({path:e.path,sizeMB:e.sizeMB})))})}}catch(e){i.debug("Large file check failed",{error:e})}return a.incrementCounter(c+"_auto_context_switch_success",1),{switched:!0,branchName:s.workspaceManager.getCurrentContext().branchName,message:"Workspace ready for request "+o,lockAcquired:l,lockedRequestId:l?o:void 0}}catch(e){if(e instanceof
|
|
4141
|
+
s.workspaceManager.largeFileWarning=e,i.warn("Large untracked files detected",{requestId:o,fileCount:a.length,files:a.map((e=>({path:e.path,sizeMB:e.sizeMB})))})}}catch(e){i.debug("Large file check failed",{error:e})}return a.incrementCounter(c+"_auto_context_switch_success",1),{switched:!0,branchName:s.workspaceManager.getCurrentContext().branchName,message:"Workspace ready for request "+o,lockAcquired:l,lockedRequestId:l?o:void 0}}catch(e){if(e instanceof f.RequestLockError)throw i.warn("Auto-switch blocked by request lock, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
|
|
4161
4142
|
return i.error("Error switching to request context",{requestId:o,error:(0,g.getErrorMessage)(e)}),a.incrementCounter(c+"_auto_context_switch_error",1),{switched:!1,message:"Context switch error: "+(0,g.getErrorMessage)(e)}}}i.warn("WorkspaceManager not available, falling back to legacy branch switching",{requestId:o})
|
|
4162
4143
|
const m=await n(o,s,i,a)
|
|
4163
4144
|
if(!m.found||!m.branchName)return i.warn("No feature branch found for request during auto-switch",{requestId:o,availableBranches:m.allBranches||[]}),a.incrementCounter(c+"_auto_branch_switch_no_branch",1),{switched:!1,message:"No feature branch found for request "+o}
|
|
4164
4145
|
const y=await r(s,i,a),w=await u.switchToBranch(s.git,m.branchName,i,a)
|
|
4165
|
-
return w.success?(s.updateBranchState&&await s.updateBranchState(m.branchName,o),i.info("Auto-switched to request branch after task promotion",{requestId:o,fromBranch:y,toBranch:m.branchName}),a.incrementCounter(c+"_auto_branch_switch_success",1),{switched:!0,branchName:m.branchName,message:"Switched to "+m.branchName}):(i.warn("Failed to auto-switch to request branch",{requestId:o,targetBranch:m.branchName,error:w.message}),a.incrementCounter(c+"_auto_branch_switch_failure",1),{switched:!1,message:"Failed to switch: "+w.message})}catch(e){if(e instanceof
|
|
4146
|
+
return w.success?(s.updateBranchState&&await s.updateBranchState(m.branchName,o),i.info("Auto-switched to request branch after task promotion",{requestId:o,fromBranch:y,toBranch:m.branchName}),a.incrementCounter(c+"_auto_branch_switch_success",1),{switched:!0,branchName:m.branchName,message:"Switched to "+m.branchName}):(i.warn("Failed to auto-switch to request branch",{requestId:o,targetBranch:m.branchName,error:w.message}),a.incrementCounter(c+"_auto_branch_switch_failure",1),{switched:!1,message:"Failed to switch: "+w.message})}catch(e){if(e instanceof f.RequestLockError)throw i.warn("Auto-switch blocked by request lock in legacy mode, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
|
|
4166
4147
|
return i.error("Error during auto-switch to request branch",{requestId:o,error:(0,g.getErrorMessage)(e)}),a.incrementCounter(c+"_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}
|
|
4167
4148
|
const o=e.workspaceManager.getCurrentContext()
|
|
4168
4149
|
if("multi-agent"!==o.mode)return n.debug("Single-agent mode detected, skipping multi-agent context validation",{operation:r,requestId:t,mode:o.mode}),{isValid:!0}
|
|
@@ -4212,8 +4193,8 @@ return r.debug("Single-agent mode: determined expected branch",{taskId:e,request
|
|
|
4212
4193
|
try{const e=await o(0,r,n,a,c,l)
|
|
4213
4194
|
if(e.switched&&a.info(`Auto-switched to request workspace during ${i} operation`,{requestId:r,branchName:e.branchName,message:e.message,taskPromoted:t,operation:i}),d&&r){const t=s(n,r,i,a)
|
|
4214
4195
|
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)
|
|
4215
|
-
return e instanceof
|
|
4216
|
-
const d=t(3807),u=l(t(7478)),h=t(5172),g=t(8824),
|
|
4196
|
+
return e instanceof f.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})}}
|
|
4197
|
+
const d=t(3807),u=l(t(7478)),h=t(5172),g=t(8824),f=t(7575)
|
|
4217
4198
|
l(t(9896)),l(t(6928))},7634(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.RequestLockManager=exports.WorktreeManager=void 0
|
|
4218
4199
|
var r=t(1502)
|
|
4219
4200
|
Object.defineProperty(exports,"WorktreeManager",{enumerable:!0,get(){return r.WorktreeManager}})
|
|
@@ -4309,7 +4290,7 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
4309
4290
|
var t={}
|
|
4310
4291
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4311
4292
|
return o(t,e),t})
|
|
4312
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,t,r,n,o,s,g,p
|
|
4293
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,t,r,n,o,s,g,f,p){const m=g.child({tool:"manage_files"})
|
|
4313
4294
|
try{const h=a.validateArgs(e,i.ManageFilesSchema),{taskId:g,operations:y,comment:w}=h
|
|
4314
4295
|
m.info("Processing manage-files operations",{taskId:g,operationCount:y.length,comment:w})
|
|
4315
4296
|
const k=[],b=[],I=[],v=[]
|
|
@@ -4321,18 +4302,18 @@ case"delete-files":I.push(...e.deleteFiles.targets)
|
|
|
4321
4302
|
break
|
|
4322
4303
|
case"get-file-info":v.push({path:e.getFileInfo.path})}const C=[]
|
|
4323
4304
|
for(const e of k){m.info("Routing to create-directory handler",{path:e.path})
|
|
4324
|
-
const s=await(0,c.handleCreateDirectory)({taskId:g,path:e.path,comment:w+" [via manage-files: create-directory]"},t,r,n,o,m,p
|
|
4305
|
+
const s=await(0,c.handleCreateDirectory)({taskId:g,path:e.path,comment:w+" [via manage-files: create-directory]"},t,r,n,o,m,f,p)
|
|
4325
4306
|
C.push({type:"create-directory",result:s})}if(b.length>0){m.info("Routing to move-files handler",{operationCount:b.length})
|
|
4326
|
-
const e=await(0,l.handleMoveFiles)({taskId:g,operations:b,comment:w+" [via manage-files: move-files]"},t,r,n,o,m,p
|
|
4307
|
+
const e=await(0,l.handleMoveFiles)({taskId:g,operations:b,comment:w+" [via manage-files: move-files]"},t,r,n,o,m,f,p)
|
|
4327
4308
|
C.push({type:"move-files",result:e})}if(I.length>0){m.info("Routing to delete-files handler",{operationCount:I.length})
|
|
4328
|
-
const e=await(0,u.handleDeleteFiles)({taskId:g,operations:I,comment:w+" [via manage-files: delete-files]"},t,s,m,p
|
|
4309
|
+
const e=await(0,u.handleDeleteFiles)({taskId:g,operations:I,comment:w+" [via manage-files: delete-files]"},t,s,m,f,p)
|
|
4329
4310
|
C.push({type:"delete-files",result:e})}for(const e of v){m.info("Routing to get-file-info handler",{path:e.path})
|
|
4330
|
-
const r=await(0,d.handleGetFileInfo)({path:e.path},t,m,
|
|
4311
|
+
const r=await(0,d.handleGetFileInfo)({path:e.path},t,m,f)
|
|
4331
4312
|
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
|
|
4332
4313
|
let S="## Manage Files Results\n\n"
|
|
4333
4314
|
S+="**Summary:**\n",S+=`- **Total operation types:** ${C.length}\n`,S+=`- **Successful:** ${E}\n`,S+=`- **Failed:** ${q}\n\n`
|
|
4334
4315
|
for(const{type:e,result:t}of C)S+=`### ${e} operations\n`,S+=t.content[0].text+"\n\n"
|
|
4335
|
-
return m.info("Manage-files operations completed",{totalOperationTypes:C.length,successCount:E,errorCount:q}),
|
|
4316
|
+
return m.info("Manage-files operations completed",{totalOperationTypes:C.length,successCount:E,errorCount:q}),f.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+""}),f.incrementCounter("manage_files_errors",1),{content:[{type:"text",text:"\u274c **Manage Files Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
|
|
4336
4317
|
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){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4337
4318
|
const r=t(6183),n=t(5303)
|
|
4338
4319
|
exports.def={name:"plan_read",description:"Read project plans.\n\nOperations:\n\u2022 get - Get a plan by ID with full content\n\u2022 list - List all plans in the project\n\u2022 get-history - View version history of a plan\n\u2022 get-requests - List requests linked to a plan",schema:r.PlanReadSchema,annotations:{title:"Plan Read",readOnlyHint:!0},readOnly:!0,handler(e,t){return(0,n.handlePlanRead)(e,t.context,t.apiClient,t.logger,t.metrics)}}},7784(e,exports,t){async function validateWorktreeForConflictResolution(e,r,s){const i=[],a=o.default.join(r,e),c="requests/"+e
|
|
@@ -4353,8 +4334,8 @@ const n=r(t(9896)),o=r(t(6928))},7834(e,exports,t){Object.defineProperty(exports
|
|
|
4353
4334
|
const r=t(5806),n=t(5715)
|
|
4354
4335
|
exports.def={name:"complete_request",description(e){return e.testsRequired?"Mark request as complete with test verification":"Mark request as complete (no test verification needed)"},schema(){return(0,r.getDynamicCompleteRequestSchema)()},annotations:{title:"Complete Request",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0},hidden:!0,handler(e,t){return(0,n.handleCompleteRequest)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},7849(e,exports,t){async function r(e,t,r,n,o,s,a,l,d,u){const h=Date.now()
|
|
4355
4336
|
if(!r||""===r.trim())throw new c.ValidationError("Project ID is required and cannot be empty for tool record creation")
|
|
4356
|
-
try{const c=await a.createToolRecord({taskId:e,requestId:t,projectId:r,type:n,metadata:{path:o,operation:n,status:"pending",timestamp:(new Date).toISOString(),fileExtension:i.default.extname(o).slice(1),fileOperationId:`${e}-${Date.now()}`,...s},note:`${"write-file"===n?"Writing":"Modifying"} file: ${o}`}),g=c.id,
|
|
4357
|
-
return l.info("Tool record created with IDs",{recordId:g,localRecordId:
|
|
4337
|
+
try{const c=await a.createToolRecord({taskId:e,requestId:t,projectId:r,type:n,metadata:{path:o,operation:n,status:"pending",timestamp:(new Date).toISOString(),fileExtension:i.default.extname(o).slice(1),fileOperationId:`${e}-${Date.now()}`,...s},note:`${"write-file"===n?"Writing":"Modifying"} file: ${o}`}),g=c.id,f=c.localId
|
|
4338
|
+
return l.info("Tool record created with IDs",{recordId:g,localRecordId:f,hasLocalId:!!c.localId,recordKeys:Object.keys(c),fullRecord:JSON.stringify(c)}),l.info("Created tool record for file operation: "+n,{taskId:e,projectId:r,path:o,recordId:g,localRecordId:f}),d.recordValue(u+"_tool_record_creation_time",Date.now()-h),d.incrementCounter(u+"_tool_record_creation_success",1),{recordId:g,localRecordId:f}}catch(t){d.incrementCounter(u+"_tool_record_creation_failure",1),d.recordValue(u+"_tool_record_creation_time",Date.now()-h)
|
|
4358
4339
|
const n=t instanceof Error?`${t.message} (${JSON.stringify(t)})`:t+""
|
|
4359
4340
|
return l.warn("Failed to create tool record for file operation: "+n,{taskId:e,projectId:r,path:o,error:t instanceof Error?t.stack:t+""}),{}}}async function n(e,t,r,n,o,s,a,c,l){const u=Date.now()
|
|
4360
4341
|
try{await s.updateToolRecord(e,{metadata:{path:t,operation:r,timestamp:(new Date).toISOString(),fileExtension:i.default.extname(t).slice(1),fileUpdateId:`${e}-${Date.now()}`,...n},note:o}),a.info("Updated tool record for file operation: "+r,{path:t,recordId:e,status:n.status}),c.recordValue(l+"_tool_record_update_time",Date.now()-u),c.incrementCounter(l+"_tool_record_update_success",1)}catch(n){c.incrementCounter(l+"_tool_record_update_failure",1),c.recordValue(l+"_tool_record_update_time",Date.now()-u),a.warn("Failed to update tool record for file operation: "+r,{path:t,recordId:e,error:(0,d.getErrorMessage)(n)})}}async function o(e,t,r,n,o){const{operationType:s,toolRecordId:i,successField:c,logger:l,metrics:u,metricsPrefix:h}=n
|
|
@@ -4367,35 +4348,35 @@ if(o.workspaceManager){const t=o.workspaceManager.getCurrentContext()
|
|
|
4367
4348
|
"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}
|
|
4368
4349
|
let g=null
|
|
4369
4350
|
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)
|
|
4370
|
-
const
|
|
4371
|
-
return l.info("Changes committed to git via shared multi-file utility",{commitMessage:
|
|
4351
|
+
const f=1===n.length?`${s} in ${n[0]} (${i})`:`${s} in ${n.length} files (${i})`,p=(await d.commit(f)).commit
|
|
4352
|
+
return l.info("Changes committed to git via shared multi-file utility",{commitMessage:f,filesCommitted:n.length,commitHash:p?.substring(0,8),previousCommitHash:g?.substring(0,8),toolRecordId:i,operationType:s}),u.incrementCounter(h+"_git_commit_success",1),u.recordValue(h+"_files_committed",n.length),{commitHash:p,previousCommitHash:g,filesCommitted:n,success:!0}}catch(e){const t=(0,d.getErrorMessage)(e)
|
|
4372
4353
|
return l.warn("Git operations failed via shared multi-file utility",{error:t,operationType:s,note:"File changes were saved but not committed to git"}),u.incrementCounter(h+"_git_commit_failure",1),{filesCommitted:[],success:!1,error:t}}}var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
4373
4354
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.createToolRecord=r,exports.updateToolRecord=n,exports.createFileOperationRecords=async function(e,t,n,o,s,i,a,c,l,u,h){const g=Date.now()
|
|
4374
|
-
let p
|
|
4355
|
+
let f,p
|
|
4375
4356
|
l.debug("createFileOperationRecords called",{taskId:e,requestId:t,projectId:n||"<empty>",projectIdType:typeof n,operationType:o,path:s})
|
|
4376
4357
|
try{const a=await r(e,t,n,o,s,i,c,l,u,h)
|
|
4377
|
-
return
|
|
4358
|
+
return f=a.recordId,p=a.localRecordId,l.info("Created tool record for file operation: "+o,{taskId:e,path:s,toolRecordId:f,localToolRecordId:p}),{toolRecordId:f,localToolRecordId:p}}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,f){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,f)}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}
|
|
4378
4359
|
try{let s=t.git
|
|
4379
4360
|
if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext()
|
|
4380
4361
|
"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)
|
|
4381
4362
|
const t=await s.commit("[USER-MODS] Preserve user modifications before tool operation: "+e)
|
|
4382
4363
|
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()
|
|
4383
|
-
let g,
|
|
4384
|
-
try{let
|
|
4364
|
+
let g,f=null
|
|
4365
|
+
try{let p=s.git
|
|
4385
4366
|
if(s.workspaceManager){const t=s.workspaceManager.getCurrentContext()
|
|
4386
4367
|
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.`)
|
|
4387
|
-
|
|
4368
|
+
p=(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(p){i.info("commitToGit called with:",{taskId:e,recordId:r,localRecordId:n,hasLocalRecordId:!!n,localRecordIdType:typeof n,normalizedPath:t})
|
|
4388
4369
|
let a=!1,m=""
|
|
4389
|
-
try{if(m=(await
|
|
4370
|
+
try{if(m=(await p.raw(["rev-parse","--show-toplevel"])).trim(),a=m.includes("/worktrees/")||m.includes("\\worktrees\\"),i.info("Git context detection for commit operation:",{taskId:e,gitRepoPath:m,isWorktreeOperation:a,multiAgentMode:s.multiAgentMode,targetFile:t,expectedContext:s.multiAgentMode?"worktree":"main repo"}),s.multiAgentMode&&!a)throw i.error("CRITICAL: Multi-agent operation using main repo Git instead of worktree",{taskId:e,detectedPath:m,targetFile:t,currentRequestId:s.getCurrentRequestId?s.getCurrentRequestId():"unknown"}),Error(`Git context mismatch: Multi-agent operation attempted to commit ${t} using main repository Git instance at ${m}, but should use worktree Git instance. This will fail due to .gitignore rules.`)}catch(e){i.warn("Failed to get Git instance info:",{error:e instanceof Error?e.message:e+""})}try{const r=await p.revparse(["--abbrev-ref","HEAD"]),n=await p.revparse(["HEAD"]),o=await p.revparse(["--show-toplevel"])
|
|
4390
4371
|
i.info("Git repository status before commit:",{taskId:e,currentBranch:r.trim(),currentCommit:n.trim().substring(0,8),repoPath:o.trim(),targetFile:t,multiAgentMode:s.multiAgentMode||!1,currentRequestId:s.getCurrentRequestId?s.getCurrentRequestId():"none"})
|
|
4391
4372
|
const a=r.trim(),c=s.getCurrentRequestId?s.getCurrentRequestId():null
|
|
4392
4373
|
if(s.multiAgentMode&&c){const t="requests/"+c
|
|
4393
|
-
a!=="requests/"+c?i.warn("Multi-agent file operation may be on wrong branch",{taskId:e,actualBranch:a,expectedPattern:t,requestId:c}):i.info("Multi-agent file operation on expected branch",{taskId:e,branchName:a,requestId:c})}}catch(e){i.warn("Failed to get Git status before commit:",{error:e instanceof Error?e.message:e+""})}try{if(
|
|
4394
|
-
|
|
4395
|
-
await
|
|
4396
|
-
try{const r=await
|
|
4397
|
-
i.info("Git repository status after commit:",{taskId:e,postCommitBranch:r.trim(),postCommitHash:n.trim().substring(0,8),commitAdvanced:n.trim()!==(
|
|
4398
|
-
return{commitHash:g,previousCommitHash:
|
|
4374
|
+
a!=="requests/"+c?i.warn("Multi-agent file operation may be on wrong branch",{taskId:e,actualBranch:a,expectedPattern:t,requestId:c}):i.info("Multi-agent file operation on expected branch",{taskId:e,branchName:a,requestId:c})}}catch(e){i.warn("Failed to get Git status before commit:",{error:e instanceof Error?e.message:e+""})}try{if(p){const r=await p.revparse(["HEAD"])
|
|
4375
|
+
f=await(0,l.findPreviousCommit)(p,t,r),i.info(`Previous commit hash for ${t}: ${f||"none (new file)"}`,{taskId:e,gitInstancePath:m||"unknown",isWorktreeOperation:a,usingCorrectGitInstance:!0})}else i.warn("Git not available for previous commit detection: "+t,{taskId:e,reason:"no_git_instance"})}catch(e){i.warn(`Failed to find previous commit for ${t}:`,{error:(0,d.getErrorMessage)(e)})}const y=n?`[RECORD:${n}] ${o}`:o
|
|
4376
|
+
await p.add(t),g=(await p.commit(y)).commit
|
|
4377
|
+
try{const r=await p.revparse(["--abbrev-ref","HEAD"]),n=await p.revparse(["HEAD"])
|
|
4378
|
+
i.info("Git repository status after commit:",{taskId:e,postCommitBranch:r.trim(),postCommitHash:n.trim().substring(0,8),commitAdvanced:n.trim()!==(f||""),targetFile:t}),g&&n.trim()!==g&&i.warn("Commit hash mismatch after commit",{taskId:e,expectedCommitHash:g,actualHeadHash:n.trim(),targetFile:t})}catch(e){i.warn("Failed to verify post-commit status:",{error:e instanceof Error?e.message:e+""})}i.info("Committed file changes to Git: "+t,{taskId:e,path:t,recordId:r,localRecordId:n,commitHash:g,previousCommitHash:f}),c.recordValue(u+"_git_commit_time",Date.now()-h),c.incrementCounter(u+"_git_commit_success",1)}else i.warn("No Git repository available, skipping commit",{taskId:e,path:t})
|
|
4379
|
+
return{commitHash:g,previousCommitHash:f}}catch(r){return c.incrementCounter(u+"_git_commit_failure",1),c.recordValue(u+"_git_commit_time",Date.now()-h),i.warn("Failed to commit file changes to Git: "+t,{taskId:e,path:t,error:r instanceof Error?r.stack:r+""}),{commitHash:void 0,previousCommitHash:f}}},exports.commitMultipleFilesToGit=o,exports.handleMultiFileGitCommit=async function(e,t,r,n,s,i){const{logger:a,metricsPrefix:c,metrics:l}=s
|
|
4399
4380
|
return 0===t.length||0===n?(a.debug("No file operations with changes to commit"),{filesCommitted:[],success:!0}):(l.incrementCounter(c+"_phase",1,{phase:u.FileOperationPhase.GIT_COMMIT}),await o(e,t,r,s,i))}
|
|
4400
4381
|
const i=s(t(6928)),a=t(3807),c=t(9860),l=t(9671),d=t(8824),u=t(7575)},7960(e,exports){function t(){const e=process.argv[1]||""
|
|
4401
4382
|
if(e.includes("/dist-dev/")||e.includes("\\dist-dev\\"))return!0
|
|
@@ -4405,17 +4386,17 @@ return!(!t.includes("/dist-dev")&&!t.includes("\\dist-dev"))}Object.defineProper
|
|
|
4405
4386
|
if(r.debug("getClientInfoForMetadata called",{mcpServerExists:!!e,mcpServerType:typeof e,hasGetClientInfo:e?typeof e.getClientInfo:void 0,mcpServerKeys:e?Object.keys(e):void 0}),e&&"function"==typeof e.getClientInfo)try{t=e.getClientInfo(),r.debug("mcpServer.getClientInfo() returned",{clientInfo:t,clientInfoType:typeof t,name:t?.name,version:t?.version})}catch(e){r.debug("mcpServer.getClientInfo() failed",{error:e})}else r.debug("mcpServer not available or getClientInfo not a function")
|
|
4406
4387
|
const n={clientName:t.name,clientVersion:t.version}
|
|
4407
4388
|
return r.debug("getClientInfoForMetadata returning",{result:n}),n}
|
|
4408
|
-
const r=t(3444).defaultLogger.child({component:"client-info-utils"})},8035(e,exports,t){function r(e,t,r){try{const n=`[${(new Date).toISOString()}] [detached-subagent] ${t}${r?" "+JSON.stringify(r):""}\n`,o=(0,a.join)(e||process.cwd(),".alchemy_lab","spawn-debug.log");(0,i.appendFileSync)(o,n)}catch{}}function n(e){const{agent:t,prompt:n,cwd:c,parentServerUrl:l,parentSessionId:d,sessionId:u,model:h,initialBranch:g,serverUrl:
|
|
4389
|
+
const r=t(3444).defaultLogger.child({component:"client-info-utils"})},8035(e,exports,t){function r(e,t,r){try{const n=`[${(new Date).toISOString()}] [detached-subagent] ${t}${r?" "+JSON.stringify(r):""}\n`,o=(0,a.join)(e||process.cwd(),".alchemy_lab","spawn-debug.log");(0,i.appendFileSync)(o,n)}catch{}}function n(e){const{agent:t,prompt:n,cwd:c,parentServerUrl:l,parentSessionId:d,sessionId:u,model:h,initialBranch:g,serverUrl:f,onSpawn:p,onError:m}=e
|
|
4409
4390
|
try{const s={...process.env}
|
|
4410
4391
|
l&&(s.OPENCODE_PARENT_SERVER=l),g&&(s.ALCHEMY_INITIAL_BRANCH=g),e.allowParallel&&(s.ALCHEMY_ALLOW_PARALLEL="1")
|
|
4411
4392
|
const d=new Date,m=`${(d.getHours()+"").padStart(2,"0")}${(d.getMinutes()+"").padStart(2,"0")}${(d.getSeconds()+"").padStart(2,"0")}`,y=Math.random().toString(36).substring(2,7)
|
|
4412
4393
|
let w
|
|
4413
|
-
if(s.ALCHEMY_SESSION_TAG=`mcp-${m}-${y}`,r(c,"Spawn env setup",{agent:t,initialBranch:g||"none",hasParentServer:!!l,sessionId:u||"new",attachMode:!!
|
|
4394
|
+
if(s.ALCHEMY_SESSION_TAG=`mcp-${m}-${y}`,r(c,"Spawn env setup",{agent:t,initialBranch:g||"none",hasParentServer:!!l,sessionId:u||"new",attachMode:!!f}),w=f&&u&&n?["run","--attach",f,"--session",u,"--agent",t,n]:u&&n?["run","--session",u,"--agent",t,n]:n?["run","--agent",t,n]:["run","--agent",t],h){const e=w.findIndex((e=>e===n))
|
|
4414
4395
|
e>0?w.splice(e,0,"--model",h):w.push("--model",h)}r(c,"Spawning opencode",{args:w.map((e=>e===n?`[prompt:${e.length}chars]`:e)),model:h||"not specified",promptLength:n?.length,promptPreview:n?.slice(0,100),cwd:c,hasSessionId:!!u,hasParentServerUrl:!!l})
|
|
4415
4396
|
const k=(0,a.join)(c||process.cwd(),".alchemy_lab"),b=(0,a.join)(k,"spawn-stderr.log")
|
|
4416
4397
|
let I
|
|
4417
4398
|
try{I=(0,i.openSync)(b,"a")}catch{}const v=(0,o.spawn)("opencode",w,{detached:!0,stdio:["ignore","ignore",I??"ignore"],cwd:c||process.cwd(),env:s})
|
|
4418
|
-
return v.unref(),
|
|
4399
|
+
return v.unref(),p&&p(v.pid),{success:!0,pid:v.pid}}catch(e){const t=(0,s.getErrorMessage)(e)
|
|
4419
4400
|
return m&&e instanceof Error&&m(e),{success:!1,error:t}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.spawnDetachedSubagent=n,exports.spawnJournalSubagent=function(e,t,r,o){return n({agent:"journal",prompt:`Generate a journal entry for request ${e}.\n\nSteps:\n1. Use ${t}__generate_request_journal tool with requestId: ${e}\n2. Write a concise narrative journal entry based on the returned data covering:\n - What was implemented and why\n - Key decisions and trade-offs made\n - Challenges encountered and solutions\n - Files modified and their purposes\n - How acceptance criteria were met\n3. Save as JOURNAL-${e}.md using ${t}__document_operations (operation: create, type: Report)\n\nKeep it story-focused and informative.`,cwd:r,parentServerUrl:o})},exports.spawnWorkSubagent=function(e,t,r){return n({agent:"work",prompt:e,cwd:t,parentServerUrl:r})}
|
|
4420
4401
|
const o=t(5317),s=t(8824),i=t(9896),a=t(6928)},8037(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListRequests=async function(e,t,i,a,c){const l=a.child({tool:"list_requests"}),d=c.startTimer("tool_execution_time")
|
|
4421
4402
|
try{const{filters:s={}}=e,a=["open","in_progress","ready_for_review","completed","canceled","reverted"]
|
|
@@ -4430,18 +4411,18 @@ s.status&&"undefined"!==s.status&&(u.status=s.status),s.type&&"undefined"!==s.ty
|
|
|
4430
4411
|
const h=i.getRequestClient(),g=await h.listRequests(u)
|
|
4431
4412
|
if(l.debug("=== RAW SERVER RESPONSE DEBUG ===",{responseType:typeof g,isArray:Array.isArray(g),responseKeys:g?Object.keys(g):[],fullResponse:JSON.stringify(g,null,2)}),g&&"object"==typeof g&&"data"in g){const e=g.data
|
|
4432
4413
|
l.debug("=== SERVER RESPONSE DATA SECTION ===",{dataType:typeof e,isDataArray:Array.isArray(e),dataLength:Array.isArray(e)?e.length:"not array",firstItemKeys:Array.isArray(e)&&e.length>0?Object.keys(e[0]):"no items",firstItemSample:Array.isArray(e)&&e.length>0?JSON.stringify(e[0],null,2):"no items"}),Array.isArray(e)&&e.length>0&&e.slice(0,3).forEach(((e,t)=>{l.info(`=== ITEM ${t+1} LOCK INFO CHECK ===`,{id:e.id,hasLockInfo:"lockInfo"in e,lockInfoValue:e.lockInfo,allKeys:Object.keys(e),lockRelatedKeys:Object.keys(e).filter((e=>e.toLowerCase().includes("lock")))})}))}l.debug("Raw requests response data",{responseData:JSON.stringify(g)}),l.debug("Requests response structure",{type:typeof g,isArray:Array.isArray(g),hasData:null!=g,properties:g?Object.keys(g):[],dataPreview:g?JSON.stringify(g).substring(0,200)+"...":"null"}),l.debug("=== BEFORE EXTRACTION ===",{responseHasData:g&&"data"in g,responseDataLength:g&&"data"in g&&Array.isArray(g.data)?g.data.length:"not array",firstItemBeforeExtraction:g&&"data"in g&&Array.isArray(g.data)&&g.data.length>0?{id:g.data[0].id,hasLockInfo:"lockInfo"in g.data[0],lockInfo:g.data[0].lockInfo,allKeys:Object.keys(g.data[0])}:"no data"})
|
|
4433
|
-
const
|
|
4434
|
-
l.info("=== AFTER EXTRACTION ===",{extractedCount:
|
|
4435
|
-
const
|
|
4436
|
-
if(l.debug("Lock info analysis",{multiAgentModeEnabled:
|
|
4437
|
-
l.info("=== PRE-DISPLAY REQUEST ANALYSIS ===",{totalRequests:
|
|
4438
|
-
const m=
|
|
4439
|
-
if(l.info(`=== FORMATTING REQUEST ${e.id} ===`,{multiAgentMode:
|
|
4414
|
+
const f=(0,n.extractArrayFromResponse)(g,{logger:l,operationName:"listRequests",defaultValue:[]})
|
|
4415
|
+
l.info("=== AFTER EXTRACTION ===",{extractedCount:f.length,firstItemAfterExtraction:f.length>0?{id:f[0].id,hasLockInfo:"lockInfo"in f[0],lockInfo:f[0].lockInfo,allKeys:Object.keys(f[0])}:"no items"}),l.info(`Extracted ${f.length} requests from response`)
|
|
4416
|
+
const p=t.multiAgentMode||!1
|
|
4417
|
+
if(l.debug("Lock info analysis",{multiAgentModeEnabled:p,requestCount:f.length,environmentVariable:process.env.ALCHEMY_MULTI_AGENT,firstRequestSample:f.length>0?{id:f[0].id,hasLockInfo:!!f[0].lockInfo,lockInfo:f[0].lockInfo,allProperties:Object.keys(f[0])}:"No requests to sample"}),f.length>0&&f.forEach(((e,t)=>{l.debug(`Request ${t+1} lock debug`,{id:e.id,title:e.title?.substring(0,50)+"...",hasLockInfo:!!e.lockInfo,lockInfoDetails:e.lockInfo||"NO LOCK INFO",allKeys:Object.keys(e).filter((e=>e.includes("lock")||e.includes("Lock")))})})),0===f.length)return d({success:!0,requestCount:0}),{content:[{type:"text",text:"No requests found with the specified filters."}]}
|
|
4418
|
+
l.info("=== PRE-DISPLAY REQUEST ANALYSIS ===",{totalRequests:f.length,multiAgentMode:p,environmentVar:process.env.ALCHEMY_MULTI_AGENT}),f.forEach(((e,t)=>{l.info(`=== REQUEST ${t+1}/${f.length} PRE-DISPLAY ANALYSIS ===`,{id:e.id,title:e.title?.substring(0,30)+"...",hasLockInfo:"lockInfo"in e,lockInfoType:typeof e.lockInfo,lockInfoValue:e.lockInfo,lockInfoIsNull:null===e.lockInfo,lockInfoIsUndefined:void 0===e.lockInfo,allProperties:Object.keys(e),lockRelatedProperties:Object.keys(e).filter((e=>e.toLowerCase().includes("lock")||e.toLowerCase().includes("session")||e.toLowerCase().includes("expire")))}),e.lockInfo&&l.info(`=== REQUEST ${e.id} LOCK INFO DEEP DIVE ===`,{lockInfoKeys:Object.keys(e.lockInfo),isLocked:e.lockInfo.isLocked,lockedBySessionTag:e.lockInfo.lockedBySessionTag,timeRemainingFormatted:e.lockInfo.timeRemainingFormatted,isExpired:e.lockInfo.isExpired,fullLockInfo:JSON.stringify(e.lockInfo,null,2)})}))
|
|
4419
|
+
const m=f.map((e=>{let t=""
|
|
4420
|
+
if(l.info(`=== FORMATTING REQUEST ${e.id} ===`,{multiAgentMode:p,hasLockInfo:!!e.lockInfo,lockInfoValue:e.lockInfo,willShowLockInfo:!!e.lockInfo,note:"Lock info displayed when available regardless of mode"}),e.lockInfo){if(l.debug(`Processing lock info for ${e.id}:`,e.lockInfo),e.lockInfo.isLocked&&!e.lockInfo.isExpired){const{sessionTag:r}=(0,o.getGlobalClientInfo)(),n=e.lockInfo.lockedBySessionTag||"unknown"
|
|
4440
4421
|
t=n===r?` [LOCKED by me, expires in ${e.lockInfo.timeRemainingFormatted}]`:` [LOCKED by ${n.length>20?n.substring(0,17)+"...":n}, expires in ${e.lockInfo.timeRemainingFormatted}]`}else t=" [AVAILABLE]"
|
|
4441
4422
|
l.debug(`Generated lock info for ${e.id}: "${t}"`)}else l.debug("No lock info available for "+e.id)
|
|
4442
|
-
return`**${e.title}** (${e.id}) [${e.type}]${t}\nStatus: ${e.status}\nType: ${e.type}\nCreated: ${new Date(e.createdAt).toLocaleString()}\nUpdated: ${new Date(e.updatedAt).toLocaleString()}\n`})).join("\n---\n"),y=
|
|
4443
|
-
let w=`Found ${
|
|
4444
|
-
return y&&
|
|
4423
|
+
return`**${e.title}** (${e.id}) [${e.type}]${t}\nStatus: ${e.status}\nType: ${e.type}\nCreated: ${new Date(e.createdAt).toLocaleString()}\nUpdated: ${new Date(e.updatedAt).toLocaleString()}\n`})).join("\n---\n"),y=f.some((e=>e.lockInfo))
|
|
4424
|
+
let w=`Found ${f.length} request${1===f.length?"":"s"}:`
|
|
4425
|
+
return y&&p&&(w+="\n\n**Lock Status:**\n",w+="LOCKED = Locked by an agent (shows session name and expiration)\n",w+="AVAILABLE = Not currently locked, safe to work on\n"),d({success:!0,requestCount:f.length}),{content:[{type:"text",text:`${w}\n\n${m}`}]}}catch(t){return l.error("Error listing requests",{args:e,error:t instanceof Error?t.stack:t+""}),d({success:!1,error:t instanceof Error?t.name:"unknown"}),{content:[{type:"text",text:"Error listing requests: "+(0,s.getErrorMessage)(t)}],isError:!0}}}
|
|
4445
4426
|
const r=t(9860),n=t(2960),o=t(5172),s=t(8824)},8045(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4446
4427
|
const r=t(6183),n=t(7456)
|
|
4447
4428
|
exports.def={name:"modify_file",description:'Make targeted edits to existing files and documents.\n\nOperations:\n\u2022 replace-string - Find and replace text\n - mode: \'unique\' (default, safer - fails if multiple matches)\n - mode: \'all\' (replaces all occurrences)\n\u2022 delete-string - Remove text patterns (same modes as replace-string)\n\u2022 insert-lines - Insert content before/after/between lines\n\u2022 replace-lines - Replace specific line numbers\n\u2022 delete-lines - Remove specific line numbers\n\nLine specification (string format for line-based operations):\n- Single line: "lines": "5"\n- Multiple lines: "lines": "1,3,7,10"\n- Range: "lines": "10-15"\n\nRead file first to know line numbers. Supports multiple files and operations in one call. Works with both filesystem files (path) and tracked documents (documentId).',schema:r.ModifyFileSchema,annotations:{title:"Modify File",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},hidden:!0,handler(e,t){return(0,n.handleModifyFile)(e,t.context,t.apiClient.getTaskClient(),t.apiClient.getToolRecordClient(),t.apiClient.getRequestClient(),t.logger,t.metrics,t.mcpServer)}}},8291(e,exports,t){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
@@ -4468,33 +4449,33 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
4468
4449
|
var t={}
|
|
4469
4450
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4470
4451
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
4471
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,t,r,n,o,s,i,
|
|
4452
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,t,r,n,o,s,i,f){const p=s.child({tool:"create_directory"}),m=Date.now()
|
|
4472
4453
|
let y,w,k=d.FileOperationPhase.VALIDATION
|
|
4473
4454
|
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}"}
|
|
4474
4455
|
try{const s=d.validateArgs(e,l.CreateDirectorySchema),{taskId:u,path:h,comment:g}=s
|
|
4475
|
-
|
|
4456
|
+
p.info("Creating directory: "+h,{taskId:u,path:h,comment:g}),d.validateTaskIdFormat(u,p,i,b.metricsPrefix),t.getCurrentBranchContext&&await t.getCurrentBranchContext()
|
|
4476
4457
|
const{normalizedPath:I,fullPath:v}=d.validateAndNormalizePath(h,t)
|
|
4477
4458
|
k=d.FileOperationPhase.TASK_VALIDATION,i.incrementCounter("create_directory_phase",1,{phase:k})
|
|
4478
|
-
const C=await d.validateTaskId(u,I,r,
|
|
4479
|
-
q.taskPromoted&&
|
|
4480
|
-
const S=await d.ensureCorrectWorkspaceContext({taskPromoted:q.taskPromoted,requestId:_,context:t,operation:"create-directory",logger:
|
|
4459
|
+
const C=await d.validateTaskId(u,I,r,p,i,b.metricsPrefix),_=C?.requestId,E=await d.validateWorkItemStates(u,I,r,o,t,p,i,b.metricsPrefix),q=await d.autoPromoteTaskStatus(u,C.status,_,E.request?.status,I,r,o,p,i,b.metricsPrefix)
|
|
4460
|
+
q.taskPromoted&&p.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&&p.info(`Auto-promoted request ${_} to in_progress for file operation`,{requestId:_,previousStatus:E.request?.status,newStatus:q.newRequestStatus,triggeringTaskId:u})
|
|
4461
|
+
const S=await d.ensureCorrectWorkspaceContext({taskPromoted:q.taskPromoted,requestId:_,context:t,operation:"create-directory",logger:p,metrics:i,metricsPrefix:b.metricsPrefix})
|
|
4481
4462
|
if(!S.success){if(S.isLockConflict)return{content:[{type:"text",text:"\u274c "+S.error}],isError:!0}
|
|
4482
4463
|
throw Error(S.error)}let T=!1
|
|
4483
4464
|
try{T=(await a.default.stat(v)).isDirectory()}catch{T=!1}k=d.FileOperationPhase.RECORD_CREATION,i.incrementCounter("create_directory_phase",1,{phase:k})
|
|
4484
|
-
const{toolRecordId:M,localToolRecordId:R}=await d.createFileOperationRecords(u,_,t.projectId,b.recordType,I,{directoryExists:T,userComment:g},r,n,
|
|
4465
|
+
const{toolRecordId:M,localToolRecordId:R}=await d.createFileOperationRecords(u,_,t.projectId,b.recordType,I,{directoryExists:T,userComment:g},r,n,p,i,b.metricsPrefix,f)
|
|
4485
4466
|
y=M,w=M,k=b.fileOperationPhase,i.incrementCounter("create_directory_phase",1,{phase:k})
|
|
4486
4467
|
let P=T
|
|
4487
|
-
if(!T){await a.default.mkdir(v,{recursive:!0}),
|
|
4468
|
+
if(!T){await a.default.mkdir(v,{recursive:!0}),p.info("Successfully created directory "+I)
|
|
4488
4469
|
try{const e=c.default.join(v,".gitkeep")
|
|
4489
|
-
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),P=!0,
|
|
4470
|
+
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),P=!0,p.info("Created .gitkeep file for Git tracking")}catch(e){p.warn("Failed to create .gitkeep file",{error:e instanceof Error?e.message:e+""}),P=!1}}const x=Date.now()-m
|
|
4490
4471
|
i.recordValue("create_directory_time",x),i.incrementCounter("create_directory_success",1),k=d.FileOperationPhase.GIT_COMMIT,i.incrementCounter("create_directory_phase",1,{phase:k})
|
|
4491
|
-
const O=`Create directory: ${I} - ${g||"Create directory"}`,j=!T&&P?I+"/.gitkeep":I,$=await d.commitToGit(u,j,M,R,O,t,
|
|
4492
|
-
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:$.commitHash,previousCommitHash:$.previousCommitHash,directoryExists:T,isDirectory:!0,userComment:g},`Successfully ${T?"verified":"created"} directory: ${I}`,r,n,
|
|
4493
|
-
const
|
|
4494
|
-
return{content:[{type:"text",text:T?"Directory already exists":`Successfully created directory${$.commitHash?"\nCommit: "+$.commitHash.substring(0,8):""}${
|
|
4495
|
-
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){
|
|
4496
|
-
if(i.recordValue("create_directory_time",s),i.incrementCounter("create_directory_errors",1),
|
|
4497
|
-
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,
|
|
4472
|
+
const O=`Create directory: ${I} - ${g||"Create directory"}`,j=!T&&P?I+"/.gitkeep":I,$=await d.commitToGit(u,j,M,R,O,t,p,i,b.metricsPrefix)
|
|
4473
|
+
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:$.commitHash,previousCommitHash:$.previousCommitHash,directoryExists:T,isDirectory:!0,userComment:g},`Successfully ${T?"verified":"created"} directory: ${I}`,r,n,p,i,b.metricsPrefix)
|
|
4474
|
+
const D=t.getCurrentBranchContext?await t.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
4475
|
+
return{content:[{type:"text",text:T?"Directory already exists":`Successfully created directory${$.commitHash?"\nCommit: "+$.commitHash.substring(0,8):""}${D.requestId?"\nBranch: "+D.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
|
|
4476
|
+
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){p.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
|
|
4477
|
+
if(i.recordValue("create_directory_time",s),i.incrementCounter("create_directory_errors",1),p.error("Error creating directory:",{error:(0,g.getErrorMessage)(o),time:s}),(y||w)&&e.taskId){k=d.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
4478
|
+
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,p,i,b.metricsPrefix)}catch(t){p.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,p,i,e,b)}}
|
|
4498
4479
|
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){function r(e){const t=[]
|
|
4499
4480
|
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"
|
|
4500
4481
|
case"replace-in-files":return"\u{1f504} Replace in Files"
|
|
@@ -4502,11 +4483,11 @@ case"move-files":return"\u{1f4cb} Move Files"
|
|
|
4502
4483
|
case"delete-files":return"\u{1f5d1}\ufe0f Delete Files"
|
|
4503
4484
|
case"manage-files":return"\u{1f4c1} Manage Files"
|
|
4504
4485
|
default:return e}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestFileHistory=async function(e,t,a,c,l){const d=c.child({tool:"request_file_history"}),u=l.startTimer("tool_execution_time")
|
|
4505
|
-
try{const{requestId:c,detailLevel:h="summary",taskId:g,showDiff:
|
|
4486
|
+
try{const{requestId:c,detailLevel:h="summary",taskId:g,showDiff:f=!1,fileFilter:p}=e
|
|
4506
4487
|
if(!c)throw(0,o.createValidationError)("Request ID is required")
|
|
4507
4488
|
if(!/^req[_\d].+$/.test(c))throw(0,o.createValidationError)(`Invalid request ID format: ${c}. Expected format: req_[26 chars] or req######`)
|
|
4508
4489
|
if(g&&!/^tas\d{6}$/.test(g))throw(0,o.createValidationError)(`Invalid task ID format: ${g}. Expected format: tas######`)
|
|
4509
|
-
if(d.info("Getting file changes for request "+c,{detailLevel:h,taskId:g,showDiff:
|
|
4490
|
+
if(d.info("Getting file changes for request "+c,{detailLevel:h,taskId:g,showDiff:f}),!t.git)throw Error("Git integration not available in this context")
|
|
4510
4491
|
const m=t.projectId
|
|
4511
4492
|
let y
|
|
4512
4493
|
a.setProjectId(m)
|
|
@@ -4529,7 +4510,7 @@ let r=0
|
|
|
4529
4510
|
e.forEach((e=>{e.replacements&&(r+=e.replacements.length)})),d+=`**Replacements**: ${r}\n`}if(t.metadata?.commitHash&&(d+=`**Commit**: ${t.metadata.commitHash.substring(0,8)}\n`,s||5>=h.length))try{const e=await a.diff([t.metadata.commitHash+"^",t.metadata.commitHash])
|
|
4530
4511
|
if(e&&e.trim()){const r=500,n=e.length
|
|
4531
4512
|
if(n>r){const o=e.substring(0,r),s=(n/1024).toFixed(1)
|
|
4532
|
-
d+=`\n**Changes preview** (first ${r} chars):\n\`\`\`diff\n${o}\n\`\`\`\n`,d+=`... (diff truncated, ${s}KB total)\n`,d+=`\u{1f4a1} Use \`file-history\` tool with commit \`${t.metadata.commitHash.substring(0,8)}\` to see full diff\n`}else d+=`\n**Changes:**\n\`\`\`diff\n${e}\n\`\`\`\n`}}catch(e){c.debug("Could not fetch diff for commit",{commit:t.metadata.commitHash,error:(0,i.getErrorMessage)(e)})}d+="\n---\n\n"}return d}(y,o,g,
|
|
4513
|
+
d+=`\n**Changes preview** (first ${r} chars):\n\`\`\`diff\n${o}\n\`\`\`\n`,d+=`... (diff truncated, ${s}KB total)\n`,d+=`\u{1f4a1} Use \`file-history\` tool with commit \`${t.metadata.commitHash.substring(0,8)}\` to see full diff\n`}else d+=`\n**Changes:**\n\`\`\`diff\n${e}\n\`\`\`\n`}}catch(e){c.debug("Could not fetch diff for commit",{commit:t.metadata.commitHash,error:(0,i.getErrorMessage)(e)})}d+="\n---\n\n"}return d}(y,o,g,f,t.git,d,p)
|
|
4533
4514
|
return u({success:!0,recordCount:o.length}),{content:[{type:"text",text:s}]}}{const e=a.getToolRecordClient()
|
|
4534
4515
|
let n=[]
|
|
4535
4516
|
try{g?(n=await e.getToolRecordsByTaskId(g),d.info(`Fetched ${n.length} records for task ${g}`)):(n=await e.getToolRecordsByRequestId(c),d.info(`Fetched ${n.length} records for request ${c}`))}catch(e){d.warn("Error fetching tool records: "+(0,i.getErrorMessage)(e)),n=[]}const o=await async function(e,t){const n=new Map
|
|
@@ -4539,7 +4520,7 @@ if(!["write-file","replace-in-files","move-files","delete-files","manage-files"]
|
|
|
4539
4520
|
o++
|
|
4540
4521
|
const i=r(s)
|
|
4541
4522
|
for(const e of i)t&&!RegExp(t.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")).test(e)||n.has(e)||n.set(e,{path:e,status:"M",linesAdded:0,linesDeleted:0,isBinary:!1})}const s=Array.from(n.values())
|
|
4542
|
-
return{summary:{filesChanged:s.length,linesAdded:0,linesDeleted:0,binaryFiles:0,renamedFiles:0,totalCommits:o,timespan:void 0},files:s}}(n,
|
|
4523
|
+
return{summary:{filesChanged:s.length,linesAdded:0,linesDeleted:0,binaryFiles:0,renamedFiles:0,totalCommits:o,timespan:void 0},files:s}}(n,p,t.git),s=function(e,t,r){const{requestInfo:n,branchInfo:o,summary:s,files:i,commits:a}=e
|
|
4543
4524
|
let c=`# File Changes for Request: ${n.id}\n\n`
|
|
4544
4525
|
if("Unknown Request"===n.title&&"unknown"===n.status||(c+=`**Request:** ${n.title}\n`,"unknown"!==n.status&&(c+=`**Status:** ${n.status}\n`),c+="\n"),r&&(c+=`**Filter:** \`${r}\`\n`),c+=`**Files Changed:** ${s.filesChanged}\n`,s.filesChanged>0&&(c+=`**Changes:** +${s.linesAdded} -${s.linesDeleted} lines\n`,s.totalCommits>0&&(c+=`**Commits:** ${s.totalCommits}\n`)),c+="\n",0===i.length)c+="No file changes found.\n\n"
|
|
4545
4526
|
else{const e=50,t=i.slice(0,e),r=i.length-e
|
|
@@ -4549,7 +4530,7 @@ case"D":return"\u{1f5d1}\ufe0f"
|
|
|
4549
4530
|
case"R":return"\u{1f4cb}"
|
|
4550
4531
|
case"C":return"\u{1f4d1}"
|
|
4551
4532
|
case"T":return"\u{1f504}"}}(e.status)
|
|
4552
|
-
c+=`- ${t} ${e.path}`,e.renamedFrom&&(c+=` (renamed from ${e.renamedFrom})`),c+="\n"})),r>0&&(c+=`\n... and ${r} more file${1===r?"":"s"}\n`,c+="\n\u{1f4a1} Use fileFilter to narrow results or use detailed mode to see all files.\n"),c+="\n"}return c}({requestInfo:y,branchInfo:{branchName:"requests/"+c,baseCommit:"",headCommit:"",exists:!1,isCompleted:"completed"===y.status},summary:o.summary,files:o.files,commits:[]},0,
|
|
4533
|
+
c+=`- ${t} ${e.path}`,e.renamedFrom&&(c+=` (renamed from ${e.renamedFrom})`),c+="\n"})),r>0&&(c+=`\n... and ${r} more file${1===r?"":"s"}\n`,c+="\n\u{1f4a1} Use fileFilter to narrow results or use detailed mode to see all files.\n"),c+="\n"}return c}({requestInfo:y,branchInfo:{branchName:"requests/"+c,baseCommit:"",headCommit:"",exists:!1,isCompleted:"completed"===y.status},summary:o.summary,files:o.files,commits:[]},0,p)
|
|
4553
4534
|
return u({success:!0,filesChanged:o.summary.filesChanged}),{content:[{type:"text",text:s}]}}}catch(e){return d.error("Error in request file history tool",{error:e instanceof Error?e.stack:e+""}),u({success:!1,error:e instanceof Error?e.name:"unknown"}),{content:[{type:"text",text:"Error: "+(0,i.getErrorMessage)(e)}],isError:!0}}}
|
|
4554
4535
|
const o=t(9860),s=t(2960),i=t(8824)},8349(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDebugGitLog=async function(e,t){try{if(!t.git)return{content:[{type:"text",text:"No git repository available"}]}
|
|
4555
4536
|
const e=await t.git.log(),r="req000010",n=e.all.filter((e=>e.message.includes(r))),o=e.all.filter((e=>e.message.toLowerCase().includes("merge"))),s=e.all.slice(0,10)
|
|
@@ -4567,28 +4548,28 @@ o+=`**${t}** \u2014 ${e.filename}\n`,o+=` Updated: ${r}\n`,n&&(o+=` ${n}\n`),o
|
|
|
4567
4548
|
const r=t(8824)},8411(e,exports,t){function r(e){if(!a.default.existsSync(e))return null
|
|
4568
4549
|
try{const t=a.default.readFileSync(e,"utf8").trim()
|
|
4569
4550
|
try{const e=JSON.parse(t)
|
|
4570
|
-
return
|
|
4571
|
-
if(isNaN(e))return
|
|
4551
|
+
return f.debug("Read JSON lock data",e),e}catch{const e=parseInt(t,10)
|
|
4552
|
+
if(isNaN(e))return f.warn("Invalid lock file content",{content:t}),null
|
|
4572
4553
|
const r={mode:"single-agent",created:(new Date).toISOString(),hostname:"unknown",pid:e}
|
|
4573
|
-
return
|
|
4554
|
+
return f.debug("Read legacy PID lock data",r),r}}catch(e){return f.error("Error reading lock file",{error:(0,h.getErrorMessage)(e)}),null}}function n(e){try{return process.kill(e,0),!0}catch{return!1}}function o(e,t,n,o,i){try{const c={mode:i?"multi-agent":"single-agent",created:o,hostname:l.default.hostname(),...i?{}:{pid:n}}
|
|
4574
4555
|
if(a.default.writeFileSync(e,JSON.stringify(c,null,2)),i){const r={count:1,processes:[{pid:n,started:o}]}
|
|
4575
4556
|
a.default.writeFileSync(t,JSON.stringify(r,null,2)),s(e,t,n)}else!function(e,t){["SIGINT","SIGTERM","exit"].forEach((n=>{process.on(n,(()=>{try{if(a.default.existsSync(e)){const o=r(e)
|
|
4576
|
-
o&&o.pid===t&&(a.default.unlinkSync(e),
|
|
4577
|
-
return
|
|
4578
|
-
s.processes=s.processes.filter((e=>e.pid!==r)),s.count=s.processes.length,s.count>0?(a.default.writeFileSync(t,JSON.stringify(s,null,2)),
|
|
4557
|
+
o&&o.pid===t&&(a.default.unlinkSync(e),f.debug("Removed single-agent lock file",{signal:n,pid:t}))}}catch(e){f.error("Error removing single-agent lock file",{error:e instanceof Error?e.message:e+"",signal:n})}"exit"!==n&&process.exit(0)}))}))}(e,n)
|
|
4558
|
+
return f.info("Created new lock",{mode:c.mode,pid:n}),!0}catch(e){return f.error("Error creating new lock",{error:(0,h.getErrorMessage)(e)}),!1}}function s(e,t,r){["SIGINT","SIGTERM","exit"].forEach((n=>{process.on(n,(()=>{try{if(a.default.existsSync(t)){const o=a.default.readFileSync(t,"utf8"),s=JSON.parse(o)
|
|
4559
|
+
s.processes=s.processes.filter((e=>e.pid!==r)),s.count=s.processes.length,s.count>0?(a.default.writeFileSync(t,JSON.stringify(s,null,2)),f.debug("Removed process from multi-agent references",{signal:n,pid:r,remaining:s.count})):(a.default.unlinkSync(t),a.default.existsSync(e)&&a.default.unlinkSync(e),f.debug("Removed multi-agent lock files (last process)",{signal:n,pid:r}))}}catch(e){f.error("Error removing multi-agent lock files",{error:e instanceof Error?e.message:e+"",signal:n})}"exit"!==n&&process.exit(0)}))}))}var i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
4579
4560
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.acquireProcessLock=function(e,t=!1){const i=c.default.join(e,d.ALCHEMY_DIR_NAME)
|
|
4580
|
-
let u,
|
|
4581
|
-
try{a.default.existsSync(i)||(a.default.mkdirSync(i,{recursive:!0}),
|
|
4561
|
+
let u,p
|
|
4562
|
+
try{a.default.existsSync(i)||(a.default.mkdirSync(i,{recursive:!0}),f.debug(`Created ${d.ALCHEMY_DIR_NAME} directory for lock file`,{alchemyLabDir:i})),u=c.default.join(i,".mcp-server.lock"),p=c.default.join(i,".mcp-agents.refs"),f.debug(`Using ${d.ALCHEMY_DIR_NAME} directory for lock files`,{lockFilePath:u,refsFilePath:p})}catch(t){f.error(`Failed to create ${d.ALCHEMY_DIR_NAME} directory`,{alchemyLabDir:i,error:t instanceof Error?t.message:t+""}),u=c.default.join(e,".mcp-server.lock"),p=c.default.join(e,".mcp-agents.refs"),f.warn("Falling back to base directory for lock files",{lockFilePath:u,refsFilePath:p})}const m=process.pid,y=(new Date).toISOString()
|
|
4582
4563
|
try{const e=r(u)
|
|
4583
|
-
if(
|
|
4564
|
+
if(f.info("Lock acquisition attempt",{pid:m,multiAgentMode:t,lockFilePath:u,lockExists:!!e,lockData:e?{mode:e.mode,pid:e.pid,hostname:e.hostname,created:e.created}:null}),!e)return f.info("No existing lock - creating new lock",{pid:m,mode:t?"multi-agent":"single-agent"}),o(u,p,m,y,t)
|
|
4584
4565
|
{const r=Date.now()-new Date(e.created).getTime(),i=r>g,c=l.default.hostname(),d=e.hostname!==c&&"unknown"!==e.hostname
|
|
4585
|
-
if(i)return
|
|
4586
|
-
if(d)return
|
|
4587
|
-
if("single-agent"===e.mode)return e.pid===m?(
|
|
4566
|
+
if(i)return f.warn("\u26a0\ufe0f Clearing stale lock (older than 24 hours)",{lockAge:Math.round(r/1e3/60/60)+" hours",lockCreated:e.created,lockHostname:e.hostname}),o(u,p,m,y,t)
|
|
4567
|
+
if(d)return f.warn("\u26a0\ufe0f Clearing lock from different machine",{lockHostname:e.hostname,currentHostname:c}),o(u,p,m,y,t)
|
|
4568
|
+
if("single-agent"===e.mode)return e.pid===m?(f.debug("Same process already has lock",{pid:m}),!0):n(e.pid)?(f.warn("Cannot acquire lock - single-agent mode active",{existingPid:e.pid,currentPid:m,requestedMode:t?"multi-agent":"single-agent"}),!1):(f.info("Taking over lock from dead single-agent process",{deadPid:e.pid,currentPid:m,newMode:t?"multi-agent":"single-agent"}),o(u,p,m,y,t))
|
|
4588
4569
|
if("multi-agent"===e.mode)return t?function(e,t,r){try{let o={count:0,processes:[]}
|
|
4589
4570
|
if(a.default.existsSync(e)){const t=a.default.readFileSync(e,"utf8")
|
|
4590
|
-
o=JSON.parse(t),o.processes=o.processes.filter((e=>n(e.pid))),o.count=o.processes.length}return o.processes.push({pid:t,started:r}),o.count=o.processes.length,a.default.writeFileSync(e,JSON.stringify(o,null,2)),s(e.replace(".mcp-agents.refs",".mcp-server.lock"),e,t),
|
|
4591
|
-
const a=i(t(9896)),c=i(t(6928)),l=i(t(857)),d=t(4139),u=t(3444),h=t(8824),g=864e5,
|
|
4571
|
+
o=JSON.parse(t),o.processes=o.processes.filter((e=>n(e.pid))),o.count=o.processes.length}return o.processes.push({pid:t,started:r}),o.count=o.processes.length,a.default.writeFileSync(e,JSON.stringify(o,null,2)),s(e.replace(".mcp-agents.refs",".mcp-server.lock"),e,t),f.info("Joined multi-agent lock",{pid:t,totalAgents:o.count}),!0}catch(e){return f.error("Error joining multi-agent lock",{error:(0,h.getErrorMessage)(e)}),!1}}(p,m,y):(f.warn("Cannot acquire lock - multi-agent mode active",{currentPid:m,requestedMode:"single-agent"}),!1)}return!1}catch(e){return f.error("Error acquiring lock",{error:(0,h.getErrorMessage)(e),pid:m}),!1}}
|
|
4572
|
+
const a=i(t(9896)),c=i(t(6928)),l=i(t(857)),d=t(4139),u=t(3444),h=t(8824),g=864e5,f=(0,u.createLogger)({serviceName:"process-lock",level:u.LogLevel.DEBUG,logToFile:!1})},8451(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.formatFileSize=function(e){return 1024>e?e+" bytes":1048576>e?(e/1024).toFixed(2)+" KB":1073741824>e?(e/1048576).toFixed(2)+" MB":(e/1073741824).toFixed(2)+" GB"},exports.truncate=function(e,t){return e.length>t?e.substring(0,t-3)+"...":e},exports.escapeRegExp=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")},exports.countOccurrences=function(e,t){if(0===t.length)return 0
|
|
4592
4573
|
let r=0,n=0
|
|
4593
4574
|
for(;n=e.indexOf(t,n),-1!==n;)r++,n+=t.length
|
|
4594
4575
|
return r},exports.handleFileOperationError=function(e,t,n,o,s,i){n.error(`${i.toolName} operation failed in phase: ${t}`,{args:s,phase:t,error:e instanceof Error?e.stack:e+""})
|
|
@@ -4629,27 +4610,27 @@ const o=new Set(["py","python","yaml","yml","pug","jade","haml","slim","sass","s
|
|
|
4629
4610
|
if(!t)throw Error(`Tool "${e}" does not have a defined RecordType mapping. This is a type safety violation. Please add this tool to the TOOL_NAME_TO_RECORD_TYPE_MAP in failure-record-utils.ts.`)
|
|
4630
4611
|
return t}function n(e){return!!e&&/^tas\d{6}$/.test(e)}function o(e){return!!e&&(/^req\d{6}$/.test(e)||/^req_[\w-]+$/.test(e))}function s(e){return!!e&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.toolNameToRecordType=r,exports.isValidTaskId=n,exports.isValidRequestId=o,exports.isValidProjectId=s,exports.createFailureToolRecord=async function(e,t,a,c,l,d,u){if(!c)return void l.warn("ToolRecordClient is not available, skipping failure record creation for "+e)
|
|
4631
4612
|
if(!s(u.projectId)){const t=Error(`Invalid projectId format: ${u.projectId}. Cannot create failure record without valid projectId.`)
|
|
4632
|
-
throw l.error("Cannot create failure record due to invalid projectId",{toolName:e,projectId:u.projectId,error:t.message}),t}const h=Date.now(),g=e.replace(/-/g,"_"),
|
|
4613
|
+
throw l.error("Cannot create failure record due to invalid projectId",{toolName:e,projectId:u.projectId,error:t.message}),t}const h=Date.now(),g=e.replace(/-/g,"_"),f=(0,i.getErrorMessage)(t),p=t instanceof Error?t.stack:void 0
|
|
4633
4614
|
try{const t=r(e),s={}
|
|
4634
4615
|
let i,m
|
|
4635
4616
|
u.taskId&&(n(u.taskId)?i=u.taskId:(s.taskId=u.taskId,l.warn(`Invalid taskId format: ${u.taskId}, not associating failure record with this ID`,{toolName:e,invalidTaskId:u.taskId}))),u.requestId&&(o(u.requestId)?m=u.requestId:(s.requestId=u.requestId,l.warn(`Invalid requestId format: ${u.requestId}, not associating failure record with this ID`,{toolName:e,invalidRequestId:u.requestId})))
|
|
4636
|
-
let y=u.note||`Failed to execute ${e}: ${
|
|
4617
|
+
let y=u.note||`Failed to execute ${e}: ${f.substring(0,100)}${f.length>100?"...":""}`
|
|
4637
4618
|
Object.keys(s).length>0&&(y+=` (Warning: Invalid IDs provided: ${Object.entries(s).map((([e,t])=>`${e}: ${t}`)).join(", ")})`)
|
|
4638
|
-
const w={projectId:u.projectId,type:t,note:y,metadata:{status:"failed",error:
|
|
4639
|
-
i&&(w.taskId=i),m&&(w.requestId=m),l.info("Creating failure tool record for "+e,{toolName:e,recordType:w.type,...i&&{taskId:i},...m&&{requestId:m},projectId:u.projectId,invalidIds:Object.keys(s).length>0?s:void 0,error:
|
|
4619
|
+
const w={projectId:u.projectId,type:t,note:y,metadata:{status:"failed",error:f,errorStack:p,originalToolName:e,timestamp:(new Date).toISOString(),invalidIds:Object.keys(s).length>0?s:void 0,...a}}
|
|
4620
|
+
i&&(w.taskId=i),m&&(w.requestId=m),l.info("Creating failure tool record for "+e,{toolName:e,recordType:w.type,...i&&{taskId:i},...m&&{requestId:m},projectId:u.projectId,invalidIds:Object.keys(s).length>0?s:void 0,error:f})
|
|
4640
4621
|
const k=await c.createToolRecord(w)
|
|
4641
|
-
d.recordValue(g+"_failure_record_creation_time",Date.now()-h),d.incrementCounter(g+"_failure_record_creation_success",1),l.info("Successfully created failure tool record for "+e,{toolName:e,recordType:w.type,...i&&{taskId:i},...m&&{requestId:m},projectId:u.projectId,toolRecordId:k.id})}catch(t){throw d.recordValue(g+"_failure_record_creation_time",Date.now()-h),d.incrementCounter(g+"_failure_record_creation_failure",1),l.error("Failed to create failure tool record for "+e,{error:t instanceof Error?t.stack:t+"",toolName:e,...u.taskId&&{originalTaskId:u.taskId},...u.requestId&&{originalRequestId:u.requestId},projectId:u.projectId,originalError:
|
|
4622
|
+
d.recordValue(g+"_failure_record_creation_time",Date.now()-h),d.incrementCounter(g+"_failure_record_creation_success",1),l.info("Successfully created failure tool record for "+e,{toolName:e,recordType:w.type,...i&&{taskId:i},...m&&{requestId:m},projectId:u.projectId,toolRecordId:k.id})}catch(t){throw d.recordValue(g+"_failure_record_creation_time",Date.now()-h),d.incrementCounter(g+"_failure_record_creation_failure",1),l.error("Failed to create failure tool record for "+e,{error:t instanceof Error?t.stack:t+"",toolName:e,...u.taskId&&{originalTaskId:u.taskId},...u.requestId&&{originalRequestId:u.requestId},projectId:u.projectId,originalError:f}),t}}
|
|
4642
4623
|
const i=t(8824),a={write_file:"write-file","delete-file":"delete-file",delete_files:"delete-files",move_files:"move-files","replace-string":"replace-string",replace_strings:"replace-strings",insert_lines:"insert-lines",replace_lines:"replace-lines","file-recover":"file-recover",complete_task:"complete-task","update-task-status":"update-task-status","create-task":"create-task",create_request:"create-request",complete_request:"complete-request",read_files:"discovery","list-directory":"discovery",search:"discovery",file_history:"discovery",request_file_history:"discovery",get_request_information:"discovery",get_task_information:"discovery",list_requests:"discovery",list_tasks:"discovery",create_directory:"write",authenticate:"discovery","find-previous-commit":"discovery"}},8625(e,exports,t){function r(e,t,r){const n=exports.ERROR_TYPE_PROPERTIES[e]||exports.ERROR_TYPE_PROPERTIES[i.INTERNAL_ERROR]
|
|
4643
4624
|
return{success:!1,error:{code:e,message:t||n.defaultMessage,details:r,retryable:n.retryable,statusCode:n.statusCode}}}function n(e){return"object"==typeof e&&null!==e&&"code"in e&&"statusCode"in e&&"details"in e&&"retryable"in e&&"string"==typeof e.code&&"number"==typeof e.statusCode}function o(e){if(n(e)){const t=r(e.code,e.message,e.details)
|
|
4644
4625
|
return{statusCode:e.statusCode,body:t}}if(e instanceof Error&&"ConnectionError"===e.name){const t=e
|
|
4645
4626
|
return{statusCode:503,body:r("CONNECTION_ERROR",t.message||"Connection to remote server failed",{operation:t.operation||"unknown",lastConnectionAttempt:t.lastConnectionAttempt||null,suggestions:["Check your network connection","Verify that the remote server is running","Try again in a few moments"],isConnectionIssue:!0})}}const t=e instanceof Error?e:Error(e+""),o=r(i.INTERNAL_ERROR,t.message||"An unexpected error occurred")
|
|
4646
|
-
return{statusCode:o.error.statusCode,body:o}}function s(e){return!n(e)||e.isRetryable()}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=void 0,exports.createErrorResponse=r,exports.createAppError=function(e,t="INTERNAL_ERROR",r=500,n){return new a(e,t,r,n)},exports.createNotFoundError=function(e="Resource not found",t){return new c(e,t)},exports.createValidationError=function(e="Invalid input",t){return new l(e,t)},exports.createAuthenticationError=function(e="Authentication required",t){return new d(e,t)},exports.createAuthorizationError=function(e="Not authorized",t){return new u(e,t)},exports.createDatabaseError=function(e="Database error",t){return new h(e,t)},exports.createServiceError=function(e="Service unavailable",t){return new g(e,t)},exports.createFileOperationError=function(e="File operation error",t){return new
|
|
4627
|
+
return{statusCode:o.error.statusCode,body:o}}function s(e){return!n(e)||e.isRetryable()}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=void 0,exports.createErrorResponse=r,exports.createAppError=function(e,t="INTERNAL_ERROR",r=500,n){return new a(e,t,r,n)},exports.createNotFoundError=function(e="Resource not found",t){return new c(e,t)},exports.createValidationError=function(e="Invalid input",t){return new l(e,t)},exports.createAuthenticationError=function(e="Authentication required",t){return new d(e,t)},exports.createAuthorizationError=function(e="Not authorized",t){return new u(e,t)},exports.createDatabaseError=function(e="Database error",t){return new h(e,t)},exports.createServiceError=function(e="Service unavailable",t){return new g(e,t)},exports.createFileOperationError=function(e="File operation error",t){return new f(e,t)},exports.createMcpProtocolError=function(e="MCP protocol error",t){return new p(e,t)},exports.isAppError=n,exports.errorToResponse=o,exports.isRetryableError=s
|
|
4647
4628
|
const i=t(7388)
|
|
4648
4629
|
exports.ERROR_TYPE_PROPERTIES={[i.TASK_NOT_FOUND]:{statusCode:404,retryable:!1,defaultMessage:"Task ID does not exist"},[i.TASK_ID_INVALID_FORMAT]:{statusCode:400,retryable:!1,defaultMessage:"Task ID format is invalid"},[i.TASK_VALIDATION_FAILED]:{statusCode:400,retryable:!1,defaultMessage:"Task validation failed"},[i.NETWORK_ERROR]:{statusCode:503,retryable:!0,defaultMessage:"Network error occurred"},[i.SERVER_ERROR]:{statusCode:500,retryable:!0,defaultMessage:"Server error occurred"},[i.CONNECTION_TIMEOUT]:{statusCode:504,retryable:!0,defaultMessage:"Connection timed out"},[i.SERVICE_UNAVAILABLE]:{statusCode:503,retryable:!0,defaultMessage:"Service is currently unavailable"},[i.CONNECTION_ERROR]:{statusCode:503,retryable:!0,defaultMessage:"Connection to remote server failed"},[i.REQUEST_NOT_FOUND]:{statusCode:404,retryable:!1,defaultMessage:"Request ID does not exist"},[i.REQUEST_ID_INVALID_FORMAT]:{statusCode:400,retryable:!1,defaultMessage:"Request ID format is invalid"},[i.REQUEST_VALIDATION_FAILED]:{statusCode:400,retryable:!1,defaultMessage:"Request validation failed"},[i.VALIDATION_ERROR]:{statusCode:400,retryable:!1,defaultMessage:"Validation error"},[i.UNAUTHORIZED]:{statusCode:401,retryable:!1,defaultMessage:"Authentication required"},[i.FORBIDDEN]:{statusCode:403,retryable:!1,defaultMessage:"Access forbidden"},[i.NOT_FOUND]:{statusCode:404,retryable:!1,defaultMessage:"Resource not found"},[i.INTERNAL_ERROR]:{statusCode:500,retryable:!0,defaultMessage:"Internal server error"},[i.BAD_REQUEST]:{statusCode:400,retryable:!1,defaultMessage:"Bad request"},[i.MCP_PROTOCOL_ERROR]:{statusCode:500,retryable:!0,defaultMessage:"MCP protocol error"}},exports.ErrorUtils={isAppError:n,errorToResponse:o,isRetryableError:s,createErrorResponse:r}
|
|
4649
4630
|
class a extends Error{constructor(e,t="INTERNAL_ERROR",r=500,n){super(e),this.name=this.constructor.name,this.code=t,this.statusCode=r,this.details=n||{},n&&"code"in n&&"string"==typeof n.code&&(this.code=n.code)
|
|
4650
4631
|
const o=exports.ERROR_TYPE_PROPERTIES[this.code]
|
|
4651
4632
|
this.retryable=o?o.retryable:!n||!("retryable"in n)||!!n.retryable,Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,details:this.details,retryable:this.retryable,stack:this.stack}}get metadata(){return this.details}isRetryable(){return this.retryable}}class c extends a{constructor(e="Resource not found",t){super(e,i.NOT_FOUND,404,t),this.resourceType="unknown",t&&("taskId"in t?(this.code=i.TASK_NOT_FOUND,this.resourceType="task"):"requestId"in t&&(this.code=i.REQUEST_NOT_FOUND,this.resourceType="request"))}}class l extends a{constructor(e="Invalid input",t){super(e,i.VALIDATION_ERROR,400,t)}}class d extends a{constructor(e="Authentication required",t){super(e,i.UNAUTHORIZED,401,t)}}class u extends a{constructor(e="Not authorized",t){super(e,i.FORBIDDEN,403,t)}}class h extends a{constructor(e="Database error",t){super(e,"DATABASE_ERROR",500,t)}}class g extends a{constructor(e="Service unavailable",t){if(super(e,i.SERVICE_UNAVAILABLE,503,t),t&&"structuredError"in t){const e=t.structuredError
|
|
4652
|
-
e&&e.error&&"retryable"in e.error&&(this.details.retryable=!!e.error.retryable)}}}class
|
|
4633
|
+
e&&e.error&&"retryable"in e.error&&(this.details.retryable=!!e.error.retryable)}}}class f extends a{constructor(e="File operation error",t){super(e,"FILE_OPERATION_ERROR",500,t)}}class p extends a{constructor(e="MCP protocol error",t){super(e,i.MCP_PROTOCOL_ERROR,500,t)}}exports.AppError=a,exports.NotFoundError=c,exports.ValidationError=l,exports.AuthenticationError=d,exports.AuthorizationError=u,exports.DatabaseError=h,exports.ServiceError=g,exports.FileOperationError=f,exports.McpProtocolError=p,exports.UnauthorizedError=d},8712(e,exports){function t(e,t){return!(!e||!e.trim())&&RegExp(`^\\s*\\${t}{7}(?:\\s|$)`).test(e)}function r(e,r,n){if(!e||!e.trim())return{cleanContent:"",filesParsed:[],hasConflictMarkers:!1}
|
|
4653
4634
|
const o=e.split("\n"),s=[],i=new Set
|
|
4654
4635
|
let a=!1,c=""
|
|
4655
4636
|
for(let e=0;e<o.length;e++){const l=o[e]
|
|
@@ -4710,7 +4691,7 @@ try{const r=await o.log({from:t,to:t,file:s,maxCount:1})
|
|
|
4710
4691
|
if(!r.all||0===r.all.length)return{content:[{type:"text",text:`No commit found with hash ${t} for file ${e}`}]}
|
|
4711
4692
|
const n=r.all[0],i=await o.diff([t+"^",t,"--",s])
|
|
4712
4693
|
let a="# File History - Commit Diff\n\n"
|
|
4713
|
-
return a+=`**File:** ${e}\n`,a+=`**Commit:** ${t.substring(0,8)}\n`,a+=`**Author:** ${n.author_name}\n`,a+=`**Date:** ${n.date}\n`,a+=`**Message:** ${n.message}\n\n`,i&&i.trim()?a+=`## Full Diff\n\n\`\`\`diff\n${i}\n\`\`\`\n`:a+="*No diff available for this commit*\n",{content:[{type:"text",text:a}]}}catch(r){return n.error("Failed to get commit diff",{error:r,commit:t,filePath:e}),{content:[{type:"text",text:`\u274c Failed to get diff for commit ${t}: ${(0,
|
|
4694
|
+
return a+=`**File:** ${e}\n`,a+=`**Commit:** ${t.substring(0,8)}\n`,a+=`**Author:** ${n.author_name}\n`,a+=`**Date:** ${n.date}\n`,a+=`**Message:** ${n.message}\n\n`,i&&i.trim()?a+=`## Full Diff\n\n\`\`\`diff\n${i}\n\`\`\`\n`:a+="*No diff available for this commit*\n",{content:[{type:"text",text:a}]}}catch(r){return n.error("Failed to get commit diff",{error:r,commit:t,filePath:e}),{content:[{type:"text",text:`\u274c Failed to get diff for commit ${t}: ${(0,f.getErrorMessage)(r)}`}],isError:!0}}}(a,I,t,i)):(i.info("Getting file history with branch support",{filePath:a,limit:y,showDiff:w,showTraceability:k,branch:b}),await async function(e,t,n,o,s,i,a,c,d,u,f){try{const{normalizedPath:m,fullPath:y}=p.validateAndNormalizePath(e,a)
|
|
4714
4695
|
try{await l.access(y)}catch(e){throw Error("File not found: "+m)}const w=a.git
|
|
4715
4696
|
if(!w)throw Error("Git is not available in this context")
|
|
4716
4697
|
let k={branch:null,requestId:null,isMain:!0}
|
|
@@ -4720,8 +4701,8 @@ else{if(k.isMain&&!o)return d.info("Showing request-level timeline on main branc
|
|
|
4720
4701
|
if(k.requestId)return d.info("Showing operation-level detail on request branch",{requestId:k.requestId}),{content:[{type:"text",text:await(0,g.getOperationDetailForFile)(m,k.requestId,c,d,u)}]}
|
|
4721
4702
|
{const e=await async function(e,t,n,o,s,i,a,c,l,d){const u=[],h=[]
|
|
4722
4703
|
if(!i.isMain&&i.branch){const g=await r(e,t,n,o,s,i.branch,a,c,l,d)
|
|
4723
|
-
u.push(...g),g.length>0&&h.push(i.branch+" (current)")}const g=await r(e,t,n,o,s,"main",a,c,l,d),
|
|
4724
|
-
return u.push(...
|
|
4704
|
+
u.push(...g),g.length>0&&h.push(i.branch+" (current)")}const g=await r(e,t,n,o,s,"main",a,c,l,d),f=new Set(u.map((e=>e.hash))),p=g.filter((e=>!f.has(e.hash)))
|
|
4705
|
+
return u.push(...p),g.length>0&&h.push("main"),u.sort(((e,t)=>new Date(t.date).getTime()-new Date(e.date).getTime())),{versions:u.slice(0,n),sources:h}}(w,m,t,n,o,k,i,c,d,u)
|
|
4725
4706
|
b=e.versions,I=`## File History: ${m} (Combined View)\n\n`,I+=`**Current Context:** ${k.isMain?"main":`${k.branch} (${k.requestId})`}\n`,I+=`**History Sources:** ${e.sources.join(", ")}\n\n`}}if(0===b.length)return I+="\u274c **No history found**\n\nThis file has no git history. It may be:\n- A new file that hasn't been committed\n- Located outside the git repository\n- The path may be incorrect\n- No history exists in the specified branch context",{content:[{type:"text",text:I}]}
|
|
4726
4707
|
const v=b.length,C=Math.min(b.length,t)
|
|
4727
4708
|
v>t?I+=`\u{1f4ca} **Summary:** ${v} versions found, showing ${C} most recent\n\n`:v>0&&(I+=`\u{1f4ca} **Summary:** ${v} version${v>1?"s":""} found\n\n`),I+=`**Total Versions:** ${b.length}\n`,I+="**Current File Size:** "
|
|
@@ -4730,9 +4711,9 @@ for(let e=0;e<b.length;e++){const t=b[e]
|
|
|
4730
4711
|
if(I+=`### Version ${e+1} (${t.hash.substring(0,8)})\n`,t.branch&&(I+=`- **Branch:** ${t.branch}\n`),I+=`- **Author:** ${t.author}\n`,I+=`- **Date:** ${t.date}\n`,I+=`- **Message:** ${t.message}\n`,o&&t.traceability&&(I+=`\n${(0,h.formatTraceabilityInfo)(t.traceability)}\n`),n&&t.diff){const e=t.diff.split("\n")
|
|
4731
4712
|
let r=0,n=0
|
|
4732
4713
|
for(const t of e)t.startsWith("+")&&!t.startsWith("+++")&&r++,t.startsWith("-")&&!t.startsWith("---")&&n++
|
|
4733
|
-
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()-
|
|
4734
|
-
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,
|
|
4735
|
-
const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),
|
|
4714
|
+
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()-f}),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
|
|
4715
|
+
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,f.getErrorMessage)(e)}],isError:!0}}}
|
|
4716
|
+
const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),f=t(8824),p=a(t(5967)),m=a(t(7478)),{getCurrentBranch:y}=m},8850(e,exports,t){Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4736
4717
|
const r=t(6183),n=t(6891)
|
|
4737
4718
|
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){function r(e){try{n.debug("Running cleanup before exit"),e(),n.debug("Cleanup completed")}catch(e){n.error("Error during cleanup",{error:e})}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.setupParentProcessDetection=function(e){n.debug("Setting up parent process detection")
|
|
4738
4719
|
const t=process.ppid,o=setInterval((()=>{try{process.kill(t,0)}catch(t){n.info("Parent process exited (detected via PPID check), shutting down"),clearInterval(o),r(e),process.exit(0)}}),5e3)
|
|
@@ -4884,37 +4865,37 @@ if(!a)throw new c.ValidationError("Could not discover current session ID. Make s
|
|
|
4884
4865
|
return(0,h.logSessionIdentity)(""+r,"per-call-discovery",{sessionId:a}),a}function s(e){const t=[],r=e.content||{}
|
|
4885
4866
|
if(t.push("**Message Code:** "+e.messageCode),t.push(`**Type:** question (${r.questionType})`),t.push("**Status:** "+e.status),t.push("**Priority:** "+e.priority),t.push("**From:** "+e.fromSessionId),t.push(e.toSessionId?"**To:** "+e.toSessionId:"**To:** (broadcast)"),t.push("**Created:** "+e.createdAt),t.push("**Expires:** "+e.expiresAt),t.push(""),t.push("**Question:** "+r.question),r.context&&t.push("**Context:** "+r.context),"alternatives"===r.questionType&&r.options){t.push(""),t.push("**Options:**")
|
|
4886
4867
|
for(const e of r.options)t.push(` - [${e.id}] ${e.label}${e.description?" - "+e.description:""}`)}return"responded"===e.status&&e.response&&(t.push(""),t.push("---"),t.push("**Answered by:** "+e.respondedBySessionId),t.push("**Answered at:** "+e.respondedAt),e.response.text&&t.push("**Answer:** "+e.response.text),e.response.selectedOptions&&t.push("**Selected:** "+e.response.selectedOptions.join(", ")),e.response.notes&&t.push("**Notes:** "+e.response.notes)),t.join("\n")}function i(e){const t=[],r=e.content||{}
|
|
4887
|
-
return t.push("**Status:** "+(r.reportStatus||"unknown")),t.push("**Summary:** "+(r.summary||"")),r.details&&(t.push(""),t.push("**Details:**"),t.push(r.details)),t.join("\n")}function a(e){return"question"===e.messageType?s(e):i(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSessionMessageOperations=async function(e,t,p,
|
|
4868
|
+
return t.push("**Status:** "+(r.reportStatus||"unknown")),t.push("**Summary:** "+(r.summary||"")),r.details&&(t.push(""),t.push("**Details:**"),t.push(r.details)),t.join("\n")}function a(e){return"question"===e.messageType?s(e):i(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSessionMessageOperations=async function(e,t,f,p,m){const y=f.child({component:"session_message_operations"})
|
|
4888
4869
|
if(!m)throw new c.ValidationError("API client not available")
|
|
4889
4870
|
const{operation:w}=e
|
|
4890
|
-
y.info("Session message operation",{operation:w}),
|
|
4871
|
+
y.info("Session message operation",{operation:w}),p.incrementCounter("session_message_operations",1,{operation:w})
|
|
4891
4872
|
try{switch(w){case"send":if(!e.type)throw new c.ValidationError('send operation requires type ("question" or "report")')
|
|
4892
4873
|
return await async function(e,t,a,l){const{type:d}=e
|
|
4893
4874
|
if(!d)throw new c.ValidationError('send operation requires type ("question" or "report")')
|
|
4894
4875
|
const u=l.getSessionMessageClient()
|
|
4895
4876
|
if(!u)throw new c.ValidationError("Session message client not available")
|
|
4896
|
-
if("question"===d)return await async function(e,t,i,a,l){const{toSessionId:d,questionType:u,questionContent:h,priority:g,expiresInHours:
|
|
4877
|
+
if("question"===d)return await async function(e,t,i,a,l){const{toSessionId:d,questionType:u,questionContent:h,priority:g,expiresInHours:f}=e
|
|
4897
4878
|
if(!u||!h?.question)throw new c.ValidationError("Question requires questionType and questionContent.question")
|
|
4898
|
-
const
|
|
4879
|
+
const p=await o(t,i,"session_message_operations",{operation:"send",send:{type:"question",questionType:u,questionContent:h}}),m=await async function(e,t,r,o){if("parent"===e){const e=await n(t,r,o)
|
|
4899
4880
|
if(!e)throw new c.ValidationError("Could not find parent session. Make sure this session was spawned as a subagent.")
|
|
4900
|
-
return o.info('Resolved toSessionId "parent" to actual ID',{parentId:e}),e}return e}(d,
|
|
4881
|
+
return o.info('Resolved toSessionId "parent" to actual ID',{parentId:e}),e}return e}(d,p,a,i)
|
|
4901
4882
|
if(!("alternatives"!==u||h.options&&Array.isArray(h.options)))throw new c.ValidationError("Alternatives questions require options array")
|
|
4902
|
-
i.info("Creating question",{fromSessionId:
|
|
4903
|
-
const y=await l.createQuestion({fromSessionId:
|
|
4883
|
+
i.info("Creating question",{fromSessionId:p,toSessionId:m,questionType:u})
|
|
4884
|
+
const y=await l.createQuestion({fromSessionId:p,toSessionId:m,questionType:u,question:h.question,options:h.options,context:h.context,allowMultiple:h.allowMultiple,priority:g,expiresInHours:f})
|
|
4904
4885
|
let w=""
|
|
4905
4886
|
return m&&(w=await r(m,function(e){const t=e.content||{},r=["\u{1f4e8} **You have a new question!**","","**Question Code:** "+e.messageCode,"**From:** "+e.fromSessionId,"**Priority:** "+e.priority,"","**Question:** "+t.question]
|
|
4906
4887
|
if(t.context&&r.push("**Context:** "+t.context),"alternatives"===t.questionType&&t.options){r.push(""),r.push("**Options:**")
|
|
4907
4888
|
for(const e of t.options)r.push(` - [${e.id}] ${e.label}${e.description?" - "+e.description:""}`)}return r.push(""),r.push(`Use \`session_message_operations\` with \`reply\` operation and message code \`${e.messageCode}\` to respond.`),r.join("\n")}(y),t,i)?"\n\n\u{1f4ec} The target session has been notified.":"\n\n\u26a0\ufe0f Could not notify the target session (may be offline)."),{content:[{type:"text",text:`\u2705 Question created!${w}\n\n**Message Code: ${y.messageCode}**\n\nUse this code to check for answers or share with other sessions.\n\n${s(y)}`}]}}(e,t,a,l,u)
|
|
4908
|
-
if("report"===d)return await async function(e,t,s,a,l){const{status:d,summary:u,details:h,finish:
|
|
4889
|
+
if("report"===d)return await async function(e,t,s,a,l){const{status:d,summary:u,details:h,finish:f}=e
|
|
4909
4890
|
if(!d||!u)throw new c.ValidationError("Report requires status and summary")
|
|
4910
|
-
const
|
|
4911
|
-
const t=await n(
|
|
4891
|
+
const p=await o(t,s,"session_message_operations",{operation:"send",send:{type:"report",status:d,summary:u}}),m=await(async()=>{if(e.toSessionId&&"parent"!==e.toSessionId)return s.info("Using explicit toSessionId for report",{parentSessionId:e.toSessionId}),e.toSessionId
|
|
4892
|
+
const t=await n(p,a,s)
|
|
4912
4893
|
if(!t)throw new c.ValidationError("Could not find parent session. This tool should only be used by subagent sessions.")
|
|
4913
4894
|
return s.info("Auto-resolved parent session",{parentSessionId:t}),t})()
|
|
4914
|
-
s.info("Submitting report",{sessionId:
|
|
4915
|
-
const y=await l.createReport({fromSessionId:
|
|
4895
|
+
s.info("Submitting report",{sessionId:p,parentSessionId:m,status:d})
|
|
4896
|
+
const y=await l.createReport({fromSessionId:p,toSessionId:m,status:d,summary:u,details:h})
|
|
4916
4897
|
let w="agent"
|
|
4917
|
-
try{const e=await fetch(`http://localhost:${g}/api/sessions/${encodeURIComponent(
|
|
4898
|
+
try{const e=await fetch(`http://localhost:${g}/api/sessions/${encodeURIComponent(p)}/agent-type`)
|
|
4918
4899
|
if(e.ok){const t=await e.json()
|
|
4919
4900
|
t.success&&t.agentType&&(w=t.agentType)}}catch{}const k=await r(m,function(e,t="agent"){const r=e.content||{},n=[`${{success:"\u2705",partial:"\u26a0\ufe0f",failure:"\u274c",blocked:"\u{1f6ab}"}[r.reportStatus]||"\u{1f4cb}"} **Report \u2014 ${r.reportStatus}**`,`from: ${t} (${e.fromSessionId})`,"",r.summary]
|
|
4920
4901
|
return r.details&&(n.push(""),n.push(r.details)),n.join("\n")}(y,w),t,s)
|
|
@@ -4936,14 +4917,14 @@ let s=null,i=null
|
|
|
4936
4917
|
try{s=await o(t,y,"session_message_operations",{operation:"offer-handoff"}),i=await n(s,m,y)}catch(e){y.warn("offer-handoff: could not discover parent session via HTTP",{error:(0,l.getErrorMessage)(e)})}if(!s){const e=u.sessionIdentity.getIdentity()
|
|
4937
4918
|
if(e?.sessionId){if(s=e.sessionId,y.info("offer-handoff: using cached session as fallback",{sessionId:s}),!i)try{i=await n(s,m,y)}catch(e){y.warn("offer-handoff: could not resolve parent from cached session",{error:(0,l.getErrorMessage)(e)})}}else y.warn("offer-handoff: no session ID available (discovery failed, no cache)")}try{const e=m.getSessionMessageClient()
|
|
4938
4919
|
if(e&&s){const t=r.requestIds?.length||0
|
|
4939
|
-
await e.createQuestion({fromSessionId:s,toSessionId:i||void 0,questionType:"alternatives",question:"Plan ready: "+(r.summary||"Plan complete"),options:[{id:"build",label:"Start Building",description:`Begin building ${t} request${1!==t?"s":""}`},{id:"plan",label:"Keep Planning",description:"Continue refining the plan"}],context:t>0?"Created requests: "+r.requestIds.join(", "):void 0,category:"action-required",priority:"high"}),y.info("offer-handoff: notification question created",{fromSessionId:s})}else y.warn("offer-handoff: skipping notification question",{hasClient:!!e,fromSessionId:s})}catch(e){y.warn("offer-handoff: failed to create notification question",{error:(0,l.getErrorMessage)(e)})}return{content:[{type:"text",text:'Handoff offered to user. STOP here and wait \u2014 the user will choose "Start Building" or "Keep Planning". You will receive their choice as a new message. Do NOT generate any further output until then.\nPLAN_HANDOFF_PENDING|'+JSON.stringify({summary:r.summary,requestIds:r.requestIds,parentSessionId:i})}],isError:!1}}case"list":return await async function(e,t,r,n){let{sessionId:o,messageType:s,direction:i,status:l,readStatus:u,reportStatus:g,limit:
|
|
4920
|
+
await e.createQuestion({fromSessionId:s,toSessionId:i||void 0,questionType:"alternatives",question:"Plan ready: "+(r.summary||"Plan complete"),options:[{id:"build",label:"Start Building",description:`Begin building ${t} request${1!==t?"s":""}`},{id:"plan",label:"Keep Planning",description:"Continue refining the plan"}],context:t>0?"Created requests: "+r.requestIds.join(", "):void 0,category:"action-required",priority:"high"}),y.info("offer-handoff: notification question created",{fromSessionId:s})}else y.warn("offer-handoff: skipping notification question",{hasClient:!!e,fromSessionId:s})}catch(e){y.warn("offer-handoff: failed to create notification question",{error:(0,l.getErrorMessage)(e)})}return{content:[{type:"text",text:'Handoff offered to user. STOP here and wait \u2014 the user will choose "Start Building" or "Keep Planning". You will receive their choice as a new message. Do NOT generate any further output until then.\nPLAN_HANDOFF_PENDING|'+JSON.stringify({summary:r.summary,requestIds:r.requestIds,parentSessionId:i})}],isError:!1}}case"list":return await async function(e,t,r,n){let{sessionId:o,messageType:s,direction:i,status:l,readStatus:u,reportStatus:g,limit:f,offset:p}=e
|
|
4940
4921
|
const m=n.getSessionMessageClient()
|
|
4941
4922
|
if(!m)throw new c.ValidationError("Session message client not available")
|
|
4942
4923
|
if(!o){const e=await(0,d.getServerUrl)(t,r)
|
|
4943
4924
|
if(!e)return{content:[{type:"text",text:"\u26a0\ufe0f Could not connect to OpenCode server. Unable to list messages without a session context."}]}
|
|
4944
4925
|
{const t={operation:"list",list:{messageType:s,direction:i,status:l}},n=await(0,d.getAndStoreSessionId)(e,r,"session_message_operations",t)
|
|
4945
4926
|
if(o=n?.sessionId,(0,h.logSessionIdentity)("session_message_operations.list",o?"per-call-discovery":"discovery-failed",{sessionId:o}),!o)return r.warn("Session discovery FAILED for list - returning empty to prevent data leak"),{content:[{type:"text",text:"\u26a0\ufe0f Could not determine current session ID. Unable to list messages without a session context."}]}}}r.debug("Listing messages",{sessionId:o,messageType:s,direction:i,status:l,readStatus:u})
|
|
4946
|
-
const y={sessionId:o,direction:i,limit:
|
|
4927
|
+
const y={sessionId:o,direction:i,limit:f,offset:p}
|
|
4947
4928
|
s&&"all"!==s&&(y.messageType=s),l&&"all"!==l&&("report"===s?y.reportStatus=l:y.status=l),u&&"all"!==u&&(y.readStatus=u),g&&"all"!==g&&(y.reportStatus=g)
|
|
4948
4929
|
const w=await m.listMessages(y)
|
|
4949
4930
|
if(0===w.length)return{content:[{type:"text",text:"No messages found matching the criteria."}]}
|
|
@@ -4993,12 +4974,12 @@ let l,d
|
|
|
4993
4974
|
try{l=await this.git.raw(["merge-base",i,c])}catch(t){return r.warn("Could not find merge-base, commits may be unrelated",{worktreeCommit:i.substring(0,8),targetCommit:c.substring(0,8),error:t}),{hasConflicts:!0,conflictedFiles:[{path:"<multiple files>",conflictType:"content",description:"Branches have diverged significantly (no merge-base found)"}],summary:"Branches have diverged significantly",resolutionInstructions:this.generateMultiAgentInstructions([{path:"<multiple files>",conflictType:"content",description:"Significant divergence"}],e.requestId,e.worktreePath,e.targetBranch),detectionMethod:"merge-tree-analysis",rawOutput:"merge-base failed: "+t}}r.debug("Commits for merge-tree analysis",{worktreeCommit:i.substring(0,8),targetCommit:c.substring(0,8),mergeBase:l.trim().substring(0,8)})
|
|
4994
4975
|
let u=0
|
|
4995
4976
|
try{d=await this.git.raw(["merge-tree",l.trim(),c.trim(),i.trim()]),u=0}catch(e){d=e.message||"",u=e.exitCode||1,r.debug("merge-tree failed with error",{exitCode:u,error:e.message})}r.debug("Merge-tree analysis completed",{outputLength:d.length,hasOutput:!!d.trim(),exitCode:u})
|
|
4996
|
-
let h=!1,g="",
|
|
4997
|
-
if(0!==u?(h=!0,g="merge-tree-exit-code"):d&&d.trim()?(
|
|
4998
|
-
!
|
|
4999
|
-
let
|
|
5000
|
-
if(
|
|
5001
|
-
else try{
|
|
4977
|
+
let h=!1,g="",f=null
|
|
4978
|
+
if(0!==u?(h=!0,g="merge-tree-exit-code"):d&&d.trim()?(f=(0,s.parseConflictOutputWithContext)(d,e.requestId,e.sourceBranch,e.targetBranch),f.hasConflictMarkers?(h=!0,g="conflict-parser-detected-markers",r.warn("Git exit code 0 but conflict parser found conflict markers - treating as conflict")):(h=!1,g="clean-merge-with-changes",r.info("Git exit code 0 and conflict parser found no markers - treating as clean merge",{hasOutput:!0,outputLength:d.length}))):(h=!1,g="clean-merge-no-changes"),r.info("FINAL conflict detection result (trusting Git exit codes)",{hasConflicts:h,exitCode:u,hasOutput:!!d.trim(),outputLength:d?d.length:0,conflictReason:g,method:"git-exit-code-primary",trustedGitExitCode:0===u}),!h)return{hasConflicts:!1,conflictedFiles:[],summary:"No conflicts detected (merge-tree clean)",resolutionInstructions:"",detectionMethod:"merge-tree-analysis",rawOutput:d}
|
|
4979
|
+
!f&&d&&d.trim()&&(f=(0,s.parseConflictOutputWithContext)(d,e.requestId,e.sourceBranch,e.targetBranch))
|
|
4980
|
+
let p=[]
|
|
4981
|
+
if(f&&f.filesParsed&&f.filesParsed.length>0)p=f.filesParsed.map((e=>({path:e,conflictType:"content",description:"Merge conflict detected"}))),r.debug("Successfully extracted conflict files from parsed content",{conflictedFilesCount:p.length,files:p.map((e=>e.path))})
|
|
4982
|
+
else try{p=this.parseMergeTreeOutput(d,r),r.debug("Used fallback merge-tree parsing",{conflictedFilesCount:p.length})}catch(e){r.warn("Both conflict parsing methods failed",{parseError:e instanceof Error?e.message:e+""}),p=[{path:"<parsing failed>",conflictType:"content",description:"Git detected conflicts but parsing failed - manual inspection required"}]}return 0===p.length&&(r.warn("Git detected conflicts but no files could be determined - using fallback"),p=[{path:"<unknown files>",conflictType:"content",description:"Git detected conflicts but could not determine specific files"}]),{hasConflicts:!0,conflictedFiles:p,summary:p.length>0&&"<parsing failed>"!==p[0].path&&"<unknown files>"!==p[0].path?p.length+" file(s) have merge conflicts (detected by Git)":"Merge conflicts detected by Git (parsing details failed)",resolutionInstructions:this.generateMultiAgentInstructions(p,e.requestId,e.worktreePath,e.targetBranch),detectionMethod:"merge-tree-analysis",rawOutput:d,rawConflictContent:f?f.cleanContent:void 0}}catch(e){throw r.error("Pure multi-agent conflict detection failed",{error:e}),e}}parseMergeTreeOutput(e,t){const r=[]
|
|
5002
4983
|
if(!e||!e.trim())return t.debug("Empty merge-tree output - no conflicts to parse"),[]
|
|
5003
4984
|
let n
|
|
5004
4985
|
try{n=e.split("\n"),t.debug("Parsing merge-tree output",{linesCount:n.length,totalLength:e.length,firstFewLines:n.slice(0,5),hasNewlines:e.includes("\n")})}catch(r){throw t.error("Failed to split merge-tree output into lines",{error:r instanceof Error?r.message:r+"",outputLength:e.length}),Error("Failed to parse merge-tree output: "+r)}let o=!1
|
|
@@ -5050,23 +5031,23 @@ o+="## Test 3: Recent merge commits (to see actual patterns)\n",o+=`Found ${e?.a
|
|
|
5050
5031
|
o+=`## Test 4: All commits containing "${n}" (not just merges)\n`,o+=`Found ${e?.all?.length||0} commits:\n`,e?.all?.length>0?e.all.forEach(((e,t)=>{o+=`${t+1}. ${e.hash.substring(0,8)} - ${e.message}\n`})):o+="No commits found\n",o+="\n"}catch(e){o+=`## Test 4: Error - ${(0,r.getErrorMessage)(e)}\n\n`}try{const e=await t.git.revparse(["--abbrev-ref","HEAD"])
|
|
5051
5032
|
o+=`## Current branch: ${e}\n\n`}catch(e){o+=`## Current branch: Error - ${(0,r.getErrorMessage)(e)}\n\n`}try{const e=await t.git.branch()
|
|
5052
5033
|
o+="## All branches:\n",e.all&&e.all.length>0?e.all.forEach((e=>{o+=`- ${e}\n`})):o+="No branches found\n",o+="\n"}catch(e){o+=`## Branches: Error - ${(0,r.getErrorMessage)(e)}\n\n`}return{content:[{type:"text",text:o}]}}catch(e){return s.error("Error in debug request file history",{error:e instanceof Error?e.stack:e+""}),{content:[{type:"text",text:"Error: "+(0,r.getErrorMessage)(e)}],isError:!0}}}
|
|
5053
|
-
const r=t(8824)},9442(e,exports,t){function r(e){return{line:e.line,actually_matched:e.actuallyMatched,match_type:e.matchType}}async function n(e,t,n,o,s,i,a){const{path:c,documentId:d,replacements:g,fuzzy_match:
|
|
5034
|
+
const r=t(8824)},9442(e,exports,t){function r(e){return{line:e.line,actually_matched:e.actuallyMatched,match_type:e.matchType}}async function n(e,t,n,o,s,i,a){const{path:c,documentId:d,replacements:g,fuzzy_match:f}=e,p=!!d,m=void 0!==f?f:t,y={type:p?"document":"file",path:c,documentId:d,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,externalEditDebugInfo:{detectionRan:!1,reason:p?"Skipped: Document operation":n.git?"Pending":"Skipped: No Git context"}}
|
|
5054
5035
|
try{let t,o
|
|
5055
|
-
if(
|
|
5036
|
+
if(p){t=await n.documentFileManager.getDocumentAsFile(d)
|
|
5056
5037
|
const e=n.documentFileManager.getCachedDocumentInfo(d)
|
|
5057
5038
|
y.filename=e?.filename,o="document:"+d}else{const e=u.validateAndNormalizePath(c,n)
|
|
5058
|
-
o=e.normalizedPath,t=e.fullPath,y.path=o}const s=await l.default.readFile(t,"utf8"),
|
|
5039
|
+
o=e.normalizedPath,t=e.fullPath,y.path=o}const s=await l.default.readFile(t,"utf8"),f=[]
|
|
5059
5040
|
for(const t of g){const{old:n,new:o,match_mode:i="unique"}=t,a={old:n,new:o,success:!1}
|
|
5060
5041
|
try{if(n===o){a.error="No-op replacement (old and new values are identical)",a.success=!1,a.matchesFound=0,y.failedReplacements++,y.replacements.push(a)
|
|
5061
5042
|
continue}const t=(0,h.findMatches)(s,n,m,100,e.path)
|
|
5062
5043
|
if(a.matchesFound=t.length,0===t.length){a.error="No matches found"+(m?" (tried fuzzy matching)":""),a.success=!1
|
|
5063
5044
|
const e=(0,h.findSimilarMatches)(s,n,5,.3)
|
|
5064
|
-
e.length>0&&(a.similarMatches=e),y.failedReplacements++}else"unique"===i&&t.length>1?(a.error=`Multiple matches found (${t.length}) - expected unique match`,a.success=!1,a.details=t.map(r),y.failedReplacements++):
|
|
5045
|
+
e.length>0&&(a.similarMatches=e),y.failedReplacements++}else"unique"===i&&t.length>1?(a.error=`Multiple matches found (${t.length}) - expected unique match`,a.success=!1,a.details=t.map(r),y.failedReplacements++):f.push({matches:t,newText:o,matchMode:i,repResult:a})}catch(e){a.error=(0,k.getErrorMessage)(e),a.success=!1,y.failedReplacements++}y.replacements.push(a)}let w=s
|
|
5065
5046
|
const b=[]
|
|
5066
|
-
for(const e of
|
|
5047
|
+
for(const e of f)for(const t of e.matches)b.push({match:t,newText:e.newText,repResult:e.repResult})
|
|
5067
5048
|
b.sort(((e,t)=>t.match.startPos-e.match.startPos))
|
|
5068
5049
|
for(const{match:e,newText:t,repResult:n}of b)w=(0,h.replaceMatch)(w,e,t),n.success?(n.lines.push(e.line),n.details.push(r(e))):(n.success=!0,n.matchType=e.matchType,n.lines=[e.line],n.details=[r(e)],y.successfulReplacements++)
|
|
5069
|
-
y.successfulReplacements>0&&(await l.default.writeFile(t,w,"utf8"),
|
|
5050
|
+
y.successfulReplacements>0&&(await l.default.writeFile(t,w,"utf8"),p&&(n.documentFileManager.markForSync(d),await n.documentFileManager.syncDocument(d))),i&&(y.externalEditWarning=i),a&&(y.externalEditDebugInfo={detectionRan:!0,...a}),y.success=0===y.failedReplacements}catch(e){y.error=(0,k.getErrorMessage)(e),y.success=!1,y.failedReplacements=g.length,y.replacements=g.map((e=>({old:e.old,new:e.new,success:!1,error:y.error})))}return y}var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
5070
5051
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
5071
5052
|
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]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[]
|
|
5072
5053
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -5076,7 +5057,7 @@ if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
|
5076
5057
|
return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
5077
5058
|
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()
|
|
5078
5059
|
let v,C=u.FileOperationPhase.VALIDATION
|
|
5079
|
-
try{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)
|
|
5060
|
+
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)
|
|
5080
5061
|
const i=u.validateArgs(e,d.ReplaceInFilesSchema),{taskId:_,operations:E,fuzzy_match:q=!0,comment:S}=i
|
|
5081
5062
|
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})
|
|
5082
5063
|
const T=E.filter((e=>e.documentId)).map((e=>e.documentId))
|
|
@@ -5095,26 +5076,26 @@ const n=await u.autoPromoteTaskStatus(_,x.status,O,e.request?.status,R,r,s,b,a,"
|
|
|
5095
5076
|
n.taskPromoted&&b.info("Auto-promoted task to in_progress",{taskId:_,requestId:O,previousStatus:x.status,newStatus:n.newTaskStatus}),Date.now(),P=Date.now()
|
|
5096
5077
|
const o=await u.ensureCorrectWorkspaceContext({taskPromoted:n.taskPromoted,requestId:O,context:t,operation:"replace_in_files",logger:b,metrics:a,metricsPrefix:"replace_in_files"})
|
|
5097
5078
|
if(!o.success){if(o.isLockConflict)return{content:[{type:"text",text:"\u274c "+o.error}],isError:!0}
|
|
5098
|
-
throw Error(o.error)}Date.now(),$=!0}if(T.length>0&&O)try{await(0,
|
|
5079
|
+
throw Error(o.error)}Date.now(),$=!0}if(T.length>0&&O)try{await(0,f.validateRequestStatusForDocumentOperation)(O,s,b,a,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
5099
5080
|
throw e}P=Date.now()
|
|
5100
|
-
const
|
|
5081
|
+
const D=new Map
|
|
5101
5082
|
if(b.info("\u{1f50d} Starting external edit detection",{hasFileOperations:j,hasGit:!!t.git,operationCount:E.length}),j&&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=[]
|
|
5102
5083
|
for(const t of e.replacements){const r=(0,h.findMatches)(n,t.old,o,100,e.path)
|
|
5103
5084
|
s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,r.fullPath)
|
|
5104
5085
|
b.info("\u{1f50d} Checking for external edits",{path:r.normalizedPath,affectedLines:o.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),matchCount:s.length})
|
|
5105
5086
|
const i=await(0,w.detectExternalEdits)(t.git,o,b)
|
|
5106
|
-
b.info("\u{1f50d} External edit detection result",{path:r.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?(
|
|
5107
|
-
const e=await(0,
|
|
5087
|
+
b.info("\u{1f50d} External edit detection result",{path:r.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?(D.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&&D.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}),D.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(),P=Date.now(),j&&t.git)try{b.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
|
|
5088
|
+
const e=await(0,p.commitUserChangesBeforeToolOperation)(t.git,"replace_in_files",{requestId:O,taskId:_,workspaceManager:t.workspaceManager},b,a)
|
|
5108
5089
|
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(),P=Date.now(),C=u.FileOperationPhase.RECORD_CREATION,a.incrementCounter("replace_in_files_phase",1,{phase:C})
|
|
5109
|
-
const{toolRecordId:
|
|
5110
|
-
v=
|
|
5090
|
+
const{toolRecordId:A}=await u.createFileOperationRecords(_,O,t.projectId,"replace-in-files",R,{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)
|
|
5091
|
+
v=A,Date.now(),P=Date.now(),C=u.FileOperationPhase.STRING_REPLACEMENT,a.incrementCounter("replace_in_files_phase",1,{phase:C})
|
|
5111
5092
|
const F=[],N=[]
|
|
5112
|
-
for(const e of E){const r=e.path?
|
|
5093
|
+
for(const e of E){const r=e.path?D.get(e.path):void 0,o=await n(e,q,t,0,0,r?.message,r?.debugInfo)
|
|
5113
5094
|
F.push(o),o.successfulReplacements>0&&"file"===o.type&&o.path&&N.push(o.path)}Date.now(),P=Date.now()
|
|
5114
|
-
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:
|
|
5095
|
+
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),B=z.commitHash
|
|
5115
5096
|
Date.now(),Date.now()
|
|
5116
|
-
const H=F.filter((e=>e.success)).length,
|
|
5117
|
-
await o.updateToolRecord(v,{metadata:{path:R,status:0===
|
|
5097
|
+
const H=F.filter((e=>e.success)).length,W=F.length-H,U=F.reduce(((e,t)=>e+t.successfulReplacements),0),G=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})))
|
|
5098
|
+
await o.updateToolRecord(v,{metadata:{path:R,status:0===W?"completed":"partial",operationCount:E.length,operations:V,successfulFiles:J,failedFiles:K,successfulReplacements:U,failedReplacements:G,processingTime:Date.now()-I,userComment:S,...z.success&&z.commitHash&&{commitHash:z.commitHash,previousCommitHash:z.previousCommitHash||void 0}}})
|
|
5118
5099
|
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
|
|
5119
5100
|
let l="## Replace In Files - Batch Results\n\n"
|
|
5120
5101
|
if(o.getCurrentBranchContext)try{const e=await o.getCurrentBranchContext()
|
|
@@ -5126,10 +5107,10 @@ if(o.length>0){l+="\n**Successful Replacements:**\n"
|
|
|
5126
5107
|
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))
|
|
5127
5108
|
if(s.length>0){l+="\n**Failed Replacement Details:**\n"
|
|
5128
5109
|
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)))
|
|
5129
|
-
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,B,
|
|
5130
|
-
return{content:[{type:"text",text:Y}],isError:0===
|
|
5110
|
+
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,B,U,G,t,v)
|
|
5111
|
+
return{content:[{type:"text",text:Y}],isError:0===U}}catch(e){const t=Date.now()-I
|
|
5131
5112
|
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}}}
|
|
5132
|
-
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),
|
|
5113
|
+
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),f=t(5003),p=t(7478),m=t(9949),y=t(9947),w=t(1318),k=t(8824)},9470(e,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseLineSpec=function(e){if(!e||""===e.trim())throw Error("Line specification cannot be empty")
|
|
5133
5114
|
const t=e.trim()
|
|
5134
5115
|
if(t.includes("-")){const r=t.split("-").map((e=>e.trim()))
|
|
5135
5116
|
if(2!==r.length)throw Error(`Invalid line range format: "${e}". Expected format: "start-end" (e.g., "5-15")`)
|
|
@@ -5272,11 +5253,11 @@ if(!u)throw new n.ValidationError("Project ID is required for listing tasks with
|
|
|
5272
5253
|
a.incrementCounter("list_tasks_attempts",1,{hasRequestId:!!i,hasFilters:Object.keys(d).length>0}),s.setProjectId(u)
|
|
5273
5254
|
const h=s.getTaskClient(),g=d
|
|
5274
5255
|
i&&(g.requestId=i),c.info("Listing tasks with filters",{projectId:u,taskFilters:g})
|
|
5275
|
-
const
|
|
5276
|
-
c.info("Raw tasks response data",{responseData:JSON.stringify(
|
|
5277
|
-
let
|
|
5278
|
-
|
|
5279
|
-
const m=
|
|
5256
|
+
const f=await h.listTasks(g)
|
|
5257
|
+
c.info("Raw tasks response data",{responseData:JSON.stringify(f)}),c.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"})
|
|
5258
|
+
let p=[]
|
|
5259
|
+
f&&"object"==typeof f?"success"in f&&"data"in f?Array.isArray(f.data)?(p=f.data,c.info("Extracted tasks from success/data wrapper",{count:p.length})):f.data&&"object"==typeof f.data&&(p=[f.data],c.info("Extracted single task from success/data wrapper")):"data"in f?Array.isArray(f.data)?(p=f.data,c.info("Extracted tasks from data wrapper",{count:p.length})):f.data&&"object"==typeof f.data&&(p=[f.data],c.info("Extracted single task from data wrapper")):Array.isArray(f)?(p=f,c.info("Tasks response is direct array",{count:p.length})):(p=[f],c.info("Tasks response is single object")):(c.warn("Unexpected response format, using empty array",{responseType:typeof f}),p=[])
|
|
5260
|
+
const m=p
|
|
5280
5261
|
if(c.info(`Retrieved ${m.length} tasks`,{count:m.length,requestId:i,projectId:u}),0===m.length){let e=""
|
|
5281
5262
|
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")
|
|
5282
5263
|
let w
|
|
@@ -5387,7 +5368,7 @@ if(null===c){n.warn("Could not read plugin source: "+e.sourceName),l.errors.push
|
|
|
5387
5368
|
continue}const d=e.destName.startsWith("lib/")?c:["const __plugin = (function() {\n const module = { exports: {} };\n const exports = module.exports;\n (function() {",c," })();\n return module.exports.default || module.exports;\n})();\nexport default __plugin;"].join("\n"),h=i.default.createHash("md5").update(d).digest("hex"),g=r(a)
|
|
5388
5369
|
if(null===g||h!==g){const t=s.default.dirname(a)
|
|
5389
5370
|
t!==u&&await o.default.promises.mkdir(t,{recursive:!0}),await o.default.promises.writeFile(a,d,"utf8"),n.info("Synced plugin: "+e.destName,{reason:null===g?"not installed":"updated"}),l.synced.push(e.destName)}else l.skipped.push(e.destName)}catch(t){n.error("Failed to sync plugin: "+e.destName,{error:t instanceof Error?t.message:"Unknown error"}),l.errors.push(e.destName)}}return l}
|
|
5390
|
-
const o=n(t(9896)),s=n(t(6928)),i=n(t(6982)),a=[{sourceName:"plugins/hooks/plugin.js",destName:"event-hooks.js"},{sourceName:"plugins/hooks/lib/condition-evaluator.js",destName:"lib/condition-evaluator.js"},{sourceName:"plugins/hooks/lib/hook-utils.js",destName:"lib/hook-utils.js"},{sourceName:"plugins/hooks/lib/dedup-utils.js",destName:"lib/dedup-utils.js"},{sourceName:"plugins/inject-session.js",destName:"inject-session.js"},{sourceName:"plugins/
|
|
5371
|
+
const o=n(t(9896)),s=n(t(6928)),i=n(t(6982)),a=[{sourceName:"plugins/hooks/plugin.js",destName:"event-hooks.js"},{sourceName:"plugins/hooks/lib/condition-evaluator.js",destName:"lib/condition-evaluator.js"},{sourceName:"plugins/hooks/lib/hook-utils.js",destName:"lib/hook-utils.js"},{sourceName:"plugins/hooks/lib/dedup-utils.js",destName:"lib/dedup-utils.js"},{sourceName:"plugins/inject-session.js",destName:"inject-session.js"},{sourceName:"plugins/system-logger.js",destName:"system-logger.js"}]},9947(e,exports){function t(e,t){return e.substring(0,t).split("\n").length}function r(e){if(0===e.length)return[]
|
|
5391
5372
|
const t=[...e].sort(((e,t)=>e.start-t.start)),r=[t[0]]
|
|
5392
5373
|
for(let e=1;e<t.length;e++){const n=t[e],o=r[r.length-1]
|
|
5393
5374
|
n.start>o.end+1?r.push(n):o.end=Math.max(o.end,n.end)}return r}function n(e,t){return e.start<=t.end&&t.start<=e.end}Object.defineProperty(exports,"__esModule",{value:!0}),exports.calculateReplacementRegion=function(e,n,o){const s=[]
|