alchemylab 1.2.4 → 1.3.1
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/640.js +14 -0
- package/dist/cli.js +177 -90
- package/dist/http-server.js +619 -582
- package/dist/index.js +411 -374
- package/dist/mcp-direct.js +152 -115
- package/package.json +1 -1
package/dist/http-server.js
CHANGED
|
@@ -14,13 +14,13 @@ h.info("Raw request verification response data",{responseData:JSON.stringify(t)}
|
|
|
14
14
|
const r=(0,o.extractDataFromResponse)(t,{logger:h,operationName:"verifyRequestExists",throwOnNoData:!0})
|
|
15
15
|
p="object"==typeof r&&null!==r&&"data"in r?r.data:r,h.info(`Verified request ${c.requestId} exists`,{requestId:c.requestId,projectId:d,requestStatus:p.status})}catch(e){throw new n.NotFoundError(`Request ${c.requestId} not found in project ${d}. Please provide a valid request ID.`,{requestId:c.requestId,projectId:d,originalError:e})}if(["pending_approval","completed","canceled","ready_for_review","ready_for_merge","reverted"].includes(p.status)){const e={pending_approval:"is pending approval. Approve the request before creating tasks.",completed:"is already completed and merged. Create a new request for additional changes.",canceled:"was canceled. Create a new request or reopen this one if needed.",ready_for_review:"is being tested. Wait for test results before making changes.",ready_for_merge:"is ready to merge. Call merge to complete it.",reverted:"was reverted and cannot accept new tasks. Re-complete the request first or create a new request."}[p.status]||`has status '${p.status}' and cannot accept new tasks.`
|
|
16
16
|
throw h.warn(`Task creation blocked on ${p.status} request`,{requestId:c.requestId,requestStatus:p.status,projectId:d}),new n.ValidationError(`The request ID "${c.requestId}" ${e}`,{requestId:c.requestId,requestStatus:p.status,reason:"request_"+p.status})}h.info("Request status validation passed for "+c.requestId,{requestId:c.requestId,requestStatus:p.status,projectId:d})
|
|
17
|
-
const
|
|
17
|
+
const m=a.getTaskClient()
|
|
18
18
|
h.info("Creating task with project context",{projectId:d})
|
|
19
|
-
const
|
|
20
|
-
h.info("Task input prepared",{taskInput:JSON.stringify(
|
|
21
|
-
const y=await
|
|
19
|
+
const f={requestId:c.requestId,projectId:d,title:c.title,description:c.description,status:"pending",...u&&{cliOrigin:u}}
|
|
20
|
+
h.info("Task input prepared",{taskInput:JSON.stringify(f)}),h.info("Creating task via task client",{projectId:d,requestId:c.requestId,title:c.title})
|
|
21
|
+
const y=await m.createTask(f)
|
|
22
22
|
h.debug("Task creation response structure",{type:typeof y,isArray:Array.isArray(y),hasData:null!=y,properties:y?Object.keys(y):[],dataPreview:y?JSON.stringify(y).substring(0,200)+"...":"null"})
|
|
23
|
-
const w=(0,o.extractDataFromResponse)(y,{logger:h,operationName:"createTask",defaultValue:{id:"tas"+Date.now().toString().substring(5,11),title:
|
|
23
|
+
const w=(0,o.extractDataFromResponse)(y,{logger:h,operationName:"createTask",defaultValue:{id:"tas"+Date.now().toString().substring(5,11),title:f.title,description:f.description,status:"pending",requestId:f.requestId,projectId:d,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}}),k="data"in w?w.data:w,I=k.localId||k.id||"tas"+Date.now().toString().substring(5,11),b=k.title||f.title,v=k.description||f.description,C=k.status||"pending",_=k.requestId||f.requestId
|
|
24
24
|
let E,q="unknown"
|
|
25
25
|
k&&"object"==typeof k&&"_workingEndpoint"in k&&(q=k._workingEndpoint),h.info("Successfully extracted task data from response",{taskId:I,requestId:_,title:b})
|
|
26
26
|
try{const e=a.getToolRecordClient()
|
|
@@ -45,9 +45,9 @@ var t={}
|
|
|
45
45
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
46
46
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
47
47
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.McpServer=void 0,exports.resetStdoutWrite=function(){process.stdout.write=x},exports.getMcpServer=r,exports.createServer=function(e,t,n,o,s={}){return r(e,t,n,o,s)}
|
|
48
|
-
const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),p=t(3444),
|
|
48
|
+
const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),p=t(3444),m=t(7660),f=t(1253),y=t(5172),w=i(t(7478)),k=t(4139),I=new Set,b=t(9860),v=t(1472),C=t(3328),_=t(8955),E=t(3217),q=t(5278),S=t(446),T=t(9060),P=t(8824),j=(0,p.createLogger)({serviceName:"stdout-capture",console:!1,logToFile:!1}),x=process.stdout.write,R=process.argv.includes("--stdio")||"true"===process.env.MCP_DIRECT_MODE
|
|
49
49
|
!(0,p.isDebugToolsEnabled)()||R&&"true"!==process.env.DEBUG_STDOUT_CAPTURE||(process.stdout.write=function(e){try{return(0,p.isDebugToolsEnabled)()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()&&"string"==typeof e&&!e.trim().startsWith('{"jsonrpc":"2.0"')&&e.trim().length>0&&j.debug("Stdout output",{content:e.substring(0,100),length:e.length}),x.call(process.stdout,e)}catch(e){return j.error("Error in safeStdoutWrite",{error:e+""}),!0}})
|
|
50
|
-
class M{constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,k.ALCHEMY_DIR_NAME),this.metrics=r,this.remoteServerUrl=n,this.existingProjectId=o.existingProjectId,this.gitBinary=(0,l.detectGitBinary)(),this.logger.info("Detected git binary",{gitBinary:this.gitBinary,version:(0,l.getGitVersion)()}),this.projectContext=new
|
|
50
|
+
class M{constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,k.ALCHEMY_DIR_NAME),this.metrics=r,this.remoteServerUrl=n,this.existingProjectId=o.existingProjectId,this.gitBinary=(0,l.detectGitBinary)(),this.logger.info("Detected git binary",{gitBinary:this.gitBinary,version:(0,l.getGitVersion)()}),this.projectContext=new m.ProjectContext(e,t),this.tokenManager=new f.TokenManager(t,e,{remoteServerUrl:n}),this.lockOverrideManager=new S.LockOverrideManager(t),this.configManager=new T.ConfigManager(t),this.logger.debug("Server paths initialized",{basePath:this.basePath,alchemyPath:this.alchemyPath}),this.server=new g.Server({name:"alchemy",version:"1.0.0"},{capabilities:{tools:{search:{},create_request:{},complete_task:{},get_task_information:{},complete_request:{},revert_request:{},get_request_information:{},list_tasks:{},list_requests:{},switch_to_branch:{},read_files:{},create_directory:{},move_files:{},write_file:{},replace_strings:{},insert_lines:{},replace_lines:{},delete_files:{},document_operations:{},file_history:{},task_file_history:{},request_file_history:{},quick_write:{},quick_replace:{},quick_manage:{}}}}),(0,y.setGlobalClientInfo)("OpenCode","1.0.0"),this.metrics.incrementCounter("mcp_server_init_started",1),this.logger.info("Starting initialization for server instance"),this.initializationPromise=this.initialize()}get branchState(){if(!this.workspaceManager)return{currentBranch:null,activeRequestId:null,isOnMainBranch:!0}
|
|
51
51
|
const e=this.workspaceManager.getCurrentContext("__server__")
|
|
52
52
|
return{currentBranch:e.branchName,activeRequestId:e.requestId,isOnMainBranch:e.isMainBranch}}async updateBranchState(e,t){this.logger.debug("updateBranchState called - managed by WorkspaceManager",{branch:e,requestId:t})}async getCurrentBranchContext(){if(!this.workspaceManager)return{branch:null,requestId:null,isMain:!0}
|
|
53
53
|
const e=this.workspaceManager.getCurrentContext("__server__")
|
|
@@ -148,9 +148,9 @@ if(!a||0===a.trim().length)throw new i.ValidationError("Search query is required
|
|
|
148
148
|
const p=t.projectId
|
|
149
149
|
if(!p)throw new i.ValidationError("Project ID is required for searching requests")
|
|
150
150
|
u.info("Searching requests",{query:a,searchIn:l,filters:g,projectId:p})
|
|
151
|
-
const
|
|
152
|
-
g.status&&(
|
|
153
|
-
const
|
|
151
|
+
const m={limit:g.limit||100,offset:g.offset||0,sortBy:"updated_at",sortDirection:"desc"}
|
|
152
|
+
g.status&&(m.status=g.status),g.type&&(m.type=g.type),g.dateFrom&&(m.dateFrom=g.dateFrom),g.dateTo&&(m.dateTo=g.dateTo),c.setProjectId(p)
|
|
153
|
+
const f=c.getRequestClient(),y=await f.listRequests(m)
|
|
154
154
|
u.debug("Fetched requests for search",{count:y.length})
|
|
155
155
|
const w=[],k=a.toLowerCase()
|
|
156
156
|
for(const e of y){const t=[]
|
|
@@ -198,12 +198,12 @@ return{id:e.id,title:e.title,description:e.description,type:e.type,status:t,acce
|
|
|
198
198
|
const o=t(6756)},355(e,exports,t){"use strict"
|
|
199
199
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteTask=async function(e,d,u,h,g){const p=h.child({tool:"complete_task"})
|
|
200
200
|
p.info("Completing task",{args:e})
|
|
201
|
-
const
|
|
201
|
+
const m=g.startTimer("tool_handler_duration")
|
|
202
202
|
try{const o=function(e){if(void 0!==e.verificationSteps){const{verificationSteps:t,...r}=e
|
|
203
203
|
e=r}try{return r.CompleteTaskSchema.parse(e)}catch(e){if(e instanceof i.ZodError&&e.errors.length>0)throw new n.ValidationError(e.errors[0].message)
|
|
204
204
|
throw new n.ValidationError("Invalid input: "+(0,c.getErrorMessage)(e))}}(e)
|
|
205
205
|
let h=o.taskId
|
|
206
|
-
const
|
|
206
|
+
const f=o.summary;(0,l.isTaskRef)(h)&&(h=await(0,l.resolveTaskRef)(h,u,p))
|
|
207
207
|
const y=d.projectId
|
|
208
208
|
if(!y)throw new n.ValidationError("Project ID is required for completing tasks with the new API structure")
|
|
209
209
|
g.incrementCounter("complete_task_attempts",1,{taskId:h}),u.setProjectId(y)
|
|
@@ -227,18 +227,18 @@ let I=d.git
|
|
|
227
227
|
if(d.workspaceManager){const e=d.workspaceManager.getCurrentContext(d.currentSessionId)
|
|
228
228
|
if("multi-agent"===e.mode&&e.requestId){const{simpleGit}=t(3807)
|
|
229
229
|
I=simpleGit({baseDir:e.basePath,binary:d.gitBinary}),p.debug("Using workspace-aware git instance for task completion",{taskId:h,mode:e.mode,requestId:e.requestId,basePath:e.basePath})}}let b=null
|
|
230
|
-
if(I)try{(await I.status()).isClean()||(b=(await I.commit(`Complete task ${h}: ${
|
|
230
|
+
if(I)try{(await I.status()).isClean()||(b=(await I.commit(`Complete task ${h}: ${f}`)).commit,p.info("Created commit for task completion",{taskId:h,commitId:b}))}catch(e){p.warn("Failed to commit changes",{error:(0,c.getErrorMessage)(e)})}let v=null
|
|
231
231
|
try{const e=u.getToolRecordClient()
|
|
232
|
-
e&&(v={id:(await e.createToolRecord({taskId:h,requestId:k.requestId,projectId:y,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:k.title,completionSummary:
|
|
232
|
+
e&&(v={id:(await e.createToolRecord({taskId:h,requestId:k.requestId,projectId:y,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:k.title,completionSummary:f,lastCommit:b,completedAt:(new Date).toISOString()},note:`Completed task: ${f.substring(0,100)}${f.length>100?"...":""}`})).id})}catch(e){p.error("Failed to create tool record for task completion, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:h,requestId:k.requestId})}try{const e=k.metadata||{},t=(new Date).toISOString(),r={status:"completed",metadata:{...e,lastCommit:b,completionSummary:f,completionRecordId:v?.id,completedAt:t}},n=await w.updateTask(h,r)
|
|
233
233
|
p.info("Raw task update response data",{responseData:JSON.stringify(n)}),p.debug("Task update response structure",{type:typeof n,isArray:Array.isArray(n),hasData:null!=n,properties:n?Object.keys(n):[],dataPreview:n?JSON.stringify(n).substring(0,200)+"...":"null"}),(0,s.extractDataFromResponse)(n,{logger:p,operationName:"updateTask",defaultValue:{id:h,status:"completed"}}),p.info("Successfully completed task",{taskId:h,recordId:v?.id})
|
|
234
234
|
const o=k.requestId,i=k.requestId
|
|
235
235
|
let a=`Task ${k.sequenceNumber&&i?(0,l.formatTaskRef)(i,k.sequenceNumber):h} (${k.title}) has been marked as completed.`
|
|
236
236
|
if(v?.id&&(a+=`\n[RECORD:${v.id}]`),b&&(a+="\nCommit: "+b.substring(0,8)),o)try{const e=await w.listTasks({requestId:o})
|
|
237
237
|
p.info("Raw tasks list response data",{responseData:JSON.stringify(e)}),p.debug("Tasks list response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
|
|
238
238
|
const t=(0,s.extractArrayFromResponse)(e,{logger:p,operationName:"listTasksForProgress",defaultValue:[]}),r=t.length,n=t.filter((e=>"completed"===e.status)).length
|
|
239
|
-
p.info("Task progress check",{requestId:o,totalTasks:r,completedTasks:n}),a+=`\n\nTask Progress: ${n}/${r} tasks completed`,n===r&&(a+=`\n\nAll tasks for request ${o} are now completed! You may consider marking the request as completed using the complete-request tool.`)}catch(e){p.warn("Failed to check task progress",{error:(0,c.getErrorMessage)(e),requestId:o})}return
|
|
239
|
+
p.info("Task progress check",{requestId:o,totalTasks:r,completedTasks:n}),a+=`\n\nTask Progress: ${n}/${r} tasks completed`,n===r&&(a+=`\n\nAll tasks for request ${o} are now completed! You may consider marking the request as completed using the complete-request tool.`)}catch(e){p.warn("Failed to check task progress",{error:(0,c.getErrorMessage)(e),requestId:o})}return m({success:!0}),{content:[{type:"text",text:a}]}}catch(e){throw p.error("Failed to complete task",{error:e instanceof Error?e.stack:e+"",taskId:h}),Error("Failed to complete task: "+(0,c.getErrorMessage)(e))}}catch(t){if(p.error("Failed to complete task",{error:t instanceof Error?t.stack:t+"",args:e}),d.projectId)try{const r=u.getToolRecordClient()
|
|
240
240
|
if(r){const o=t instanceof n.NotFoundError||t instanceof n.ValidationError||t instanceof i.ZodError
|
|
241
|
-
await r.createToolRecord({...o?{}:{taskId:e.taskId},projectId:d.projectId,type:"complete-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.summary?.substring(0,100)+(e.summary?.length>100?"...":""),error:(0,c.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",attemptedTaskId:e.taskId,taskIdValidationFailed:o},note:"Failed to complete task "+e.taskId})}}catch(e){p.error("Failed to create failure record for task completion",{error:e instanceof Error?e.message:e+""})}
|
|
241
|
+
await r.createToolRecord({...o?{}:{taskId:e.taskId},projectId:d.projectId,type:"complete-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.summary?.substring(0,100)+(e.summary?.length>100?"...":""),error:(0,c.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",attemptedTaskId:e.taskId,taskIdValidationFailed:o},note:"Failed to complete task "+e.taskId})}}catch(e){p.error("Failed to create failure record for task completion",{error:e instanceof Error?e.message:e+""})}m({success:!1,error:t instanceof Error?t.name:"unknown"})
|
|
242
242
|
let r=(0,c.getErrorMessage)(t)
|
|
243
243
|
return t instanceof n.NotFoundError&&(r=`The task ID "${e.taskId}" was not found. Please provide a valid task ID.`),t instanceof o.ConnectionError&&(r="Unable to complete task: Connection to the server failed. Please check your network connection and try again."),t instanceof i.ZodError&&t.errors.length>0&&(r=t.errors[0].message),{content:[{type:"text",text:"Error: "+r}],isError:!0}}}
|
|
244
244
|
const r=t(6183),n=t(9860),o=t(5674),s=t(2960),i=t(1569),a=t(5172),c=t(8824),l=t(4466)},405(e,exports,t){"use strict"
|
|
@@ -374,23 +374,23 @@ var t={}
|
|
|
374
374
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
375
375
|
return o(t,e),t})
|
|
376
376
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQueryHistory=async function(e,r,n,o,s,g){const p=o.child({tool:"query_history"})
|
|
377
|
-
try{const h=a.validateArgs(e,i.QueryHistorySchema),{queryType:
|
|
378
|
-
let
|
|
379
|
-
switch(p.info("Processing query_history request",{queryType:
|
|
377
|
+
try{const h=a.validateArgs(e,i.QueryHistorySchema),{queryType:m}=h
|
|
378
|
+
let f
|
|
379
|
+
switch(p.info("Processing query_history request",{queryType:m}),m){case"file-history":p.info("Routing to file-history handler",{path:h.fileHistory.path}),f=await(0,c.handleFileHistory)({path:h.fileHistory.path,limit:h.fileHistory.limit,showDiff:h.fileHistory.showDiff,showTraceability:h.fileHistory.showTraceability,branch:h.fileHistory.branch,since:h.fileHistory.since},r,n,p,s)
|
|
380
380
|
break
|
|
381
|
-
case"request-file-history":p.info("Routing to request-file-history handler",{requestId:h.requestHistory.requestId}),
|
|
381
|
+
case"request-file-history":p.info("Routing to request-file-history handler",{requestId:h.requestHistory.requestId}),f=await(0,l.handleRequestFileHistory)({requestId:h.requestHistory.requestId,showDiff:h.requestHistory.showDiff,detailLevel:h.requestHistory.detailLevel,taskId:h.requestHistory.taskId,fileFilter:h.requestHistory.fileFilter},r,n,p,s)
|
|
382
382
|
break
|
|
383
383
|
case"recover":p.info("Routing to file-recover handler",{path:h.recover.path,commitHash:h.recover.commitHash})
|
|
384
384
|
let i=h.recover.commitHash
|
|
385
385
|
if(!i){const e=h.recover.path,n=r.workspaceManager?.getCurrentContext(r.currentSessionId)?.basePath||r.basePath||process.cwd(),{resolve:o}=await Promise.resolve().then(t.t.bind(t,6928,23)),s=o(n,e)
|
|
386
386
|
try{const{execSync:r}=await Promise.resolve().then(t.t.bind(t,5317,23)),o=r(`git log --format=%H -n 2 -- "${s}"`,{cwd:n,encoding:"utf8"}).trim().split("\n").filter(Boolean)
|
|
387
387
|
if(i=o[1]||o[0],!i)return{content:[{type:"text",text:"No previous versions found for "+e}],isError:!0}
|
|
388
|
-
p.info("Auto-resolved previous version",{filePath:e,commitHash:i})}catch{return{content:[{type:"text",text:"Could not find previous versions of "+e}],isError:!0}}}
|
|
388
|
+
p.info("Auto-resolved previous version",{filePath:e,commitHash:i})}catch{return{content:[{type:"text",text:"Could not find previous versions of "+e}],isError:!0}}}f=await(0,d.handleFileRecover)({taskId:e.recover?.taskId||await(async()=>{const{resolveActiveTaskId:e}=await Promise.resolve().then(t.bind(t,3451))
|
|
389
389
|
return await e(r,n,o)||"untracked"})(),path:h.recover.path,commitHash:i,createBackup:h.recover.createBackup},r,n,n.getToolRecordClient(),p,s,g)
|
|
390
390
|
break
|
|
391
|
-
case"blame":p.info("Routing to file-blame handler",{path:h.blame.path,lines:h.blame.lines}),
|
|
391
|
+
case"blame":p.info("Routing to file-blame handler",{path:h.blame.path,lines:h.blame.lines}),f=await(0,u.handleFileBlame)({path:h.blame.path,lines:h.blame.lines,branch:h.blame.branch},r,n,p,s)
|
|
392
392
|
break
|
|
393
|
-
default:throw Error("Unknown query type: "+
|
|
393
|
+
default:throw Error("Unknown query type: "+m)}return p.info("query_history request completed",{queryType:m,success:!f.isError}),s.incrementCounter("query_history_total",1,{success:!f.isError,queryType:m}),f}catch(e){return p.error("query_history request failed",{error:e instanceof Error?e.stack:e+""}),s.incrementCounter("query_history_errors",1),{content:[{type:"text",text:"\u274c **Query History Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
|
|
394
394
|
const i=t(6183),a=s(t(5967)),c=t(8828),l=t(8317),d=t(4640),u=t(4811),h=t(8824)},1038(e,exports){"use strict"
|
|
395
395
|
function t(e){let t
|
|
396
396
|
if("string"==typeof e.metadata&&e.metadata)try{t=JSON.parse(e.metadata)}catch(e){t=void 0}else e.metadata&&"object"==typeof e.metadata&&(t=e.metadata)
|
|
@@ -448,7 +448,7 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
448
448
|
var t={}
|
|
449
449
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
450
450
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
451
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerApiRoutes=async function(e,r,n,o){const s=n.child({component:"api"}),i=r.getTokenManager(),T=process.env.REMOTE_SERVER_URL||"https://api.alchemylabcode.com",P=new
|
|
451
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerApiRoutes=async function(e,r,n,o){const s=n.child({component:"api"}),i=r.getTokenManager(),T=process.env.REMOTE_SERVER_URL||"https://api.alchemylabcode.com",P=new f.AuthenticationManager(i,n.child({component:"auth-manager"})),j=P.getTokenSynchronizer(),x=await P.getTokenString()||void 0
|
|
452
452
|
n.debug("Token retrieved from authentication manager")
|
|
453
453
|
const R=new k.ConnectionStatusManager(T,n.child({component:"connection-status-manager"}),o,{checkIntervalMs:3e4,timeoutMs:5e3}),M=new w.ProjectClient(T,n.child({component:"project-client"}),o,R,x)
|
|
454
454
|
j.registerClient(M)
|
|
@@ -499,7 +499,7 @@ return r({endpoint:"files/content",method:"GET",success:!0,encoding:"binary"}),t
|
|
|
499
499
|
r({endpoint:"files/content",method:"GET",success:!0,encoding:o}),t.json({success:!0,data:{path:e.relativePath,content:s,size:n.size,modified:n.mtime}})}catch(t){throw"ENOENT"===t.code?(r({endpoint:"files/content",method:"GET",success:!1,error:"not_found"}),(0,u.createNotFoundError)("File not found: "+e.relativePath)):t}}catch(e){r(e)}})),e.post("/api/files/write",U,G,(async(e,t,s)=>{try{o.incrementCounter("api_requests_total",1,{endpoint:"files/write",method:"POST"})
|
|
500
500
|
const s=B("api_request_duration"),{content:i,taskId:a,format:c="text"}=e.body
|
|
501
501
|
if(void 0===i)throw(0,u.createValidationError)("Content parameter is required")
|
|
502
|
-
const l=await(0,
|
|
502
|
+
const l=await(0,m.handleWriteFile)({taskId:a,path:e.relativePath,content:i,format:c},r.getContext(),$,O,N,A,n,o)
|
|
503
503
|
s({endpoint:"files/write",method:"POST",success:!0}),t.json({success:!0,data:l})}catch(e){s(e)}})),e.post("/api/files/replace",U,G,(async(e,t,s)=>{try{o.incrementCounter("api_requests_total",1,{endpoint:"files/replace",method:"POST"})
|
|
504
504
|
const s=B("api_request_duration"),{replacements:i,mode:a="unique",taskId:c}=e.body
|
|
505
505
|
if(!i||!Array.isArray(i))throw(0,u.createValidationError)("Replacements array is required")
|
|
@@ -540,7 +540,7 @@ throw e}}catch(e){r(e)}})),e.patch("/api/proxy/*",G,(async(e,t,r)=>{try{const r=
|
|
|
540
540
|
try{const n=await L.proxyPatch(r,e.body)
|
|
541
541
|
t.json(n)}catch(e){if(e instanceof Error&&e.message.includes("ECONNREFUSED"))return t.status(503).json({success:!1,error:"Remote server is unreachable",remotePath:r})
|
|
542
542
|
throw e}}catch(e){r(e)}}))}
|
|
543
|
-
const a=i(t(7252)),c=i(t(6928)),l=i(t(1943)),d=t(3444),u=t(9860),h=t(6776),g=t(6476),p=t(3306),
|
|
543
|
+
const a=i(t(7252)),c=i(t(6928)),l=i(t(1943)),d=t(3444),u=t(9860),h=t(6776),g=t(6476),p=t(3306),m=t(4079),f=t(3895),y=s(t(5967)),w=t(4710),k=t(5681),I=t(8824),b=t(2968),v=t(6153),C=t(1887),_=t(1666),E=t(9884),q=t(922),S=t(3328)},1253(e,exports,t){"use strict"
|
|
544
544
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
545
545
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.TokenManager=void 0
|
|
546
546
|
const n=r(t(6928)),o=r(t(1943)),s=r(t(6982)),i=r(t(857)),a=t(9067),c=t(8824),l="alchemy-lab"
|
|
@@ -604,9 +604,9 @@ this.logger.debug("Making token validation request",{validationUrl:t})
|
|
|
604
604
|
const r=await fetch(t,{method:"GET",headers:{Authorization:"Bearer "+e.token,"Content-Type":"application/json"},signal:AbortSignal.timeout(1e4)})
|
|
605
605
|
if(r.ok){const e=await r.json()
|
|
606
606
|
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){"use strict"
|
|
607
|
-
async function r(e,t,o,s,i,a,c,l,d,u=0){let p=0,
|
|
607
|
+
async function r(e,t,o,s,i,a,c,l,d,u=0){let p=0,m=0,f=0
|
|
608
608
|
const y=[]
|
|
609
|
-
if(o.length>=b||c>10)return a.debug("Stopping search in directory - hard cap or depth limit reached",{dir:e,matchesCount:o.length,hardCap:b,depth:c}),{filesCount:p,fileMatchesCount:
|
|
609
|
+
if(o.length>=b||c>10)return a.debug("Stopping search in directory - hard cap or depth limit reached",{dir:e,matchesCount:o.length,hardCap:b,depth:c}),{filesCount:p,fileMatchesCount:m,subdirCount:f,subdirStats:y}
|
|
610
610
|
try{const w=await g.default.readdir(e,{withFileTypes:!0}),v=[],C=[]
|
|
611
611
|
for(const t of w){const r=h.default.join(e,t.name)
|
|
612
612
|
if(t.isDirectory()){if(I.includes(t.name)||t.name.startsWith(".")){a.debug("Skipping excluded directory: "+t.name)
|
|
@@ -615,15 +615,15 @@ continue}v.push({entry:t,fullPath:r})}}if(v.length>0){const e=[]
|
|
|
615
615
|
for(let t=0;t<v.length;t+=16)e.push(v.slice(t,t+16))
|
|
616
616
|
for(const r of e){if(o.length>=b)break
|
|
617
617
|
const e=await Promise.all(r.map((({entry:e,fullPath:r})=>n(r,t,0,o,l,d,e.name,u))))
|
|
618
|
-
for(const t of e){p++,t.hasMatches&&
|
|
619
|
-
for(const e of t.matches){if(o.length>=b)return{filesCount:p,fileMatchesCount:
|
|
618
|
+
for(const t of e){p++,t.hasMatches&&m++
|
|
619
|
+
for(const e of t.matches){if(o.length>=b)return{filesCount:p,fileMatchesCount:m,subdirCount:f,subdirStats:y}
|
|
620
620
|
o.push(e)}}}}for(const{entry:e,fullPath:n}of C){if(o.length>=b)break
|
|
621
|
-
|
|
621
|
+
f++
|
|
622
622
|
const e={path:n,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
|
|
623
623
|
try{const l=await r(n,t,o,s,i,a,c+1,e,d,u)
|
|
624
|
-
p+=l.filesCount,
|
|
624
|
+
p+=l.filesCount,m+=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)}`
|
|
625
625
|
e.errors.push(r),y.push(e),a.error(r)}}}catch(t){const r=`Error searching directory ${e}: ${(0,k.getErrorMessage)(t)}`
|
|
626
|
-
l.errors.push(r),a.warn(r)}return{filesCount:p,fileMatchesCount:
|
|
626
|
+
l.errors.push(r),a.warn(r)}return{filesCount:p,fileMatchesCount:m,subdirCount:f,subdirStats:y}}async function n(e,t,r,n,o,s,i,a=0){const c=[]
|
|
627
627
|
let l,d=!1
|
|
628
628
|
const u=async()=>{if(void 0===l)try{const t=await g.default.stat(e)
|
|
629
629
|
l=t.mtime.getTime()}catch(e){l=void 0}return l}
|
|
@@ -659,21 +659,21 @@ let I=0
|
|
|
659
659
|
const b={searchDirectory:"",resolvedPath:"",patternInfo:{needle:"",regex:"",caseSensitive:!1,fileExtension:"",normalizedExtension:""},environmentInfo:{platform:process.platform,nodeVersion:process.version,hostname:p.default.hostname(),username:p.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:[]}
|
|
660
660
|
try{const{needle:n,directory:p,options:v={}}=e
|
|
661
661
|
if(!n||""===n.trim())return l.info("Empty needle detected, switching to list-all mode"),await(0,w.handleListDirectory)({path:p||".",levels:v.levels||1,sortBy:v.sortBy||"name"},t,a,c)
|
|
662
|
-
if("string"!=typeof n)throw b.errors.push("Search term (needle) must be a string"),(0,
|
|
662
|
+
if("string"!=typeof n)throw b.errors.push("Search term (needle) must be a string"),(0,m.createValidationError)("Search term (needle) must be a string")
|
|
663
663
|
let C
|
|
664
|
-
if(b.searchDirectory=p||".",p){const{normalizedPath:e,fullPath:r}=
|
|
664
|
+
if(b.searchDirectory=p||".",p){const{normalizedPath:e,fullPath:r}=f.validateAndNormalizePath(p,t)
|
|
665
665
|
C=r}else C=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
|
|
666
666
|
b.resolvedPath=C
|
|
667
667
|
let _=!1
|
|
668
668
|
try{_=(await g.default.stat(C)).isFile()}catch(e){const t=`Cannot access path ${C}: ${(0,k.getErrorMessage)(e)}`
|
|
669
669
|
throw b.errors.push(t),Error(t)}const E=v.maxResults||50,q=v.caseSensitive||!1,S=v.useRegex||!1,T=v.fileExtension,P=v.searchIn||"content"
|
|
670
670
|
let j=void 0!==v.contextLines?v.contextLines:0
|
|
671
|
-
if(0>j?j=0:j>10&&(l.warn(`contextLines ${j} exceeds maximum of 10, clamping to 10`),j=10),!_&&!T)throw b.errors.push('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")'),(0,
|
|
671
|
+
if(0>j?j=0:j>10&&(l.warn(`contextLines ${j} exceeds maximum of 10, clamping to 10`),j=10),!_&&!T)throw b.errors.push('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")'),(0,m.createValidationError)('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")')
|
|
672
672
|
let x,R=""
|
|
673
673
|
if(_)R="*"
|
|
674
674
|
else if("*"===T)R="*"
|
|
675
675
|
else if(T){let e=T;(e.startsWith("*.")||e.startsWith("*"))&&(e=e.substring(1)),R=e.startsWith(".")?e:"."+e}try{x=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)}`
|
|
676
|
-
throw b.errors.push(t),(0,
|
|
676
|
+
throw b.errors.push(t),(0,m.createValidationError)(t)}if(b.patternInfo={needle:n,regex:x.toString(),caseSensitive:q,fileExtension:T,normalizedExtension:R},!_)try{const e=Date.now(),t=await g.default.readdir(C,{withFileTypes:!0}),r=[],n=[]
|
|
677
677
|
for(const e of t)e.isDirectory()?r.push(e.name):e.isFile()&&n.push(e.name)
|
|
678
678
|
b.initialScan={totalEntries:t.length,directories:r,files:n,firstFewFiles:n.slice(0,10),scanTime:Date.now()-e},b.phases.directoryListingTime=b.initialScan.scanTime}catch(e){const t="Failed to scan directory contents: "+(0,k.getErrorMessage)(e)
|
|
679
679
|
b.errors.push(t),l.error(t)}const M=_?"file":"directory"
|
|
@@ -692,10 +692,10 @@ t.contextBefore=r.slice(e,n).map((e=>(0,y.truncate)(e.trim(),120)))
|
|
|
692
692
|
const o=Math.min(r.length,n+1+s)
|
|
693
693
|
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)}`
|
|
694
694
|
o.errors.push(r),n.error(r)}return{matches:i,totalFiles:1}}(e,t,l,s,i,u)
|
|
695
|
-
const
|
|
696
|
-
try{const{filesCount:n,fileMatchesCount:c,subdirCount:d,subdirStats:h}=await r(e,t,p,a,o,s,0,
|
|
697
|
-
return
|
|
698
|
-
return
|
|
695
|
+
const m={path:e,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
|
|
696
|
+
try{const{filesCount:n,fileMatchesCount:c,subdirCount:d,subdirStats:h}=await r(e,t,p,a,o,s,0,m,l,u)
|
|
697
|
+
return m.filesProcessed=n,m.filesMatched=c,m.subdirectories=d,i.directoryStats.push(m),h&&h.length>0&&i.directoryStats.push(...h),s.info("performLocalSearch completed",{totalFiles:n,matchesFound:p.length,directories:d+1}),{matches:p,totalFiles:n}}catch(t){const r="Error in performLocalSearch: "+(0,k.getErrorMessage)(t)
|
|
698
|
+
return m.errors.push(r),i.directoryStats.push(m),i.errors.push(r),s.error(r,{error:t instanceof Error?t.stack:t+"",searchPath:e}),{matches:p,totalFiles:m.filesProcessed}}}(C,x,{maxResults:E,fileExtension:R,searchIn:P,isFile:_,contextLines:j},R,l,b)
|
|
699
699
|
$=e.matches,D=e.totalFiles
|
|
700
700
|
const t=1e3
|
|
701
701
|
$.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)
|
|
@@ -729,7 +729,7 @@ else F+="No matches found."
|
|
|
729
729
|
return d({success:!0}),{content:[{type:"text",text:F}]}}catch(t){l.error("Search failed",{args:e,error:t instanceof Error?t.stack:t+""}),b.errors.push((0,k.getErrorMessage)(t)),b.endTime=Date.now(),l.debug("Search diagnostic information on error",{diagnostic:b})
|
|
730
730
|
let r="Search failed: "+(0,k.getErrorMessage)(t)
|
|
731
731
|
return d({success:!1,error:t instanceof Error?t.name:"unknown"}),{content:[{type:"text",text:r}],isError:!0}}}
|
|
732
|
-
const h=u(t(6928)),g=u(t(1943)),p=u(t(857)),
|
|
732
|
+
const h=u(t(6928)),g=u(t(1943)),p=u(t(857)),m=t(9860),f=d(t(5967)),y=t(5967),w=t(2537),k=t(8824),I=["node_modules"],b=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){"use strict"
|
|
733
733
|
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)
|
|
734
734
|
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}`])
|
|
735
735
|
if(!a||""===a.trim())return null
|
|
@@ -747,12 +747,12 @@ for(const e of r){const r=e.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/)
|
|
|
747
747
|
if(r){const e=parseInt(r[3],10),n=r[4]?parseInt(r[4],10):1,o=e+n-1
|
|
748
748
|
n>0&&t.push({start:e,end:o})}}return t}(s)
|
|
749
749
|
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})
|
|
750
|
-
return s.latest?.message||null}catch(e){return null}}(e,t.path,i),g=!!h&&n(h),p=t.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),
|
|
750
|
+
return s.latest?.message||null}catch(e){return null}}(e,t.path,i),g=!!h&&n(h),p=t.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),m=d.map((e=>`${e.start}-${e.end}`)).join(", ")||"none",f=u?u.substring(0,300):"no diff"
|
|
751
751
|
if(0===d.length){const r=[]
|
|
752
752
|
for(const s of t.lineRanges){const a=await o(e,t.path,s.start,s.end,i)
|
|
753
753
|
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 ${p} 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")
|
|
754
754
|
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:p,uncommittedChanges:"none",lastCommit:r[0].commit.message,wasLastCommitAlchemy:!1,diffPreview:e,overlapDetected:!0}}}return{hasExternalEdits:!1,conflictingLines:[],debugInfo:{detectionRan:!0,affectedRegion:p,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)
|
|
755
|
-
return 0===w.length?{hasExternalEdits:!1,conflictingLines:[],message:"File has uncommitted changes, but they do not conflict with this operation.",debugInfo:{detectionRan:!0,affectedRegion:p,uncommittedChanges:
|
|
755
|
+
return 0===w.length?{hasExternalEdits:!1,conflictingLines:[],message:"File has uncommitted changes, but they do not conflict with this operation.",debugInfo:{detectionRan:!0,affectedRegion:p,uncommittedChanges:m,lastCommit:h,wasLastCommitAlchemy:g,diffPreview:f,overlapDetected:!1}}:{hasExternalEdits:!0,conflictingLines:w,message:["\u26a0\ufe0f Warning: File has uncommitted changes in lines you're about to modify.\n","Affected lines: "+p,"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:p,uncommittedChanges:m,lastCommit:h,wasLastCommitAlchemy:g,diffPreview:f,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}}
|
|
756
756
|
const a=t(9947),c=i(t(6928)),l=t(8824)},1387(e,exports,t){"use strict"
|
|
757
757
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.WorkspaceRequestProcessor=void 0
|
|
758
758
|
const r=t(7075),n=t(5964),o=t(8824)
|
|
@@ -802,41 +802,44 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
|
|
|
802
802
|
var t={}
|
|
803
803
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
804
804
|
return s(t,e),t})
|
|
805
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=void 0,exports.registerTools=function(e,
|
|
806
|
-
|
|
807
|
-
const
|
|
808
|
-
try{return await
|
|
809
|
-
|
|
805
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=void 0,exports.registerTools=function(e,n,o,s,i,g,f){const y=s.child({component:"tools"})
|
|
806
|
+
y.info("Registering tools...")
|
|
807
|
+
const w=!!g,k=async()=>{if(!w)return!0
|
|
808
|
+
try{return await g.hasValidToken()}catch(e){return y.error("Error checking authentication status",{error:(0,l.getErrorMessage)(e)}),!1}},I=async()=>{const e=(0,c.areTestsRequiredForCompletion)(),t=await k()
|
|
809
|
+
y.info(`Generating tools list with testsRequired=${e}, authenticated=${t}`)
|
|
810
810
|
const r={testsRequired:e,authenticated:t}
|
|
811
|
-
return(0,
|
|
812
|
-
let I
|
|
813
|
-
|
|
814
|
-
let
|
|
815
|
-
e.setRequestHandler(a.CallToolRequestSchema,(async e=>{try{const{name:
|
|
816
|
-
const
|
|
811
|
+
return(0,m.generateVisibleToolsList)(r)}
|
|
812
|
+
let b=I(),v=[]
|
|
813
|
+
b.then((e=>{v=e})).catch((e=>{y.error("Error generating initial tools list",{error:(0,l.getErrorMessage)(e)}),v=[]})),e.setRequestHandler(a.ListToolsRequestSchema,(async()=>{try{return v=await I(),{tools:v}}catch(e){return y.error("Error generating tools list",{error:(0,l.getErrorMessage)(e)}),{tools:[]}}}))
|
|
814
|
+
let C=!1
|
|
815
|
+
e.setRequestHandler(a.CallToolRequestSchema,(async e=>{try{const{name:a,arguments:c={},_meta:g}=e.params;(0,p.logSessionIdentity)(a,"_meta-debug",{has_meta:!!g,sessionId:g?.sessionId||null,messageId:g?.messageId||null,paramKeys:Object.keys(e.params)}),y.info("Tool call received: "+a,{tool:a}),i.incrementCounter("tool_calls_total",1,{tool:a})
|
|
816
|
+
const I=i.startTimer("tool_execution_time")
|
|
817
817
|
Date.now()
|
|
818
|
-
let
|
|
819
|
-
const
|
|
820
|
-
if(Date.now(),
|
|
821
|
-
if(Date.now(),!e)return
|
|
822
|
-
let
|
|
823
|
-
if(
|
|
824
|
-
if(
|
|
825
|
-
else{const
|
|
826
|
-
u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:
|
|
827
|
-
u.sessionIdentity.setCurrentCallOrigin(
|
|
828
|
-
const E
|
|
829
|
-
if(
|
|
830
|
-
try{const e=await(0,d.getServerUrl)(
|
|
831
|
-
e&&
|
|
832
|
-
if(e?.sessionId&&t){const r=t.match(/^requests\/(.+)$/),
|
|
833
|
-
if(r&&!
|
|
834
|
-
|
|
835
|
-
try{const{sessionTag:r}=(0,h.getGlobalClientInfo)(),o
|
|
836
|
-
await Promise.all([i,a])}catch(e){
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
818
|
+
let b=Date.now()
|
|
819
|
+
const v=r(c)
|
|
820
|
+
if(Date.now(),b=Date.now(),w){const e=await k()
|
|
821
|
+
if(Date.now(),!e)return y.warn("Unauthenticated tool call attempt",{tool:a}),{content:[{type:"text",text:"Authentication required. Please run 'alchemylab setup' to authenticate and configure your project."}],isError:!0}}const _=(0,m.getToolByName)(a)
|
|
822
|
+
let E
|
|
823
|
+
if(b=Date.now(),o?(o.setOptions({createRecords:_?.createsRecords??!1}),y.info(`Setting record creation for tool ${a}: ${_?.createsRecords??!1}`)):y.debug(`No API client available for tool ${a} (minimal mode)`),Date.now(),Date.now(),b=Date.now(),g?.sessionId){const e=g.sessionId,t=g.messageId,r=u.sessionIdentity.getIdentity()
|
|
824
|
+
if(r)r.sessionId!==e&&((0,p.logSessionIdentity)(a,"_meta-session-switch",{prevSessionId:r.sessionId,prevAgentType:r.agentType,newSessionId:e}),u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:r.serverUrl}),n?.workspaceManager?.resetCurrentContext?.(e))
|
|
825
|
+
else{const t=await(0,d.getServerUrl)(n,y)
|
|
826
|
+
u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:t||""})}E={providerId:"opencode",sessionId:e,messageId:t,createdAt:(new Date).toISOString()},(0,p.logSessionIdentity)(a,"_meta",{sessionId:e,messageId:t})}else y.warn("No _meta.sessionId on tool call \u2014 session identity unavailable",{tool:a})
|
|
827
|
+
u.sessionIdentity.setCurrentCallOrigin(E)
|
|
828
|
+
const q=E?.sessionId||g?.sessionId
|
|
829
|
+
if(n?.workspaceManager){b=Date.now()
|
|
830
|
+
try{const e=await(0,d.getServerUrl)(n,y)
|
|
831
|
+
e&&o&&await n.workspaceManager.ensureReadonlyBranchIfNeeded(e,a,o,q)}catch(e){y.debug("Error during workspace check",{error:(0,l.getErrorMessage)(e)})}Date.now()}if(!C&&o){const e=u.sessionIdentity.getIdentity(),t=process.env.ALCHEMY_INITIAL_BRANCH
|
|
832
|
+
if(e?.sessionId&&t){const r=t.match(/^requests\/(.+)$/),n="1"===process.env.ALCHEMY_ALLOW_PARALLEL
|
|
833
|
+
if(r&&!n){const t=r[1]
|
|
834
|
+
C=!0
|
|
835
|
+
try{const{sessionTag:r}=(0,h.getGlobalClientInfo)(),n=o.getSessionTagMappingClient(),s=o.getRequestClient(),i=n?n.getMappingByOpencodeSessionId(e.sessionId).then((t=>{t?((0,h.setSessionTag)(t.sessionTag),y.info("Recovered session tag from mapping",{opencodeSessionId:e.sessionId,sessionTag:t.sessionTag})):(n.createOrUpdateMapping(r,e.sessionId).catch((()=>{})),y.info("Registered session tag mapping",{opencodeSessionId:e.sessionId,sessionTag:r}))}),(e=>y.debug("Mapping lookup failed",{error:(0,l.getErrorMessage)(e)}))):Promise.resolve(),a=s.lockRequest?s.lockRequest(t,r).then((e=>{e.locked?y.info("Acquired request lock",{requestId:t,sessionTag:r}):y.warn("Failed to acquire request lock",{requestId:t,sessionTag:r})}),(e=>y.warn("Lock acquisition failed",{error:(0,l.getErrorMessage)(e)}))):Promise.resolve()
|
|
836
|
+
await Promise.all([i,a])}catch(e){y.warn("Error in session tag mapping / lock acquisition",{error:(0,l.getErrorMessage)(e)})}}}}n&&(n.currentSessionId=q||"__unknown__")
|
|
837
|
+
const S=`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,T=e=>{const{getActionServerBaseUrl:r}=t(9414)
|
|
838
|
+
fetch(r()+"/api/mcp/tool-call-event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,callId:S}),signal:AbortSignal.timeout(500)}).catch((()=>{}))}
|
|
839
|
+
let P
|
|
840
|
+
T("start")
|
|
841
|
+
try{if(_){const e={context:n,apiClient:o,logger:s,metrics:i,mcpServer:f,cliOrigin:E}
|
|
842
|
+
P=await _.handler(v,e)}else y.info(`Tool ${a} not found, returning negative response`),P={content:[{type:"text",text:`The tool '${a}' does not exist.`}]}}finally{T("end")}return Date.now(),Date.now(),I({tool:a,success:!0}),P}catch(t){y.error("Error executing tool:",{error:t instanceof Error?t.stack:t+"",tool:e.params.name}),i.incrementCounter("tool_errors_total",1,{tool:e.params.name,error:t instanceof Error?t.name:"unknown"})
|
|
840
843
|
let r="Unknown error"
|
|
841
844
|
if(t instanceof Error)r=t.message
|
|
842
845
|
else if("string"==typeof t)r=t
|
|
@@ -849,23 +852,23 @@ else if(e.body&&"string"==typeof e.body)try{const t=JSON.parse(e.body)
|
|
|
849
852
|
r=t.error&&t.error.message?t.error.message:t.message?t.message:e.body.substring(0,200)}catch{r=e.body.substring(0,200)}else{const t=Object.keys(e).filter((t=>"string"==typeof e[t]&&e[t].length>0))
|
|
850
853
|
if(t.length>0){const n=t[0]
|
|
851
854
|
r=`${n}: ${e[n]}`}else r="Unknown error (no readable properties)"}}else r=t+""
|
|
852
|
-
return{content:[{type:"text",text:"Error: "+r}],isError:!0}}})),
|
|
855
|
+
return{content:[{type:"text",text:"Error: "+r}],isError:!0}}})),y.info("Tools registration complete")}
|
|
853
856
|
const a=t(9150),c=t(2478),l=t(8824),d=t(7617),u=t(6688),h=t(5172)
|
|
854
857
|
i(t(9896)),i(t(6928))
|
|
855
858
|
var g=t(7280)
|
|
856
859
|
Object.defineProperty(exports,"logSessionIdentity",{enumerable:!0,get(){return g.logSessionIdentity}})
|
|
857
860
|
const p=t(7280)
|
|
858
861
|
t(2462)
|
|
859
|
-
const
|
|
862
|
+
const m=t(2245)
|
|
860
863
|
i(t(857))},1483(e,exports,t){"use strict"
|
|
861
864
|
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")
|
|
862
865
|
try{let i
|
|
863
866
|
try{i=r.SearchDocumentsSchema.parse(e)}catch(t){if(t instanceof n.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
864
|
-
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:p,searchIn:
|
|
865
|
-
c.info("Searching documents",{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,searchIn:
|
|
866
|
-
const
|
|
867
|
-
if(!
|
|
868
|
-
return c.warn("No project context"),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}s.setProjectId(
|
|
867
|
+
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:p,searchIn:m}=i
|
|
868
|
+
c.info("Searching documents",{query:a,type:l,requestId:d,includeArchived:u,maxResults:h,searchIn:m})
|
|
869
|
+
const f=t.projectId
|
|
870
|
+
if(!f){const e="Project ID is required. Make sure you are in a project context."
|
|
871
|
+
return c.warn("No project context"),{content:[{type:"text",text:"\u274c "+e}],isError:!0}}s.setProjectId(f)
|
|
869
872
|
const y=s.getDocumentClient()
|
|
870
873
|
try{const e={limit:h||100,offset:0,sortBy:"updatedAt",sortDirection:"desc",searchQuery:a,includeArchived:u||!1}
|
|
871
874
|
l&&(e.type=l),d&&(e.requestId=d),c.debug("Fetching documents with filters",{filters:e})
|
|
@@ -875,7 +878,7 @@ t=t.filter((t=>new Date(t.createdAt)>=e))}if(p){const e=new Date(p)
|
|
|
875
878
|
t=t.filter((t=>new Date(t.createdAt)<=e))}c.info(`Fetched and filtered ${t.length} documents for search`)
|
|
876
879
|
const r=[],n=a.toLowerCase()
|
|
877
880
|
for(const e of t){let t,o=null
|
|
878
|
-
if("filename"!==
|
|
881
|
+
if("filename"!==m&&"both"!==m||!e.filename.toLowerCase().includes(n)||(o="filename",t=e.filename),("content"===m||"both"===m)&&e.content&&e.content.toLowerCase().includes(n)){o="content"
|
|
879
882
|
const r=e.content.split("\n")
|
|
880
883
|
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)
|
|
881
884
|
t=r.slice(n,o+1).map(((t,r)=>n+r===e?"> "+t.trim():" "+t.trim())).join("\n")
|
|
@@ -1205,13 +1208,13 @@ r(t,"serverUrl resolved",{serverUrl:h})
|
|
|
1205
1208
|
const g=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
|
|
1206
1209
|
if(!g)throw new y.ValidationError("Working directory not available in context")
|
|
1207
1210
|
const p=s?.sessionId
|
|
1208
|
-
let
|
|
1211
|
+
let m=""
|
|
1209
1212
|
if(o&&c)try{const e=o.getSessionRequestAssociationClient()
|
|
1210
1213
|
if(e){const t=await e.getSessionsForRequest(c,!0),r=p?t.filter((e=>e.opencodeSessionId!==p)):t
|
|
1211
1214
|
if(r.length>0){const e=r.map((e=>e.opencodeSessionId)).join(", ")
|
|
1212
1215
|
if(!l)return n.warn("Blocked spawn: request already has active workers",{requestId:c,existingWorkerCount:r.length,existingSessionIds:r.map((e=>e.opencodeSessionId))}),{content:[{type:"text",text:`\u274c Cannot spawn: Request ${c} already has ${r.length} active worker(s): ${e}\n\nOptions:\n\u2022 Use \`useExistingSession: "${r[0].opencodeSessionId}"\` to send work to the existing session\n\u2022 Use \`allowParallel: true\` if you really need multiple workers on the same request`}],isError:!0}
|
|
1213
|
-
|
|
1214
|
-
c&&(
|
|
1216
|
+
m=`\u26a0\ufe0f Warning: Request ${c} already has ${r.length} active worker(s): ${e}. Proceeding anyway (allowParallel=true).\n\n`,n.warn("Spawning parallel subagent for request with existing active workers",{requestId:c,existingWorkerCount:r.length,existingSessionIds:r.map((e=>e.opencodeSessionId)),allowParallel:!0})}}}catch(e){n.debug("Failed to check for existing workers",{error:(0,_.getErrorMessage)(e)})}let f,v,C=a
|
|
1217
|
+
c&&(f="requests/"+c,r(t,"Setting initialBranch for agent",{agent:i,requestId:c,initialBranch:f,agentRequestContextMode:u||"undefined"}),C="readonly"===u?`Working on request ${c} (READONLY mode - you cannot modify files, only explore and report).\n\n${a}`:`Working on request ${c}.\n\n${a}`)
|
|
1215
1218
|
let E=!1
|
|
1216
1219
|
if(d){if(v=d,n.info("Using existing session for spawn",{sessionId:v,requestId:c}),!h)throw new y.ValidationError("Could not determine OpenCode server URL")
|
|
1217
1220
|
try{let e
|
|
@@ -1226,11 +1229,11 @@ try{const s=`http://localhost:${T}/api/spawn-session`,d=await fetch(s,{method:"P
|
|
|
1226
1229
|
if(!d.ok){const e=await d.text().catch((()=>"Unknown error"))
|
|
1227
1230
|
throw Error(`Spawn session endpoint failed: ${d.status} ${e}`)}const u=await d.json()
|
|
1228
1231
|
if(!u.success||!u.data)throw Error(u.error||"Spawn session returned unsuccessful")
|
|
1229
|
-
const{sessionId:h,model:p,serverUrl:
|
|
1230
|
-
|
|
1231
|
-
const k=(0,w.spawnDetachedSubagent)({agent:i,prompt:C,cwd:g,sessionId:h,model:p,initialBranch:
|
|
1232
|
+
const{sessionId:h,model:p,serverUrl:m,initialBranch:y}=u.data
|
|
1233
|
+
f=y
|
|
1234
|
+
const k=(0,w.spawnDetachedSubagent)({agent:i,prompt:C,cwd:g,sessionId:h,model:p,initialBranch:f,allowParallel:l,serverUrl:m})
|
|
1232
1235
|
if(!k.success)throw Error("Failed to spawn subagent: "+k.error)
|
|
1233
|
-
v=h,r(t,"Spawn successful via unified endpoint",{sessionId:h,pid:k.pid,parentSessionId:o,model:p}),n.info("Background subagent spawned via unified endpoint",{agent:i,requestId:c,sessionId:h,pid:k.pid,parentSessionId:o})}catch(e){throw Error("Failed to spawn subagent: "+(0,_.getErrorMessage)(e))}}let q=
|
|
1236
|
+
v=h,r(t,"Spawn successful via unified endpoint",{sessionId:h,pid:k.pid,parentSessionId:o,model:p}),n.info("Background subagent spawned via unified endpoint",{agent:i,requestId:c,sessionId:h,pid:k.pid,parentSessionId:o})}catch(e){throw Error("Failed to spawn subagent: "+(0,_.getErrorMessage)(e))}}let q=m
|
|
1234
1237
|
return d?q+=`Prompt sent to existing session ${v}.`:(q+=`Background ${i} subagent spawned successfully.`,v&&"unknown"!==v&&"spawning"!==v&&(q+=`\n[SESSION:${v}]`)),c&&(q+="\nWorking on: "+c),q+="\n\nThe subagent is now working independently. You can continue with other tasks.","coder"===i&&(q+="\n\nIf this work has shifted or expanded your area of expertise, update your specialization summary with `update_specialization`."),{content:[{type:"text",text:q}]}}async function o(e,t,r,n,o,s,i){const a=await(0,k.getServerUrl)(r,n)
|
|
1235
1238
|
if(!a)throw new y.ValidationError("Could not determine OpenCode server URL")
|
|
1236
1239
|
if(n.info("Sending message to subagent session",{sessionId:e,promptLength:t.length}),o)try{const t=i?.sessionId
|
|
@@ -1265,11 +1268,11 @@ n.info("Checking status of subagent session",{sessionId:e})
|
|
|
1265
1268
|
try{const d=`${a.replace(/\/$/,"")}/session/${e}`,u=await fetch(d)
|
|
1266
1269
|
if(!u.ok)return{content:[{type:"text",text:`Session ${e} not found or has exited.`}],isError:!0}
|
|
1267
1270
|
const h=await u.json(),g=`${a.replace(/\/$/,"")}/session/${e}/message`,p=await fetch(g)
|
|
1268
|
-
let
|
|
1271
|
+
let m={input:0,output:0,reasoning:0},f="",y=c(null,h.time.updated)
|
|
1269
1272
|
if(p.ok){const e=await p.json()
|
|
1270
|
-
for(const t of e)"assistant"===t.info.role&&t.info.tokens&&(
|
|
1273
|
+
for(const t of e)"assistant"===t.info.role&&t.info.tokens&&(m.input+=t.info.tokens.input||0,m.output+=t.info.tokens.output||0,m.reasoning+=t.info.tokens.reasoning||0)
|
|
1271
1274
|
const t=i(e)
|
|
1272
|
-
y=c(t.lastActivityTime,h.time.updated),t.current&&(
|
|
1275
|
+
y=c(t.lastActivityTime,h.time.updated),t.current&&(f+="\nCurrent: "+t.current),t.recent.length>0&&(f+="\nRecent: "+t.recent.join(", "))}const w=Date.now()-h.time.created,k=y.status,I=y.isReady,b=m.input+m.output+m.reasoning
|
|
1273
1276
|
let v="",C="",_=null
|
|
1274
1277
|
if(o)try{const t=o.getSessionRequestAssociationClient()
|
|
1275
1278
|
if(t){const r=await t.getActiveRequestsForSession(e,!1)
|
|
@@ -1284,7 +1287,7 @@ if(e.trim())return l(e)}try{const t=n(`git log main --merges --oneline -n 50 --g
|
|
|
1284
1287
|
if(t){const e=t.split("\n")[0].split(" ")[0],o=n(`git diff ${e}^1...${e} --numstat`,{cwd:r,encoding:"utf8"})
|
|
1285
1288
|
if(o.trim())return{...l(o),merged:!0}}}catch{}return null}catch{return null}}(_,r.basePath)
|
|
1286
1289
|
if(e){const t=e.additions+e.deletions,r=e.merged?" (merged)":""
|
|
1287
|
-
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: ${I?"Yes":"No"}\nAge: ${s(w)}\nTokens: ${b.toLocaleString()} (in: ${
|
|
1290
|
+
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: ${I?"Yes":"No"}\nAge: ${s(w)}\nTokens: ${b.toLocaleString()} (in: ${m.input.toLocaleString()}, out: ${m.output.toLocaleString()}${m.reasoning>0?", reasoning: "+m.reasoning.toLocaleString():""})${f}${C}${v}`}]}}catch(e){throw Error("Failed to check session status: "+(0,_.getErrorMessage)(e))}}async function u(e,t,r){const n=await(0,k.getServerUrl)(t,r)
|
|
1288
1291
|
if(!n)throw new y.ValidationError("Could not determine OpenCode server URL")
|
|
1289
1292
|
r.info("Aborting subagent session",{sessionId:e})
|
|
1290
1293
|
try{const t=`${n.replace(/\/$/,"")}/session/${e}/abort`,o=await fetch(t,{method:"POST"})
|
|
@@ -1296,9 +1299,9 @@ try{const e=g.replace(/\/$/,"")+"/session",t=await fetch(e)
|
|
|
1296
1299
|
if(!t.ok)throw Error("Failed to fetch sessions: "+t.status)
|
|
1297
1300
|
let p=await t.json()
|
|
1298
1301
|
if(0===p.length)return{content:[{type:"text",text:"No sessions found."}]}
|
|
1299
|
-
const
|
|
1302
|
+
const m=p
|
|
1300
1303
|
n.parentSessionId&&(p=p.filter((e=>(e.parentId||e.parentID)===n.parentSessionId))),p.sort(((e,t)=>t.time.created-e.time.created))
|
|
1301
|
-
const
|
|
1304
|
+
const f=g.replace(/\/$/,"")+"/session/status",y=await fetch(f),w=y.ok?await y.json():{}
|
|
1302
1305
|
let k=p
|
|
1303
1306
|
if(o&&(k=k.filter((e=>"idle"!==(w[e.id]?.type||"idle")))),void 0!==h){const e=36e5*h,t=Date.now()-e
|
|
1304
1307
|
k=k.filter((e=>e.time.created>=t))}if(0===k.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
|
|
@@ -1306,7 +1309,7 @@ let I={}
|
|
|
1306
1309
|
const b=k.map((e=>e.id))
|
|
1307
1310
|
let v={},C=[]
|
|
1308
1311
|
if("specialist"===n.agentType){const e=new Set(b)
|
|
1309
|
-
for(const t of
|
|
1312
|
+
for(const t of m){const r=t.parentId||t.parentID
|
|
1310
1313
|
r&&e.has(r)&&(v[r]||(v[r]=[]),v[r].push(t.id),C.push(t.id))}}if(r)try{const e=r.getCLISessionClient()
|
|
1311
1314
|
if(e){const t=[...b,...C]
|
|
1312
1315
|
I=await e.batchEnrich(t)}}catch{}const _=g.replace(/\/$/,""),E=await Promise.allSettled(k.map((e=>fetch(`${_}/session/${e.id}/message`).then((e=>e.ok?e.json():[])).catch((()=>[]))))),q=[]
|
|
@@ -1315,15 +1318,15 @@ let o=0,s=null,l=[],h=c(null,t.time.updated)
|
|
|
1315
1318
|
const g=E[e],p="fulfilled"===g.status?g.value:[]
|
|
1316
1319
|
for(const e of p)"assistant"===e.info.role&&e.info.tokens&&(o+=(e.info.tokens.input||0)+(e.info.tokens.output||0)+(e.info.tokens.reasoning||0))
|
|
1317
1320
|
if(p.length>0){const e=i(p)
|
|
1318
|
-
h=c(e.lastActivityTime,t.time.updated),s=e.current||null,l=e.recent}const
|
|
1321
|
+
h=c(e.lastActivityTime,t.time.updated),s=e.current||null,l=e.recent}const m=h.status
|
|
1319
1322
|
if(void 0!==d&&d>o)continue
|
|
1320
1323
|
if(void 0!==u&&o>u)continue
|
|
1321
|
-
const
|
|
1322
|
-
if(n.agentType&&(!
|
|
1323
|
-
if("archived"===
|
|
1324
|
+
const f=I[t.id]
|
|
1325
|
+
if(n.agentType&&(!f||f.agentType!==n.agentType))continue
|
|
1326
|
+
if("archived"===f?.status)continue
|
|
1324
1327
|
let y=""
|
|
1325
1328
|
const b=[],C=[]
|
|
1326
|
-
|
|
1329
|
+
f?.associations&&C.push(...f.associations)
|
|
1327
1330
|
const _=v[t.id]
|
|
1328
1331
|
if(_)for(const e of _){const t=I[e]
|
|
1329
1332
|
if(t?.associations){const r=w[e]?.type||"idle",n="idle"===r||"stalled"===r
|
|
@@ -1335,17 +1338,17 @@ const n=[]
|
|
|
1335
1338
|
if(t.length>0&&n.push("active: "+t.join(", ")),r.length>0){const e=5,t=r.slice(0,e),o=r.length-t.length
|
|
1336
1339
|
n.push(`prev: ${t.join(", ")}${o>0?` +${o} more`:""}`)}n.length>0&&(y=` [${n.join(" | ")}]`)}if(a&&!b.includes(a))continue
|
|
1337
1340
|
const S=t.title||"Untitled",T=S.length>50?S.slice(0,47)+"...":S
|
|
1338
|
-
q.push({id:t.id,title:T,status:
|
|
1341
|
+
q.push({id:t.id,title:T,status:m,age:r,totalTokens:o,requestsInfo:y,allRequestIds:b,statusDetail:h.detail,specialization:f?.specialization??null,currentAction:s,recentActions:l})}if(0===q.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
|
|
1339
1342
|
const S=l?q.slice(0,l):q,T=S.map((e=>{const t=e.specialization?"\n Specialization: "+e.specialization:"",r=e.currentAction?"\n Current: "+e.currentAction:"",o="specialist"!==n.agentType&&e.recentActions.length>0?"\n Recent: "+e.recentActions.join(", "):""
|
|
1340
1343
|
return`\u2022 ${e.id}\n ${e.title}${t}\n Status: ${e.status} (${e.statusDetail}) | Age: ${s(e.age)} | ${e.totalTokens.toLocaleString()} tokens${e.requestsInfo}${r}${o}`})),P=l&&q.length>l?` (showing ${l} of ${q.length})`:""
|
|
1341
1344
|
return{content:[{type:"text",text:`Found ${S.length} session${1!==S.length?"s":""}${P}:\n\n${T.join("\n\n")}`}]}}catch(e){throw Error("Failed to list sessions: "+(0,_.getErrorMessage)(e))}}var g,p=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
1342
1345
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
1343
|
-
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]}),
|
|
1346
|
+
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}),f=this&&this.__importStar||(g=function(e){return g=Object.getOwnPropertyNames||function(e){var t=[]
|
|
1344
1347
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
1345
1348
|
return t},g(e)},function(e){if(e&&e.__esModule)return e
|
|
1346
1349
|
var t={}
|
|
1347
1350
|
if(null!=e)for(var r=g(e),n=0;n<r.length;n++)"default"!==r[n]&&p(t,e,r[n])
|
|
1348
|
-
return
|
|
1351
|
+
return m(t,e),t})
|
|
1349
1352
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpawn=n,exports.handleContinue=o,exports.handleCheckStatus=d,exports.handleAbort=u,exports.handleListSessions=h,exports.handleSubagentOperations=async function(e,t,r,s,i,a){const c=r.child({tool:"subagent_operations"}),l=s.startTimer("tool_execution_time")
|
|
1350
1353
|
try{if(e?.spawn&&"object"==typeof e.spawn){const t=e.spawn
|
|
1351
1354
|
e.agent=e.agent||t.agent,e.prompt=e.prompt||t.prompt,e.description=e.description||t.description,e.requestId=e.requestId||t.requestId,e.allowParallel=e.allowParallel??t.allowParallel,e.useExistingSession=e.useExistingSession||t.useExistingSession,delete e.spawn}if(e?.continue&&"object"==typeof e.continue){const t=e.continue
|
|
@@ -1353,17 +1356,17 @@ e.prompt=e.prompt||t.prompt,delete e.continue}if(e?.readMessages&&"object"==type
|
|
|
1353
1356
|
e.limit=e.limit??t.limit,delete e.readMessages}if(e?.listSessions&&"object"==typeof e.listSessions){const t=e.listSessions
|
|
1354
1357
|
e.activeOnly=e.activeOnly??t.activeOnly,e.requestId=e.requestId||t.requestId,e.limit=e.limit??t.limit,e.minTokens=e.minTokens??t.minTokens,e.maxTokens=e.maxTokens??t.maxTokens,e.maxAgeHours=e.maxAgeHours??t.maxAgeHours,delete e.listSessions}!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="spawn":e.prompt&&e.sessionId?e.operation="continue":e.sessionId&&(e.operation="check-status")),e?.operation&&("spawn"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours):"continue"===e.operation?(delete e.agent,delete e.description,delete e.allowParallel,delete e.useExistingSession,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours,delete e.limit):"check-status"===e.operation||"abort"===e.operation?(delete e.agent,delete e.prompt,delete e.description,delete e.requestId,delete e.allowParallel,delete e.useExistingSession,delete e.limit,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours):"read-messages"===e.operation?(delete e.agent,delete e.prompt,delete e.description,delete e.requestId,delete e.allowParallel,delete e.useExistingSession,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours):"list-sessions"===e.operation&&(delete e.sessionId,delete e.agent,delete e.prompt,delete e.description,delete e.allowParallel,delete e.useExistingSession))
|
|
1355
1358
|
const r=C.validateArgs(e,v.SubagentOperationsSchema),{sessionId:g,operation:p}=r
|
|
1356
|
-
let
|
|
1357
|
-
switch(c.info("Processing subagent_operations",{operation:p,sessionId:g}),p){case"spawn":
|
|
1359
|
+
let m
|
|
1360
|
+
switch(c.info("Processing subagent_operations",{operation:p,sessionId:g}),p){case"spawn":m=await n({agent:r.agent,prompt:r.prompt,requestId:r.requestId,allowParallel:r.allowParallel,useExistingSession:r.useExistingSession},t,c,i,a)
|
|
1358
1361
|
break
|
|
1359
|
-
case"continue":
|
|
1362
|
+
case"continue":m=await o(g,r.prompt,t,c,i,void 0,a)
|
|
1360
1363
|
break
|
|
1361
|
-
case"check-status":
|
|
1364
|
+
case"check-status":m=await d(g,t,c,i)
|
|
1362
1365
|
break
|
|
1363
|
-
case"abort":
|
|
1366
|
+
case"abort":m=await u(g,t,c)
|
|
1364
1367
|
break
|
|
1365
1368
|
case"read-messages":const e=r.limit??1
|
|
1366
|
-
|
|
1369
|
+
m=await async function(e,t,r,n){const o=await(0,k.getServerUrl)(r,n)
|
|
1367
1370
|
if(!o)throw new y.ValidationError("Could not determine OpenCode server URL")
|
|
1368
1371
|
n.info("Reading messages from subagent session",{sessionId:e,limit:t})
|
|
1369
1372
|
try{const r=`${o.replace(/\/$/,"")}/session/${e}/message?limit=${t}`,n=await fetch(r)
|
|
@@ -1375,10 +1378,10 @@ return`[${t+1}] ${r} (${new Date(e.info.time.created).toLocaleTimeString()}):\n$
|
|
|
1375
1378
|
return{content:[{type:"text",text:`Session ${e} - Last ${s.length} messages:\n\n${i}`}]}}catch(e){throw Error("Failed to read messages: "+(0,_.getErrorMessage)(e))}}(g,e,t,c)
|
|
1376
1379
|
break
|
|
1377
1380
|
case"list-sessions":const s={activeOnly:r.activeOnly,requestId:r.requestId,limit:r.limit,minTokens:r.minTokens,maxTokens:r.maxTokens,maxAgeHours:r.maxAgeHours,parentSessionId:a?.sessionId}
|
|
1378
|
-
|
|
1381
|
+
m=await h(t,c,i,s)
|
|
1379
1382
|
break
|
|
1380
|
-
default:throw new y.ValidationError("Unknown operation: "+p)}return l({success:!0}),s.incrementCounter(`subagent_operations_${p}_success`,1),
|
|
1381
|
-
const y=t(9860),w=t(8035),k=t(7617),I=t(6688),b=t(7280),v=t(6183),C=
|
|
1383
|
+
default:throw new y.ValidationError("Unknown operation: "+p)}return l({success:!0}),s.incrementCounter(`subagent_operations_${p}_success`,1),m}catch(e){return c.error("Subagent operations failed",{error:e instanceof Error?e.stack:e+""}),l({success:!1}),s.incrementCounter("subagent_operations_errors",1),{content:[{type:"text",text:"Subagent operation failed: "+(0,_.getErrorMessage)(e)}],isError:!0}}}
|
|
1384
|
+
const y=t(9860),w=t(8035),k=t(7617),I=t(6688),b=t(7280),v=t(6183),C=f(t(5967)),_=t(8824),E=t(9896),q=t(6928),S=t(8955),T=(0,t(9414).getActionServerPort)(),P=6e4,j=3e5},1791(e,exports,t){"use strict"
|
|
1382
1385
|
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}}
|
|
1383
1386
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectContext=void 0,exports.projectContextMiddleware=r
|
|
1384
1387
|
const o=n(t(9896)),s=n(t(6928)),i=t(4139),a=t(4055),c=t(8824)
|
|
@@ -1535,20 +1538,20 @@ const p=[]
|
|
|
1535
1538
|
for(const t of l){c.info("Executing test command",{name:t.name,command:t.command,timeout:t.timeout,cwd:h})
|
|
1536
1539
|
try{const e=d(t.command,{cwd:h,timeout:1e3*t.timeout,encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"win32"===process.platform?"cmd.exe":"/bin/sh",env:{...u.env,FORCE_COLOR:"0"}})
|
|
1537
1540
|
p.push({name:t.name,command:t.command,exitCode:0,output:e.slice(-4e3),timedOut:!1})}catch(r){const n=!0===r.killed,o=((r.stdout||"")+"\n"+(r.stderr||"")).trim().slice(-4e3),s=r.status??1
|
|
1538
|
-
if(p.push({name:t.name,command:t.command,exitCode:s,output:o,timedOut:n}),"setup"===e.commandName)break}}const
|
|
1541
|
+
if(p.push({name:t.name,command:t.command,exitCode:s,output:o,timedOut:n}),"setup"===e.commandName)break}}const m=p.every((e=>0===e.exitCode)),f=p.map((e=>{const t=e.timedOut?"\u23f1 TIMEOUT":0===e.exitCode?"\u2705 PASS":`\u274c FAIL (exit ${e.exitCode})`
|
|
1539
1542
|
return`### ${e.name}: ${t}\n\`\`\`\n$ ${e.command}\n${e.output}\n\`\`\``})).join("\n\n")
|
|
1540
|
-
return a({success:!0}),{content:[{type:"text",text:`## ${"setup"===e.commandName?"Setup":e.commandName} \u2014 ${
|
|
1541
|
-
try{const{sessionIdentity:
|
|
1542
|
-
if(!
|
|
1543
|
-
const
|
|
1544
|
-
if(!
|
|
1545
|
-
const f=
|
|
1543
|
+
return a({success:!0}),{content:[{type:"text",text:`## ${"setup"===e.commandName?"Setup":e.commandName} \u2014 ${m?"PASSED":"FAILED"}\n\n${f}`}]}}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,c){const l=a.startTimer("tool_execution_time")
|
|
1544
|
+
try{const{sessionIdentity:d}=await Promise.resolve().then(t.bind(t,6688)),u=await d.getSessionRequestId(s,i,c?.sessionId)
|
|
1545
|
+
if(!u)return l({success:!1,error:"no_request_association"}),{content:[{type:"text",text:"Cannot report test results: this session is not associated with a request."}],isError:!0}
|
|
1546
|
+
const h=await s.proxyGet(`/api/projects/${o.projectId}/requests/${u}/test-runs`),g=h?.data||h||[],p=Array.isArray(g)?g:[],m=p.find((e=>"pending"===e.status||"running"===e.status))||p[0]
|
|
1547
|
+
if(!m)return l({success:!1,error:"no_test_run"}),{content:[{type:"text",text:`No test run found for request ${u}.`}],isError:!0}
|
|
1548
|
+
const f=m.id
|
|
1546
1549
|
await s.proxyPatch(`/api/projects/${o.projectId}/test-runs/${f}`,{status:e.status,results:e.results})
|
|
1547
|
-
const
|
|
1550
|
+
const y="passed"===e.status?"\u2705":"failed"===e.status?"\u274c":"\u26a0\ufe0f"
|
|
1548
1551
|
try{const t=s.getRequestClient()
|
|
1549
|
-
"passed"===e.status?(await t.updateRequest(
|
|
1550
|
-
try{const t=await(0,n.handleSessionMessageOperations)({operation:"send",type:"report",status:"passed"===e.status?"success":"failure",summary:
|
|
1551
|
-
return
|
|
1552
|
+
"passed"===e.status?(await t.updateRequest(u,{status:"ready_for_merge"}),i.info("Tests passed, set request to ready_for_merge",{requestId:u})):(await t.updateRequest(u,{status:"in_progress"}),i.info("Tests failed, set request back to in_progress",{requestId:u}))}catch(e){i.warn("Failed to update request status after test results",{requestId:u,error:(0,r.getErrorMessage)(e)})}const w="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.",k=`${y} Test run ${e.status} for request ${u}\n\n${e.results.summary}${w}`
|
|
1553
|
+
try{const t=await(0,n.handleSessionMessageOperations)({operation:"send",type:"report",status:"passed"===e.status?"success":"failure",summary:k,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,c),r=t?.content?.[0]?.text||"unknown",d=t?.isError
|
|
1554
|
+
return l({success:!0}),{content:[{type:"text",text:`Test run for request ${u} reported as **${e.status}**.${d?" Parent notification FAILED: "+r:" Parent session notified."}\n\n${e.results.summary}`}]}}catch(t){return l({success:!0}),{content:[{type:"text",text:`Test run for request ${u} reported as **${e.status}** but failed to notify parent: ${(0,r.getErrorMessage)(t)}\n\n${e.results.summary}`}]}}}catch(e){return l({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'}]}}
|
|
1552
1555
|
const r=t(8824),n=t(9072)},2085(e,exports,t){"use strict"
|
|
1553
1556
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.getRequestTimelineForFile=async function(e,t,s,i){let a=`# File History: ${t}\n\n`
|
|
1554
1557
|
a+="**Context**: Main branch (request-level view)\n\n"
|
|
@@ -1593,7 +1596,29 @@ return e&&o[e]?o[e]:e?null:o}catch(t){return this.logger.debug("No user preferen
|
|
|
1593
1596
|
this.logger.info("Saving user tool preferences",{clientType:e,preset:t,disabledToolsCount:r?.length||0,allowedToolsCount:s?.length||0}),await n.default.mkdir(a,{recursive:!0})
|
|
1594
1597
|
let c={}
|
|
1595
1598
|
try{const e=await n.default.readFile(i,"utf-8")
|
|
1596
|
-
c=JSON.parse(e)}catch(e){}c[e]={preset:t,disabledTools:r||[],allowedAlchemyTools:s||[],updatedAt:(new Date).toISOString()},await n.default.writeFile(i,JSON.stringify(c,null,2),"utf-8"),this.logger.info("User tool preferences saved",{clientType:e,prefsFile:i})}}},
|
|
1599
|
+
c=JSON.parse(e)}catch(e){}c[e]={preset:t,disabledTools:r||[],allowedAlchemyTools:s||[],updatedAt:(new Date).toISOString()},await n.default.writeFile(i,JSON.stringify(c,null,2),"utf-8"),this.logger.info("User tool preferences saved",{clientType:e,prefsFile:i})}}},2113(e,exports,t){"use strict"
|
|
1600
|
+
async function r(e,t){const r=await fetch(`${e}/session/${t}/message`,{signal:AbortSignal.timeout(5e3)})
|
|
1601
|
+
if(!r.ok)throw Error("status "+r.status)
|
|
1602
|
+
return await r.json()}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCommitToViewedSession=async function(e,t){const a=Math.random().toString(36).slice(2,8),c=Date.now()
|
|
1603
|
+
let l
|
|
1604
|
+
t.info("commit_to_viewed_session:enter",{callId:a,enteredAt:c})
|
|
1605
|
+
try{l=n.CommitToViewedSessionSchema.parse(e).message}catch(e){return t.warn("commit_to_viewed_session:schema-fail",{callId:a,error:(0,o.getErrorMessage)(e)}),{content:[{type:"text",text:"Invalid commit: "+(0,o.getErrorMessage)(e)}],isError:!0}}t.info("commit_to_viewed_session:parsed",{callId:a,messagePreview:l.slice(0,80),messageLength:l.length})
|
|
1606
|
+
const d=s.sessionIdentity.getIdentity(),u=d?.sessionId,h=d?.serverUrl
|
|
1607
|
+
if(!u||!h)return t.warn("commit_to_viewed_session: missing session identity",{hasHeraldId:!!u,hasServerUrl:!!h}),{content:[{type:"text",text:"Commit failed: herald session identity unavailable."}],isError:!0}
|
|
1608
|
+
let g
|
|
1609
|
+
try{g=await r(h,u)}catch(e){return t.warn("commit_to_viewed_session: could not fetch herald messages",{heraldId:u,error:(0,o.getErrorMessage)(e)}),{content:[{type:"text",text:`Commit failed: unable to read herald context (${(0,o.getErrorMessage)(e)}).`}],isError:!0}}const p=function(e){for(let t=e.length-1;t>=0;t--){const r=e[t]
|
|
1610
|
+
if("user"===r.info?.role)for(const e of r.parts??[]){if("text"!==e.type||!e.text)continue
|
|
1611
|
+
const t=e.text.match(/<viewed_session\s+id="([^"]+)"\s*\/?>/)
|
|
1612
|
+
if(t)return t[1]}}return null}(g)
|
|
1613
|
+
if(!p)return{content:[{type:"text",text:"Commit failed: no <viewed_session/> tag in herald context. The UI must embed one in each dictation envelope."}],isError:!0}
|
|
1614
|
+
let m
|
|
1615
|
+
try{m=function(e){for(let t=e.length-1;t>=0;t--){const r=e[t]
|
|
1616
|
+
if("assistant"===r.info?.role&&r.info.agent)return r.info.agent}}(await r(h,p)),m||t.warn("commit_to_viewed_session: no agent resolvable for viewed session; omitting agent",{viewedId:p})}catch(e){t.warn("commit_to_viewed_session: could not fetch viewed messages; omitting agent",{viewedId:p,error:(0,o.getErrorMessage)(e)})}const f={parts:[{type:"text",text:`${i}${l}`}]}
|
|
1617
|
+
m&&(f.agent=m),t.info("commit_to_viewed_session:posting",{callId:a,viewedId:p,heraldId:u,agent:m})
|
|
1618
|
+
try{const e=await fetch(`${h}/session/${p}/prompt_async`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f),signal:AbortSignal.timeout(1e4)})
|
|
1619
|
+
if(t.info("commit_to_viewed_session:posted",{callId:a,status:e.status}),!e.ok){const t=await e.text().catch((()=>""))
|
|
1620
|
+
return{content:[{type:"text",text:`Commit failed: prompt_async returned ${e.status}${t?` (${t.slice(0,120)})`:""}.`}],isError:!0}}}catch(e){return t.warn("commit_to_viewed_session:post-failed",{callId:a,error:(0,o.getErrorMessage)(e)}),{content:[{type:"text",text:"Commit failed: "+(0,o.getErrorMessage)(e)}],isError:!0}}return t.info("Translator forwarded message to viewed session",{callId:a,heraldId:u,viewedId:p,agent:m,messageLength:l.length,preview:l.slice(0,120),durationMs:Date.now()-c}),{content:[{type:"text",text:"Committed."}]}}
|
|
1621
|
+
const n=t(6183),o=t(8824),s=t(6688),i="\x3c!-- via-herald --\x3e"},2140(e,exports,t){"use strict"
|
|
1597
1622
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSwitchToMainBranch=async function(e,t,i,a,c){const l=a.child({tool:"switch_to_main_branch"}),d=Date.now()
|
|
1598
1623
|
try{if(r.SwitchToMainBranchSchema.parse(e),l.info("Switching to main branch/repository"),!t.workspaceManager)throw(0,n.createServiceError)("WorkspaceManager not available",{phase:"workspace_manager_check"})
|
|
1599
1624
|
let a=null
|
|
@@ -1682,27 +1707,27 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
1682
1707
|
var t={}
|
|
1683
1708
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
1684
1709
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1685
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,r,n,o,s,i,f
|
|
1710
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,r,n,o,s,i,m,f){const y=i.child({tool:"move_files"}),w=Date.now()
|
|
1686
1711
|
let k,I,b=d.FileOperationPhase.VALIDATION
|
|
1687
1712
|
const v={toolName:"move-files",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"move-files",metricsPrefix:"move_files",successMessage:"Successfully moved files",failureMessage:"Failed to move files"}
|
|
1688
1713
|
try{const u=d.validateArgs(e,l.MoveFilesSchema),{operations:h,comment:C}=u,{resolveActiveTaskId:_}=await Promise.resolve().then(t.bind(t,3451)),E=e.taskId||await _(r,n,i)||"untracked"
|
|
1689
1714
|
if(y.info("Moving multiple files and directories",{taskId:E,operationCount:h.length,comment:C}),!h||0===h.length)throw Error("At least one move operation must be specified")
|
|
1690
|
-
d.validateTaskIdFormat(E,y,
|
|
1715
|
+
d.validateTaskIdFormat(E,y,m,v.metricsPrefix)
|
|
1691
1716
|
const q=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
1692
1717
|
y.info("Initial branch context",{initialBranch:q.branch,initialRequestId:q.requestId,isMain:q.isMain})
|
|
1693
1718
|
const S=[]
|
|
1694
1719
|
for(const e of h){const{normalizedPath:t,fullPath:n}=d.validateAndNormalizePath(e.source,r),{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(e.destination,r)
|
|
1695
|
-
S.push({source:t,destination:o,fullSource:n,fullDestination:s})}b=d.FileOperationPhase.TASK_VALIDATION,
|
|
1696
|
-
const T=await d.validateTaskId(E,S[0].source,n,y,
|
|
1720
|
+
S.push({source:t,destination:o,fullSource:n,fullDestination:s})}b=d.FileOperationPhase.TASK_VALIDATION,m.incrementCounter("move_files_phase",1,{phase:b})
|
|
1721
|
+
const T=await d.validateTaskId(E,S[0].source,n,y,m,v.metricsPrefix),P=T?.requestId,j=await d.validateWorkItemStates(E,S[0].source,n,s,r,y,m,v.metricsPrefix),x=await d.autoPromoteTaskStatus(E,T.status,P,j.request?.status,S[0].source,n,s,y,m,v.metricsPrefix)
|
|
1697
1722
|
x.taskPromoted&&y.info(`Auto-promoted task ${E} (${T.title||"Untitled"}) to in_progress for file operations`,{taskId:E,taskTitle:T.title,previousStatus:T.status,newStatus:x.newTaskStatus,operationCount:h.length}),x.requestPromoted&&y.info(`Auto-promoted request ${P} to in_progress for file operations`,{requestId:P,previousStatus:j.request?.status,newStatus:x.newRequestStatus,triggeringTaskId:E})
|
|
1698
|
-
const R=await d.ensureCorrectWorkspaceContext({taskPromoted:x.taskPromoted,requestId:P,context:r,operation:"move-files",logger:y,metrics:
|
|
1723
|
+
const R=await d.ensureCorrectWorkspaceContext({taskPromoted:x.taskPromoted,requestId:P,context:r,operation:"move-files",logger:y,metrics:m,metricsPrefix:v.metricsPrefix})
|
|
1699
1724
|
if(!R.success){if(R.isLockConflict)return{content:[{type:"text",text:"\u274c "+R.error}],isError:!0}
|
|
1700
1725
|
throw Error(R.error)}let M={hadUserMods:!1,userModsCommitHash:void 0}
|
|
1701
1726
|
if(r.git)try{y.debug("[MOVE-FILES] Checking for user changes before move operations")
|
|
1702
|
-
const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"move-files",{requestId:P,taskId:E,workspaceManager:r.workspaceManager},y,
|
|
1703
|
-
e.userChangesCommitted&&(y.debug("[MOVE-FILES] User changes committed before move operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before move-files operation",{taskId:E,moveOperationsCount:S.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),M={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){y.debug("[MOVE-FILES] Pre-tool commit failed, continuing with move operations",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with move operation",{taskId:E,moveOperationsCount:S.length,error:e instanceof Error?e.message:e+""})}y.debug("[MOVE-FILES] Proceeding with move operations",{operationCount:S.length}),b=d.FileOperationPhase.RECORD_CREATION,
|
|
1704
|
-
const{toolRecordId:O,localToolRecordId:$}=await d.createFileOperationRecords(E,P,r.projectId,v.recordType,S[0].source,{operationCount:h.length,operations:S.map((e=>({source:e.source,destination:e.destination}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},n,o,y,
|
|
1705
|
-
k=O,I=O,b=v.fileOperationPhase,
|
|
1727
|
+
const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"move-files",{requestId:P,taskId:E,workspaceManager:r.workspaceManager},y,m)
|
|
1728
|
+
e.userChangesCommitted&&(y.debug("[MOVE-FILES] User changes committed before move operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before move-files operation",{taskId:E,moveOperationsCount:S.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),M={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){y.debug("[MOVE-FILES] Pre-tool commit failed, continuing with move operations",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with move operation",{taskId:E,moveOperationsCount:S.length,error:e instanceof Error?e.message:e+""})}y.debug("[MOVE-FILES] Proceeding with move operations",{operationCount:S.length}),b=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("move_files_phase",1,{phase:b})
|
|
1729
|
+
const{toolRecordId:O,localToolRecordId:$}=await d.createFileOperationRecords(E,P,r.projectId,v.recordType,S[0].source,{operationCount:h.length,operations:S.map((e=>({source:e.source,destination:e.destination}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},n,o,y,m,v.metricsPrefix,f)
|
|
1730
|
+
k=O,I=O,b=v.fileOperationPhase,m.incrementCounter("move_files_phase",1,{phase:b})
|
|
1706
1731
|
const D=[]
|
|
1707
1732
|
let A=0
|
|
1708
1733
|
for(const e of S){const t={operation:{source:e.source,destination:e.destination},success:!1}
|
|
@@ -1710,13 +1735,13 @@ try{try{await a.default.access(e.fullSource)}catch(t){throw Error("Source path n
|
|
|
1710
1735
|
t.isDirectory=r
|
|
1711
1736
|
const n=c.default.dirname(e.fullDestination)
|
|
1712
1737
|
try{await a.default.mkdir(n,{recursive:!0})}catch(e){throw Error("Failed to create destination directory: "+n)}try{throw await a.default.access(e.fullDestination),Error("Destination already exists: "+e.destination)}catch(e){if(!(e instanceof Error&&e.message.includes("ENOENT")))throw e}await a.default.rename(e.fullSource,e.fullDestination),t.success=!0,A++,y.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,p.getErrorMessage)(r),y.warn(`Failed to move ${e.source} to ${e.destination}`,{error:t.error})}D.push(t)}const F=Date.now()-w
|
|
1713
|
-
|
|
1738
|
+
m.recordValue("move_files_time",F),m.incrementCounter("move_files_operations_total",h.length),m.incrementCounter("move_files_operations_success",A),m.incrementCounter("move_files_operations_failed",h.length-A),A===h.length?m.incrementCounter("move_files_success",1):A>0?m.incrementCounter("move_files_partial_success",1):m.incrementCounter("move_files_total_failure",1)
|
|
1714
1739
|
let N=null
|
|
1715
|
-
if(A>0){b=d.FileOperationPhase.GIT_COMMIT,
|
|
1740
|
+
if(A>0){b=d.FileOperationPhase.GIT_COMMIT,m.incrementCounter("move_files_phase",1,{phase:b})
|
|
1716
1741
|
const e=D.filter((e=>e.success)),t=1===e.length?`Move ${e[0].isDirectory?"directory":"file"} from ${e[0].operation.source} to ${e[0].operation.destination} - ${C}`:`Move ${e.length} ${1===e.length?"item":"items"} - ${C}`
|
|
1717
|
-
N=await d.commitToGit(E,S[0].destination,O,$,t,r,y,
|
|
1742
|
+
N=await d.commitToGit(E,S[0].destination,O,$,t,r,y,m,v.metricsPrefix)}b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,m.incrementCounter("move_files_phase",1,{phase:b})
|
|
1718
1743
|
const L=D.filter((e=>e.success)),z=D.filter((e=>!e.success))
|
|
1719
|
-
await d.updateFileOperationRecords(E,k,I,S[0].source,v.recordType,A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,{status:A===h.length?"completed":"partial_success",commitHash:N?.commitHash,previousCommitHash:N?.previousCommitHash,operationCount:h.length,successCount:A,failureCount:h.length-A,successfulOperations:L.map((e=>({source:e.operation.source,destination:e.operation.destination,isDirectory:e.isDirectory}))),failedOperations:z.map((e=>({source:e.operation.source,destination:e.operation.destination,error:e.error}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,n,o,y,
|
|
1744
|
+
await d.updateFileOperationRecords(E,k,I,S[0].source,v.recordType,A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,{status:A===h.length?"completed":"partial_success",commitHash:N?.commitHash,previousCommitHash:N?.previousCommitHash,operationCount:h.length,successCount:A,failureCount:h.length-A,successfulOperations:L.map((e=>({source:e.operation.source,destination:e.operation.destination,isDirectory:e.isDirectory}))),failedOperations:z.map((e=>({source:e.operation.source,destination:e.operation.destination,error:e.error}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,n,o,y,m,v.metricsPrefix)
|
|
1720
1745
|
const H=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
1721
1746
|
let B=""
|
|
1722
1747
|
if(A===h.length)B=`Successfully moved all ${h.length} ${1===h.length?"item":"items"}`
|
|
@@ -1725,15 +1750,15 @@ B=`Successfully moved ${A}/${h.length} items.\n\nFailed operations:\n`+e.map((e=
|
|
|
1725
1750
|
if(N?.commitHash&&(B+="\nCommit: "+N.commitHash.substring(0,8)),H.requestId&&(B+="\nBranch: "+H.requestId),R.lockAcquired&&R.lockedRequestId){const e=r.workspaceManager?.getCurrentContext(r.currentSessionId)
|
|
1726
1751
|
e?.permanentBranch||(B+="\n\u{1f512} **Locked request:** "+R.lockedRequestId)}return{content:[{type:"text",text:B}],isError:0===A}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
|
|
1727
1752
|
await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"move-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment,error:(0,p.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:"Failed to move files - "+(0,p.getErrorMessage)(t)})}catch(t){y.error("Failed to create failure record for move-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,operationCount:e.operations?.length||0})}const s=Date.now()-w
|
|
1728
|
-
if(
|
|
1729
|
-
try{await d.updateFileOperationRecords(e.taskId,k,I,e.operations?.[0]?.source||"unknown",v.recordType,"Failed to move files",{status:"failed",error:(0,p.getErrorMessage)(t),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment},"Failed to move files",n,o,y,
|
|
1753
|
+
if(m.recordValue("move_files_time",s),m.incrementCounter("move_files_errors",1),y.error("Error in move-files operation:",{error:(0,p.getErrorMessage)(t),time:s}),(k||I)&&e.taskId){b=d.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
1754
|
+
try{await d.updateFileOperationRecords(e.taskId,k,I,e.operations?.[0]?.source||"unknown",v.recordType,"Failed to move files",{status:"failed",error:(0,p.getErrorMessage)(t),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment},"Failed to move files",n,o,y,m,v.metricsPrefix)}catch(t){y.error("Failed to update record with failure status",{taskId:e.taskId,recordId:k,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(t,b,y,m,e,v)}}
|
|
1730
1755
|
const a=i(t(1943)),c=i(t(6928)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(1569),g=t(7478),p=t(8824)},2422(module){"use strict"
|
|
1731
1756
|
module.exports=require("@modelcontextprotocol/sdk/server/sse.js")},2425(e,exports,t){"use strict"
|
|
1732
1757
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
1733
1758
|
const r=t(6183),n=t(3707)
|
|
1734
1759
|
exports.def={name:"quick_manage",description:"Move, delete, or create directories. Wraps the change in a request/task workflow that auto-completes.\n\nProvide an array of operations, each with operationType and corresponding data:\n\u2022 create-directory: { createDirectory: { path } }\n\u2022 move-files: { moveFiles: { moves: [{ source, destination }] } }\n\u2022 delete-files: { deleteFiles: { targets: [{ path }] } }\n\nFor read-only operations like get-file-info, use manage_files instead.\n\nRequires: title, description, operations.",schema:r.QuickManageSchema,annotations:{title:"Quick Manage",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"manage",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},2462(e,exports,t){"use strict"
|
|
1735
1760
|
Object.defineProperty(exports,"__esModule",{value:!0})
|
|
1736
|
-
const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),
|
|
1761
|
+
const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),m=t(260),f=t(2283),y=t(4165),w=t(7834),k=t(9373),I=t(6111),b=t(700),v=t(2783),C=t(2601),_=t(1722),E=t(7257),q=t(9230),S=t(6064),T=t(5216),P=t(6473),j=t(4921),x=t(8850),R=t(3556),M=t(1391),O=t(6315),$=t(7713),D=t(6252),A=t(213),F=t(7250),N=t(2425),L=t(1540),z=t(5767),H=t(4973),B=t(509),U=t(7613),G=t(8456),W=t(3322),V=t(5247),J=t(8849),K=t(542);(0,r.registerTool)(n.def),(0,r.registerTool)(o.def),(0,r.registerTool)(s.def),(0,r.registerTool)(i.def),(0,r.registerTool)(a.def),(0,r.registerTool)(c.def),(0,r.registerTool)(l.def),(0,r.registerTool)(d.def),(0,r.registerTool)(u.def),(0,r.registerTool)(h.def),(0,r.registerTool)(g.def),(0,r.registerTool)(p.def),(0,r.registerTool)(m.def),(0,r.registerTool)(f.def),(0,r.registerTool)(y.def),(0,r.registerTool)(w.def),(0,r.registerTool)(k.def),(0,r.registerTool)(I.def),(0,r.registerTool)(b.def),(0,r.registerTool)(v.def),(0,r.registerTool)(S.def),(0,r.registerTool)(C.def),(0,r.registerTool)(_.def),(0,r.registerTool)(E.def),(0,r.registerTool)(q.def),(0,r.registerTool)(T.def),(0,r.registerTool)(P.def),(0,r.registerTool)(j.def),(0,r.registerTool)(x.def),(0,r.registerTool)(R.def),(0,r.registerTool)(M.def),(0,r.registerTool)(O.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)(H.def),(0,r.registerTool)(B.def),(0,r.registerTool)(U.def),(0,r.registerTool)(G.def),(0,r.registerTools)(W.metaDefs),(0,r.registerTools)(V.testingDefs),(0,r.registerTools)(J.checkingDefs),(0,r.registerTools)(K.debugDefs),(0,t(2245).freezeRegistry)()},2478(e,exports){"use strict"
|
|
1737
1762
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.requestConfig=void 0,exports.areTestsRequiredForCompletion=function(){return exports.requestConfig.requireTestsForCompletion},exports.setTestsRequiredForCompletion=function(e){exports.requestConfig.requireTestsForCompletion=e},exports.getCompletionMode=function(e){return e&&["auto-merge","auto-test-then-merge","manual-review"].includes(e)?e:"auto-merge"},exports.getApprovalMode=function(e){return e&&["none","require-approval"].includes(e)?e:"none"},exports.requestConfig={requireTestsForCompletion:!1}},2537(e,exports,t){"use strict"
|
|
1738
1763
|
async function r(e,t,r){if(C.has(r)&&_>=t){if(0===t)return 0
|
|
1739
1764
|
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]"
|
|
@@ -1758,10 +1783,10 @@ let t=e,r=0
|
|
|
1758
1783
|
for(;t>=1024&&4>r;)t/=1024,r++
|
|
1759
1784
|
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[]
|
|
1760
1785
|
try{const{fullPath:d}=I.validateAndNormalizePath(e,t),h=await y.default.readdir(d,{withFileTypes:!0}),g=[]
|
|
1761
|
-
for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=I.validateAndNormalizePath(u,t),p=await y.default.stat(h),
|
|
1762
|
-
let
|
|
1763
|
-
d.isFile()&&(
|
|
1764
|
-
const k={name:d.name,isDirectory:d.isDirectory(),depth:n,size:p.size,modified:p.mtime,extension:
|
|
1786
|
+
for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=I.validateAndNormalizePath(u,t),p=await y.default.stat(h),m=d.isFile()?w.default.extname(d.name).toLowerCase():""
|
|
1787
|
+
let f
|
|
1788
|
+
d.isFile()&&(f=await r(h,p.size,m))
|
|
1789
|
+
const k={name:d.name,isDirectory:d.isDirectory(),depth:n,size:p.size,modified:p.mtime,extension:m,lineCount:f}
|
|
1765
1790
|
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""
|
|
1766
1791
|
const o=[]
|
|
1767
1792
|
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?"/":""
|
|
@@ -1787,34 +1812,34 @@ case"type":const o=e.extension||"",s=r.extension||""
|
|
|
1787
1812
|
return o!==s?o.localeCompare(s):e.name.localeCompare(r.name)
|
|
1788
1813
|
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)
|
|
1789
1814
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
1790
|
-
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]}),p=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),
|
|
1815
|
+
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]}),p=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),m=this&&this.__importStar||(h=function(e){return h=Object.getOwnPropertyNames||function(e){var t=[]
|
|
1791
1816
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
1792
1817
|
return t},h(e)},function(e){if(e&&e.__esModule)return e
|
|
1793
1818
|
var t={}
|
|
1794
1819
|
if(null!=e)for(var r=h(e),n=0;n<r.length;n++)"default"!==r[n]&&g(t,e,r[n])
|
|
1795
|
-
return p(t,e),t}),
|
|
1820
|
+
return p(t,e),t}),f=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1796
1821
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListDirectory=async function(e,t,i,a){const h=Date.now()
|
|
1797
1822
|
let g=I.FileOperationPhase.VALIDATION
|
|
1798
1823
|
I.FileOperationPhase.FILE_WRITE
|
|
1799
|
-
try{const p=I.validateArgs(e,k.ListDirectorySchema),{path:
|
|
1800
|
-
i.info("Listing directory: "+
|
|
1801
|
-
const{normalizedPath:C,fullPath:_}=I.validateAndNormalizePath(
|
|
1824
|
+
try{const p=I.validateArgs(e,k.ListDirectorySchema),{path:m,levels:f=1,sortBy:b="name"}=p
|
|
1825
|
+
i.info("Listing directory: "+m)
|
|
1826
|
+
const{normalizedPath:C,fullPath:_}=I.validateAndNormalizePath(m,t)
|
|
1802
1827
|
g=I.FileOperationPhase.FILE_WRITE
|
|
1803
|
-
try{if(!(await y.default.stat(_)).isDirectory())return{content:[{type:"text",text:"Path is not a directory: "+
|
|
1804
|
-
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: "+
|
|
1805
|
-
if(
|
|
1806
|
-
const e=await o(C,t,0,
|
|
1828
|
+
try{if(!(await y.default.stat(_)).isDirectory())return{content:[{type:"text",text:"Path is not a directory: "+m}],isError:!0}
|
|
1829
|
+
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: "+m}],isError:!0}:e instanceof Error&&"EACCES"===e.code?{content:[{type:"text",text:"Directory not accessible: "+m}],isError:!0}:{content:[{type:"text",text:"Cannot access directory: "+m}],isError:!0}}let E,q
|
|
1830
|
+
if(f>1){i.info(`Building tree structure for: ${C} (levels: ${f}, sortBy: ${b})`)
|
|
1831
|
+
const e=await o(C,t,0,f,b,i)
|
|
1807
1832
|
if(e.length>0){const t=s(e,b)
|
|
1808
|
-
E=`Directory tree for ${C} (${
|
|
1833
|
+
E=`Directory tree for ${C} (${f} levels):\n${l(c(e))}\n\n${t}`,q=d(e)}else E=`Directory ${C} is empty or inaccessible.`,q=0}else{const e=await y.default.readdir(_,{withFileTypes:!0}),o=[]
|
|
1809
1834
|
for(const n of e)try{const e=w.default.join(C,n.name).replace(/\\/g,"/"),{fullPath:s}=I.validateAndNormalizePath(e,t),i=await y.default.stat(s),a=n.isFile()?w.default.extname(n.name).toLowerCase():""
|
|
1810
1835
|
let c
|
|
1811
1836
|
n.isFile()&&(c=await r(s,i.size,a)),o.push({name:n.name,isDirectory:n.isDirectory(),depth:0,size:i.size,modified:i.mtime,extension:a,lineCount:c})}catch(e){i.debug("Excluding directory entry from listing: "+n.name,{reason:(0,v.getErrorMessage)(e)})}const s=u(o,b),a=s.map((e=>n({name:e.name,isDirectory(){return e.isDirectory},isFile(){return!e.isDirectory}},b,e)))
|
|
1812
1837
|
E=a.length>0?`Directory listing for ${C}:\n${l(c(s))}\n\n${a.join("\n")}`:`Directory ${C} is empty.`,q=s.length}const S=t.workspaceManager?.getCurrentContext(t.currentSessionId)
|
|
1813
1838
|
E+="\n\nBranch: "+(S?.branchName||"unknown")
|
|
1814
1839
|
const T=Date.now()-h
|
|
1815
|
-
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:
|
|
1840
|
+
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:f,time:T}),{content:[{type:"text",text:E}]}}catch(e){const t=Date.now()-h
|
|
1816
1841
|
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}}}
|
|
1817
|
-
const y=
|
|
1842
|
+
const y=f(t(1943)),w=f(t(6928)),k=t(6183),I=m(t(5967)),b=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},2568(e,exports,t){"use strict"
|
|
1818
1843
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1819
1844
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectSynchronizer=void 0
|
|
1820
1845
|
const n=r(t(6928)),o=t(8029),s=t(8824),i=t(2096)
|
|
@@ -1929,12 +1954,12 @@ if(!r())return t.level=(0,l.isDevBuild)()?c.LogLevel.INFO:c.LogLevel.ERROR,t.log
|
|
|
1929
1954
|
if("true"===process.env.DEBUG_LOGGING?.toLowerCase()){t.level=c.LogLevel.DEBUG,t.logToFile=!0
|
|
1930
1955
|
const r=e||process.cwd()
|
|
1931
1956
|
t.logFilePath=i.default.join(r,"logs","debug.log")}const n=process.env.DEBUG_LEVEL?.toLowerCase()
|
|
1932
|
-
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:p=!1,logFilePath:
|
|
1933
|
-
if(console&&
|
|
1934
|
-
a.default.existsSync(t)||a.default.mkdirSync(t,{recursive:!0})}(
|
|
1957
|
+
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:p=!1,logFilePath:m="./logs/app.log",console=!0}=t,f=[]
|
|
1958
|
+
if(console&&f.push(new s.default.transports.Console({format:d,stderrLevels:["error","warn","info","debug"]})),p){!function(e){const t=i.default.dirname(e)
|
|
1959
|
+
a.default.existsSync(t)||a.default.mkdirSync(t,{recursive:!0})}(m)
|
|
1935
1960
|
const e=o===c.LogLevel.DEBUG&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()
|
|
1936
|
-
|
|
1937
|
-
return o===c.LogLevel.DEBUG&&p&&r()&&y.info("Enhanced logging initialized",{level:o,serviceName:g,logToFile:p,logFilePath:
|
|
1961
|
+
f.push(new s.default.transports.File({filename:m,format:e?h:u}))}const y=s.default.createLogger({level:o,defaultMeta:{service:g},transports:f})
|
|
1962
|
+
return o===c.LogLevel.DEBUG&&p&&r()&&y.info("Enhanced logging initialized",{level:o,serviceName:g,logToFile:p,logFilePath:m,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)
|
|
1938
1963
|
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}}
|
|
1939
1964
|
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
|
|
1940
1965
|
const e=process.env.DEBUG_LEVEL?.toLowerCase()
|
|
@@ -1997,13 +2022,13 @@ i.info("Request breakdown",{fileRequests:h.length,documentRequests:g.length})
|
|
|
1997
2022
|
const p=[]
|
|
1998
2023
|
for(const e of h)p.push(r(e,t,0,l))
|
|
1999
2024
|
for(const e of g)p.push(n(e,t,0,l))
|
|
2000
|
-
const
|
|
2001
|
-
let
|
|
2025
|
+
const m=await Promise.all(p)
|
|
2026
|
+
let f=""
|
|
2002
2027
|
if(t.workspaceManager)try{const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
2003
|
-
e.branchName&&!e.permanentBranch&&(
|
|
2028
|
+
e.branchName&&!e.permanentBranch&&(f=`**Current Branch:** ${e.branchName}\n`)}catch(e){i.debug("Could not get branch context",{error:e})}const y=m.filter((e=>e.success)).length,w=m.filter((e=>!e.success)).length,k=m.length
|
|
2004
2029
|
let I="## Read Files/Documents\n\n"
|
|
2005
|
-
|
|
2006
|
-
for(let e=0;e<
|
|
2030
|
+
f&&(I+=f),I+=`**Total Requests:** ${k} - **Successful:** ${y} - **Failed:** ${w}\n\n`
|
|
2031
|
+
for(let e=0;e<m.length;e++){const t=m[e]
|
|
2007
2032
|
"file"===t.type?I+=`File ${e+1}: ${t.path}\n`:(I+=`Document ${e+1}: ${t.documentId}`,t.filename&&(I+=` (${t.filename})`),I+="\n"),t.success?(I+="**Status:** Success\n",t.lineCount&&t.totalLines&&(I+=`Lines Read / Total Lines ${t.lineCount} / ${t.totalLines}\n`),t.originalRequest?.lines&&t.totalLines&&(I+=`**Lines:** ${t.originalRequest.lines}\n`),I+=`\n**Content:**\n\`\`\`\n${t.content}\n\`\`\`\n`):(I+="**Status:** Failed\n",I+=`**Error:** ${t.error}\n`),I+="\n"}const b=0===w
|
|
2008
2033
|
return i.info("Multiple file/document read completed",{duration:Date.now()-a,totalRequests:k,successfulReads:y,failedReads:w,success:b}),s.incrementCounter("read_files_total",1,{success:b}),{content:[{type:"text",text:I}],isError:!b}}catch(e){const t=Date.now()-a
|
|
2009
2034
|
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,p.getErrorMessage)(e)}],isError:!0}}}
|
|
@@ -2119,7 +2144,7 @@ d.info("Generating journal for request",{requestId:c})
|
|
|
2119
2144
|
const h=t.projectId
|
|
2120
2145
|
if(!h)throw(0,n.createValidationError)("Project ID is required. Make sure you are in a project context.")
|
|
2121
2146
|
o.setProjectId(h),d.info("Fetching request data, tasks, and file history in parallel")
|
|
2122
|
-
const g=o.getRequestClient(),p=o.getTaskClient(),
|
|
2147
|
+
const g=o.getRequestClient(),p=o.getTaskClient(),m=o.getToolRecordClient(),[f,y,w]=await Promise.all([g.getRequest(c),p.listTasks({requestId:c}),m.getToolRecordsByRequestId(c).catch((e=>(d.warn("Failed to fetch tool records",{error:e+""}),[])))]),k=(0,s.extractDataFromResponse)(f,{logger:d,operationName:"getRequest",throwOnNoData:!0}),I="data"in k?k.data:k,b={id:I.id||c,title:I.title||"Unknown Request",description:I.description||"No description available",status:I.status||"unknown",type:I.type||"unknown",acceptanceCriteria:I.acceptanceCriteria||[],createdAt:I.createdAt||(new Date).toISOString(),updatedAt:I.updatedAt||(new Date).toISOString(),completedAt:I.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})))
|
|
2123
2148
|
d.info(`Fetched request, ${C.length} tasks, ${w.length} tool records`)
|
|
2124
2149
|
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()))
|
|
2125
2150
|
for(const e of o){const o=r(e),s=e.metadata?.comment||e.metadata?.userComment||"No comment"
|
|
@@ -2157,10 +2182,10 @@ const p=await t.workspaceManager.switchToRequest(h,{isCompleted:"completed"===g.
|
|
|
2157
2182
|
if(!p.success){try{const{sessionTag:e}=(0,s.getGlobalClientInfo)()
|
|
2158
2183
|
d.warn("Workspace switch failed, attempting to release acquired lock",{requestId:h,sessionTag:e,switchError:p.message}),await a.unlockRequest(h,e),d.info("Successfully released lock after workspace switch failure",{requestId:h})}catch(e){d.error("Failed to release lock after workspace switch failure",{requestId:h,unlockError:e instanceof Error?e.message:e+""})}const e=p.message||"Unknown error"
|
|
2159
2184
|
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}
|
|
2160
|
-
throw(0,o.createServiceError)(`Failed to switch to request ${h}: ${e}`,{requestId:h,error:e})}const
|
|
2161
|
-
l.recordValue("switch_to_request_branch_time",
|
|
2162
|
-
const
|
|
2163
|
-
return
|
|
2185
|
+
throw(0,o.createServiceError)(`Failed to switch to request ${h}: ${e}`,{requestId:h,error:e})}const m=Date.now()-u
|
|
2186
|
+
l.recordValue("switch_to_request_branch_time",m),l.incrementCounter("switch_to_request_branch_success",1)
|
|
2187
|
+
const f=["Successfully switched to branch: "+(p.newContext?.branchName||"unknown"),"**Previous branch:** "+(p.previousContext?.branchName||"unknown")]
|
|
2188
|
+
return f.push("\u{1f512} **Locked request:** "+h),d.info("Successfully switched to request workspace",{requestId:h,mode:p.newContext?.mode,branch:p.newContext?.branchName,duration:m}),{content:[{type:"text",text:f.join("\n")}]}}catch(t){const r=Date.now()-u
|
|
2164
2189
|
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}
|
|
2165
2190
|
throw t}}
|
|
2166
2191
|
const n=t(6183),o=t(9860),s=t(5172),i=t(8824)},3102(e,exports,t){"use strict"
|
|
@@ -2235,7 +2260,7 @@ if(0===a)throw Error(`String "${s}" not found`)
|
|
|
2235
2260
|
if(a>1)throw Error(`String "${s}" appears ${a} times (expected exactly 1 in unique mode)`)
|
|
2236
2261
|
o=o.replace(s,i),t.success=!0,t.occurrences=1}else{const e=(o.match(RegExp(r(s),"g"))||[]).length
|
|
2237
2262
|
if(0===e)throw Error(`String "${s}" not found`)
|
|
2238
|
-
o=o.replace(RegExp(r(s),"g"),i),t.success=!0,t.occurrences=e}}catch(e){t.error=(0,
|
|
2263
|
+
o=o.replace(RegExp(r(s),"g"),i),t.success=!0,t.occurrences=e}}catch(e){t.error=(0,f.getErrorMessage)(e)}s.push(t)}return{newContent:o,results:s}}var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
2239
2264
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
2240
2265
|
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=[]
|
|
2241
2266
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -2256,7 +2281,7 @@ x.push({type:"file",path:t,fullPath:n,replacements:e.replacements,mode:e.mode||"
|
|
|
2256
2281
|
if(j.length>0&&!r.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
2257
2282
|
for(const e of j)R.push({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode||"unique"})
|
|
2258
2283
|
if(R.length>0&&r.apiClient){const e=R.map((e=>e.documentId))
|
|
2259
|
-
try{await(0,
|
|
2284
|
+
try{await(0,m.ensureDocumentsNotLocked)(e,r.apiClient,w,c,"replace-strings-documents")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2260
2285
|
throw e}}v=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_strings_phase",1,{phase:v})
|
|
2261
2286
|
const M=x.length>0?x[0].path:"document-operation",O=await u.validateTaskId(T,M,o,w,c,C.metricsPrefix),$=O?.requestId
|
|
2262
2287
|
let D=null
|
|
@@ -2278,11 +2303,11 @@ let H=0,B=0
|
|
|
2278
2303
|
for(const e of x){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
2279
2304
|
try{if(await l.default.access(e.fullPath),!(await l.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
|
|
2280
2305
|
const r=await l.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await n(r,e.replacements,e.mode)
|
|
2281
|
-
t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,o!==r?(await l.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,B++,w.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,
|
|
2306
|
+
t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,o!==r?(await l.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,B++,w.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,w.error("File operation failed",{path:e.path,error:t.error})}z.push(t)}for(const e of R){const t={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
2282
2307
|
try{const o=await r.documentFileManager.getDocumentAsFile(e.documentId),s=r.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
2283
2308
|
t.filename=s?.filename
|
|
2284
2309
|
const i=await l.default.readFile(o,"utf8"),{newContent:a,results:c}=await n(i,e.replacements,e.mode)
|
|
2285
|
-
t.replacements=c,t.successfulReplacements=c.filter((e=>e.success)).length,t.failedReplacements=c.filter((e=>!e.success)).length,a!==i?(await l.default.writeFile(o,a,"utf8"),r.documentFileManager.markForSync(e.documentId),t.success=!0,B++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,
|
|
2310
|
+
t.replacements=c,t.successfulReplacements=c.filter((e=>e.success)).length,t.failedReplacements=c.filter((e=>!e.success)).length,a!==i?(await l.default.writeFile(o,a,"utf8"),r.documentFileManager.markForSync(e.documentId),t.success=!0,B++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,w.error("Document operation failed",{documentId:e.documentId,error:t.error})}z.push(t)}if(R.length>0)try{for(const e of R){const t=z.find((t=>t.documentId===e.documentId))
|
|
2286
2311
|
t?.success&&await r.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const U=await u.handleMultiFileGitCommit(T,x,z,B,{operationType:"Replace strings",toolRecordId:b,successField:"successfulReplacements",logger:w,metrics:c,metricsPrefix:"replace_strings"},r),G=u.processMultiFileOperationResults(z,"successfulReplacements"),{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q}=G
|
|
2287
2312
|
try{await s.updateToolRecord(b,{metadata:{path:x.length>0?x[0].path:"document:"+R[0]?.documentId,status:K?"completed":"failed",error:K?void 0:V+" operations failed",totalOperations:z.length,successfulFiles:Y,failedFiles:Q,operations:N,totalSuccessfulReplacements:J,totalFailedReplacements:H,operationsWithChanges:B,processingTime:Date.now()-k,userComment:q,...x.length>0&&U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}},note:K?`String replacement completed: ${W}/${z.length} operations successful${x.length>0?" (committed to git)":""}`:`String replacement partially failed: ${V}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}u.formatMultiFileToolResponse("String Replacement",{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q},U,F)
|
|
2288
2313
|
let Z="## String Replacement Results\n\n"
|
|
@@ -2294,8 +2319,8 @@ for(const e of z){if("file"===e.type?Z+=`### File: ${e.path}\n`:(Z+="### Documen
|
|
|
2294
2319
|
for(const t of e.replacements.filter((e=>!e.success)))Z+=` - "${t.old_str}" \u2192 "${t.new_str}": ${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")
|
|
2295
2320
|
const X=Date.now()-k
|
|
2296
2321
|
return w.info("Replace strings operation completed",{duration:X,success:K,totalOperations:z.length,successfulOperations:W,failedOperations:V}),c.incrementCounter("replace_strings_total",1,{success:K}),{content:[{type:"text",text:Z}],isError:!K}}catch(t){const r=Date.now()-k
|
|
2297
|
-
if(w.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),b)try{await s.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,
|
|
2298
|
-
const l=c(t(1943)),d=t(6183),u=a(t(5967)),h=t(9860),g=t(5003),p=t(7478),
|
|
2322
|
+
if(w.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),b)try{await s.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,f.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"String replacement failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return c.incrementCounter("replace_strings_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Replace Strings Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
|
|
2323
|
+
const l=c(t(1943)),d=t(6183),u=a(t(5967)),h=t(9860),g=t(5003),p=t(7478),m=t(9949),f=t(8824)},3322(e,exports,t){"use strict"
|
|
2299
2324
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
2300
2325
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
2301
2326
|
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=[]
|
|
@@ -2333,10 +2358,10 @@ var g=t(1599)
|
|
|
2333
2358
|
Object.defineProperty(exports,"SessionRequestAssociationClient",{enumerable:!0,get(){return g.SessionRequestAssociationClient}})
|
|
2334
2359
|
var p=t(4465)
|
|
2335
2360
|
Object.defineProperty(exports,"SessionTagMappingClient",{enumerable:!0,get(){return p.SessionTagMappingClient}})
|
|
2336
|
-
var
|
|
2337
|
-
Object.defineProperty(exports,"CLISessionClient",{enumerable:!0,get(){return
|
|
2338
|
-
var
|
|
2339
|
-
Object.defineProperty(exports,"ClientFactory",{enumerable:!0,get(){return
|
|
2361
|
+
var m=t(5187)
|
|
2362
|
+
Object.defineProperty(exports,"CLISessionClient",{enumerable:!0,get(){return m.CLISessionClient}})
|
|
2363
|
+
var f=t(6539)
|
|
2364
|
+
Object.defineProperty(exports,"ClientFactory",{enumerable:!0,get(){return f.ClientFactory}})
|
|
2340
2365
|
const y=t(6539)
|
|
2341
2366
|
exports.default={ClientFactory:y.ClientFactory}},3420(e,exports,t){"use strict"
|
|
2342
2367
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleGetTaskInformation=async function(e,t,a,c,l){const d=c.child({tool:"get_task_information"})
|
|
@@ -2361,12 +2386,12 @@ const n=e
|
|
|
2361
2386
|
"metadata"in t&&t.metadata&&(n.metadata=t.metadata),g=n}else g={id:r,title:"Untitled Task",description:"No description available.",status:"pending",projectId:c,requestId:"",createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}
|
|
2362
2387
|
d.info("Retrieved task information",{taskId:r,title:g.title,status:g.status})}catch(e){throw new o.NotFoundError(`Task ${r} not found in project ${c}. Please provide a valid task ID.`,{taskId:r,projectId:c,originalError:e})}let p=null
|
|
2363
2388
|
if(g.requestId)try{const e=a.getRequestClient()
|
|
2364
|
-
p=await e.getRequest(g.requestId),d.info("Retrieved parent request information",{taskId:r,requestId:g.requestId})}catch(e){d.warn("Failed to retrieve parent request",{error:(0,s.getErrorMessage)(e),taskId:r,requestId:g.requestId})}const
|
|
2389
|
+
p=await e.getRequest(g.requestId),d.info("Retrieved parent request information",{taskId:r,requestId:g.requestId})}catch(e){d.warn("Failed to retrieve parent request",{error:(0,s.getErrorMessage)(e),taskId:r,requestId:g.requestId})}const m=e=>{if(!e)return"Unknown date"
|
|
2365
2390
|
try{const t=new Date(e)
|
|
2366
|
-
return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return d.warn("Invalid date format: "+e),"Unknown date"}},m
|
|
2391
|
+
return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return d.warn("Invalid date format: "+e),"Unknown date"}},f=m(g.createdAt),y=m(g.updatedAt),w=g.requestId||g.requestLocalId,k=g.sequenceNumber&&w?(0,i.formatTaskRef)(w,g.sequenceNumber):r
|
|
2367
2392
|
let I=`# Task: ${g.title} (${k})\n\n`
|
|
2368
|
-
if(I+=`**Status**: ${g.status}\n`,I+=`**Created**: ${
|
|
2369
|
-
I+="\n## Metadata\n\n",e.lastCommit&&(I+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(I+=`**Completed At**: ${
|
|
2393
|
+
if(I+=`**Status**: ${g.status}\n`,I+=`**Created**: ${f}\n`,I+=`**Updated**: ${y}\n`,g.requestId&&(I+="**Parent Request**: "+g.requestId,I+=p?` (${p.title})\n`:"\n"),g.metadata){const e=g.metadata
|
|
2394
|
+
I+="\n## Metadata\n\n",e.lastCommit&&(I+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(I+=`**Completed At**: ${m(e.completedAt)}\n`),e.completionSummary&&(I+=`**Completion Summary**: ${e.completionSummary}\n`)
|
|
2370
2395
|
const t=["lastCommit","completedAt","completionSummary"]
|
|
2371
2396
|
Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{I+=`**${e}**: ${t}\n`}))}return I+="\n## Description\n\n",g.description&&g.description.trim().length>0?I+=g.description:I+="No description provided.",u({success:!0}),{content:[{type:"text",text:I}]}}catch(n){d.error("Failed to get task information",{error:n instanceof Error?n.stack:n+"",args:e})
|
|
2372
2397
|
try{const o=a.getToolRecordClient()
|
|
@@ -2401,13 +2426,13 @@ const r=t(6183),n=t(8317)
|
|
|
2401
2426
|
exports.def={name:"request_file_history",description:"Get file change history for an entire request. Supports summary mode (net diffs) or detailed mode (chronological operations). Can be filtered to specific task. Use query_history tool instead.",schema:r.QueryHistorySchema,annotations:{title:"Request File History",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleRequestFileHistory)(e,t.context,t.apiClient,t.logger,t.metrics)}}},3611(e,exports,t){"use strict"
|
|
2402
2427
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2403
2428
|
Object.defineProperty(exports,"__esModule",{value:!0})
|
|
2404
|
-
const n=r(t(6928)),o=r(t(7252)),s=r(t(8577)),i=t(184),a=t(1213),c=t(3444),l=t(9955),d=t(2568),u=t(3102),h=t(1152),g=t(3884),p=t(7888),
|
|
2429
|
+
const n=r(t(6928)),o=r(t(7252)),s=r(t(8577)),i=t(184),a=t(1213),c=t(3444),l=t(9955),d=t(2568),u=t(3102),h=t(1152),g=t(3884),p=t(7888),m=t(4139),f=t(6800),y=t(6539),w=t(8824),k=t(6975),I=t(1253),b=process.argv.slice(2),v=b[0]||process.cwd(),C=n.default.resolve(v),_=parseInt(process.env.LOCAL_SERVER_PORT||b[1]||"3002",10),E=(0,c.createEnvLogger)({serviceName:"mcp-http-server"});(0,c.isDebugToolsEnabled)()?E.info("HTTP server initializing",{baseDir:C,preferredPort:_,debugLogging:process.env.DEBUG_LOGGING,debugLevel:process.env.DEBUG_LEVEL}):E.info("HTTP server starting",{port:_})
|
|
2405
2430
|
const q=(0,h.createMetricsCollector)(!0),S=(process.env.REMOTE_SERVER_PORT,process.env.REMOTE_SERVER_HOST,process.env.REMOTE_SERVER_URL||"https://api.alchemylabcode.com")
|
|
2406
2431
|
E.info("Using remote server URL",{remoteServerUrl:S}),async function(){try{E.info("Finding available port...",{preferredPort:_,baseDir:C,remoteServerUrl:S})
|
|
2407
|
-
const e=await(0,
|
|
2432
|
+
const e=await(0,f.findAvailablePort)(_)
|
|
2408
2433
|
e!==_&&E.info(`Preferred port ${_} is in use, using port ${e} instead`),E.info("Starting HTTP API server...",{port:e,baseDir:C,remoteServerUrl:S})
|
|
2409
|
-
const t=new l.ProjectRegistry(E),r=new u.DefaultProjectFileSystem(E),c=n.default.join(C,
|
|
2410
|
-
E.info(`Checking ${
|
|
2434
|
+
const t=new l.ProjectRegistry(E),r=new u.DefaultProjectFileSystem(E),c=n.default.join(C,m.ALCHEMY_DIR_NAME)
|
|
2435
|
+
E.info(`Checking ${m.ALCHEMY_DIR_NAME} directory`,{alchemyPath:c}),await r.ensureDirectoryExists(c)
|
|
2411
2436
|
const h=new I.TokenManager(E,n.default.join(c,"auth-token.json")),b=(await y.ClientFactory.createClient(S,E,q,{tokenManager:h,workingDir:C,alchemyPath:c})).projectClient,v=new k.ProjectClientAdapter(b,E),T=new d.ProjectSynchronizer(E,t,v,r),P=await T.getOrCreateProject(C,{name:n.default.basename(C)||"Local Project",description:"Project for "+n.default.basename(C),status:"active",metadata:{basePath:C,alchemyPath:c,bootstrapped:!0}})
|
|
2412
2437
|
E.info("Using project",{projectId:P.id,projectName:P.name})
|
|
2413
2438
|
const j=(0,o.default)()
|
|
@@ -2460,16 +2485,16 @@ if(i.length>h)break
|
|
|
2460
2485
|
if(i===l){c.push({line:s+1,actuallyMatched:o,matchType:"whitespace_normalized",startPos:r,endPos:t})
|
|
2461
2486
|
break}}}o+=i.length+1}return c}const g=t.trim()[0]
|
|
2462
2487
|
if(!g)return c
|
|
2463
|
-
let p=0,
|
|
2464
|
-
for(;;){if(
|
|
2465
|
-
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`)}
|
|
2488
|
+
let p=0,m=0
|
|
2489
|
+
for(;;){if(m%100==0&&Date.now()-d>o){const r=Date.now()-d
|
|
2490
|
+
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`)}m++
|
|
2466
2491
|
const r=e.indexOf(g,p)
|
|
2467
2492
|
if(-1===r)break
|
|
2468
2493
|
let i=r+t.length
|
|
2469
|
-
const u=Math.min(Math.floor(.5*t.length),200),h=Math.min(r+t.length+u,e.length),
|
|
2494
|
+
const u=Math.min(Math.floor(.5*t.length),200),h=Math.min(r+t.length+u,e.length),f=l.length
|
|
2470
2495
|
let y=!1
|
|
2471
2496
|
for(let t=i;h>=t;t++){const o=e.substring(r,t),i=n(o,a)
|
|
2472
|
-
if(i.length>
|
|
2497
|
+
if(i.length>f)break
|
|
2473
2498
|
if(i===l){c.push({line:s(e,r),actuallyMatched:o,matchType:"whitespace_normalized",startPos:r,endPos:t}),p=t,y=!0
|
|
2474
2499
|
break}}y||(p=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[]
|
|
2475
2500
|
const c=[],l=o(t),d=Date.now()
|
|
@@ -2481,12 +2506,12 @@ for(;;){if(p%100==0&&Date.now()-d>n){const r=Date.now()-d
|
|
|
2481
2506
|
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`)}p++
|
|
2482
2507
|
const r=e.indexOf(u,g)
|
|
2483
2508
|
if(-1===r)break
|
|
2484
|
-
const i=r+h,a=Math.min(t.length,300),
|
|
2485
|
-
let
|
|
2486
|
-
for(let t=i;
|
|
2509
|
+
const i=r+h,a=Math.min(t.length,300),m=Math.min(r+h+a,e.length)
|
|
2510
|
+
let f=!1
|
|
2511
|
+
for(let t=i;m>=t;t++){const n=e.substring(r,t),i=o(n)
|
|
2487
2512
|
if(i.length>h)break
|
|
2488
|
-
if(i===l){c.push({line:s(e,r),actuallyMatched:n,matchType:"whitespace_agnostic",startPos:r,endPos:t}),g=t,
|
|
2489
|
-
break}}
|
|
2513
|
+
if(i===l){c.push({line:s(e,r),actuallyMatched:n,matchType:"whitespace_agnostic",startPos:r,endPos:t}),g=t,f=!0
|
|
2514
|
+
break}}f||(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))
|
|
2490
2515
|
let o=e
|
|
2491
2516
|
for(const e of n)o=a(o,e,r)
|
|
2492
2517
|
return o},exports.findSimilarMatches=function(e,t,r=5,n=.3){const o=e.split("\n"),s=[]
|
|
@@ -2511,47 +2536,47 @@ let i=u.FileOperationPhase.VALIDATION
|
|
|
2511
2536
|
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}"}
|
|
2512
2537
|
try{const a=u.validateArgs(e,d.GetFileInfoSchema),{path:h}=a
|
|
2513
2538
|
n.info("Getting file info: "+h)
|
|
2514
|
-
const{normalizedPath:
|
|
2539
|
+
const{normalizedPath:m,fullPath:f}=u.validateAndNormalizePath(h,t)
|
|
2515
2540
|
i=u.FileOperationPhase.FILE_WRITE
|
|
2516
|
-
try{await c.default.access(
|
|
2541
|
+
try{await c.default.access(f)}catch(e){throw Error("Path not accessible: "+h)}const y=await c.default.stat(f),w=y.isFile()?l.default.extname(f).slice(1):"",k={path:m,type:y.isDirectory()?"directory":"file",size:y.size,sizeFormatted:(p=y.size,u.formatFileSize(p)),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},I=["File Information for: "+m,"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]
|
|
2517
2542
|
k.isFile&&w&&I.push("Extension: "+w)
|
|
2518
2543
|
const b=Date.now()-s
|
|
2519
|
-
return o.recordValue("get_file_info_time",b),o.incrementCounter("get_file_info_success",1),n.info("Successfully retrieved file info: "+
|
|
2544
|
+
return o.recordValue("get_file_info_time",b),o.incrementCounter("get_file_info_success",1),n.info("Successfully retrieved file info: "+m,{type:k.type,size:k.size,time:b}),{content:[{type:"text",text:I.join("\n")}]}}catch(t){const r=Date.now()-s
|
|
2520
2545
|
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,p}
|
|
2521
2546
|
const c=a(t(1943)),l=a(t(6928)),d=t(6183),u=i(t(5967)),h=t(8824)},3707(e,exports,t){"use strict"
|
|
2522
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQuickChange=async function(e,t,d,u,h,g,p){const
|
|
2547
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQuickChange=async function(e,t,d,u,h,g,p){const m=h.child({tool:"quick_edit"}),f=Date.now()
|
|
2523
2548
|
try{const y=u.getRequestClient(),w=u.getTaskClient(),k=u.getFileClient(),I=u.getToolRecordClient(),{title:b,description:v,...C}=e,_=e.comment||b
|
|
2524
|
-
|
|
2549
|
+
m.info("Starting quick_edit workflow",{title:b,operationType:t})
|
|
2525
2550
|
let E=!1
|
|
2526
2551
|
try{const e=await y.listRequests({limit:2,sortBy:"created_at",sortDirection:"desc"})
|
|
2527
|
-
e&&2===e.length&&e.every((e=>"quick-edit"===e.type))&&(E=!0,
|
|
2552
|
+
e&&2===e.length&&e.every((e=>"quick-edit"===e.type))&&(E=!0,m.info("Detected two consecutive quick-edits, will recommend normal request"))}catch(e){m.warn("Could not check recent requests for recommendation",{error:e})}m.debug("Creating quick_edit request")
|
|
2528
2553
|
const q=await y.createRequest({title:b,description:v,type:"quick-edit",acceptanceCriteria:["Quick change completed successfully"]})
|
|
2529
2554
|
if(!q||!q.id)throw Error("Failed to create request")
|
|
2530
2555
|
const S=q.id
|
|
2531
2556
|
let T
|
|
2532
|
-
|
|
2533
|
-
try{if(
|
|
2534
|
-
e.userChangesCommitted?
|
|
2535
|
-
|
|
2557
|
+
m.info("Created request",{requestId:S})
|
|
2558
|
+
try{if(m.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)
|
|
2559
|
+
e.userChangesCommitted?m.info("Committed user changes to main before quick-edit branch creation",{requestId:S,commitHash:e.commitHash?.substring(0,8)}):m.debug("No uncommitted changes found, proceeding with quick-edit")}catch(e){m.warn("Failed to commit user changes before quick-edit, proceeding anyway",{requestId:S,error:e instanceof Error?e.message:e+""})}else m.debug("No git instance available, skipping uncommitted changes check")
|
|
2560
|
+
m.debug("Creating task")
|
|
2536
2561
|
const e=await w.createTask({requestId:S,projectId:d.projectId,title:`Execute ${t} operation`,description:"Quick change: "+b})
|
|
2537
2562
|
if(!e||!e.id)throw Error("Failed to create task")
|
|
2538
2563
|
let v
|
|
2539
|
-
if(T=e.id,
|
|
2564
|
+
if(T=e.id,m.info("Created task",{taskId:T}),m.debug("Executing file operation",{operationType:t}),"write"===t)v=await(0,n.handleWriteFile)({taskId:T,...C,comment:_},d,k,w,I,y,h,g,p)
|
|
2540
2565
|
else if("replace"===t)v=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,I,y,h,g,p)
|
|
2541
2566
|
else{if("manage"!==t)throw new r.ValidationError("Unsupported operation type: "+t)
|
|
2542
|
-
v=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||b},d,w,I,y,u,h,g,p)}if(v.isError){
|
|
2543
|
-
try{await w.updateTaskStatus(T,"canceled"),
|
|
2544
|
-
P?
|
|
2545
|
-
try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${b}${P?" (partial success)":""}`},d,u,h,g),
|
|
2546
|
-
try{await w.updateTaskStatus(T,"completed"),
|
|
2567
|
+
v=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||b},d,w,I,y,u,h,g,p)}if(v.isError){m.error("File operation failed, cleaning up request and task",{requestId:S,taskId:T})
|
|
2568
|
+
try{await w.updateTaskStatus(T,"canceled"),m.info("Canceled task after operation failure",{taskId:T})}catch(e){m.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),m.info("Canceled request after operation failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),m.info("Cleaned up branch/worktree after operation failure",{requestId:S}))}catch(e){m.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${v.content[0].text}\n\nThe request (${S}) and task have been canceled and cleaned up.`}],isError:!0}}const q=v.content[0].text,P=q.includes("\u26a0\ufe0f Partial Success")||q.includes("\u274c Failed")||q.includes("\u274c 0 successful")
|
|
2569
|
+
P?m.warn("File operation completed with partial failures",{requestId:S}):m.info("File operation completed successfully"),m.debug("Completing task")
|
|
2570
|
+
try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${b}${P?" (partial success)":""}`},d,u,h,g),m.info("Task completed successfully",{taskId:T})}catch(e){m.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})
|
|
2571
|
+
try{await w.updateTaskStatus(T,"completed"),m.info("Task completed via direct updateTaskStatus call",{taskId:T})}catch(e){return m.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}}}m.debug("Completing request")
|
|
2547
2572
|
const j=P?`Quick change completed with partial success: ${b}. Some replacements failed - see details below.`:"Quick change completed: "+b,x=P?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
|
|
2548
2573
|
let R=!1
|
|
2549
2574
|
try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:j,acceptanceEvidence:[{evidence:x}],testVerification:void 0},d,u,h,g,p)
|
|
2550
|
-
if(e.isError)
|
|
2551
|
-
else{try{await y.updateRequest(S,{status:"completed",completionSummary:j}),
|
|
2575
|
+
if(e.isError)m.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text})
|
|
2576
|
+
else{try{await y.updateRequest(S,{status:"completed",completionSummary:j}),m.info("Request finalized to completed",{requestId:S})}catch(e){m.warn("Failed to finalize request to completed, may be stuck at ready_for_merge",{requestId:S,error:(0,l.getErrorMessage)(e)})}R=!0,m.info("Request completed successfully",{requestId:S})}}catch(e){m.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!R)try{m.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:j}),R=!0,m.info("Request completed successfully via direct API call",{requestId:S})}catch(e){return m.error("Direct request completion also failed",{requestId:S,error:e instanceof Error?e.message:e+""}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but request completion failed.\n\n**Request:** ${S}\n**Status:** Still in 'in_progress' - please complete manually\n\nThe file operation was successful, but we couldn't automatically complete the request. Please use the complete-request tool manually.`}],isError:!0}}const M=Date.now()-f
|
|
2552
2577
|
let O
|
|
2553
|
-
return
|
|
2554
|
-
return
|
|
2578
|
+
return m.info("Quick fix completed",{requestId:S,duration:M,hasPartialFailure:P}),O=P?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${b}\n**Operation:** ${t}\n**Duration:** ${M}ms\n**Status:** Some operations succeeded, some failed\n\nThe successful changes have been applied and automatically merged to main.\n**Active branch:** main\n\n**\u26a0\ufe0f Note:** This quick-fix had partial failures. See operation details below:\n\n`+q:`\u2705 Quick change completed successfully!\n\n**Request:** ${S}\n**Title:** ${b}\n**Operation:** ${t}\n**Duration:** ${M}ms\n\nThe change has been applied and automatically merged to main.\n**Active branch:** main`+(q.match(/\[RECORD:trec\d{6}\]/)?.[0]?"\n"+q.match(/\[RECORD:trec\d{6}\]/)?.[0]:""),E&&(O+="\n\n\u{1f4a1} **Recommendation:** You've created several quick-edits in a row. For better traceability and organization, consider creating a proper feature or bugfix request with multiple tasks for your next change."),{content:[{type:"text",text:O}]}}catch(e){if(m.error("Quick change workflow failed after request creation, cleaning up",{requestId:S,error:(0,l.getErrorMessage)(e)}),T)try{await w.updateTaskStatus(T,"canceled"),m.info("Canceled task after workflow failure",{taskId:T})}catch(e){m.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),m.info("Canceled request after workflow failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),m.info("Cleaned up branch/worktree after workflow failure",{requestId:S}))}catch(e){m.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}throw e}}catch(e){const t=Date.now()-f
|
|
2579
|
+
return m.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}}}
|
|
2555
2580
|
const r=t(9860),n=t(4079),o=t(9442),s=t(7684),i=t(355),a=t(5715),c=t(7478),l=t(8824)},3807(module){"use strict"
|
|
2556
2581
|
module.exports=require("simple-git")},3884(e,exports,t){"use strict"
|
|
2557
2582
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.middleware=exports.validateRequest=exports.authenticate=exports.corsOptions=exports.errorHandler=exports.requestLogger=void 0
|
|
@@ -2630,13 +2655,13 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
2630
2655
|
var t={}
|
|
2631
2656
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2632
2657
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2633
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,r,n,o,s,i,
|
|
2658
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,r,n,o,s,i,f,y,w){const k=f.child({tool:"write_file"}),I=y.startTimer("tool_execution_time"),b=Date.now()
|
|
2634
2659
|
let v,C,_=d.FileOperationPhase.VALIDATION
|
|
2635
2660
|
const E={toolName:"write_file",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"write-file",metricsPrefix:"write_file",successMessage:"Successfully wrote content",failureMessage:"Failed to write content"}
|
|
2636
|
-
try{const n=d.validateArgs(e,l.WriteFileSchema),{path:
|
|
2637
|
-
k.info("Writing content to "+(M?"document":"file"),{taskId:R,filePath:O?
|
|
2661
|
+
try{const n=d.validateArgs(e,l.WriteFileSchema),{path:m,documentId:q,content:S,format:T,append:P,comment:j}=n,{resolveActiveTaskId:x}=await Promise.resolve().then(t.bind(t,3451)),R=e.taskId||await x(r,o,f)||"untracked",M=!!q,O=!!m
|
|
2662
|
+
k.info("Writing content to "+(M?"document":"file"),{taskId:R,filePath:O?m:void 0,documentId:M?q:void 0,contentLength:"string"==typeof S?S.length:JSON.stringify(S).length,format:T,append:P,comment:j})
|
|
2638
2663
|
let $,D,A,F="",N=!1,L=!1
|
|
2639
|
-
const z=O?
|
|
2664
|
+
const z=O?m:void 0
|
|
2640
2665
|
if(M){if(r.apiClient)try{await(0,p.ensureDocumentNotLocked)(q,r.apiClient,k,y,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2641
2666
|
throw e}if(!r.documentFileManager)throw Error("Document file manager not available")
|
|
2642
2667
|
F=await r.documentFileManager.getDocumentAsFile(q)
|
|
@@ -2670,8 +2695,8 @@ Z=t.commitHash,ee=t.previousCommitHash,k.info("Changes committed to git via shar
|
|
|
2670
2695
|
re+=`**Content Length:** ${Y.length} characters\n`,O&&X&&(te||(re+=`**Branch:** ${X}\n`)),V.lockAcquired&&V.lockedRequestId&&!te&&(re+=`**Locked request:** ${V.lockedRequestId}\n`),O&&Z&&(re+=`**Commit Hash:** ${Z.substring(0,8)}\n`,ee&&(re+=`**Previous Commit:** ${ee.substring(0,8)}\n`)),C&&(re+=`[RECORD:${C}]\n`),M&&(re+=`\n**Document Update:** The document content has been updated and synced back to the tracking system. You can continue editing using other file modification tools with documentId \`${q}\`.`)
|
|
2671
2696
|
const ne=Date.now()
|
|
2672
2697
|
return k.info("Write operation completed successfully",{duration:ne-b,path:O?$:"document:"+q,contentLength:Y.length,wasCreated:N}),I({tool:"write_file",success:!0}),y.incrementCounter("write_file_total",1,{success:!0}),r.workspaceManager?.largeFileWarning&&(re+=r.workspaceManager.largeFileWarning,r.workspaceManager.largeFileWarning=""),{content:[{type:"text",text:re}]}}catch(t){const r=Date.now()-b
|
|
2673
|
-
if(k.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{path:e?.path,status:"failed",error:(0,
|
|
2674
|
-
const a=i(t(6928)),c=i(t(1943)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),
|
|
2698
|
+
if(k.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{path:e?.path,status:"failed",error:(0,m.getErrorMessage)(t),phase:_,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,m.getErrorMessage)(t)})}catch(e){}return I({tool:"write_file",success:!1}),y.incrementCounter("write_file_errors",1,{phase:_}),{content:[{type:"text",text:"\u274c **Write Operation Failed:** "+(0,m.getErrorMessage)(t)}],isError:!0}}}
|
|
2699
|
+
const a=i(t(6928)),c=i(t(1943)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),m=t(8824)},4139(e,exports){"use strict"
|
|
2675
2700
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ALCHEMY_DIR_NAME=exports.TOKEN_DIR_NAME=void 0,exports.TOKEN_DIR_NAME="alchemy-key",exports.ALCHEMY_DIR_NAME=".alchemy_lab"},4165(e,exports,t){"use strict"
|
|
2676
2701
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
2677
2702
|
const r=t(6183),n=t(4648)
|
|
@@ -2752,8 +2777,8 @@ a=e?.data||e}catch(e){const t=(0,s.getErrorMessage)(e)
|
|
|
2752
2777
|
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`
|
|
2753
2778
|
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")
|
|
2754
2779
|
let g="workspace-manager"
|
|
2755
|
-
const p=await e.getRequest(u),
|
|
2756
|
-
try{
|
|
2780
|
+
const p=await e.getRequest(u),m=p?.title||"Request "+u,f="resolving_conflicts"===p?.status
|
|
2781
|
+
try{f?(l.info("Merge retry (resolving_conflicts) \u2014 using -X theirs",{requestId:u}),c=await t.workspaceManager.completeRequest(u,m,{skipConflictDetection:!0}),g="retry-theirs"):(c=await t.workspaceManager.completeRequest(u,m),g=c.autoMergeInfo?.strategy||"workspace-manager"),l.info("Merge completed",{requestId:u,mergeCommitHash:c.mergeCommitHash,mergeMethod:g})}catch(r){if(r.conflictInfo){const o=r.conflictInfo,a=o.workingDirectory||t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||process.cwd(),c=(0,n.createConflictResolutionManager)(l,i,a,t.git),h=await c.handleConflicts(o)
|
|
2757
2782
|
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)
|
|
2758
2783
|
return d({success:!1,error:"merge_failure"}),{content:[{type:"text",text:"Merge failed: "+o}],isError:!0}}try{await i.proxyPost(`/api/projects/${t.projectId}/requests/${u}/finalize-completion`,{summary:p?.completionSummary||"Merged request "+u,acceptanceEvidence:h.map((e=>({evidence:e.evidence}))),mergeResult:{mergeCommitHash:c.mergeCommitHash,mergedFiles:c.mergedFiles,cleanedUp:c.cleanedUp,method:g}})}catch(e){const t=(0,s.getErrorMessage)(e)
|
|
2759
2784
|
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)
|
|
@@ -2792,19 +2817,19 @@ if(!r)return l({success:!1,error:"not_found"}),{content:[{type:"text",text:`Comm
|
|
|
2792
2817
|
try{return await s.proxyDelete(`/api/projects/${t.projectId}/check-commands/${r.id}`),i.info("Removed command",{name:r.name,id:r.id}),l({success:!0}),{content:[{type:"text",text:`Removed command **${r.name}**.`}]}}catch(e){return l({success:!1,error:"remove_failed"}),{content:[{type:"text",text:"Failed to remove command: "+(0,n.getErrorMessage)(e)}],isError:!0}}}if(!e.name){const e=h.map((e=>e.name)).join(", ")
|
|
2793
2818
|
return l({success:!1,error:"missing_name"}),{content:[{type:"text",text:"Error: `name` is required when running a command.\n\nAvailable commands: "+(e||"(none configured)")}],isError:!0}}const p=h.find((t=>t.name.toLowerCase()===e.name.toLowerCase()))
|
|
2794
2819
|
if(!p){const t=h.map((e=>e.name)).join(", ")
|
|
2795
|
-
return l({success:!1,error:"not_found"}),{content:[{type:"text",text:`Command "${e.name}" not found.\n\nAvailable commands: ${t||"(none configured)"}`}],isError:!0}}let
|
|
2796
|
-
e.grep&&(
|
|
2797
|
-
const
|
|
2798
|
-
i.info("Running command",{name:p.name,command:
|
|
2820
|
+
return l({success:!1,error:"not_found"}),{content:[{type:"text",text:`Command "${e.name}" not found.\n\nAvailable commands: ${t||"(none configured)"}`}],isError:!0}}let m=e.args?`${p.command} ${e.args}`:p.command
|
|
2821
|
+
e.grep&&(m=`${m} 2>&1 | grep -i ${JSON.stringify(e.grep)}`)
|
|
2822
|
+
const f=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
|
|
2823
|
+
i.info("Running command",{name:p.name,command:m,cwd:f})
|
|
2799
2824
|
let y="",w="",k=0,I=!1
|
|
2800
|
-
try{y=(0,r.execSync)(
|
|
2825
|
+
try{y=(0,r.execSync)(m,{cwd:f,timeout:1e3*(p.timeout||60),encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"win32"===process.platform?"cmd.exe":"/bin/sh",env:{...process.env,FORCE_COLOR:"0"}})||""}catch(e){k=e.status??1,y=e.stdout||"",w=e.stderr||"",e.killed&&(I=!0)}const b=8e3,v=4e3
|
|
2801
2826
|
y.length>b&&(y="\u2026"+y.slice(-b)),w.length>v&&(w="\u2026"+w.slice(-v))
|
|
2802
2827
|
const C=I?"TIMEOUT":null,_=[y,w].filter(Boolean).join("\n")||"(no output)"
|
|
2803
2828
|
let E
|
|
2804
|
-
if(c)try{const e=await c.createToolRecord({projectId:t.projectId,type:"run-command",metadata:{name:p.name,command:
|
|
2829
|
+
if(c)try{const e=await c.createToolRecord({projectId:t.projectId,type:"run-command",metadata:{name:p.name,command:m,exitCode:k,timedOut:I,status:I?"timeout":0===k?"success":"failed",timestamp:(new Date).toISOString()}})
|
|
2805
2830
|
E=e?.id}catch(e){i.debug("Failed to create tool record for command run",{error:(0,n.getErrorMessage)(e)})}l({success:!0})
|
|
2806
2831
|
const q=E?`\n[RECORD:${E}]`:""
|
|
2807
|
-
return{content:[{type:"text",text:`## ${p.name}${C?` \u2014 ${C} (killed after ${p.timeout}s)`:""}\n\`\`\`\n$ ${
|
|
2832
|
+
return{content:[{type:"text",text:`## ${p.name}${C?` \u2014 ${C} (killed after ${p.timeout}s)`:""}\n\`\`\`\n$ ${m}\n${_}\n\`\`\`\n\nExit code: ${k}${q}`}]}}catch(e){return l({success:!1,error:"api_error"}),{content:[{type:"text",text:"Failed to run command: "+(0,n.getErrorMessage)(e)}],isError:!0}}}
|
|
2808
2833
|
const r=t(5317),n=t(8824),o=t(6688)},4465(e,exports,t){"use strict"
|
|
2809
2834
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.SessionTagMappingClient=void 0
|
|
2810
2835
|
const r=t(7645),n=t(2161)
|
|
@@ -2845,9 +2870,9 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handlePlannerOps=
|
|
|
2845
2870
|
try{if(e?.request&&"object"==typeof e.request){const t=e.request
|
|
2846
2871
|
e.prompt=e.prompt||t.prompt,e.description=e.description||t.description,delete e.request}if(e?.list&&"object"==typeof e.list){const t=e.list
|
|
2847
2872
|
e.activeOnly=e.activeOnly??t.activeOnly,e.limit=e.limit??t.limit,delete e.list}!e?.operation&&e&&(e.prompt?e.operation="request":e.sessionId&&(e.operation="check-status")),e?.operation&&("request"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.limit):"check-status"===e.operation?(delete e.prompt,delete e.description,delete e.activeOnly,delete e.limit):"list"===e.operation&&(delete e.sessionId,delete e.prompt,delete e.description))
|
|
2848
|
-
const r=c.validateArgs(e,a.PlannerOpsSchema),{operation:p,sessionId:
|
|
2849
|
-
let
|
|
2850
|
-
switch(h.info("Processing planner_ops",{operation:p,sessionId:
|
|
2873
|
+
const r=c.validateArgs(e,a.PlannerOpsSchema),{operation:p,sessionId:m}=r
|
|
2874
|
+
let f
|
|
2875
|
+
switch(h.info("Processing planner_ops",{operation:p,sessionId:m}),p){case"request":{const e=await async function(e,t,r){if(!e)return"ask"
|
|
2851
2876
|
try{const n=r?.sessionId||d.sessionIdentity.getIdentity()?.sessionId
|
|
2852
2877
|
if(!n)return"ask"
|
|
2853
2878
|
const o=e.getCLISessionClient()
|
|
@@ -2863,16 +2888,16 @@ if("interactive"===n)return"interactive"}catch(e){t.warn("Failed to read project
|
|
|
2863
2888
|
if("ask"===e||"interactive"===e){h.info("Returning planner choice pending",{planningMode:e})
|
|
2864
2889
|
try{const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,t=o?.getSessionMessageClient()
|
|
2865
2890
|
if(t&&e){const n=await d.sessionIdentity.getParentSessionId(e,o,h),s=r.description||r.prompt
|
|
2866
|
-
await t.createQuestion({fromSessionId:e,toSessionId:n||void 0,questionType:"alternatives",question:"Planning requested: "+s,options:[{id:"auto",label:"Auto Plan",description:"Spawn an autonomous planner agent"},{id:"manual",label:"Manual Plan",description:"Open the interactive plan editor"},{id:"cancel",label:"Skip",description:"Dismiss this planning request"}],context:r.prompt,category:"action-required",priority:"high"}),h.info("planner-request: notification created",{fromSessionId:e})}else h.warn("planner-request: skipping notification",{hasClient:!!t,hasCallerSessionId:!!e})}catch(e){h.warn("planner-request: failed to create notification",{error:(0,l.getErrorMessage)(e)})}
|
|
2891
|
+
await t.createQuestion({fromSessionId:e,toSessionId:n||void 0,questionType:"alternatives",question:"Planning requested: "+s,options:[{id:"auto",label:"Auto Plan",description:"Spawn an autonomous planner agent"},{id:"manual",label:"Manual Plan",description:"Open the interactive plan editor"},{id:"cancel",label:"Skip",description:"Dismiss this planning request"}],context:r.prompt,category:"action-required",priority:"high"}),h.info("planner-request: notification created",{fromSessionId:e})}else h.warn("planner-request: skipping notification",{hasClient:!!t,hasCallerSessionId:!!e})}catch(e){h.warn("planner-request: failed to create notification",{error:(0,l.getErrorMessage)(e)})}f={content:[{type:"text",text:"Planning request submitted. The user will choose the planning approach. This is non-blocking \u2014 continue with your other work.\nPLANNER_CHOICE_PENDING|"+JSON.stringify({prompt:r.prompt,description:r.description})}]}
|
|
2867
2892
|
break}const n="auto-planner"
|
|
2868
|
-
if(h.info("Spawning planner",{planningMode:e,agent:n}),
|
|
2869
|
-
|
|
2893
|
+
if(h.info("Spawning planner",{planningMode:e,agent:n}),f=await(0,u.handleSpawn)({agent:n,prompt:r.prompt,title:r.description},t,h,o,s),!f.isError&&f.content.length>0){const t=f.content[0].text
|
|
2894
|
+
f.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":f=await(0,u.handleCheckStatus)(m,t,h,o)
|
|
2870
2895
|
break
|
|
2871
2896
|
case"list":const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,[n,a]=await Promise.all([(0,u.handleListSessions)(t,h,o,{activeOnly:r.activeOnly,limit:r.limit,agentType:"auto-planner",parentSessionId:e}),(0,u.handleListSessions)(t,h,o,{activeOnly:r.activeOnly,limit:r.limit,agentType:"planner",parentSessionId:e})]),c=n.content[0]?.text??"",g=a.content[0]?.text??""
|
|
2872
2897
|
if(c.trim()||g.trim()){const e=[]
|
|
2873
|
-
c.trim()&&e.push("## Auto-planner sessions\n"+c),g.trim()&&e.push("## Interactive plan sessions\n"+g),
|
|
2898
|
+
c.trim()&&e.push("## Auto-planner sessions\n"+c),g.trim()&&e.push("## Interactive plan sessions\n"+g),f={content:[{type:"text",text:e.join("\n\n")}]}}else f={content:[{type:"text",text:"No planning sessions found."}]}
|
|
2874
2899
|
break
|
|
2875
|
-
default:throw new i.ValidationError("Unknown operation: "+p)}return g({success:!0}),n.incrementCounter(`planner_ops_${p}_success`,1),
|
|
2900
|
+
default:throw new i.ValidationError("Unknown operation: "+p)}return g({success:!0}),n.incrementCounter(`planner_ops_${p}_success`,1),f}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}}}
|
|
2876
2901
|
const i=t(9860),a=t(6183),c=s(t(5967)),l=t(8824),d=t(6688),u=t(1725)},4600(e,exports,t){"use strict"
|
|
2877
2902
|
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"]})
|
|
2878
2903
|
let c="",l=""
|
|
@@ -2889,13 +2914,13 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
2889
2914
|
var t={}
|
|
2890
2915
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2891
2916
|
return o(t,e),t})
|
|
2892
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,r,n,o,s,g,p){const
|
|
2893
|
-
try{let
|
|
2894
|
-
try{
|
|
2895
|
-
return
|
|
2896
|
-
return
|
|
2897
|
-
try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:I}=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",
|
|
2898
|
-
|
|
2917
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,r,n,o,s,g,p){const m=s.child({tool:"file_recover"}),f=g.startTimer("tool_execution_time"),y=Date.now()
|
|
2918
|
+
try{let f
|
|
2919
|
+
try{f=i.FileRecoverSchema.parse(e)}catch(t){if(t instanceof a.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
2920
|
+
return m.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{path:w,commitHash:k,createBackup:I}=f,{resolveActiveTaskId:b}=await Promise.resolve().then(t.bind(t,3451)),v=e.taskId||await b(r,n,s)||"untracked"
|
|
2921
|
+
return m.info("Recovering file to previous version",{taskId:v,filePath:w,commitHash:k,createBackup:I}),await async function(e,t,r,n,o,s,i,a,g,p,m){let f
|
|
2922
|
+
try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:I}=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",m)
|
|
2923
|
+
f=I
|
|
2899
2924
|
let b,v=!1
|
|
2900
2925
|
try{await l.access(w),v=!0,n&&(b=`${w}.backup-${(new Date).toISOString().replace(/[:.]/g,"-")}`,await l.copyFile(w,b),a.info("Created backup",{originalPath:w,backupPath:b}))}catch{v=!1}const C=o.git
|
|
2901
2926
|
if(!C)throw Error("Git is not available")
|
|
@@ -2906,34 +2931,34 @@ if(t.includes("does not exist")||t.includes("not found")||t.includes("Path"))thr
|
|
|
2906
2931
|
throw Error(`Failed to retrieve file '${y}' from commit '${r}': ${t}`)}await l.writeFile(w,_,"utf8")
|
|
2907
2932
|
let E={}
|
|
2908
2933
|
try{const t=`Recover ${y} from ${r.substring(0,8)}`
|
|
2909
|
-
E=await d.commitToGit(e,y,
|
|
2934
|
+
E=await d.commitToGit(e,y,f,f,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(f)try{await i.updateToolRecord(f,{metadata:{path:y,status:"completed",recoveredLength:_.length,hadBackup:n&&v,backupPath:b,wasFileCreated:!v,processingTime:Date.now()-p,...E.commitHash&&{commitHash:E.commitHash,previousCommitHash:E.previousCommitHash||void 0}},note:"File recovered successfully from "+r.substring(0,8)})}catch(e){a.warn("Failed to update tool record",{recordError:e})}const q=v?"recovered":"created from recovery"
|
|
2910
2935
|
let S=`\u2705 **File ${q.charAt(0).toUpperCase()+q.slice(1)} Successfully**\n\n`
|
|
2911
|
-
return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&b&&(S+=`**Backup created:** ${c.basename(b)}\n`),S+="**Git status:** Recovery committed\n",S+="\u{1f4a1} **Tip:** The file has been restored to its state at the specified commit.",a.info("File recovery completed successfully",{path:y,commitHash:r,duration:Date.now()-p}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(v,w,k,I,r,n,o,
|
|
2912
|
-
return
|
|
2936
|
+
return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&b&&(S+=`**Backup created:** ${c.basename(b)}\n`),S+="**Git status:** Recovery committed\n",S+="\u{1f4a1} **Tip:** The file has been restored to its state at the specified commit.",a.info("File recovery completed successfully",{path:y,commitHash:r,duration:Date.now()-p}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(v,w,k,I,r,n,o,m,g,y,p)}catch(e){const t=Date.now()-y
|
|
2937
|
+
return m.error("Recovery operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),f({tool:"file_recover",success:!1}),g.incrementCounter("file_recover_errors",1),{content:[{type:"text",text:"\u274c **Recovery Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
|
|
2913
2938
|
const i=t(6183),a=t(1569),c=s(t(6928)),l=s(t(1943)),d=s(t(5967)),u=t(3922),h=t(8824)},4648(e,exports,t){"use strict"
|
|
2914
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,u,h,g,p,
|
|
2939
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,u,h,g,p,m){const f=g.child({tool:"request_operations"})
|
|
2915
2940
|
try{for(const t of["complete","verifyCriteria","merge","revert","search","list"])if(e&&"string"==typeof e[t])try{e[t]=JSON.parse(e[t])}catch{}if("complete"===e?.operation&&e?.summary&&!e?.complete&&(e.complete={summary:e.summary},delete e.summary),"complete"!==e?.operation||e?.complete||e?.summary||(e.complete={summary:""}),"merge"===e?.operation&&e?.verifications&&!e?.merge&&(e.merge={verifications:e.verifications},delete e.verifications),e?.merge&&Array.isArray(e.merge)&&(e.merge={verifications:e.merge}),"verify-criteria"===e?.operation&&(e.operation="merge",e.verifyCriteria&&!e.merge&&(e.merge=e.verifyCriteria,delete e.verifyCriteria)),"finalize"===e?.operation&&(e.operation="merge",e.merge||(e.merge={verifications:[]})),"revert"===e?.operation&&e?.reason&&!e?.revert&&(e.revert={reason:e.reason,confirmDestructive:e.confirmDestructive},delete e.reason,delete e.confirmDestructive),"search"===e?.operation&&e?.query&&!e?.search&&(e.search={query:e.query,searchIn:e.searchIn||"all",filters:e.filters},delete e.query,delete e.searchIn,delete e.filters),e?.operation){const t=e.operation,r=["complete","merge","revert","list","search","approve"],n={complete:"complete",merge:"merge",revert:"revert",list:"list",search:"search",approve:void 0,"get-info":void 0,"delete-empty":void 0}[t]
|
|
2916
2941
|
for(const t of r)t!==n&&delete e[t]}const y=r.RequestOperationsSchema.parse(e)
|
|
2917
2942
|
let{requestId:w}=y
|
|
2918
2943
|
const{operation:k}=y
|
|
2919
2944
|
if(!w){const{sessionIdentity:e}=await Promise.resolve().then(t.bind(t,6688)),r=u.currentSessionId
|
|
2920
|
-
if(r&&"__unknown__"!==r&&"__server__"!==r&&(w=await e.getSessionRequestId(h,
|
|
2945
|
+
if(r&&"__unknown__"!==r&&"__server__"!==r&&(w=await e.getSessionRequestId(h,f,r)||void 0),!w)return{content:[{type:"text",text:`Error: requestId is required for '${k}' and could not be resolved from session`}],isError:!0}}switch(f.info("Processing request operation",{requestId:w,operation:k}),k){case"complete":{f.info("Routing to complete-request handler")
|
|
2921
2946
|
const e={requestId:w,summary:y.complete.summary}
|
|
2922
|
-
return await(0,n.handleCompleteRequest)(e,u,h,g,p,
|
|
2923
|
-
case"approve":{
|
|
2947
|
+
return await(0,n.handleCompleteRequest)(e,u,h,g,p,m)}case"merge":return f.info("Routing to merge handler"),await(0,l.handleMergeRequest)({requestId:w,verifications:y.merge?.verifications||[]},u,h,g,p,m)
|
|
2948
|
+
case"approve":{f.info("Routing to approve-request handler")
|
|
2924
2949
|
const e={requestId:w}
|
|
2925
|
-
return await(0,c.handleApproveRequest)(e,u,h,g,p,
|
|
2950
|
+
return await(0,c.handleApproveRequest)(e,u,h,g,p,m)}case"revert":{f.info("Routing to revert-request handler")
|
|
2926
2951
|
const e={requestId:w,reason:y.revert.reason,confirmDestructive:y.revert.confirmDestructive}
|
|
2927
|
-
return await(0,o.handleRevertRequest)(e,u,h,g,p)}case"get-info":{
|
|
2952
|
+
return await(0,o.handleRevertRequest)(e,u,h,g,p)}case"get-info":{f.info("Routing to get-request-information handler")
|
|
2928
2953
|
const e={requestId:w}
|
|
2929
|
-
return await(0,s.handleGetRequestInformation)(e,u,h,g,p)}case"list":{
|
|
2954
|
+
return await(0,s.handleGetRequestInformation)(e,u,h,g,p)}case"list":{f.info("Routing to list-requests handler")
|
|
2930
2955
|
const e={filters:y.list?.filters}
|
|
2931
|
-
return await(0,i.handleListRequests)(e,u,h,g,p)}case"search":{
|
|
2956
|
+
return await(0,i.handleListRequests)(e,u,h,g,p)}case"search":{f.info("Routing to search-requests handler")
|
|
2932
2957
|
const e={search:y.search}
|
|
2933
|
-
return await(0,a.handleSearchRequests)(e,u,h,g,p)}case"delete-empty":if(
|
|
2958
|
+
return await(0,a.handleSearchRequests)(e,u,h,g,p)}case"delete-empty":if(f.info("Routing to delete-empty handler"),!w)return{content:[{type:"text",text:"\u274c **Request Operations Failed:** requestId is required for delete-empty"}],isError:!0}
|
|
2934
2959
|
try{const e=h.getProxyClient(),t=await e.proxyGet(`/api/projects/${u.projectId}/tasks`,{requestLocalId:w,limit:1}),r=t?.data||t||[]
|
|
2935
|
-
return(Array.isArray(r)?r.length:0)>0?{content:[{type:"text",text:`\u274c Cannot delete ${w}: it has tasks. Only empty requests (no tasks created) can be deleted.`}],isError:!0}:(await e.proxyDelete(`/api/projects/${u.projectId}/requests/${w}`),
|
|
2936
|
-
return
|
|
2960
|
+
return(Array.isArray(r)?r.length:0)>0?{content:[{type:"text",text:`\u274c Cannot delete ${w}: it has tasks. Only empty requests (no tasks created) can be deleted.`}],isError:!0}:(await e.proxyDelete(`/api/projects/${u.projectId}/requests/${w}`),f.info("Empty request deleted",{requestId:w}),{content:[{type:"text",text:`\u2705 Request ${w} deleted (had no tasks).`}]})}catch(e){return{content:[{type:"text",text:"\u274c **Failed to delete request:** "+(0,d.getErrorMessage)(e)}],isError:!0}}default:{const e="Unknown operation type: "+k
|
|
2961
|
+
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+""}),p.incrementCounter("request_operations_errors",1),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
|
|
2937
2962
|
const r=t(6183),n=t(5715),o=t(6416),s=t(5434),i=t(8037),a=t(233),c=t(1537),l=t(4306),d=t(8824)},4710(e,exports,t){"use strict"
|
|
2938
2963
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2939
2964
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectClient=void 0
|
|
@@ -3058,9 +3083,9 @@ var t={}
|
|
|
3058
3083
|
if(null!=e)for(var r=s(e),n=0;n<r.length;n++)"default"!==r[n]&&i(t,e,r[n])
|
|
3059
3084
|
return a(t,e),t})
|
|
3060
3085
|
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()
|
|
3061
|
-
try{const{path:i,lines:p,branch:
|
|
3062
|
-
c.info("Processing blame request",{filePath:i,lines:p,branch:
|
|
3063
|
-
const
|
|
3086
|
+
try{const{path:i,lines:p,branch:m}=e
|
|
3087
|
+
c.info("Processing blame request",{filePath:i,lines:p,branch:m})
|
|
3088
|
+
const f=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath,y=d.isAbsolute(i)?i:d.join(f,i),w=d.relative(f,y)
|
|
3064
3089
|
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
|
|
3065
3090
|
if(/^\d+$/.test(e)){const t=parseInt(e,10)
|
|
3066
3091
|
return{start:t,end:t}}const t=e.match(/^(\d+)-(\d+)$/)
|
|
@@ -3068,7 +3093,7 @@ if(t)return{start:parseInt(t[1],10),end:parseInt(t[2],10)}
|
|
|
3068
3093
|
if(e.match(/^(\d+(?:,\d+)+)$/)){const t=e.split(",").map((e=>parseInt(e,10)))
|
|
3069
3094
|
return{start:Math.min(...t),end:Math.max(...t)}}return null}(p),I=["blame","--porcelain"]
|
|
3070
3095
|
let b
|
|
3071
|
-
k&&I.push(`-L${k.start},${k.end}`),
|
|
3096
|
+
k&&I.push(`-L${k.start},${k.end}`),m&&I.push(m),I.push("--",w),c.debug("Executing git blame",{args:I})
|
|
3072
3097
|
try{if(!t.git)throw Error("Git context not available")
|
|
3073
3098
|
b=await t.git.raw(I)}catch(e){const t=(0,h.getErrorMessage)(e)
|
|
3074
3099
|
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")
|
|
@@ -3208,7 +3233,7 @@ var t={}
|
|
|
3208
3233
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3209
3234
|
return o(t,e),t})
|
|
3210
3235
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.testingDefs=void 0
|
|
3211
|
-
const i=s(t(6183)),a=t(2052),c=e=>(t,r)=>e(t,r.context,r.apiClient,r.logger,r.metrics)
|
|
3236
|
+
const i=s(t(6183)),a=t(2052),c=e=>(t,r)=>e(t,r.context,r.apiClient,r.logger,r.metrics,r.cliOrigin)
|
|
3212
3237
|
exports.testingDefs=[{name:"testing_process_list",description:"List all test processes for this project. Shows active/inactive status, command count, and scope.",schema:i.TestingProcessListSchema,annotations:{title:"List Test Processes",readOnlyHint:!0},readOnly:!0,handler:c(a.handleTestingProcessList)},{name:"testing_process_get",description:"Get detailed configuration of a test process including setup and test commands.",schema:i.TestingProcessGetSchema,annotations:{title:"Get Test Process",readOnlyHint:!0},readOnly:!0,handler:c(a.handleTestingProcessGet)},{name:"testing_process_create",description:"Create a new test process with optional setup commands and one or more test commands. Each command has a name, shell command, required flag, and timeout.",schema:i.TestingProcessCreateSchema,annotations:{title:"Create Test Process",readOnlyHint:!1},handler:c(a.handleTestingProcessCreate)},{name:"testing_process_update",description:"Update an existing test process. Can modify name, description, scope, active status, and test configuration.",schema:i.TestingProcessUpdateSchema,annotations:{title:"Update Test Process",readOnlyHint:!1},handler:c(a.handleTestingProcessUpdate)},{name:"testing_reference",description:"Get the test process design guide with patterns for Node.js, Python, Go, Rust, and monorepo setups.",schema:i.TestingReferenceSchema,annotations:{title:"Testing Reference",readOnlyHint:!0},readOnly:!0,handler:c(a.handleTestingReference)},{name:"execute_test_command",description:'Execute a specific command from a configured test process. Use commandName="setup" to run all setup commands, or specify a test command name to run it. Only commands defined in the test process can be executed.',schema:i.ExecuteTestCommandSchema,annotations:{title:"Execute Test Command",readOnlyHint:!1},handler:c(a.handleExecuteTestCommand)},{name:"report_test_results",description:"Report the results of a test run. Call this after running all test commands to record pass/fail status and per-command results. The test run is auto-discovered from the current request context.",schema:i.ReportTestResultsSchema,annotations:{title:"Report Test Results",readOnlyHint:!1},handler:c(a.handleReportTestResults)}]},5278(e,exports,t){"use strict"
|
|
3213
3238
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3214
3239
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.DocumentFileManager=void 0
|
|
@@ -3283,16 +3308,16 @@ const h=(0,o.extractDataFromResponse)(c,{logger:d,operationName:"getRequestInfor
|
|
|
3283
3308
|
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"})
|
|
3284
3309
|
const p=(0,o.extractArrayFromResponse)(l,{logger:d,operationName:"listTasksForRequest",defaultValue:[]})
|
|
3285
3310
|
d.info(`Successfully extracted ${p.length} tasks using data extraction utility`)
|
|
3286
|
-
const
|
|
3311
|
+
const m={pending:0,in_progress:0,blocked:0,ready_for_review:0,completed:0,reverted:0,total:p.length}
|
|
3287
3312
|
p.forEach((e=>{const t=e.status
|
|
3288
|
-
t in
|
|
3289
|
-
const
|
|
3290
|
-
|
|
3313
|
+
t in m&&m[t]++}))
|
|
3314
|
+
const f=g.acceptanceCriteria||[],y={unverified:0,partial:0,verified:0,partially_verified:0,total:f.length}
|
|
3315
|
+
f.forEach((e=>{const t=e.status||"unverified"
|
|
3291
3316
|
t in y&&y[t]++}))
|
|
3292
3317
|
let w=g.testVerification||null
|
|
3293
3318
|
const k=g.title,I=g.type
|
|
3294
|
-
let b=`# ${"feature"===I?"Feature":"quick-edit"===I?"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: ${
|
|
3295
|
-
return b+=`\n## Task Status\n- Pending: ${
|
|
3319
|
+
let b=`# ${"feature"===I?"Feature":"quick-edit"===I?"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: ${m.completed}/${m.total} completed (${Math.round(m.completed/m.total*100)||0}%)\n- Acceptance Criteria: ${y.verified}/${y.total} verified (${Math.round(y.verified/y.total*100)||0}%)\n`
|
|
3320
|
+
return b+=`\n## Task Status\n- Pending: ${m.pending}\n- In Progress: ${m.in_progress}\n- Blocked: ${m.blocked}\n- Ready for Review: ${m.ready_for_review}\n- Completed: ${m.completed}\n- Reverted: ${m.reverted}\n`,b+="\n## Tasks\n",0===p.length?b+="No tasks found for this request.\n":p.forEach((e=>{b+=`**[${e.id}]** ${e.title} (Status: ${e.status})\n`})),d.info(`Added task listing with ${p.length} tasks`),b+="\n## Acceptance Criteria\n",b+=(0,i.formatCriteriaWithHashes)(f)+"\n","ready_for_review"===g.status&&f.some((e=>"verified"!==e.status))&&(b+="\n> **Status: ready_for_review** \u2014 Use the merge operation to verify criteria and merge to main.\n"),w&&(b+=`\n## Test Coverage\n- Test Cases: ${w.totalTestCases||0}\n- Criteria Tested: ${w.criteriaTestedCount||0}/${y.total}\n`,w.criterionCoverage&&Array.isArray(w.criterionCoverage)&&(b+="\n### Detailed Test Coverage:\n",w.criterionCoverage.forEach((e=>{b+=`- Criterion ${e.criterionId}: ${e.coverage} coverage\n`})))),g.recentActivity&&Array.isArray(g.recentActivity)&&(b+="\n## Recent Activity\n",g.recentActivity.slice(0,5).forEach((e=>{const t=new Date(e.timestamp).toLocaleString()
|
|
3296
3321
|
b+=`- ${t}: ${e.description}\n`}))),u({success:!0}),{content:[{type:"text",text:b}]}}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}}}
|
|
3297
3322
|
const r=t(9860),n=t(5674),o=t(2960),s=t(8824),i=t(5454)},5454(e,exports){"use strict"
|
|
3298
3323
|
function t(e,t){let r=0
|
|
@@ -3381,12 +3406,12 @@ let l
|
|
|
3381
3406
|
try{const e=await a.proxyPost(`/api/projects/${t.projectId}/requests/${n}/validate-completion`,{sessionId:c})
|
|
3382
3407
|
l=e?.data||e}catch(e){const t=(0,s.getErrorMessage)(e)
|
|
3383
3408
|
return h.error("Server validation failed",{requestId:n,error:t}),g({success:!1,error:"validation_request_failed"}),{content:[{type:"text",text:"Failed to validate completion: "+t}],isError:!0}}if(!l.canComplete){let e=`Cannot complete request ${n}: ${l.reason}\n`
|
|
3384
|
-
return l.blockedByTasks&&l.blockedByTasks.length>0&&(e+="\n**Tasks that must be completed or canceled first:**\n",l.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (Status: ${t.status})\n`}))),l.lifoViolation&&(e+="\n**Requests that must be re-completed first (LIFO order):**\n",l.lifoViolation.blockingRequests.forEach(((t,r)=>{e+=`${r+1}. **${t.requestId}** - ${t.title} (Status: ${t.status})\n`}))),g({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}const d=a.getRequestClient(),p="auto-test-then-merge"===l.completionMode,
|
|
3385
|
-
try{await d.updateRequest(n,{status:
|
|
3386
|
-
return g({success:!1,error:"status_transition_failed"}),{content:[{type:"text",text:"Failed to transition request: "+t}],isError:!0}}let
|
|
3387
|
-
try{
|
|
3388
|
-
return g({success:!1,error:"fetch_request_failed"}),{content:[{type:"text",text:"Failed to fetch request criteria: "+t}],isError:!0}}const y=
|
|
3389
|
-
return g({success:!0}),p?{content:[{type:"text",text:`Request ${n} 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===y.length?{content:[{type:"text",text:`Request ${n} is ready. No acceptance criteria defined \u2014 call merge directly.`}]}:{content:[{type:"text",text:`Request ${n} completion started (${
|
|
3409
|
+
return l.blockedByTasks&&l.blockedByTasks.length>0&&(e+="\n**Tasks that must be completed or canceled first:**\n",l.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (Status: ${t.status})\n`}))),l.lifoViolation&&(e+="\n**Requests that must be re-completed first (LIFO order):**\n",l.lifoViolation.blockingRequests.forEach(((t,r)=>{e+=`${r+1}. **${t.requestId}** - ${t.title} (Status: ${t.status})\n`}))),g({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}const d=a.getRequestClient(),p="auto-test-then-merge"===l.completionMode,m=p?"ready_for_review":"ready_for_merge"
|
|
3410
|
+
try{await d.updateRequest(n,{status:m,completionSummary:o})}catch(e){const t=(0,s.getErrorMessage)(e)
|
|
3411
|
+
return g({success:!1,error:"status_transition_failed"}),{content:[{type:"text",text:"Failed to transition request: "+t}],isError:!0}}let f
|
|
3412
|
+
try{f=await d.getRequest(n)}catch(e){const t=(0,s.getErrorMessage)(e)
|
|
3413
|
+
return g({success:!1,error:"fetch_request_failed"}),{content:[{type:"text",text:"Failed to fetch request criteria: "+t}],isError:!0}}const y=f?.acceptanceCriteria||[]
|
|
3414
|
+
return g({success:!0}),p?{content:[{type:"text",text:`Request ${n} 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===y.length?{content:[{type:"text",text:`Request ${n} is ready. No acceptance criteria defined \u2014 call merge directly.`}]}:{content:[{type:"text",text:`Request ${n} completion started (${m}).\n\n## Next Step: Verify & Merge\n\n${(0,i.formatVerifyInstructions)(y)}\n\nUse the merge operation with your verification evidence to merge to main.`}]}}catch(r){let s="An unexpected error occurred",i=""
|
|
3390
3415
|
r instanceof n.ZodError?(s="Validation error",i=r.errors.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")):r instanceof Error?(s=r.message,i=r.stack||""):i=r+"",h.error("Complete request failed",{error:s,details:i})
|
|
3391
3416
|
try{await(0,o.createFailureToolRecord)("complete-request",r,{error:s,details:i,requestId:e?.requestId},a.getToolRecordClient(),h,l,{requestId:e?.requestId,projectId:t.projectId,note:"Failed to complete request"})}catch{}return l.startTimer("tool_execution_time")({success:!1,error:r instanceof Error?r.name:"unknown"}),{content:[{type:"text",text:"Error: "+s}],isError:!0}}}
|
|
3392
3417
|
const r=t(9860),n=t(1569),o=t(8616),s=t(8824),i=t(5454)},5767(e,exports,t){"use strict"
|
|
@@ -3412,7 +3437,7 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3412
3437
|
var t={}
|
|
3413
3438
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3414
3439
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3415
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDeleteFiles=async function(e,r,n,o,s,i){const
|
|
3440
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDeleteFiles=async function(e,r,n,o,s,i){const f=o.child({tool:"delete_files"}),y=Date.now()
|
|
3416
3441
|
let w,k,I=l.FileOperationPhase.VALIDATION
|
|
3417
3442
|
const b={toolName:"delete-files",operationName:"delete",fileOperationPhase:l.FileOperationPhase.FILE_WRITE,recordType:"delete-files",metricsPrefix:"delete_files",successMessage:"Successfully deleted files",failureMessage:"Failed to delete files"}
|
|
3418
3443
|
try{const u=n.getTaskClient(),v=n.getToolRecordClient(),C=n.getRequestClient(),_=l.validateArgs(e,c.DeleteFilesSchema),{paths:E,operations:q,comment:S}=_,{resolveActiveTaskId:T}=await Promise.resolve().then(t.bind(t,3451)),P=e.taskId||await T(r,n,o)||"untracked"
|
|
@@ -3423,42 +3448,42 @@ j=q.map((e=>{if(e.path)return{type:"file",target:e.path}
|
|
|
3423
3448
|
if(e.documentId)return{type:"document",target:e.documentId}
|
|
3424
3449
|
throw Error("Invalid operation: neither path nor documentId specified")}))}if(0===j.length)throw Error("At least one file or document must be specified for deletion")
|
|
3425
3450
|
const x=j.filter((e=>"file"===e.type)),R=j.filter((e=>"document"===e.type)),M=j.length
|
|
3426
|
-
|
|
3451
|
+
f.info("Starting mixed file and document deletion operation",{taskId:P,totalOperations:j.length,fileOperations:x.length,documentOperations:R.length,comment:S}),l.validateTaskIdFormat(P,f,s,b.metricsPrefix)
|
|
3427
3452
|
const O=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3428
|
-
|
|
3453
|
+
f.info("Initial branch context",{initialBranch:O.branch,initialRequestId:O.requestId,isMain:O.isMain})
|
|
3429
3454
|
const $=[]
|
|
3430
3455
|
for(const e of x){const{normalizedPath:t,fullPath:n}=l.validateAndNormalizePath(e.target,r)
|
|
3431
3456
|
$.push({normalized:t,full:n})}I=l.FileOperationPhase.TASK_VALIDATION,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3432
|
-
const D=$.length>0?$[0].normalized:"document_operations",A=await l.validateTaskId(P,D,u,
|
|
3433
|
-
L.taskPromoted&&
|
|
3434
|
-
const z=await l.ensureCorrectWorkspaceContext({taskPromoted:L.taskPromoted,requestId:F,context:r,operation:"delete-files",logger:
|
|
3457
|
+
const D=$.length>0?$[0].normalized:"document_operations",A=await l.validateTaskId(P,D,u,f,s,b.metricsPrefix),F=A?.requestId,N=await l.validateWorkItemStates(P,D,u,C,r,f,s,b.metricsPrefix),L=await l.autoPromoteTaskStatus(P,A.status,F,N.request?.status,D,u,C,f,s,b.metricsPrefix)
|
|
3458
|
+
L.taskPromoted&&f.info(`Auto-promoted task ${P} (${A.title||"Untitled"}) to in_progress for mixed operations`,{taskId:P,taskTitle:A.title,previousStatus:A.status,newStatus:L.newTaskStatus,totalOperations:j.length,fileOperations:x.length,documentOperations:R.length}),L.requestPromoted&&f.info(`Auto-promoted request ${F} to in_progress for file operations`,{requestId:F,previousStatus:N.request?.status,newStatus:L.newRequestStatus,triggeringTaskId:P})
|
|
3459
|
+
const z=await l.ensureCorrectWorkspaceContext({taskPromoted:L.taskPromoted,requestId:F,context:r,operation:"delete-files",logger:f,metrics:s,metricsPrefix:b.metricsPrefix})
|
|
3435
3460
|
if(!z.success){if(z.isLockConflict)return{content:[{type:"text",text:"\u274c "+z.error}],isError:!0}
|
|
3436
3461
|
throw Error(z.error)}let H={hadUserMods:!1,userModsCommitHash:void 0}
|
|
3437
|
-
if(r.git)try{
|
|
3438
|
-
const e=await(0,h.commitUserChangesBeforeToolOperation)(r.git,"delete-files",{requestId:F,taskId:P,workspaceManager:r.workspaceManager},
|
|
3439
|
-
e.userChangesCommitted&&(
|
|
3440
|
-
const{toolRecordId:B,localToolRecordId:U}=await l.createFileOperationRecords(P,F,r.projectId,b.recordType,D,{totalOperations:j.length,fileOperations:x.length,documentOperations:R.length,filePaths:$.map((e=>e.normalized)),documentIds:R.map((e=>e.target)),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},u,v,
|
|
3462
|
+
if(r.git)try{f.debug("[DELETE-FILES] Checking for user changes before mixed delete operations")
|
|
3463
|
+
const e=await(0,h.commitUserChangesBeforeToolOperation)(r.git,"delete-files",{requestId:F,taskId:P,workspaceManager:r.workspaceManager},f,s)
|
|
3464
|
+
e.userChangesCommitted&&(f.debug("[DELETE-FILES] User changes committed before mixed delete operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),f.info("User changes committed before mixed delete-files operation",{taskId:P,totalOperations:j.length,fileOperations:x.length,documentOperations:R.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),H={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){f.debug("[DELETE-FILES] Pre-tool commit failed, continuing with mixed delete operations",{error:e instanceof Error?e.message:e+""}),f.warn("Pre-tool user changes commit failed, continuing with mixed delete operation",{taskId:P,totalOperations:j.length,fileOperations:x.length,documentOperations:R.length,error:e instanceof Error?e.message:e+""})}f.debug("[DELETE-FILES] Proceeding with mixed delete operations",{totalOperations:j.length,fileDeletes:x.length,documentDeletes:R.length}),I=l.FileOperationPhase.RECORD_CREATION,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3465
|
+
const{toolRecordId:B,localToolRecordId:U}=await l.createFileOperationRecords(P,F,r.projectId,b.recordType,D,{totalOperations:j.length,fileOperations:x.length,documentOperations:R.length,filePaths:$.map((e=>e.normalized)),documentIds:R.map((e=>e.target)),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},u,v,f,s,b.metricsPrefix,i)
|
|
3441
3466
|
w=B,k=B,I=b.fileOperationPhase,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3442
3467
|
const G=[]
|
|
3443
3468
|
let W=0
|
|
3444
3469
|
R.length>0&&n.setProjectId(r.projectId)
|
|
3445
3470
|
for(let e=0;e<$.length;e++){const t=$[e],r={type:"file",path:t.normalized,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
3446
3471
|
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)
|
|
3447
|
-
await a.default.unlink(t.full),r.success=!0,W++,
|
|
3472
|
+
await a.default.unlink(t.full),r.success=!0,W++,f.info("Successfully deleted file",{path:t.normalized})}catch(e){r.error=(0,m.getErrorMessage)(e),f.warn("Failed to delete file "+t.normalized,{error:r.error})}G.push(r)}const V=R.length>0?n.getDocumentClient():null
|
|
3448
3473
|
for(const e of R){const t=e.target,r={type:"document",documentId:t,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
3449
3474
|
try{let e
|
|
3450
|
-
try{if(e=await V.getDocument(t),r.filename=e.filename,
|
|
3451
|
-
throw e}try{await(0,p.ensureDocumentNotLocked)(t,n,
|
|
3452
|
-
throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,
|
|
3453
|
-
r.success=!0,r.filename=o.filename,W++,
|
|
3475
|
+
try{if(e=await V.getDocument(t),r.filename=e.filename,f.info("Document found for archival",{documentId:e.id,filename:e.filename,type:e.type,requestId:e.requestId}),e.requestId)try{await(0,g.validateRequestStatusForDocumentOperation)(e.requestId,C,f,s,"delete-document")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
|
|
3476
|
+
throw e}try{await(0,p.ensureDocumentNotLocked)(t,n,f,s,"delete-document-archive")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
|
|
3477
|
+
throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,m.getErrorMessage)(e)}`)}const o=await V.archiveDocument(t)
|
|
3478
|
+
r.success=!0,r.filename=o.filename,W++,f.info("Document archived successfully",{documentId:o.id,filename:o.filename,archivedAt:o.archived_at})}catch(e){r.error=(0,m.getErrorMessage)(e),f.warn("Failed to delete document "+t,{error:r.error})}G.push(r)}const J=Date.now()-y
|
|
3454
3479
|
s.recordValue("delete_files_time",J),s.incrementCounter("delete_files_operations_total",M),s.incrementCounter("delete_files_operations_success",W),s.incrementCounter("delete_files_operations_failed",M-W),s.incrementCounter("delete_files_file_operations",x.length),s.incrementCounter("delete_files_document_operations",R.length),W===M?s.incrementCounter("delete_files_success",1):W>0?s.incrementCounter("delete_files_partial_success",1):s.incrementCounter("delete_files_total_failure",1)
|
|
3455
3480
|
let K=null
|
|
3456
3481
|
if(W>0){I=l.FileOperationPhase.GIT_COMMIT,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3457
3482
|
const e=G.filter((e=>e.success)),t=e.filter((e=>"file"===e.type)).length,n=e.filter((e=>"document"===e.type)).length
|
|
3458
3483
|
let o
|
|
3459
|
-
o=t>0&&n>0?`Delete ${t} files and ${n} documents - ${S}`:t>0?1===t?"Delete file - "+S:`Delete ${t} files - ${S}`:1===n?"Delete document - "+S:`Delete ${n} documents - ${S}`,K=await l.commitToGit(P,D,B,U,o,r,
|
|
3484
|
+
o=t>0&&n>0?`Delete ${t} files and ${n} documents - ${S}`:t>0?1===t?"Delete file - "+S:`Delete ${t} files - ${S}`:1===n?"Delete document - "+S:`Delete ${n} documents - ${S}`,K=await l.commitToGit(P,D,B,U,o,r,f,s,b.metricsPrefix)}I=l.FileOperationPhase.RECORD_UPDATE_SUCCESS,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3460
3485
|
const Y=G.filter((e=>e.success)),Q=G.filter((e=>!e.success))
|
|
3461
|
-
await l.updateFileOperationRecords(P,w,k,D,b.recordType,W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,{status:W===M?"completed":"partial_success",commitHash:K?.commitHash,previousCommitHash:K?.previousCommitHash,totalOperations:M,fileOperations:x.length,documentOperations:R.length,successCount:W,failureCount:M-W,successfulOperations:Y.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename}))),failedOperations:Q.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,error:e.error}))),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,u,v,
|
|
3486
|
+
await l.updateFileOperationRecords(P,w,k,D,b.recordType,W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,{status:W===M?"completed":"partial_success",commitHash:K?.commitHash,previousCommitHash:K?.previousCommitHash,totalOperations:M,fileOperations:x.length,documentOperations:R.length,successCount:W,failureCount:M-W,successfulOperations:Y.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename}))),failedOperations:Q.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,error:e.error}))),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,u,v,f,s,b.metricsPrefix)
|
|
3462
3487
|
const Z=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3463
3488
|
let X=""
|
|
3464
3489
|
if(W===M){const e=Y.filter((e=>"file"===e.type)).length,t=Y.filter((e=>"document"===e.type)).length
|
|
@@ -3467,11 +3492,11 @@ return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n"):"All delete operations
|
|
|
3467
3492
|
return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n")
|
|
3468
3493
|
if(K?.commitHash&&(X+="\nCommit: "+K.commitHash.substring(0,8)),Z.requestId&&(X+="\nBranch: "+Z.requestId),z.lockAcquired&&z.lockedRequestId){const e=r.workspaceManager?.getCurrentContext(r.currentSessionId)
|
|
3469
3494
|
e?.permanentBranch||(X+="\n\u{1f512} **Locked request:** "+z.lockedRequestId)}return{content:[{type:"text",text:X}],isError:0===W}}catch(t){if(e.taskId&&n)try{const o=n.getToolRecordClient(),s=t instanceof d.NotFoundError||t instanceof d.ValidationError||t instanceof u.ZodError
|
|
3470
|
-
await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:r.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,
|
|
3471
|
-
if(s.recordValue("delete_files_time",o),s.incrementCounter("delete_files_errors",1),
|
|
3495
|
+
await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:r.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,m.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:I,attemptedTaskId:e.taskId,taskIdValidationFailed:s},note:"Failed to delete files - "+(0,m.getErrorMessage)(t)})}catch(t){f.error("Failed to create failure record for delete-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0})}const o=Date.now()-y
|
|
3496
|
+
if(s.recordValue("delete_files_time",o),s.incrementCounter("delete_files_errors",1),f.error("Error in delete-files operation:",{error:(0,m.getErrorMessage)(t),time:o}),(w||k)&&e.taskId){I=l.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
3472
3497
|
try{const r=n.getTaskClient(),o=n.getToolRecordClient()
|
|
3473
|
-
await l.updateFileOperationRecords(e.taskId,w,k,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",b.recordType,"Failed to delete operations",{status:"failed",error:(0,
|
|
3474
|
-
const a=i(t(1943)),c=t(6183),l=s(t(5967)),d=t(9860),u=t(1569),h=t(7478),g=t(5003),p=t(9949),
|
|
3498
|
+
await l.updateFileOperationRecords(e.taskId,w,k,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",b.recordType,"Failed to delete operations",{status:"failed",error:(0,m.getErrorMessage)(t),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment},"Failed to delete operations",r,o,f,s,b.metricsPrefix)}catch(t){f.error("Failed to update record with failure status",{taskId:e.taskId,recordId:w,error:t instanceof Error?t.message:t+""})}}return l.handleFileOperationError(t,I,f,s,e,b)}}
|
|
3499
|
+
const a=i(t(1943)),c=t(6183),l=s(t(5967)),d=t(9860),u=t(1569),h=t(7478),g=t(5003),p=t(9949),m=t(8824)},5997(e,exports,t){"use strict"
|
|
3475
3500
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
3476
3501
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
3477
3502
|
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=[]
|
|
@@ -3536,7 +3561,7 @@ const n=await this.requestWithRetry("POST","/api/files/recover",t)
|
|
|
3536
3561
|
if(!(0,i.safeGetResponseData)(n,null))throw new r.ServiceError("Empty response when recovering file")
|
|
3537
3562
|
const o=(0,i.safeGetResponseData)(n,{success:!0,path:e.path,commitHash:e.commitHash,backupPath:void 0})
|
|
3538
3563
|
return this.logger.info("Successfully recovered file "+e.path,{path:o.path,commitHash:o.commitHash,backupPath:o.backupPath}),o}catch(t){throw this.logger.error("Failed to recover file "+e.path,{path:e.path,commitHash:e.commitHash,error:t instanceof Error?t.stack:t+""}),t}}}exports.FileOperationsClient=a},6183(e,exports,t){"use strict"
|
|
3539
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranchSchema=exports.PlanWriteSchema=exports.PlanReadSchema=exports.DocumentOperationsSchema=exports.SearchDocumentsSchema=exports.CreateDocumentSchema=exports.ReplaceLinesSchema=exports.InsertLinesSchema=exports.SwitchToRequestBranchSchema=exports.PlannerOpsSchema=exports.SpecialistOpsSchema=exports.SubagentOperationsSchema=exports.TaskOperationsSchema=exports.CompleteTaskSchema=exports.GetTaskInformationSchema=exports.GetRequestInformationSchema=exports.ListRequestsSchema=exports.ListTasksSchema=exports.SearchSchema=exports.QueryHistorySchema=exports.FileRecoverSchema=exports.FileHistorySchema=exports.DeleteFilesSchema=exports.DeleteFileSchema=exports.ReplaceInFilesSchema=exports.ReplaceStringsSchema=exports.ReplaceStringSchema=exports.MoveFilesSchema=exports.CreateDirectorySchema=exports.GetFileInfoSchema=exports.ListDirectorySchema=exports.ReadFilesSchema=exports.ViewAssetSchema=exports.WriteFileSchema=exports.UpdateTaskStatusSchema=exports.CreateTaskSchema=exports.CreateRequestSchema=exports.CompleteRequestSchema=exports.ExecutedTestSchema=exports.TestVerificationSchema=exports.TestDefinitionSchema=exports.AcceptanceCriterionSchema=exports.RecordTypeEnum=exports.EvidenceTypeEnum=exports.CriterionStatusEnum=exports.RequestStatusEnum=exports.TaskStatusEnum=exports.RequestTypeEnum=exports.TestCoverageTypeEnum=exports.CompletionStatusEnum=void 0,exports.UpdateSpecializationSchema=exports.SessionMessageOperationsSchema=exports.ReportTestResultsSchema=exports.CommandsSchema=exports.ExecuteTestCommandSchema=exports.TestingReferenceSchema=exports.TestingProcessUpdateSchema=exports.TestingProcessCreateSchema=exports.TestingProcessGetSchema=exports.TestingProcessListSchema=exports.MetaReferenceSchema=exports.MetaAgentListSchema=exports.MetaWorkflowRemoveRecipeSchema=exports.MetaWorkflowAddRecipeSchema=exports.MetaHookCreateSchema=exports.MetaHookListSchema=exports.MetaRecipeRemoveHookSchema=exports.MetaRecipeAddHookSchema=exports.MetaRecipeCreateSchema=exports.MetaRecipeGetSchema=exports.MetaRecipeListSchema=exports.MetaWorkflowUpdateSchema=exports.MetaWorkflowCreateSchema=exports.MetaWorkflowGetSchema=exports.MetaWorkflowListSchema=exports.GenerateRequestJournalSchema=exports.QuickManageSchema=exports.QuickReplaceSchema=exports.QuickWriteSchema=exports.RequestOperationsSchema=exports.ManageFilesSchema=exports.ModifyFileSchema=exports.RevertRequestSchema=exports.SwitchToBranchSchema=void 0
|
|
3564
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranchSchema=exports.PlanWriteSchema=exports.PlanReadSchema=exports.DocumentOperationsSchema=exports.SearchDocumentsSchema=exports.CreateDocumentSchema=exports.ReplaceLinesSchema=exports.InsertLinesSchema=exports.SwitchToRequestBranchSchema=exports.PlannerOpsSchema=exports.SpecialistOpsSchema=exports.SubagentOperationsSchema=exports.TaskOperationsSchema=exports.CompleteTaskSchema=exports.GetTaskInformationSchema=exports.GetRequestInformationSchema=exports.ListRequestsSchema=exports.ListTasksSchema=exports.SearchSchema=exports.QueryHistorySchema=exports.FileRecoverSchema=exports.FileHistorySchema=exports.DeleteFilesSchema=exports.DeleteFileSchema=exports.ReplaceInFilesSchema=exports.ReplaceStringsSchema=exports.ReplaceStringSchema=exports.MoveFilesSchema=exports.CreateDirectorySchema=exports.GetFileInfoSchema=exports.ListDirectorySchema=exports.ReadFilesSchema=exports.ViewAssetSchema=exports.WriteFileSchema=exports.UpdateTaskStatusSchema=exports.CreateTaskSchema=exports.CreateRequestSchema=exports.CompleteRequestSchema=exports.ExecutedTestSchema=exports.TestVerificationSchema=exports.TestDefinitionSchema=exports.AcceptanceCriterionSchema=exports.RecordTypeEnum=exports.EvidenceTypeEnum=exports.CriterionStatusEnum=exports.RequestStatusEnum=exports.TaskStatusEnum=exports.RequestTypeEnum=exports.TestCoverageTypeEnum=exports.CompletionStatusEnum=void 0,exports.CommitToViewedSessionSchema=exports.UpdateSpecializationSchema=exports.SessionMessageOperationsSchema=exports.ReportTestResultsSchema=exports.CommandsSchema=exports.ExecuteTestCommandSchema=exports.TestingReferenceSchema=exports.TestingProcessUpdateSchema=exports.TestingProcessCreateSchema=exports.TestingProcessGetSchema=exports.TestingProcessListSchema=exports.MetaReferenceSchema=exports.MetaAgentListSchema=exports.MetaWorkflowRemoveRecipeSchema=exports.MetaWorkflowAddRecipeSchema=exports.MetaHookCreateSchema=exports.MetaHookListSchema=exports.MetaRecipeRemoveHookSchema=exports.MetaRecipeAddHookSchema=exports.MetaRecipeCreateSchema=exports.MetaRecipeGetSchema=exports.MetaRecipeListSchema=exports.MetaWorkflowUpdateSchema=exports.MetaWorkflowCreateSchema=exports.MetaWorkflowGetSchema=exports.MetaWorkflowListSchema=exports.GenerateRequestJournalSchema=exports.QuickManageSchema=exports.QuickReplaceSchema=exports.QuickWriteSchema=exports.RequestOperationsSchema=exports.ManageFilesSchema=exports.ModifyFileSchema=exports.RevertRequestSchema=exports.SwitchToBranchSchema=void 0
|
|
3540
3565
|
const r=t(1569),n=t(8955),o=r.z.string().refine((e=>!(!e||!/^tas\d{6}$/.test(e)&&!/^req\d{6}#\d+$/.test(e))),{message:"Task ID must be req######+#NN (e.g. req000005#03) or tas###### format (e.g. tas000001)."}),s=r.z.string().refine((e=>!!e&&/^req\d{6}$/.test(e)),{message:"Request ID must match format: req###### (e.g. req000001)"}),i=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^(doc|plan|jour)\d{6}$/.test(e))),{message:"Document ID must match format: doc_[26 alphanumeric] (ULID) or doc######/plan######/jour###### (local ID)"})
|
|
3541
3566
|
exports.CompletionStatusEnum=r.z.enum(["complete","incomplete","partial"]),exports.TestCoverageTypeEnum=r.z.enum(["unit","e2e","integration","manual"]),exports.RequestTypeEnum=r.z.enum(["feature","bugfix","quick-edit"]),exports.TaskStatusEnum=r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]),exports.RequestStatusEnum=r.z.enum(["open","in_progress","ready_for_review","ready_for_merge","completed","canceled","reverted","conflicted"]),exports.CriterionStatusEnum=r.z.enum(["unverified","verified"]),exports.EvidenceTypeEnum=r.z.enum(["test","manual","other"]),exports.RecordTypeEnum=r.z.enum(["write","modify","blocker","resolution","discovery","test","delete"]),exports.AcceptanceCriterionSchema=r.z.object({description:r.z.string(),status:r.z.enum(["unverified","verified"]).default("unverified"),evidence:r.z.string().nullable().optional(),evidenceType:r.z.enum(["test","manual","other"]).nullable().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.TestDefinitionSchema=r.z.object({id:r.z.string(),description:r.z.string(),status:exports.CompletionStatusEnum,coverageType:exports.TestCoverageTypeEnum,accepts:r.z.array(r.z.string())}),exports.TestVerificationSchema=r.z.object({criteria:r.z.array(r.z.string()),tests:r.z.array(r.z.string()),coverageType:exports.TestCoverageTypeEnum,coverageRatio:r.z.number(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.ExecutedTestSchema=r.z.object({id:r.z.string(),testId:r.z.string(),status:exports.CompletionStatusEnum,results:r.z.string(),coverage:r.z.array(r.z.string()),executedAt:r.z.string()}),exports.CompleteRequestSchema=r.z.object({status:exports.RequestStatusEnum,acceptanceCriteria:r.z.array(exports.AcceptanceCriterionSchema),testVerification:exports.TestVerificationSchema.optional(),completionSummary:r.z.string().optional()}),exports.CreateRequestSchema=r.z.object({title:r.z.string(),type:r.z.enum(["feature","bugfix"]),description:r.z.string(),acceptanceCriteria:r.z.array(r.z.string()),planDocumentId:r.z.string().optional()}),exports.CreateTaskSchema=r.z.object({requestId:s,title:r.z.string(),description:r.z.string()}),exports.UpdateTaskStatusSchema=r.z.object({taskId:o,status:exports.TaskStatusEnum,note:r.z.string()}),exports.WriteFileSchema=r.z.object({path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional(),comment:r.z.string()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}),exports.ViewAssetSchema=r.z.object({filename:r.z.string().describe("The asset filename (e.g., 01JMXYZ.png)")}),exports.ReadFilesSchema=r.z.object({paths:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),lines:r.z.string().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),encoding:r.z.enum(["utf8","utf-8","ascii","binary"]).optional()}),exports.ListDirectorySchema=r.z.object({path:r.z.string(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}),exports.GetFileInfoSchema=r.z.object({path:r.z.string()}),exports.CreateDirectorySchema=r.z.object({path:r.z.string(),comment:r.z.string().optional()}),exports.MoveFilesSchema=r.z.object({operations:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()})),comment:r.z.string()}),exports.ReplaceStringSchema=r.z.object({path:r.z.string(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional(),comment:r.z.string()}),exports.ReplaceStringsSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceInFilesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1,"old string cannot be empty"),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1,"At least one replacement required"),fuzzy_match:r.z.boolean().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"Either path or documentId is required, but not both"})).min(1,"At least one operation required"),fuzzy_match:r.z.boolean().optional().default(!0),comment:r.z.string()}),exports.DeleteFileSchema=r.z.object({path:r.z.string(),comment:r.z.string()}),exports.DeleteFilesSchema=r.z.object({paths:r.z.array(r.z.string()).optional(),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})).optional(),comment:r.z.string()}).refine((e=>e.paths&&!e.operations||!e.paths&&e.operations),{message:"paths or operations required"}).refine((e=>e.paths?.length||e.operations?.length),{message:"path/operation required"}),exports.FileHistorySchema=r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}),exports.FileRecoverSchema=r.z.object({path:r.z.string(),commitHash:r.z.string(),createBackup:r.z.boolean().default(!0)}),exports.QueryHistorySchema=r.z.object({queryType:r.z.enum(["file-history","request-file-history","recover","blame"],{errorMap(){return{message:"Invalid queryType. Valid options: file-history, request-file-history, recover, blame"}}}),fileHistory:r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}).optional(),requestHistory:r.z.object({requestId:s,detailLevel:r.z.enum(["summary","detailed"]).default("summary"),taskId:o.optional(),showDiff:r.z.boolean().optional(),fileFilter:r.z.string().optional()}).optional(),recover:r.z.object({path:r.z.string(),commitHash:r.z.string().optional(),createBackup:r.z.boolean().default(!0)}).optional(),blame:r.z.object({path:r.z.string(),lines:r.z.string().optional(),branch:r.z.string().optional()}).optional()}).refine((e=>"file-history"===e.queryType?e.fileHistory&&!e.requestHistory&&!e.recover:"request-file-history"===e.queryType?e.requestHistory&&!e.fileHistory&&!e.recover:"recover"===e.queryType?e.recover&&!e.fileHistory&&!e.requestHistory&&!e.blame:"blame"===e.queryType&&e.blame&&!e.fileHistory&&!e.requestHistory&&!e.recover),{message:"Invalid query data"}),exports.SearchSchema=r.z.object({needle:r.z.string().optional(),directory:r.z.string().optional(),options:r.z.object({caseSensitive:r.z.boolean().optional(),fileExtension:r.z.string().optional(),maxResults:r.z.number().optional(),useRegex:r.z.boolean().optional(),searchIn:r.z.enum(["content","filename","both"]).default("content").optional(),contextLines:r.z.number().min(0).max(10).optional(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}).optional()}),exports.ListTasksSchema=r.z.object({requestId:s,filters:r.z.object({status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.ListRequestsSchema=r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["open","in_progress","ready_for_review","completed","canceled"]).optional(),planDocumentId:r.z.string().optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.GetRequestInformationSchema=r.z.object({requestId:s}),exports.GetTaskInformationSchema=r.z.object({taskId:o}),exports.CompleteTaskSchema=r.z.object({taskId:o,summary:r.z.string()}),exports.TaskOperationsSchema=r.z.object({operation:r.z.enum(["create","complete","get-info","list"]),taskId:o.optional(),requestId:s.optional(),title:r.z.string().optional(),description:r.z.string().optional(),summary:r.z.string().optional(),status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).superRefine(((e,t)=>{"create"!==e.operation||e.requestId||t.addIssue({code:"custom",message:'requestId is required for create. Example: { "operation": "create", "requestId": "req000001", "title": "...", "description": "..." }'}),"create"!==e.operation||e.title||t.addIssue({code:"custom",message:"title is required for create."}),"create"!==e.operation||e.description||t.addIssue({code:"custom",message:"description is required for create."}),"complete"!==e.operation||e.taskId||t.addIssue({code:"custom",message:'taskId is required for complete. Example: { "operation": "complete", "taskId": "req000001#01", "summary": "..." }'}),"complete"!==e.operation||e.summary||t.addIssue({code:"custom",message:"summary is required for complete."}),"get-info"!==e.operation||e.taskId||t.addIssue({code:"custom",message:'taskId is required for get-info. Example: { "operation": "get-info", "taskId": "req000001#01" }'}),"list"!==e.operation||e.requestId||t.addIssue({code:"custom",message:'requestId is required for list. Example: { "operation": "list", "requestId": "req000001" }'})}))
|
|
3542
3567
|
const a=r.z.string().min(1).describe("OpenCode session ID")
|
|
@@ -3547,7 +3572,7 @@ exports.PlanReadSchema=r.z.object({operation:r.z.enum(["get","get-active","list"
|
|
|
3547
3572
|
const r=e.operation,n={complete:{field:"complete",hint:'Provide: { complete: { summary: "..." } }'},merge:{field:"merge",hint:'Provide: { merge: { verifications: [{key: "1a", evidence: "..."}] } }'},revert:{field:"revert",hint:'Provide: { revert: { reason: "..." } }'},search:{field:"search",hint:'Provide: { search: { query: "..." } }'}}[r]
|
|
3548
3573
|
n&&!e[n.field]&&t.addIssue({code:"custom",message:`'${r}' operation requires '${n.field}' data. ${n.hint}`})})),exports.QuickWriteSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional()}),exports.QuickReplaceSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1),fuzzy_match:r.z.boolean().optional()})).min(1),fuzzy_match:r.z.boolean().optional(),comment:r.z.string().min(1,"Comment describing the change is required")}),exports.QuickManageSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}))}).optional()})).min(1)}),exports.GenerateRequestJournalSchema=r.z.object({requestId:r.z.string().regex(/^req[_\d].+$/,"Invalid request ID format. Expected format: req_[26 chars] or req######")}),exports.MetaWorkflowListSchema=r.z.object({}),exports.MetaWorkflowGetSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to retrieve")}),exports.MetaWorkflowCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the workflow"),shortName:r.z.string().min(1).max(10).describe("Short display name (required, max 10 chars)"),description:r.z.string().optional().describe("Description of what the workflow does"),documentation:r.z.string().optional().describe("Detailed documentation"),defaultAgent:r.z.string().optional().describe("Default agent template to use"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior: auto-merge (default), auto-test-then-merge, or manual-review"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaWorkflowUpdateSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to update"),name:r.z.string().min(1).optional().describe("New name"),shortName:r.z.string().max(10).optional().describe("New short name (max 10 chars)"),description:r.z.string().optional().describe("New description"),documentation:r.z.string().optional().describe("New documentation"),defaultAgent:r.z.string().optional().describe("New default agent"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaRecipeListSchema=r.z.object({}),exports.MetaRecipeGetSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to retrieve")}),exports.MetaRecipeCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the recipe"),description:r.z.string().optional().describe("Description of what the recipe does"),documentation:r.z.string().optional().describe("Detailed documentation")}),exports.MetaRecipeAddHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to add the hook to"),hookId:r.z.string().describe("Hook template ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the recipe (0-based, appended if omitted)")}),exports.MetaRecipeRemoveHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to remove the hook from"),hookId:r.z.string().describe("Hook template ID to remove")}),exports.MetaHookListSchema=r.z.object({}),exports.MetaHookCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the hook"),description:r.z.string().optional().describe("Description of what the hook does"),eventType:r.z.string().describe("Event type that triggers this hook (e.g., session_idle, request_completed, custom:plan_ready)"),category:r.z.enum(["alchemy","session","message","editing","reading","file_management","documents","history","tool"]).default("session").describe("Hook category"),agent:r.z.string().describe("Agent template to execute when hook fires"),promptTemplate:r.z.string().describe("Prompt template with {{variable}} substitution"),condition:r.z.record(r.z.any()).optional().describe("Condition object for filtering when hook fires"),executionMode:r.z.enum(["same_session","sub_agent","background","notification","direct_report"]).default("background").describe("How to execute the hook"),timing:r.z.enum(["before","after"]).default("after").describe("When to fire relative to the event"),maxIterations:r.z.number().int().min(1).optional().describe("Maximum times to fire per session"),emitEvent:r.z.string().optional().describe("Custom event to emit on completion"),emitEventOnCondition:r.z.union([r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}),r.z.array(r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}))]).optional().describe("Conditional event emission based on output")}),exports.MetaWorkflowAddRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to add the recipe to"),recipeId:r.z.string().describe("Recipe ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the workflow (0-based, appended if omitted)")}),exports.MetaWorkflowRemoveRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to remove the recipe from"),recipeId:r.z.string().describe("Recipe ID to remove")}),exports.MetaAgentListSchema=r.z.object({}),exports.MetaReferenceSchema=r.z.object({}),exports.TestingProcessListSchema=r.z.object({}),exports.TestingProcessGetSchema=r.z.object({processId:r.z.string().describe("Test process ID to retrieve")})
|
|
3549
3574
|
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)")})
|
|
3550
|
-
exports.TestingProcessCreateSchema=r.z.object({name:r.z.string().min(1).describe("Name for the test process"),description:r.z.string().optional().describe("Description of what this process verifies"),scope:r.z.string().optional().describe('Path prefix for monorepo scoping (e.g., "packages/api/"). Omit for global.'),setup:r.z.array(r.z.string()).optional().describe('Commands to prepare the environment (e.g., ["ln -s ../../node_modules node_modules"])'),commands:r.z.array(l).min(1).describe("Test commands to execute in order"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingProcessUpdateSchema=r.z.object({processId:r.z.string().describe("Test process ID to update"),name:r.z.string().min(1).optional().describe("New name"),description:r.z.string().optional().describe("New description"),scope:r.z.string().nullable().optional().describe("New scope (null to remove)"),isActive:r.z.boolean().optional().describe("Enable or disable the process"),setup:r.z.array(r.z.string()).optional().describe("New setup commands (replaces existing)"),commands:r.z.array(l).optional().describe("New test commands (replaces existing)"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingReferenceSchema=r.z.object({}),exports.ExecuteTestCommandSchema=r.z.object({processId:r.z.string().describe("Test process ID containing the command"),commandName:r.z.string().describe('Name of the test command to run, or "setup" to run all setup commands in sequence')}),exports.CommandsSchema=r.z.object({operation:r.z.enum(["run","list","add","remove"]).default("run").describe('"run" to execute a command, "list" to see available commands, "add" to register a new command, "remove" to delete one'),name:r.z.string().optional().describe('Command name (required for "run", "add", and "remove")'),args:r.z.string().optional().describe('Additional arguments appended to the base command (optional, for "run")'),grep:r.z.string().optional().describe('Filter output through grep (optional, for "run"). Pipes command output through grep -i with this pattern.'),command:r.z.string().optional().describe('Shell command to register (required for "add", e.g. "tsc --noEmit")'),description:r.z.string().optional().describe('What this command verifies (optional, for "add")'),timeout:r.z.number().optional().describe('Timeout in seconds (optional, for "add", default 60)')}),exports.ReportTestResultsSchema=r.z.object({status:r.z.enum(["passed","failed","error"]).describe("Overall result"),results:r.z.object({commands:r.z.array(r.z.object({name:r.z.string().describe("Command name"),status:r.z.enum(["passed","failed","skipped","error"]).describe("Command result"),output:r.z.string().optional().describe("Relevant output snippet"),diagnosis:r.z.string().optional().describe("Why it failed, if applicable")})).describe("Per-command results"),summary:r.z.string().describe("Brief overall summary"),acceptanceCriteria:r.z.array(r.z.object({criterion:r.z.string().describe("The acceptance criterion text"),status:r.z.enum(["verified","unverified","unclear"]),evidence:r.z.string().describe("How verified, or why not")})).optional().describe("AC verification results, if applicable")}).describe("Structured test results")}),exports.SessionMessageOperationsSchema=r.z.object({operation:r.z.enum(["send","reply","list","get","offer-handoff"]),type:r.z.enum(["question","report"]).optional().describe("Message type to send (required for send)"),toSessionId:r.z.string().optional().describe('Target session ID, or "parent" to auto-resolve to parent session (omit for broadcast questions)'),questionType:r.z.enum(["free-form","alternatives"]).optional().describe('Type of question (required for send type="question")'),questionContent:r.z.object({question:r.z.string().min(1).describe("The question text"),context:r.z.string().optional().describe("Additional context"),options:r.z.array(r.z.object({id:r.z.string(),label:r.z.string(),description:r.z.string().optional()})).optional().describe("Options for alternatives questions"),allowMultiple:r.z.boolean().optional().describe("Allow selecting multiple options")}).optional().describe('Question content (required for send type="question")'),priority:r.z.enum(["low","normal","high"]).optional().describe("Question priority"),expiresInHours:r.z.number().optional().describe("Question expiry in hours"),status:r.z.enum(["success","partial","failure","blocked"]).optional().describe('Report status (required for send type="report")'),summary:r.z.string().optional().describe('Report summary (required for send type="report")'),details:r.z.string().optional().describe("Report details"),finish:r.z.boolean().optional().describe("Release request associations after report"),messageCode:r.z.string().optional().describe("Message code (required for reply and get operations)"),respondedBySessionId:r.z.string().optional().describe("Session ID answering the question"),text:r.z.string().optional().describe("Text answer for free-form questions"),selectedOptions:r.z.array(r.z.string()).optional().describe("Selected option IDs for alternatives"),notes:r.z.string().optional().describe("Additional notes"),list:r.z.object({sessionId:r.z.string().optional().describe("Filter by session ID (auto-discovered if omitted)"),messageType:r.z.enum(["question","report","all"]).default("all").describe("Filter by message type"),direction:r.z.enum(["incoming","outgoing","all"]).default("all"),status:r.z.enum(["pending","answered","expired","success","partial","failure","blocked","all"]).default("all").describe("Filter by status"),readStatus:r.z.enum(["unread","read","acknowledged","all"]).default("all").describe("Filter by read status (reports only)"),limit:r.z.number().min(1).max(100).default(50),offset:r.z.number().min(0).default(0)}).optional().describe('List filters (operation: "list" only)'),offerHandoff:r.z.object({summary:r.z.string().describe("Summary of what was planned/created"),requestIds:r.z.array(r.z.string()).describe("Request IDs that were created from the plan")}).optional().describe('Handoff offer details (operation: "offer-handoff" only)')}).refine((e=>"send"===e.operation?!!e.type:"reply"===e.operation?!!e.messageCode:"list"===e.operation||("get"===e.operation?!!e.messageCode:"offer-handoff"===e.operation)),{message:"Invalid operation data: send requires type, reply requires messageCode, get requires messageCode"}),exports.UpdateSpecializationSchema=r.z.object({specialization:r.z.string().min(1).max(500).describe("Your updated specialization summary \u2014 a concise description of your accumulated domain expertise")})},6252(e,exports,t){"use strict"
|
|
3575
|
+
exports.TestingProcessCreateSchema=r.z.object({name:r.z.string().min(1).describe("Name for the test process"),description:r.z.string().optional().describe("Description of what this process verifies"),scope:r.z.string().optional().describe('Path prefix for monorepo scoping (e.g., "packages/api/"). Omit for global.'),setup:r.z.array(r.z.string()).optional().describe('Commands to prepare the environment (e.g., ["ln -s ../../node_modules node_modules"])'),commands:r.z.array(l).min(1).describe("Test commands to execute in order"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingProcessUpdateSchema=r.z.object({processId:r.z.string().describe("Test process ID to update"),name:r.z.string().min(1).optional().describe("New name"),description:r.z.string().optional().describe("New description"),scope:r.z.string().nullable().optional().describe("New scope (null to remove)"),isActive:r.z.boolean().optional().describe("Enable or disable the process"),setup:r.z.array(r.z.string()).optional().describe("New setup commands (replaces existing)"),commands:r.z.array(l).optional().describe("New test commands (replaces existing)"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingReferenceSchema=r.z.object({}),exports.ExecuteTestCommandSchema=r.z.object({processId:r.z.string().describe("Test process ID containing the command"),commandName:r.z.string().describe('Name of the test command to run, or "setup" to run all setup commands in sequence')}),exports.CommandsSchema=r.z.object({operation:r.z.enum(["run","list","add","remove"]).default("run").describe('"run" to execute a command, "list" to see available commands, "add" to register a new command, "remove" to delete one'),name:r.z.string().optional().describe('Command name (required for "run", "add", and "remove")'),args:r.z.string().optional().describe('Additional arguments appended to the base command (optional, for "run")'),grep:r.z.string().optional().describe('Filter output through grep (optional, for "run"). Pipes command output through grep -i with this pattern.'),command:r.z.string().optional().describe('Shell command to register (required for "add", e.g. "tsc --noEmit")'),description:r.z.string().optional().describe('What this command verifies (optional, for "add")'),timeout:r.z.number().optional().describe('Timeout in seconds (optional, for "add", default 60)')}),exports.ReportTestResultsSchema=r.z.object({status:r.z.enum(["passed","failed","error"]).describe("Overall result"),results:r.z.object({commands:r.z.array(r.z.object({name:r.z.string().describe("Command name"),status:r.z.enum(["passed","failed","skipped","error"]).describe("Command result"),output:r.z.string().optional().describe("Relevant output snippet"),diagnosis:r.z.string().optional().describe("Why it failed, if applicable")})).describe("Per-command results"),summary:r.z.string().describe("Brief overall summary"),acceptanceCriteria:r.z.array(r.z.object({criterion:r.z.string().describe("The acceptance criterion text"),status:r.z.enum(["verified","unverified","unclear"]),evidence:r.z.string().describe("How verified, or why not")})).optional().describe("AC verification results, if applicable")}).describe("Structured test results")}),exports.SessionMessageOperationsSchema=r.z.object({operation:r.z.enum(["send","reply","list","get","offer-handoff"]),type:r.z.enum(["question","report"]).optional().describe("Message type to send (required for send)"),toSessionId:r.z.string().optional().describe('Target session ID, or "parent" to auto-resolve to parent session (omit for broadcast questions)'),questionType:r.z.enum(["free-form","alternatives"]).optional().describe('Type of question (required for send type="question")'),questionContent:r.z.object({question:r.z.string().min(1).describe("The question text"),context:r.z.string().optional().describe("Additional context"),options:r.z.array(r.z.object({id:r.z.string(),label:r.z.string(),description:r.z.string().optional()})).optional().describe("Options for alternatives questions"),allowMultiple:r.z.boolean().optional().describe("Allow selecting multiple options")}).optional().describe('Question content (required for send type="question")'),priority:r.z.enum(["low","normal","high"]).optional().describe("Question priority"),expiresInHours:r.z.number().optional().describe("Question expiry in hours"),status:r.z.enum(["success","partial","failure","blocked"]).optional().describe('Report status (required for send type="report")'),summary:r.z.string().optional().describe('Report summary (required for send type="report")'),details:r.z.string().optional().describe("Report details"),finish:r.z.boolean().optional().describe("Release request associations after report"),messageCode:r.z.string().optional().describe("Message code (required for reply and get operations)"),respondedBySessionId:r.z.string().optional().describe("Session ID answering the question"),text:r.z.string().optional().describe("Text answer for free-form questions"),selectedOptions:r.z.array(r.z.string()).optional().describe("Selected option IDs for alternatives"),notes:r.z.string().optional().describe("Additional notes"),list:r.z.object({sessionId:r.z.string().optional().describe("Filter by session ID (auto-discovered if omitted)"),messageType:r.z.enum(["question","report","all"]).default("all").describe("Filter by message type"),direction:r.z.enum(["incoming","outgoing","all"]).default("all"),status:r.z.enum(["pending","answered","expired","success","partial","failure","blocked","all"]).default("all").describe("Filter by status"),readStatus:r.z.enum(["unread","read","acknowledged","all"]).default("all").describe("Filter by read status (reports only)"),limit:r.z.number().min(1).max(100).default(50),offset:r.z.number().min(0).default(0)}).optional().describe('List filters (operation: "list" only)'),offerHandoff:r.z.object({summary:r.z.string().describe("Summary of what was planned/created"),requestIds:r.z.array(r.z.string()).describe("Request IDs that were created from the plan")}).optional().describe('Handoff offer details (operation: "offer-handoff" only)')}).refine((e=>"send"===e.operation?!!e.type:"reply"===e.operation?!!e.messageCode:"list"===e.operation||("get"===e.operation?!!e.messageCode:"offer-handoff"===e.operation)),{message:"Invalid operation data: send requires type, reply requires messageCode, get requires messageCode"}),exports.UpdateSpecializationSchema=r.z.object({specialization:r.z.string().min(1).max(500).describe("Your updated specialization summary \u2014 a concise description of your accumulated domain expertise")}),exports.CommitToViewedSessionSchema=r.z.object({message:r.z.coerce.string().min(1).describe("The cleaned-up user message to post to the viewed session. Fix obvious dictation errors, add punctuation, but preserve the user's intent exactly.")})},6252(e,exports,t){"use strict"
|
|
3551
3576
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3552
3577
|
const r=t(6183),n=t(405)
|
|
3553
3578
|
exports.def={name:"plan_write",description:"Modify project plans.\n\nOperations:\n\u2022 update - Update plan content\n\u2022 append - Append content to an existing plan\n\u2022 replace - Find and replace text within a plan\n\u2022 create-snapshot - Create a version snapshot\n\u2022 restore - Restore to a previous version",schema:r.PlanWriteSchema,annotations:{title:"Plan Write",readOnlyHint:!1,destructiveHint:!1},handler(e,t){return(0,n.handlePlanWrite)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},6261(module){"use strict"
|
|
@@ -3560,14 +3585,14 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3560
3585
|
var t={}
|
|
3561
3586
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3562
3587
|
return o(t,e),t})
|
|
3563
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,p){const
|
|
3588
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,p){const m=n.child({tool:"specialist_ops"}),f=o.startTimer("tool_execution_time")
|
|
3564
3589
|
try{if(e?.delegate&&"object"==typeof e.delegate){const t=e.delegate
|
|
3565
3590
|
e.prompt=e.prompt||t.prompt,e.description=e.description||t.description,e.specialization=e.specialization||t.specialization,e.requestId=e.requestId||t.requestId,delete e.delegate}if(e?.followUp&&"object"==typeof e.followUp){const t=e.followUp
|
|
3566
3591
|
e.prompt=e.prompt||t.prompt,e.specialization=e.specialization||t.specialization,delete e.followUp}if(e?.list&&"object"==typeof e.list){const t=e.list
|
|
3567
3592
|
e.activeOnly=e.activeOnly??t.activeOnly,e.requestId=e.requestId||t.requestId,e.limit=e.limit??t.limit,delete e.list}!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="delegate":e.prompt&&e.sessionId?e.operation="follow-up":e.sessionId&&(e.operation="check-status")),e?.operation&&("delegate"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.limit):"follow-up"===e.operation?(delete e.description,delete e.activeOnly,delete e.limit):"check-status"===e.operation||"abort"===e.operation?(delete e.prompt,delete e.description,delete e.specialization,delete e.requestId,delete e.activeOnly,delete e.limit):"list"===e.operation&&(delete e.sessionId,delete e.prompt,delete e.description,delete e.specialization))
|
|
3568
3593
|
const n=c.validateArgs(e,a.SpecialistOpsSchema),{operation:y,sessionId:w}=n
|
|
3569
3594
|
let k
|
|
3570
|
-
switch(
|
|
3595
|
+
switch(m.info("Processing specialist_ops",{operation:y,sessionId:w}),y){case"delegate":{const e=10,o=p?.sessionId||g.sessionIdentity.getIdentity()?.sessionId
|
|
3571
3596
|
if(o&&s){const t=await async function(e,t,r,n,o){n.info("enforcePoolLimit called",{parentSessionId:e,maxPoolSize:t})
|
|
3572
3597
|
const s=await(0,h.getServerUrl)(r,n)
|
|
3573
3598
|
if(s)try{const r=await fetch(s.replace(/\/$/,"")+"/session")
|
|
@@ -3581,32 +3606,31 @@ return"specialist"===t?.agentType&&"archived"!==t?.status}))
|
|
|
3581
3606
|
if(n.info("Pool check: specialist count",{specialistCount:h.length,maxPoolSize:t}),h.length<t)return
|
|
3582
3607
|
const g=h.map((e=>{const t=l[e.id],r=u[e.id]?.type||"idle",n=t?.specialization||"(none)"
|
|
3583
3608
|
return` \u2022 ${e.id} \u2014 ${n} [${r}]`})).join("\n")
|
|
3584
|
-
return{content:[{type:"text",text:`\u274c Specialist pool is full (${h.length}/${t}).\nAbort an idle specialist first with \`specialist_ops abort\`, then delegate again.\n\nCurrent pool:\n`+g}],isError:!0}}catch(e){return void n.warn("Pool limit check failed, allowing spawn",{error:(0,l.getErrorMessage)(e)})}}(o,e,r,
|
|
3609
|
+
return{content:[{type:"text",text:`\u274c Specialist pool is full (${h.length}/${t}).\nAbort an idle specialist first with \`specialist_ops abort\`, then delegate again.\n\nCurrent pool:\n`+g}],isError:!0}}catch(e){return void n.warn("Pool limit check failed, allowing spawn",{error:(0,l.getErrorMessage)(e)})}}(o,e,r,m,s)
|
|
3585
3610
|
if(t){k=t
|
|
3586
3611
|
break}}let i=n.description||n.prompt.slice(0,60)
|
|
3587
3612
|
const a=await Promise.resolve().then(t.t.bind(t,9896,23)),c=e=>a.appendFileSync(t(6928).join(t(857).tmpdir(),"specialist-name-debug.log"),`${(new Date).toISOString()} ${e}\n`)
|
|
3588
|
-
if(o)try{const e=await(0,h.getServerUrl)(r,
|
|
3613
|
+
if(o)try{const e=await(0,h.getServerUrl)(r,m)
|
|
3589
3614
|
if(c(`serverUrl=${e}, parentId=${o}`),e){const t=await fetch(e.replace(/\/$/,"")+"/session")
|
|
3590
3615
|
if(c("session fetch status="+t.status),t.ok){const e=(await t.json()).filter((e=>(e.parentId||e.parentID)===o)).map((e=>e.title||""))
|
|
3591
3616
|
c(`siblings=${e.length}: ${e.join(", ")}`)
|
|
3592
3617
|
const r=(0,d.pickSpecialistName)(e)
|
|
3593
3618
|
i=r,c("picked name: "+r)}}else c("no serverUrl")}catch(e){c("error: "+(e instanceof Error?e.message:e+""))}else c("no parentId")
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
break}case"follow-up":{const e=await(0,h.getServerUrl)(r,f)
|
|
3619
|
+
k=await(0,u.handleSpawn)({agent:"specialist",prompt:n.prompt,title:i,specialization:n.specialization},r,m,s,p)
|
|
3620
|
+
break}case"follow-up":{const e=await(0,h.getServerUrl)(r,m)
|
|
3597
3621
|
if(e)try{const t=await fetch(e.replace(/\/$/,"")+"/session/status")
|
|
3598
3622
|
if(t.ok){const e=await t.json(),r=e[w]?.type
|
|
3599
3623
|
if(r&&"idle"!==r&&"prompting"!==r){k={content:[{type:"text",text:`\u274c Specialist ${w} is currently busy (status: ${r}).\nUse \`delegate\` to spawn a new specialist instead.`}],isError:!0}
|
|
3600
|
-
break}}}catch{}k=await(0,u.handleContinue)(w,n.prompt,r,
|
|
3624
|
+
break}}}catch{}k=await(0,u.handleContinue)(w,n.prompt,r,m,s,"specialist",p)
|
|
3601
3625
|
const t=n.specialization
|
|
3602
3626
|
if(t&&s)try{const e=s.getCLISessionClient()
|
|
3603
|
-
e&&(await e.createOrUpdateSession({externalSessionId:w,specialization:t}),k.content[0].text+="\nSpecialization updated to: "+t)}catch{}break}case"check-status":k=await(0,u.handleCheckStatus)(w,r,
|
|
3627
|
+
e&&(await e.createOrUpdateSession({externalSessionId:w,specialization:t}),k.content[0].text+="\nSpecialization updated to: "+t)}catch{}break}case"check-status":k=await(0,u.handleCheckStatus)(w,r,m,s)
|
|
3604
3628
|
break
|
|
3605
|
-
case"abort":if(k=await(0,u.handleAbort)(w,r,
|
|
3629
|
+
case"abort":if(k=await(0,u.handleAbort)(w,r,m),!k.isError&&s)try{const e=s.getCLISessionClient()
|
|
3606
3630
|
e&&await e.createOrUpdateSession({externalSessionId:w,status:"archived"})}catch{}break
|
|
3607
3631
|
case"list":{const e=p?.sessionId||g.sessionIdentity.getIdentity()?.sessionId
|
|
3608
|
-
k=await(0,u.handleListSessions)(r,
|
|
3609
|
-
break}default:throw new i.ValidationError("Unknown operation: "+y)}return
|
|
3632
|
+
k=await(0,u.handleListSessions)(r,m,s,{activeOnly:n.activeOnly,requestId:n.requestId,limit:n.limit,agentType:"specialist",parentSessionId:e})
|
|
3633
|
+
break}default:throw new i.ValidationError("Unknown operation: "+y)}return f({success:!0}),o.incrementCounter(`specialist_ops_${y}_success`,1),k}catch(e){return m.error("Specialist ops failed",{error:e instanceof Error?e.stack:e+""}),f({success:!1}),o.incrementCounter("specialist_ops_errors",1),{content:[{type:"text",text:"Specialist operation failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
|
|
3610
3634
|
const i=t(9860),a=t(6183),c=s(t(5967)),l=t(8824),d=t(9089),u=t(1725),h=t(7617),g=t(6688)},6315(e,exports,t){"use strict"
|
|
3611
3635
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3612
3636
|
const r=t(6183),n=t(2982)
|
|
@@ -3622,16 +3646,16 @@ return o(t,e),t})
|
|
|
3622
3646
|
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")
|
|
3623
3647
|
try{const n=i.RevertRequestSchema.parse(e),{requestId:d,reason:g,confirmDestructive:p}=n
|
|
3624
3648
|
if(s.info("Starting revert/cancel process",{requestId:d,reason:g}),!p)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}
|
|
3625
|
-
let
|
|
3649
|
+
let m
|
|
3626
3650
|
try{const e=await r.proxyPost(`/api/projects/${t.projectId}/requests/${d}/validate-revert`,{})
|
|
3627
|
-
|
|
3628
|
-
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:
|
|
3629
|
-
return
|
|
3630
|
-
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: ${
|
|
3651
|
+
m=e?.data||e}catch(e){const t=(0,u.getErrorMessage)(e)
|
|
3652
|
+
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:m.canRevert,operationType:m.operationType,mergeCommitHash:m.mergeCommitHash?.substring(0,8),reason:m.reason}),!m.canRevert){let e=`Cannot revert request ${d}: ${m.reason}\n`
|
|
3653
|
+
return m.lifoViolation?.blockingRequests?.length&&(e+="\n**Requests that must be reverted first (in reverse order):**\n",m.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"===m.operationType){s.info("Cancel operation \u2014 delegating to server",{requestId:d})
|
|
3654
|
+
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: ${m.tasksToUpdate.length} task(s) marked as canceled\nReason: ${g}`}]}}catch(e){const t=(0,u.getErrorMessage)(e)
|
|
3631
3655
|
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})
|
|
3632
3656
|
t.syncBranchState&&await t.syncBranchState()
|
|
3633
|
-
let m
|
|
3634
|
-
if(!
|
|
3657
|
+
let f=m.mergeCommitHash
|
|
3658
|
+
if(!f){s.info("No merge commit hash from server, searching git log",{requestId:d})
|
|
3635
3659
|
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(" ")
|
|
3636
3660
|
return-1===t?{hash:e,message:""}:{hash:e.substring(0,t),message:e.substring(t+1)}})):[],s=c.generateMergeMessagePatterns(e)
|
|
3637
3661
|
for(const e of s){let t
|
|
@@ -3639,14 +3663,14 @@ if(e.includes("\\")||e.includes(".*")){const r=RegExp(e,"i")
|
|
|
3639
3663
|
t=o.find((e=>r.test(e.message)))}else t=o.find((t=>t.message.includes(e)))
|
|
3640
3664
|
if(t)return{found:!0,commitHash:t.hash}}return{found:!1}}catch(t){return r.error("Failed to find merge commit",{requestId:e,error:(0,u.getErrorMessage)(t)}),{found:!1}}}(d,t,s)
|
|
3641
3665
|
if(!e.found||!e.commitHash)return h({success:!1,error:"merge_commit_not_found"}),{content:[{type:"text",text:"Could not find merge commit for request "+d}],isError:!0}
|
|
3642
|
-
|
|
3666
|
+
f=e.commitHash}const y=t.workspaceManager.getMainGit(),w=await c.getRepositoryStatus(y,s,o)
|
|
3643
3667
|
if(w.currentBranch!==w.defaultBranch){const e=await c.switchToBranch(y,w.defaultBranch||"main",s,o)
|
|
3644
3668
|
if(!e.success)return h({success:!1,error:"branch_switch_failed"}),{content:[{type:"text",text:"Failed to switch to main branch: "+e.message}],isError:!0}}let k
|
|
3645
|
-
try{s.info("Executing git revert",{mergeCommitHash:
|
|
3669
|
+
try{s.info("Executing git revert",{mergeCommitHash:f.substring(0,8)}),await y.raw(["revert","-m","1","--no-edit",f]),k=await(0,l.captureCommitHashRobustly)(y,s,"revert-request-"+d,3,150)
|
|
3646
3670
|
const e=await(0,l.verifyGitStateConsistency)(y,k,s,`revert-request-${d}-verification`)
|
|
3647
|
-
e.consistent||s.error("Git state inconsistency after revert",{issues:e.issues}),s.info("Git revert completed",{requestId:d,originalMergeCommit:
|
|
3648
|
-
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:
|
|
3649
|
-
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: ${
|
|
3671
|
+
e.consistent||s.error("Git state inconsistency after revert",{issues:e.issues}),s.info("Git revert completed",{requestId:d,originalMergeCommit:f.substring(0,8),revertCommitHash:k.substring(0,8)})}catch(e){const t=(0,u.getErrorMessage)(e)
|
|
3672
|
+
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:f})}catch(e){const t=(0,u.getErrorMessage)(e)
|
|
3673
|
+
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: ${m.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}
|
|
3650
3674
|
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}
|
|
3651
3675
|
if(t.projectId&&e.requestId)try{const o=r.getToolRecordClient()
|
|
3652
3676
|
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}}}
|
|
@@ -3672,15 +3696,15 @@ const s=[...t].sort(((e,t)=>"between"===e.type&&"between"===t.type?(t.afterLine|
|
|
|
3672
3696
|
for(const e of s){const t={type:e.type,line:e.line,afterLine:e.afterLine,beforeLine:e.beforeLine,success:!1}
|
|
3673
3697
|
try{let n
|
|
3674
3698
|
switch(e.type){case"before":if(void 0===e.line)throw Error("Line number is required for before insertion")
|
|
3675
|
-
n=(0,
|
|
3699
|
+
n=(0,f.insertBeforeLine)(r,e.line,e.content)
|
|
3676
3700
|
break
|
|
3677
3701
|
case"after":if(void 0===e.line)throw Error("Line number is required for after insertion")
|
|
3678
|
-
n=(0,
|
|
3702
|
+
n=(0,f.insertAfterLine)(r,e.line,e.content)
|
|
3679
3703
|
break
|
|
3680
3704
|
case"between":if(void 0===e.afterLine||void 0===e.beforeLine)throw Error("Both afterLine and beforeLine are required for between insertion")
|
|
3681
|
-
n=(0,
|
|
3705
|
+
n=(0,f.insertBetweenLines)(r,e.afterLine,e.beforeLine,e.content)
|
|
3682
3706
|
break
|
|
3683
|
-
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,
|
|
3707
|
+
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,m.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)
|
|
3684
3708
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
3685
3709
|
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=[]
|
|
3686
3710
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -3688,7 +3712,7 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3688
3712
|
var t={}
|
|
3689
3713
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
3690
3714
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3691
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleInsertLines=async function(e,n,o,s,i,a,
|
|
3715
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleInsertLines=async function(e,n,o,s,i,a,f,y){const w=a.child({tool:"insert_lines"}),k=Date.now()
|
|
3692
3716
|
let I,b,v=d.FileOperationPhase.VALIDATION
|
|
3693
3717
|
const C={toolName:"insert-lines",operationName:"insert-lines",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"insert-lines",metricsPrefix:"insert_lines",successMessage:"Successfully inserted lines into files and documents",failureMessage:"Failed to insert lines into files and documents"}
|
|
3694
3718
|
try{const _=d.validateArgs(e,l.InsertLinesSchema),{operations:E,comment:q}=_,{resolveActiveTaskId:S}=await Promise.resolve().then(t.bind(t,3451)),T=e.taskId||await S(n,o,a)||"untracked"
|
|
@@ -3701,34 +3725,34 @@ x.push({type:"file",path:t,fullPath:r,insertions:e.insertions})}const R=[]
|
|
|
3701
3725
|
if(j.length>0&&!n.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
3702
3726
|
for(const e of j)R.push({type:"document",documentId:e.documentId,insertions:e.insertions})
|
|
3703
3727
|
if(R.length>0&&n.apiClient){const e=R.map((e=>e.documentId))
|
|
3704
|
-
try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,w,
|
|
3705
|
-
throw e}}v=d.FileOperationPhase.TASK_VALIDATION,
|
|
3706
|
-
const M=x.length>0?x[0].path:"document-operation",O=await d.validateTaskId(T,M,o,w,
|
|
3728
|
+
try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,w,f,"insert-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3729
|
+
throw e}}v=d.FileOperationPhase.TASK_VALIDATION,f.incrementCounter("insert_lines_phase",1,{phase:v})
|
|
3730
|
+
const M=x.length>0?x[0].path:"document-operation",O=await d.validateTaskId(T,M,o,w,f,C.metricsPrefix),$=O?.requestId
|
|
3707
3731
|
let D=null
|
|
3708
|
-
x.length>0&&$&&(D=await d.validateWorkItemStates(T,x[0].path,o,i,n,w,
|
|
3732
|
+
x.length>0&&$&&(D=await d.validateWorkItemStates(T,x[0].path,o,i,n,w,f,C.metricsPrefix))
|
|
3709
3733
|
let A={taskPromoted:!1,requestPromoted:!1}
|
|
3710
|
-
x.length>0&&$&&D&&(A=await d.autoPromoteTaskStatus(T,O.status,$,D.request?.status,x[0].path,o,i,w,
|
|
3711
|
-
const F=await d.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:$,context:n,operation:"insert-lines",logger:w,metrics:
|
|
3734
|
+
x.length>0&&$&&D&&(A=await d.autoPromoteTaskStatus(T,O.status,$,D.request?.status,x[0].path,o,i,w,f,C.metricsPrefix),A.taskPromoted&&w.info("Auto-promoted task to in_progress for insert-lines operation",{taskId:T,requestId:$,previousStatus:O.status,newStatus:A.newTaskStatus,triggeringOperation:"insert-lines"}))
|
|
3735
|
+
const F=await d.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:$,context:n,operation:"insert-lines",logger:w,metrics:f,metricsPrefix:C.metricsPrefix})
|
|
3712
3736
|
if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
|
|
3713
3737
|
throw Error(F.error)}if(x.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:x.length,workspaceBasePath:n.workspaceManager?.getCurrentContext(n.currentSessionId).basePath})
|
|
3714
3738
|
for(let e=0;e<x.length;e++){const t=x[e],r=P[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(r.path,n)
|
|
3715
|
-
x[e]={...t,path:o,fullPath:s}}}if(R.length>0&&$)try{await(0,h.validateRequestStatusForDocumentOperation)($,i,w,
|
|
3716
|
-
throw e}v=d.FileOperationPhase.RECORD_CREATION,
|
|
3717
|
-
const N=[...x.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...R.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:L}=await d.createFileOperationRecords(T,$,n.projectId,C.recordType,M,{operationCount:E.length,fileOperations:x.length,documentOperations:R.length,operations:N,userComment:q},o,s,w,
|
|
3718
|
-
if(I=L,b=L,v=C.fileOperationPhase,
|
|
3719
|
-
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"insert-lines",{requestId:$,taskId:T,workspaceManager:n.workspaceManager},w,
|
|
3739
|
+
x[e]={...t,path:o,fullPath:s}}}if(R.length>0&&$)try{await(0,h.validateRequestStatusForDocumentOperation)($,i,w,f,"insert-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3740
|
+
throw e}v=d.FileOperationPhase.RECORD_CREATION,f.incrementCounter("insert_lines_phase",1,{phase:v})
|
|
3741
|
+
const N=[...x.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...R.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:L}=await d.createFileOperationRecords(T,$,n.projectId,C.recordType,M,{operationCount:E.length,fileOperations:x.length,documentOperations:R.length,operations:N,userComment:q},o,s,w,f,C.metricsPrefix,y)
|
|
3742
|
+
if(I=L,b=L,v=C.fileOperationPhase,f.incrementCounter("insert_lines_phase",1,{phase:v}),x.length>0&&n.git)try{w.debug("[INSERT-LINES] Checking for user changes before insert operations")
|
|
3743
|
+
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"insert-lines",{requestId:$,taskId:T,workspaceManager:n.workspaceManager},w,f)
|
|
3720
3744
|
e.userChangesCommitted&&(w.debug("[INSERT-LINES] User changes committed before insert operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before insert-lines operation",{taskId:T,fileOperationsCount:x.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[INSERT-LINES] Pre-tool commit failed, continuing with insertions",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with insert operation",{taskId:T,fileOperationsCount:x.length,error:e instanceof Error?e.message:e+""})}w.debug("[INSERT-LINES] Proceeding with file operations",{fileCount:x.length})
|
|
3721
3745
|
const z=[]
|
|
3722
3746
|
let H=0,B=0,U=0
|
|
3723
3747
|
for(const e of x){const t={type:"file",path:e.path,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
|
|
3724
3748
|
try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
|
|
3725
3749
|
const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.insertions)
|
|
3726
|
-
t.insertions=s,t.successfulInsertions=s.filter((e=>e.success)).length,t.failedInsertions=s.filter((e=>!e.success)).length,t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulInsertions>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,U++,w.info("File updated successfully",{path:e.path,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,
|
|
3750
|
+
t.insertions=s,t.successfulInsertions=s.filter((e=>e.success)).length,t.failedInsertions=s.filter((e=>!e.success)).length,t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulInsertions>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,U++,w.info("File updated successfully",{path:e.path,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedInsertions=e.insertions.length,H+=t.failedInsertions,w.error("File operation failed",{path:e.path,error:t.error})}z.push(t)}for(const e of R){const t={type:"document",documentId:e.documentId,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
|
|
3727
3751
|
try{const o=await n.documentFileManager.getDocumentAsFile(e.documentId),s=n.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
3728
3752
|
t.filename=s?.filename
|
|
3729
3753
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.insertions)
|
|
3730
|
-
t.insertions=l,t.successfulInsertions=l.filter((e=>e.success)).length,t.failedInsertions=l.filter((e=>!e.success)).length,t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulInsertions>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,U++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,
|
|
3731
|
-
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const G=await d.handleMultiFileGitCommit(T,x,z,U,{operationType:"Insert lines",toolRecordId:b,successField:"successfulInsertions",logger:w,metrics:
|
|
3754
|
+
t.insertions=l,t.successfulInsertions=l.filter((e=>e.success)).length,t.failedInsertions=l.filter((e=>!e.success)).length,t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulInsertions>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,U++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedInsertions=e.insertions.length,H+=t.failedInsertions,w.error("Document operation failed",{documentId:e.documentId,error:t.error})}z.push(t)}if(R.length>0)try{for(const e of R){const t=z.find((t=>t.documentId===e.documentId))
|
|
3755
|
+
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const G=await d.handleMultiFileGitCommit(T,x,z,U,{operationType:"Insert lines",toolRecordId:b,successField:"successfulInsertions",logger:w,metrics:f,metricsPrefix:"insert_lines"},n),W=d.processMultiFileOperationResults(z,"successfulInsertions"),{successfulOperations:V,failedOperations:J,totalSuccessfulChanges:K,overallSuccess:Y,successfulFiles:Q,failedFiles:Z}=W
|
|
3732
3756
|
try{await s.updateToolRecord(b,{metadata:{path:x.length>0?x[0].path:"document:"+R[0]?.documentId,status:Y?"completed":"failed",error:Y?void 0:J+" operations failed",totalOperations:z.length,successfulFiles:Q,failedFiles:Z,operations:N,totalSuccessfulInsertions:K,totalFailedInsertions:H,totalLinesAdded:B,operationsWithChanges:U,processingTime:Date.now()-k,userComment:q,...x.length>0&&G.success&&G.commitHash&&{commitHash:G.commitHash,previousCommitHash:G.previousCommitHash||void 0}},note:Y?`Line insertion completed: ${V}/${z.length} operations successful${x.length>0?" (committed to git)":""}`:`Line insertion partially failed: ${J}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let X="## Line Insertion Results\n\n"
|
|
3733
3757
|
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
3734
3758
|
e.permanentBranch||(X+=`**Branch:** \`${e.branchName}\`\n\n`)}if(X+="**Summary:**\n",X+=`- **Files processed:** ${V+J}\n`,X+=`- **Successful operations:** ${V}\n`,X+=`- **Failed operations:** ${J}\n`,X+=`- **Total insertions:** ${K} successful, ${H} failed\n`,X+=`- **Total Lines Added:** ${B}\n`,X+="\n",G.success&&G.commitHash&&(X+="**Git Commit:**\n",X+=`- **Commit Hash:** ${G.commitHash.substring(0,8)}\n`,X+=`- **Files Committed:** ${G.filesCommitted.length}\n`,G.previousCommitHash&&(X+=`- **Previous Commit:** ${G.previousCommitHash.substring(0,8)}\n`),X+="\n"),F.lockAcquired&&F.lockedRequestId&&(n.workspaceManager?.getCurrentContext(n.currentSessionId)?.permanentBranch||(X+=`\u{1f512} **Locked request:** ${F.lockedRequestId}\n\n`)),1===z.length){const e=z[0]
|
|
@@ -3739,37 +3763,37 @@ for(const e of z){if("file"===e.type?X+=`### File: ${e.path}\n`:(X+="### Documen
|
|
|
3739
3763
|
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}`
|
|
3740
3764
|
X+=` - ${t.type} insertion ${e}: ${t.error}\n`}}X+="\n"}}R.length>0&&(X+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3741
3765
|
const ee=Date.now()-k
|
|
3742
|
-
return w.info("Insert lines operation completed",{duration:ee,success:Y,totalOperations:z.length,successfulOperations:V,failedOperations:J}),
|
|
3743
|
-
if(w.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),b)try{await s.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,
|
|
3744
|
-
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),
|
|
3766
|
+
return w.info("Insert lines operation completed",{duration:ee,success:Y,totalOperations:z.length,successfulOperations:V,failedOperations:J}),f.incrementCounter("insert_lines_total",1,{success:Y}),{content:[{type:"text",text:X}],isError:!Y}}catch(t){const r=Date.now()-k
|
|
3767
|
+
if(w.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),b)try{await s.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,m.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"Line insertion failed: "+(0,m.getErrorMessage)(t)})}catch(e){}return f.incrementCounter("insert_lines_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Insert Lines Failed:** "+(0,m.getErrorMessage)(t)}],isError:!0}}}
|
|
3768
|
+
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),m=t(8824),f=t(3255)},6539(e,exports,t){"use strict"
|
|
3745
3769
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientFactory=void 0
|
|
3746
|
-
const r=t(1253),n=t(5681),o=t(6595),s=t(3895),i=t(6848),a=t(6153),c=t(4710),l=t(6975),d=t(1887),u=t(1666),h=t(8824),g=t(9884),p=t(2968),
|
|
3747
|
-
exports.ClientFactory=class{static async createClient(e,
|
|
3748
|
-
const k=w.tokenManager||new r.TokenManager(
|
|
3770
|
+
const r=t(1253),n=t(5681),o=t(6595),s=t(3895),i=t(6848),a=t(6153),c=t(4710),l=t(6975),d=t(1887),u=t(1666),h=t(8824),g=t(9884),p=t(2968),m=t(922)
|
|
3771
|
+
exports.ClientFactory=class{static async createClient(e,f,y,w={}){(f=f.child({component:"client-factory"})).info("Creating API client with components")
|
|
3772
|
+
const k=w.tokenManager||new r.TokenManager(f,w.workingDir||process.cwd())
|
|
3749
3773
|
await k.initialize()
|
|
3750
|
-
const I=w.tokenSynchronizer||new i.ClientTokenSynchronizer(
|
|
3774
|
+
const I=w.tokenSynchronizer||new i.ClientTokenSynchronizer(f),b=new s.AuthenticationManager(k,f,I),v=await b.getTokenString(),C=w.connectionStatusManager||new n.ConnectionStatusManager(e,f,y,{alchemyPath:w.alchemyPath,checkIntervalMs:w.offlineCheckIntervalMs,timeoutMs:w.timeout,retryCount:w.retryAttempts}),_=new c.ProjectClient(e,f,y,C,v||void 0,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3751
3775
|
I.registerClient(_),w.alchemyPath&&_.setAlchemyPath(w.alchemyPath)
|
|
3752
|
-
const E=new p.TaskClient(e,
|
|
3776
|
+
const E=new p.TaskClient(e,f,y,_,C,v||void 0,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3753
3777
|
I.registerClient(E)
|
|
3754
|
-
const q=new a.FileOperationsClient(e,
|
|
3755
|
-
I.registerClient(q),
|
|
3756
|
-
const S=new u.RequestClient(e,
|
|
3757
|
-
I.registerClient(S),
|
|
3758
|
-
const T=new g.DocumentClient(e,
|
|
3778
|
+
const q=new a.FileOperationsClient(e,f,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3779
|
+
I.registerClient(q),f.info("RequestClient constructor received token: "+(v?"present":"missing"))
|
|
3780
|
+
const S=new u.RequestClient(e,f,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3781
|
+
I.registerClient(S),f.info("RequestClient post-constructor token: "+(S.getAuthToken()?"present":"missing"))
|
|
3782
|
+
const T=new g.DocumentClient(e,f,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3759
3783
|
I.registerClient(T)
|
|
3760
|
-
const P=new
|
|
3784
|
+
const P=new m.ToolRecordClient(e,f,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3761
3785
|
I.registerClient(P)
|
|
3762
|
-
const j=new d.ProxyClient(e,
|
|
3786
|
+
const j=new d.ProxyClient(e,f,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3763
3787
|
if(I.registerClient(j),!w.alchemyPath)throw Error("alchemyPath is required for ProjectSynchronizer creation. Cannot create API client without project synchronization capabilities.")
|
|
3764
|
-
try{
|
|
3765
|
-
const{ProjectRegistry,ProjectFileSystem,ProjectSynchronizer}=await t.e(478).then(t.bind(t,5478)),e=new ProjectRegistry(
|
|
3766
|
-
_.setProjectSynchronizer(n),
|
|
3767
|
-
throw
|
|
3768
|
-
|
|
3788
|
+
try{f.info("Creating ProjectSynchronizer components")
|
|
3789
|
+
const{ProjectRegistry,ProjectFileSystem,ProjectSynchronizer}=await t.e(478).then(t.bind(t,5478)),e=new ProjectRegistry(f),r=new ProjectFileSystem(f),n=new ProjectSynchronizer(f,e,new l.ProjectClientAdapter(_,f),r,{createRemoteProjects:!0})
|
|
3790
|
+
_.setProjectSynchronizer(n),f.info("ProjectSynchronizer created and connected to ProjectClient")}catch(e){const t="Failed to create required ProjectSynchronizer components: "+(0,h.getErrorMessage)(e)
|
|
3791
|
+
throw f.error(t,{error:e instanceof Error?e.stack:e+""}),Error(t)}const x=new o.ApiClient(b,_,E,q,S,T,P,j,f)
|
|
3792
|
+
f.info("API client initialized with specialized clients"),v?(x.setAuthToken(v),f.info("Auth token set on ApiClient during creation",{hasToken:!0,tokenLength:v.length})):f.warn("No auth token available during ApiClient creation",{info:"Client will need to authenticate before making requests"})
|
|
3769
3793
|
const R=I.verifyAllClients()
|
|
3770
|
-
R.success?
|
|
3794
|
+
R.success?f.info("Token consistency verified across all clients"):f.error(`Token inconsistency detected in ${R.failedClients.length} clients: ${R.failedClients.join(", ")}`)
|
|
3771
3795
|
const M=x.getAuthToken()
|
|
3772
|
-
return v&&!M?(
|
|
3796
|
+
return v&&!M?(f.error("CRITICAL: ApiClient token was not set properly!"),x.setAuthToken(v)):M&&f.info("ApiClient token verified",{tokenLength:M.length,matches:M===v}),f.info("API client creation completed successfully"),x}}},6540(e,exports){"use strict"
|
|
3773
3797
|
var t
|
|
3774
3798
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.LogLevel=void 0,function(e){e.ERROR="error",e.WARN="warn",e.INFO="info",e.DEBUG="debug"}(t||(exports.LogLevel=t={}))},6595(e,exports,t){"use strict"
|
|
3775
3799
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ApiClient=void 0
|
|
@@ -3800,8 +3824,8 @@ async function r(e,t){let r=e
|
|
|
3800
3824
|
const n=[],o=[...t].sort(((e,t)=>{const r=e=>"number"==typeof e?e:Array.isArray(e)?Math.max(...e):e.end
|
|
3801
3825
|
return r(t.lines)-r(e.lines)}))
|
|
3802
3826
|
for(const e of o){const t={lines:e.lines,success:!1}
|
|
3803
|
-
try{const n=(0,
|
|
3804
|
-
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,
|
|
3827
|
+
try{const n=(0,f.replaceLines)(r,e.lines,e.content)
|
|
3828
|
+
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,m.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)
|
|
3805
3829
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
3806
3830
|
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=[]
|
|
3807
3831
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -3809,7 +3833,7 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3809
3833
|
var t={}
|
|
3810
3834
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
3811
3835
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3812
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceLines=async function(e,n,o,s,i,a,
|
|
3836
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceLines=async function(e,n,o,s,i,a,f,w){const k=a.child({tool:"replace_lines"}),I=Date.now()
|
|
3813
3837
|
let b,v,C=d.FileOperationPhase.VALIDATION
|
|
3814
3838
|
const _={toolName:"replace-lines",operationName:"replace-lines",fileOperationPhase:d.FileOperationPhase.STRING_REPLACEMENT,recordType:"replace-lines",metricsPrefix:"replace_lines",successMessage:"Successfully replaced lines in files and documents",failureMessage:"Failed to replace lines in files and documents"}
|
|
3815
3839
|
try{const E=d.validateArgs(e,l.ReplaceLinesSchema),{operations:q,comment:S}=E,{resolveActiveTaskId:T}=await Promise.resolve().then(t.bind(t,3451)),P=e.taskId||await T(n,o,a)||"untracked"
|
|
@@ -3822,34 +3846,34 @@ R.push({type:"file",path:t,fullPath:r,replacements:e.replacements.map((e=>({line
|
|
|
3822
3846
|
if(x.length>0&&!n.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
3823
3847
|
for(const e of x)M.push({type:"document",documentId:e.documentId,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})
|
|
3824
3848
|
if(M.length>0&&n.apiClient){const e=M.map((e=>e.documentId))
|
|
3825
|
-
try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,k,
|
|
3826
|
-
throw e}}C=d.FileOperationPhase.TASK_VALIDATION,
|
|
3827
|
-
const O=R.length>0?R[0].path:"document-operation",$=await d.validateTaskId(P,O,o,k,
|
|
3849
|
+
try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,k,f,"replace-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3850
|
+
throw e}}C=d.FileOperationPhase.TASK_VALIDATION,f.incrementCounter("replace_lines_phase",1,{phase:C})
|
|
3851
|
+
const O=R.length>0?R[0].path:"document-operation",$=await d.validateTaskId(P,O,o,k,f,_.metricsPrefix),D=$?.requestId
|
|
3828
3852
|
let A=null
|
|
3829
|
-
R.length>0&&D&&(A=await d.validateWorkItemStates(P,R[0].path,o,i,n,k,
|
|
3853
|
+
R.length>0&&D&&(A=await d.validateWorkItemStates(P,R[0].path,o,i,n,k,f,_.metricsPrefix))
|
|
3830
3854
|
let F={taskPromoted:!1,requestPromoted:!1}
|
|
3831
|
-
R.length>0&&D&&A&&(F=await d.autoPromoteTaskStatus(P,$.status,D,A.request?.status,R[0].path,o,i,k,
|
|
3832
|
-
const N=await d.ensureCorrectWorkspaceContext({taskPromoted:F.taskPromoted,requestId:D,context:n,operation:"replace-lines",logger:k,metrics:
|
|
3855
|
+
R.length>0&&D&&A&&(F=await d.autoPromoteTaskStatus(P,$.status,D,A.request?.status,R[0].path,o,i,k,f,_.metricsPrefix),F.taskPromoted&&k.info("Auto-promoted task to in_progress for replace-lines operation",{taskId:P,requestId:D,previousStatus:$.status,newStatus:F.newTaskStatus,triggeringOperation:"replace-lines"}))
|
|
3856
|
+
const N=await d.ensureCorrectWorkspaceContext({taskPromoted:F.taskPromoted,requestId:D,context:n,operation:"replace-lines",logger:k,metrics:f,metricsPrefix:_.metricsPrefix})
|
|
3833
3857
|
if(!N.success){if(N.isLockConflict)return{content:[{type:"text",text:"\u274c "+N.error}],isError:!0}
|
|
3834
3858
|
throw Error(N.error)}if(R.length>0){k.debug("Re-validating file paths with correct workspace context",{operationCount:R.length,workspaceBasePath:n.workspaceManager?.getCurrentContext(n.currentSessionId).basePath})
|
|
3835
3859
|
for(let e=0;e<R.length;e++){const t=R[e],r=j[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(r.path,n)
|
|
3836
|
-
R[e]={...t,path:o,fullPath:s}}}if(M.length>0&&D)try{await(0,h.validateRequestStatusForDocumentOperation)(D,i,k,
|
|
3837
|
-
throw e}C=d.FileOperationPhase.RECORD_CREATION,
|
|
3838
|
-
const L=[...R.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:z}=await d.createFileOperationRecords(P,D,n.projectId,_.recordType,O,{operationCount:q.length,fileOperations:R.length,documentOperations:M.length,operations:L,userComment:S},o,s,k,
|
|
3839
|
-
if(b=z,v=z,C=_.fileOperationPhase,
|
|
3840
|
-
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"replace-lines",{requestId:D,taskId:P,workspaceManager:n.workspaceManager},k,
|
|
3860
|
+
R[e]={...t,path:o,fullPath:s}}}if(M.length>0&&D)try{await(0,h.validateRequestStatusForDocumentOperation)(D,i,k,f,"replace-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3861
|
+
throw e}C=d.FileOperationPhase.RECORD_CREATION,f.incrementCounter("replace_lines_phase",1,{phase:C})
|
|
3862
|
+
const L=[...R.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:z}=await d.createFileOperationRecords(P,D,n.projectId,_.recordType,O,{operationCount:q.length,fileOperations:R.length,documentOperations:M.length,operations:L,userComment:S},o,s,k,f,_.metricsPrefix,w)
|
|
3863
|
+
if(b=z,v=z,C=_.fileOperationPhase,f.incrementCounter("replace_lines_phase",1,{phase:C}),R.length>0&&n.git)try{k.debug("[REPLACE-LINES] Checking for user changes before replace operations")
|
|
3864
|
+
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"replace-lines",{requestId:D,taskId:P,workspaceManager:n.workspaceManager},k,f)
|
|
3841
3865
|
e.userChangesCommitted&&(k.debug("[REPLACE-LINES] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),k.info("User changes committed before replace-lines operation",{taskId:P,fileOperationsCount:R.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){k.debug("[REPLACE-LINES] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),k.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:P,fileOperationsCount:R.length,error:e instanceof Error?e.message:e+""})}k.debug("[REPLACE-LINES] Proceeding with file operations",{fileCount:R.length})
|
|
3842
3866
|
const H=[]
|
|
3843
3867
|
let B=0,U=0,G=0,W=0
|
|
3844
3868
|
for(const e of R){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
|
|
3845
3869
|
try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
|
|
3846
3870
|
const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.replacements)
|
|
3847
|
-
t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,t.totalLinesReplaced=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulReplacements>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,W++,k.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,
|
|
3871
|
+
t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,t.totalLinesReplaced=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulReplacements>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,W++,k.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,B+=t.failedReplacements,k.error("File operation failed",{path:e.path,error:t.error})}H.push(t)}for(const e of M){const t={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
|
|
3848
3872
|
try{const o=await n.documentFileManager.getDocumentAsFile(e.documentId),s=n.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
3849
3873
|
t.filename=s?.filename
|
|
3850
3874
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.replacements)
|
|
3851
|
-
t.replacements=l,t.successfulReplacements=l.filter((e=>e.success)).length,t.failedReplacements=l.filter((e=>!e.success)).length,t.totalLinesReplaced=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulReplacements>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,W++,k.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,
|
|
3852
|
-
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){k.warn("Some documents may not have synced properly",{error:e})}const V=await d.handleMultiFileGitCommit(P,R,H,W,{operationType:"Replace lines",toolRecordId:v,successField:"successfulReplacements",logger:k,metrics:
|
|
3875
|
+
t.replacements=l,t.successfulReplacements=l.filter((e=>e.success)).length,t.failedReplacements=l.filter((e=>!e.success)).length,t.totalLinesReplaced=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulReplacements>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,W++,k.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,B+=t.failedReplacements,k.error("Document operation failed",{documentId:e.documentId,error:t.error})}H.push(t)}if(M.length>0)try{for(const e of M){const t=H.find((t=>t.documentId===e.documentId))
|
|
3876
|
+
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){k.warn("Some documents may not have synced properly",{error:e})}const V=await d.handleMultiFileGitCommit(P,R,H,W,{operationType:"Replace lines",toolRecordId:v,successField:"successfulReplacements",logger:k,metrics:f,metricsPrefix:"replace_lines"},n),J=d.processMultiFileOperationResults(H,"successfulReplacements"),{successfulOperations:K,failedOperations:Y,totalSuccessfulChanges:Q,overallSuccess:Z,successfulFiles:X,failedFiles:ee}=J
|
|
3853
3877
|
try{await s.updateToolRecord(v,{metadata:{path:R.length>0?R[0].path:"document:"+M[0]?.documentId,status:Z?"completed":"failed",error:Z?void 0:Y+" operations failed",totalOperations:H.length,successfulFiles:X,failedFiles:ee,operations:L,totalSuccessfulReplacements:Q,totalFailedReplacements:B,totalLinesReplaced:U,totalLinesAdded:G,operationsWithChanges:W,processingTime:Date.now()-I,userComment:S,...R.length>0&&V.success&&V.commitHash&&{commitHash:V.commitHash,previousCommitHash:V.previousCommitHash||void 0}},note:Z?`Line replacement completed: ${K}/${H.length} operations successful${R.length>0?" (committed to git)":""}`:`Line replacement partially failed: ${Y}/${H.length} operations failed`})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let te="## Line Replacement Results\n\n"
|
|
3854
3878
|
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
3855
3879
|
e.permanentBranch||(te+=`**Branch:** \`${e.branchName}\`\n\n`)}if(te+="**Summary:**\n",te+=`- **Files processed:** ${K+Y}\n`,te+=`- **Successful operations:** ${K}\n`,te+=`- **Failed operations:** ${Y}\n`,te+=`- **Total replacements:** ${Q} successful, ${B} failed\n`,te+=`- **Total Lines Replaced:** ${U}\n`,G>0&&(te+=`- **Total Lines Added:** ${G}\n`),te+="\n",V.success&&V.commitHash&&(te+="**Git Commit:**\n",te+=`- **Commit Hash:** ${V.commitHash.substring(0,8)}\n`,te+=`- **Files Committed:** ${V.filesCommitted.length}\n`,V.previousCommitHash&&(te+=`- **Previous Commit:** ${V.previousCommitHash.substring(0,8)}\n`),te+="\n"),N.lockAcquired&&N.lockedRequestId&&(n.workspaceManager?.getCurrentContext(n.currentSessionId)?.permanentBranch||(te+=`\u{1f512} **Locked request:** ${N.lockedRequestId}\n\n`)),1===H.length){const e=H[0]
|
|
@@ -3858,12 +3882,12 @@ for(const t of e.replacements.filter((e=>!e.success)))te+=`- Replace ${"number"=
|
|
|
3858
3882
|
for(const e of H){if("file"===e.type?te+=`### File: ${e.path}\n`:(te+="### Document: "+e.documentId,e.filename&&(te+=` (${e.filename})`),te+="\n"),te+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error&&(te+=`- **Error:** ${e.error}\n`),te+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(te+=`, ${e.failedReplacements} failed`),te+="\n",te+=`- **Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(te+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.replacements.some((e=>!e.success))){te+="- **Failed Replacement Details:**\n"
|
|
3859
3883
|
for(const t of e.replacements.filter((e=>!e.success)))te+=` - Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}te+="\n"}}M.length>0&&(te+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3860
3884
|
const re=Date.now()-I
|
|
3861
|
-
return k.info("Replace lines operation completed",{duration:re,success:Z,totalOperations:H.length,successfulOperations:K,failedOperations:Y}),
|
|
3862
|
-
if(k.error("Replace lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:C}),v)try{await s.updateToolRecord(v,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,
|
|
3863
|
-
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),
|
|
3885
|
+
return k.info("Replace lines operation completed",{duration:re,success:Z,totalOperations:H.length,successfulOperations:K,failedOperations:Y}),f.incrementCounter("replace_lines_total",1,{success:Z}),{content:[{type:"text",text:te}],isError:!Z}}catch(t){const r=Date.now()-I
|
|
3886
|
+
if(k.error("Replace lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:C}),v)try{await s.updateToolRecord(v,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,m.getErrorMessage)(t),phase:C,duration:r,userComment:e?.comment},note:"Line replacement failed: "+(0,m.getErrorMessage)(t)})}catch(e){}return f.incrementCounter("replace_lines_errors",1,{phase:C}),{content:[{type:"text",text:"\u274c **Replace Lines Failed:** "+(0,m.getErrorMessage)(t)}],isError:!0}}}
|
|
3887
|
+
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),m=t(8824),f=t(3255),y=t(9470)},6688(e,exports,t){"use strict"
|
|
3864
3888
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.sessionIdentity=void 0
|
|
3865
3889
|
const r=t(9896),n=t(6928)
|
|
3866
|
-
exports.sessionIdentity=new class{constructor(){this.parentCache=new Map}setIdentity(e){const t=this.identity
|
|
3890
|
+
exports.sessionIdentity=new class{constructor(){this.parentCache=new Map,this.sessionRequestCache=new Map}setIdentity(e){const t=this.identity
|
|
3867
3891
|
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}
|
|
3868
3892
|
this.identity={...this.identity,...e},this.log("updateIdentity",{sessionId:this.identity.sessionId,updates:Object.keys(e),agentTypeBefore:t.agentType||null,agentTypeAfter:this.identity.agentType||null})}}async getParentSessionId(e,t,r){if(this.parentCache.has(e)){const t=this.parentCache.get(e)
|
|
3869
3893
|
return this.log("getParentSessionId.cache-hit",{childExternalId:e,parentExternalId:t}),t}try{const n=t.getCLISessionClient()
|
|
@@ -3872,12 +3896,14 @@ const o=await n.getParent(e),s=o?.externalSessionId||null
|
|
|
3872
3896
|
return this.parentCache.set(e,s),this.log("getParentSessionId.resolved",{childExternalId:e,parentExternalId:s}),s||r.warn("Parent session not found",{sessionId:e}),s}catch(t){const n=t instanceof Error?t.message:t+""
|
|
3873
3897
|
return r.warn("Error getting parent session",{sessionId:e,error:n}),null}}setParentSessionId(e,t){this.parentCache.set(e,t)}async getSessionRequestId(e,t,r){const n=r||this.identity?.sessionId
|
|
3874
3898
|
if(!n)return t.warn("Cannot get session request: no session identity"),null
|
|
3899
|
+
const o=this.sessionRequestCache.get(n)
|
|
3900
|
+
if(o)return this.log("getSessionRequestId.cache-hit",{sessionId:n,requestId:o}),o
|
|
3875
3901
|
try{const r=e.getSessionRequestAssociationClient?.()
|
|
3876
3902
|
if(!r)return t.warn("Session request association client not available"),null
|
|
3877
3903
|
const o=await r.getActiveRequestsForSession(n)
|
|
3878
3904
|
if(o?.length>0){const e=o[0].requestLocalId||o[0].request_local_id
|
|
3879
|
-
return this.log("getSessionRequestId.resolved",{sessionId:n,requestId:e}),e||null}return this.log("getSessionRequestId.none",{sessionId:n}),null}catch(e){const r=e instanceof Error?e.message:e+""
|
|
3880
|
-
return t.warn("Error getting session request",{sessionId:n,error:r}),null}}buildCliOrigin(e){if(this.identity)return{providerId:this.identity.providerId,sessionId:this.identity.sessionId,messageId:e,createdAt:(new Date).toISOString()}}setCurrentCallOrigin(e){this.currentCallOrigin=e}getCurrentCallOrigin(){return this.currentCallOrigin||this.buildCliOrigin()}log(e,t){try{const o=process.env.ALCHEMY_PROJECT_PATH||process.cwd(),s=(0,n.join)(o,".alchemy_lab");(0,r.existsSync)(s)||(0,r.mkdirSync)(s,{recursive:!0})
|
|
3905
|
+
return e&&this.sessionRequestCache.set(n,e),this.log("getSessionRequestId.resolved",{sessionId:n,requestId:e}),e||null}return this.log("getSessionRequestId.none",{sessionId:n}),null}catch(e){const r=e instanceof Error?e.message:e+""
|
|
3906
|
+
return t.warn("Error getting session request",{sessionId:n,error:r}),null}}clearSessionRequestCache(e){e?this.sessionRequestCache.delete(e):this.sessionRequestCache.clear()}buildCliOrigin(e){if(this.identity)return{providerId:this.identity.providerId,sessionId:this.identity.sessionId,messageId:e,createdAt:(new Date).toISOString()}}setCurrentCallOrigin(e){this.currentCallOrigin=e}getCurrentCallOrigin(){return this.currentCallOrigin||this.buildCliOrigin()}log(e,t){try{const o=process.env.ALCHEMY_PROJECT_PATH||process.cwd(),s=(0,n.join)(o,".alchemy_lab");(0,r.existsSync)(s)||(0,r.mkdirSync)(s,{recursive:!0})
|
|
3881
3907
|
const i=(0,n.join)(s,"mcp-identity-debug.log"),a=(new Date).toISOString(),c=process.pid,l=t?" "+JSON.stringify(t):"";(0,r.appendFileSync)(i,`[${a}] [PID:${c}] identity.${e}${l}\n`)}catch{}}},exports.sessionIdentity.log("module-load",{ALCHEMY_SESSION_TAG:process.env.ALCHEMY_SESSION_TAG||null,ALCHEMY_INITIAL_BRANCH:process.env.ALCHEMY_INITIAL_BRANCH||null,ALCHEMY_ALLOW_PARALLEL:process.env.ALCHEMY_ALLOW_PARALLEL||null})},6756(e,exports){"use strict"
|
|
3882
3908
|
var t,r
|
|
3883
3909
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.TaskStatus=exports.RequestStatus=void 0,function(e){e.OPEN="open",e.IN_PROGRESS="in_progress",e.COMPLETED="completed",e.CONFLICTED="conflicted",e.READY_FOR_REVIEW="ready_for_review",e.PENDING_APPROVAL="pending_approval"}(t||(exports.RequestStatus=t={})),function(e){e.PENDING="pending",e.IN_PROGRESS="in_progress",e.READY_FOR_REVIEW="ready_for_review",e.COMPLETED="completed"}(r||(exports.TaskStatus=r={}))},6770(e,exports,t){"use strict"
|
|
@@ -3939,12 +3965,12 @@ try{const{taskId:g,showDiff:p=!1}=e
|
|
|
3939
3965
|
if(!g)throw(0,i.createValidationError)("Task ID is required")
|
|
3940
3966
|
if(!/^tas\d{6}$/.test(g))throw(0,i.createValidationError)(`Invalid task ID format: ${g}. Expected format: tas######`)
|
|
3941
3967
|
s.info("Getting file changes for task "+g,{showDiff:p})
|
|
3942
|
-
const
|
|
3968
|
+
const m=r.getTaskClient(),f=r.getToolRecordClient(),y=t.projectId
|
|
3943
3969
|
let w
|
|
3944
3970
|
r.setProjectId(y)
|
|
3945
|
-
try{const P=await
|
|
3971
|
+
try{const P=await m.getTask(g)
|
|
3946
3972
|
s.info("Raw task response data",{responseDataType:typeof P,isArray:Array.isArray(P),hasData:null!=P,properties:P&&"object"==typeof P?Object.keys(P):[]}),w=(0,l.extractDataFromResponse)(P,{logger:s,operationName:"getTask",defaultValue:{id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}),s.info("Found task: "+w.title)}catch(j){s.warn("Could not fetch task information: "+(0,u.getErrorMessage)(j)),w={id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}let k=[]
|
|
3947
|
-
try{const x=await
|
|
3973
|
+
try{const x=await f.getToolRecordsByTaskId(g)
|
|
3948
3974
|
if(s.info("Raw records response data",{responseDataType:typeof x,isArray:Array.isArray(x),hasData:null!=x,properties:x&&"object"==typeof x?Object.keys(x):[]}),k=(0,l.extractArrayFromResponse)(x,{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 R={}
|
|
3949
3975
|
k.forEach((e=>{R[e.type]=(R[e.type]||0)+1})),s.info("Record type distribution:",R)}}catch(M){s.warn("Error fetching records for task "+g,{error:(0,u.getErrorMessage)(M)}),k=[]}if(0===k.length)return h({success:!0,recordCount:0}),{content:[{type:"text",text:`No records found for task ${g}.`}]}
|
|
3950
3976
|
function I(e){const t=new Map,r=new Map,n=[]
|
|
@@ -4024,12 +4050,12 @@ _.set(A,{firstChange:G,lastChange:H,hasDiff:!0,diffText:de}),s.info(`Formatted n
|
|
|
4024
4050
|
continue}}catch(ge){s.warn("Error getting new file content for "+A,{error:(0,u.getErrorMessage)(ge)})}_.set(A,{firstChange:G,lastChange:H,hasDiff:!1,diffText:"Only one commit available for this file"})
|
|
4025
4051
|
continue}if(z.commitHash===H.commitHash&&U){if(B===z.commitHash){_.set(A,{firstChange:G,lastChange:H,hasDiff:!1,diffText:"No changes detected"})
|
|
4026
4052
|
continue}s.info("Special case: First and last task commits are the same, but pre-task commit is different")}let W="",V=!1
|
|
4027
|
-
if(p||"pre-task"!==G.status){try{if(t.git){try{await t.git.show([`${H.commitHash}:${A}`])}catch(
|
|
4053
|
+
if(p||"pre-task"!==G.status){try{if(t.git){try{await t.git.show([`${H.commitHash}:${A}`])}catch(me){s.warn(`File ${A} does not exist in commit ${H.commitHash}, might be deleted or moved`),W="File was deleted or moved from this location during the task",V=!0,_.set(A,{firstChange:G,lastChange:H,hasDiff:V,diffText:W})
|
|
4028
4054
|
continue}let pe
|
|
4029
4055
|
if("pre-task"===G.status?(pe=[`${G.commitHash}..${H.commitHash}`,"--",A],s.info(`Comparing pre-task commit with final commit: ${G.commitHash?G.commitHash.substring(0,8):"unknown"}..${H.commitHash?H.commitHash.substring(0,8):"unknown"} for ${A}`)):(pe=["4b825dc642cb6eb9a060e54bf8d69288fbee4904.."+H.commitHash,"--",A],s.info(`File created during task, showing full file diff using empty tree object: ${H.commitHash?H.commitHash.substring(0,8):"unknown"} for ${A}`)),W=await t.git.diff(pe),V=!!W&&W.trim().length>0,!V&&G.commitHash!==H.commitHash){s.info("No diff found between commits but commits are different, trying direct file content comparison")
|
|
4030
|
-
try{const
|
|
4031
|
-
if(
|
|
4032
|
-
Math.abs(we.length-ke.length)>0&&(W+=`\n\nLine count changed: ${we.length} \u2192 ${ke.length}`),
|
|
4056
|
+
try{const fe=await t.git.show([`${G.commitHash}:${A}`]),ye=await t.git.show([`${H.commitHash}:${A}`])
|
|
4057
|
+
if(fe!==ye&&(V=!0,W="Changes detected through direct content comparison (not visible in standard diff)",p)){const we=fe.split("\n"),ke=ye.split("\n")
|
|
4058
|
+
Math.abs(we.length-ke.length)>0&&(W+=`\n\nLine count changed: ${we.length} \u2192 ${ke.length}`),fe.includes("\0")||ye.includes("\0")?W+="\n\nBinary content detected - changes not displayed":fe.replace(/\s+/g,"")===ye.replace(/\s+/g,"")&&(W+="\n\nWhitespace-only changes detected")}}catch(Ie){s.warn("Error in direct file comparison: "+(Ie instanceof Error?Ie.message:Ie+""))}}s.info(`Diff generation result for ${A}: hasDiff=${V}, length=${W.length}`)}}catch(be){if(s.warn("Error getting diff for "+A,{error:(0,u.getErrorMessage)(be),firstCommit:z.commitHash||"unknown",lastCommit:H.commitHash||"unknown"}),W="Error getting diff: "+(0,u.getErrorMessage)(be),"pre-task"!==z.status&&t.git)try{const ve=[`${H.commitHash}:${A}`]
|
|
4033
4059
|
s.info(`Trying fallback to show file content using git show: ${H.commitHash?H.commitHash.substring(0,8):"unknown"}:${A}`)
|
|
4034
4060
|
const Ce=await t.git.show(ve)
|
|
4035
4061
|
if(Ce&&Ce.trim().length>0){if(p){let _e=""
|
|
@@ -4189,31 +4215,31 @@ const p=d.startTimer("tool_handler_duration")
|
|
|
4189
4215
|
try{if(e&&"string"==typeof e.acceptanceCriteria)try{e.acceptanceCriteria=JSON.parse(e.acceptanceCriteria)}catch{}const l=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)
|
|
4190
4216
|
throw new n.ValidationError("Invalid input: "+(0,i.getErrorMessage)(e))}}(e)
|
|
4191
4217
|
d.incrementCounter("create_request_attempts",1,{type:l.type,criteriaCounts:l.acceptanceCriteria.length})
|
|
4192
|
-
const
|
|
4193
|
-
if(!
|
|
4194
|
-
c.setProjectId(
|
|
4195
|
-
const
|
|
4218
|
+
const m=t.projectId
|
|
4219
|
+
if(!m)throw new n.ValidationError("Project ID is required for creating requests.")
|
|
4220
|
+
c.setProjectId(m)
|
|
4221
|
+
const f=c.getRequestClient()
|
|
4196
4222
|
let y=(0,a.getApprovalMode)()
|
|
4197
4223
|
try{const e=h?.sessionId
|
|
4198
4224
|
if(e){const t=c.getCLISessionClient()
|
|
4199
4225
|
if(t){const r=await t.getByExternalId(e)
|
|
4200
4226
|
if(r?.workflowId){const e=await c.proxyGet("/api/workflows/"+r.workflowId),t=e?.data||e
|
|
4201
|
-
t?.approvalMode&&(y=(0,a.getApprovalMode)(t.approvalMode))}}}if("none"===y)try{const e=await c.proxyGet("/api/projects/"+
|
|
4227
|
+
t?.approvalMode&&(y=(0,a.getApprovalMode)(t.approvalMode))}}}if("none"===y)try{const e=await c.proxyGet("/api/projects/"+m),t=e?.data||e,r=t?.metadata?.defaultApprovalMode
|
|
4202
4228
|
r&&(y=(0,a.getApprovalMode)(r))}catch(e){g.warn("Failed to read project metadata for approvalMode fallback",{error:(0,i.getErrorMessage)(e)})}}catch(e){g.warn("Failed to resolve approval mode, using default",{error:(0,i.getErrorMessage)(e)})}const w="require-approval"===y&&"quick-edit"!==l.type?"pending_approval":"open"
|
|
4203
4229
|
let k=h
|
|
4204
4230
|
if(h?.sessionId)try{const e=c.getCLISessionClient()
|
|
4205
4231
|
if(e){const t=await e.getByExternalId(h.sessionId)
|
|
4206
4232
|
"planner"!==t?.agentType&&"auto-planner"!==t?.agentType||(k=void 0,g.info("Skipping cliOrigin for planner-created request",{agentType:t.agentType}))}}catch{}const I={title:l.title,description:l.description,type:l.type,acceptanceCriteria:l.acceptanceCriteria,status:w,...l.planDocumentId&&{planDocumentId:l.planDocumentId},...k&&{cliOrigin:k}}
|
|
4207
|
-
g.info("Creating request via request client",{projectId:
|
|
4208
|
-
const b=await
|
|
4233
|
+
g.info("Creating request via request client",{projectId:m,title:l.title,type:l.type,criteriaCount:l.acceptanceCriteria.length})
|
|
4234
|
+
const b=await f.createRequest(I)
|
|
4209
4235
|
g.debug("Create request response structure",{type:typeof b,isArray:Array.isArray(b),hasData:null!=b,properties:b?Object.keys(b):[],dataPreview:b?JSON.stringify(b).substring(0,200)+"...":"null"})
|
|
4210
4236
|
const v=(0,o.extractDataFromResponse)(b,{logger:g,operationName:"createRequest",throwOnNoData:!0}),C="data"in v?v.data:v
|
|
4211
4237
|
let _,E={created:!1}
|
|
4212
4238
|
if(u?.workspaceManager)try{await u.workspaceManager.initializeRequest(C.id,C.title),E={created:!0,branchName:"requests/"+C.id,message:"Branch created successfully"},g.info("Request branch initialized successfully",{requestId:C.id,branchName:E.branchName,title:C.title})}catch(e){g.warn("Failed to initialize request branch, will retry on first operation",{requestId:C.id,error:(0,i.getErrorMessage)(e)})}else"quick-edit"===l.type?g.info("Quick-edit request - skipping branch creation, will work directly on main",{requestId:C.id}):g.debug("No workspace manager available, branch creation deferred",{requestId:C.id})
|
|
4213
4239
|
g.info("Request created successfully",{requestId:C.id,title:C.title,branchCreated:E.created,branchName:E.branchName})
|
|
4214
4240
|
try{const e=c.getToolRecordClient()
|
|
4215
|
-
if(e){const t=await e.createToolRecord({requestId:C.id,projectId:
|
|
4216
|
-
_=t?.id}}catch(e){g.warn("Failed to create tool record for request creation",{error:(0,i.getErrorMessage)(e),requestId:C.id})}p({success:!0,type:l.type,hasProjectId:!0}),g.info("Request created successfully",{requestId:C.id,title:C.title,type:C.type,projectId:
|
|
4241
|
+
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"}`})
|
|
4242
|
+
_=t?.id}}catch(e){g.warn("Failed to create tool record for request creation",{error:(0,i.getErrorMessage)(e),requestId:C.id})}p({success:!0,type:l.type,hasProjectId:!0}),g.info("Request created successfully",{requestId:C.id,title:C.title,type:C.type,projectId:m})
|
|
4217
4243
|
const q=C.localId||C.id
|
|
4218
4244
|
let S="pending_approval"===w?`Created Request ${q} (pending approval)`:"Created Request "+q
|
|
4219
4245
|
return _&&(S+=`\n[RECORD:${_}]`),{content:[{type:"text",text:S}]}}catch(r){if(g.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")))g.info("Skipping tool record creation for disabled project error",{projectId:t.projectId,error:r.message})
|
|
@@ -4235,11 +4261,11 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
4235
4261
|
var t={}
|
|
4236
4262
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4237
4263
|
return o(t,e),t})
|
|
4238
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,r,n,o,s,h,g,p){const
|
|
4239
|
-
try{const u=a.validateArgs(e,i.ModifyFileSchema),{operations:
|
|
4240
|
-
|
|
4264
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,r,n,o,s,h,g,p){const m=h.child({tool:"modify_file"})
|
|
4265
|
+
try{const u=a.validateArgs(e,i.ModifyFileSchema),{operations:f,comment:y}=u,{resolveActiveTaskId:w}=await Promise.resolve().then(t.bind(t,3451)),k=e.taskId||await w(r,n,h)||"untracked"
|
|
4266
|
+
m.info("Processing modify-file operations",{taskId:k,operationCount:f.length,comment:y})
|
|
4241
4267
|
const I=[],b=[],v=[],C=[],_=[]
|
|
4242
|
-
for(const e of
|
|
4268
|
+
for(const e of f){const t={path:e.path,documentId:e.documentId}
|
|
4243
4269
|
switch(e.operationType){case"replace-string":I.push({...t,replacements:e.replaceString.replacements,mode:e.replaceString.mode})
|
|
4244
4270
|
break
|
|
4245
4271
|
case"insert-lines":b.push({...t,insertions:e.insertLines.insertions})
|
|
@@ -4249,41 +4275,41 @@ break
|
|
|
4249
4275
|
case"delete-string":C.push({...t,replacements:e.deleteString.patterns.map((e=>({old_str:e,new_str:""}))),mode:e.deleteString.mode||"all"})
|
|
4250
4276
|
break
|
|
4251
4277
|
case"delete-lines":_.push({...t,lines:e.deleteLines.lines})}}const E=[]
|
|
4252
|
-
if(I.length>0){
|
|
4253
|
-
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:I,comment:y+" [via modify-file: replace-string]"},r,n,o,s,
|
|
4254
|
-
E.push({type:"replace-string",result:e})}if(b.length>0){
|
|
4255
|
-
const e=await(0,l.handleInsertLines)({taskId:k,operations:b,comment:y+" [via modify-file: insert-lines]"},r,n,o,s,
|
|
4256
|
-
E.push({type:"insert-lines",result:e})}if(v.length>0){
|
|
4257
|
-
const e=await(0,d.handleReplaceLines)({taskId:k,operations:v,comment:y+" [via modify-file: replace-lines]"},r,n,o,s,
|
|
4258
|
-
E.push({type:"replace-lines",result:e})}if(C.length>0){
|
|
4259
|
-
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:C,comment:y+" [via modify-file: delete-string]"},r,n,o,s,
|
|
4260
|
-
E.push({type:"delete-string",result:e})}if(_.length>0){
|
|
4261
|
-
const e=_.map((e=>({path:e.path,documentId:e.documentId,replacements:[{lines:e.lines,content:[]}]}))),t=await(0,d.handleReplaceLines)({taskId:k,operations:e,comment:y+" [via modify-file: delete-lines]"},r,n,o,s,
|
|
4278
|
+
if(I.length>0){m.info("Routing to replace-strings handler",{operationCount:I.length})
|
|
4279
|
+
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:I,comment:y+" [via modify-file: replace-string]"},r,n,o,s,m,g,p)
|
|
4280
|
+
E.push({type:"replace-string",result:e})}if(b.length>0){m.info("Routing to insert-lines handler",{operationCount:b.length})
|
|
4281
|
+
const e=await(0,l.handleInsertLines)({taskId:k,operations:b,comment:y+" [via modify-file: insert-lines]"},r,n,o,s,m,g,p)
|
|
4282
|
+
E.push({type:"insert-lines",result:e})}if(v.length>0){m.info("Routing to replace-lines handler",{operationCount:v.length})
|
|
4283
|
+
const e=await(0,d.handleReplaceLines)({taskId:k,operations:v,comment:y+" [via modify-file: replace-lines]"},r,n,o,s,m,g,p)
|
|
4284
|
+
E.push({type:"replace-lines",result:e})}if(C.length>0){m.info("Routing delete-string to replace-strings handler",{operationCount:C.length})
|
|
4285
|
+
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:C,comment:y+" [via modify-file: delete-string]"},r,n,o,s,m,g,p)
|
|
4286
|
+
E.push({type:"delete-string",result:e})}if(_.length>0){m.info("Processing delete-lines operations",{operationCount:_.length})
|
|
4287
|
+
const e=_.map((e=>({path:e.path,documentId:e.documentId,replacements:[{lines:e.lines,content:[]}]}))),t=await(0,d.handleReplaceLines)({taskId:k,operations:e,comment:y+" [via modify-file: delete-lines]"},r,n,o,s,m,g,p)
|
|
4262
4288
|
E.push({type:"delete-lines",result:t})}const q=E.some((e=>e.result.isError)),S=E.filter((e=>!e.result.isError)).length,T=E.filter((e=>e.result.isError)).length
|
|
4263
4289
|
let P="## Modify File Results\n\n"
|
|
4264
4290
|
P+="**Summary:**\n",P+=`- **Total operation types:** ${E.length}\n`,P+=`- **Successful:** ${S}\n`,P+=`- **Failed:** ${T}\n\n`
|
|
4265
4291
|
for(const{type:e,result:t}of E)P+=`### ${e} operations\n`,P+=t.content[0].text+"\n\n"
|
|
4266
|
-
return
|
|
4292
|
+
return m.info("Modify-file operations completed",{totalOperationTypes:E.length,successCount:S,errorCount:T}),g.incrementCounter("modify_file_total",1,{success:!q}),{content:[{type:"text",text:P}],isError:q}}catch(e){return m.error("Modify-file operation failed",{error:e instanceof Error?e.stack:e+""}),g.incrementCounter("modify_file_errors",1),{content:[{type:"text",text:"\u274c **Modify File Failed:** "+(0,u.getErrorMessage)(e)}],isError:!0}}}
|
|
4267
4293
|
const i=t(6183),a=s(t(5967)),c=t(3306),l=t(6486),d=t(6651),u=t(8824)},7478(e,exports,t){"use strict"
|
|
4268
4294
|
async function r(e,t,r){const n=r.startTimer("git_get_current_branch_duration")
|
|
4269
4295
|
try{const o=(await e.status()).current
|
|
4270
4296
|
if(!o)throw new g.ValidationError("Repository is in detached HEAD state or branch detection failed")
|
|
4271
|
-
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,
|
|
4297
|
+
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,m.getErrorMessage)(e)
|
|
4272
4298
|
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")
|
|
4273
4299
|
try{const s=(await e.branch(["-l"])).all.includes(t)
|
|
4274
|
-
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,
|
|
4300
|
+
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,m.getErrorMessage)(e)
|
|
4275
4301
|
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")
|
|
4276
4302
|
try{const a=await r(e,o,s)
|
|
4277
4303
|
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}'`}
|
|
4278
4304
|
if(!await n(e,t,o,s)){const e=`Branch '${t}' does not exist`
|
|
4279
4305
|
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)
|
|
4280
4306
|
const c=await e.revparse(["HEAD"])
|
|
4281
|
-
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,
|
|
4307
|
+
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,m.getErrorMessage)(e)
|
|
4282
4308
|
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")
|
|
4283
4309
|
try{let o,s=!0
|
|
4284
4310
|
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")
|
|
4285
4311
|
let g=""
|
|
4286
|
-
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,
|
|
4312
|
+
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,m.getErrorMessage)(e)
|
|
4287
4313
|
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")
|
|
4288
4314
|
try{t.debug("Starting uncommitted changes check"),t.debug("Checking for uncommitted changes before merge"),Date.now()
|
|
4289
4315
|
const o=await e.status()
|
|
@@ -4295,7 +4321,7 @@ t.debug("Uncommitted changes summary",{hasChanges:l,totalFiles:c,staged:s.length
|
|
|
4295
4321
|
let d=""
|
|
4296
4322
|
if(l){const e=[]
|
|
4297
4323
|
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"
|
|
4298
|
-
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,
|
|
4324
|
+
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,m.getErrorMessage)(e)
|
|
4299
4325
|
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)
|
|
4300
4326
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
4301
4327
|
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=[]
|
|
@@ -4309,34 +4335,34 @@ try{if(await n(e,t,s,i)){const e=`Branch '${t}' already exists`
|
|
|
4309
4335
|
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)
|
|
4310
4336
|
await e.checkoutBranch(t,o)
|
|
4311
4337
|
const d=await e.revparse(["HEAD"]),u=a||l
|
|
4312
|
-
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,
|
|
4338
|
+
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,m.getErrorMessage)(e)
|
|
4313
4339
|
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")
|
|
4314
4340
|
try{const d=await r(e,i,a)
|
|
4315
4341
|
if(d!==s&&await o(e,s,i,a),!await n(e,t,i,a)){const e=`Source branch '${t}' does not exist`
|
|
4316
4342
|
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"]))
|
|
4317
|
-
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,
|
|
4343
|
+
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,m.getErrorMessage)(e)
|
|
4318
4344
|
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")
|
|
4319
4345
|
try{const c=await r(e,s,i)
|
|
4320
4346
|
if(c===t){const e=`Cannot delete current branch '${t}'`
|
|
4321
4347
|
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}'`
|
|
4322
4348
|
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`
|
|
4323
4349
|
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]
|
|
4324
|
-
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,
|
|
4350
|
+
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,m.getErrorMessage)(e)
|
|
4325
4351
|
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")
|
|
4326
4352
|
try{const o=await s(e,t,r)
|
|
4327
|
-
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,
|
|
4353
|
+
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,m.getErrorMessage)(e)
|
|
4328
4354
|
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)
|
|
4329
4355
|
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})-/)
|
|
4330
4356
|
return t?t[1]:null},exports.switchToDefaultBranch=async function(e,t,r){const n=r.startTimer("git_switch_to_default_duration")
|
|
4331
4357
|
try{const i=await s(e,t,r)
|
|
4332
4358
|
if(!i.defaultBranch){const e="No default branch found"
|
|
4333
4359
|
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)
|
|
4334
|
-
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,
|
|
4360
|
+
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,m.getErrorMessage)(e)
|
|
4335
4361
|
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")
|
|
4336
4362
|
try{const o=await s(e,t,r),i=[]
|
|
4337
4363
|
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")
|
|
4338
4364
|
const a=0===i.length
|
|
4339
|
-
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,
|
|
4365
|
+
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,m.getErrorMessage)(e)
|
|
4340
4366
|
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")
|
|
4341
4367
|
try{r.debug("Starting main branch change detection",{providedRevertCommitHash:t.substring(0,8),fullRevertCommitHash:t})
|
|
4342
4368
|
const n=await e.revparse(["HEAD"])
|
|
@@ -4352,10 +4378,10 @@ let a=!1,c=0,l=null
|
|
|
4352
4378
|
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})
|
|
4353
4379
|
const o=await e.raw(["rev-list","--count",t+"..HEAD"])
|
|
4354
4380
|
c=parseInt(o.trim(),10),a=!0
|
|
4355
|
-
break}catch(e){l=e,r.debug("Ancestor check attempt failed",{attempt:n,error:(0,
|
|
4381
|
+
break}catch(e){l=e,r.debug("Ancestor check attempt failed",{attempt:n,error:(0,m.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"])
|
|
4356
4382
|
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})
|
|
4357
4383
|
try{const o=await e.raw(["merge-base",t,"HEAD"])
|
|
4358
|
-
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,
|
|
4384
|
+
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,m.getErrorMessage)(e)
|
|
4359
4385
|
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})
|
|
4360
4386
|
const n=await t.getToolRecordsByRequestId(e,"revert-request")
|
|
4361
4387
|
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"}
|
|
@@ -4364,7 +4390,7 @@ for(const t of n)if(r.debug("Examining tool record",{requestId:e,recordId:t.id,r
|
|
|
4364
4390
|
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})
|
|
4365
4391
|
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"})
|
|
4366
4392
|
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+""})
|
|
4367
|
-
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,
|
|
4393
|
+
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,m.getErrorMessage)(t)
|
|
4368
4394
|
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")
|
|
4369
4395
|
try{if(!r.hasChanges)throw new g.ValidationError("No uncommitted changes to commit")
|
|
4370
4396
|
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})
|
|
@@ -4373,7 +4399,7 @@ i.length>0?(n.debug("Staging files",{files:i.slice(0,10),total:i.length}),await
|
|
|
4373
4399
|
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.`
|
|
4374
4400
|
n.debug("Commit message",{message:a.split("\n")[0]}),n.debug("Creating commit"),await e.commit(a)
|
|
4375
4401
|
const c=await e.revparse(["HEAD"])
|
|
4376
|
-
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,
|
|
4402
|
+
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,m.getErrorMessage)(e)
|
|
4377
4403
|
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")
|
|
4378
4404
|
try{let c=Date.now()
|
|
4379
4405
|
o.debug("Checking for user changes before tool operation",{toolName:r})
|
|
@@ -4391,16 +4417,16 @@ o.debug("Committing user changes with message",{firstLine:h.split("\n")[0]})
|
|
|
4391
4417
|
const g=[...d.unstagedFiles,...d.untrackedFiles]
|
|
4392
4418
|
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()
|
|
4393
4419
|
const p=await l.revparse(["HEAD"])
|
|
4394
|
-
return o.debug("User changes committed successfully before tool",{commitHash:p.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:p.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:p,filesCommitted:d.totalFiles}}catch(e){const t=(0,
|
|
4420
|
+
return o.debug("User changes committed successfully before tool",{commitHash:p.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:p.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:p,filesCommitted:d.totalFiles}}catch(e){const t=(0,m.getErrorMessage)(e)
|
|
4395
4421
|
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=[]
|
|
4396
4422
|
try{const o=t(3807).simpleGit(e),s=(await o.status()).not_added||[]
|
|
4397
|
-
for(const t of s)try{const o=y.join(e,t),s=
|
|
4423
|
+
for(const t of s)try{const o=y.join(e,t),s=f.statSync(o)
|
|
4398
4424
|
s.isFile()&&s.size>=r&&n.push({path:t,sizeBytes:s.size,sizeMB:Math.round(s.size/1048576*10)/10})}catch{}}catch{}return n},exports.formatLargeFileWarning=function(e){if(0===e.length)return""
|
|
4399
4425
|
const t=e.reduce(((e,t)=>e+t.sizeMB),0)
|
|
4400
4426
|
let r=`\n\n\u26a0\ufe0f **Performance Warning**: Large untracked files detected (${Math.round(t)} MB total) that may slow git operations:\n`
|
|
4401
4427
|
for(const t of e.slice(0,5))r+=`- \`${t.path}\` (${t.sizeMB} MB)\n`
|
|
4402
4428
|
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}
|
|
4403
|
-
const h=t(3444),g=t(9860),p=t(3922),
|
|
4429
|
+
const h=t(3444),g=t(9860),p=t(3922),m=t(8824),f=u(t(9896)),y=u(t(6928))
|
|
4404
4430
|
t(857)},7561(e,exports,t){"use strict"
|
|
4405
4431
|
async function r(e,t){const r=e.getTaskClient(),n=await r.listTasks({requestId:t,status:"in_progress"})
|
|
4406
4432
|
if(0===n.length)return null
|
|
@@ -4420,8 +4446,8 @@ if(!n)return{content:[{type:"text",text:"Error: description is required for crea
|
|
|
4420
4446
|
const s=i.getTaskClient(),a=await s.createTask({requestId:h,projectId:c,title:t,description:n}),l=a.localId||a.id,u=await r(i,h)
|
|
4421
4447
|
let g=!1
|
|
4422
4448
|
if(!u)try{await s.updateTaskStatus(l,"in_progress"),g=!0}catch(e){d.debug("Could not auto-start task",{taskId:l,error:(0,o.getErrorMessage)(e)})}const p=a.sequenceNumber??null
|
|
4423
|
-
let
|
|
4424
|
-
return g&&(
|
|
4449
|
+
let m=p?`Created #${p}: ${t}`:`Created ${l}: ${t}`
|
|
4450
|
+
return g&&(m+=" (started)"),{content:[{type:"text",text:m}]}}case"done":{const{summary:t}=e
|
|
4425
4451
|
if(!t)return{content:[{type:"text",text:"Error: summary is required for done"}],isError:!0}
|
|
4426
4452
|
const n=await r(i,h)
|
|
4427
4453
|
if(!n)return{content:[{type:"text",text:"No active (in_progress) task to complete."}],isError:!0}
|
|
@@ -4452,7 +4478,7 @@ return s.info("Plan updated",{planId:a}),{content:[{type:"text",text:`\u2705 **P
|
|
|
4452
4478
|
const r=t(8824)},7613(e,exports,t){"use strict"
|
|
4453
4479
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4454
4480
|
const r=t(6183),n=t(9072)
|
|
4455
|
-
exports.def={name:"session_message_operations",description:'Inter-session messaging (questions and reports).\n\nOperations:\n\u2022 send - Send a message (type: "question" or "report")\n\u2022 reply - Reply to a message (answer a question or acknowledge a report). Type inferred from code prefix (Q-/R-).\n\u2022 list - List messages (filter by messageType, direction, status)\n\u2022 get - Get a message by its code\n\u2022 offer-handoff - Present the user with a choice to start building or keep planning\n\nMessage codes: Q-{id}-{seq} for questions, R-{id}-{seq} for reports.',schema:r.SessionMessageOperationsSchema,annotations:{title:"Session Message Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSessionMessageOperations)(e,t.context,t.logger,t.metrics,t.apiClient??void 0)}}},7617(e,exports,t){"use strict"
|
|
4481
|
+
exports.def={name:"session_message_operations",description:'Inter-session messaging (questions and reports).\n\nOperations:\n\u2022 send - Send a message (type: "question" or "report")\n\u2022 reply - Reply to a message (answer a question or acknowledge a report). Type inferred from code prefix (Q-/R-).\n\u2022 list - List messages (filter by messageType, direction, status)\n\u2022 get - Get a message by its code\n\u2022 offer-handoff - Present the user with a choice to start building or keep planning\n\nMessage codes: Q-{id}-{seq} for questions, R-{id}-{seq} for reports.',schema:r.SessionMessageOperationsSchema,annotations:{title:"Session Message Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSessionMessageOperations)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},7617(e,exports,t){"use strict"
|
|
4456
4482
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.getServerUrl=async function(e,r){let n=process.env.OPENCODE_TUI_URL
|
|
4457
4483
|
if(!n)try{const{readFileSync:o}=await Promise.resolve().then(t.t.bind(t,9896,23)),{join:s}=await Promise.resolve().then(t.t.bind(t,6928,23)),i=o(s(e.basePath,".alchemy_lab","opencode.json"),"utf8"),a=JSON.parse(i)
|
|
4458
4484
|
a.port&&(n="http://127.0.0.1:"+a.port,r.debug("Discovered OpenCode server URL from .alchemy_lab/opencode.json",{serverUrl:n}))}catch(e){r.debug("Could not read .alchemy_lab/opencode.json",{error:e instanceof Error?e.message:e+""})}return n}},7621(e,exports,t){"use strict"
|
|
@@ -4649,7 +4675,7 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
4649
4675
|
var t={}
|
|
4650
4676
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4651
4677
|
return o(t,e),t})
|
|
4652
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,r,n,o,s,g,p,f
|
|
4678
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,r,n,o,s,g,p,m,f){const y=p.child({tool:"manage_files"})
|
|
4653
4679
|
try{const h=a.validateArgs(e,i.ManageFilesSchema),{operations:w,comment:k}=h,{resolveActiveTaskId:I}=await Promise.resolve().then(t.bind(t,3451)),b=e.taskId||await I(r,g,p)||"untracked"
|
|
4654
4680
|
y.info("Processing manage-files operations",{taskId:b,operationCount:w.length,comment:k})
|
|
4655
4681
|
const v=[],C=[],_=[],E=[]
|
|
@@ -4661,18 +4687,18 @@ case"delete-files":_.push(...e.deleteFiles.targets)
|
|
|
4661
4687
|
break
|
|
4662
4688
|
case"get-file-info":E.push({path:e.getFileInfo.path})}const q=[]
|
|
4663
4689
|
for(const e of v){y.info("Routing to create-directory handler",{path:e.path})
|
|
4664
|
-
const t=await(0,c.handleCreateDirectory)({taskId:b,path:e.path,comment:k+" [via manage-files: create-directory]"},r,n,o,s,y,f
|
|
4690
|
+
const t=await(0,c.handleCreateDirectory)({taskId:b,path:e.path,comment:k+" [via manage-files: create-directory]"},r,n,o,s,y,m,f)
|
|
4665
4691
|
q.push({type:"create-directory",result:t})}if(C.length>0){y.info("Routing to move-files handler",{operationCount:C.length})
|
|
4666
|
-
const e=await(0,l.handleMoveFiles)({taskId:b,operations:C,comment:k+" [via manage-files: move-files]"},r,n,o,s,y,f
|
|
4692
|
+
const e=await(0,l.handleMoveFiles)({taskId:b,operations:C,comment:k+" [via manage-files: move-files]"},r,n,o,s,y,m,f)
|
|
4667
4693
|
q.push({type:"move-files",result:e})}if(_.length>0){y.info("Routing to delete-files handler",{operationCount:_.length})
|
|
4668
|
-
const e=await(0,u.handleDeleteFiles)({taskId:b,operations:_,comment:k+" [via manage-files: delete-files]"},r,g,y,f
|
|
4694
|
+
const e=await(0,u.handleDeleteFiles)({taskId:b,operations:_,comment:k+" [via manage-files: delete-files]"},r,g,y,m,f)
|
|
4669
4695
|
q.push({type:"delete-files",result:e})}for(const e of E){y.info("Routing to get-file-info handler",{path:e.path})
|
|
4670
|
-
const t=await(0,d.handleGetFileInfo)({path:e.path},r,y,
|
|
4696
|
+
const t=await(0,d.handleGetFileInfo)({path:e.path},r,y,m)
|
|
4671
4697
|
q.push({type:"get-file-info",result:t})}const S=q.some((e=>e.result.isError)),T=q.filter((e=>!e.result.isError)).length,P=q.filter((e=>e.result.isError)).length
|
|
4672
4698
|
let j="## Manage Files Results\n\n"
|
|
4673
4699
|
j+="**Summary:**\n",j+=`- **Total operation types:** ${q.length}\n`,j+=`- **Successful:** ${T}\n`,j+=`- **Failed:** ${P}\n\n`
|
|
4674
4700
|
for(const{type:e,result:t}of q)j+=`### ${e} operations\n`,j+=t.content[0].text+"\n\n"
|
|
4675
|
-
return y.info("Manage-files operations completed",{totalOperationTypes:q.length,successCount:T,errorCount:P}),
|
|
4701
|
+
return y.info("Manage-files operations completed",{totalOperationTypes:q.length,successCount:T,errorCount:P}),m.incrementCounter("manage_files_total",1,{success:!S}),{content:[{type:"text",text:j}],isError:S}}catch(e){return y.error("Manage-files operation failed",{error:e instanceof Error?e.stack:e+""}),m.incrementCounter("manage_files_errors",1),{content:[{type:"text",text:"\u274c **Manage Files Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
|
|
4676
4702
|
const i=t(6183),a=s(t(5967)),c=t(8309),l=t(2414),d=t(3628),u=t(5992),h=t(8824)},7713(e,exports,t){"use strict"
|
|
4677
4703
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4678
4704
|
const r=t(6183),n=t(5303)
|
|
@@ -4711,33 +4737,33 @@ if(o.workspaceManager){const t=o.workspaceManager.getCurrentContext(o.currentSes
|
|
|
4711
4737
|
"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}
|
|
4712
4738
|
let g=null
|
|
4713
4739
|
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)
|
|
4714
|
-
const p=1===n.length?`${s} in ${n[0]} (${i})`:`${s} in ${n.length} files (${i})`,
|
|
4715
|
-
return l.info("Changes committed to git via shared multi-file utility",{commitMessage:p,filesCommitted:n.length,commitHash:
|
|
4740
|
+
const p=1===n.length?`${s} in ${n[0]} (${i})`:`${s} in ${n.length} files (${i})`,m=(await d.commit(p)).commit
|
|
4741
|
+
return l.info("Changes committed to git via shared multi-file utility",{commitMessage:p,filesCommitted:n.length,commitHash:m?.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:m,previousCommitHash:g,filesCommitted:n,success:!0}}catch(e){const t=(0,d.getErrorMessage)(e)
|
|
4716
4742
|
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}}
|
|
4717
4743
|
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()
|
|
4718
|
-
let p,
|
|
4744
|
+
let p,m
|
|
4719
4745
|
l.debug("createFileOperationRecords called",{taskId:e,requestId:t,projectId:n||"<empty>",projectIdType:typeof n,operationType:o,path:s})
|
|
4720
4746
|
try{const a=await r(e,t,n,o,s,i,c,l,u,h)
|
|
4721
|
-
return p=a.recordId,
|
|
4747
|
+
return p=a.recordId,m=a.localRecordId,l.info("Created tool record for file operation: "+o,{taskId:e,path:s,toolRecordId:p,localToolRecordId:m}),{toolRecordId:p,localToolRecordId:m}}catch(r){throw l.error("Failed to create tool record for file operation: "+o,{error:(0,d.getErrorMessage)(r),errorStack:r instanceof Error?r.stack:void 0,taskId:e,requestId:t,projectId:n||"<empty>",projectIdType:typeof n,path:s}),u.recordValue(h+"_record_creation_time",Date.now()-g),u.incrementCounter(h+"_record_creation_error",1),r}},exports.updateFileOperationRecords=async function(e,t,r,o,s,i,a,c,l,u,h,g,p){try{t&&h.info("Task record update skipped (task records removed): "+t,{taskId:e,path:o}),r&&await n(r,o,s,a,c,u,h,g,p)}catch(t){h.warn("Error updating tool record for operation: "+s,{error:(0,d.getErrorMessage)(t),taskId:e,normalizedPath:o,toolRecordId:r})}},exports.checkAndCommitUserMods=async function(e,t,r,n,o){if(!t.git)return{hadUserMods:!1}
|
|
4722
4748
|
try{let s=t.git
|
|
4723
4749
|
if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
4724
4750
|
"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)
|
|
4725
4751
|
const t=await s.commit("[USER-MODS] Preserve user modifications before tool operation: "+e)
|
|
4726
4752
|
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()
|
|
4727
4753
|
let g,p=null
|
|
4728
|
-
try{let
|
|
4754
|
+
try{let m=s.git
|
|
4729
4755
|
if(s.workspaceManager){const t=s.workspaceManager.getCurrentContext(s.currentSessionId)
|
|
4730
4756
|
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.`)
|
|
4731
|
-
|
|
4732
|
-
let a=!1,
|
|
4733
|
-
try{if(
|
|
4757
|
+
m=(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(m){i.info("commitToGit called with:",{taskId:e,recordId:r,localRecordId:n,hasLocalRecordId:!!n,localRecordIdType:typeof n,normalizedPath:t})
|
|
4758
|
+
let a=!1,f=""
|
|
4759
|
+
try{if(f=(await m.raw(["rev-parse","--show-toplevel"])).trim(),a=f.includes("/worktrees/")||f.includes("\\worktrees\\"),i.info("Git context detection for commit operation:",{taskId:e,gitRepoPath:f,isWorktreeOperation:a,targetFile:t,expectedContext:"worktree"}),!a)throw i.error("CRITICAL: Multi-agent operation using main repo Git instead of worktree",{taskId:e,detectedPath:f,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 ${f}, 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 m.revparse(["--abbrev-ref","HEAD"]),n=await m.revparse(["HEAD"]),o=await m.revparse(["--show-toplevel"])
|
|
4734
4760
|
i.info("Git repository status before commit:",{taskId:e,currentBranch:r.trim(),currentCommit:n.trim().substring(0,8),repoPath:o.trim(),targetFile:t,currentRequestId:s.getCurrentRequestId?s.getCurrentRequestId():"none"})
|
|
4735
4761
|
const a=r.trim(),c=s.getCurrentRequestId?s.getCurrentRequestId():null
|
|
4736
4762
|
if(c){const t="requests/"+c
|
|
4737
|
-
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(
|
|
4738
|
-
p=await(0,l.findPreviousCommit)(
|
|
4739
|
-
await
|
|
4740
|
-
try{const r=await
|
|
4763
|
+
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(m){const r=await m.revparse(["HEAD"])
|
|
4764
|
+
p=await(0,l.findPreviousCommit)(m,t,r),i.info(`Previous commit hash for ${t}: ${p||"none (new file)"}`,{taskId:e,gitInstancePath:f||"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
|
|
4765
|
+
await m.add(t),g=(await m.commit(y)).commit
|
|
4766
|
+
try{const r=await m.revparse(["--abbrev-ref","HEAD"]),n=await m.revparse(["HEAD"])
|
|
4741
4767
|
i.info("Git repository status after commit:",{taskId:e,postCommitBranch:r.trim(),postCommitHash:n.trim().substring(0,8),commitAdvanced:n.trim()!==(p||""),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:p}),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})
|
|
4742
4768
|
return{commitHash:g,previousCommitHash:p}}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:p}}},exports.commitMultipleFilesToGit=o,exports.handleMultiFileGitCommit=async function(e,t,r,n,s,i){const{logger:a,metricsPrefix:c,metrics:l}=s
|
|
4743
4769
|
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))}
|
|
@@ -4760,9 +4786,9 @@ return o.fromString(`prj_${e}_${t}`)},fromString(e){return this.isValid(e)?new o
|
|
|
4760
4786
|
if(e.includes("_")){const t=e.split("_")
|
|
4761
4787
|
return t.length>=3&&"prj"===t[0]}return!1}},exports.ProjectIDBackwardCompat={create:exports.ProjectIDFactory.create,fromString:exports.ProjectIDFactory.fromString,isValid:exports.ProjectIDFactory.isValid},Object.assign(o,exports.ProjectIDBackwardCompat)},8035(e,exports,t){"use strict"
|
|
4762
4788
|
function r(e,t,r){try{const n=`[${(new Date).toISOString()}] [detached-subagent] ${t}${r?" "+JSON.stringify(r):""}\n`,o=(0,i.join)(e||process.cwd(),".alchemy_lab","spawn-debug.log");(0,s.appendFileSync)(o,n)}catch{}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.spawnDetachedSubagent=function(e){const{agent:t,prompt:c,cwd:l,sessionId:d,model:u,initialBranch:h,serverUrl:g,onSpawn:p}=e
|
|
4763
|
-
try{const o={...process.env},
|
|
4764
|
-
o.OPENCODE_DATA_DIR=(0,i.join)(
|
|
4765
|
-
const
|
|
4789
|
+
try{const o={...process.env},m=l||process.cwd()
|
|
4790
|
+
o.OPENCODE_DATA_DIR=(0,i.join)(m,".alchemy_lab","opencode"),h&&(o.ALCHEMY_INITIAL_BRANCH=h),e.allowParallel&&(o.ALCHEMY_ALLOW_PARALLEL="1")
|
|
4791
|
+
const f=new Date,y=`${(f.getHours()+"").padStart(2,"0")}${(f.getMinutes()+"").padStart(2,"0")}${(f.getSeconds()+"").padStart(2,"0")}`,w=Math.random().toString(36).substring(2,7)
|
|
4766
4792
|
let k
|
|
4767
4793
|
if(o.ALCHEMY_SESSION_TAG=`mcp-${y}-${w}`,r(l,"Spawn env setup",{agent:t,initialBranch:h||"none",sessionId:d||"new",attachMode:!!g}),k=g&&d&&c?["run","--attach",g,"--session",d,"--agent",t,c]:d&&c?["run","--session",d,"--agent",t,c]:c?["run","--agent",t,c]:["run","--agent",t],u){const e=k.findIndex((e=>e===c))
|
|
4768
4794
|
e>0?k.splice(e,0,"--model",u):k.push("--model",u)}r(l,"Spawning opencode",{args:k.map((e=>e===c?`[prompt:${e.length}chars]`:e)),model:u||"not specified",promptLength:c?.length,promptPreview:c?.slice(0,100),cwd:l,hasSessionId:!!d})
|
|
@@ -4787,13 +4813,13 @@ l.debug("=== SERVER RESPONSE DATA SECTION ===",{dataType:typeof e,isDataArray:Ar
|
|
|
4787
4813
|
const p=(0,n.extractArrayFromResponse)(g,{logger:l,operationName:"listRequests",defaultValue:[]})
|
|
4788
4814
|
if(l.info("=== AFTER EXTRACTION ===",{extractedCount:p.length,firstItemAfterExtraction:p.length>0?{id:p[0].id,hasLockInfo:"lockInfo"in p[0],lockInfo:p[0].lockInfo,allKeys:Object.keys(p[0])}:"no items"}),l.info(`Extracted ${p.length} requests from response`),l.debug("Lock info analysis",{requestCount:p.length,firstRequestSample:p.length>0?{id:p[0].id,hasLockInfo:!!p[0].lockInfo,lockInfo:p[0].lockInfo,allProperties:Object.keys(p[0])}:"No requests to sample"}),p.length>0&&p.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===p.length)return d({success:!0,requestCount:0}),{content:[{type:"text",text:"No requests found with the specified filters."}]}
|
|
4789
4815
|
l.info("=== PRE-DISPLAY REQUEST ANALYSIS ===",{totalRequests:p.length}),p.forEach(((e,t)=>{l.info(`=== REQUEST ${t+1}/${p.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)})}))
|
|
4790
|
-
const
|
|
4816
|
+
const m=p.map((e=>{let t=""
|
|
4791
4817
|
if(l.info(`=== FORMATTING REQUEST ${e.id} ===`,{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"
|
|
4792
4818
|
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]"
|
|
4793
4819
|
l.debug(`Generated lock info for ${e.id}: "${t}"`)}else l.debug("No lock info available for "+e.id)
|
|
4794
|
-
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"),
|
|
4820
|
+
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"),f=p.some((e=>e.lockInfo))
|
|
4795
4821
|
let y=`Found ${p.length} request${1===p.length?"":"s"}:`
|
|
4796
|
-
return
|
|
4822
|
+
return f&&(y+="\n\n**Lock Status:**\n",y+="LOCKED = Locked by an agent (shows session name and expiration)\n",y+="AVAILABLE = Not currently locked, safe to work on\n"),d({success:!0,requestCount:p.length}),{content:[{type:"text",text:`${y}\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}}}
|
|
4797
4823
|
const r=t(9860),n=t(2960),o=t(5172),s=t(8824)},8045(e,exports,t){"use strict"
|
|
4798
4824
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4799
4825
|
const r=t(6183),n=t(7456)
|
|
@@ -4823,33 +4849,33 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
4823
4849
|
var t={}
|
|
4824
4850
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4825
4851
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
4826
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,r,n,o,s,i,p,
|
|
4852
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,r,n,o,s,i,p,m){const f=i.child({tool:"create_directory"}),y=Date.now()
|
|
4827
4853
|
let w,k,I=d.FileOperationPhase.VALIDATION
|
|
4828
4854
|
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}"}
|
|
4829
4855
|
try{const u=d.validateArgs(e,l.CreateDirectorySchema),{path:h,comment:g}=u,{resolveActiveTaskId:v}=await Promise.resolve().then(t.bind(t,3451)),C=e.taskId||await v(r,n,i)||"untracked"
|
|
4830
|
-
|
|
4856
|
+
f.info("Creating directory: "+h,{taskId:C,path:h,comment:g}),d.validateTaskIdFormat(C,f,p,b.metricsPrefix),r.getCurrentBranchContext&&await r.getCurrentBranchContext()
|
|
4831
4857
|
const{normalizedPath:_,fullPath:E}=d.validateAndNormalizePath(h,r)
|
|
4832
4858
|
I=d.FileOperationPhase.TASK_VALIDATION,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4833
|
-
const q=await d.validateTaskId(C,_,n,
|
|
4834
|
-
P.taskPromoted&&
|
|
4835
|
-
const j=await d.ensureCorrectWorkspaceContext({taskPromoted:P.taskPromoted,requestId:S,context:r,operation:"create-directory",logger:
|
|
4859
|
+
const q=await d.validateTaskId(C,_,n,f,p,b.metricsPrefix),S=q?.requestId,T=await d.validateWorkItemStates(C,_,n,s,r,f,p,b.metricsPrefix),P=await d.autoPromoteTaskStatus(C,q.status,S,T.request?.status,_,n,s,f,p,b.metricsPrefix)
|
|
4860
|
+
P.taskPromoted&&f.info(`Auto-promoted task ${C} (${q.title||"Untitled"}) to in_progress for file operation`,{taskId:C,taskTitle:q.title,previousStatus:q.status,newStatus:P.newTaskStatus,path:_}),P.requestPromoted&&f.info(`Auto-promoted request ${S} to in_progress for file operation`,{requestId:S,previousStatus:T.request?.status,newStatus:P.newRequestStatus,triggeringTaskId:C})
|
|
4861
|
+
const j=await d.ensureCorrectWorkspaceContext({taskPromoted:P.taskPromoted,requestId:S,context:r,operation:"create-directory",logger:f,metrics:p,metricsPrefix:b.metricsPrefix})
|
|
4836
4862
|
if(!j.success){if(j.isLockConflict)return{content:[{type:"text",text:"\u274c "+j.error}],isError:!0}
|
|
4837
4863
|
throw Error(j.error)}let x=!1
|
|
4838
4864
|
try{x=(await a.default.stat(E)).isDirectory()}catch{x=!1}I=d.FileOperationPhase.RECORD_CREATION,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4839
|
-
const{toolRecordId:R,localToolRecordId:M}=await d.createFileOperationRecords(C,S,r.projectId,b.recordType,_,{directoryExists:x,userComment:g},n,o,
|
|
4865
|
+
const{toolRecordId:R,localToolRecordId:M}=await d.createFileOperationRecords(C,S,r.projectId,b.recordType,_,{directoryExists:x,userComment:g},n,o,f,p,b.metricsPrefix,m)
|
|
4840
4866
|
w=R,k=R,I=b.fileOperationPhase,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4841
4867
|
let O=x
|
|
4842
|
-
if(!x){await a.default.mkdir(E,{recursive:!0}),
|
|
4868
|
+
if(!x){await a.default.mkdir(E,{recursive:!0}),f.info("Successfully created directory "+_)
|
|
4843
4869
|
try{const e=c.default.join(E,".gitkeep")
|
|
4844
|
-
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),O=!0,
|
|
4870
|
+
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),O=!0,f.info("Created .gitkeep file for Git tracking")}catch(e){f.warn("Failed to create .gitkeep file",{error:e instanceof Error?e.message:e+""}),O=!1}}const $=Date.now()-y
|
|
4845
4871
|
p.recordValue("create_directory_time",$),p.incrementCounter("create_directory_success",1),I=d.FileOperationPhase.GIT_COMMIT,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4846
|
-
const D=`Create directory: ${_} - ${g||"Create directory"}`,A=!x&&O?_+"/.gitkeep":_,F=await d.commitToGit(C,A,R,M,D,r,
|
|
4847
|
-
I=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,p.incrementCounter("create_directory_phase",1,{phase:I}),await d.updateFileOperationRecords(C,w,k,_,b.recordType,`Successfully ${x?"verified":"created"} directory: ${_}`,{status:"completed",commitHash:F.commitHash,previousCommitHash:F.previousCommitHash,directoryExists:x,isDirectory:!0,userComment:g},`Successfully ${x?"verified":"created"} directory: ${_}`,n,o,
|
|
4872
|
+
const D=`Create directory: ${_} - ${g||"Create directory"}`,A=!x&&O?_+"/.gitkeep":_,F=await d.commitToGit(C,A,R,M,D,r,f,p,b.metricsPrefix)
|
|
4873
|
+
I=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,p.incrementCounter("create_directory_phase",1,{phase:I}),await d.updateFileOperationRecords(C,w,k,_,b.recordType,`Successfully ${x?"verified":"created"} directory: ${_}`,{status:"completed",commitHash:F.commitHash,previousCommitHash:F.previousCommitHash,directoryExists:x,isDirectory:!0,userComment:g},`Successfully ${x?"verified":"created"} directory: ${_}`,n,o,f,p,b.metricsPrefix)
|
|
4848
4874
|
const N=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
4849
4875
|
return{content:[{type:"text",text:x?"Directory already exists":`Successfully created directory${F.commitHash?"\nCommit: "+F.commitHash.substring(0,8):""}${N.requestId&&!N.permanentBranch?"\nBranch: "+N.requestId:""}${j.lockAcquired&&j.lockedRequestId&&!N.permanentBranch?"\n\u{1f512} **Locked request:** "+j.lockedRequestId:""}`}]}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
|
|
4850
|
-
await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"create-directory",metadata:{status:"failed",timestamp:(new Date).toISOString(),path:e.path,userComment:e.comment,error:(0,g.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:I,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:`Failed to create directory ${e.path} - ${(0,g.getErrorMessage)(t)}`})}catch(t){
|
|
4851
|
-
if(p.recordValue("create_directory_time",s),p.incrementCounter("create_directory_errors",1),
|
|
4852
|
-
try{await d.updateFileOperationRecords(e.taskId,w,k,e.path,b.recordType,"Failed to create directory "+e.path,{status:"failed",error:(0,g.getErrorMessage)(t),userComment:e.comment},"Failed to create directory "+e.path,n,o,
|
|
4876
|
+
await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"create-directory",metadata:{status:"failed",timestamp:(new Date).toISOString(),path:e.path,userComment:e.comment,error:(0,g.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:I,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:`Failed to create directory ${e.path} - ${(0,g.getErrorMessage)(t)}`})}catch(t){f.error("Failed to create failure record for create directory operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,path:e.path})}const s=Date.now()-y
|
|
4877
|
+
if(p.recordValue("create_directory_time",s),p.incrementCounter("create_directory_errors",1),f.error("Error creating directory:",{error:(0,g.getErrorMessage)(t),time:s}),(w||k)&&e.taskId){I=d.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
4878
|
+
try{await d.updateFileOperationRecords(e.taskId,w,k,e.path,b.recordType,"Failed to create directory "+e.path,{status:"failed",error:(0,g.getErrorMessage)(t),userComment:e.comment},"Failed to create directory "+e.path,n,o,f,p,b.metricsPrefix)}catch(t){f.error("Failed to update record with failure status",{taskId:e.taskId,recordId:w,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(t,I,f,p,e,b)}}
|
|
4853
4879
|
const a=i(t(1943)),c=i(t(6928)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(1569),g=t(8824)},8317(e,exports,t){"use strict"
|
|
4854
4880
|
function r(e){const t=[]
|
|
4855
4881
|
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"
|
|
@@ -4858,14 +4884,14 @@ case"move-files":return"\u{1f4cb} Move Files"
|
|
|
4858
4884
|
case"delete-files":return"\u{1f5d1}\ufe0f Delete Files"
|
|
4859
4885
|
case"manage-files":return"\u{1f4c1} Manage Files"
|
|
4860
4886
|
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")
|
|
4861
|
-
try{const{requestId:c,detailLevel:h="summary",taskId:g,showDiff:p=!1,fileFilter:
|
|
4887
|
+
try{const{requestId:c,detailLevel:h="summary",taskId:g,showDiff:p=!1,fileFilter:m}=e
|
|
4862
4888
|
if(!c)throw(0,o.createValidationError)("Request ID is required")
|
|
4863
4889
|
if(!/^req[_\d].+$/.test(c))throw(0,o.createValidationError)(`Invalid request ID format: ${c}. Expected format: req_[26 chars] or req######`)
|
|
4864
4890
|
if(g&&!/^tas\d{6}$/.test(g))throw(0,o.createValidationError)(`Invalid task ID format: ${g}. Expected format: tas######`)
|
|
4865
4891
|
if(d.info("Getting file changes for request "+c,{detailLevel:h,taskId:g,showDiff:p}),!t.git)throw Error("Git integration not available in this context")
|
|
4866
|
-
const
|
|
4892
|
+
const f=t.projectId
|
|
4867
4893
|
let y
|
|
4868
|
-
a.setProjectId(
|
|
4894
|
+
a.setProjectId(f)
|
|
4869
4895
|
try{const e=a.getRequestClient(),t=await e.getRequest(c),r=(0,s.extractDataFromResponse)(t,{logger:d,operationName:"getRequest",throwOnNoData:!1}),n="data"in r?r.data:r
|
|
4870
4896
|
y={id:n.id||c,title:n.title||"Unknown Request",description:n.description||"No description available",status:n.status||"unknown",type:n.type||"unknown",createdAt:n.createdAt||(new Date).toISOString(),updatedAt:n.updatedAt||(new Date).toISOString()},d.info("Found request: "+y.title)}catch(e){const t=(0,i.getErrorMessage)(e)
|
|
4871
4897
|
if(t.includes("not found")||t.includes("Not found"))return d.warn("Request not found: "+c),u({tool:"request_file_history",success:!1}),l.incrementCounter("request_file_history_errors",1),{content:[{type:"text",text:`\u274c **Request not found:** ${c}\n\nThe request ID does not exist in the system. Please verify the request ID is correct.`}],isError:!0}
|
|
@@ -4885,7 +4911,7 @@ let r=0
|
|
|
4885
4911
|
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])
|
|
4886
4912
|
if(e&&e.trim()){const r=500,n=e.length
|
|
4887
4913
|
if(n>r){const o=e.substring(0,r),s=(n/1024).toFixed(1)
|
|
4888
|
-
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,p,t.git,d,
|
|
4914
|
+
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,p,t.git,d,m)
|
|
4889
4915
|
return u({success:!0,recordCount:o.length}),{content:[{type:"text",text:s}]}}{const e=a.getToolRecordClient()
|
|
4890
4916
|
let n=[]
|
|
4891
4917
|
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
|
|
@@ -4895,7 +4921,7 @@ if(!["write-file","replace-in-files","move-files","delete-files","manage-files"]
|
|
|
4895
4921
|
o++
|
|
4896
4922
|
const i=r(s)
|
|
4897
4923
|
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())
|
|
4898
|
-
return{summary:{filesChanged:s.length,linesAdded:0,linesDeleted:0,binaryFiles:0,renamedFiles:0,totalCommits:o,timespan:void 0},files:s}}(n,
|
|
4924
|
+
return{summary:{filesChanged:s.length,linesAdded:0,linesDeleted:0,binaryFiles:0,renamedFiles:0,totalCommits:o,timespan:void 0},files:s}}(n,m,t.git),s=function(e,t,r){const{requestInfo:n,branchInfo:o,summary:s,files:i,commits:a}=e
|
|
4899
4925
|
let c=`# File Changes for Request: ${n.id}\n\n`
|
|
4900
4926
|
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"
|
|
4901
4927
|
else{const e=50,t=i.slice(0,e),r=i.length-e
|
|
@@ -4905,7 +4931,7 @@ case"D":return"\u{1f5d1}\ufe0f"
|
|
|
4905
4931
|
case"R":return"\u{1f4cb}"
|
|
4906
4932
|
case"C":return"\u{1f4d1}"
|
|
4907
4933
|
case"T":return"\u{1f504}"}}(e.status)
|
|
4908
|
-
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,
|
|
4934
|
+
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,m)
|
|
4909
4935
|
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}}}
|
|
4910
4936
|
const o=t(9860),s=t(2960),i=t(8824)},8349(e,exports,t){"use strict"
|
|
4911
4937
|
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"}]}
|
|
@@ -4936,7 +4962,10 @@ let u=`**${e} Operation Complete**\n\n`
|
|
|
4936
4962
|
return u+="**Summary:**\n",u+=`- **Files processed:** ${s+i}\n`,u+=`- **Successful operations:** ${s}\n`,u+=`- **Failed operations:** ${i}\n`,u+=`- **Total changes made:** ${a}\n\n`,r.success&&r.commitHash?(u+="**Git Commit:**\n",u+=`- **Commit Hash:** ${r.commitHash.substring(0,8)}\n`,u+=`- **Files Committed:** ${r.filesCommitted.length}\n`,r.previousCommitHash&&(u+=`- **Previous Commit:** ${r.previousCommitHash.substring(0,8)}\n`),u+="\n"):r.error&&(u+=`**Git Status:** Changes saved but commit failed - ${r.error}\n\n`),n?.lockAcquired&&n.lockedRequestId&&(u+=`\u{1f512} **Locked request:** ${n.lockedRequestId}\n\n`),l.length>0&&(u+="**\u2705 Successful Operations:**\n",l.slice(0,10).forEach((e=>{const t=o?e[o]||0:"completed",r=e.path||e.documentId||"unknown"
|
|
4937
4963
|
u+=`- \`${r}\`: ${t} changes\n`})),l.length>10&&(u+=`- ... and ${l.length-10} more files\n`),u+="\n"),d.length>0&&(u+="**\u274c Failed Operations:**\n",d.slice(0,5).forEach((e=>{const t=e.path||e.documentId||"unknown"
|
|
4938
4964
|
u+=`- \`${t}\`: ${e.error||"Unknown error"}\n`})),d.length>5&&(u+=`- ... and ${d.length-5} more failures\n`)),{content:[{type:"text",text:u}],isError:!c}}
|
|
4939
|
-
const r=t(8824)},
|
|
4965
|
+
const r=t(8824)},8456(e,exports,t){"use strict"
|
|
4966
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4967
|
+
const r=t(6183),n=t(2113)
|
|
4968
|
+
exports.def={name:"commit_to_viewed_session",description:"Post a cleaned-up user message to the session the user is currently viewing. Translator-only. Call this when the dictation is clear and ready to forward.",schema:r.CommitToViewedSessionSchema,annotations:{title:"Commit to Viewed Session",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleCommitToViewedSession)(e,t.logger)}}},8485(e,exports){"use strict"
|
|
4940
4969
|
function t(e,t){const r=e.match(/^([ \t]*)(.*?)\s*$/)
|
|
4941
4970
|
if(!r)return e
|
|
4942
4971
|
const[,n,s]=r
|
|
@@ -4967,28 +4996,28 @@ function r(e){const t=a[e]
|
|
|
4967
4996
|
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.`)
|
|
4968
4997
|
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)
|
|
4969
4998
|
if(!s(u.projectId)){const t=Error(`Invalid projectId format: ${u.projectId}. Cannot create failure record without valid projectId.`)
|
|
4970
|
-
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,"_"),p=(0,i.getErrorMessage)(t),
|
|
4999
|
+
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,"_"),p=(0,i.getErrorMessage)(t),m=t instanceof Error?t.stack:void 0
|
|
4971
5000
|
try{const t=r(e),s={}
|
|
4972
|
-
let i,
|
|
4973
|
-
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)?
|
|
5001
|
+
let i,f
|
|
5002
|
+
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)?f=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})))
|
|
4974
5003
|
let y=u.note||`Failed to execute ${e}: ${p.substring(0,100)}${p.length>100?"...":""}`
|
|
4975
5004
|
Object.keys(s).length>0&&(y+=` (Warning: Invalid IDs provided: ${Object.entries(s).map((([e,t])=>`${e}: ${t}`)).join(", ")})`)
|
|
4976
|
-
const w={projectId:u.projectId,type:t,note:y,metadata:{status:"failed",error:p,errorStack:
|
|
4977
|
-
i&&(w.taskId=i),
|
|
5005
|
+
const w={projectId:u.projectId,type:t,note:y,metadata:{status:"failed",error:p,errorStack:m,originalToolName:e,timestamp:(new Date).toISOString(),invalidIds:Object.keys(s).length>0?s:void 0,...a}}
|
|
5006
|
+
i&&(w.taskId=i),f&&(w.requestId=f),l.info("Creating failure tool record for "+e,{toolName:e,recordType:w.type,...i&&{taskId:i},...f&&{requestId:f},projectId:u.projectId,invalidIds:Object.keys(s).length>0?s:void 0,error:p})
|
|
4978
5007
|
const k=await c.createToolRecord(w)
|
|
4979
|
-
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},...
|
|
5008
|
+
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},...f&&{requestId:f},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:p}),t}}
|
|
4980
5009
|
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){"use strict"
|
|
4981
5010
|
function r(e,t,r){const n=exports.ERROR_TYPE_PROPERTIES[e]||exports.ERROR_TYPE_PROPERTIES[i.INTERNAL_ERROR]
|
|
4982
5011
|
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)
|
|
4983
5012
|
return{statusCode:e.statusCode,body:t}}if(e instanceof Error&&"ConnectionError"===e.name){const t=e
|
|
4984
5013
|
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")
|
|
4985
|
-
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 p(e,t)},exports.createMcpProtocolError=function(e="MCP protocol error",t){return new
|
|
5014
|
+
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 p(e,t)},exports.createMcpProtocolError=function(e="MCP protocol error",t){return new m(e,t)},exports.isAppError=n,exports.errorToResponse=o,exports.isRetryableError=s
|
|
4986
5015
|
const i=t(7388)
|
|
4987
5016
|
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}
|
|
4988
5017
|
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)
|
|
4989
5018
|
const o=exports.ERROR_TYPE_PROPERTIES[this.code]
|
|
4990
5019
|
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
|
|
4991
|
-
e&&e.error&&"retryable"in e.error&&(this.details.retryable=!!e.error.retryable)}}}class p extends a{constructor(e="File operation error",t){super(e,"FILE_OPERATION_ERROR",500,t)}}class
|
|
5020
|
+
e&&e.error&&"retryable"in e.error&&(this.details.retryable=!!e.error.retryable)}}}class p extends a{constructor(e="File operation error",t){super(e,"FILE_OPERATION_ERROR",500,t)}}class m 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=p,exports.McpProtocolError=m,exports.UnauthorizedError=d},8712(e,exports){"use strict"
|
|
4992
5021
|
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}
|
|
4993
5022
|
const o=e.split("\n"),s=[],i=new Set
|
|
4994
5023
|
let a=!1,c=""
|
|
@@ -5043,7 +5072,7 @@ return t},o(e)},function(e){if(e&&e.__esModule)return e
|
|
|
5043
5072
|
var t={}
|
|
5044
5073
|
if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
5045
5074
|
return i(t,e),t})
|
|
5046
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileHistory=async function(e,t,n,o,s){const i=o.child({tool:"file_history"}),a=s.startTimer("tool_execution_time"),
|
|
5075
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileHistory=async function(e,t,n,o,s){const i=o.child({tool:"file_history"}),a=s.startTimer("tool_execution_time"),f=Date.now()
|
|
5047
5076
|
try{let o
|
|
5048
5077
|
try{o=d.FileHistorySchema.parse(e)}catch(t){if(t instanceof u.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
5049
5078
|
return i.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{path:a,limit:y,showDiff:w,showTraceability:k,branch:I,commit:b,since:v}=o
|
|
@@ -5053,19 +5082,19 @@ try{const r=await o.log({from:t,to:t,file:s,maxCount:1})
|
|
|
5053
5082
|
if(!r.all||0===r.all.length)return{content:[{type:"text",text:`No commit found with hash ${t} for file ${e}`}]}
|
|
5054
5083
|
const n=r.all[0],i=await o.diff([t+"^",t,"--",s])
|
|
5055
5084
|
let a="# File History - Commit Diff\n\n"
|
|
5056
|
-
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,p.getErrorMessage)(r)}`}],isError:!0}}}(a,b,t,i)):(i.info("Getting file history with branch support",{filePath:a,limit:y,showDiff:w,showTraceability:k,branch:I}),await async function(e,t,n,o,s,i,a,c,d,u,p){try{const{normalizedPath:
|
|
5057
|
-
try{await l.access(y)}catch(e){throw Error("File not found: "+
|
|
5085
|
+
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,p.getErrorMessage)(r)}`}],isError:!0}}}(a,b,t,i)):(i.info("Getting file history with branch support",{filePath:a,limit:y,showDiff:w,showTraceability:k,branch:I}),await async function(e,t,n,o,s,i,a,c,d,u,p){try{const{normalizedPath:f,fullPath:y}=m.validateAndNormalizePath(e,a)
|
|
5086
|
+
try{await l.access(y)}catch(e){throw Error("File not found: "+f)}const w=a.git
|
|
5058
5087
|
if(!w)throw Error("Git is not available in this context")
|
|
5059
5088
|
let k={branch:null,requestId:null,isMain:!0}
|
|
5060
5089
|
if(a.getCurrentBranchContext)try{k=await a.getCurrentBranchContext(),d.info("Current branch context detected",{branch:k.branch,requestId:k.requestId,isMain:k.isMain})}catch(e){d.warn("Could not get current branch context",{error:e})}let I=[],b=""
|
|
5061
|
-
if(s)I=await r(w,
|
|
5062
|
-
else{if(k.isMain&&!o)return d.info("Showing request-level timeline on main branch"),{content:[{type:"text",text:await(0,g.getRequestTimelineForFile)(w,
|
|
5063
|
-
if(k.requestId)return d.info("Showing operation-level detail on request branch",{requestId:k.requestId}),{content:[{type:"text",text:await(0,g.getOperationDetailForFile)(
|
|
5090
|
+
if(s)I=await r(w,f,t,n,o,s,i,c,d,u),b=`## File History: ${f} (Branch: ${s})\n\n`
|
|
5091
|
+
else{if(k.isMain&&!o)return d.info("Showing request-level timeline on main branch"),{content:[{type:"text",text:await(0,g.getRequestTimelineForFile)(w,f,c,d,u)}]}
|
|
5092
|
+
if(k.requestId)return d.info("Showing operation-level detail on request branch",{requestId:k.requestId}),{content:[{type:"text",text:await(0,g.getOperationDetailForFile)(f,k.requestId,c,d,u)}]}
|
|
5064
5093
|
{const e=await async function(e,t,n,o,s,i,a,c,l,d){const u=[],h=[]
|
|
5065
5094
|
if(!i.isMain&&i.branch){const g=await r(e,t,n,o,s,i.branch,a,c,l,d)
|
|
5066
|
-
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),p=new Set(u.map((e=>e.hash))),
|
|
5067
|
-
return u.push(...
|
|
5068
|
-
I=e.versions,b=`## File History: ${
|
|
5095
|
+
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),p=new Set(u.map((e=>e.hash))),m=g.filter((e=>!p.has(e.hash)))
|
|
5096
|
+
return u.push(...m),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,f,t,n,o,k,i,c,d,u)
|
|
5097
|
+
I=e.versions,b=`## File History: ${f} (Combined View)\n\n`,b+=`**Current Context:** ${k.isMain?"main":`${k.branch} (${k.requestId})`}\n`,b+=`**History Sources:** ${e.sources.join(", ")}\n\n`}}if(0===I.length)return b+="\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:b}]}
|
|
5069
5098
|
const v=I.length,C=Math.min(I.length,t)
|
|
5070
5099
|
v>t?b+=`\u{1f4ca} **Summary:** ${v} versions found, showing ${C} most recent\n\n`:v>0&&(b+=`\u{1f4ca} **Summary:** ${v} version${v>1?"s":""} found\n\n`),b+=`**Total Versions:** ${I.length}\n`,b+="**Current File Size:** "
|
|
5071
5100
|
try{b+=(await l.stat(y)).size+" bytes\n"}catch{b+="Unknown\n"}b+="\n"
|
|
@@ -5073,9 +5102,9 @@ for(let e=0;e<I.length;e++){const t=I[e]
|
|
|
5073
5102
|
if(b+=`### Version ${e+1} (${t.hash.substring(0,8)})\n`,t.branch&&(b+=`- **Branch:** ${t.branch}\n`),b+=`- **Author:** ${t.author}\n`,b+=`- **Date:** ${t.date}\n`,b+=`- **Message:** ${t.message}\n`,o&&t.traceability&&(b+=`\n${(0,h.formatTraceabilityInfo)(t.traceability)}\n`),n&&t.diff){const e=t.diff.split("\n")
|
|
5074
5103
|
let r=0,n=0
|
|
5075
5104
|
for(const t of e)t.startsWith("+")&&!t.startsWith("+++")&&r++,t.startsWith("-")&&!t.startsWith("---")&&n++
|
|
5076
|
-
b+=`\n**Changes:**${r>0||n>0?` (Added ${r} lines, removed ${n} lines)`:""}\n\`\`\`diff\n${t.diff}\n\`\`\`\n`}b+="\n"}return b+="\u{1f4a1} **Tips:**\n",b+="- Use `file-recover` with a commit hash to restore the file to a previous version\n",b+='- Use `{"branch": "main"}` to see only main branch history\n',b+='- Use `{"branch": "req123456"}` to see only request branch history\n\n',d.info("Branch-aware file history retrieved successfully",{path:
|
|
5105
|
+
b+=`\n**Changes:**${r>0||n>0?` (Added ${r} lines, removed ${n} lines)`:""}\n\`\`\`diff\n${t.diff}\n\`\`\`\n`}b+="\n"}return b+="\u{1f4a1} **Tips:**\n",b+="- Use `file-recover` with a commit hash to restore the file to a previous version\n",b+='- Use `{"branch": "main"}` to see only main branch history\n',b+='- Use `{"branch": "req123456"}` to see only request branch history\n\n',d.info("Branch-aware file history retrieved successfully",{path:f,versions:I.length,targetBranch:s,currentBranch:k.branch,duration:Date.now()-p}),u.incrementCounter("file_history_total",1,{success:!0,type:"file",mode:s?"single-branch":"combined"}),{content:[{type:"text",text:b}]}}catch(e){throw e}}(a,y,w,k,I,v,t,n,i,s,f))}catch(e){const t=Date.now()-f
|
|
5077
5106
|
return i.error("File/Document history operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),a({tool:"file_history",success:!1}),s.incrementCounter("file_history_errors",1),{content:[{type:"text",text:"\u274c **History Operation Failed:** "+(0,p.getErrorMessage)(e)}],isError:!0}}}
|
|
5078
|
-
const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),p=t(8824),
|
|
5107
|
+
const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),p=t(8824),m=a(t(5967)),f=a(t(7478)),{getCurrentBranch:y}=f},8849(e,exports,t){"use strict"
|
|
5079
5108
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
5080
5109
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
5081
5110
|
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=[]
|
|
@@ -5198,47 +5227,47 @@ e.success&&e.agentType&&(s=e.agentType)}}catch(t){n.warn("Agent type lookup fail
|
|
|
5198
5227
|
if(e.ok){const t=await e.json()
|
|
5199
5228
|
if(t.data?.defaultModel){const[e,...r]=t.data.defaultModel.split("/")
|
|
5200
5229
|
i={providerID:e,modelID:r.join("/")}}}}catch{}const a=`${o.replace(/\/$/,"")}/session/${e}/prompt_async`,c=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:[{type:"text",text:"\x3c!-- inserted-prompt --\x3e"+t}],...s?{agent:s}:{},...i?{model:i}:{}})})
|
|
5201
|
-
return c.ok?(n.info("Notified session",{sessionId:e}),!0):(n.warn("Failed to notify session",{sessionId:e,status:c.status}),!1)}catch(t){return n.warn("Error notifying session",{sessionId:e,error:(0,l.getErrorMessage)(t)}),!1}}function n(e,t,r){return u.sessionIdentity.getParentSessionId(e,t,r)}function o(e,t,r){const
|
|
5202
|
-
if(!
|
|
5203
|
-
return(0,h.logSessionIdentity)(""+r,"identity",{sessionId:
|
|
5230
|
+
return c.ok?(n.info("Notified session",{sessionId:e}),!0):(n.warn("Failed to notify session",{sessionId:e,status:c.status}),!1)}catch(t){return n.warn("Error notifying session",{sessionId:e,error:(0,l.getErrorMessage)(t)}),!1}}function n(e,t,r){return u.sessionIdentity.getParentSessionId(e,t,r)}function o(e,t,r,n,o){const s=o?.sessionId||u.sessionIdentity.getIdentity()?.sessionId
|
|
5231
|
+
if(!s)throw new c.ValidationError("No session identity available. Make sure you are running within an OpenCode session.")
|
|
5232
|
+
return(0,h.logSessionIdentity)(""+r,"identity",{sessionId:s,fromCliOrigin:!!o?.sessionId}),s}function s(e){const t=[],r=e.content||{}
|
|
5204
5233
|
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:**")
|
|
5205
5234
|
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||{}
|
|
5206
|
-
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,d,p,f){const
|
|
5207
|
-
if(!
|
|
5208
|
-
const{operation:
|
|
5209
|
-
|
|
5210
|
-
try{switch(
|
|
5211
|
-
return await async function(e,t,a,l){const{type:
|
|
5212
|
-
if(!
|
|
5213
|
-
const
|
|
5214
|
-
if(!
|
|
5215
|
-
if("question"===
|
|
5216
|
-
if(!
|
|
5217
|
-
const f=o(0,0,"session_message_operations"),
|
|
5235
|
+
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,d,p,m,f){const y=d.child({component:"session_message_operations"})
|
|
5236
|
+
if(!m)throw new c.ValidationError("API client not available")
|
|
5237
|
+
const{operation:w}=e
|
|
5238
|
+
y.info("Session message operation",{operation:w}),p.incrementCounter("session_message_operations",1,{operation:w})
|
|
5239
|
+
try{switch(w){case"send":if(!e.type)throw new c.ValidationError('send operation requires type ("question" or "report")')
|
|
5240
|
+
return await async function(e,t,a,l,d){const{type:u}=e
|
|
5241
|
+
if(!u)throw new c.ValidationError('send operation requires type ("question" or "report")')
|
|
5242
|
+
const h=l.getSessionMessageClient()
|
|
5243
|
+
if(!h)throw new c.ValidationError("Session message client not available")
|
|
5244
|
+
if("question"===u)return await async function(e,t,i,a,l,d){const{toSessionId:u,questionType:h,questionContent:g,priority:p,expiresInHours:m}=e
|
|
5245
|
+
if(!h||!g?.question)throw new c.ValidationError("Question requires questionType and questionContent.question")
|
|
5246
|
+
const f=o(0,0,"session_message_operations",0,d),y=await async function(e,t,r,o){if("parent"===e){const e=await n(t,r,o)
|
|
5218
5247
|
if(!e)throw new c.ValidationError("Could not find parent session. Make sure this session was spawned as a subagent.")
|
|
5219
|
-
return o.info('Resolved toSessionId "parent" to actual ID',{parentId:e}),e}return e}(
|
|
5220
|
-
if(!("alternatives"!==
|
|
5221
|
-
i.info("Creating question",{fromSessionId:f,toSessionId:
|
|
5222
|
-
const
|
|
5223
|
-
let
|
|
5224
|
-
return
|
|
5248
|
+
return o.info('Resolved toSessionId "parent" to actual ID',{parentId:e}),e}return e}(u,f,a,i)
|
|
5249
|
+
if(!("alternatives"!==h||g.options&&Array.isArray(g.options)))throw new c.ValidationError("Alternatives questions require options array")
|
|
5250
|
+
i.info("Creating question",{fromSessionId:f,toSessionId:y,questionType:h})
|
|
5251
|
+
const w=await l.createQuestion({fromSessionId:f,toSessionId:y,questionType:h,question:g.question,options:g.options,context:g.context,allowMultiple:g.allowMultiple,priority:p,expiresInHours:m})
|
|
5252
|
+
let k=""
|
|
5253
|
+
return y&&(k=await r(y,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]
|
|
5225
5254
|
if(t.context&&r.push("**Context:** "+t.context),"alternatives"===t.questionType&&t.options){r.push(""),r.push("**Options:**")
|
|
5226
|
-
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")}(
|
|
5227
|
-
if("report"===
|
|
5228
|
-
if(!
|
|
5229
|
-
const f=o(0,0,"session_message_operations"),
|
|
5255
|
+
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")}(w),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!${k}\n\n**Message Code: ${w.messageCode}**\n\nUse this code to check for answers or share with other sessions.\n\n${s(w)}`}]}}(e,t,a,l,h,d)
|
|
5256
|
+
if("report"===u)return await async function(e,t,s,a,l,d){const{status:u,summary:h,details:p,finish:m}=e
|
|
5257
|
+
if(!u||!h)throw new c.ValidationError("Report requires status and summary")
|
|
5258
|
+
const f=o(0,0,"session_message_operations",0,d),y=await(async()=>{if(e.toSessionId&&"parent"!==e.toSessionId)return s.info("Using explicit toSessionId for report",{parentSessionId:e.toSessionId}),e.toSessionId
|
|
5230
5259
|
const t=await n(f,a,s)
|
|
5231
|
-
if(
|
|
5232
|
-
|
|
5233
|
-
s.info("Submitting report",{sessionId:f,parentSessionId:
|
|
5234
|
-
const
|
|
5235
|
-
let
|
|
5260
|
+
if(t)return s.info("Auto-resolved parent session",{parentSessionId:t}),t
|
|
5261
|
+
throw new c.ValidationError("Could not find parent session. Ensure this session was created with a parent link, or provide an explicit toSessionId.")})()
|
|
5262
|
+
s.info("Submitting report",{sessionId:f,parentSessionId:y,status:u})
|
|
5263
|
+
const w=await l.createReport({fromSessionId:f,toSessionId:y,status:u,summary:h,details:p})
|
|
5264
|
+
let k="agent"
|
|
5236
5265
|
try{const e=await fetch(`http://localhost:${g}/api/sessions/${encodeURIComponent(f)}/agent-type`)
|
|
5237
5266
|
if(e.ok){const t=await e.json()
|
|
5238
|
-
t.success&&t.agentType&&(
|
|
5239
|
-
return r.details&&(n.push(""),n.push(r.details)),n.join("\n")}(
|
|
5240
|
-
return{content:[{type:"text",text:`\u2705 Report submitted.${
|
|
5241
|
-
throw new c.ValidationError(`Unknown message type: ${
|
|
5267
|
+
t.success&&t.agentType&&(k=t.agentType)}}catch{}const I=await r(y,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]
|
|
5268
|
+
return r.details&&(n.push(""),n.push(r.details)),n.join("\n")}(w,k),t,s)
|
|
5269
|
+
return{content:[{type:"text",text:`\u2705 Report submitted.${I?"\n\n\u{1f4ec} The parent session has been notified.":"\n\n\u26a0\ufe0f Could not notify the parent session (may be offline)."}\n\n${i(w)}`}]}}(e,t,a,l,h,d)
|
|
5270
|
+
throw new c.ValidationError(`Unknown message type: ${u}. Use "question" or "report".`)}(e,t,y,m,f)
|
|
5242
5271
|
case"reply":if(!e.messageCode)throw new c.ValidationError("reply operation requires messageCode")
|
|
5243
5272
|
return await async function(e,t,n,o){const{messageCode:a}=e
|
|
5244
5273
|
if(!a)throw new c.ValidationError("reply operation requires messageCode")
|
|
@@ -5249,24 +5278,24 @@ n.info("Answering question",{messageCode:a,respondedBySessionId:o})
|
|
|
5249
5278
|
const u=await l.answerQuestion(a,{respondedBySessionId:o,text:i,selectedOptions:c,notes:d})
|
|
5250
5279
|
return{content:[{type:"text",text:`\u2705 Question answered!${await r(u.fromSessionId,function(e){const t=e.content||{},r=e.response||{},n=["\u{1f4ec} **Your question has been answered!**","","**Question Code:** "+e.messageCode,"**Question:** "+t.question,"","---","**Answered by:** "+e.respondedBySessionId]
|
|
5251
5280
|
return r.text&&n.push("**Answer:** "+r.text),r.selectedOptions&&n.push("**Selected:** "+r.selectedOptions.join(", ")),r.notes&&n.push("**Notes:** "+r.notes),n.join("\n")}(u),t,n)?"\n\n\u{1f4ec} The asking session has been notified.":"\n\n\u26a0\ufe0f Could not notify the asking session (may be offline)."}\n\n${s(u)}`}]}}if(a.startsWith("R-"))return n.info("Acknowledging report",{messageCode:a}),{content:[{type:"text",text:"\u2705 Report acknowledged!\n\n"+i(await l.acknowledgeReport(a))}]}
|
|
5252
|
-
throw new c.ValidationError(`Cannot determine message type from code "${a}". Expected Q-xxx (question) or R-xxx (report).`)}(e,t,m
|
|
5253
|
-
case"offer-handoff":{const t=e.offerHandoff||{summary:e.summary||"",requestIds:e.requestIds||[]}
|
|
5254
|
-
|
|
5255
|
-
try{
|
|
5256
|
-
if(e
|
|
5257
|
-
await e.createQuestion({fromSessionId:r,toSessionId:s||void 0,questionType:"alternatives",question:"Plan ready: "+(t.summary||"Plan complete"),options:[{id:"build",label:"Start Building",description:`Begin building ${n} request${1!==n?"s":""}`},{id:"plan",label:"Keep Planning",description:"Continue refining the plan"}],context:
|
|
5258
|
-
const
|
|
5259
|
-
if(!
|
|
5260
|
-
if(!
|
|
5261
|
-
if(!e
|
|
5262
|
-
|
|
5263
|
-
const
|
|
5264
|
-
|
|
5265
|
-
const
|
|
5266
|
-
if(0===
|
|
5267
|
-
const
|
|
5268
|
-
for(const e of
|
|
5269
|
-
return{content:[{type:"text",text:
|
|
5281
|
+
throw new c.ValidationError(`Cannot determine message type from code "${a}". Expected Q-xxx (question) or R-xxx (report).`)}(e,t,y,m)
|
|
5282
|
+
case"offer-handoff":{const t=e.offerHandoff||{summary:e.summary||"",requestIds:e.requestIds||[]},r=o(0,0,"session_message_operations",0,f),s=await n(r,m,y)
|
|
5283
|
+
s||y.warn("offer-handoff: no parent session found \u2014 notification will be global",{fromSessionId:r})
|
|
5284
|
+
try{const e=m.getSessionMessageClient()
|
|
5285
|
+
if(e){const n=t.requestIds?.length||0
|
|
5286
|
+
await e.createQuestion({fromSessionId:r,toSessionId:s||void 0,questionType:"alternatives",question:"Plan ready: "+(t.summary||"Plan complete"),options:[{id:"build",label:"Start Building",description:`Begin building ${n} request${1!==n?"s":""}`},{id:"plan",label:"Keep Planning",description:"Continue refining the plan"}],context:JSON.stringify({type:"plan-completion",plannerSessionId:r,parentSessionId:s,requestIds:t.requestIds,summary:t.summary}),category:"action-required",priority:"high"}),y.info("offer-handoff: notification question created",{fromSessionId:r,parentSessionId:s})}else y.warn("offer-handoff: skipping notification question \u2014 no message client")}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:t.summary,requestIds:t.requestIds,parentSessionId:s,fromSessionId:r})}],isError:!1}}case"list":return await async function(e,t,r,n,o){let{sessionId:s,messageType:i,direction:l,status:d,readStatus:g,reportStatus:p,limit:m,offset:f}=e
|
|
5287
|
+
const y=n.getSessionMessageClient()
|
|
5288
|
+
if(!y)throw new c.ValidationError("Session message client not available")
|
|
5289
|
+
if(!s){const e=o?.sessionId||u.sessionIdentity.getIdentity()?.sessionId
|
|
5290
|
+
if(!e)return r.warn("No session identity for list operation"),{content:[{type:"text",text:"\u26a0\ufe0f Could not determine current session ID. Unable to list messages without a session context."}]}
|
|
5291
|
+
s=e,(0,h.logSessionIdentity)("session_message_operations.list","identity",{sessionId:s,fromCliOrigin:!!o?.sessionId})}r.debug("Listing messages",{sessionId:s,messageType:i,direction:l,status:d,readStatus:g})
|
|
5292
|
+
const w={sessionId:s,direction:l,limit:m,offset:f}
|
|
5293
|
+
i&&"all"!==i&&(w.messageType=i),d&&"all"!==d&&("report"===i?w.reportStatus=d:w.status=d),g&&"all"!==g&&(w.readStatus=g),p&&"all"!==p&&(w.reportStatus=p)
|
|
5294
|
+
const k=await y.listMessages(w)
|
|
5295
|
+
if(0===k.length)return{content:[{type:"text",text:"No messages found matching the criteria."}]}
|
|
5296
|
+
const I=[`Found ${k.length} message(s):\n`]
|
|
5297
|
+
for(const e of k)I.push("---\n"),I.push(a(e)),I.push("")
|
|
5298
|
+
return{content:[{type:"text",text:I.join("\n")}]}}(e.list||{},0,y,m,f)
|
|
5270
5299
|
case"get":if(!e.messageCode)throw new c.ValidationError("get operation requires messageCode")
|
|
5271
5300
|
return await async function(e,t,r){const{messageCode:n}=e
|
|
5272
5301
|
if(!n)throw new c.ValidationError("get operation requires messageCode")
|
|
@@ -5274,9 +5303,9 @@ const o=r.getSessionMessageClient()
|
|
|
5274
5303
|
if(!o)throw new c.ValidationError("Session message client not available")
|
|
5275
5304
|
t.debug("Getting message",{messageCode:n})
|
|
5276
5305
|
const s=await o.getMessage(n)
|
|
5277
|
-
return s?{content:[{type:"text",text:a(s)}]}:{content:[{type:"text",text:`\u274c Message with code ${n} not found.`}],isError:!0}}(e,m
|
|
5278
|
-
default:throw new c.ValidationError(`Unknown operation: ${
|
|
5279
|
-
const c=t(9860),l=t(8824),d=t(7617),u=t(6688),h=t(7280),g=
|
|
5306
|
+
return s?{content:[{type:"text",text:a(s)}]}:{content:[{type:"text",text:`\u274c Message with code ${n} not found.`}],isError:!0}}(e,y,m)
|
|
5307
|
+
default:throw new c.ValidationError(`Unknown operation: ${w}. Valid operations: send, reply, list, get`)}}catch(e){return y.error("Session message operation failed",{operation:w,error:(0,l.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c Error: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
|
|
5308
|
+
const c=t(9860),l=t(8824),d=t(7617),u=t(6688),h=t(7280),g=(0,t(9414).getActionServerPort)()},9080(e,exports,t){"use strict"
|
|
5280
5309
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
5281
5310
|
const r=t(6183),n=t(1281)
|
|
5282
5311
|
exports.def={name:"search",description:"Search for text patterns in files on the currently active branch. Supports regex patterns and sorts results by file modification time (newest first).\n\nFile extensions: 'ts', '.ts', '*.ts' (all valid). Use '*' for any file type.\n\nCONTEXT LINES: Use contextLines option (0-10) to show surrounding lines before and after matches, reducing need for follow-up reads.\n\nLIST-ALL MODE: Omit 'needle' to list all files in a directory with tree structure (like ls/tree). Options: levels (1-4 depth), sortBy (name/modified/size/type).",schema:r.SearchSchema,annotations:{title:"Search Files",readOnlyHint:!0},readOnly:!0,handler(e,t){return(0,n.handleSearch)(e,t.context,t.apiClient,t.logger,t.metrics)}}},9089(e,exports){"use strict"
|
|
@@ -5305,9 +5334,9 @@ try{d=await this.git.raw(["merge-tree",l.trim(),c.trim(),i.trim()]),u=0}catch(e)
|
|
|
5305
5334
|
let h=!1,g="",p=null
|
|
5306
5335
|
if(0!==u?(h=!0,g="merge-tree-exit-code"):d&&d.trim()?(p=(0,o.parseConflictOutputWithContext)(d,e.requestId,e.sourceBranch,e.targetBranch),p.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}
|
|
5307
5336
|
!p&&d&&d.trim()&&(p=(0,o.parseConflictOutputWithContext)(d,e.requestId,e.sourceBranch,e.targetBranch))
|
|
5308
|
-
let
|
|
5309
|
-
if(p&&p.filesParsed&&p.filesParsed.length>0)
|
|
5310
|
-
else try{
|
|
5337
|
+
let m=[]
|
|
5338
|
+
if(p&&p.filesParsed&&p.filesParsed.length>0)m=p.filesParsed.map((e=>({path:e,conflictType:"content",description:"Merge conflict detected"}))),r.debug("Successfully extracted conflict files from parsed content",{conflictedFilesCount:m.length,files:m.map((e=>e.path))})
|
|
5339
|
+
else try{m=this.parseMergeTreeOutput(d,r),r.debug("Used fallback merge-tree parsing",{conflictedFilesCount:m.length})}catch(e){r.warn("Both conflict parsing methods failed",{parseError:e instanceof Error?e.message:e+""}),m=[{path:"<parsing failed>",conflictType:"content",description:"Git detected conflicts but parsing failed - manual inspection required"}]}return 0===m.length&&(r.warn("Git detected conflicts but no files could be determined - using fallback"),m=[{path:"<unknown files>",conflictType:"content",description:"Git detected conflicts but could not determine specific files"}]),{hasConflicts:!0,conflictedFiles:m,summary:m.length>0&&"<parsing failed>"!==m[0].path&&"<unknown files>"!==m[0].path?m.length+" file(s) have merge conflicts (detected by Git)":"Merge conflicts detected by Git (parsing details failed)",resolutionInstructions:this.generateMultiAgentInstructions(m,e.requestId,e.worktreePath,e.targetBranch),detectionMethod:"merge-tree-analysis",rawOutput:d,rawConflictContent:p?p.cleanContent:void 0}}catch(e){throw r.error("Pure multi-agent conflict detection failed",{error:e}),e}}parseMergeTreeOutput(e,t){const r=[]
|
|
5311
5340
|
if(!e||!e.trim())return t.debug("Empty merge-tree output - no conflicts to parse"),[]
|
|
5312
5341
|
let n
|
|
5313
5342
|
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
|
|
@@ -5342,7 +5371,15 @@ exports.def={name:"list_tasks",description:"List and filter tasks",schema:r.List
|
|
|
5342
5371
|
module.exports=require("net")},9373(e,exports,t){"use strict"
|
|
5343
5372
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
5344
5373
|
const r=t(6183),n=t(6416)
|
|
5345
|
-
exports.def={name:"revert_request",description:"Cancel open/in-progress requests or revert completed requests.\n\nCancel (open/in-progress):\n\u2022 Status set to 'canceled', request becomes read-only\n\u2022 No git operations, branch preserved\n\nRevert (completed):\n\u2022 All file changes undone via git revert\n\u2022 Request/task status set to 'reverted'\n\u2022 Request branch deleted\n\u2022 Fails fast if conflicts detected\n\nPreserved: Documents, git history, tool records (for audit trail).",schema:r.RevertRequestSchema,annotations:{title:"Revert Request",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},hidden:!0,handler(e,t){return(0,n.handleRevertRequest)(e,t.context,t.apiClient,t.logger,t.metrics)}}},
|
|
5374
|
+
exports.def={name:"revert_request",description:"Cancel open/in-progress requests or revert completed requests.\n\nCancel (open/in-progress):\n\u2022 Status set to 'canceled', request becomes read-only\n\u2022 No git operations, branch preserved\n\nRevert (completed):\n\u2022 All file changes undone via git revert\n\u2022 Request/task status set to 'reverted'\n\u2022 Request branch deleted\n\u2022 Fails fast if conflicts detected\n\nPreserved: Documents, git history, tool records (for audit trail).",schema:r.RevertRequestSchema,annotations:{title:"Revert Request",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},hidden:!0,handler(e,t){return(0,n.handleRevertRequest)(e,t.context,t.apiClient,t.logger,t.metrics)}}},9414(e,exports,t){"use strict"
|
|
5375
|
+
function r(){const e=Date.now()
|
|
5376
|
+
if(null!==c&&d>e-l)return c
|
|
5377
|
+
const t=(0,o.join)(process.env.ALCHEMY_PROJECT_PATH||process.cwd(),i,a)
|
|
5378
|
+
if((0,n.existsSync)(t))try{const r=(0,n.readFileSync)(t,"utf-8"),o=JSON.parse(r)
|
|
5379
|
+
if("number"==typeof o.port&&o.port>0&&65536>o.port)return c=o.port,l=e,c}catch{}return c=s,l=e,c}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getActionServerPort=r,exports.getActionServerBaseUrl=function(){return"http://localhost:"+r()}
|
|
5380
|
+
const n=t(9896),o=t(6928),s=3456,i=".alchemy_lab",a="action-server.json"
|
|
5381
|
+
let c=null,l=0
|
|
5382
|
+
const d=5e3},9422(e,exports,t){"use strict"
|
|
5346
5383
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDebugRequestFileHistory=async function(e,t,n,o){const s=o.child({tool:"debug_request_file_history"})
|
|
5347
5384
|
try{const{requestId:n="req000046"}=e
|
|
5348
5385
|
if(!t.git)throw Error("Git integration not available")
|
|
@@ -5356,23 +5393,23 @@ o+=`## Test 4: All commits containing "${n}" (not just merges)\n`,o+=`Found ${e?
|
|
|
5356
5393
|
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()
|
|
5357
5394
|
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}}}
|
|
5358
5395
|
const r=t(8824)},9442(e,exports,t){"use strict"
|
|
5359
|
-
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:p}=e,
|
|
5396
|
+
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:p}=e,m=!!d,f=void 0!==p?p:t,y={type:m?"document":"file",path:c,documentId:d,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,externalEditDebugInfo:{detectionRan:!1,reason:m?"Skipped: Document operation":n.git?"Pending":"Skipped: No Git context"}}
|
|
5360
5397
|
try{let t,o
|
|
5361
|
-
if(
|
|
5398
|
+
if(m){t=await n.documentFileManager.getDocumentAsFile(d)
|
|
5362
5399
|
const e=n.documentFileManager.getCachedDocumentInfo(d)
|
|
5363
5400
|
y.filename=e?.filename,o="document:"+d}else{const e=u.validateAndNormalizePath(c,n)
|
|
5364
5401
|
o=e.normalizedPath,t=e.fullPath,y.path=o}const s=await l.default.readFile(t,"utf8"),p=[]
|
|
5365
5402
|
for(const t of g){const{old:n,new:o,match_mode:i="unique"}=t,a={old:n,new:o,success:!1}
|
|
5366
5403
|
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)
|
|
5367
|
-
continue}const t=(0,h.findMatches)(s,n,
|
|
5368
|
-
if(a.matchesFound=t.length,0===t.length){a.error="No matches found"+(
|
|
5404
|
+
continue}const t=(0,h.findMatches)(s,n,f,100,e.path)
|
|
5405
|
+
if(a.matchesFound=t.length,0===t.length){a.error="No matches found"+(f?" (tried fuzzy matching)":""),a.success=!1
|
|
5369
5406
|
const e=(0,h.findSimilarMatches)(s,n,5,.3)
|
|
5370
5407
|
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++):p.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
|
|
5371
5408
|
const I=[]
|
|
5372
5409
|
for(const e of p)for(const t of e.matches)I.push({match:t,newText:e.newText,repResult:e.repResult})
|
|
5373
5410
|
I.sort(((e,t)=>t.match.startPos-e.match.startPos))
|
|
5374
5411
|
for(const{match:e,newText:t,repResult:n}of I)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++)
|
|
5375
|
-
y.successfulReplacements>0&&(await l.default.writeFile(t,w,"utf8"),
|
|
5412
|
+
y.successfulReplacements>0&&(await l.default.writeFile(t,w,"utf8"),m&&(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)
|
|
5376
5413
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
5377
5414
|
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=[]
|
|
5378
5415
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -5386,7 +5423,7 @@ try{if(e&&"string"==typeof e.operations)try{e.operations=JSON.parse(e.operations
|
|
|
5386
5423
|
const E=u.validateArgs(e,d.ReplaceInFilesSchema),{resolveActiveTaskId:q}=await Promise.resolve().then(t.bind(t,3451)),S=e.taskId||await q(r,o,a)||"untracked",{operations:T,fuzzy_match:P=!0,comment:j}=E
|
|
5387
5424
|
b.info("Replace in files batch operation",{taskId:S,operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,comment:j})
|
|
5388
5425
|
const x=T.filter((e=>e.documentId)).map((e=>e.documentId))
|
|
5389
|
-
if(x.length>0&&r.apiClient)try{await(0,
|
|
5426
|
+
if(x.length>0&&r.apiClient)try{await(0,f.ensureDocumentsNotLocked)(x,r.apiClient,b,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
5390
5427
|
throw e}_=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5391
5428
|
const R=T[0],M=R.documentId?"document:"+R.documentId:R.path
|
|
5392
5429
|
let O=Date.now()
|
|
@@ -5410,7 +5447,7 @@ s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,t.fullP
|
|
|
5410
5447
|
b.info("\u{1f50d} Checking for external edits",{path:t.normalizedPath,affectedLines:o.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),matchCount:s.length})
|
|
5411
5448
|
const i=await(0,w.detectExternalEdits)(r.git,o,b)
|
|
5412
5449
|
b.info("\u{1f50d} External edit detection result",{path:t.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?(N.set(e.path,{message:i.message,debugInfo:i.debugInfo}),b.warn("\u26a0\ufe0f External edits detected before auto-commit",{path:t.normalizedPath,conflictingLines:i.conflictingLines})):(i.debugInfo&&N.set(e.path,{message:"",debugInfo:i.debugInfo}),b.info("\u2705 No external edit conflicts detected",{path:t.normalizedPath}))}else b.info("\u2139\ufe0f No matches found for external edit detection",{path:t.normalizedPath}),N.set(e.path,{message:"",debugInfo:{detectionRan:!1,reason:"No matches found - patterns not found in file",affectedRegion:"none",uncommittedChanges:"not checked",overlapDetected:!1}})}catch(t){b.warn("Failed to check for external edits before auto-commit",{path:e.path,error:(0,k.getErrorMessage)(t)})}if(Date.now(),O=Date.now(),A&&r.git)try{b.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
|
|
5413
|
-
const e=await(0,
|
|
5450
|
+
const e=await(0,m.commitUserChangesBeforeToolOperation)(r.git,"replace_in_files",{requestId:D,taskId:S,workspaceManager:r.workspaceManager},b,c)
|
|
5414
5451
|
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:S,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){b.warn("Pre-tool user changes commit failed",{taskId:S,error:e instanceof Error?e.message:e+""})}Date.now(),O=Date.now(),_=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5415
5452
|
const{toolRecordId:L}=await u.createFileOperationRecords(S,D,r.projectId,"replace-in-files",M,{operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,userComment:j},o,s,b,c,"replace_in_files",I)
|
|
5416
5453
|
C=L,Date.now(),O=Date.now(),_=u.FileOperationPhase.STRING_REPLACEMENT,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
@@ -5435,7 +5472,7 @@ for(const e of s)l+=`- \u274c \`${e.old.substring(0,40)}${e.old.length>40?"...":
|
|
|
5435
5472
|
return d.length>0&&(l+=`\n**Document Changes:** ${d.length} modified document(s) synced back to tracking system.\n`),o.workspaceManager?.largeFileWarning&&(l+=o.workspaceManager.largeFileWarning,o.workspaceManager.largeFileWarning=""),l}(z,G,J,K,r,C)
|
|
5436
5473
|
return{content:[{type:"text",text:X}],isError:0===J}}catch(e){const t=Date.now()-v
|
|
5437
5474
|
if(b.error("Replace in files batch operation failed",{error:e instanceof Error?e.stack:e+"",duration:t,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{status:"failed",error:(0,k.getErrorMessage)(e),phase:_,duration:t}})}catch(e){}return c.incrementCounter("replace_in_files_errors",1,{phase:_}),{content:[{type:"text",text:"\u274c **Replace In Files Failed:** "+(0,k.getErrorMessage)(e)}],isError:!0}}},c(t(857))
|
|
5438
|
-
const l=c(t(1943)),d=(a(t(9896)),a(t(6928)),c(t(6982)),t(6183)),u=a(t(5967)),h=t(3626),g=t(9860),p=t(5003),
|
|
5475
|
+
const l=c(t(1943)),d=(a(t(9896)),a(t(6928)),c(t(6982)),t(6183)),u=a(t(5967)),h=t(3626),g=t(9860),p=t(5003),m=t(7478),f=t(9949),y=t(9947),w=t(1318),k=t(8824)},9470(e,exports){"use strict"
|
|
5439
5476
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseLineSpec=function(e){if(!e||""===e.trim())throw Error("Line specification cannot be empty")
|
|
5440
5477
|
const t=e.trim()
|
|
5441
5478
|
if(t.includes("-")){const r=t.split("-").map((e=>e.trim()))
|
|
@@ -5506,11 +5543,11 @@ if(!h)throw new n.ValidationError("Project ID is required for listing tasks with
|
|
|
5506
5543
|
c.incrementCounter("list_tasks_attempts",1,{hasRequestId:!!a,hasFilters:Object.keys(u).length>0}),i.setProjectId(h)
|
|
5507
5544
|
const g=i.getTaskClient(),p=u
|
|
5508
5545
|
a&&(p.requestId=a),l.info("Listing tasks with filters",{projectId:h,taskFilters:p})
|
|
5509
|
-
const
|
|
5510
|
-
l.info("Raw tasks response data",{responseData:JSON.stringify(
|
|
5511
|
-
let
|
|
5512
|
-
|
|
5513
|
-
const y=
|
|
5546
|
+
const m=await g.listTasks(p)
|
|
5547
|
+
l.info("Raw tasks response data",{responseData:JSON.stringify(m)}),l.info("Tasks 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"})
|
|
5548
|
+
let f=[]
|
|
5549
|
+
m&&"object"==typeof m?"success"in m&&"data"in m?Array.isArray(m.data)?(f=m.data,l.info("Extracted tasks from success/data wrapper",{count:f.length})):m.data&&"object"==typeof m.data&&(f=[m.data],l.info("Extracted single task from success/data wrapper")):"data"in m?Array.isArray(m.data)?(f=m.data,l.info("Extracted tasks from data wrapper",{count:f.length})):m.data&&"object"==typeof m.data&&(f=[m.data],l.info("Extracted single task from data wrapper")):Array.isArray(m)?(f=m,l.info("Tasks response is direct array",{count:f.length})):(f=[m],l.info("Tasks response is single object")):(l.warn("Unexpected response format, using empty array",{responseType:typeof m}),f=[])
|
|
5550
|
+
const y=f
|
|
5514
5551
|
if(l.info(`Retrieved ${y.length} tasks`,{count:y.length,requestId:a,projectId:h}),0===y.length){let e=""
|
|
5515
5552
|
return e=a?`No tasks found for request ${a}.`:`No tasks found for project ${h} with the specified filters.`,d({success:!0,taskCount:0}),{content:[{type:"text",text:e}]}}const w=y.map(((e,t)=>{const r=e.sequenceNumber??t+1
|
|
5516
5553
|
return`**[${a?(0,s.formatTaskRef)(a,r):e.localId||e.id}]** ${e.title}\nStatus: ${e.status}\nCreated: ${new Date(e.createdAt).toLocaleString()}\nUpdated: ${new Date(e.updatedAt).toLocaleString()}`})).join("\n\n")
|