alchemylab 1.3.1 → 1.3.3
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/cli.js +8 -7
- package/dist/http-server.js +64 -59
- package/dist/index.js +331 -326
- package/dist/mcp-direct.js +152 -147
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -20,13 +20,13 @@ const m={requestId:c.requestId,projectId:d,title:c.title,description:c.descripti
|
|
|
20
20
|
h.info("Task input prepared",{taskInput:JSON.stringify(m)}),h.info("Creating task via task client",{projectId:d,requestId:c.requestId,title:c.title})
|
|
21
21
|
const y=await f.createTask(m)
|
|
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:m.title,description:m.description,status:"pending",requestId:m.requestId,projectId:d,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}}),k="data"in w?w.data:w,
|
|
23
|
+
const w=(0,o.extractDataFromResponse)(y,{logger:h,operationName:"createTask",defaultValue:{id:"tas"+Date.now().toString().substring(5,11),title:m.title,description:m.description,status:"pending",requestId:m.requestId,projectId:d,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}}),k="data"in w?w.data:w,b=k.localId||k.id||"tas"+Date.now().toString().substring(5,11),I=k.title||m.title,v=k.description||m.description,C=k.status||"pending",_=k.requestId||m.requestId
|
|
24
24
|
let E,q="unknown"
|
|
25
|
-
k&&"object"==typeof k&&"_workingEndpoint"in k&&(q=k._workingEndpoint),h.info("Successfully extracted task data from response",{taskId:
|
|
25
|
+
k&&"object"==typeof k&&"_workingEndpoint"in k&&(q=k._workingEndpoint),h.info("Successfully extracted task data from response",{taskId:b,requestId:_,title:I})
|
|
26
26
|
try{const e=a.getToolRecordClient()
|
|
27
|
-
if(e){const t=await e.createToolRecord({taskId:
|
|
28
|
-
E=t?.id}}catch(e){h.error("Failed to create tool record for task creation, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:
|
|
29
|
-
let S=`Created Task ${k.sequenceNumber&&_?(0,i.formatTaskRef)(_,k.sequenceNumber):
|
|
27
|
+
if(e){const t=await e.createToolRecord({taskId:b,requestId:_,projectId:d,type:"create-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:I,taskDescription:v,taskStatus:C},note:"Created task "+I})
|
|
28
|
+
E=t?.id}}catch(e){h.error("Failed to create tool record for task creation, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:b,requestId:_})}g({success:!0,requestId:c.requestId,projectId:d}),h.info("Task created successfully",{taskId:b,requestId:_,title:I,projectId:d})
|
|
29
|
+
let S=`Created Task ${k.sequenceNumber&&_?(0,i.formatTaskRef)(_,k.sequenceNumber):b}: ${I}`
|
|
30
30
|
return E&&(S+=`\n[RECORD:${E}]`),{content:[{type:"text",text:S}]}}catch(r){if(h.error("Failed to create task",{error:r instanceof Error?r.stack:r+"",args:e}),t.projectId)try{if(r instanceof Error&&(r.message.includes("Project is disabled")||r.message.includes("Project cannot accept new tasks")||r.message.includes("disabled due to tier limits")||r.message.includes("Project is inactive due to tier limits")))h.info("Skipping tool record creation for disabled project error",{projectId:t.projectId,error:r.message})
|
|
31
31
|
else{const n=a.getToolRecordClient()
|
|
32
32
|
n&&await n.createToolRecord({requestId:e.requestId,projectId:t.projectId,type:"create-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.title,taskDescription:e.description?.substring(0,100)+(e.description?.length>100?"...":""),error:(0,s.getErrorMessage)(r),errorDetails:r instanceof Error?r.stack:r+""},note:"Failed to create task: "+e.title})}}catch(e){h.error("Failed to create failure record for task creation",{error:e instanceof Error?e.message:e+""})}g({success:!1,error:r instanceof Error?r.name:"unknown"})
|
|
@@ -45,7 +45,7 @@ var t={}
|
|
|
45
45
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
46
46
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
47
47
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.McpServer=void 0,exports.resetStdoutWrite=function(){process.stdout.write=R},exports.getMcpServer=r,exports.createServer=function(e,t,n,o,s={}){return r(e,t,n,o,s)}
|
|
48
|
-
const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),p=t(3444),f=t(7660),m=t(1253),y=t(5172),w=i(t(7478)),k=t(4139),
|
|
48
|
+
const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),p=t(3444),f=t(7660),m=t(1253),y=t(5172),w=i(t(7478)),k=t(4139),b=new Set,I=t(9860),v=t(1472),C=t(3328),_=t(8955),E=t(3217),q=t(5278),S=t(446),T=t(9060),P=t(8824),j=(0,p.createLogger)({serviceName:"stdout-capture",console:!1,logToFile:!1}),R=process.stdout.write,x=process.argv.includes("--stdio")||"true"===process.env.MCP_DIRECT_MODE
|
|
49
49
|
!(0,p.isDebugToolsEnabled)()||x&&"true"!==process.env.DEBUG_STDOUT_CAPTURE||(process.stdout.write=function(e){try{return(0,p.isDebugToolsEnabled)()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()&&"string"==typeof e&&!e.trim().startsWith('{"jsonrpc":"2.0"')&&e.trim().length>0&&j.debug("Stdout output",{content:e.substring(0,100),length:e.length}),R.call(process.stdout,e)}catch(e){return j.error("Error in safeStdoutWrite",{error:e+""}),!0}})
|
|
50
50
|
class M{constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,k.ALCHEMY_DIR_NAME),this.metrics=r,this.remoteServerUrl=n,this.existingProjectId=o.existingProjectId,this.gitBinary=(0,l.detectGitBinary)(),this.logger.info("Detected git binary",{gitBinary:this.gitBinary,version:(0,l.getGitVersion)()}),this.projectContext=new f.ProjectContext(e,t),this.tokenManager=new m.TokenManager(t,e,{remoteServerUrl:n}),this.lockOverrideManager=new S.LockOverrideManager(t),this.configManager=new T.ConfigManager(t),this.logger.debug("Server paths initialized",{basePath:this.basePath,alchemyPath:this.alchemyPath}),this.server=new g.Server({name:"alchemy",version:"1.0.0"},{capabilities:{tools:{search:{},create_request:{},complete_task:{},get_task_information:{},complete_request:{},revert_request:{},get_request_information:{},list_tasks:{},list_requests:{},switch_to_branch:{},read_files:{},create_directory:{},move_files:{},write_file:{},replace_strings:{},insert_lines:{},replace_lines:{},delete_files:{},document_operations:{},file_history:{},task_file_history:{},request_file_history:{},quick_write:{},quick_replace:{},quick_manage:{}}}}),(0,y.setGlobalClientInfo)("OpenCode","1.0.0"),this.metrics.incrementCounter("mcp_server_init_started",1),this.logger.info("Starting initialization for server instance"),this.initializationPromise=this.initialize()}get branchState(){if(!this.workspaceManager)return{currentBranch:null,activeRequestId:null,isOnMainBranch:!0}
|
|
51
51
|
const e=this.workspaceManager.getCurrentContext("__server__")
|
|
@@ -57,7 +57,7 @@ const n=await r.getNextId(e)
|
|
|
57
57
|
return t({success:!0,type:e}),this.metrics.incrementCounter("remote_id_success",1,{type:e}),n}catch(t){throw this.metrics.incrementCounter("remote_id_failure",1,{type:e,error:t instanceof Error?t.name:"unknown"}),this.logger.warn("Failed to get ID from remote server, unable to perform operation",{type:e,error:(0,P.getErrorMessage)(t)}),Error("Failed to get ID from remote server.")}}async initialize(){const e=this.remoteServerUrl||"https://api.alchemylabcode.com"
|
|
58
58
|
this.logger.debug("Using remote server URL",{remoteServerUrl:e})
|
|
59
59
|
const t=d.default.resolve(this.basePath)
|
|
60
|
-
if(
|
|
60
|
+
if(b.has(t))return this.logger.info("Path already initialized in global registry, skipping initialization",{path:t}),void(this.isInitialized=!0)
|
|
61
61
|
if(this.isInitialized)this.logger.info("Server already initialized, skipping initialization")
|
|
62
62
|
else{if(this.isInitializing)return this.logger.info("Initialization already in progress, waiting..."),void await this.initializationPromise
|
|
63
63
|
this.isInitializing=!0,this.logger.info("SERVER INITIALIZATION STARTING",{path:t,pid:process.pid,time:(new Date).toISOString()}),this.metrics.setGauge("mcp_initialization",0,{status:"starting"})
|
|
@@ -78,7 +78,7 @@ const e=d.default.join(this.basePath,"README.md")
|
|
|
78
78
|
if(!u.default.existsSync(e)){const t=`# Project at ${this.basePath}\n\nCreated with AlchemyMCP Server.\n`
|
|
79
79
|
await h.default.writeFile(e,t)}this.logger.info("Git repository initialized successfully"),await this.git.add(".")
|
|
80
80
|
const t=await this.git.status()
|
|
81
|
-
t.staged.length>0?(await this.git.commit("Initial commit by AlchemyMCP Server"),this.logger.info(`Initial commit created with ${t.staged.length} files`)):this.logger.info("No files to commit in initial repository")}catch(e){this.logger.error("Failed to initialize git repository",{error:e instanceof Error?e.stack:e+""})}}cleanupSSEConnection(){this.currentSSEConnection&&(this.currentSSEConnection.transport.close(),this.currentSSEConnection=null,this.logger.debug("SSE connection closed"))}handleError(e,t){if(t instanceof Error){const r=(0,
|
|
81
|
+
t.staged.length>0?(await this.git.commit("Initial commit by AlchemyMCP Server"),this.logger.info(`Initial commit created with ${t.staged.length} files`)):this.logger.info("No files to commit in initial repository")}catch(e){this.logger.error("Failed to initialize git repository",{error:e instanceof Error?e.stack:e+""})}}cleanupSSEConnection(){this.currentSSEConnection&&(this.currentSSEConnection.transport.close(),this.currentSSEConnection=null,this.logger.debug("SSE connection closed"))}handleError(e,t){if(t instanceof Error){const r=(0,I.createMcpProtocolError)(t.message||"Unknown error")
|
|
82
82
|
this.logger.error("MCP error",{message:t.message,name:t.name,stack:t.stack,code:r.code}),e.status(500).json({error:{message:t.message,code:r.code,data:r.data||{details:t.message}}})}else this.logger.error("Unknown error",{error:t+""}),e.status(500).json({error:{message:"Unknown error occurred",code:-32e3,data:{details:t+""}}})
|
|
83
83
|
return Promise.resolve()}async waitForInitialization(){return this.isInitialized?Promise.resolve():(this.logger.debug("Waiting for initialization to complete..."),this.initializationPromise)}async initializeComplete(){let e
|
|
84
84
|
this.logger.info("Starting server initialization")
|
|
@@ -128,7 +128,7 @@ return t?.path||this.basePath}}exports.McpServer=M
|
|
|
128
128
|
const O=new Map},213(e,exports,t){"use strict"
|
|
129
129
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
130
130
|
const r=t(6183),n=t(3707)
|
|
131
|
-
exports.def={name:"quick_write",description:"
|
|
131
|
+
exports.def={name:"quick_write",description:"WHEN TO USE: trivial single-file edits only. For multi-file or feature work, spawn a coder via subagent_operations.\n\nCreate or update a file or document. Wraps the change in a request/task workflow that auto-completes.\n\nUse 'path' for filesystem files or 'documentId' for tracked documents.\nSet append:true to add content to existing content.\n\nRequires: title, description, path/documentId, content.",schema:r.QuickWriteSchema,annotations:{title:"Quick Write",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"write",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},233(e,exports,t){"use strict"
|
|
132
132
|
function r(e,t){const r=e.toLowerCase().indexOf(t.toLowerCase())
|
|
133
133
|
return-1===r?e:`${e.substring(0,r)}**${e.substring(r,r+t.length)}**${e.substring(r+t.length)}`}function n(e,t,r){const n=e.toLowerCase().indexOf(t)
|
|
134
134
|
if(-1===n)return e.substring(0,r)+"..."
|
|
@@ -156,13 +156,13 @@ const w=[],k=a.toLowerCase()
|
|
|
156
156
|
for(const e of y){const t=[]
|
|
157
157
|
if("all"!==l&&"title"!==l||!e.title||e.title.toLowerCase().includes(k)&&t.push({request:e,matchType:"title",matchSnippet:r(e.title,a)}),"all"!==l&&"description"!==l||!e.description||e.description.toLowerCase().includes(k)&&t.push({request:e,matchType:"description",matchSnippet:n(e.description,k,150)}),("all"===l||"criteria"===l)&&e.acceptanceCriteria)for(const r of e.acceptanceCriteria){const o="string"==typeof r?r:r.description
|
|
158
158
|
if(o&&o.toLowerCase().includes(k)){t.push({request:e,matchType:"criteria",matchSnippet:n(o,k,150)})
|
|
159
|
-
break}}t.length>0&&w.push(t[0])}const
|
|
160
|
-
if(0===
|
|
161
|
-
let v=`Found ${
|
|
162
|
-
for(const e of
|
|
159
|
+
break}}t.length>0&&w.push(t[0])}const b=g.limit||20,I=w.slice(0,b)
|
|
160
|
+
if(0===I.length)return h({success:!0,resultCount:0}),{content:[{type:"text",text:`No requests found matching "${a}".\n\nSearched in: ${l}\nTotal requests checked: ${y.length}`}]}
|
|
161
|
+
let v=`Found ${I.length} request${1===I.length?"":"s"} matching "${a}":\n\n`
|
|
162
|
+
for(const e of I){const t=e.request,r=o(t.status)
|
|
163
163
|
v+=`${s(t.type)} **${t.title}** (${t.id}) ${r}\n`,v+=" \u{1f4cd} Match in "+e.matchType,e.matchSnippet&&(v+=": "+e.matchSnippet),v+="\n\n"}v+=`---\nSearched ${y.length} requests (filtered by: `
|
|
164
164
|
const C=[]
|
|
165
|
-
return g.status&&C.push("status="+g.status),g.type&&C.push("type="+g.type),g.dateFrom&&C.push("from="+g.dateFrom),g.dateTo&&C.push("to="+g.dateTo),v+=C.length>0?C.join(", "):"none",v+=")",h({success:!0,resultCount:
|
|
165
|
+
return g.status&&C.push("status="+g.status),g.type&&C.push("type="+g.type),g.dateFrom&&C.push("from="+g.dateFrom),g.dateTo&&C.push("to="+g.dateTo),v+=C.length>0?C.join(", "):"none",v+=")",h({success:!0,resultCount:I.length}),d.incrementCounter("search_requests_success",1),{content:[{type:"text",text:v}]}}catch(e){return u.error("Search requests failed",{error:e instanceof Error?e.stack:e+""}),h({success:!1,error:(0,a.getErrorMessage)(e)}),d.incrementCounter("search_requests_errors",1),{content:[{type:"text",text:"\u274c **Search Failed:** "+(0,a.getErrorMessage)(e)}],isError:!0}}}
|
|
166
166
|
const i=t(9860),a=t(8824)},260(e,exports,t){"use strict"
|
|
167
167
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
168
168
|
const r=t(6183),n=t(4221)
|
|
@@ -223,17 +223,17 @@ const r=await e.lockRequest(k.requestId,t)
|
|
|
223
223
|
if(!r.locked)throw new n.ValidationError(`Failed to acquire lock for request ${k.requestId}. Another agent may have just locked it. Try again shortly.`,{taskId:h,requestId:k.requestId})
|
|
224
224
|
p.info("Auto-acquired lock for task completion",{requestId:k.requestId,sessionTag:t,lockedAt:r.lockedAt})}p.info("Request lock validation passed",{taskId:h,requestId:k.requestId,sessionTag:t})}catch(e){if(e instanceof n.ValidationError)throw e
|
|
225
225
|
throw p.error("Failed to check request lock status",{taskId:h,requestId:k.requestId,error:(0,c.getErrorMessage)(e)}),new n.ValidationError("Failed to verify request lock status: "+(0,c.getErrorMessage)(e),{taskId:h,requestId:k.requestId})}}else p.debug("Task without requestId: skipping lock check",{taskId:h,hasRequestId:!!k.requestId})
|
|
226
|
-
let
|
|
226
|
+
let b=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
|
-
|
|
230
|
-
if(
|
|
229
|
+
b=simpleGit({baseDir:e.basePath,binary:d.gitBinary}),p.debug("Using workspace-aware git instance for task completion",{taskId:h,mode:e.mode,requestId:e.requestId,basePath:e.basePath})}}let I=null
|
|
230
|
+
if(b)try{(await b.status()).isClean()||(I=(await b.commit(`Complete task ${h}: ${m}`)).commit,p.info("Created commit for task completion",{taskId:h,commitId:I}))}catch(e){p.warn("Failed to commit changes",{error:(0,c.getErrorMessage)(e)})}let v=null
|
|
231
231
|
try{const e=u.getToolRecordClient()
|
|
232
|
-
e&&(v={id:(await e.createToolRecord({taskId:h,requestId:k.requestId,projectId:y,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:k.title,completionSummary:m,lastCommit:
|
|
232
|
+
e&&(v={id:(await e.createToolRecord({taskId:h,requestId:k.requestId,projectId:y,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:k.title,completionSummary:m,lastCommit:I,completedAt:(new Date).toISOString()},note:`Completed task: ${m.substring(0,100)}${m.length>100?"...":""}`})).id})}catch(e){p.error("Failed to create tool record for task completion, but continuing",{error:e instanceof Error?e.stack:e+"",taskId:h,requestId:k.requestId})}try{const e=k.metadata||{},t=(new Date).toISOString(),r={status:"completed",metadata:{...e,lastCommit:I,completionSummary:m,completionRecordId:v?.id,completedAt:t}},n=await w.updateTask(h,r)
|
|
233
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
|
-
if(v?.id&&(a+=`\n[RECORD:${v.id}]`),
|
|
236
|
+
if(v?.id&&(a+=`\n[RECORD:${v.id}]`),I&&(a+="\nCommit: "+I.substring(0,8)),o)try{const e=await w.listTasks({requestId:o})
|
|
237
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
239
|
p.info("Task progress check",{requestId:o,totalTasks:r,completedTasks:n}),a+=`\n\nTask Progress: ${n}/${r} tasks completed`,n===r&&(a+=`\n\nAll tasks for request ${o} are now completed! You may consider marking the request as completed using the complete-request tool.`)}catch(e){p.warn("Failed to check task progress",{error:(0,c.getErrorMessage)(e),requestId:o})}return f({success:!0}),{content:[{type:"text",text:a}]}}catch(e){throw p.error("Failed to complete task",{error:e instanceof Error?e.stack:e+"",taskId:h}),Error("Failed to complete task: "+(0,c.getErrorMessage)(e))}}catch(t){if(p.error("Failed to complete task",{error:t instanceof Error?t.stack:t+"",args:e}),d.projectId)try{const r=u.getToolRecordClient()
|
|
@@ -453,7 +453,7 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerApiRoutes
|
|
|
453
453
|
n.debug("Token retrieved from authentication manager")
|
|
454
454
|
const x=new k.ConnectionStatusManager(T,n.child({component:"connection-status-manager"}),o,{checkIntervalMs:3e4,timeoutMs:5e3}),M=new w.ProjectClient(T,n.child({component:"project-client"}),o,x,R)
|
|
455
455
|
j.registerClient(M)
|
|
456
|
-
const O=new
|
|
456
|
+
const O=new I.TaskClient(T,n.child({component:"task-client"}),o,M,x,R)
|
|
457
457
|
j.registerClient(O)
|
|
458
458
|
const D=new v.FileOperationsClient(T,n.child({component:"file-client"}),o,M,R,x)
|
|
459
459
|
j.registerClient(D)
|
|
@@ -479,9 +479,9 @@ if((0,d.isDebugToolsEnabled)()&&s.debug("Task validation response received",{tas
|
|
|
479
479
|
let o=!1
|
|
480
480
|
if("object"==typeof e&&null!==e){404===e.statusCode&&(o=!0),404===e.response?.statusCode&&(o=!0)
|
|
481
481
|
const t=(e.message||e.error||e)+"";(t.includes("404")||t.toLowerCase().includes("not found"))&&(o=!0)}if(o)return s.info("Task ID not found - blocking operation",{taskId:n,statusCode:404,action:"blocking"}),t.status(400).json({success:!1,error:{code:"TASK_NOT_FOUND",message:"Task ID does not exist: "+n,retryable:!1,statusCode:400}})
|
|
482
|
-
s.warn("Error validating task ID",{taskId:n,error:(0,
|
|
482
|
+
s.warn("Error validating task ID",{taskId:n,error:(0,b.getErrorMessage)(e)}),s.warn("Error validating task ID, but continuing as fallback",{taskId:n,action:"continuing"}),r()}}
|
|
483
483
|
e.get("/health",((e,t)=>{o.incrementCounter("api_requests_total",1,{endpoint:"health",method:"GET"}),t.json({success:!0,data:{status:"ok",version:"0.1.0",serverType:"mcp-local-server",timestamp:(new Date).toISOString()}})})),e.get("/mcp/sse",(async(e,t)=>{s.info("New SSE connection requested",{ip:e.ip,userAgent:e.headers["user-agent"]}),o.incrementCounter("mcp_connections_total",1,{type:"sse"})
|
|
484
|
-
try{await r.createSseConnection(t,e.headers["user-agent"]),t.on("close",(()=>{s.info("SSE connection closed"),o.setGauge("mcp_active_connections",0,{type:"sse"}),r.cleanupSSEConnection()}))}catch(e){s.error("Failed to establish MCP SSE connection",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("mcp_connection_errors",1,{type:"sse",error:e instanceof Error?e.name:"unknown"}),t.headersSent?t.end():t.status(500).json({success:!1,error:"Failed to establish SSE connection",message:(0,
|
|
484
|
+
try{await r.createSseConnection(t,e.headers["user-agent"]),t.on("close",(()=>{s.info("SSE connection closed"),o.setGauge("mcp_active_connections",0,{type:"sse"}),r.cleanupSSEConnection()}))}catch(e){s.error("Failed to establish MCP SSE connection",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("mcp_connection_errors",1,{type:"sse",error:e instanceof Error?e.name:"unknown"}),t.headersSent?t.end():t.status(500).json({success:!1,error:"Failed to establish SSE connection",message:(0,b.getErrorMessage)(e)})}})),e.get("/api/files/exists",U,(async(e,t,r)=>{try{o.incrementCounter("api_requests_total",1,{endpoint:"files/exists",method:"GET"})
|
|
485
485
|
const r=B("api_request_duration")
|
|
486
486
|
try{const n=await l.default.stat(e.fullPath)
|
|
487
487
|
r({endpoint:"files/exists",method:"GET",success:!0}),t.json({success:!0,data:{exists:!0,isDirectory:n.isDirectory(),isFile:n.isFile(),size:n.size,modified:n.mtime}})}catch(e){if("ENOENT"!==e.code)throw e
|
|
@@ -531,7 +531,7 @@ r.getContext(),s.info("Manual project synchronization requested"),s.info("Starti
|
|
|
531
531
|
try{await M.syncProjects(),e({endpoint:"sync/projects",method:"POST",success:!0}),t.json({success:!0,data:{message:"Project synchronization completed successfully",timestamp:(new Date).toISOString()}})}catch(r){s.error("Project synchronization failed",{error:r instanceof Error?r.stack:r+""}),e({endpoint:"sync/projects",method:"POST",success:!1}),t.status(500).json({success:!1,error:"Project synchronization failed",message:r instanceof Error?r.message:r+"",timestamp:(new Date).toISOString()})}}catch(e){n(e)}})),e.get("/api/remote/status",(async(e,t,r)=>{try{o.incrementCounter("api_requests_total",1,{endpoint:"remote/status",method:"GET"})
|
|
532
532
|
const e=B("api_request_duration")
|
|
533
533
|
try{const r=await M.pingDetailed(),n="online"===r.status,o=r.latency
|
|
534
|
-
e({endpoint:"remote/status",method:"GET",success:!0,connected:n}),s.info("Remote server status check",{status:n?"ONLINE":"OFFLINE",latencyMs:o}),t.json({success:!0,data:{connected:n,url:T,latency:o,queueStats:{total:0,pending:0,inProgress:0,completed:0,failed:0},isOffline:M.isOffline(),serverTime:(new Date).toISOString()}})}catch(r){e({endpoint:"remote/status",method:"GET",success:!0,connected:!1}),t.json({success:!0,data:{connected:!1,url:T,error:(0,
|
|
534
|
+
e({endpoint:"remote/status",method:"GET",success:!0,connected:n}),s.info("Remote server status check",{status:n?"ONLINE":"OFFLINE",latencyMs:o}),t.json({success:!0,data:{connected:n,url:T,latency:o,queueStats:{total:0,pending:0,inProgress:0,completed:0,failed:0},isOffline:M.isOffline(),serverTime:(new Date).toISOString()}})}catch(r){e({endpoint:"remote/status",method:"GET",success:!0,connected:!1}),t.json({success:!0,data:{connected:!1,url:T,error:(0,b.getErrorMessage)(r),serverTime:(new Date).toISOString()}})}}catch(e){r(e)}})),e.get("/api/proxy/*",(async(e,t,r)=>{try{const r=e.path.substring(11)
|
|
535
535
|
try{const n=await L.proxyGet(r,e.query)
|
|
536
536
|
t.json(n)}catch(e){if(e instanceof Error&&e.message.includes("ECONNREFUSED"))return t.status(503).json({success:!1,error:"Remote server is unreachable",remotePath:r})
|
|
537
537
|
throw e}}catch(e){r(e)}})),e.post("/api/proxy/*",G,(async(e,t,r)=>{try{const r=e.path.substring(11)
|
|
@@ -541,7 +541,7 @@ throw e}}catch(e){r(e)}})),e.patch("/api/proxy/*",G,(async(e,t,r)=>{try{const r=
|
|
|
541
541
|
try{const n=await L.proxyPatch(r,e.body)
|
|
542
542
|
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})
|
|
543
543
|
throw e}}catch(e){r(e)}}))}
|
|
544
|
-
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),f=t(4079),m=t(3895),y=s(t(5967)),w=t(4710),k=t(5681),
|
|
544
|
+
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),f=t(4079),m=t(3895),y=s(t(5967)),w=t(4710),k=t(5681),b=t(8824),I=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"
|
|
545
545
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
546
546
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.TokenManager=void 0
|
|
547
547
|
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"
|
|
@@ -588,9 +588,9 @@ if(this.TOKEN_CACHE.hasValidToken&&e<this.TOKEN_CACHE.hasValidToken.expiresAt){c
|
|
|
588
588
|
return this.logger.debug("Using cached hasValidToken result",{ageSecs:Math.round((e-t.timestamp)/1e3),hasToken:t.value}),t.value}this.logger.debug("Checking if valid token exists (cache miss or expired)")
|
|
589
589
|
const t=null!==await this.getToken()
|
|
590
590
|
return this.TOKEN_CACHE.hasValidToken={value:t,timestamp:e,expiresAt:e+this.CACHE_TTL_MS,lastCheck:e,exists:t},t}getTokenDirectoryPath(){return this.tokenDirPath}getManualTokenFilePath(){return n.default.join(this.tokenDirPath,"manual-token.json")}logTokenLocationInstructions(){const e=this.getManualTokenFilePath()
|
|
591
|
-
console.log("========================================"),console.log("To use
|
|
591
|
+
console.log("========================================"),console.log("To use the alchemy CLI, you need to authenticate."),console.log("Token file location: "+e),console.log("You can either:"),console.log('\n1. Use the authenticate tool (recommended)\n2. Manually place a token file at the above location\n3. Set up automatic authentication flow\n\nFor manual token placement, create a JSON file with:\n{\n "token": "your_token_here",\n "userId": "your_user_id",\n "username": "your_username", \n "role": "user",\n "expiresAt": "2025-12-31T23:59:59.000Z"\n}\n'),console.log("For more information, see the authentication documentation."),console.log("========================================")}async startAuthenticationFlow(){this.pendingAuthCheck=!0
|
|
592
592
|
try{const{tempCode:e,authUrl:t}=await this.authFlow.startAuthFlow()
|
|
593
|
-
return this.tempAuthCode=e,this.logger.info("Started external authentication flow",{tempCode:e,authUrl:t}),this.authFlow.startPolling(e,(async t=>{this.logger.info("Authentication flow completed",{tempCode:e.substring(0,4)+"***",username:t.username}),await this.storeToken(t),this.pendingAuthCheck=!1,this.tempAuthCode=null,this.invalidateCache(),console.log("Authentication successful!"),console.log(`Welcome, ${t.username}!`),console.log("You can now use
|
|
593
|
+
return this.tempAuthCode=e,this.logger.info("Started external authentication flow",{tempCode:e,authUrl:t}),this.authFlow.startPolling(e,(async t=>{this.logger.info("Authentication flow completed",{tempCode:e.substring(0,4)+"***",username:t.username}),await this.storeToken(t),this.pendingAuthCheck=!1,this.tempAuthCode=null,this.invalidateCache(),console.log("Authentication successful!"),console.log(`Welcome, ${t.username}!`),console.log("You can now use the alchemy CLI."),console.log("========================================")}),(()=>{this.logger.info("Authentication flow timed out",{tempCode:e.substring(0,4)+"***"}),this.pendingAuthCheck=!1,this.tempAuthCode=null,console.log("Authentication flow timed out."),console.log("Please try again or manually place a token file."),console.log("Token file location:"),console.log(""+this.getManualTokenFilePath()),console.log("========================================")}),(t=>{this.logger.error("Authentication flow error",{tempCode:e.substring(0,4)+"***",error:t}),this.pendingAuthCheck=!1,this.tempAuthCode=null,console.log("Authentication flow error."),console.log("Error: "+t),console.log("Please try again or manually place a token file."),console.log(""+this.getManualTokenFilePath()),console.log("========================================")})),{tempCode:e,authUrl:t}}catch(e){throw this.logger.error("Error starting authentication flow",{error:(0,c.getErrorMessage)(e)}),this.pendingAuthCheck=!1,this.tempAuthCode=null,e}}hasPendingAuth(){return this.pendingAuthCheck||!!this.tempAuthCode}getAuthStatus(){return this.hasPendingAuth()?{hasToken:!1,isPendingAuth:!0,tempCode:this.tempAuthCode,authUrl:this.authFlow.getAuthUrl(this.tempAuthCode)}:{hasToken:!1,isPendingAuth:!1}}async checkAuthStatus(e){if(!e)return null
|
|
594
594
|
try{const t=this.authFlow.getPollingStatus()
|
|
595
595
|
if(t.status===a.PollingStatus.AUTHENTICATED&&t.tokenInfo)return this.logger.info("Authentication polling has token available",{tempCode:e.substring(0,4)+"***",username:t.tokenInfo.username}),t.tokenInfo
|
|
596
596
|
if(t.status===a.PollingStatus.ERROR||t.status===a.PollingStatus.TIMEOUT)return this.pendingAuthCheck=!1,this.tempAuthCode=null,null
|
|
@@ -608,18 +608,18 @@ return this.logger.info("Token validation successful",{status:e.status||"unknown
|
|
|
608
608
|
Object.defineProperty(exports,"__esModule",{value:!0})},1281(e,exports,t){"use strict"
|
|
609
609
|
async function r(e,t,o,s,i,a,c,l,d,u=0){let p=0,f=0,m=0
|
|
610
610
|
const y=[]
|
|
611
|
-
if(o.length>=
|
|
611
|
+
if(o.length>=I||c>10)return a.debug("Stopping search in directory - hard cap or depth limit reached",{dir:e,matchesCount:o.length,hardCap:I,depth:c}),{filesCount:p,fileMatchesCount:f,subdirCount:m,subdirStats:y}
|
|
612
612
|
try{const w=await g.default.readdir(e,{withFileTypes:!0}),v=[],C=[]
|
|
613
613
|
for(const t of w){const r=h.default.join(e,t.name)
|
|
614
|
-
if(t.isDirectory()){if(
|
|
614
|
+
if(t.isDirectory()){if(b.includes(t.name)||t.name.startsWith(".")){a.debug("Skipping excluded directory: "+t.name)
|
|
615
615
|
continue}C.push({entry:t,fullPath:r})}else if(t.isFile()){if("*"!==i&&!t.name.endsWith(i)){a.debug("Skipping file due to extension mismatch",{filename:t.name,requiredExtension:i})
|
|
616
616
|
continue}v.push({entry:t,fullPath:r})}}if(v.length>0){const e=[]
|
|
617
617
|
for(let t=0;t<v.length;t+=16)e.push(v.slice(t,t+16))
|
|
618
|
-
for(const r of e){if(o.length>=
|
|
618
|
+
for(const r of e){if(o.length>=I)break
|
|
619
619
|
const e=await Promise.all(r.map((({entry:e,fullPath:r})=>n(r,t,0,o,l,d,e.name,u))))
|
|
620
620
|
for(const t of e){p++,t.hasMatches&&f++
|
|
621
|
-
for(const e of t.matches){if(o.length>=
|
|
622
|
-
o.push(e)}}}}for(const{entry:e,fullPath:n}of C){if(o.length>=
|
|
621
|
+
for(const e of t.matches){if(o.length>=I)return{filesCount:p,fileMatchesCount:f,subdirCount:m,subdirStats:y}
|
|
622
|
+
o.push(e)}}}}for(const{entry:e,fullPath:n}of C){if(o.length>=I)break
|
|
623
623
|
m++
|
|
624
624
|
const e={path:n,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
|
|
625
625
|
try{const l=await r(n,t,o,s,i,a,c+1,e,d,u)
|
|
@@ -630,7 +630,7 @@ let l,d=!1
|
|
|
630
630
|
const u=async()=>{if(void 0===l)try{const t=await g.default.stat(e)
|
|
631
631
|
l=t.mtime.getTime()}catch(e){l=void 0}return l}
|
|
632
632
|
if("filename"!==s&&"both"!==s||t.test(i)&&(d=!0,await u(),c.push({file:e,line:0,text:i,modifiedTime:l,matchType:"filename"})),"content"===s||"both"===s)try{const r=(await g.default.readFile(e,"utf8")).split("\n")
|
|
633
|
-
for(let o=0;o<r.length&&n.length<
|
|
633
|
+
for(let o=0;o<r.length&&n.length<I;o++)if(t.test(r[o])){d=!0,await u()
|
|
634
634
|
const t={file:e,line:o+1,text:(0,y.truncate)(r[o].trim(),120),modifiedTime:l,matchType:"content"}
|
|
635
635
|
if(a>0){const e=Math.max(0,o-a)
|
|
636
636
|
t.contextBefore=r.slice(e,o).map((e=>(0,y.truncate)(e.trim(),120)))
|
|
@@ -657,29 +657,29 @@ var t={}
|
|
|
657
657
|
if(null!=e)for(var r=a(e),n=0;n<r.length;n++)"default"!==r[n]&&c(t,e,r[n])
|
|
658
658
|
return l(t,e),t}),u=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
659
659
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSearch=async function(e,t,n,a,c){const l=a.child({tool:"search"}),d=c.startTimer("tool_execution_time"),u=Date.now()
|
|
660
|
-
let
|
|
661
|
-
const
|
|
660
|
+
let b=0
|
|
661
|
+
const I={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:[]}
|
|
662
662
|
try{const{needle:n,directory:p,options:v={}}=e
|
|
663
663
|
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)
|
|
664
|
-
if("string"!=typeof n)throw
|
|
664
|
+
if("string"!=typeof n)throw I.errors.push("Search term (needle) must be a string"),(0,f.createValidationError)("Search term (needle) must be a string")
|
|
665
665
|
let C
|
|
666
|
-
if(
|
|
666
|
+
if(I.searchDirectory=p||".",p){const{normalizedPath:e,fullPath:r}=m.validateAndNormalizePath(p,t)
|
|
667
667
|
C=r}else C=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
|
|
668
|
-
|
|
668
|
+
I.resolvedPath=C
|
|
669
669
|
let _=!1
|
|
670
670
|
try{_=(await g.default.stat(C)).isFile()}catch(e){const t=`Cannot access path ${C}: ${(0,k.getErrorMessage)(e)}`
|
|
671
|
-
throw
|
|
671
|
+
throw I.errors.push(t),Error(t)}const E=v.maxResults||50,q=v.caseSensitive||!1,S=v.useRegex||!1,T=v.fileExtension,P=v.searchIn||"content"
|
|
672
672
|
let j=void 0!==v.contextLines?v.contextLines:0
|
|
673
|
-
if(0>j?j=0:j>10&&(l.warn(`contextLines ${j} exceeds maximum of 10, clamping to 10`),j=10),!_&&!T)throw
|
|
673
|
+
if(0>j?j=0:j>10&&(l.warn(`contextLines ${j} exceeds maximum of 10, clamping to 10`),j=10),!_&&!T)throw I.errors.push('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")'),(0,f.createValidationError)('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")')
|
|
674
674
|
let R,x=""
|
|
675
675
|
if(_)x="*"
|
|
676
676
|
else if("*"===T)x="*"
|
|
677
677
|
else if(T){let e=T;(e.startsWith("*.")||e.startsWith("*"))&&(e=e.substring(1)),x=e.startsWith(".")?e:"."+e}try{R=S?q?RegExp(n):RegExp(n,"i"):q?RegExp(o(n)):RegExp(o(n),"i")}catch(e){const t=`Invalid ${S?"regex":"search"} pattern: ${(0,k.getErrorMessage)(e)}`
|
|
678
|
-
throw
|
|
678
|
+
throw I.errors.push(t),(0,f.createValidationError)(t)}if(I.patternInfo={needle:n,regex:R.toString(),caseSensitive:q,fileExtension:T,normalizedExtension:x},!_)try{const e=Date.now(),t=await g.default.readdir(C,{withFileTypes:!0}),r=[],n=[]
|
|
679
679
|
for(const e of t)e.isDirectory()?r.push(e.name):e.isFile()&&n.push(e.name)
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
l.info(`Searching for "${n}" in ${M} ${C} (mode: ${P})`,{needle:n,searchTarget:M,path:C,options:{maxResults:E,caseSensitive:q,fileExtension:x,searchIn:P}}),
|
|
680
|
+
I.initialScan={totalEntries:t.length,directories:r,files:n,firstFewFiles:n.slice(0,10),scanTime:Date.now()-e},I.phases.directoryListingTime=I.initialScan.scanTime}catch(e){const t="Failed to scan directory contents: "+(0,k.getErrorMessage)(e)
|
|
681
|
+
I.errors.push(t),l.error(t)}const M=_?"file":"directory"
|
|
682
|
+
l.info(`Searching for "${n}" in ${M} ${C} (mode: ${P})`,{needle:n,searchTarget:M,path:C,options:{maxResults:E,caseSensitive:q,fileExtension:x,searchIn:P}}),b=Date.now(),I.phases.initializationTime=b-u
|
|
683
683
|
const O=Date.now()
|
|
684
684
|
let D=[],$=0,A=0
|
|
685
685
|
try{const e=await async function(e,t,n,o,s,i){const{maxResults:a,fileExtension:c,searchIn:l,isFile:d,contextLines:u}=n,p=[]
|
|
@@ -697,15 +697,15 @@ o.errors.push(r),n.error(r)}return{matches:i,totalFiles:1}}(e,t,l,s,i,u)
|
|
|
697
697
|
const f={path:e,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
|
|
698
698
|
try{const{filesCount:n,fileMatchesCount:c,subdirCount:d,subdirStats:h}=await r(e,t,p,a,o,s,0,f,l,u)
|
|
699
699
|
return f.filesProcessed=n,f.filesMatched=c,f.subdirectories=d,i.directoryStats.push(f),h&&h.length>0&&i.directoryStats.push(...h),s.info("performLocalSearch completed",{totalFiles:n,matchesFound:p.length,directories:d+1}),{matches:p,totalFiles:n}}catch(t){const r="Error in performLocalSearch: "+(0,k.getErrorMessage)(t)
|
|
700
|
-
return f.errors.push(r),i.directoryStats.push(f),i.errors.push(r),s.error(r,{error:t instanceof Error?t.stack:t+"",searchPath:e}),{matches:p,totalFiles:f.filesProcessed}}}(C,R,{maxResults:E,fileExtension:x,searchIn:P,isFile:_,contextLines:j},x,l,
|
|
700
|
+
return f.errors.push(r),i.directoryStats.push(f),i.errors.push(r),s.error(r,{error:t instanceof Error?t.stack:t+"",searchPath:e}),{matches:p,totalFiles:f.filesProcessed}}}(C,R,{maxResults:E,fileExtension:x,searchIn:P,isFile:_,contextLines:j},x,l,I)
|
|
701
701
|
D=e.matches,$=e.totalFiles
|
|
702
702
|
const t=1e3
|
|
703
703
|
D.length>0&&D.length<=t?(D.sort(((e,t)=>void 0!==e.modifiedTime&&void 0!==t.modifiedTime?t.modifiedTime-e.modifiedTime:void 0!==e.modifiedTime&&void 0===t.modifiedTime?-1:void 0===e.modifiedTime&&void 0!==t.modifiedTime?1:0)),l.info(`Sorted ${D.length} matches by modification time (newest first)`)):D.length>t&&l.info(`Skipped sorting ${D.length} matches (exceeds hard cap of ${t} for performance)`),A=D.length,D.length>E&&(D=D.slice(0,E),l.info(`Limited results to ${E} (from ${A} total matches)`)),D.forEach((e=>{e.relativePath=function(e,t){const r=h.default.relative(e,t)
|
|
704
|
-
return r?r===h.default.basename(t)?r:r.startsWith("./")?r.substring(2):r:h.default.basename(t)}(C,e.file)})),l.info(`Local search completed: found ${A||D.length} total matches in ${$} files, returning ${D.length} results`),
|
|
705
|
-
|
|
704
|
+
return r?r===h.default.basename(t)?r:r.startsWith("./")?r.substring(2):r:h.default.basename(t)}(C,e.file)})),l.info(`Local search completed: found ${A||D.length} total matches in ${$} files, returning ${D.length} results`),I.phases.searchTime=Date.now()-O}catch(e){const t="Error during search: "+(0,k.getErrorMessage)(e)
|
|
705
|
+
I.errors.push(t),l.error(t),I.phases.searchTime=Date.now()-O}I.totalFiles=$,I.totalMatches=D.length,I.endTime=Date.now()
|
|
706
706
|
let F,N=""
|
|
707
707
|
try{if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
708
|
-
e.branchName&&!e.permanentBranch&&(N=e.isMainBranch?` (searched on main branch: ${e.branchName})`:` (searched on request branch: ${e.branchName}${e.requestId?" for "+e.requestId:""})`)}}catch(e){l.debug("Could not get branch context",{error:e}),N=" (branch context unavailable)"}l.debug("Search diagnostic information",{diagnostic:
|
|
708
|
+
e.branchName&&!e.permanentBranch&&(N=e.isMainBranch?` (searched on main branch: ${e.branchName})`:` (searched on request branch: ${e.branchName}${e.requestId?" for "+e.requestId:""})`)}}catch(e){l.debug("Could not get branch context",{error:e}),N=" (branch context unavailable)"}l.debug("Search diagnostic information",{diagnostic:I})
|
|
709
709
|
const L="content"===P?"content":"filename"===P?"filenames":"content and filenames"
|
|
710
710
|
if(A>D.length?(F=`Found ${A} results for "${n}" (searching ${L})`,p&&(F+=" in "+p),T&&(F+=" with extension "+T),F+=`${N}. Showing first ${D.length}:\n\n`):(F=`Found ${D.length} results for "${n}" (searching ${L})`,p&&(F+=" in "+p),T&&(F+=" with extension "+T),F+=N+":\n\n"),D.length>0)if(j>0){const{filenameMatches:e,mergedGroups:t}=function(e,t){const r=e.filter((e=>"filename"===e.matchType)),n=e.filter((e=>"content"===e.matchType))
|
|
711
711
|
if(0===n.length)return{filenameMatches:r,mergedGroups:[]}
|
|
@@ -728,10 +728,10 @@ void 0!==s&&(a+=` (${s} lines)`),a+=` - ${o} ${1===o?"match":"matches"}:`
|
|
|
728
728
|
const c=t.map((e=>` :${e.line} - ${e.text}`))
|
|
729
729
|
n.push(a+"\n"+c.join("\n"))}return n.join("\n\n")}(D)
|
|
730
730
|
else F+="No matches found."
|
|
731
|
-
return d({success:!0}),{content:[{type:"text",text:F}]}}catch(t){l.error("Search failed",{args:e,error:t instanceof Error?t.stack:t+""}),
|
|
731
|
+
return d({success:!0}),{content:[{type:"text",text:F}]}}catch(t){l.error("Search failed",{args:e,error:t instanceof Error?t.stack:t+""}),I.errors.push((0,k.getErrorMessage)(t)),I.endTime=Date.now(),l.debug("Search diagnostic information on error",{diagnostic:I})
|
|
732
732
|
let r="Search failed: "+(0,k.getErrorMessage)(t)
|
|
733
733
|
return d({success:!1,error:t instanceof Error?t.name:"unknown"}),{content:[{type:"text",text:r}],isError:!0}}}
|
|
734
|
-
const h=u(t(6928)),g=u(t(1943)),p=u(t(857)),f=t(9860),m=d(t(5967)),y=t(5967),w=t(2537),k=t(8824),
|
|
734
|
+
const h=u(t(6928)),g=u(t(1943)),p=u(t(857)),f=t(9860),m=d(t(5967)),y=t(5967),w=t(2537),k=t(8824),b=["node_modules"],I=1e4,v=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore"]),C=1048576},1318(e,exports,t){"use strict"
|
|
735
735
|
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)
|
|
736
736
|
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}`])
|
|
737
737
|
if(!a||""===a.trim())return null
|
|
@@ -796,54 +796,62 @@ t.success?this.logger.info("Successfully cleaned up worktree after non-conflict
|
|
|
796
796
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
797
797
|
const r=t(6183),n=t(5626)
|
|
798
798
|
exports.def={name:"document_operations",description:"Manage tracked documents linked to requests.\n\nOperations:\n\u2022 create - Create new document with content\n\u2022 search - Find documents by content or metadata\n\u2022 create-snapshot - Create a version snapshot with optional label and summary\n\u2022 get-history - View version snapshots and change history\n\u2022 get-version - Retrieve a specific version's content\n\u2022 restore-version - Restore document to a previous version\n\nDocuments support markdown with syntax highlighting, Mermaid diagrams, GFM tables, and entity links ([RECORD:trec######], [DOC:doc######], [REQUEST:req######], [TASK:tas######]). Use JOURNAL-{requestId}.md naming for explanation documents.",schema:r.DocumentOperationsSchema,annotations:{title:"Document Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleDocumentOperations)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},1472(e,exports,t){"use strict"
|
|
799
|
-
function r(e){if("string"==typeof e)try{return r(JSON.parse(e))}catch{return e}return Array.isArray(e)?e.map((e=>r(e))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e}
|
|
799
|
+
function r(e){if("string"==typeof e)try{return r(JSON.parse(e))}catch{return e}return Array.isArray(e)?e.map((e=>r(e))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e}function n(e,t){const r=e.path.length?e.path.join("."):"<root>",n=function(e,t){let r=e
|
|
800
|
+
for(const e of t){if(null==r)return
|
|
801
|
+
r=r[e]}return r}(t,e.path)
|
|
802
|
+
if("too_big"===e.code&&"string"===e.type&&"string"==typeof n){const t=+e.maximum,o=n.length
|
|
803
|
+
return`${r}: string too long \u2014 received ${o} chars, max ${t} (trim ${o-t})`}if("too_small"===e.code&&"string"===e.type&&"string"==typeof n){const t=+e.minimum
|
|
804
|
+
return`${r}: string too short \u2014 received ${n.length} chars, min ${t}`}if("too_big"===e.code&&"array"===e.type&&Array.isArray(n)){const t=+e.maximum
|
|
805
|
+
return`${r}: array too long \u2014 received ${n.length} items, max ${t}`}if("too_small"===e.code&&"array"===e.type&&Array.isArray(n)){const t=+e.minimum
|
|
806
|
+
return`${r}: array too short \u2014 received ${n.length} items, min ${t}`}return"too_big"===e.code&&"number"===e.type&&"number"==typeof n?`${r}: number too large \u2014 received ${n}, max ${+e.maximum}`:"too_small"===e.code&&"number"===e.type&&"number"==typeof n?`${r}: number too small \u2014 received ${n}, min ${+e.minimum}`:`${r}: ${e.message}`}var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
800
807
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
801
|
-
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]}),
|
|
808
|
+
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=[]
|
|
802
809
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
803
|
-
return t},
|
|
810
|
+
return t},o(e)},function(e){if(e&&e.__esModule)return e
|
|
804
811
|
var t={}
|
|
805
|
-
if(null!=e)for(var r=
|
|
806
|
-
return
|
|
807
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=void 0,exports.registerTools=function(e,
|
|
808
|
-
|
|
809
|
-
const
|
|
810
|
-
try{return await
|
|
811
|
-
|
|
812
|
+
if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
813
|
+
return i(t,e),t})
|
|
814
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=void 0,exports.registerTools=function(e,o,s,i,a,p,w){const k=i.child({component:"tools"})
|
|
815
|
+
k.info("Registering tools...")
|
|
816
|
+
const b=!!p,I=async()=>{if(!b)return!0
|
|
817
|
+
try{return await p.hasValidToken()}catch(e){return k.error("Error checking authentication status",{error:(0,d.getErrorMessage)(e)}),!1}},v=async()=>{const e=(0,l.areTestsRequiredForCompletion)(),t=await I()
|
|
818
|
+
k.info(`Generating tools list with testsRequired=${e}, authenticated=${t}`)
|
|
812
819
|
const r={testsRequired:e,authenticated:t}
|
|
813
|
-
return(0,
|
|
814
|
-
let
|
|
815
|
-
|
|
816
|
-
let
|
|
817
|
-
e.setRequestHandler(
|
|
818
|
-
const
|
|
820
|
+
return(0,m.generateVisibleToolsList)(r)}
|
|
821
|
+
let C=v(),_=[]
|
|
822
|
+
C.then((e=>{_=e})).catch((e=>{k.error("Error generating initial tools list",{error:(0,d.getErrorMessage)(e)}),_=[]})),e.setRequestHandler(c.ListToolsRequestSchema,(async()=>{try{return _=await v(),{tools:_}}catch(e){return k.error("Error generating tools list",{error:(0,d.getErrorMessage)(e)}),{tools:[]}}}))
|
|
823
|
+
let E=!1
|
|
824
|
+
e.setRequestHandler(c.CallToolRequestSchema,(async e=>{let c
|
|
825
|
+
try{const{name:n,arguments:l={},_meta:p}=e.params;(0,f.logSessionIdentity)(n,"_meta-debug",{has_meta:!!p,sessionId:p?.sessionId||null,messageId:p?.messageId||null,paramKeys:Object.keys(e.params)}),k.info("Tool call received: "+n,{tool:n}),a.incrementCounter("tool_calls_total",1,{tool:n})
|
|
826
|
+
const y=a.startTimer("tool_execution_time")
|
|
819
827
|
Date.now()
|
|
820
|
-
let
|
|
821
|
-
const
|
|
822
|
-
if(Date.now()
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
if(
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
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
|
|
828
|
+
let v=Date.now()
|
|
829
|
+
if(c=r(l),Date.now(),v=Date.now(),b){const e=await I()
|
|
830
|
+
if(Date.now(),!e)return k.warn("Unauthenticated tool call attempt",{tool:n}),{content:[{type:"text",text:"Authentication required. Please run 'alchemylab setup' to authenticate and configure your project."}],isError:!0}}const C=(0,m.getToolByName)(n)
|
|
831
|
+
let _
|
|
832
|
+
if(v=Date.now(),s?(s.setOptions({createRecords:C?.createsRecords??!1}),k.info(`Setting record creation for tool ${n}: ${C?.createsRecords??!1}`)):k.debug(`No API client available for tool ${n} (minimal mode)`),Date.now(),Date.now(),v=Date.now(),p?.sessionId){const e=p.sessionId,t=p.messageId,r=h.sessionIdentity.getIdentity()
|
|
833
|
+
if(r)r.sessionId!==e&&((0,f.logSessionIdentity)(n,"_meta-session-switch",{prevSessionId:r.sessionId,prevAgentType:r.agentType,newSessionId:e}),h.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:r.serverUrl}),o?.workspaceManager?.resetCurrentContext?.(e))
|
|
834
|
+
else{const t=await(0,u.getServerUrl)(o,k)
|
|
835
|
+
h.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:t||""})}_={providerId:"opencode",sessionId:e,messageId:t,createdAt:(new Date).toISOString()},(0,f.logSessionIdentity)(n,"_meta",{sessionId:e,messageId:t})}else k.warn("No _meta.sessionId on tool call \u2014 session identity unavailable",{tool:n})
|
|
836
|
+
h.sessionIdentity.setCurrentCallOrigin(_)
|
|
837
|
+
const q=_?.sessionId||p?.sessionId
|
|
838
|
+
if(o?.workspaceManager){v=Date.now()
|
|
839
|
+
try{const e=await(0,u.getServerUrl)(o,k)
|
|
840
|
+
e&&s&&await o.workspaceManager.ensureReadonlyBranchIfNeeded(e,n,s,q)}catch(e){k.debug("Error during workspace check",{error:(0,d.getErrorMessage)(e)})}Date.now()}if(!E&&s){const e=h.sessionIdentity.getIdentity(),t=process.env.ALCHEMY_INITIAL_BRANCH
|
|
834
841
|
if(e?.sessionId&&t){const r=t.match(/^requests\/(.+)$/),n="1"===process.env.ALCHEMY_ALLOW_PARALLEL
|
|
835
842
|
if(r&&!n){const t=r[1]
|
|
836
|
-
|
|
837
|
-
try{const{sessionTag:r}=(0,
|
|
838
|
-
await Promise.all([i,a])}catch(e){
|
|
843
|
+
E=!0
|
|
844
|
+
try{const{sessionTag:r}=(0,g.getGlobalClientInfo)(),n=s.getSessionTagMappingClient(),o=s.getRequestClient(),i=n?n.getMappingByOpencodeSessionId(e.sessionId).then((t=>{t?((0,g.setSessionTag)(t.sessionTag),k.info("Recovered session tag from mapping",{opencodeSessionId:e.sessionId,sessionTag:t.sessionTag})):(n.createOrUpdateMapping(r,e.sessionId).catch((()=>{})),k.info("Registered session tag mapping",{opencodeSessionId:e.sessionId,sessionTag:r}))}),(e=>k.debug("Mapping lookup failed",{error:(0,d.getErrorMessage)(e)}))):Promise.resolve(),a=o.lockRequest?o.lockRequest(t,r).then((e=>{e.locked?k.info("Acquired request lock",{requestId:t,sessionTag:r}):k.warn("Failed to acquire request lock",{requestId:t,sessionTag:r})}),(e=>k.warn("Lock acquisition failed",{error:(0,d.getErrorMessage)(e)}))):Promise.resolve()
|
|
845
|
+
await Promise.all([i,a])}catch(e){k.warn("Error in session tag mapping / lock acquisition",{error:(0,d.getErrorMessage)(e)})}}}}o&&(o.currentSessionId=q||"__unknown__")
|
|
839
846
|
const S=`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,T=e=>{const{getActionServerBaseUrl:r}=t(9414)
|
|
840
847
|
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((()=>{}))}
|
|
841
848
|
let P
|
|
842
849
|
T("start")
|
|
843
|
-
try{if(
|
|
844
|
-
P=await
|
|
850
|
+
try{if(C){const e={context:o,apiClient:s,logger:i,metrics:a,mcpServer:w,cliOrigin:_}
|
|
851
|
+
P=await C.handler(c,e)}else k.info(`Tool ${n} not found, returning negative response`),P={content:[{type:"text",text:`The tool '${n}' does not exist.`}]}}finally{T("end")}return Date.now(),Date.now(),y({tool:n,success:!0}),P}catch(t){k.error("Error executing tool:",{error:t instanceof Error?t.stack:t+"",tool:e.params.name}),a.incrementCounter("tool_errors_total",1,{tool:e.params.name,error:t instanceof Error?t.name:"unknown"})
|
|
845
852
|
let r="Unknown error"
|
|
846
|
-
if(t instanceof
|
|
853
|
+
if(t instanceof y.ZodError)r=function(e,t){return 1===e.issues.length?n(e.issues[0],t):e.issues.map((e=>n(e,t))).join("; ")}(t,c)
|
|
854
|
+
else if(t instanceof Error)r=t.message
|
|
847
855
|
else if("string"==typeof t)r=t
|
|
848
856
|
else if(t&&"object"==typeof t){const e=t
|
|
849
857
|
if(e.message)r=e.message
|
|
@@ -854,15 +862,14 @@ else if(e.body&&"string"==typeof e.body)try{const t=JSON.parse(e.body)
|
|
|
854
862
|
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))
|
|
855
863
|
if(t.length>0){const n=t[0]
|
|
856
864
|
r=`${n}: ${e[n]}`}else r="Unknown error (no readable properties)"}}else r=t+""
|
|
857
|
-
return{content:[{type:"text",text:"Error: "+r}],isError:!0}}})),
|
|
858
|
-
const
|
|
859
|
-
|
|
860
|
-
var
|
|
861
|
-
Object.defineProperty(exports,"logSessionIdentity",{enumerable:!0,get(){return
|
|
862
|
-
const
|
|
865
|
+
return{content:[{type:"text",text:"Error: "+r}],isError:!0}}})),k.info("Tools registration complete")}
|
|
866
|
+
const c=t(9150),l=t(2478),d=t(8824),u=t(7617),h=t(6688),g=t(5172)
|
|
867
|
+
a(t(9896)),a(t(6928))
|
|
868
|
+
var p=t(7280)
|
|
869
|
+
Object.defineProperty(exports,"logSessionIdentity",{enumerable:!0,get(){return p.logSessionIdentity}})
|
|
870
|
+
const f=t(7280)
|
|
863
871
|
t(2462)
|
|
864
|
-
const
|
|
865
|
-
i(t(857))},1483(e,exports,t){"use strict"
|
|
872
|
+
const m=t(2245),y=(a(t(857)),t(1569))},1483(e,exports,t){"use strict"
|
|
866
873
|
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")
|
|
867
874
|
try{let i
|
|
868
875
|
try{i=r.SearchDocumentsSchema.parse(e)}catch(t){if(t instanceof n.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
@@ -956,7 +963,7 @@ e&&t.projectId&&await e.createToolRecord({requestId:s,projectId:t.projectId,type
|
|
|
956
963
|
const r=t(9860),n=t(8824)},1540(e,exports,t){"use strict"
|
|
957
964
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
958
965
|
const r=t(6183),n=t(1725),o=t(8955)
|
|
959
|
-
exports.def={name:"subagent_operations",description:"
|
|
966
|
+
exports.def={name:"subagent_operations",description:"WHEN TO USE spawn (agent: coder): any change touching 2+ files, feature work, bug fixes, or anything needing acceptance-criteria verification.\n\nManage background subagents that work independently.\n\nOperations:\n\u2022 spawn - Create a new detached subagent to work in the background. Include a short 'description' for display in the UI.\n\u2022 continue - Send new instructions/feedback to an existing subagent session\n\u2022 check-status - Check if a subagent is idle or busy\n\u2022 abort - Stop a running subagent\n\u2022 read-messages - Fetch the latest messages from a subagent session\n\nThe spawned subagent runs as a separate OpenCode process.\n\nAvailable agents: "+(0,o.formatAgentsForDescription)(),schema:r.SubagentOperationsSchema,annotations:{title:"Subagent Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSubagentOperations)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},1569(module){"use strict"
|
|
960
967
|
module.exports=require("zod")},1572(e,exports,t){"use strict"
|
|
961
968
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDocument=async function(e,t,s,i,a,c,l){const d=i.child({tool:"create_document"}),u=a.startTimer("tool_execution_time")
|
|
962
969
|
try{let i
|
|
@@ -1192,12 +1199,12 @@ exports.def={name:"complete_task",description:"Mark a task as completed with a s
|
|
|
1192
1199
|
function r(e,t,r){try{const n=`[${(new Date).toISOString()}] ${t}${r?" "+JSON.stringify(r):""}\n`,o=(0,q.join)(e.basePath||process.cwd(),".alchemy_lab","spawn-debug.log");(0,E.appendFileSync)(o,n)}catch{}}async function n(e,t,n,o,s){const{agent:i="work",prompt:a,requestId:c,allowParallel:l=!1,useExistingSession:d}=e
|
|
1193
1200
|
if(r(t,"handleSpawn called",{agent:i,promptLength:a.length,requestId:c,useExistingSession:d,cliOriginSessionId:s?.sessionId||null}),!(0,S.isValidAgent)(i))return{content:[{type:"text",text:`\u274c Unknown agent '${i}'.\n\n**Available agents:** ${(0,S.getAgentNames)().join(", ")}\n\nChoose one of the available agents listed above to see detailed descriptions of each agent.`}],isError:!0}
|
|
1194
1201
|
try{const e=s?.sessionId
|
|
1195
|
-
let n=
|
|
1202
|
+
let n=b.sessionIdentity.getIdentity()?.agentType
|
|
1196
1203
|
if(r(t,"Spawn agent type check",{callerSessionId:e||null,cachedAgentType:n||null,pid:process.pid}),!n&&e)try{const o=`http://localhost:${T}/api/sessions/${encodeURIComponent(e)}/agent-type`
|
|
1197
1204
|
r(t,"Looking up agent type from action server",{sessionId:e,url:o})
|
|
1198
1205
|
const s=await fetch(o)
|
|
1199
1206
|
if(s.ok){const o=await s.json()
|
|
1200
|
-
r(t,"Agent type response from action server",{sessionId:e,agentType:o.agentType||null,source:o.source||null,success:o.success}),o.success&&o.agentType&&(n=o.agentType,
|
|
1207
|
+
r(t,"Agent type response from action server",{sessionId:e,agentType:o.agentType||null,source:o.source||null,success:o.success}),o.success&&o.agentType&&(n=o.agentType,b.sessionIdentity.updateIdentity({agentType:n}))}else r(t,"Agent type lookup failed",{sessionId:e,status:s.status})}catch(n){r(t,"Agent type lookup error",{sessionId:e,error:(0,_.getErrorMessage)(n)})}if(n){const e=(0,S.getAllowedSubagents)(n)
|
|
1201
1208
|
if(e&&!e.includes(i))return{content:[{type:"text",text:`\u274c Agent type '${n}' cannot spawn '${i}'.\n\n**Allowed subagents for ${n}:** ${e.join(", ")}\n\nUse one of the allowed agent types instead.`}],isError:!0}}}catch(e){r(t,"allowedSubagents check failed",{error:(0,_.getErrorMessage)(e)})}let u
|
|
1202
1209
|
try{const e=await async function(e){try{const t=`http://localhost:${T}/api/agents/by-name/${encodeURIComponent(e)}`,r=await fetch(t)
|
|
1203
1210
|
if(!r.ok)return null
|
|
@@ -1226,8 +1233,8 @@ if(r.data?.defaultModel){const[t,...n]=r.data.defaultModel.split("/")
|
|
|
1226
1233
|
e={providerID:t,modelID:n.join("/")}}}}catch{}const t=`${h.replace(/\/$/,"")}/session/${v}/prompt_async`,r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:[{type:"text",text:C}],...i?{agent:i}:{},...e?{model:e}:{}}),signal:AbortSignal.timeout(1e4)})
|
|
1227
1234
|
if(!r.ok){const e=await r.text().catch((()=>"Unknown error"))
|
|
1228
1235
|
throw Error(`Failed to send to existing session: ${r.status} ${e}`)}n.info("Prompt sent to existing session",{sessionId:v,agent:i})}catch(e){throw Error("Failed to use existing session: "+(0,_.getErrorMessage)(e))}}else{E=!0,r(t,"Creating session via spawn-session endpoint")
|
|
1229
|
-
const o=p;(0,
|
|
1230
|
-
try{const s=`http://localhost:${T}/api/spawn-session`,d=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:i,prompt:a,requestId:c,parentSessionId:o,title:e.title,specialization:e.specialization,allowParallel:l,callerAgentType:
|
|
1236
|
+
const o=p;(0,I.logSessionIdentity)("subagent_operations.spawn","_meta",{parentSessionId:o})
|
|
1237
|
+
try{const s=`http://localhost:${T}/api/spawn-session`,d=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agent:i,prompt:a,requestId:c,parentSessionId:o,title:e.title,specialization:e.specialization,allowParallel:l,callerAgentType:b.sessionIdentity.getIdentity()?.agentType}),signal:AbortSignal.timeout(15e3)})
|
|
1231
1238
|
if(!d.ok){const e=await d.text().catch((()=>"Unknown error"))
|
|
1232
1239
|
throw Error(`Spawn session endpoint failed: ${d.status} ${e}`)}const u=await d.json()
|
|
1233
1240
|
if(!u.success||!u.data)throw Error(u.error||"Spawn session returned unsuccessful")
|
|
@@ -1274,7 +1281,7 @@ let f={input:0,output:0,reasoning:0},m="",y=c(null,h.time.updated)
|
|
|
1274
1281
|
if(p.ok){const e=await p.json()
|
|
1275
1282
|
for(const t of e)"assistant"===t.info.role&&t.info.tokens&&(f.input+=t.info.tokens.input||0,f.output+=t.info.tokens.output||0,f.reasoning+=t.info.tokens.reasoning||0)
|
|
1276
1283
|
const t=i(e)
|
|
1277
|
-
y=c(t.lastActivityTime,h.time.updated),t.current&&(m+="\nCurrent: "+t.current),t.recent.length>0&&(m+="\nRecent: "+t.recent.join(", "))}const w=Date.now()-h.time.created,k=y.status,
|
|
1284
|
+
y=c(t.lastActivityTime,h.time.updated),t.current&&(m+="\nCurrent: "+t.current),t.recent.length>0&&(m+="\nRecent: "+t.recent.join(", "))}const w=Date.now()-h.time.created,k=y.status,b=y.isReady,I=f.input+f.output+f.reasoning
|
|
1278
1285
|
let v="",C="",_=null
|
|
1279
1286
|
if(o)try{const t=o.getSessionRequestAssociationClient()
|
|
1280
1287
|
if(t){const r=await t.getActiveRequestsForSession(e,!1)
|
|
@@ -1289,7 +1296,7 @@ if(e.trim())return l(e)}try{const t=n(`git log main --merges --oneline -n 50 --g
|
|
|
1289
1296
|
if(t){const e=t.split("\n")[0].split(" ")[0],o=n(`git diff ${e}^1...${e} --numstat`,{cwd:r,encoding:"utf8"})
|
|
1290
1297
|
if(o.trim())return{...l(o),merged:!0}}}catch{}return null}catch{return null}}(_,r.basePath)
|
|
1291
1298
|
if(e){const t=e.additions+e.deletions,r=e.merged?" (merged)":""
|
|
1292
|
-
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: ${
|
|
1299
|
+
v=`\nDiff vs main (${_}): +${e.additions}/-${e.deletions} lines (${t} total) in ${e.files} file${1!==e.files?"s":""}${r}`}}return{content:[{type:"text",text:`Session ${e}\nTitle: ${h.title||"Untitled"}\nStatus: ${k} (${y.detail})\nReady for input: ${b?"Yes":"No"}\nAge: ${s(w)}\nTokens: ${I.toLocaleString()} (in: ${f.input.toLocaleString()}, out: ${f.output.toLocaleString()}${f.reasoning>0?", reasoning: "+f.reasoning.toLocaleString():""})${m}${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)
|
|
1293
1300
|
if(!n)throw new y.ValidationError("Could not determine OpenCode server URL")
|
|
1294
1301
|
r.info("Aborting subagent session",{sessionId:e})
|
|
1295
1302
|
try{const t=`${n.replace(/\/$/,"")}/session/${e}/abort`,o=await fetch(t,{method:"POST"})
|
|
@@ -1307,14 +1314,14 @@ const m=g.replace(/\/$/,"")+"/session/status",y=await fetch(m),w=y.ok?await y.js
|
|
|
1307
1314
|
let k=p
|
|
1308
1315
|
if(o&&(k=k.filter((e=>"idle"!==(w[e.id]?.type||"idle")))),void 0!==h){const e=36e5*h,t=Date.now()-e
|
|
1309
1316
|
k=k.filter((e=>e.time.created>=t))}if(0===k.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
|
|
1310
|
-
let
|
|
1311
|
-
const
|
|
1317
|
+
let b={}
|
|
1318
|
+
const I=k.map((e=>e.id))
|
|
1312
1319
|
let v={},C=[]
|
|
1313
|
-
if("specialist"===n.agentType){const e=new Set(
|
|
1320
|
+
if("specialist"===n.agentType){const e=new Set(I)
|
|
1314
1321
|
for(const t of f){const r=t.parentId||t.parentID
|
|
1315
1322
|
r&&e.has(r)&&(v[r]||(v[r]=[]),v[r].push(t.id),C.push(t.id))}}if(r)try{const e=r.getCLISessionClient()
|
|
1316
|
-
if(e){const t=[...
|
|
1317
|
-
|
|
1323
|
+
if(e){const t=[...I,...C]
|
|
1324
|
+
b=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=[]
|
|
1318
1325
|
for(let e=0;e<k.length;e++){const t=k[e],r=Date.now()-t.time.created
|
|
1319
1326
|
let o=0,s=null,l=[],h=c(null,t.time.updated)
|
|
1320
1327
|
const g=E[e],p="fulfilled"===g.status?g.value:[]
|
|
@@ -1323,24 +1330,24 @@ if(p.length>0){const e=i(p)
|
|
|
1323
1330
|
h=c(e.lastActivityTime,t.time.updated),s=e.current||null,l=e.recent}const f=h.status
|
|
1324
1331
|
if(void 0!==d&&d>o)continue
|
|
1325
1332
|
if(void 0!==u&&o>u)continue
|
|
1326
|
-
const m=
|
|
1333
|
+
const m=b[t.id]
|
|
1327
1334
|
if(n.agentType&&(!m||m.agentType!==n.agentType))continue
|
|
1328
1335
|
if("archived"===m?.status)continue
|
|
1329
1336
|
let y=""
|
|
1330
|
-
const
|
|
1337
|
+
const I=[],C=[]
|
|
1331
1338
|
m?.associations&&C.push(...m.associations)
|
|
1332
1339
|
const _=v[t.id]
|
|
1333
|
-
if(_)for(const e of _){const t=
|
|
1340
|
+
if(_)for(const e of _){const t=b[e]
|
|
1334
1341
|
if(t?.associations){const r=w[e]?.type||"idle",n="idle"===r||"stalled"===r
|
|
1335
1342
|
for(const e of t.associations)n&&!e.endedAt?C.push({...e,endedAt:"idle"}):C.push(e)}}if(C.length>0){const e=new Map
|
|
1336
1343
|
for(const t of C){const r=e.get(t.requestLocalId)
|
|
1337
1344
|
void 0!==r&&(r||t.endedAt)||e.set(t.requestLocalId,!t.endedAt)}const t=[...e.entries()].filter((([,e])=>e)).map((([e])=>e)),r=[...e.entries()].filter((([,e])=>!e)).map((([e])=>e))
|
|
1338
|
-
|
|
1345
|
+
I.push(...t,...r)
|
|
1339
1346
|
const n=[]
|
|
1340
1347
|
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
|
|
1341
|
-
n.push(`prev: ${t.join(", ")}${o>0?` +${o} more`:""}`)}n.length>0&&(y=` [${n.join(" | ")}]`)}if(a&&!
|
|
1348
|
+
n.push(`prev: ${t.join(", ")}${o>0?` +${o} more`:""}`)}n.length>0&&(y=` [${n.join(" | ")}]`)}if(a&&!I.includes(a))continue
|
|
1342
1349
|
const S=t.title||"Untitled",T=S.length>50?S.slice(0,47)+"...":S
|
|
1343
|
-
q.push({id:t.id,title:T,status:f,age:r,totalTokens:o,requestsInfo:y,allRequestIds:
|
|
1350
|
+
q.push({id:t.id,title:T,status:f,age:r,totalTokens:o,requestsInfo:y,allRequestIds:I,statusDetail:h.detail,specialization:m?.specialization??null,currentAction:s,recentActions:l})}if(0===q.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
|
|
1344
1351
|
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(", "):""
|
|
1345
1352
|
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})`:""
|
|
1346
1353
|
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)
|
|
@@ -1383,7 +1390,7 @@ case"list-sessions":const s={activeOnly:r.activeOnly,requestId:r.requestId,limit
|
|
|
1383
1390
|
f=await h(t,c,i,s)
|
|
1384
1391
|
break
|
|
1385
1392
|
default:throw new y.ValidationError("Unknown operation: "+p)}return l({success:!0}),s.incrementCounter(`subagent_operations_${p}_success`,1),f}catch(e){return c.error("Subagent operations failed",{error:e instanceof Error?e.stack:e+""}),l({success:!1}),s.incrementCounter("subagent_operations_errors",1),{content:[{type:"text",text:"Subagent operation failed: "+(0,_.getErrorMessage)(e)}],isError:!0}}}
|
|
1386
|
-
const y=t(9860),w=t(8035),k=t(7617),
|
|
1393
|
+
const y=t(9860),w=t(8035),k=t(7617),b=t(6688),I=t(7280),v=t(6183),C=m(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"
|
|
1387
1394
|
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}}
|
|
1388
1395
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectContext=void 0,exports.projectContextMiddleware=r
|
|
1389
1396
|
const o=n(t(9896)),s=n(t(6928)),i=t(4139),a=t(4055),c=t(8824)
|
|
@@ -1710,7 +1717,7 @@ var t={}
|
|
|
1710
1717
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
1711
1718
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1712
1719
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,r,n,o,s,i,f,m){const y=i.child({tool:"move_files"}),w=Date.now()
|
|
1713
|
-
let k,I
|
|
1720
|
+
let k,b,I=d.FileOperationPhase.VALIDATION
|
|
1714
1721
|
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"}
|
|
1715
1722
|
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"
|
|
1716
1723
|
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")
|
|
@@ -1719,7 +1726,7 @@ const q=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null
|
|
|
1719
1726
|
y.info("Initial branch context",{initialBranch:q.branch,initialRequestId:q.requestId,isMain:q.isMain})
|
|
1720
1727
|
const S=[]
|
|
1721
1728
|
for(const e of h){const{normalizedPath:t,fullPath:n}=d.validateAndNormalizePath(e.source,r),{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(e.destination,r)
|
|
1722
|
-
S.push({source:t,destination:o,fullSource:n,fullDestination:s})}
|
|
1729
|
+
S.push({source:t,destination:o,fullSource:n,fullDestination:s})}I=d.FileOperationPhase.TASK_VALIDATION,f.incrementCounter("move_files_phase",1,{phase:I})
|
|
1723
1730
|
const T=await d.validateTaskId(E,S[0].source,n,y,f,v.metricsPrefix),P=T?.requestId,j=await d.validateWorkItemStates(E,S[0].source,n,s,r,y,f,v.metricsPrefix),R=await d.autoPromoteTaskStatus(E,T.status,P,j.request?.status,S[0].source,n,s,y,f,v.metricsPrefix)
|
|
1724
1731
|
R.taskPromoted&&y.info(`Auto-promoted task ${E} (${T.title||"Untitled"}) to in_progress for file operations`,{taskId:E,taskTitle:T.title,previousStatus:T.status,newStatus:R.newTaskStatus,operationCount:h.length}),R.requestPromoted&&y.info(`Auto-promoted request ${P} to in_progress for file operations`,{requestId:P,previousStatus:j.request?.status,newStatus:R.newRequestStatus,triggeringTaskId:E})
|
|
1725
1732
|
const x=await d.ensureCorrectWorkspaceContext({taskPromoted:R.taskPromoted,requestId:P,context:r,operation:"move-files",logger:y,metrics:f,metricsPrefix:v.metricsPrefix})
|
|
@@ -1727,9 +1734,9 @@ if(!x.success){if(x.isLockConflict)return{content:[{type:"text",text:"\u274c "+x
|
|
|
1727
1734
|
throw Error(x.error)}let M={hadUserMods:!1,userModsCommitHash:void 0}
|
|
1728
1735
|
if(r.git)try{y.debug("[MOVE-FILES] Checking for user changes before move operations")
|
|
1729
1736
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"move-files",{requestId:P,taskId:E,workspaceManager:r.workspaceManager},y,f)
|
|
1730
|
-
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}),
|
|
1737
|
+
e.userChangesCommitted&&(y.debug("[MOVE-FILES] User changes committed before move operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before move-files operation",{taskId:E,moveOperationsCount:S.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),M={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){y.debug("[MOVE-FILES] Pre-tool commit failed, continuing with move operations",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with move operation",{taskId:E,moveOperationsCount:S.length,error:e instanceof Error?e.message:e+""})}y.debug("[MOVE-FILES] Proceeding with move operations",{operationCount:S.length}),I=d.FileOperationPhase.RECORD_CREATION,f.incrementCounter("move_files_phase",1,{phase:I})
|
|
1731
1738
|
const{toolRecordId:O,localToolRecordId:D}=await d.createFileOperationRecords(E,P,r.projectId,v.recordType,S[0].source,{operationCount:h.length,operations:S.map((e=>({source:e.source,destination:e.destination}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},n,o,y,f,v.metricsPrefix,m)
|
|
1732
|
-
k=O,
|
|
1739
|
+
k=O,b=O,I=v.fileOperationPhase,f.incrementCounter("move_files_phase",1,{phase:I})
|
|
1733
1740
|
const $=[]
|
|
1734
1741
|
let A=0
|
|
1735
1742
|
for(const e of S){const t={operation:{source:e.source,destination:e.destination},success:!1}
|
|
@@ -1739,11 +1746,11 @@ const n=c.default.dirname(e.fullDestination)
|
|
|
1739
1746
|
try{await a.default.mkdir(n,{recursive:!0})}catch(e){throw Error("Failed to create destination directory: "+n)}try{throw await a.default.access(e.fullDestination),Error("Destination already exists: "+e.destination)}catch(e){if(!(e instanceof Error&&e.message.includes("ENOENT")))throw e}await a.default.rename(e.fullSource,e.fullDestination),t.success=!0,A++,y.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,p.getErrorMessage)(r),y.warn(`Failed to move ${e.source} to ${e.destination}`,{error:t.error})}$.push(t)}const F=Date.now()-w
|
|
1740
1747
|
f.recordValue("move_files_time",F),f.incrementCounter("move_files_operations_total",h.length),f.incrementCounter("move_files_operations_success",A),f.incrementCounter("move_files_operations_failed",h.length-A),A===h.length?f.incrementCounter("move_files_success",1):A>0?f.incrementCounter("move_files_partial_success",1):f.incrementCounter("move_files_total_failure",1)
|
|
1741
1748
|
let N=null
|
|
1742
|
-
if(A>0){
|
|
1749
|
+
if(A>0){I=d.FileOperationPhase.GIT_COMMIT,f.incrementCounter("move_files_phase",1,{phase:I})
|
|
1743
1750
|
const e=$.filter((e=>e.success)),t=1===e.length?`Move ${e[0].isDirectory?"directory":"file"} from ${e[0].operation.source} to ${e[0].operation.destination} - ${C}`:`Move ${e.length} ${1===e.length?"item":"items"} - ${C}`
|
|
1744
|
-
N=await d.commitToGit(E,S[0].destination,O,D,t,r,y,f,v.metricsPrefix)}
|
|
1751
|
+
N=await d.commitToGit(E,S[0].destination,O,D,t,r,y,f,v.metricsPrefix)}I=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,f.incrementCounter("move_files_phase",1,{phase:I})
|
|
1745
1752
|
const L=$.filter((e=>e.success)),z=$.filter((e=>!e.success))
|
|
1746
|
-
await d.updateFileOperationRecords(E,k,
|
|
1753
|
+
await d.updateFileOperationRecords(E,k,b,S[0].source,v.recordType,A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,{status:A===h.length?"completed":"partial_success",commitHash:N?.commitHash,previousCommitHash:N?.previousCommitHash,operationCount:h.length,successCount:A,failureCount:h.length-A,successfulOperations:L.map((e=>({source:e.operation.source,destination:e.operation.destination,isDirectory:e.isDirectory}))),failedOperations:z.map((e=>({source:e.operation.source,destination:e.operation.destination,error:e.error}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,n,o,y,f,v.metricsPrefix)
|
|
1747
1754
|
const H=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
1748
1755
|
let B=""
|
|
1749
1756
|
if(A===h.length)B=`Successfully moved all ${h.length} ${1===h.length?"item":"items"}`
|
|
@@ -1751,16 +1758,16 @@ else if(A>0){const e=$.filter((e=>!e.success))
|
|
|
1751
1758
|
B=`Successfully moved ${A}/${h.length} items.\n\nFailed operations:\n`+e.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")}else B="All move operations failed:\n"+$.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")
|
|
1752
1759
|
if(N?.commitHash&&(B+="\nCommit: "+N.commitHash.substring(0,8)),H.requestId&&(B+="\nBranch: "+H.requestId),x.lockAcquired&&x.lockedRequestId){const e=r.workspaceManager?.getCurrentContext(r.currentSessionId)
|
|
1753
1760
|
e?.permanentBranch||(B+="\n\u{1f512} **Locked request:** "+x.lockedRequestId)}return{content:[{type:"text",text:B}],isError:0===A}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
|
|
1754
|
-
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:
|
|
1755
|
-
if(f.recordValue("move_files_time",s),f.incrementCounter("move_files_errors",1),y.error("Error in move-files operation:",{error:(0,p.getErrorMessage)(t),time:s}),(k||
|
|
1756
|
-
try{await d.updateFileOperationRecords(e.taskId,k,
|
|
1761
|
+
await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"move-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment,error:(0,p.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:I,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:"Failed to move files - "+(0,p.getErrorMessage)(t)})}catch(t){y.error("Failed to create failure record for move-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,operationCount:e.operations?.length||0})}const s=Date.now()-w
|
|
1762
|
+
if(f.recordValue("move_files_time",s),f.incrementCounter("move_files_errors",1),y.error("Error in move-files operation:",{error:(0,p.getErrorMessage)(t),time:s}),(k||b)&&e.taskId){I=d.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
1763
|
+
try{await d.updateFileOperationRecords(e.taskId,k,b,e.operations?.[0]?.source||"unknown",v.recordType,"Failed to move files",{status:"failed",error:(0,p.getErrorMessage)(t),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment},"Failed to move files",n,o,y,f,v.metricsPrefix)}catch(t){y.error("Failed to update record with failure status",{taskId:e.taskId,recordId:k,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(t,I,y,f,e,v)}}
|
|
1757
1764
|
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"
|
|
1758
1765
|
module.exports=require("@modelcontextprotocol/sdk/server/sse.js")},2425(e,exports,t){"use strict"
|
|
1759
1766
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
1760
1767
|
const r=t(6183),n=t(3707)
|
|
1761
|
-
exports.def={name:"quick_manage",description:"
|
|
1768
|
+
exports.def={name:"quick_manage",description:"WHEN TO USE: trivial single-file edits only. For multi-file or feature work, spawn a coder via subagent_operations.\n\nMove, 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"
|
|
1762
1769
|
Object.defineProperty(exports,"__esModule",{value:!0})
|
|
1763
|
-
const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),f=t(260),m=t(2283),y=t(4165),w=t(7834),k=t(9373),
|
|
1770
|
+
const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),f=t(260),m=t(2283),y=t(4165),w=t(7834),k=t(9373),b=t(6111),I=t(700),v=t(2783),C=t(2601),_=t(1722),E=t(7257),q=t(9230),S=t(6064),T=t(5216),P=t(6473),j=t(4921),R=t(8850),x=t(3556),M=t(1391),O=t(6315),D=t(7713),$=t(6252),A=t(213),F=t(7250),N=t(2425),L=t(1540),z=t(5767),H=t(4973),B=t(509),U=t(7613),G=t(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)(f.def),(0,r.registerTool)(m.def),(0,r.registerTool)(y.def),(0,r.registerTool)(w.def),(0,r.registerTool)(k.def),(0,r.registerTool)(b.def),(0,r.registerTool)(I.def),(0,r.registerTool)(v.def),(0,r.registerTool)(S.def),(0,r.registerTool)(C.def),(0,r.registerTool)(_.def),(0,r.registerTool)(E.def),(0,r.registerTool)(q.def),(0,r.registerTool)(T.def),(0,r.registerTool)(P.def),(0,r.registerTool)(j.def),(0,r.registerTool)(R.def),(0,r.registerTool)(x.def),(0,r.registerTool)(M.def),(0,r.registerTool)(O.def),(0,r.registerTool)(D.def),(0,r.registerTool)($.def),(0,r.registerTool)(A.def),(0,r.registerTool)(F.def),(0,r.registerTool)(N.def),(0,r.registerTool)(L.def),(0,r.registerTool)(z.def),(0,r.registerTool)(H.def),(0,r.registerTool)(B.def),(0,r.registerTool)(U.def),(0,r.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"
|
|
1764
1771
|
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"
|
|
1765
1772
|
async function r(e,t,r){if(C.has(r)&&_>=t){if(0===t)return 0
|
|
1766
1773
|
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]"
|
|
@@ -1778,14 +1785,14 @@ if(30>s)return`${s} day${1===s?"":"s"} ago`
|
|
|
1778
1785
|
const i=Math.floor(s/30)
|
|
1779
1786
|
if(12>i)return`${i} month${1===i?"":"s"} ago`
|
|
1780
1787
|
const a=Math.floor(i/12)
|
|
1781
|
-
return`${a} year${1===a?"":"s"} ago`}(o.modified)} | ${(0,
|
|
1788
|
+
return`${a} year${1===a?"":"s"} ago`}(o.modified)} | ${(0,I.formatTimestamp)(o.modified)})`)
|
|
1782
1789
|
break
|
|
1783
1790
|
case"size":s||"number"!=typeof o.size||(l+=` (${function(e){if(0===e)return"0 bytes"
|
|
1784
1791
|
let t=e,r=0
|
|
1785
1792
|
for(;t>=1024&&4>r;)t/=1024,r++
|
|
1786
1793
|
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[]
|
|
1787
|
-
try{const{fullPath:d}=
|
|
1788
|
-
for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=
|
|
1794
|
+
try{const{fullPath:d}=b.validateAndNormalizePath(e,t),h=await y.default.readdir(d,{withFileTypes:!0}),g=[]
|
|
1795
|
+
for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=b.validateAndNormalizePath(u,t),p=await y.default.stat(h),f=d.isFile()?w.default.extname(d.name).toLowerCase():""
|
|
1789
1796
|
let m
|
|
1790
1797
|
d.isFile()&&(m=await r(h,p.size,f))
|
|
1791
1798
|
const k={name:d.name,isDirectory:d.isDirectory(),depth:n,size:p.size,modified:p.mtime,extension:f,lineCount:m}
|
|
@@ -1794,8 +1801,8 @@ const o=[]
|
|
|
1794
1801
|
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?"/":""
|
|
1795
1802
|
if(o.push(`${r}${l}${d}${u}`),i.children&&i.children.length>0){const e=r+(c?" ":"\u2502 "),n=s(i.children,t,e)
|
|
1796
1803
|
n&&o.push(n)}})),o.join("\n")}function i(e){return e.toLocaleString()}async function a(e,t,n){const o={files:0,directories:0,lines:0}
|
|
1797
|
-
try{const{fullPath:n}=
|
|
1798
|
-
for(const n of s)try{const s=w.default.join(e,n.name).replace(/\\/g,"/"),{fullPath:i}=
|
|
1804
|
+
try{const{fullPath:n}=b.validateAndNormalizePath(e,t),s=await y.default.readdir(n,{withFileTypes:!0})
|
|
1805
|
+
for(const n of s)try{const s=w.default.join(e,n.name).replace(/\\/g,"/"),{fullPath:i}=b.validateAndNormalizePath(s,t)
|
|
1799
1806
|
if(n.isDirectory())o.directories+=1
|
|
1800
1807
|
else{o.files+=1
|
|
1801
1808
|
const e=await y.default.stat(i),t=w.default.extname(n.name).toLowerCase(),s=await r(i,e.size,t)
|
|
@@ -1821,27 +1828,27 @@ var t={}
|
|
|
1821
1828
|
if(null!=e)for(var r=h(e),n=0;n<r.length;n++)"default"!==r[n]&&g(t,e,r[n])
|
|
1822
1829
|
return p(t,e),t}),m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1823
1830
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListDirectory=async function(e,t,i,a){const h=Date.now()
|
|
1824
|
-
let g=
|
|
1825
|
-
|
|
1826
|
-
try{const p=
|
|
1831
|
+
let g=b.FileOperationPhase.VALIDATION
|
|
1832
|
+
b.FileOperationPhase.FILE_WRITE
|
|
1833
|
+
try{const p=b.validateArgs(e,k.ListDirectorySchema),{path:f,levels:m=1,sortBy:I="name"}=p
|
|
1827
1834
|
i.info("Listing directory: "+f)
|
|
1828
|
-
const{normalizedPath:C,fullPath:_}=
|
|
1829
|
-
g=
|
|
1835
|
+
const{normalizedPath:C,fullPath:_}=b.validateAndNormalizePath(f,t)
|
|
1836
|
+
g=b.FileOperationPhase.FILE_WRITE
|
|
1830
1837
|
try{if(!(await y.default.stat(_)).isDirectory())return{content:[{type:"text",text:"Path is not a directory: "+f}],isError:!0}
|
|
1831
1838
|
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: "+f}],isError:!0}:e instanceof Error&&"EACCES"===e.code?{content:[{type:"text",text:"Directory not accessible: "+f}],isError:!0}:{content:[{type:"text",text:"Cannot access directory: "+f}],isError:!0}}let E,q
|
|
1832
|
-
if(m>1){i.info(`Building tree structure for: ${C} (levels: ${m}, sortBy: ${
|
|
1833
|
-
const e=await o(C,t,0,m,
|
|
1834
|
-
if(e.length>0){const t=s(e,
|
|
1839
|
+
if(m>1){i.info(`Building tree structure for: ${C} (levels: ${m}, sortBy: ${I})`)
|
|
1840
|
+
const e=await o(C,t,0,m,I,i)
|
|
1841
|
+
if(e.length>0){const t=s(e,I)
|
|
1835
1842
|
E=`Directory tree for ${C} (${m} 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=[]
|
|
1836
|
-
for(const n of e)try{const e=w.default.join(C,n.name).replace(/\\/g,"/"),{fullPath:s}=
|
|
1843
|
+
for(const n of e)try{const e=w.default.join(C,n.name).replace(/\\/g,"/"),{fullPath:s}=b.validateAndNormalizePath(e,t),i=await y.default.stat(s),a=n.isFile()?w.default.extname(n.name).toLowerCase():""
|
|
1837
1844
|
let c
|
|
1838
|
-
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,
|
|
1845
|
+
n.isFile()&&(c=await r(s,i.size,a)),o.push({name:n.name,isDirectory:n.isDirectory(),depth:0,size:i.size,modified:i.mtime,extension:a,lineCount:c})}catch(e){i.debug("Excluding directory entry from listing: "+n.name,{reason:(0,v.getErrorMessage)(e)})}const s=u(o,I),a=s.map((e=>n({name:e.name,isDirectory(){return e.isDirectory},isFile(){return!e.isDirectory}},I,e)))
|
|
1839
1846
|
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)
|
|
1840
1847
|
E+="\n\nBranch: "+(S?.branchName||"unknown")
|
|
1841
1848
|
const T=Date.now()-h
|
|
1842
1849
|
return a.recordValue("list_directory_time",T),a.recordValue("list_directory_entries",q),a.incrementCounter("list_directory_success",1),i.info("Successfully listed directory: "+C,{entryCount:q,levels:m,time:T}),{content:[{type:"text",text:E}]}}catch(e){const t=Date.now()-h
|
|
1843
1850
|
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}}}
|
|
1844
|
-
const y=m(t(1943)),w=m(t(6928)),k=t(6183),
|
|
1851
|
+
const y=m(t(1943)),w=m(t(6928)),k=t(6183),b=f(t(5967)),I=t(3253),v=t(8824),C=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore",".config",".conf",".ini",".cfg"]),_=1048576},2568(e,exports,t){"use strict"
|
|
1845
1852
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1846
1853
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectSynchronizer=void 0
|
|
1847
1854
|
const n=r(t(6928)),o=t(8029),s=t(8824),i=t(2096)
|
|
@@ -2028,11 +2035,11 @@ const f=await Promise.all(p)
|
|
|
2028
2035
|
let m=""
|
|
2029
2036
|
if(t.workspaceManager)try{const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
2030
2037
|
e.branchName&&!e.permanentBranch&&(m=`**Current Branch:** ${e.branchName}\n`)}catch(e){i.debug("Could not get branch context",{error:e})}const y=f.filter((e=>e.success)).length,w=f.filter((e=>!e.success)).length,k=f.length
|
|
2031
|
-
let
|
|
2032
|
-
m&&(
|
|
2038
|
+
let b="## Read Files/Documents\n\n"
|
|
2039
|
+
m&&(b+=m),b+=`**Total Requests:** ${k} - **Successful:** ${y} - **Failed:** ${w}\n\n`
|
|
2033
2040
|
for(let e=0;e<f.length;e++){const t=f[e]
|
|
2034
|
-
"file"===t.type?
|
|
2035
|
-
return i.info("Multiple file/document read completed",{duration:Date.now()-a,totalRequests:k,successfulReads:y,failedReads:w,success:
|
|
2041
|
+
"file"===t.type?b+=`File ${e+1}: ${t.path}\n`:(b+=`Document ${e+1}: ${t.documentId}`,t.filename&&(b+=` (${t.filename})`),b+="\n"),t.success?(b+="**Status:** Success\n",t.lineCount&&t.totalLines&&(b+=`Lines Read / Total Lines ${t.lineCount} / ${t.totalLines}\n`),t.originalRequest?.lines&&t.totalLines&&(b+=`**Lines:** ${t.originalRequest.lines}\n`),b+=`\n**Content:**\n\`\`\`\n${t.content}\n\`\`\`\n`):(b+="**Status:** Failed\n",b+=`**Error:** ${t.error}\n`),b+="\n"}const I=0===w
|
|
2042
|
+
return i.info("Multiple file/document read completed",{duration:Date.now()-a,totalRequests:k,successfulReads:y,failedReads:w,success:I}),s.incrementCounter("read_files_total",1,{success:I}),{content:[{type:"text",text:b}],isError:!I}}catch(e){const t=Date.now()-a
|
|
2036
2043
|
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}}}
|
|
2037
2044
|
const l=c(t(1943)),d=t(6183),u=t(1569),h=a(t(5967)),g=t(9470),p=t(8824)},2968(e,exports,t){"use strict"
|
|
2038
2045
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.TaskClient=void 0
|
|
@@ -2146,12 +2153,12 @@ d.info("Generating journal for request",{requestId:c})
|
|
|
2146
2153
|
const h=t.projectId
|
|
2147
2154
|
if(!h)throw(0,n.createValidationError)("Project ID is required. Make sure you are in a project context.")
|
|
2148
2155
|
o.setProjectId(h),d.info("Fetching request data, tasks, and file history in parallel")
|
|
2149
|
-
const g=o.getRequestClient(),p=o.getTaskClient(),f=o.getToolRecordClient(),[m,y,w]=await Promise.all([g.getRequest(c),p.listTasks({requestId:c}),f.getToolRecordsByRequestId(c).catch((e=>(d.warn("Failed to fetch tool records",{error:e+""}),[])))]),k=(0,s.extractDataFromResponse)(m,{logger:d,operationName:"getRequest",throwOnNoData:!0}),
|
|
2156
|
+
const g=o.getRequestClient(),p=o.getTaskClient(),f=o.getToolRecordClient(),[m,y,w]=await Promise.all([g.getRequest(c),p.listTasks({requestId:c}),f.getToolRecordsByRequestId(c).catch((e=>(d.warn("Failed to fetch tool records",{error:e+""}),[])))]),k=(0,s.extractDataFromResponse)(m,{logger:d,operationName:"getRequest",throwOnNoData:!0}),b="data"in k?k.data:k,I={id:b.id||c,title:b.title||"Unknown Request",description:b.description||"No description available",status:b.status||"unknown",type:b.type||"unknown",acceptanceCriteria:b.acceptanceCriteria||[],createdAt:b.createdAt||(new Date).toISOString(),updatedAt:b.updatedAt||(new Date).toISOString(),completedAt:b.completedAt},v=(0,s.extractDataFromResponse)(y,{logger:d,operationName:"listTasks",throwOnNoData:!1}),C=(Array.isArray(v)?v:"data"in v?v.data:[]).map((e=>({id:e.id,title:e.title||"Untitled Task",description:e.description||"No description",status:e.status||"unknown",createdAt:e.createdAt||(new Date).toISOString(),completedAt:e.metadata?.completedAt})))
|
|
2150
2157
|
d.info(`Fetched request, ${C.length} tasks, ${w.length} tool records`)
|
|
2151
2158
|
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()))
|
|
2152
2159
|
for(const e of o){const o=r(e),s=e.metadata?.comment||e.metadata?.userComment||"No comment"
|
|
2153
2160
|
n.push({type:e.type,timestamp:e.createdAt,comment:s,files:o,recordId:e.localId||e.id})
|
|
2154
|
-
for(const e of o)t.set(e,(t.get(e)||0)+1)}return{files:Array.from(t.entries()).map((([e,t])=>({path:e,operations:t}))).sort(((e,t)=>t.operations-e.operations)),operations:n}}(w),E={request:
|
|
2161
|
+
for(const e of o)t.set(e,(t.get(e)||0)+1)}return{files:Array.from(t.entries()).map((([e,t])=>({path:e,operations:t}))).sort(((e,t)=>t.operations-e.operations)),operations:n}}(w),E={request:I,tasks:C,fileChanges:{summary:{totalFiles:_.files.length,totalOperations:_.operations.length,files:_.files},operations:_.operations},suggestedFilename:`JOURNAL-${c}.md`,metadata:{projectId:h,requestId:c,generatedAt:(new Date).toISOString()}},q=`\u2705 **Request Data Fetched Successfully!**\n\n**Request:** ${I.title} (${c})\n**Status:** ${I.status}\n**Type:** ${I.type}\n**Tasks:** ${C.length}\n**Files Changed:** ${_.files.length}\n**File Operations:** ${_.operations.length}\n\n**Data Summary:**\n\`\`\`json\n${JSON.stringify(E,null,2)}\n\`\`\`\n\n**Next Steps:**\nWrite a **compact technical narrative** and save as \`JOURNAL-${c}.md\` using document_operations (create).\n\n**Style Guide:**\n- Be concise and direct - no fluff, repetition, or unnecessary elaboration\n- Write in narrative flow connecting the changes chronologically\n- Reference files with paths: "Modified \\\`src/tools/example.ts\\\` to add X..."\n- Include operation comments inline: ("comment: 'Fix bug in parser'")\n- **Link to tool records**: Use \\\`[RECORD:trec######]\\\` format to reference operations (e.g., "Modified parser.ts [RECORD:trec004123]")\n- Show key code changes with brief snippets where they add clarity\n- Explain what changed and why, skip obvious details\n- Focus on technical substance over structure\n\n**Example:** "Modified \\\`parser.ts\\\` [RECORD:trec004123] to handle edge cases (comment: 'Fix null handling'). Added \\\`if (!input) return null;\\\` check at line 45. Then updated \\\`validator.ts\\\` [RECORD:trec004124] to use the new parser behavior..."`
|
|
2155
2162
|
return u({tool:"generate_request_journal",success:!0}),l.incrementCounter("generate_request_journal_total",1,{success:!0}),{content:[{type:"text",text:q}]}}catch(e){return d.error("Error generating request journal",{error:e instanceof Error?e.stack:e+""}),u({tool:"generate_request_journal",success:!1}),l.incrementCounter("generate_request_journal_errors",1),{content:[{type:"text",text:"\u274c **Failed to generate journal:** "+(0,i.getErrorMessage)(e)}],isError:!0}}}
|
|
2156
2163
|
const n=t(9860),o=t(1569),s=t(2960),i=t(8824),a=o.z.object({requestId:o.z.string().regex(/^req[_\d].+$/,"Invalid request ID format")})},3064(e,exports,t){"use strict"
|
|
2157
2164
|
async function r(e,t,r,n){if(!r.lockOverrideManager||!r.configManager)return e
|
|
@@ -2275,7 +2282,7 @@ var t={}
|
|
|
2275
2282
|
if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
2276
2283
|
return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2277
2284
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceStrings=async function(e,r,o,s,i,a,c,y){const w=a.child({tool:"replace_strings"}),k=Date.now()
|
|
2278
|
-
let I,
|
|
2285
|
+
let b,I,v=u.FileOperationPhase.VALIDATION
|
|
2279
2286
|
const C={toolName:"replace-strings",operationName:"replace-string",fileOperationPhase:u.FileOperationPhase.STRING_REPLACEMENT,recordType:"replace-strings",metricsPrefix:"replace_strings",successMessage:"Successfully replaced strings across files and documents",failureMessage:"Failed to replace strings across files and documents"}
|
|
2280
2287
|
try{const _=u.validateArgs(e,d.ReplaceStringsSchema),{operations:E,comment:q}=_,{resolveActiveTaskId:S}=await Promise.resolve().then(t.bind(t,3451)),T=e.taskId||await S(r,o,a)||"untracked"
|
|
2281
2288
|
if(w.info("Replacing strings across files and documents",{taskId:T,operationCount:E.length,comment:q}),!E||0===E.length)throw new h.ValidationError("At least one operation is required")
|
|
@@ -2301,7 +2308,7 @@ for(let e=0;e<R.length;e++){const t=R[e],n=P[e],{normalizedPath:o,fullPath:s}=u.
|
|
|
2301
2308
|
R[e]={...t,path:o,fullPath:s}}}if(x.length>0&&D)try{await(0,g.validateRequestStatusForDocumentOperation)(D,i,w,c,"replace-strings-document")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2302
2309
|
throw e}v=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_strings_phase",1,{phase:v})
|
|
2303
2310
|
const N=[...R.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...x.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:L}=await u.createFileOperationRecords(T,D,r.projectId,C.recordType,M,{operationCount:E.length,fileOperations:R.length,documentOperations:x.length,operations:N,userComment:q},o,s,w,c,C.metricsPrefix,y)
|
|
2304
|
-
if(
|
|
2311
|
+
if(b=L,I=L,v=C.fileOperationPhase,c.incrementCounter("replace_strings_phase",1,{phase:v}),R.length>0&&r.git)try{w.debug("[REPLACE-STRINGS] Checking for user changes before replace operations")
|
|
2305
2312
|
const e=await(0,p.commitUserChangesBeforeToolOperation)(r.git,"replace-strings",{requestId:D,taskId:T,workspaceManager:r.workspaceManager},w,c)
|
|
2306
2313
|
e.userChangesCommitted&&(w.debug("[REPLACE-STRINGS] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before replace-strings operation",{taskId:T,fileOperationsCount:R.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[REPLACE-STRINGS] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:T,fileOperationsCount:R.length,error:e instanceof Error?e.message:e+""})}w.debug("[REPLACE-STRINGS] Proceeding with file operations",{fileCount:R.length})
|
|
2307
2314
|
const z=[]
|
|
@@ -2314,8 +2321,8 @@ try{const o=await r.documentFileManager.getDocumentAsFile(e.documentId),s=r.docu
|
|
|
2314
2321
|
t.filename=s?.filename
|
|
2315
2322
|
const i=await l.default.readFile(o,"utf8"),{newContent:a,results:c}=await n(i,e.replacements,e.mode)
|
|
2316
2323
|
t.replacements=c,t.successfulReplacements=c.filter((e=>e.success)).length,t.failedReplacements=c.filter((e=>!e.success)).length,a!==i?(await l.default.writeFile(o,a,"utf8"),r.documentFileManager.markForSync(e.documentId),t.success=!0,B++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,w.error("Document operation failed",{documentId:e.documentId,error:t.error})}z.push(t)}if(x.length>0)try{for(const e of x){const t=z.find((t=>t.documentId===e.documentId))
|
|
2317
|
-
t?.success&&await r.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const U=await u.handleMultiFileGitCommit(T,R,z,B,{operationType:"Replace strings",toolRecordId:
|
|
2318
|
-
try{await s.updateToolRecord(
|
|
2324
|
+
t?.success&&await r.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const U=await u.handleMultiFileGitCommit(T,R,z,B,{operationType:"Replace strings",toolRecordId:I,successField:"successfulReplacements",logger:w,metrics:c,metricsPrefix:"replace_strings"},r),G=u.processMultiFileOperationResults(z,"successfulReplacements"),{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q}=G
|
|
2325
|
+
try{await s.updateToolRecord(I,{metadata:{path:R.length>0?R[0].path:"document:"+x[0]?.documentId,status:K?"completed":"failed",error:K?void 0:V+" operations failed",totalOperations:z.length,successfulFiles:Y,failedFiles:Q,operations:N,totalSuccessfulReplacements:J,totalFailedReplacements:H,operationsWithChanges:B,processingTime:Date.now()-k,userComment:q,...R.length>0&&U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}},note:K?`String replacement completed: ${W}/${z.length} operations successful${R.length>0?" (committed to git)":""}`:`String replacement partially failed: ${V}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}u.formatMultiFileToolResponse("String Replacement",{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q},U,F)
|
|
2319
2326
|
let Z="## String Replacement Results\n\n"
|
|
2320
2327
|
if(r.workspaceManager){const e=r.workspaceManager.getCurrentContext(r.currentSessionId)
|
|
2321
2328
|
e.permanentBranch||(Z+=`**Branch:** \`${e.branchName}\`\n\n`)}if(Z+="**Summary:**\n",Z+=`- **Files processed:** ${W+V}\n`,Z+=`- **Successful operations:** ${W}\n`,Z+=`- **Failed operations:** ${V}\n`,Z+=`- **Total replacements:** ${J} successful, ${H} failed\n\n`,U.success&&U.commitHash&&(Z+="**Git Commit:**\n",Z+=`- **Commit Hash:** ${U.commitHash.substring(0,8)}\n`,Z+=`- **Files Committed:** ${U.filesCommitted.length}\n`,U.previousCommitHash&&(Z+=`- **Previous Commit:** ${U.previousCommitHash.substring(0,8)}\n`),Z+="\n"),F.lockAcquired&&F.lockedRequestId&&(r.workspaceManager?.getCurrentContext(r.currentSessionId)?.permanentBranch||(Z+=`\u{1f512} **Locked request:** ${F.lockedRequestId}\n\n`)),1===z.length){const e=z[0]
|
|
@@ -2325,7 +2332,7 @@ for(const e of z){if("file"===e.type?Z+=`### File: ${e.path}\n`:(Z+="### Documen
|
|
|
2325
2332
|
for(const t of e.replacements.filter((e=>!e.success)))Z+=` - "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}Z+="\n"}}x.length>0&&(Z+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
2326
2333
|
const X=Date.now()-k
|
|
2327
2334
|
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
|
|
2328
|
-
if(w.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),
|
|
2335
|
+
if(w.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),I)try{await s.updateToolRecord(I,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,m.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"String replacement failed: "+(0,m.getErrorMessage)(t)})}catch(e){}return c.incrementCounter("replace_strings_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Replace Strings Failed:** "+(0,m.getErrorMessage)(t)}],isError:!0}}}
|
|
2329
2336
|
const l=c(t(1943)),d=t(6183),u=a(t(5967)),h=t(9860),g=t(5003),p=t(7478),f=t(9949),m=t(8824)},3322(e,exports,t){"use strict"
|
|
2330
2337
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
2331
2338
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
@@ -2395,11 +2402,11 @@ if(g.requestId)try{const e=a.getRequestClient()
|
|
|
2395
2402
|
p=await e.getRequest(g.requestId),d.info("Retrieved parent request information",{taskId:r,requestId:g.requestId})}catch(e){d.warn("Failed to retrieve parent request",{error:(0,s.getErrorMessage)(e),taskId:r,requestId:g.requestId})}const f=e=>{if(!e)return"Unknown date"
|
|
2396
2403
|
try{const t=new Date(e)
|
|
2397
2404
|
return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return d.warn("Invalid date format: "+e),"Unknown date"}},m=f(g.createdAt),y=f(g.updatedAt),w=g.requestId||g.requestLocalId,k=g.sequenceNumber&&w?(0,i.formatTaskRef)(w,g.sequenceNumber):r
|
|
2398
|
-
let
|
|
2399
|
-
if(
|
|
2400
|
-
|
|
2405
|
+
let b=`# Task: ${g.title} (${k})\n\n`
|
|
2406
|
+
if(b+=`**Status**: ${g.status}\n`,b+=`**Created**: ${m}\n`,b+=`**Updated**: ${y}\n`,g.requestId&&(b+="**Parent Request**: "+g.requestId,b+=p?` (${p.title})\n`:"\n"),g.metadata){const e=g.metadata
|
|
2407
|
+
b+="\n## Metadata\n\n",e.lastCommit&&(b+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(b+=`**Completed At**: ${f(e.completedAt)}\n`),e.completionSummary&&(b+=`**Completion Summary**: ${e.completionSummary}\n`)
|
|
2401
2408
|
const t=["lastCommit","completedAt","completionSummary"]
|
|
2402
|
-
Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{
|
|
2409
|
+
Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{b+=`**${e}**: ${t}\n`}))}return b+="\n## Description\n\n",g.description&&g.description.trim().length>0?b+=g.description:b+="No description provided.",u({success:!0}),{content:[{type:"text",text:b}]}}catch(n){d.error("Failed to get task information",{error:n instanceof Error?n.stack:n+"",args:e})
|
|
2403
2410
|
try{const o=a.getToolRecordClient()
|
|
2404
2411
|
await(0,r.createFailureToolRecord)("get-task-information",n,{args:e},o,d,l,{taskId:e.taskId,projectId:t.projectId,note:"Failed to get task information: "+(0,s.getErrorMessage)(n)})}catch(e){d.warn("Failed to create failure record",{recordError:e instanceof Error?e.message:e+""})}u({success:!1,error:n instanceof Error?n.name:"unknown"})
|
|
2405
2412
|
let i=(0,s.getErrorMessage)(n)
|
|
@@ -2432,14 +2439,14 @@ const r=t(6183),n=t(8317)
|
|
|
2432
2439
|
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"
|
|
2433
2440
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2434
2441
|
Object.defineProperty(exports,"__esModule",{value:!0})
|
|
2435
|
-
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),f=t(4139),m=t(6800),y=t(6539),w=t(8824),k=t(6975),
|
|
2442
|
+
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),f=t(4139),m=t(6800),y=t(6539),w=t(8824),k=t(6975),b=t(1253),I=process.argv.slice(2),v=I[0]||process.cwd(),C=n.default.resolve(v),_=parseInt(process.env.LOCAL_SERVER_PORT||I[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:_})
|
|
2436
2443
|
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")
|
|
2437
2444
|
E.info("Using remote server URL",{remoteServerUrl:S}),async function(){try{E.info("Finding available port...",{preferredPort:_,baseDir:C,remoteServerUrl:S})
|
|
2438
2445
|
const e=await(0,m.findAvailablePort)(_)
|
|
2439
2446
|
e!==_&&E.info(`Preferred port ${_} is in use, using port ${e} instead`),E.info("Starting HTTP API server...",{port:e,baseDir:C,remoteServerUrl:S})
|
|
2440
2447
|
const t=new l.ProjectRegistry(E),r=new u.DefaultProjectFileSystem(E),c=n.default.join(C,f.ALCHEMY_DIR_NAME)
|
|
2441
2448
|
E.info(`Checking ${f.ALCHEMY_DIR_NAME} directory`,{alchemyPath:c}),await r.ensureDirectoryExists(c)
|
|
2442
|
-
const h=new
|
|
2449
|
+
const h=new b.TokenManager(E,n.default.join(c,"auth-token.json")),I=(await y.ClientFactory.createClient(S,E,q,{tokenManager:h,workingDir:C,alchemyPath:c})).projectClient,v=new k.ProjectClientAdapter(I,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}})
|
|
2443
2450
|
E.info("Using project",{projectId:P.id,projectName:P.name})
|
|
2444
2451
|
const j=(0,o.default)()
|
|
2445
2452
|
j.use((0,s.default)()),j.use(o.default.json({limit:"50mb"})),j.use(o.default.urlencoded({extended:!0})),j.use((0,g.requestLogger)(E))
|
|
@@ -2544,19 +2551,19 @@ try{const a=u.validateArgs(e,d.GetFileInfoSchema),{path:h}=a
|
|
|
2544
2551
|
n.info("Getting file info: "+h)
|
|
2545
2552
|
const{normalizedPath:f,fullPath:m}=u.validateAndNormalizePath(h,t)
|
|
2546
2553
|
i=u.FileOperationPhase.FILE_WRITE
|
|
2547
|
-
try{await c.default.access(m)}catch(e){throw Error("Path not accessible: "+h)}const y=await c.default.stat(m),w=y.isFile()?l.default.extname(m).slice(1):"",k={path:f,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},
|
|
2548
|
-
k.isFile&&w&&
|
|
2549
|
-
const
|
|
2550
|
-
return o.recordValue("get_file_info_time",
|
|
2554
|
+
try{await c.default.access(m)}catch(e){throw Error("Path not accessible: "+h)}const y=await c.default.stat(m),w=y.isFile()?l.default.extname(m).slice(1):"",k={path:f,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},b=["File Information for: "+f,"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]
|
|
2555
|
+
k.isFile&&w&&b.push("Extension: "+w)
|
|
2556
|
+
const I=Date.now()-s
|
|
2557
|
+
return o.recordValue("get_file_info_time",I),o.incrementCounter("get_file_info_success",1),n.info("Successfully retrieved file info: "+f,{type:k.type,size:k.size,time:I}),{content:[{type:"text",text:b.join("\n")}]}}catch(t){const r=Date.now()-s
|
|
2551
2558
|
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}
|
|
2552
2559
|
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"
|
|
2553
2560
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQuickChange=async function(e,t,d,u,h,g,p){const f=h.child({tool:"quick_edit"}),m=Date.now()
|
|
2554
|
-
try{const y=u.getRequestClient(),w=u.getTaskClient(),k=u.getFileClient(),
|
|
2555
|
-
f.info("Starting quick_edit workflow",{title:
|
|
2561
|
+
try{const y=u.getRequestClient(),w=u.getTaskClient(),k=u.getFileClient(),b=u.getToolRecordClient(),{title:I,description:v,...C}=e,_=e.comment||I
|
|
2562
|
+
f.info("Starting quick_edit workflow",{title:I,operationType:t})
|
|
2556
2563
|
let E=!1
|
|
2557
2564
|
try{const e=await y.listRequests({limit:2,sortBy:"created_at",sortDirection:"desc"})
|
|
2558
2565
|
e&&2===e.length&&e.every((e=>"quick-edit"===e.type))&&(E=!0,f.info("Detected two consecutive quick-edits, will recommend normal request"))}catch(e){f.warn("Could not check recent requests for recommendation",{error:e})}f.debug("Creating quick_edit request")
|
|
2559
|
-
const q=await y.createRequest({title:
|
|
2566
|
+
const q=await y.createRequest({title:I,description:v,type:"quick-edit",acceptanceCriteria:["Quick change completed successfully"]})
|
|
2560
2567
|
if(!q||!q.id)throw Error("Failed to create request")
|
|
2561
2568
|
const S=q.id
|
|
2562
2569
|
let T
|
|
@@ -2564,24 +2571,24 @@ f.info("Created request",{requestId:S})
|
|
|
2564
2571
|
try{if(f.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)
|
|
2565
2572
|
e.userChangesCommitted?f.info("Committed user changes to main before quick-edit branch creation",{requestId:S,commitHash:e.commitHash?.substring(0,8)}):f.debug("No uncommitted changes found, proceeding with quick-edit")}catch(e){f.warn("Failed to commit user changes before quick-edit, proceeding anyway",{requestId:S,error:e instanceof Error?e.message:e+""})}else f.debug("No git instance available, skipping uncommitted changes check")
|
|
2566
2573
|
f.debug("Creating task")
|
|
2567
|
-
const e=await w.createTask({requestId:S,projectId:d.projectId,title:`Execute ${t} operation`,description:"Quick change: "+
|
|
2574
|
+
const e=await w.createTask({requestId:S,projectId:d.projectId,title:`Execute ${t} operation`,description:"Quick change: "+I})
|
|
2568
2575
|
if(!e||!e.id)throw Error("Failed to create task")
|
|
2569
2576
|
let v
|
|
2570
|
-
if(T=e.id,f.info("Created task",{taskId:T}),f.debug("Executing file operation",{operationType:t}),"write"===t)v=await(0,n.handleWriteFile)({taskId:T,...C,comment:_},d,k,w,
|
|
2571
|
-
else if("replace"===t)v=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,
|
|
2577
|
+
if(T=e.id,f.info("Created task",{taskId:T}),f.debug("Executing file operation",{operationType:t}),"write"===t)v=await(0,n.handleWriteFile)({taskId:T,...C,comment:_},d,k,w,b,y,h,g,p)
|
|
2578
|
+
else if("replace"===t)v=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,b,y,h,g,p)
|
|
2572
2579
|
else{if("manage"!==t)throw new r.ValidationError("Unsupported operation type: "+t)
|
|
2573
|
-
v=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||
|
|
2580
|
+
v=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||I},d,w,b,y,u,h,g,p)}if(v.isError){f.error("File operation failed, cleaning up request and task",{requestId:S,taskId:T})
|
|
2574
2581
|
try{await w.updateTaskStatus(T,"canceled"),f.info("Canceled task after operation failure",{taskId:T})}catch(e){f.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),f.info("Canceled request after operation failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),f.info("Cleaned up branch/worktree after operation failure",{requestId:S}))}catch(e){f.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")
|
|
2575
2582
|
P?f.warn("File operation completed with partial failures",{requestId:S}):f.info("File operation completed successfully"),f.debug("Completing task")
|
|
2576
|
-
try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${
|
|
2583
|
+
try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${I}${P?" (partial success)":""}`},d,u,h,g),f.info("Task completed successfully",{taskId:T})}catch(e){f.error("Task completion via handleCompleteTask failed, attempting direct status update",{taskId:T,error:e instanceof Error?e.message:e+"",errorStack:e instanceof Error?e.stack:void 0})
|
|
2577
2584
|
try{await w.updateTaskStatus(T,"completed"),f.info("Task completed via direct updateTaskStatus call",{taskId:T})}catch(e){return f.error("Direct task completion ALSO failed - task may be stuck in in_progress",{taskId:T,error:e instanceof Error?e.message:e+"",errorStack:e instanceof Error?e.stack:void 0,operationType:t,isDocumentOperation:!!C.documentId}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but task completion failed.\n\n**Request:** ${S}\n**Task:** ${T}\n**Issue:** Could not mark task as completed - it remains in 'in_progress' state\n\nThe ${t} operation was successful, but we couldn't automatically complete the task. Please use the complete-task tool manually with taskId: ${T}\n\nError: `+(e instanceof Error?e.message:e+"")}],isError:!0}}}f.debug("Completing request")
|
|
2578
|
-
const j=P?`Quick change completed with partial success: ${
|
|
2585
|
+
const j=P?`Quick change completed with partial success: ${I}. Some replacements failed - see details below.`:"Quick change completed: "+I,R=P?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
|
|
2579
2586
|
let x=!1
|
|
2580
2587
|
try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:j,acceptanceEvidence:[{evidence:R}],testVerification:void 0},d,u,h,g,p)
|
|
2581
2588
|
if(e.isError)f.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text})
|
|
2582
2589
|
else{try{await y.updateRequest(S,{status:"completed",completionSummary:j}),f.info("Request finalized to completed",{requestId:S})}catch(e){f.warn("Failed to finalize request to completed, may be stuck at ready_for_merge",{requestId:S,error:(0,l.getErrorMessage)(e)})}x=!0,f.info("Request completed successfully",{requestId:S})}}catch(e){f.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!x)try{f.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:j}),x=!0,f.info("Request completed successfully via direct API call",{requestId:S})}catch(e){return f.error("Direct request completion also failed",{requestId:S,error:e instanceof Error?e.message:e+""}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but request completion failed.\n\n**Request:** ${S}\n**Status:** Still in 'in_progress' - please complete manually\n\nThe file operation was successful, but we couldn't automatically complete the request. Please use the complete-request tool manually.`}],isError:!0}}const M=Date.now()-m
|
|
2583
2590
|
let O
|
|
2584
|
-
return f.info("Quick fix completed",{requestId:S,duration:M,hasPartialFailure:P}),O=P?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${
|
|
2591
|
+
return f.info("Quick fix completed",{requestId:S,duration:M,hasPartialFailure:P}),O=P?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${M}ms\n**Status:** Some operations succeeded, some failed\n\nThe successful changes have been applied and automatically merged to main.\n**Active branch:** main\n\n**\u26a0\ufe0f Note:** This quick-fix had partial failures. See operation details below:\n\n`+q:`\u2705 Quick change completed successfully!\n\n**Request:** ${S}\n**Title:** ${I}\n**Operation:** ${t}\n**Duration:** ${M}ms\n\nThe change has been applied and automatically merged to main.\n**Active branch:** main`+(q.match(/\[RECORD:trec\d{6}\]/)?.[0]?"\n"+q.match(/\[RECORD:trec\d{6}\]/)?.[0]:""),E&&(O+="\n\n\u{1f4a1} **Recommendation:** You've created several quick-edits in a row. For better traceability and organization, consider creating a proper feature or bugfix request with multiple tasks for your next change."),{content:[{type:"text",text:O}]}}catch(e){if(f.error("Quick change workflow failed after request creation, cleaning up",{requestId:S,error:(0,l.getErrorMessage)(e)}),T)try{await w.updateTaskStatus(T,"canceled"),f.info("Canceled task after workflow failure",{taskId:T})}catch(e){f.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),f.info("Canceled request after workflow failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),f.info("Cleaned up branch/worktree after workflow failure",{requestId:S}))}catch(e){f.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}throw e}}catch(e){const t=Date.now()-m
|
|
2585
2592
|
return f.error("Quick change failed",{error:(0,l.getErrorMessage)(e),duration:t}),e instanceof r.ValidationError?{content:[{type:"text",text:"\u274c "+e.message}],isError:!0}:{content:[{type:"text",text:"\u274c Quick change failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
|
|
2586
2593
|
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"
|
|
2587
2594
|
module.exports=require("simple-git")},3884(e,exports,t){"use strict"
|
|
@@ -2661,7 +2668,7 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
2661
2668
|
var t={}
|
|
2662
2669
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2663
2670
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2664
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,r,n,o,s,i,m,y,w){const k=m.child({tool:"write_file"}),
|
|
2671
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,r,n,o,s,i,m,y,w){const k=m.child({tool:"write_file"}),b=y.startTimer("tool_execution_time"),I=Date.now()
|
|
2665
2672
|
let v,C,_=d.FileOperationPhase.VALIDATION
|
|
2666
2673
|
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"}
|
|
2667
2674
|
try{const n=d.validateArgs(e,l.WriteFileSchema),{path:f,documentId:q,content:S,format:T,append:P,comment:j}=n,{resolveActiveTaskId:R}=await Promise.resolve().then(t.bind(t,3451)),x=e.taskId||await R(r,o,m)||"untracked",M=!!q,O=!!f
|
|
@@ -2697,11 +2704,11 @@ if(await c.default.mkdir(Q,{recursive:!0}),await c.default.writeFile(F,Y,"utf8")
|
|
|
2697
2704
|
try{await r.documentFileManager.syncDocument(q),k.info("Document synced successfully",{documentId:q})}catch(e){k.warn("Failed to sync document immediately",{documentId:q,error:e})}}let Z,X,ee=null,te=!1
|
|
2698
2705
|
if(O){if(_=d.FileOperationPhase.GIT_COMMIT,y.incrementCounter("write_file_phase",1,{phase:_}),r.workspaceManager){const e=r.workspaceManager.getCurrentContext(r.currentSessionId)
|
|
2699
2706
|
X=e.branchName,te=e.permanentBranch,k.debug("Retrieved branch name from workspace manager",{branchName:X,requestId:e.requestId,mode:e.mode,isMainBranch:e.isMainBranch})}try{const e=`${N?"Create":P?"Append to":"Update"} ${D} (${C})`,t=await d.commitToGit(x,D,C,C,e,r,k,y,E.metricsPrefix)
|
|
2700
|
-
Z=t.commitHash,ee=t.previousCommitHash,k.info("Changes committed to git via shared utility",{path:D,commitMessage:e,commitHash:Z?.substring(0,8),previousCommitHash:ee?.substring(0,8),branchName:X,toolRecordId:C})}catch(e){k.warn("Git operations failed via shared utility",{error:e})}}try{await s.updateToolRecord(C,{metadata:{path:O?D:"document:"+q,status:"completed",finalContentLength:Y.length,wasFileCreated:N,wasAppended:P&&L,operationType:M?"document":"file",processingTime:Date.now()-
|
|
2707
|
+
Z=t.commitHash,ee=t.previousCommitHash,k.info("Changes committed to git via shared utility",{path:D,commitMessage:e,commitHash:Z?.substring(0,8),previousCommitHash:ee?.substring(0,8),branchName:X,toolRecordId:C})}catch(e){k.warn("Git operations failed via shared utility",{error:e})}}try{await s.updateToolRecord(C,{metadata:{path:O?D:"document:"+q,status:"completed",finalContentLength:Y.length,wasFileCreated:N,wasAppended:P&&L,operationType:M?"document":"file",processingTime:Date.now()-I,userComment:j,...O&&Z&&{commitHash:Z,previousCommitHash:ee||void 0}},note:"Write operation completed successfully"+(M?" (document synced)":" (committed to git)")})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let re=`**${N?"Created":P?"Appended to":"Updated"} ${M?`document ${q}${A?` (${A})`:""}`:"file "+D}**\n`
|
|
2701
2708
|
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}\`.`)
|
|
2702
2709
|
const ne=Date.now()
|
|
2703
|
-
return k.info("Write operation completed successfully",{duration:ne-
|
|
2704
|
-
if(k.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{path:e?.path,status:"failed",error:(0,f.getErrorMessage)(t),phase:_,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return
|
|
2710
|
+
return k.info("Write operation completed successfully",{duration:ne-I,path:O?D:"document:"+q,contentLength:Y.length,wasCreated:N}),b({tool:"write_file",success:!0}),y.incrementCounter("write_file_total",1,{success:!0}),r.workspaceManager?.largeFileWarning&&(re+=r.workspaceManager.largeFileWarning,r.workspaceManager.largeFileWarning=""),{content:[{type:"text",text:re}]}}catch(t){const r=Date.now()-I
|
|
2711
|
+
if(k.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{path:e?.path,status:"failed",error:(0,f.getErrorMessage)(t),phase:_,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return b({tool:"write_file",success:!1}),y.incrementCounter("write_file_errors",1,{phase:_}),{content:[{type:"text",text:"\u274c **Write Operation Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
|
|
2705
2712
|
const a=i(t(6928)),c=i(t(1943)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824)},4118(e,exports){"use strict"
|
|
2706
2713
|
Object.defineProperty(exports,"__esModule",{value:!0})},4139(e,exports){"use strict"
|
|
2707
2714
|
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"
|
|
@@ -2828,12 +2835,12 @@ return l({success:!1,error:"not_found"}),{content:[{type:"text",text:`Command "$
|
|
|
2828
2835
|
e.grep&&(f=`${f} 2>&1 | grep -i ${JSON.stringify(e.grep)}`)
|
|
2829
2836
|
const m=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
|
|
2830
2837
|
i.info("Running command",{name:p.name,command:f,cwd:m})
|
|
2831
|
-
let y="",w="",k=0,
|
|
2832
|
-
try{y=(0,r.execSync)(f,{cwd:m,timeout:1e3*(p.timeout||60),encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"win32"===process.platform?"cmd.exe":"/bin/sh",env:{...process.env,FORCE_COLOR:"0"}})||""}catch(e){k=e.status??1,y=e.stdout||"",w=e.stderr||"",e.killed&&(
|
|
2833
|
-
y.length>
|
|
2834
|
-
const C=
|
|
2838
|
+
let y="",w="",k=0,b=!1
|
|
2839
|
+
try{y=(0,r.execSync)(f,{cwd:m,timeout:1e3*(p.timeout||60),encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"win32"===process.platform?"cmd.exe":"/bin/sh",env:{...process.env,FORCE_COLOR:"0"}})||""}catch(e){k=e.status??1,y=e.stdout||"",w=e.stderr||"",e.killed&&(b=!0)}const I=8e3,v=4e3
|
|
2840
|
+
y.length>I&&(y="\u2026"+y.slice(-I)),w.length>v&&(w="\u2026"+w.slice(-v))
|
|
2841
|
+
const C=b?"TIMEOUT":null,_=[y,w].filter(Boolean).join("\n")||"(no output)"
|
|
2835
2842
|
let E
|
|
2836
|
-
if(c)try{const e=await c.createToolRecord({projectId:t.projectId,type:"run-command",metadata:{name:p.name,command:f,exitCode:k,timedOut:
|
|
2843
|
+
if(c)try{const e=await c.createToolRecord({projectId:t.projectId,type:"run-command",metadata:{name:p.name,command:f,exitCode:k,timedOut:b,status:b?"timeout":0===k?"success":"failed",timestamp:(new Date).toISOString()}})
|
|
2837
2844
|
E=e?.id}catch(e){i.debug("Failed to create tool record for command run",{error:(0,n.getErrorMessage)(e)})}l({success:!0})
|
|
2838
2845
|
const q=E?`\n[RECORD:${E}]`:""
|
|
2839
2846
|
return{content:[{type:"text",text:`## ${p.name}${C?` \u2014 ${C} (killed after ${p.timeout}s)`:""}\n\`\`\`\n$ ${f}\n${_}\n\`\`\`\n\nExit code: ${k}${q}`}]}}catch(e){return l({success:!1,error:"api_error"}),{content:[{type:"text",text:"Failed to run command: "+(0,n.getErrorMessage)(e)}],isError:!0}}}
|
|
@@ -2925,12 +2932,12 @@ return o(t,e),t})
|
|
|
2925
2932
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,r,n,o,s,g,p){const f=s.child({tool:"file_recover"}),m=g.startTimer("tool_execution_time"),y=Date.now()
|
|
2926
2933
|
try{let m
|
|
2927
2934
|
try{m=i.FileRecoverSchema.parse(e)}catch(t){if(t instanceof a.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
2928
|
-
return f.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{path:w,commitHash:k,createBackup:
|
|
2929
|
-
return f.info("Recovering file to previous version",{taskId:v,filePath:w,commitHash:k,createBackup:
|
|
2930
|
-
try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:
|
|
2931
|
-
m=
|
|
2932
|
-
let
|
|
2933
|
-
try{await l.access(w),v=!0,n&&(
|
|
2935
|
+
return f.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{path:w,commitHash:k,createBackup:b}=m,{resolveActiveTaskId:I}=await Promise.resolve().then(t.bind(t,3451)),v=e.taskId||await I(r,n,s)||"untracked"
|
|
2936
|
+
return f.info("Recovering file to previous version",{taskId:v,filePath:w,commitHash:k,createBackup:b}),await async function(e,t,r,n,o,s,i,a,g,p,f){let m
|
|
2937
|
+
try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:b}=await d.createFileOperationRecords(e,k?.requestId,o.projectId,"file-recover",y,{operationType:"file",filePath:y,commitHash:r,createBackup:n},s.getTaskClient(),i,a,g,"file-recover",f)
|
|
2938
|
+
m=b
|
|
2939
|
+
let I,v=!1
|
|
2940
|
+
try{await l.access(w),v=!0,n&&(I=`${w}.backup-${(new Date).toISOString().replace(/[:.]/g,"-")}`,await l.copyFile(w,I),a.info("Created backup",{originalPath:w,backupPath:I}))}catch{v=!1}const C=o.git
|
|
2934
2941
|
if(!C)throw Error("Git is not available")
|
|
2935
2942
|
if(!(await(0,u.validateCommitHash)(C,r,a,"file-recover")).valid)throw Error(`Commit hash '${r}' is invalid or not found`)
|
|
2936
2943
|
let _
|
|
@@ -2939,9 +2946,9 @@ if(t.includes("does not exist")||t.includes("not found")||t.includes("Path"))thr
|
|
|
2939
2946
|
throw Error(`Failed to retrieve file '${y}' from commit '${r}': ${t}`)}await l.writeFile(w,_,"utf8")
|
|
2940
2947
|
let E={}
|
|
2941
2948
|
try{const t=`Recover ${y} from ${r.substring(0,8)}`
|
|
2942
|
-
E=await d.commitToGit(e,y,m,m,t,o,a,g,"file-recover"),a.info("Recovery committed via shared utility",{path:y,sourceCommitHash:r,newCommitHash:E.commitHash?.substring(0,8),commitMessage:t})}catch(e){a.warn("Failed to commit recovery via shared utility",{error:e})}if(m)try{await i.updateToolRecord(m,{metadata:{path:y,status:"completed",recoveredLength:_.length,hadBackup:n&&v,backupPath:
|
|
2949
|
+
E=await d.commitToGit(e,y,m,m,t,o,a,g,"file-recover"),a.info("Recovery committed via shared utility",{path:y,sourceCommitHash:r,newCommitHash:E.commitHash?.substring(0,8),commitMessage:t})}catch(e){a.warn("Failed to commit recovery via shared utility",{error:e})}if(m)try{await i.updateToolRecord(m,{metadata:{path:y,status:"completed",recoveredLength:_.length,hadBackup:n&&v,backupPath:I,wasFileCreated:!v,processingTime:Date.now()-p,...E.commitHash&&{commitHash:E.commitHash,previousCommitHash:E.previousCommitHash||void 0}},note:"File recovered successfully from "+r.substring(0,8)})}catch(e){a.warn("Failed to update tool record",{recordError:e})}const q=v?"recovered":"created from recovery"
|
|
2943
2950
|
let S=`\u2705 **File ${q.charAt(0).toUpperCase()+q.slice(1)} Successfully**\n\n`
|
|
2944
|
-
return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&
|
|
2951
|
+
return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&I&&(S+=`**Backup created:** ${c.basename(I)}\n`),S+="**Git status:** Recovery committed\n",S+="\u{1f4a1} **Tip:** The file has been restored to its state at the specified commit.",a.info("File recovery completed successfully",{path:y,commitHash:r,duration:Date.now()-p}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(v,w,k,b,r,n,o,f,g,y,p)}catch(e){const t=Date.now()-y
|
|
2945
2952
|
return f.error("Recovery operation failed",{error:e instanceof Error?e.stack:e+"",duration:t}),m({tool:"file_recover",success:!1}),g.incrementCounter("file_recover_errors",1),{content:[{type:"text",text:"\u274c **Recovery Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
|
|
2946
2953
|
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"
|
|
2947
2954
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,u,h,g,p,f){const m=g.child({tool:"request_operations"})
|
|
@@ -3099,15 +3106,15 @@ if(/^\d+$/.test(e)){const t=parseInt(e,10)
|
|
|
3099
3106
|
return{start:t,end:t}}const t=e.match(/^(\d+)-(\d+)$/)
|
|
3100
3107
|
if(t)return{start:parseInt(t[1],10),end:parseInt(t[2],10)}
|
|
3101
3108
|
if(e.match(/^(\d+(?:,\d+)+)$/)){const t=e.split(",").map((e=>parseInt(e,10)))
|
|
3102
|
-
return{start:Math.min(...t),end:Math.max(...t)}}return null}(p),
|
|
3103
|
-
let
|
|
3104
|
-
k&&
|
|
3109
|
+
return{start:Math.min(...t),end:Math.max(...t)}}return null}(p),b=["blame","--porcelain"]
|
|
3110
|
+
let I
|
|
3111
|
+
k&&b.push(`-L${k.start},${k.end}`),f&&b.push(f),b.push("--",w),c.debug("Executing git blame",{args:b})
|
|
3105
3112
|
try{if(!t.git)throw Error("Git context not available")
|
|
3106
|
-
|
|
3113
|
+
I=await t.git.raw(b)}catch(e){const t=(0,h.getErrorMessage)(e)
|
|
3107
3114
|
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")
|
|
3108
3115
|
let n="",o="",s="",i=0,a=0,c=new Map
|
|
3109
3116
|
for(let e=0;e<r.length;e++){const l=r[e],d=l.match(/^([0-9a-f]{40})\s+\d+\s+(\d+)/)
|
|
3110
|
-
d?(n=d[1],a=parseInt(d[2],10)):l.startsWith("author ")?o=l.substring(7):l.startsWith("author-mail ")?s=l.substring(12).replace(/[<>]/g,""):l.startsWith("author-time ")?i=parseInt(l.substring(12),10):l.startsWith("summary ")?c.set(n,l.substring(8)):l.startsWith("\t")&&t.push({lineNumber:a,commitHash:n,author:o,authorEmail:s,timestamp:i,content:l.substring(1),commitMessage:c.get(n)})}return t}(
|
|
3117
|
+
d?(n=d[1],a=parseInt(d[2],10)):l.startsWith("author ")?o=l.substring(7):l.startsWith("author-mail ")?s=l.substring(12).replace(/[<>]/g,""):l.startsWith("author-time ")?i=parseInt(l.substring(12),10):l.startsWith("summary ")?c.set(n,l.substring(8)):l.startsWith("\t")&&t.push({lineNumber:a,commitHash:n,author:o,authorEmail:s,timestamp:i,content:l.substring(1),commitMessage:c.get(n)})}return t}(I)
|
|
3111
3118
|
if(0===v.length)return{content:[{type:"text",text:"\u274c No blame information found for "+w}],isError:!0}
|
|
3112
3119
|
const C=function(e){if(0===e.length)return[]
|
|
3113
3120
|
const t=[]
|
|
@@ -3176,7 +3183,7 @@ return t.success?(this.logger.info("Successfully removed worktree",{requestId:e.
|
|
|
3176
3183
|
return await this.worktreeManager.getWorktreeInfo(t)||null}catch(t){return this.logger.warn("Failed to get worktree info",{requestId:e,error:(0,i.getErrorMessage)(t)}),null}}getMainGit(){return this.mainGit}}},4973(e,exports,t){"use strict"
|
|
3177
3184
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3178
3185
|
const r=t(6183),n=t(4592)
|
|
3179
|
-
exports.def={name:"planner_ops",description:"
|
|
3186
|
+
exports.def={name:"planner_ops",description:"WHEN TO USE request: when asked to plan/design/architect. Do NOT manually create requests from the plan \u2014 the planner does that.\n\nRequest a planning session and check on planner progress.\n\nAll params are flat (no nested objects). The operation field determines which params apply.\n\nOperations:\n\u2022 request \u2014 prompt required. Optional: description\n\u2022 check-status \u2014 sessionId required\n\u2022 list \u2014 all optional: activeOnly, limit",schema:r.PlannerOpsSchema,annotations:{title:"Planner Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handlePlannerOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5003(e,exports,t){"use strict"
|
|
3180
3187
|
async function r(e,t,r,s,i){const a=r.child({requestId:e,operation:"request-status-validation"})
|
|
3181
3188
|
try{a.info("Validating request status for document operation",{requestId:e})
|
|
3182
3189
|
const r=await t.getRequest(e)
|
|
@@ -3323,10 +3330,10 @@ const m=g.acceptanceCriteria||[],y={unverified:0,partial:0,verified:0,partially_
|
|
|
3323
3330
|
m.forEach((e=>{const t=e.status||"unverified"
|
|
3324
3331
|
t in y&&y[t]++}))
|
|
3325
3332
|
let w=g.testVerification||null
|
|
3326
|
-
const k=g.title,
|
|
3327
|
-
let
|
|
3328
|
-
return
|
|
3329
|
-
|
|
3333
|
+
const k=g.title,b=g.type
|
|
3334
|
+
let I=`# ${"feature"===b?"Feature":"quick-edit"===b?"Quick Edit":"Bug Fix"} Request: ${k} (${t})\nStatus: ${g.status}\nCreated: ${new Date(g.createdAt).toLocaleString()}\nUpdated: ${new Date(g.updatedAt).toLocaleString()}\n\n## Description\n${g.description||"_No description provided._"}\n\n## Progress Summary\n- Tasks: ${f.completed}/${f.total} completed (${Math.round(f.completed/f.total*100)||0}%)\n- Acceptance Criteria: ${y.verified}/${y.total} verified (${Math.round(y.verified/y.total*100)||0}%)\n`
|
|
3335
|
+
return I+=`\n## Task Status\n- Pending: ${f.pending}\n- In Progress: ${f.in_progress}\n- Blocked: ${f.blocked}\n- Ready for Review: ${f.ready_for_review}\n- Completed: ${f.completed}\n- Reverted: ${f.reverted}\n`,I+="\n## Tasks\n",0===p.length?I+="No tasks found for this request.\n":p.forEach((e=>{I+=`**[${e.id}]** ${e.title} (Status: ${e.status})\n`})),d.info(`Added task listing with ${p.length} tasks`),I+="\n## Acceptance Criteria\n",I+=(0,i.formatCriteriaWithHashes)(m)+"\n","ready_for_review"===g.status&&m.some((e=>"verified"!==e.status))&&(I+="\n> **Status: ready_for_review** \u2014 Use the merge operation to verify criteria and merge to main.\n"),w&&(I+=`\n## Test Coverage\n- Test Cases: ${w.totalTestCases||0}\n- Criteria Tested: ${w.criteriaTestedCount||0}/${y.total}\n`,w.criterionCoverage&&Array.isArray(w.criterionCoverage)&&(I+="\n### Detailed Test Coverage:\n",w.criterionCoverage.forEach((e=>{I+=`- Criterion ${e.criterionId}: ${e.coverage} coverage\n`})))),g.recentActivity&&Array.isArray(g.recentActivity)&&(I+="\n## Recent Activity\n",g.recentActivity.slice(0,5).forEach((e=>{const t=new Date(e.timestamp).toLocaleString()
|
|
3336
|
+
I+=`- ${t}: ${e.description}\n`}))),u({success:!0}),{content:[{type:"text",text:I}]}}catch(t){return d.error("Error getting request information",{args:e,error:t instanceof Error?t.stack:t+""}),u({success:!1,error:t instanceof Error?t.name:"unknown"}),t instanceof n.ConnectionError?{content:[{type:"text",text:"Unable to get request information: Connection to the server failed. Please check your network connection and try again."}],isError:!0}:{content:[{type:"text",text:"Error getting request information: "+(0,s.getErrorMessage)(t)}],isError:!0}}}
|
|
3330
3337
|
const r=t(9860),n=t(5674),o=t(2960),s=t(8824),i=t(5454)},5454(e,exports){"use strict"
|
|
3331
3338
|
function t(e,t){let r=0
|
|
3332
3339
|
for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t)|0
|
|
@@ -3426,7 +3433,7 @@ try{await(0,o.createFailureToolRecord)("complete-request",r,{error:s,details:i,r
|
|
|
3426
3433
|
const r=t(9860),n=t(1569),o=t(8616),s=t(8824),i=t(5454)},5767(e,exports,t){"use strict"
|
|
3427
3434
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3428
3435
|
const r=t(6183),n=t(6285)
|
|
3429
|
-
exports.def={name:"specialist_ops",description:"Manage your pool of up to 10 specialists. Each has a specialization describing their domain. Reuse specialists via follow-up before spawning new ones.\n\nAll params are flat (no nested objects). The operation field determines which params apply.\n\nOperations:\n\u2022 delegate \u2014 prompt + specialization required. Optional: description, requestId\n\u2022 follow-up \u2014 prompt + sessionId required
|
|
3436
|
+
exports.def={name:"specialist_ops",description:"Manage your pool of up to 10 specialists. Each has a specialization describing their domain. Reuse specialists via follow-up before spawning new ones.\n\nAll params are flat (no nested objects). The operation field determines which params apply.\n\nOperations:\n\u2022 delegate \u2014 prompt + specialization required. Optional: description, requestId\n\u2022 follow-up \u2014 prompt + sessionId required\n\u2022 check-status \u2014 sessionId required\n\u2022 list \u2014 all params optional: activeOnly, requestId (filter), limit\n\u2022 abort \u2014 sessionId required",schema:r.SpecialistOpsSchema,annotations:{title:"Specialist Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSpecialistOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5802(module){"use strict"
|
|
3430
3437
|
module.exports=require("@modelcontextprotocol/sdk/server/stdio.js")},5806(e,exports,t){"use strict"
|
|
3431
3438
|
function r(){const e=n.z.object({requestId:n.z.string(),summary:n.z.string(),acceptanceEvidence:n.z.array(n.z.object({evidence:n.z.string()}))}),t=n.z.object({testRecords:n.z.array(n.z.string()),coverage:n.z.object({criteriaTestedCount:n.z.number(),totalTestCases:n.z.number()}),criterionCoverage:n.z.array(n.z.object({coverage:n.z.enum(["none","partial","full"]),testRecords:n.z.array(n.z.string())}))})
|
|
3432
3439
|
return(0,o.areTestsRequiredForCompletion)()?e.extend({testVerification:t}):e}Object.defineProperty(exports,"__esModule",{value:!0}),exports.DynamicCompleteRequestSchema=void 0,exports.getDynamicCompleteRequestSchema=r
|
|
@@ -3447,8 +3454,8 @@ var t={}
|
|
|
3447
3454
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3448
3455
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3449
3456
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDeleteFiles=async function(e,r,n,o,s,i){const m=o.child({tool:"delete_files"}),y=Date.now()
|
|
3450
|
-
let w,k,
|
|
3451
|
-
const
|
|
3457
|
+
let w,k,b=l.FileOperationPhase.VALIDATION
|
|
3458
|
+
const I={toolName:"delete-files",operationName:"delete",fileOperationPhase:l.FileOperationPhase.FILE_WRITE,recordType:"delete-files",metricsPrefix:"delete_files",successMessage:"Successfully deleted files",failureMessage:"Failed to delete files"}
|
|
3452
3459
|
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"
|
|
3453
3460
|
let j=[]
|
|
3454
3461
|
if(E)j=E.map((e=>({type:"file",target:e})))
|
|
@@ -3457,22 +3464,22 @@ j=q.map((e=>{if(e.path)return{type:"file",target:e.path}
|
|
|
3457
3464
|
if(e.documentId)return{type:"document",target:e.documentId}
|
|
3458
3465
|
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")
|
|
3459
3466
|
const R=j.filter((e=>"file"===e.type)),x=j.filter((e=>"document"===e.type)),M=j.length
|
|
3460
|
-
m.info("Starting mixed file and document deletion operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,comment:S}),l.validateTaskIdFormat(P,m,s,
|
|
3467
|
+
m.info("Starting mixed file and document deletion operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,comment:S}),l.validateTaskIdFormat(P,m,s,I.metricsPrefix)
|
|
3461
3468
|
const O=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3462
3469
|
m.info("Initial branch context",{initialBranch:O.branch,initialRequestId:O.requestId,isMain:O.isMain})
|
|
3463
3470
|
const D=[]
|
|
3464
3471
|
for(const e of R){const{normalizedPath:t,fullPath:n}=l.validateAndNormalizePath(e.target,r)
|
|
3465
|
-
D.push({normalized:t,full:n})}
|
|
3466
|
-
const $=D.length>0?D[0].normalized:"document_operations",A=await l.validateTaskId(P,$,u,m,s,
|
|
3472
|
+
D.push({normalized:t,full:n})}b=l.FileOperationPhase.TASK_VALIDATION,s.incrementCounter("delete_files_phase",1,{phase:b})
|
|
3473
|
+
const $=D.length>0?D[0].normalized:"document_operations",A=await l.validateTaskId(P,$,u,m,s,I.metricsPrefix),F=A?.requestId,N=await l.validateWorkItemStates(P,$,u,C,r,m,s,I.metricsPrefix),L=await l.autoPromoteTaskStatus(P,A.status,F,N.request?.status,$,u,C,m,s,I.metricsPrefix)
|
|
3467
3474
|
L.taskPromoted&&m.info(`Auto-promoted task ${P} (${A.title||"Untitled"}) to in_progress for mixed operations`,{taskId:P,taskTitle:A.title,previousStatus:A.status,newStatus:L.newTaskStatus,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length}),L.requestPromoted&&m.info(`Auto-promoted request ${F} to in_progress for file operations`,{requestId:F,previousStatus:N.request?.status,newStatus:L.newRequestStatus,triggeringTaskId:P})
|
|
3468
|
-
const z=await l.ensureCorrectWorkspaceContext({taskPromoted:L.taskPromoted,requestId:F,context:r,operation:"delete-files",logger:m,metrics:s,metricsPrefix:
|
|
3475
|
+
const z=await l.ensureCorrectWorkspaceContext({taskPromoted:L.taskPromoted,requestId:F,context:r,operation:"delete-files",logger:m,metrics:s,metricsPrefix:I.metricsPrefix})
|
|
3469
3476
|
if(!z.success){if(z.isLockConflict)return{content:[{type:"text",text:"\u274c "+z.error}],isError:!0}
|
|
3470
3477
|
throw Error(z.error)}let H={hadUserMods:!1,userModsCommitHash:void 0}
|
|
3471
3478
|
if(r.git)try{m.debug("[DELETE-FILES] Checking for user changes before mixed delete operations")
|
|
3472
3479
|
const e=await(0,h.commitUserChangesBeforeToolOperation)(r.git,"delete-files",{requestId:F,taskId:P,workspaceManager:r.workspaceManager},m,s)
|
|
3473
|
-
e.userChangesCommitted&&(m.debug("[DELETE-FILES] User changes committed before mixed delete operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),m.info("User changes committed before mixed delete-files operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),H={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){m.debug("[DELETE-FILES] Pre-tool commit failed, continuing with mixed delete operations",{error:e instanceof Error?e.message:e+""}),m.warn("Pre-tool user changes commit failed, continuing with mixed delete operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,error:e instanceof Error?e.message:e+""})}m.debug("[DELETE-FILES] Proceeding with mixed delete operations",{totalOperations:j.length,fileDeletes:R.length,documentDeletes:x.length}),
|
|
3474
|
-
const{toolRecordId:B,localToolRecordId:U}=await l.createFileOperationRecords(P,F,r.projectId,
|
|
3475
|
-
w=B,k=B,I
|
|
3480
|
+
e.userChangesCommitted&&(m.debug("[DELETE-FILES] User changes committed before mixed delete operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),m.info("User changes committed before mixed delete-files operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),H={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){m.debug("[DELETE-FILES] Pre-tool commit failed, continuing with mixed delete operations",{error:e instanceof Error?e.message:e+""}),m.warn("Pre-tool user changes commit failed, continuing with mixed delete operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,error:e instanceof Error?e.message:e+""})}m.debug("[DELETE-FILES] Proceeding with mixed delete operations",{totalOperations:j.length,fileDeletes:R.length,documentDeletes:x.length}),b=l.FileOperationPhase.RECORD_CREATION,s.incrementCounter("delete_files_phase",1,{phase:b})
|
|
3481
|
+
const{toolRecordId:B,localToolRecordId:U}=await l.createFileOperationRecords(P,F,r.projectId,I.recordType,$,{totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,filePaths:D.map((e=>e.normalized)),documentIds:x.map((e=>e.target)),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},u,v,m,s,I.metricsPrefix,i)
|
|
3482
|
+
w=B,k=B,b=I.fileOperationPhase,s.incrementCounter("delete_files_phase",1,{phase:b})
|
|
3476
3483
|
const G=[]
|
|
3477
3484
|
let W=0
|
|
3478
3485
|
x.length>0&&n.setProjectId(r.projectId)
|
|
@@ -3487,12 +3494,12 @@ throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${
|
|
|
3487
3494
|
r.success=!0,r.filename=o.filename,W++,m.info("Document archived successfully",{documentId:o.id,filename:o.filename,archivedAt:o.archived_at})}catch(e){r.error=(0,f.getErrorMessage)(e),m.warn("Failed to delete document "+t,{error:r.error})}G.push(r)}const J=Date.now()-y
|
|
3488
3495
|
s.recordValue("delete_files_time",J),s.incrementCounter("delete_files_operations_total",M),s.incrementCounter("delete_files_operations_success",W),s.incrementCounter("delete_files_operations_failed",M-W),s.incrementCounter("delete_files_file_operations",R.length),s.incrementCounter("delete_files_document_operations",x.length),W===M?s.incrementCounter("delete_files_success",1):W>0?s.incrementCounter("delete_files_partial_success",1):s.incrementCounter("delete_files_total_failure",1)
|
|
3489
3496
|
let K=null
|
|
3490
|
-
if(W>0){
|
|
3497
|
+
if(W>0){b=l.FileOperationPhase.GIT_COMMIT,s.incrementCounter("delete_files_phase",1,{phase:b})
|
|
3491
3498
|
const e=G.filter((e=>e.success)),t=e.filter((e=>"file"===e.type)).length,n=e.filter((e=>"document"===e.type)).length
|
|
3492
3499
|
let o
|
|
3493
|
-
o=t>0&&n>0?`Delete ${t} files and ${n} documents - ${S}`:t>0?1===t?"Delete file - "+S:`Delete ${t} files - ${S}`:1===n?"Delete document - "+S:`Delete ${n} documents - ${S}`,K=await l.commitToGit(P,$,B,U,o,r,m,s,
|
|
3500
|
+
o=t>0&&n>0?`Delete ${t} files and ${n} documents - ${S}`:t>0?1===t?"Delete file - "+S:`Delete ${t} files - ${S}`:1===n?"Delete document - "+S:`Delete ${n} documents - ${S}`,K=await l.commitToGit(P,$,B,U,o,r,m,s,I.metricsPrefix)}b=l.FileOperationPhase.RECORD_UPDATE_SUCCESS,s.incrementCounter("delete_files_phase",1,{phase:b})
|
|
3494
3501
|
const Y=G.filter((e=>e.success)),Q=G.filter((e=>!e.success))
|
|
3495
|
-
await l.updateFileOperationRecords(P,w,k,$,
|
|
3502
|
+
await l.updateFileOperationRecords(P,w,k,$,I.recordType,W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,{status:W===M?"completed":"partial_success",commitHash:K?.commitHash,previousCommitHash:K?.previousCommitHash,totalOperations:M,fileOperations:R.length,documentOperations:x.length,successCount:W,failureCount:M-W,successfulOperations:Y.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename}))),failedOperations:Q.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,error:e.error}))),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,u,v,m,s,I.metricsPrefix)
|
|
3496
3503
|
const Z=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3497
3504
|
let X=""
|
|
3498
3505
|
if(W===M){const e=Y.filter((e=>"file"===e.type)).length,t=Y.filter((e=>"document"===e.type)).length
|
|
@@ -3501,10 +3508,10 @@ return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n"):"All delete operations
|
|
|
3501
3508
|
return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n")
|
|
3502
3509
|
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)
|
|
3503
3510
|
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
|
|
3504
|
-
await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:r.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,f.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:
|
|
3505
|
-
if(s.recordValue("delete_files_time",o),s.incrementCounter("delete_files_errors",1),m.error("Error in delete-files operation:",{error:(0,f.getErrorMessage)(t),time:o}),(w||k)&&e.taskId){
|
|
3511
|
+
await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:r.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,f.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:s},note:"Failed to delete files - "+(0,f.getErrorMessage)(t)})}catch(t){m.error("Failed to create failure record for delete-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0})}const o=Date.now()-y
|
|
3512
|
+
if(s.recordValue("delete_files_time",o),s.incrementCounter("delete_files_errors",1),m.error("Error in delete-files operation:",{error:(0,f.getErrorMessage)(t),time:o}),(w||k)&&e.taskId){b=l.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
3506
3513
|
try{const r=n.getTaskClient(),o=n.getToolRecordClient()
|
|
3507
|
-
await l.updateFileOperationRecords(e.taskId,w,k,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",
|
|
3514
|
+
await l.updateFileOperationRecords(e.taskId,w,k,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",I.recordType,"Failed to delete operations",{status:"failed",error:(0,f.getErrorMessage)(t),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment},"Failed to delete operations",r,o,m,s,I.metricsPrefix)}catch(t){m.error("Failed to update record with failure status",{taskId:e.taskId,recordId:w,error:t instanceof Error?t.message:t+""})}}return l.handleFileOperationError(t,b,m,s,e,I)}}
|
|
3508
3515
|
const a=i(t(1943)),c=t(6183),l=s(t(5967)),d=t(9860),u=t(1569),h=t(7478),g=t(5003),p=t(9949),f=t(8824)},5997(e,exports,t){"use strict"
|
|
3509
3516
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
3510
3517
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
@@ -3574,7 +3581,7 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranc
|
|
|
3574
3581
|
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)"})
|
|
3575
3582
|
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" }'})}))
|
|
3576
3583
|
const a=r.z.string().min(1).describe("OpenCode session ID")
|
|
3577
|
-
exports.SubagentOperationsSchema=r.z.object({sessionId:a.optional(),operation:r.z.enum(["spawn","continue","check-status","abort","read-messages","list-sessions"]),prompt:r.z.string().min(1).describe("Instructions for the subagent (required for spawn and continue)").optional(),agent:r.z.string().default("work").refine((e=>(0,n.isValidAgent)(e)),{message:"Invalid agent. Check tool description for available agents."}).describe("The subagent type to spawn (see tool description for available agents)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, spawn only)").optional(),requestId:r.z.string().describe("Request ID \u2014 associates work (spawn) or filters results (list-sessions)").optional(),allowParallel:r.z.boolean().describe("Allow spawning even if request already has active workers (spawn only)").optional(),useExistingSession:r.z.string().describe("Existing session ID to send prompt to instead of creating new session (spawn only)").optional(),limit:r.z.number().min(1).max(100).describe("Max items to return (read-messages: max 50, list-sessions: max 100)").optional(),activeOnly:r.z.boolean().describe("Only show sessions that are currently active/busy (list-sessions only)").optional(),minTokens:r.z.number().min(0).describe("Only show sessions with at least this many tokens (list-sessions only)").optional(),maxTokens:r.z.number().min(0).describe("Only show sessions with at most this many tokens (list-sessions only)").optional(),maxAgeHours:r.z.number().min(0).describe("Only show sessions newer than X hours (list-sessions only)").optional()}).refine((e=>"spawn"===e.operation?!!e.prompt:"continue"===e.operation?!!e.prompt&&!!e.sessionId:"check-status"===e.operation||"abort"===e.operation||"read-messages"===e.operation?!!e.sessionId:"list-sessions"===e.operation),{message:"spawn requires prompt; continue requires prompt+sessionId; check-status/abort/read-messages require sessionId"}),exports.SpecialistOpsSchema=r.z.object({operation:r.z.enum(["delegate","follow-up","check-status","list","abort"]),sessionId:a.optional(),prompt:r.z.string().min(1).describe("Instructions for the specialist (required for delegate and follow-up)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, delegate only)").optional(),specialization:r.z.string().max(500).describe('Domain description (e.g. "Frontend UI components"). Required for delegate
|
|
3584
|
+
exports.SubagentOperationsSchema=r.z.object({sessionId:a.optional(),operation:r.z.enum(["spawn","continue","check-status","abort","read-messages","list-sessions"]),prompt:r.z.string().min(1).describe("Instructions for the subagent (required for spawn and continue)").optional(),agent:r.z.string().default("work").refine((e=>(0,n.isValidAgent)(e)),{message:"Invalid agent. Check tool description for available agents."}).describe("The subagent type to spawn (see tool description for available agents)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, spawn only)").optional(),requestId:r.z.string().describe("Request ID \u2014 associates work (spawn) or filters results (list-sessions)").optional(),allowParallel:r.z.boolean().describe("Allow spawning even if request already has active workers (spawn only)").optional(),useExistingSession:r.z.string().describe("Existing session ID to send prompt to instead of creating new session (spawn only)").optional(),limit:r.z.number().min(1).max(100).describe("Max items to return (read-messages: max 50, list-sessions: max 100)").optional(),activeOnly:r.z.boolean().describe("Only show sessions that are currently active/busy (list-sessions only)").optional(),minTokens:r.z.number().min(0).describe("Only show sessions with at least this many tokens (list-sessions only)").optional(),maxTokens:r.z.number().min(0).describe("Only show sessions with at most this many tokens (list-sessions only)").optional(),maxAgeHours:r.z.number().min(0).describe("Only show sessions newer than X hours (list-sessions only)").optional()}).refine((e=>"spawn"===e.operation?!!e.prompt:"continue"===e.operation?!!e.prompt&&!!e.sessionId:"check-status"===e.operation||"abort"===e.operation||"read-messages"===e.operation?!!e.sessionId:"list-sessions"===e.operation),{message:"spawn requires prompt; continue requires prompt+sessionId; check-status/abort/read-messages require sessionId"}),exports.SpecialistOpsSchema=r.z.object({operation:r.z.enum(["delegate","follow-up","check-status","list","abort"]),sessionId:a.optional(),prompt:r.z.string().min(1).describe("Instructions for the specialist (required for delegate and follow-up)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, delegate only)").optional(),specialization:r.z.string().max(500).describe('Domain description (e.g. "Frontend UI components"). Required for delegate').optional(),requestId:r.z.string().describe("Request ID \u2014 associates work (delegate) or filters results (list)").optional(),activeOnly:r.z.boolean().describe("Only show active/busy specialists (list only)").optional(),limit:r.z.number().min(1).max(100).describe("Max sessions to return (list only)").optional()}).refine((e=>"delegate"===e.operation?!!e.prompt&&!!e.specialization&&!e.sessionId:"follow-up"===e.operation?!!e.prompt&&!!e.sessionId:"check-status"===e.operation||"abort"===e.operation?!!e.sessionId:"list"===e.operation),{message:"delegate requires prompt+specialization; follow-up requires prompt+sessionId; check-status/abort require sessionId"}),exports.PlannerOpsSchema=r.z.object({operation:r.z.enum(["request","check-status","list"]),sessionId:a.optional(),prompt:r.z.string().min(1).describe("What to plan \u2014 feature description, architecture question, etc. (required for request)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, request only)").optional(),activeOnly:r.z.boolean().describe("Only show active/busy planning sessions (list only)").optional(),limit:r.z.number().min(1).max(100).describe("Max sessions to return (list only)").optional()}).refine((e=>"request"===e.operation?!!e.prompt:"check-status"===e.operation?!!e.sessionId:"list"===e.operation),{message:"request requires prompt; check-status requires sessionId"}),exports.SwitchToRequestBranchSchema=r.z.object({requestId:s}),exports.InsertLinesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceLinesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.CreateDocumentSchema=r.z.object({requestId:s.optional(),filename:r.z.string().refine((e=>e.toLowerCase().endsWith(".md")),{message:"Filename must end with .md extension"}),content:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"],{errorMap(){return{message:"Document type must be one of: Report, Documentation, Plan, Other"}}}),comment:r.z.string()}),exports.SearchDocumentsSchema=r.z.object({query:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),requestId:s.optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both")}),exports.DocumentOperationsSchema=r.z.object({operation:r.z.enum(["create","search","create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"]),documentId:i.optional(),requestId:s.optional(),filename:r.z.string().optional(),content:r.z.string().optional(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),comment:r.z.string().optional(),query:r.z.string().optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional(),selectedText:r.z.string().optional(),prefixContext:r.z.string().optional(),suffixContext:r.z.string().optional(),lineHint:r.z.number().int().optional(),body:r.z.string().optional(),annotationId:r.z.string().optional()}).superRefine(((e,t)=>{const r=e.operation;["create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"].includes(r)&&!e.documentId&&t.addIssue({code:"custom",message:`documentId is required for '${r}'. Example: { "operation": "${r}", "documentId": "doc000001" }`}),"create"===r&&(e.filename?e.filename.toLowerCase().endsWith(".md")||t.addIssue({code:"custom",message:"Filename must end with .md extension"}):t.addIssue({code:"custom",message:"filename is required for create (must end with .md)"}),e.content||t.addIssue({code:"custom",message:"content is required for create"}),e.type||t.addIssue({code:"custom",message:"type is required for create (Report, Documentation, Plan, or Other)"}),e.comment||t.addIssue({code:"custom",message:"comment is required for create"})),"search"!==r||e.query||t.addIssue({code:"custom",message:'query is required for search. Example: { "operation": "search", "query": "search term" }'}),"get-version"!==r&&"restore-version"!==r||e.versionNumber||t.addIssue({code:"custom",message:`versionNumber is required for '${r}'`}),"create-annotation"===r&&(e.selectedText||t.addIssue({code:"custom",message:"selectedText is required for create-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for create-annotation"})),"reply-to-annotation"===r&&(e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for reply-to-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for reply-to-annotation"})),"resolve-annotation"!==r||e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for resolve-annotation"})}))
|
|
3578
3585
|
const c=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^plan\d{6}$/.test(e))),{message:"Plan ID must match format: doc_[26 alphanumeric] (ULID) or plan###### (local ID)"})
|
|
3579
3586
|
exports.PlanReadSchema=r.z.object({operation:r.z.enum(["get","get-active","list","get-history","get-requests"]),planId:c.optional(),searchQuery:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["createdAt","updatedAt","filename"]).default("updatedAt"),sortDirection:r.z.enum(["ASC","DESC"]).default("DESC")}).superRefine(((e,t)=>{["get","get-history","get-requests"].includes(e.operation)&&!e.planId&&t.addIssue({code:"custom",message:`planId is required for '${e.operation}'. Example: { "operation": "${e.operation}", "planId": "plan000001" }`})})),exports.PlanWriteSchema=r.z.object({operation:r.z.enum(["update","append","replace","create-snapshot","restore","set-active"]),planId:c,content:r.z.string().optional(),name:r.z.string().optional().describe("Optional new name for the plan"),old:r.z.string().optional().describe("Text to find in the plan (for replace)"),new:r.z.string().optional().describe("Replacement text (for replace)"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional()}).superRefine(((e,t)=>{const r=e.operation
|
|
3580
3587
|
"update"!==r&&"append"!==r||e.content||t.addIssue({code:"custom",message:`content is required for '${r}'. Example: { "operation": "${r}", "planId": "plan000001", "content": "..." }`}),"replace"===r&&(e.old||t.addIssue({code:"custom",message:'old is required for replace. Example: { "operation": "replace", "planId": "plan000001", "old": "find this", "new": "replace with" }'}),void 0===e.new&&t.addIssue({code:"custom",message:"new is required for replace"})),"restore"!==r||e.versionNumber||t.addIssue({code:"custom",message:'versionNumber is required for restore. Example: { "operation": "restore", "planId": "plan000001", "versionNumber": 1 }'})})),exports.SwitchToMainBranchSchema=r.z.object({}),exports.SwitchToBranchSchema=r.z.object({branch:r.z.string().optional(),password:r.z.string().optional()}),exports.RevertRequestSchema=r.z.object({requestId:s,reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}),exports.ModifyFileSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),operationType:r.z.enum(["replace-string","insert-lines","replace-lines","delete-string","delete-lines"]),replaceString:r.z.object({replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).optional(),insertLines:r.z.object({insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).optional(),replaceLines:r.z.object({replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).optional(),deleteString:r.z.object({patterns:r.z.array(r.z.string()),mode:r.z.enum(["all","unique"]).optional()}).optional(),deleteLines:r.z.object({lines:r.z.string()}).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}).refine((e=>"replace-string"===e.operationType?e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"insert-lines"===e.operationType?e.insertLines&&!e.replaceString&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"replace-lines"===e.operationType?e.replaceLines&&!e.replaceString&&!e.insertLines&&!e.deleteString&&!e.deleteLines:"delete-string"===e.operationType?e.deleteString&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteLines:"delete-lines"===e.operationType&&e.deleteLines&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString),{message:"Invalid operation data"})),comment:r.z.string()}),exports.ManageFilesSchema=r.z.object({operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files","get-file-info"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}))}).optional(),getFileInfo:r.z.object({path:r.z.string()}).optional()}).refine((e=>"create-directory"===e.operationType?e.createDirectory&&!e.moveFiles&&!e.deleteFiles&&!e.getFileInfo:"move-files"===e.operationType?e.moveFiles&&!e.createDirectory&&!e.deleteFiles&&!e.getFileInfo:"delete-files"===e.operationType?e.deleteFiles&&!e.createDirectory&&!e.moveFiles&&!e.getFileInfo:"get-file-info"===e.operationType&&e.getFileInfo&&!e.createDirectory&&!e.moveFiles&&!e.deleteFiles),{message:"Invalid operation data"})),comment:r.z.string()}),exports.RequestOperationsSchema=r.z.object({requestId:s.optional(),operation:r.z.enum(["complete","merge","approve","revert","get-info","list","search","delete-empty"]),complete:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({summary:r.z.string()})).optional(),merge:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({verifications:r.z.array(r.z.object({key:r.z.string().min(2).max(4),evidence:r.z.string().min(1)})).min(1)})).optional(),revert:r.z.object({reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}).optional(),list:r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}).optional(),search:r.z.object({query:r.z.string().min(1),searchIn:r.z.enum(["title","description","criteria","all"]).default("all"),filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0)}).optional()}).optional(),approve:r.z.object({}).optional()}).superRefine(((e,t)=>{e.requestId
|
|
@@ -3597,8 +3604,8 @@ return o(t,e),t})
|
|
|
3597
3604
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,p){const f=n.child({tool:"specialist_ops"}),m=o.startTimer("tool_execution_time")
|
|
3598
3605
|
try{if(e?.delegate&&"object"==typeof e.delegate){const t=e.delegate
|
|
3599
3606
|
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
|
|
3600
|
-
e.prompt=e.prompt||t.prompt,
|
|
3601
|
-
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))
|
|
3607
|
+
e.prompt=e.prompt||t.prompt,delete e.followUp}if(e?.list&&"object"==typeof e.list){const t=e.list
|
|
3608
|
+
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.specialization,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))
|
|
3602
3609
|
const n=c.validateArgs(e,a.SpecialistOpsSchema),{operation:y,sessionId:w}=n
|
|
3603
3610
|
let k
|
|
3604
3611
|
switch(f.info("Processing specialist_ops",{operation:y,sessionId:w}),y){case"delegate":{const e=10,o=p?.sessionId||g.sessionIdentity.getIdentity()?.sessionId
|
|
@@ -3631,9 +3638,7 @@ if(e)try{const t=await fetch(e.replace(/\/$/,"")+"/session/status")
|
|
|
3631
3638
|
if(t.ok){const e=await t.json(),r=e[w]?.type
|
|
3632
3639
|
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}
|
|
3633
3640
|
break}}}catch{}k=await(0,u.handleContinue)(w,n.prompt,r,f,s,"specialist",p)
|
|
3634
|
-
|
|
3635
|
-
if(t&&s)try{const e=s.getCLISessionClient()
|
|
3636
|
-
e&&(await e.createOrUpdateSession({externalSessionId:w,specialization:t}),k.content[0].text+="\nSpecialization updated to: "+t)}catch{}break}case"check-status":k=await(0,u.handleCheckStatus)(w,r,f,s)
|
|
3641
|
+
break}case"check-status":k=await(0,u.handleCheckStatus)(w,r,f,s)
|
|
3637
3642
|
break
|
|
3638
3643
|
case"abort":if(k=await(0,u.handleAbort)(w,r,f),!k.isError&&s)try{const e=s.getCLISessionClient()
|
|
3639
3644
|
e&&await e.createOrUpdateSession({externalSessionId:w,status:"archived"})}catch{}break
|
|
@@ -3722,7 +3727,7 @@ var t={}
|
|
|
3722
3727
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
3723
3728
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3724
3729
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleInsertLines=async function(e,n,o,s,i,a,m,y){const w=a.child({tool:"insert_lines"}),k=Date.now()
|
|
3725
|
-
let I,
|
|
3730
|
+
let b,I,v=d.FileOperationPhase.VALIDATION
|
|
3726
3731
|
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"}
|
|
3727
3732
|
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"
|
|
3728
3733
|
if(w.info("Inserting lines into files and documents",{taskId:T,operationCount:E.length,comment:q}),!E||0===E.length)throw new u.ValidationError("At least one operation is required")
|
|
@@ -3748,7 +3753,7 @@ for(let e=0;e<R.length;e++){const t=R[e],r=P[e],{normalizedPath:o,fullPath:s}=d.
|
|
|
3748
3753
|
R[e]={...t,path:o,fullPath:s}}}if(x.length>0&&D)try{await(0,h.validateRequestStatusForDocumentOperation)(D,i,w,m,"insert-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3749
3754
|
throw e}v=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("insert_lines_phase",1,{phase:v})
|
|
3750
3755
|
const N=[...R.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...x.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:L}=await d.createFileOperationRecords(T,D,n.projectId,C.recordType,M,{operationCount:E.length,fileOperations:R.length,documentOperations:x.length,operations:N,userComment:q},o,s,w,m,C.metricsPrefix,y)
|
|
3751
|
-
if(
|
|
3756
|
+
if(b=L,I=L,v=C.fileOperationPhase,m.incrementCounter("insert_lines_phase",1,{phase:v}),R.length>0&&n.git)try{w.debug("[INSERT-LINES] Checking for user changes before insert operations")
|
|
3752
3757
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"insert-lines",{requestId:D,taskId:T,workspaceManager:n.workspaceManager},w,m)
|
|
3753
3758
|
e.userChangesCommitted&&(w.debug("[INSERT-LINES] User changes committed before insert operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before insert-lines operation",{taskId:T,fileOperationsCount:R.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[INSERT-LINES] Pre-tool commit failed, continuing with insertions",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with insert operation",{taskId:T,fileOperationsCount:R.length,error:e instanceof Error?e.message:e+""})}w.debug("[INSERT-LINES] Proceeding with file operations",{fileCount:R.length})
|
|
3754
3759
|
const z=[]
|
|
@@ -3761,8 +3766,8 @@ try{const o=await n.documentFileManager.getDocumentAsFile(e.documentId),s=n.docu
|
|
|
3761
3766
|
t.filename=s?.filename
|
|
3762
3767
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.insertions)
|
|
3763
3768
|
t.insertions=l,t.successfulInsertions=l.filter((e=>e.success)).length,t.failedInsertions=l.filter((e=>!e.success)).length,t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulInsertions>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,U++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedInsertions=e.insertions.length,H+=t.failedInsertions,w.error("Document operation failed",{documentId:e.documentId,error:t.error})}z.push(t)}if(x.length>0)try{for(const e of x){const t=z.find((t=>t.documentId===e.documentId))
|
|
3764
|
-
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const G=await d.handleMultiFileGitCommit(T,R,z,U,{operationType:"Insert lines",toolRecordId:
|
|
3765
|
-
try{await s.updateToolRecord(
|
|
3769
|
+
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const G=await d.handleMultiFileGitCommit(T,R,z,U,{operationType:"Insert lines",toolRecordId:I,successField:"successfulInsertions",logger:w,metrics:m,metricsPrefix:"insert_lines"},n),W=d.processMultiFileOperationResults(z,"successfulInsertions"),{successfulOperations:V,failedOperations:J,totalSuccessfulChanges:K,overallSuccess:Y,successfulFiles:Q,failedFiles:Z}=W
|
|
3770
|
+
try{await s.updateToolRecord(I,{metadata:{path:R.length>0?R[0].path:"document:"+x[0]?.documentId,status:Y?"completed":"failed",error:Y?void 0:J+" operations failed",totalOperations:z.length,successfulFiles:Q,failedFiles:Z,operations:N,totalSuccessfulInsertions:K,totalFailedInsertions:H,totalLinesAdded:B,operationsWithChanges:U,processingTime:Date.now()-k,userComment:q,...R.length>0&&G.success&&G.commitHash&&{commitHash:G.commitHash,previousCommitHash:G.previousCommitHash||void 0}},note:Y?`Line insertion completed: ${V}/${z.length} operations successful${R.length>0?" (committed to git)":""}`:`Line insertion partially failed: ${J}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let X="## Line Insertion Results\n\n"
|
|
3766
3771
|
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
3767
3772
|
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]
|
|
3768
3773
|
if(X+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?X+=`**File:** ${e.path}\n`:(X+="**Document:** "+e.documentId,e.filename&&(X+=` (${e.filename})`),X+="\n"),e.error?X+=`**Error:** ${e.error}\n`:(X+=`**Insertions:** ${e.successfulInsertions} successful`,e.failedInsertions>0&&(X+=`, ${e.failedInsertions} failed`),X+="\n",X+=`**Lines Added:** ${e.totalLinesAdded}\n`),e.insertions.some((e=>!e.success))){X+="**Failed Insertion Details:**\n"
|
|
@@ -3773,33 +3778,33 @@ for(const t of e.insertions.filter((e=>!e.success))){const e="between"===t.type?
|
|
|
3773
3778
|
X+=` - ${t.type} insertion ${e}: ${t.error}\n`}}X+="\n"}}x.length>0&&(X+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3774
3779
|
const ee=Date.now()-k
|
|
3775
3780
|
return w.info("Insert lines operation completed",{duration:ee,success:Y,totalOperations:z.length,successfulOperations:V,failedOperations:J}),m.incrementCounter("insert_lines_total",1,{success:Y}),{content:[{type:"text",text:X}],isError:!Y}}catch(t){const r=Date.now()-k
|
|
3776
|
-
if(w.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),
|
|
3781
|
+
if(w.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),I)try{await s.updateToolRecord(I,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,f.getErrorMessage)(t),phase:v,duration:r,userComment:e?.comment},note:"Line insertion failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return m.incrementCounter("insert_lines_errors",1,{phase:v}),{content:[{type:"text",text:"\u274c **Insert Lines Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
|
|
3777
3782
|
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824),m=t(3255)},6539(e,exports,t){"use strict"
|
|
3778
3783
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientFactory=void 0
|
|
3779
3784
|
const r=t(1253),n=t(5681),o=t(6595),s=t(3895),i=t(6848),a=t(6153),c=t(4710),l=t(6975),d=t(1887),u=t(1666),h=t(8824),g=t(9884),p=t(2968),f=t(922)
|
|
3780
3785
|
exports.ClientFactory=class{static async createClient(e,m,y,w={}){(m=m.child({component:"client-factory"})).info("Creating API client with components")
|
|
3781
3786
|
const k=w.tokenManager||new r.TokenManager(m,w.workingDir||process.cwd())
|
|
3782
3787
|
await k.initialize()
|
|
3783
|
-
const
|
|
3784
|
-
|
|
3788
|
+
const b=w.tokenSynchronizer||new i.ClientTokenSynchronizer(m),I=new s.AuthenticationManager(k,m,b),v=await I.getTokenString(),C=w.connectionStatusManager||new n.ConnectionStatusManager(e,m,y,{alchemyPath:w.alchemyPath,checkIntervalMs:w.offlineCheckIntervalMs,timeoutMs:w.timeout,retryCount:w.retryAttempts}),_=new c.ProjectClient(e,m,y,C,v||void 0,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3789
|
+
b.registerClient(_),w.alchemyPath&&_.setAlchemyPath(w.alchemyPath)
|
|
3785
3790
|
const E=new p.TaskClient(e,m,y,_,C,v||void 0,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3786
|
-
|
|
3791
|
+
b.registerClient(E)
|
|
3787
3792
|
const q=new a.FileOperationsClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3788
|
-
|
|
3793
|
+
b.registerClient(q),m.info("RequestClient constructor received token: "+(v?"present":"missing"))
|
|
3789
3794
|
const S=new u.RequestClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3790
|
-
|
|
3795
|
+
b.registerClient(S),m.info("RequestClient post-constructor token: "+(S.getAuthToken()?"present":"missing"))
|
|
3791
3796
|
const T=new g.DocumentClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3792
|
-
|
|
3797
|
+
b.registerClient(T)
|
|
3793
3798
|
const P=new f.ToolRecordClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3794
|
-
|
|
3799
|
+
b.registerClient(P)
|
|
3795
3800
|
const j=new d.ProxyClient(e,m,y,_,v||void 0,C,{timeout:w.timeout,retryAttempts:w.retryAttempts,retryDelay:w.retryDelay,circuitBreakerThreshold:w.circuitBreakerThreshold,circuitBreakerResetTime:w.circuitBreakerResetTime})
|
|
3796
|
-
if(
|
|
3801
|
+
if(b.registerClient(j),!w.alchemyPath)throw Error("alchemyPath is required for ProjectSynchronizer creation. Cannot create API client without project synchronization capabilities.")
|
|
3797
3802
|
try{m.info("Creating ProjectSynchronizer components")
|
|
3798
3803
|
const{ProjectRegistry,ProjectFileSystem,ProjectSynchronizer}=await t.e(478).then(t.bind(t,5478)),e=new ProjectRegistry(m),r=new ProjectFileSystem(m),n=new ProjectSynchronizer(m,e,new l.ProjectClientAdapter(_,m),r,{createRemoteProjects:!0})
|
|
3799
3804
|
_.setProjectSynchronizer(n),m.info("ProjectSynchronizer created and connected to ProjectClient")}catch(e){const t="Failed to create required ProjectSynchronizer components: "+(0,h.getErrorMessage)(e)
|
|
3800
|
-
throw m.error(t,{error:e instanceof Error?e.stack:e+""}),Error(t)}const R=new o.ApiClient(
|
|
3805
|
+
throw m.error(t,{error:e instanceof Error?e.stack:e+""}),Error(t)}const R=new o.ApiClient(I,_,E,q,S,T,P,j,m)
|
|
3801
3806
|
m.info("API client initialized with specialized clients"),v?(R.setAuthToken(v),m.info("Auth token set on ApiClient during creation",{hasToken:!0,tokenLength:v.length})):m.warn("No auth token available during ApiClient creation",{info:"Client will need to authenticate before making requests"})
|
|
3802
|
-
const x=
|
|
3807
|
+
const x=b.verifyAllClients()
|
|
3803
3808
|
x.success?m.info("Token consistency verified across all clients"):m.error(`Token inconsistency detected in ${x.failedClients.length} clients: ${x.failedClients.join(", ")}`)
|
|
3804
3809
|
const M=R.getAuthToken()
|
|
3805
3810
|
return v&&!M?(m.error("CRITICAL: ApiClient token was not set properly!"),R.setAuthToken(v)):M&&m.info("ApiClient token verified",{tokenLength:M.length,matches:M===v}),m.info("API client creation completed successfully"),R}}},6540(e,exports){"use strict"
|
|
@@ -3813,10 +3818,10 @@ Object.defineProperty(exports,"__esModule",{value:!0})
|
|
|
3813
3818
|
const o=t(5802),s=n(t(6928)),i=t(184),a=t(3444),c=t(1152),l=t(8851),d=t(8411),u=n(t(9896)),h=t(4139),g=t(8824),p=t(9939),f=t(7960),m=process.argv.slice(2),y=m[0]||process.cwd(),w=s.default.resolve(y)
|
|
3814
3819
|
console.error("\n=== MCP STARTUP DIAGNOSTICS ==="),console.error("Script path (process.argv[1]):",process.argv[1]),console.error("Base directory:",w),console.error("ENABLE_DEBUG_TOOLS env:",process.env.ENABLE_DEBUG_TOOLS),console.error("DEBUG_LOGGING env:",process.env.DEBUG_LOGGING),console.error("isDevBuild():",(0,f.isDevBuild)()),console.error("isDebugToolsEnabled():",(0,a.isDebugToolsEnabled)()),console.error("===============================\n")
|
|
3815
3820
|
const k=(0,a.createEnvLogger)({serviceName:"direct-mcp-server",console:!0,baseDir:w});(0,a.isDebugToolsEnabled)()?k.info("MCP Direct server initializing",{baseDir:w,debugLogging:process.env.DEBUG_LOGGING,debugLevel:process.env.DEBUG_LEVEL,pid:process.pid}):k.info("MCP Direct server starting"),console.log=function(...e){console.error("[LOG]",...e)},console.info=function(...e){console.error("[INFO]",...e)},console.warn=function(...e){console.error("[WARN]",...e)},process.on("uncaughtException",(e=>{if(k.error("UNCAUGHT EXCEPTION: "+e,{stack:e.stack||"No stack available"}),_)try{_.cleanupSSEConnection()}catch(e){k.error("Error during cleanup after uncaught exception: "+e)}setTimeout((()=>process.exit(1)),500)})),process.on("unhandledRejection",(e=>{k.error("UNHANDLED REJECTION: "+e,{stack:e instanceof Error?e.stack:"No stack available"})})),process.on("exit",(e=>{k.info("Process exiting with code: "+e)}))
|
|
3816
|
-
const
|
|
3817
|
-
process.stdout.write=function(e,t,r){try{if("string"==typeof e)try{JSON.parse(e)}catch(t){return e.includes('"__message_type"')||(process.stderr.write("[STDOUT REDIRECTED]: "+e),r&&r()),!0}return"string"==typeof t&&"function"==typeof r?
|
|
3821
|
+
const b=process.stdout.write
|
|
3822
|
+
process.stdout.write=function(e,t,r){try{if("string"==typeof e)try{JSON.parse(e)}catch(t){return e.includes('"__message_type"')||(process.stderr.write("[STDOUT REDIRECTED]: "+e),r&&r()),!0}return"string"==typeof t&&"function"==typeof r?b.call(process.stdout,e,t,r):"function"==typeof t?b.call(process.stdout,e,void 0,t):b.call(process.stdout,e)}catch(e){return process.stderr.write("[STDOUT ERROR]: "+e),!0}},(0,a.isDebugToolsEnabled)()&&(k.info("Initialized stdout filtering to ensure only valid JSON is sent"),k.info("!!!MARKER!!! COMMAND-LINE ARGS:",{args:JSON.stringify(m)}),k.info("!!!MARKER!!! BASE DIRECTORY:",{baseDir:y}),k.info("!!!MARKER!!! ABSOLUTE BASE DIR:",{absBaseDir:w}),k.info("Working with base directory:",{absBaseDir:w}))
|
|
3818
3823
|
try{if(u.default.existsSync(w)||(k.warn(`Base directory ${w} does not exist. Creating it...`),u.default.mkdirSync(w,{recursive:!0})),(0,a.isDebugToolsEnabled)()){const e=s.default.join(w,".mcp-test-file")
|
|
3819
|
-
u.default.writeFileSync(e,(new Date).toISOString()),k.info("Successfully wrote test file to "+e),u.default.unlinkSync(e),k.info("Successfully deleted test file"),k.info(`Confirmed base directory ${w} exists and is accessible`)}}catch(e){k.error(`Error accessing base directory ${w}:`,{error:e}),k.warn("This may cause issues with file operations - please check permissions")}const
|
|
3824
|
+
u.default.writeFileSync(e,(new Date).toISOString()),k.info("Successfully wrote test file to "+e),u.default.unlinkSync(e),k.info("Successfully deleted test file"),k.info(`Confirmed base directory ${w} exists and is accessible`)}}catch(e){k.error(`Error accessing base directory ${w}:`,{error:e}),k.warn("This may cause issues with file operations - please check permissions")}const I=(0,c.createMetricsCollector)(!1)
|
|
3820
3825
|
let v=process.env.REMOTE_SERVER_URL||"https://api.alchemylabcode.com"
|
|
3821
3826
|
const C=global.__serverInitialized
|
|
3822
3827
|
void 0===C?(global.__serverInitialized=!1,(0,a.isDebugToolsEnabled)()&&k.info("FIRST RUN: Setting global.__serverInitialized to false")):(0,a.isDebugToolsEnabled)()&&k.info("REUSE: global.__serverInitialized is already "+global.__serverInitialized)
|
|
@@ -3831,7 +3836,7 @@ try{const{createConfigManager:e}=await Promise.resolve().then(t.t.bind(t,9060,23
|
|
|
3831
3836
|
if(n.remoteServerUrl)return(0,a.isDebugToolsEnabled)()&&k.info("Loaded REMOTE_SERVER_URL from installation config",{remoteServerUrl:n.remoteServerUrl}),n.remoteServerUrl}catch(e){(0,a.isDebugToolsEnabled)()&&k.debug("Could not read REMOTE_SERVER_URL from installation config",{error:e instanceof Error?e.message:"Unknown error"})}return"https://api.alchemylabcode.com"}()
|
|
3832
3837
|
try{const e=await(0,p.syncPlugins)(w,(0,f.isDevBuild)(),k)
|
|
3833
3838
|
e.synced.length>0&&k.info("Synced plugins on startup",{synced:e.synced}),e.errors.length>0&&k.warn("Some plugins failed to sync",{errors:e.errors})}catch(e){k.warn("Plugin sync failed",{error:e instanceof Error?e.message:"Unknown error"})}(0,a.isDebugToolsEnabled)()&&(k.info("Creating MCP server with base dir: "+w),k.info("Using remote server URL: "+v))
|
|
3834
|
-
const e=await(0,i.createServer)(w,k,
|
|
3839
|
+
const e=await(0,i.createServer)(w,k,I,v)
|
|
3835
3840
|
_=e,global.__serverInitialized=!0,(0,a.isDebugToolsEnabled)()&&k.info("MCP server created successfully")
|
|
3836
3841
|
const n=r()
|
|
3837
3842
|
return(0,a.isDebugToolsEnabled)()&&k.info("Stdio transport registered with server"),{server:_,transportInfo:n}}catch(e){throw k.error("Failed to initialize MCP server",{error:e}),e}})().then((()=>{(0,a.isDebugToolsEnabled)()&&k.info("MCP server initialization complete")})).catch((e=>{const t=e instanceof Error?{message:e.message,name:e.name,stack:e.stack}:e+""
|
|
@@ -3874,8 +3879,8 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3874
3879
|
var t={}
|
|
3875
3880
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
3876
3881
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3877
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceLines=async function(e,n,o,s,i,a,m,w){const k=a.child({tool:"replace_lines"}),
|
|
3878
|
-
let
|
|
3882
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceLines=async function(e,n,o,s,i,a,m,w){const k=a.child({tool:"replace_lines"}),b=Date.now()
|
|
3883
|
+
let I,v,C=d.FileOperationPhase.VALIDATION
|
|
3879
3884
|
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"}
|
|
3880
3885
|
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"
|
|
3881
3886
|
if(k.info("Replacing lines in files and documents",{taskId:P,operationCount:q.length,comment:S}),!q||0===q.length)throw new u.ValidationError("At least one operation is required")
|
|
@@ -3901,7 +3906,7 @@ for(let e=0;e<x.length;e++){const t=x[e],r=j[e],{normalizedPath:o,fullPath:s}=d.
|
|
|
3901
3906
|
x[e]={...t,path:o,fullPath:s}}}if(M.length>0&&$)try{await(0,h.validateRequestStatusForDocumentOperation)($,i,k,m,"replace-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3902
3907
|
throw e}C=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("replace_lines_phase",1,{phase:C})
|
|
3903
3908
|
const L=[...x.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:z}=await d.createFileOperationRecords(P,$,n.projectId,_.recordType,O,{operationCount:q.length,fileOperations:x.length,documentOperations:M.length,operations:L,userComment:S},o,s,k,m,_.metricsPrefix,w)
|
|
3904
|
-
if(
|
|
3909
|
+
if(I=z,v=z,C=_.fileOperationPhase,m.incrementCounter("replace_lines_phase",1,{phase:C}),x.length>0&&n.git)try{k.debug("[REPLACE-LINES] Checking for user changes before replace operations")
|
|
3905
3910
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"replace-lines",{requestId:$,taskId:P,workspaceManager:n.workspaceManager},k,m)
|
|
3906
3911
|
e.userChangesCommitted&&(k.debug("[REPLACE-LINES] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),k.info("User changes committed before replace-lines operation",{taskId:P,fileOperationsCount:x.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){k.debug("[REPLACE-LINES] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),k.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:P,fileOperationsCount:x.length,error:e instanceof Error?e.message:e+""})}k.debug("[REPLACE-LINES] Proceeding with file operations",{fileCount:x.length})
|
|
3907
3912
|
const H=[]
|
|
@@ -3915,15 +3920,15 @@ t.filename=s?.filename
|
|
|
3915
3920
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.replacements)
|
|
3916
3921
|
t.replacements=l,t.successfulReplacements=l.filter((e=>e.success)).length,t.failedReplacements=l.filter((e=>!e.success)).length,t.totalLinesReplaced=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulReplacements>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,W++,k.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedReplacements=e.replacements.length,B+=t.failedReplacements,k.error("Document operation failed",{documentId:e.documentId,error:t.error})}H.push(t)}if(M.length>0)try{for(const e of M){const t=H.find((t=>t.documentId===e.documentId))
|
|
3917
3922
|
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){k.warn("Some documents may not have synced properly",{error:e})}const V=await d.handleMultiFileGitCommit(P,x,H,W,{operationType:"Replace lines",toolRecordId:v,successField:"successfulReplacements",logger:k,metrics:m,metricsPrefix:"replace_lines"},n),J=d.processMultiFileOperationResults(H,"successfulReplacements"),{successfulOperations:K,failedOperations:Y,totalSuccessfulChanges:Q,overallSuccess:Z,successfulFiles:X,failedFiles:ee}=J
|
|
3918
|
-
try{await s.updateToolRecord(v,{metadata:{path:x.length>0?x[0].path:"document:"+M[0]?.documentId,status:Z?"completed":"failed",error:Z?void 0:Y+" operations failed",totalOperations:H.length,successfulFiles:X,failedFiles:ee,operations:L,totalSuccessfulReplacements:Q,totalFailedReplacements:B,totalLinesReplaced:U,totalLinesAdded:G,operationsWithChanges:W,processingTime:Date.now()-
|
|
3923
|
+
try{await s.updateToolRecord(v,{metadata:{path:x.length>0?x[0].path:"document:"+M[0]?.documentId,status:Z?"completed":"failed",error:Z?void 0:Y+" operations failed",totalOperations:H.length,successfulFiles:X,failedFiles:ee,operations:L,totalSuccessfulReplacements:Q,totalFailedReplacements:B,totalLinesReplaced:U,totalLinesAdded:G,operationsWithChanges:W,processingTime:Date.now()-b,userComment:S,...x.length>0&&V.success&&V.commitHash&&{commitHash:V.commitHash,previousCommitHash:V.previousCommitHash||void 0}},note:Z?`Line replacement completed: ${K}/${H.length} operations successful${x.length>0?" (committed to git)":""}`:`Line replacement partially failed: ${Y}/${H.length} operations failed`})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let te="## Line Replacement Results\n\n"
|
|
3919
3924
|
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
3920
3925
|
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]
|
|
3921
3926
|
if(te+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?te+=`**File:** ${e.path}\n`:(te+="**Document:** "+e.documentId,e.filename&&(te+=` (${e.filename})`),te+="\n"),e.error?te+=`**Error:** ${e.error}\n`:(te+=`**Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(te+=`, ${e.failedReplacements} failed`),te+="\n",te+=`**Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(te+=`**Lines Added:** ${e.totalLinesAdded}\n`)),e.replacements.some((e=>!e.success))){te+="**Failed Replacement Details:**\n"
|
|
3922
3927
|
for(const t of e.replacements.filter((e=>!e.success)))te+=`- Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}}else{te+="**Summary:**\n",te+=`- **Total Operations:** ${H.length}\n`,te+=`- **Successful:** ${K}\n`,te+=`- **Failed:** ${Y}\n`,te+=`- **Total Replacements:** ${Q} successful, ${B} failed\n`,te+=`- **Total Lines Replaced:** ${U}\n`,G>0&&(te+=`- **Total Lines Added:** ${G}\n`),te+="\n",te+="**Detailed Results:**\n\n"
|
|
3923
3928
|
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"
|
|
3924
3929
|
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")
|
|
3925
|
-
const re=Date.now()-
|
|
3926
|
-
return k.info("Replace lines operation completed",{duration:re,success:Z,totalOperations:H.length,successfulOperations:K,failedOperations:Y}),m.incrementCounter("replace_lines_total",1,{success:Z}),{content:[{type:"text",text:te}],isError:!Z}}catch(t){const r=Date.now()-
|
|
3930
|
+
const re=Date.now()-b
|
|
3931
|
+
return k.info("Replace lines operation completed",{duration:re,success:Z,totalOperations:H.length,successfulOperations:K,failedOperations:Y}),m.incrementCounter("replace_lines_total",1,{success:Z}),{content:[{type:"text",text:te}],isError:!Z}}catch(t){const r=Date.now()-b
|
|
3927
3932
|
if(k.error("Replace lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:C}),v)try{await s.updateToolRecord(v,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,f.getErrorMessage)(t),phase:C,duration:r,userComment:e?.comment},note:"Line replacement failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return m.incrementCounter("replace_lines_errors",1,{phase:C}),{content:[{type:"text",text:"\u274c **Replace Lines Failed:** "+(0,f.getErrorMessage)(t)}],isError:!0}}}
|
|
3928
3933
|
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824),m=t(3255),y=t(9470)},6688(e,exports,t){"use strict"
|
|
3929
3934
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.sessionIdentity=void 0
|
|
@@ -4014,13 +4019,13 @@ s.info("Raw task response data",{responseDataType:typeof P,isArray:Array.isArray
|
|
|
4014
4019
|
try{const R=await m.getToolRecordsByTaskId(g)
|
|
4015
4020
|
if(s.info("Raw records response data",{responseDataType:typeof R,isArray:Array.isArray(R),hasData:null!=R,properties:R&&"object"==typeof R?Object.keys(R):[]}),k=(0,l.extractArrayFromResponse)(R,{logger:s,operationName:"searchRecords",defaultValue:[]}),k.length>0&&s.info("First record summary:",{id:k[0].id,type:k[0].type,hasMetadata:!!k[0].metadata,hasCommitHash:!!k[0].metadata?.commitHash}),s.info(`Extracted ${k.length} records for task ${g}`),k.length>0){const x={}
|
|
4016
4021
|
k.forEach((e=>{x[e.type]=(x[e.type]||0)+1})),s.info("Record type distribution:",x)}}catch(M){s.warn("Error fetching records for task "+g,{error:(0,u.getErrorMessage)(M)}),k=[]}if(0===k.length)return h({success:!0,recordCount:0}),{content:[{type:"text",text:`No records found for task ${g}.`}]}
|
|
4017
|
-
function
|
|
4022
|
+
function b(e){const t=new Map,r=new Map,n=[]
|
|
4018
4023
|
for(const o of e)if("move-file"===o.type&&o.metadata){const e=o.metadata.source||o.metadata.oldPath,s=o.metadata.destination||o.metadata.newPath
|
|
4019
4024
|
if(e&&s){const i={source:e,destination:s,recordId:o.id,timestamp:o.createdAt,type:"move-file"}
|
|
4020
4025
|
t.set(e,i),r.set(s,i),n.push(i)}}else if("move-files"===o.type&&o.metadata){const e=[...o.metadata.successfulOperations||[],...o.metadata.failedOperations||[]]
|
|
4021
4026
|
for(const s of e)if(s.source&&s.destination){const e={source:s.source,destination:s.destination,recordId:o.id,timestamp:o.createdAt,type:"move-files"}
|
|
4022
|
-
t.set(s.source,e),r.set(s.destination,e),n.push(e)}}return{sourceToMove:t,destToMove:r,allMoves:n}}const b
|
|
4023
|
-
s.info(`Detected ${
|
|
4027
|
+
t.set(s.source,e),r.set(s.destination,e),n.push(e)}}return{sourceToMove:t,destToMove:r,allMoves:n}}const I=b(k)
|
|
4028
|
+
s.info(`Detected ${I.allMoves.length} move operations`)
|
|
4024
4029
|
const v=k.filter((e=>{if(!e||"object"!=typeof e)return s.warn("Skipping invalid record (not an object)"),!1
|
|
4025
4030
|
if(!["write-file","replace-in-files","move-file","move-files","delete-file","delete-files","manage-files"].includes(e.type))return s.debug("Skipping record with non-file operation type: "+e.type),!1
|
|
4026
4031
|
if(!e.metadata)return s.warn("Skipping record without metadata: "+e.id),!1
|
|
@@ -4096,7 +4101,7 @@ continue}let pe
|
|
|
4096
4101
|
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")
|
|
4097
4102
|
try{const me=await t.git.show([`${G.commitHash}:${A}`]),ye=await t.git.show([`${H.commitHash}:${A}`])
|
|
4098
4103
|
if(me!==ye&&(V=!0,W="Changes detected through direct content comparison (not visible in standard diff)",p)){const we=me.split("\n"),ke=ye.split("\n")
|
|
4099
|
-
Math.abs(we.length-ke.length)>0&&(W+=`\n\nLine count changed: ${we.length} \u2192 ${ke.length}`),me.includes("\0")||ye.includes("\0")?W+="\n\nBinary content detected - changes not displayed":me.replace(/\s+/g,"")===ye.replace(/\s+/g,"")&&(W+="\n\nWhitespace-only changes detected")}}catch(
|
|
4104
|
+
Math.abs(we.length-ke.length)>0&&(W+=`\n\nLine count changed: ${we.length} \u2192 ${ke.length}`),me.includes("\0")||ye.includes("\0")?W+="\n\nBinary content detected - changes not displayed":me.replace(/\s+/g,"")===ye.replace(/\s+/g,"")&&(W+="\n\nWhitespace-only changes detected")}}catch(be){s.warn("Error in direct file comparison: "+(be instanceof Error?be.message:be+""))}}s.info(`Diff generation result for ${A}: hasDiff=${V}, length=${W.length}`)}}catch(Ie){if(s.warn("Error getting diff for "+A,{error:(0,u.getErrorMessage)(Ie),firstCommit:z.commitHash||"unknown",lastCommit:H.commitHash||"unknown"}),W="Error getting diff: "+(0,u.getErrorMessage)(Ie),"pre-task"!==z.status&&t.git)try{const ve=[`${H.commitHash}:${A}`]
|
|
4100
4105
|
s.info(`Trying fallback to show file content using git show: ${H.commitHash?H.commitHash.substring(0,8):"unknown"}:${A}`)
|
|
4101
4106
|
const Ce=await t.git.show(ve)
|
|
4102
4107
|
if(Ce&&Ce.trim().length>0){if(p){let _e=""
|
|
@@ -4108,14 +4113,14 @@ w&&"object"==typeof w&&(E+="## Task Information\n",E+=`- **Title**: ${w.title||"
|
|
|
4108
4113
|
const q=3e3
|
|
4109
4114
|
let S=0,T=!1
|
|
4110
4115
|
if(p){for(const Te of _.values())Te.hasDiff&&Te.diffText&&(S+=Te.diffText.split("\n").length)
|
|
4111
|
-
T=S>q,s.info(`Total diff size: ${S} lines (limit: ${q} lines)`),s.info(`Diffs ${T?"will be limited":"will be shown"} based on size`)}if(E+="## Summary\n",E+=`- **Files Modified**: ${C.size}\n`,E+=`- **Total File Operations**: ${v.length}\n`,E+="- **What's Shown**: For existing files, comparing state before task started with final state.\n",E+=" For files created during task, showing the entire file as created.\n",T?(E+=`- **Diff Display**: Limited (total diff size of ${S} lines exceeds limit of ${q} lines)\n`,E+=" Use file-history tool with individual files to see detailed changes\n\n"):E+=`- **Diff Display**: ${p?"Enabled":"Disabled"} (use showDiff=${!p} to ${p?"hide":"show"} diffs)\n\n`,
|
|
4112
|
-
for(const Pe of
|
|
4116
|
+
T=S>q,s.info(`Total diff size: ${S} lines (limit: ${q} lines)`),s.info(`Diffs ${T?"will be limited":"will be shown"} based on size`)}if(E+="## Summary\n",E+=`- **Files Modified**: ${C.size}\n`,E+=`- **Total File Operations**: ${v.length}\n`,E+="- **What's Shown**: For existing files, comparing state before task started with final state.\n",E+=" For files created during task, showing the entire file as created.\n",T?(E+=`- **Diff Display**: Limited (total diff size of ${S} lines exceeds limit of ${q} lines)\n`,E+=" Use file-history tool with individual files to see detailed changes\n\n"):E+=`- **Diff Display**: ${p?"Enabled":"Disabled"} (use showDiff=${!p} to ${p?"hide":"show"} diffs)\n\n`,I.allMoves.length>0){E+="## Move Operations\n\n",E+=`Detected ${I.allMoves.length} file move operation(s):\n\n`
|
|
4117
|
+
for(const Pe of I.allMoves)E+=`- **${Pe.source}** \u2192 **${Pe.destination}**\n`,E+=` - Operation: ${Pe.type}\n`,E+=` - Timestamp: ${new Date(Pe.timestamp).toLocaleString()}\n`,E+=` - Record ID: ${Pe.recordId}\n\n`}E+="## Modified Files\n\n"
|
|
4113
4118
|
for(const[je,Re]of _.entries()){const{normalizedPath:xe,fullPath:Me}=d.validateAndNormalizePath(je,t)
|
|
4114
4119
|
let Oe=!1
|
|
4115
4120
|
try{await a.access(Me),Oe=!0}catch{}E+=`### ${je} ${Oe?"":"(Deleted)"}\n\n`
|
|
4116
4121
|
const De=new Date(Re.firstChange.timestamp).toLocaleString(),$e=new Date(Re.lastChange.timestamp).toLocaleString()
|
|
4117
4122
|
E+=`**First Change**: ${De}\n`,E+=`**Last Change**: ${$e}\n`,"pre-task"===Re.firstChange.status&&Re.firstChange.commitHash?E+=`**Pre-Task Commit**: ${Re.firstChange.commitHash.substring(0,8)}\n`:Re.firstChange.commitHash&&(E+=`**File Created During Task**: ${Re.firstChange.commitHash.substring(0,8)}\n`),Re.lastChange.commitHash&&(E+=`**Final Commit**: ${Re.lastChange.commitHash.substring(0,8)}\n`)
|
|
4118
|
-
const Ae=
|
|
4123
|
+
const Ae=I.sourceToMove.get(je),Fe=I.destToMove.get(je)
|
|
4119
4124
|
Ae?E+=`**\u2139\ufe0f Move Operation**: This file was moved TO **${Ae.destination}**\n`:Fe&&(E+=`**\u2139\ufe0f Move Operation**: This file was moved FROM **${Fe.source}**\n`),p&&!T?Re.hasDiff?(E+="\n**Changes**:\n",E+="```diff\n",E+=Re.diffText,E+="\n```\n\n"):E+=`\n**Note**: ${Re.diffText}\n\n`:T&&Re.hasDiff?(E+=`\n**Note**: File has changes (${Re.diffText?Re.diffText.split("\n").length:0} lines). `,E+=`Compare ${Re.firstChange.commitHash?Re.firstChange.commitHash.substring(0,8):"unknown"}..${Re.lastChange.commitHash?Re.lastChange.commitHash.substring(0,8):"unknown"} to see changes.\n\n`):Re.hasDiff?E+="\n**Note**: File has changes. Use showDiff=true to see the diff.\n\n":E+=`\n**Note**: ${Re.diffText}\n\n`,E+="---\n\n"}return h({success:!0,fileCount:C.size}),{content:[{type:"text",text:E}]}}catch(Ne){return s.error("Error in task file history tool",{error:Ne instanceof Error?Ne.stack:Ne+""}),h({success:!1,error:Ne instanceof Error?Ne.name:"unknown"}),{content:[{type:"text",text:"Error: "+(0,u.getErrorMessage)(Ne)}],isError:!0}}}
|
|
4120
4125
|
const i=t(9860),a=s(t(1943)),c=t(9671),l=t(2960),d=s(t(5967)),u=t(8824)},6928(module){"use strict"
|
|
4121
4126
|
module.exports=require("path")},6975(e,exports,t){"use strict"
|
|
@@ -4232,7 +4237,7 @@ this.logger.debug("Branch creation failed, retrying",{attempt:n,maxRetries:t,req
|
|
|
4232
4237
|
this.logger.debug("Branch creation attempt failed, retrying",{attempt:n,maxRetries:t,requestId:e.requestId,error:(0,a.getErrorMessage)(o)}),await new Promise((e=>setTimeout(e,r*n)))}throw Error("Unexpected end of retry loop")}}exports.SharedBranchManager=c},7250(e,exports,t){"use strict"
|
|
4233
4238
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4234
4239
|
const r=t(6183),n=t(3707)
|
|
4235
|
-
exports.def={name:"quick_replace",description:"
|
|
4240
|
+
exports.def={name:"quick_replace",description:"WHEN TO USE: trivial single-file edits only. For multi-file or feature work, spawn a coder via subagent_operations.\n\nReplace text in files or documents. Wraps the change in a request/task workflow that auto-completes.\n\nProvide an array of operations, each with path/documentId and replacements [{old, new}].\nSupports fuzzy matching (default: true) and match_mode ('unique' or 'all').\n\nRequires: title, description, comment, operations.",schema:r.QuickReplaceSchema,annotations:{title:"Quick Replace",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"replace",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},7252(module){"use strict"
|
|
4236
4241
|
module.exports=require("express")},7257(e,exports,t){"use strict"
|
|
4237
4242
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4238
4243
|
const r=t(6183),n=t(3420)
|
|
@@ -4270,11 +4275,11 @@ r&&(y=(0,a.getApprovalMode)(r))}catch(e){g.warn("Failed to read project metadata
|
|
|
4270
4275
|
let k=h
|
|
4271
4276
|
if(h?.sessionId)try{const e=c.getCLISessionClient()
|
|
4272
4277
|
if(e){const t=await e.getByExternalId(h.sessionId)
|
|
4273
|
-
"planner"!==t?.agentType&&"auto-planner"!==t?.agentType||(k=void 0,g.info("Skipping cliOrigin for planner-created request",{agentType:t.agentType}))}}catch{}const
|
|
4278
|
+
"planner"!==t?.agentType&&"auto-planner"!==t?.agentType||(k=void 0,g.info("Skipping cliOrigin for planner-created request",{agentType:t.agentType}))}}catch{}const b={title:l.title,description:l.description,type:l.type,acceptanceCriteria:l.acceptanceCriteria,status:w,...l.planDocumentId&&{planDocumentId:l.planDocumentId},...k&&{cliOrigin:k}}
|
|
4274
4279
|
g.info("Creating request via request client",{projectId:f,title:l.title,type:l.type,criteriaCount:l.acceptanceCriteria.length})
|
|
4275
|
-
const
|
|
4276
|
-
g.debug("Create request response structure",{type:typeof
|
|
4277
|
-
const v=(0,o.extractDataFromResponse)(
|
|
4280
|
+
const I=await m.createRequest(b)
|
|
4281
|
+
g.debug("Create request response structure",{type:typeof I,isArray:Array.isArray(I),hasData:null!=I,properties:I?Object.keys(I):[],dataPreview:I?JSON.stringify(I).substring(0,200)+"...":"null"})
|
|
4282
|
+
const v=(0,o.extractDataFromResponse)(I,{logger:g,operationName:"createRequest",throwOnNoData:!0}),C="data"in v?v.data:v
|
|
4278
4283
|
let _,E={created:!1}
|
|
4279
4284
|
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})
|
|
4280
4285
|
g.info("Request created successfully",{requestId:C.id,title:C.title,branchCreated:E.created,branchName:E.branchName})
|
|
@@ -4305,21 +4310,21 @@ return o(t,e),t})
|
|
|
4305
4310
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,r,n,o,s,h,g,p){const f=h.child({tool:"modify_file"})
|
|
4306
4311
|
try{const u=a.validateArgs(e,i.ModifyFileSchema),{operations:m,comment:y}=u,{resolveActiveTaskId:w}=await Promise.resolve().then(t.bind(t,3451)),k=e.taskId||await w(r,n,h)||"untracked"
|
|
4307
4312
|
f.info("Processing modify-file operations",{taskId:k,operationCount:m.length,comment:y})
|
|
4308
|
-
const
|
|
4313
|
+
const b=[],I=[],v=[],C=[],_=[]
|
|
4309
4314
|
for(const e of m){const t={path:e.path,documentId:e.documentId}
|
|
4310
|
-
switch(e.operationType){case"replace-string":
|
|
4315
|
+
switch(e.operationType){case"replace-string":b.push({...t,replacements:e.replaceString.replacements,mode:e.replaceString.mode})
|
|
4311
4316
|
break
|
|
4312
|
-
case"insert-lines":
|
|
4317
|
+
case"insert-lines":I.push({...t,insertions:e.insertLines.insertions})
|
|
4313
4318
|
break
|
|
4314
4319
|
case"replace-lines":v.push({...t,replacements:e.replaceLines.replacements})
|
|
4315
4320
|
break
|
|
4316
4321
|
case"delete-string":C.push({...t,replacements:e.deleteString.patterns.map((e=>({old_str:e,new_str:""}))),mode:e.deleteString.mode||"all"})
|
|
4317
4322
|
break
|
|
4318
4323
|
case"delete-lines":_.push({...t,lines:e.deleteLines.lines})}}const E=[]
|
|
4319
|
-
if(
|
|
4320
|
-
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:
|
|
4321
|
-
E.push({type:"replace-string",result:e})}if(
|
|
4322
|
-
const e=await(0,l.handleInsertLines)({taskId:k,operations:
|
|
4324
|
+
if(b.length>0){f.info("Routing to replace-strings handler",{operationCount:b.length})
|
|
4325
|
+
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:b,comment:y+" [via modify-file: replace-string]"},r,n,o,s,f,g,p)
|
|
4326
|
+
E.push({type:"replace-string",result:e})}if(I.length>0){f.info("Routing to insert-lines handler",{operationCount:I.length})
|
|
4327
|
+
const e=await(0,l.handleInsertLines)({taskId:k,operations:I,comment:y+" [via modify-file: insert-lines]"},r,n,o,s,f,g,p)
|
|
4323
4328
|
E.push({type:"insert-lines",result:e})}if(v.length>0){f.info("Routing to replace-lines handler",{operationCount:v.length})
|
|
4324
4329
|
const e=await(0,d.handleReplaceLines)({taskId:k,operations:v,comment:y+" [via modify-file: replace-lines]"},r,n,o,s,f,g,p)
|
|
4325
4330
|
E.push({type:"replace-lines",result:e})}if(C.length>0){f.info("Routing delete-string to replace-strings handler",{operationCount:C.length})
|
|
@@ -4717,8 +4722,8 @@ var t={}
|
|
|
4717
4722
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4718
4723
|
return o(t,e),t})
|
|
4719
4724
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,r,n,o,s,g,p,f,m){const y=p.child({tool:"manage_files"})
|
|
4720
|
-
try{const h=a.validateArgs(e,i.ManageFilesSchema),{operations:w,comment:k}=h,{resolveActiveTaskId:
|
|
4721
|
-
y.info("Processing manage-files operations",{taskId:
|
|
4725
|
+
try{const h=a.validateArgs(e,i.ManageFilesSchema),{operations:w,comment:k}=h,{resolveActiveTaskId:b}=await Promise.resolve().then(t.bind(t,3451)),I=e.taskId||await b(r,g,p)||"untracked"
|
|
4726
|
+
y.info("Processing manage-files operations",{taskId:I,operationCount:w.length,comment:k})
|
|
4722
4727
|
const v=[],C=[],_=[],E=[]
|
|
4723
4728
|
for(const e of w)switch(e.operationType){case"create-directory":v.push({path:e.createDirectory.path})
|
|
4724
4729
|
break
|
|
@@ -4728,11 +4733,11 @@ case"delete-files":_.push(...e.deleteFiles.targets)
|
|
|
4728
4733
|
break
|
|
4729
4734
|
case"get-file-info":E.push({path:e.getFileInfo.path})}const q=[]
|
|
4730
4735
|
for(const e of v){y.info("Routing to create-directory handler",{path:e.path})
|
|
4731
|
-
const t=await(0,c.handleCreateDirectory)({taskId:
|
|
4736
|
+
const t=await(0,c.handleCreateDirectory)({taskId:I,path:e.path,comment:k+" [via manage-files: create-directory]"},r,n,o,s,y,f,m)
|
|
4732
4737
|
q.push({type:"create-directory",result:t})}if(C.length>0){y.info("Routing to move-files handler",{operationCount:C.length})
|
|
4733
|
-
const e=await(0,l.handleMoveFiles)({taskId:
|
|
4738
|
+
const e=await(0,l.handleMoveFiles)({taskId:I,operations:C,comment:k+" [via manage-files: move-files]"},r,n,o,s,y,f,m)
|
|
4734
4739
|
q.push({type:"move-files",result:e})}if(_.length>0){y.info("Routing to delete-files handler",{operationCount:_.length})
|
|
4735
|
-
const e=await(0,u.handleDeleteFiles)({taskId:
|
|
4740
|
+
const e=await(0,u.handleDeleteFiles)({taskId:I,operations:_,comment:k+" [via manage-files: delete-files]"},r,g,y,f,m)
|
|
4736
4741
|
q.push({type:"delete-files",result:e})}for(const e of E){y.info("Routing to get-file-info handler",{path:e.path})
|
|
4737
4742
|
const t=await(0,d.handleGetFileInfo)({path:e.path},r,y,f)
|
|
4738
4743
|
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
|
|
@@ -4833,9 +4838,9 @@ const m=new Date,y=`${(m.getHours()+"").padStart(2,"0")}${(m.getMinutes()+"").pa
|
|
|
4833
4838
|
let k
|
|
4834
4839
|
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))
|
|
4835
4840
|
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})
|
|
4836
|
-
const
|
|
4841
|
+
const b=(0,i.join)(l||process.cwd(),".alchemy_lab"),I=(0,i.join)(b,"spawn-stderr.log")
|
|
4837
4842
|
let v
|
|
4838
|
-
try{v=(0,s.openSync)(
|
|
4843
|
+
try{v=(0,s.openSync)(I,"a")}catch{}const C=(0,a.resolveRunCommand)(),_=(0,n.spawn)(C.command,[...C.prependArgs,...k],{detached:!0,stdio:["ignore","ignore",v??"ignore"],cwd:l||process.cwd(),env:o})
|
|
4839
4844
|
return _.unref(),p&&p(_.pid),{success:!0,pid:_.pid}}catch(e){return{success:!1,error:(0,o.getErrorMessage)(e)}}}
|
|
4840
4845
|
const n=t(5317),o=t(8824),s=t(9896),i=t(6928),a=t(9068)},8037(e,exports,t){"use strict"
|
|
4841
4846
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListRequests=async function(e,t,i,a,c){const l=a.child({tool:"list_requests"}),d=c.startTimer("tool_execution_time")
|
|
@@ -4915,32 +4920,32 @@ var t={}
|
|
|
4915
4920
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4916
4921
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
4917
4922
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,r,n,o,s,i,p,f){const m=i.child({tool:"create_directory"}),y=Date.now()
|
|
4918
|
-
let w,k,
|
|
4919
|
-
const
|
|
4923
|
+
let w,k,b=d.FileOperationPhase.VALIDATION
|
|
4924
|
+
const I={toolName:"create-directory",operationName:"create",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"create-directory",metricsPrefix:"create_directory",successMessage:"Successfully created directory {path}",failureMessage:"Failed to create directory {path}"}
|
|
4920
4925
|
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"
|
|
4921
|
-
m.info("Creating directory: "+h,{taskId:C,path:h,comment:g}),d.validateTaskIdFormat(C,m,p,
|
|
4926
|
+
m.info("Creating directory: "+h,{taskId:C,path:h,comment:g}),d.validateTaskIdFormat(C,m,p,I.metricsPrefix),r.getCurrentBranchContext&&await r.getCurrentBranchContext()
|
|
4922
4927
|
const{normalizedPath:_,fullPath:E}=d.validateAndNormalizePath(h,r)
|
|
4923
|
-
|
|
4924
|
-
const q=await d.validateTaskId(C,_,n,m,p,
|
|
4928
|
+
b=d.FileOperationPhase.TASK_VALIDATION,p.incrementCounter("create_directory_phase",1,{phase:b})
|
|
4929
|
+
const q=await d.validateTaskId(C,_,n,m,p,I.metricsPrefix),S=q?.requestId,T=await d.validateWorkItemStates(C,_,n,s,r,m,p,I.metricsPrefix),P=await d.autoPromoteTaskStatus(C,q.status,S,T.request?.status,_,n,s,m,p,I.metricsPrefix)
|
|
4925
4930
|
P.taskPromoted&&m.info(`Auto-promoted task ${C} (${q.title||"Untitled"}) to in_progress for file operation`,{taskId:C,taskTitle:q.title,previousStatus:q.status,newStatus:P.newTaskStatus,path:_}),P.requestPromoted&&m.info(`Auto-promoted request ${S} to in_progress for file operation`,{requestId:S,previousStatus:T.request?.status,newStatus:P.newRequestStatus,triggeringTaskId:C})
|
|
4926
|
-
const j=await d.ensureCorrectWorkspaceContext({taskPromoted:P.taskPromoted,requestId:S,context:r,operation:"create-directory",logger:m,metrics:p,metricsPrefix:
|
|
4931
|
+
const j=await d.ensureCorrectWorkspaceContext({taskPromoted:P.taskPromoted,requestId:S,context:r,operation:"create-directory",logger:m,metrics:p,metricsPrefix:I.metricsPrefix})
|
|
4927
4932
|
if(!j.success){if(j.isLockConflict)return{content:[{type:"text",text:"\u274c "+j.error}],isError:!0}
|
|
4928
4933
|
throw Error(j.error)}let R=!1
|
|
4929
|
-
try{R=(await a.default.stat(E)).isDirectory()}catch{R=!1}
|
|
4930
|
-
const{toolRecordId:x,localToolRecordId:M}=await d.createFileOperationRecords(C,S,r.projectId,
|
|
4931
|
-
w=x,k=x,I
|
|
4934
|
+
try{R=(await a.default.stat(E)).isDirectory()}catch{R=!1}b=d.FileOperationPhase.RECORD_CREATION,p.incrementCounter("create_directory_phase",1,{phase:b})
|
|
4935
|
+
const{toolRecordId:x,localToolRecordId:M}=await d.createFileOperationRecords(C,S,r.projectId,I.recordType,_,{directoryExists:R,userComment:g},n,o,m,p,I.metricsPrefix,f)
|
|
4936
|
+
w=x,k=x,b=I.fileOperationPhase,p.incrementCounter("create_directory_phase",1,{phase:b})
|
|
4932
4937
|
let O=R
|
|
4933
4938
|
if(!R){await a.default.mkdir(E,{recursive:!0}),m.info("Successfully created directory "+_)
|
|
4934
4939
|
try{const e=c.default.join(E,".gitkeep")
|
|
4935
4940
|
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),O=!0,m.info("Created .gitkeep file for Git tracking")}catch(e){m.warn("Failed to create .gitkeep file",{error:e instanceof Error?e.message:e+""}),O=!1}}const D=Date.now()-y
|
|
4936
|
-
p.recordValue("create_directory_time",D),p.incrementCounter("create_directory_success",1),
|
|
4937
|
-
const $=`Create directory: ${_} - ${g||"Create directory"}`,A=!R&&O?_+"/.gitkeep":_,F=await d.commitToGit(C,A,x,M,$,r,m,p,
|
|
4938
|
-
|
|
4941
|
+
p.recordValue("create_directory_time",D),p.incrementCounter("create_directory_success",1),b=d.FileOperationPhase.GIT_COMMIT,p.incrementCounter("create_directory_phase",1,{phase:b})
|
|
4942
|
+
const $=`Create directory: ${_} - ${g||"Create directory"}`,A=!R&&O?_+"/.gitkeep":_,F=await d.commitToGit(C,A,x,M,$,r,m,p,I.metricsPrefix)
|
|
4943
|
+
b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,p.incrementCounter("create_directory_phase",1,{phase:b}),await d.updateFileOperationRecords(C,w,k,_,I.recordType,`Successfully ${R?"verified":"created"} directory: ${_}`,{status:"completed",commitHash:F.commitHash,previousCommitHash:F.previousCommitHash,directoryExists:R,isDirectory:!0,userComment:g},`Successfully ${R?"verified":"created"} directory: ${_}`,n,o,m,p,I.metricsPrefix)
|
|
4939
4944
|
const N=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
4940
4945
|
return{content:[{type:"text",text:R?"Directory already exists":`Successfully created directory${F.commitHash?"\nCommit: "+F.commitHash.substring(0,8):""}${N.requestId&&!N.permanentBranch?"\nBranch: "+N.requestId:""}${j.lockAcquired&&j.lockedRequestId&&!N.permanentBranch?"\n\u{1f512} **Locked request:** "+j.lockedRequestId:""}`}]}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
|
|
4941
|
-
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:
|
|
4942
|
-
if(p.recordValue("create_directory_time",s),p.incrementCounter("create_directory_errors",1),m.error("Error creating directory:",{error:(0,g.getErrorMessage)(t),time:s}),(w||k)&&e.taskId){
|
|
4943
|
-
try{await d.updateFileOperationRecords(e.taskId,w,k,e.path,
|
|
4946
|
+
await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"create-directory",metadata:{status:"failed",timestamp:(new Date).toISOString(),path:e.path,userComment:e.comment,error:(0,g.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:`Failed to create directory ${e.path} - ${(0,g.getErrorMessage)(t)}`})}catch(t){m.error("Failed to create failure record for create directory operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,path:e.path})}const s=Date.now()-y
|
|
4947
|
+
if(p.recordValue("create_directory_time",s),p.incrementCounter("create_directory_errors",1),m.error("Error creating directory:",{error:(0,g.getErrorMessage)(t),time:s}),(w||k)&&e.taskId){b=d.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
4948
|
+
try{await d.updateFileOperationRecords(e.taskId,w,k,e.path,I.recordType,"Failed to create directory "+e.path,{status:"failed",error:(0,g.getErrorMessage)(t),userComment:e.comment},"Failed to create directory "+e.path,n,o,m,p,I.metricsPrefix)}catch(t){m.error("Failed to update record with failure status",{taskId:e.taskId,recordId:w,error:t instanceof Error?t.message:t+""})}}return d.handleFileOperationError(t,b,m,p,e,I)}}
|
|
4944
4949
|
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"
|
|
4945
4950
|
function r(e){const t=[]
|
|
4946
4951
|
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"
|
|
@@ -5159,34 +5164,34 @@ return i(t,e),t})
|
|
|
5159
5164
|
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"),m=Date.now()
|
|
5160
5165
|
try{let o
|
|
5161
5166
|
try{o=d.FileHistorySchema.parse(e)}catch(t){if(t instanceof u.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
5162
|
-
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:
|
|
5163
|
-
return
|
|
5167
|
+
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:b,commit:I,since:v}=o
|
|
5168
|
+
return I?(i.info("Getting diff for specific commit",{filePath:a,commit:I}),await async function(e,t,r,n){const o=r.git,s=c.normalize(e).replace(/\\/g,"/")
|
|
5164
5169
|
if(n.info("Getting full diff for commit",{filePath:e,commit:t}),!o)return{content:[{type:"text",text:"\u274c Git not initialized"}],isError:!0}
|
|
5165
5170
|
try{const r=await o.log({from:t,to:t,file:s,maxCount:1})
|
|
5166
5171
|
if(!r.all||0===r.all.length)return{content:[{type:"text",text:`No commit found with hash ${t} for file ${e}`}]}
|
|
5167
5172
|
const n=r.all[0],i=await o.diff([t+"^",t,"--",s])
|
|
5168
5173
|
let a="# File History - Commit Diff\n\n"
|
|
5169
|
-
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,
|
|
5174
|
+
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,I,t,i)):(i.info("Getting file history with branch support",{filePath:a,limit:y,showDiff:w,showTraceability:k,branch:b}),await async function(e,t,n,o,s,i,a,c,d,u,p){try{const{normalizedPath:m,fullPath:y}=f.validateAndNormalizePath(e,a)
|
|
5170
5175
|
try{await l.access(y)}catch(e){throw Error("File not found: "+m)}const w=a.git
|
|
5171
5176
|
if(!w)throw Error("Git is not available in this context")
|
|
5172
5177
|
let k={branch:null,requestId:null,isMain:!0}
|
|
5173
|
-
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
|
|
5174
|
-
if(s)
|
|
5178
|
+
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 b=[],I=""
|
|
5179
|
+
if(s)b=await r(w,m,t,n,o,s,i,c,d,u),I=`## File History: ${m} (Branch: ${s})\n\n`
|
|
5175
5180
|
else{if(k.isMain&&!o)return d.info("Showing request-level timeline on main branch"),{content:[{type:"text",text:await(0,g.getRequestTimelineForFile)(w,m,c,d,u)}]}
|
|
5176
5181
|
if(k.requestId)return d.info("Showing operation-level detail on request branch",{requestId:k.requestId}),{content:[{type:"text",text:await(0,g.getOperationDetailForFile)(m,k.requestId,c,d,u)}]}
|
|
5177
5182
|
{const e=await async function(e,t,n,o,s,i,a,c,l,d){const u=[],h=[]
|
|
5178
5183
|
if(!i.isMain&&i.branch){const g=await r(e,t,n,o,s,i.branch,a,c,l,d)
|
|
5179
5184
|
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))),f=g.filter((e=>!p.has(e.hash)))
|
|
5180
5185
|
return u.push(...f),g.length>0&&h.push("main"),u.sort(((e,t)=>new Date(t.date).getTime()-new Date(e.date).getTime())),{versions:u.slice(0,n),sources:h}}(w,m,t,n,o,k,i,c,d,u)
|
|
5181
|
-
|
|
5182
|
-
const v=
|
|
5183
|
-
v>t?
|
|
5184
|
-
try{
|
|
5185
|
-
for(let e=0;e<
|
|
5186
|
-
if(
|
|
5186
|
+
b=e.versions,I=`## File History: ${m} (Combined View)\n\n`,I+=`**Current Context:** ${k.isMain?"main":`${k.branch} (${k.requestId})`}\n`,I+=`**History Sources:** ${e.sources.join(", ")}\n\n`}}if(0===b.length)return I+="\u274c **No history found**\n\nThis file has no git history. It may be:\n- A new file that hasn't been committed\n- Located outside the git repository\n- The path may be incorrect\n- No history exists in the specified branch context",{content:[{type:"text",text:I}]}
|
|
5187
|
+
const v=b.length,C=Math.min(b.length,t)
|
|
5188
|
+
v>t?I+=`\u{1f4ca} **Summary:** ${v} versions found, showing ${C} most recent\n\n`:v>0&&(I+=`\u{1f4ca} **Summary:** ${v} version${v>1?"s":""} found\n\n`),I+=`**Total Versions:** ${b.length}\n`,I+="**Current File Size:** "
|
|
5189
|
+
try{I+=(await l.stat(y)).size+" bytes\n"}catch{I+="Unknown\n"}I+="\n"
|
|
5190
|
+
for(let e=0;e<b.length;e++){const t=b[e]
|
|
5191
|
+
if(I+=`### Version ${e+1} (${t.hash.substring(0,8)})\n`,t.branch&&(I+=`- **Branch:** ${t.branch}\n`),I+=`- **Author:** ${t.author}\n`,I+=`- **Date:** ${t.date}\n`,I+=`- **Message:** ${t.message}\n`,o&&t.traceability&&(I+=`\n${(0,h.formatTraceabilityInfo)(t.traceability)}\n`),n&&t.diff){const e=t.diff.split("\n")
|
|
5187
5192
|
let r=0,n=0
|
|
5188
5193
|
for(const t of e)t.startsWith("+")&&!t.startsWith("+++")&&r++,t.startsWith("-")&&!t.startsWith("---")&&n++
|
|
5189
|
-
|
|
5194
|
+
I+=`\n**Changes:**${r>0||n>0?` (Added ${r} lines, removed ${n} lines)`:""}\n\`\`\`diff\n${t.diff}\n\`\`\`\n`}I+="\n"}return I+="\u{1f4a1} **Tips:**\n",I+="- Use `file-recover` with a commit hash to restore the file to a previous version\n",I+='- Use `{"branch": "main"}` to see only main branch history\n',I+='- Use `{"branch": "req123456"}` to see only request branch history\n\n',d.info("Branch-aware file history retrieved successfully",{path:m,versions:b.length,targetBranch:s,currentBranch:k.branch,duration:Date.now()-p}),u.incrementCounter("file_history_total",1,{success:!0,type:"file",mode:s?"single-branch":"combined"}),{content:[{type:"text",text:I}]}}catch(e){throw e}}(a,y,w,k,b,v,t,n,i,s,m))}catch(e){const t=Date.now()-m
|
|
5190
5195
|
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}}}
|
|
5191
5196
|
const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),p=t(8824),f=a(t(5967)),m=a(t(7478)),{getCurrentBranch:y}=m},8849(e,exports,t){"use strict"
|
|
5192
5197
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
@@ -5275,7 +5280,7 @@ if(this.logger.debug("Polling response",{data:n}),n.authenticated&&n.token){this
|
|
|
5275
5280
|
const r=this.parseTokenResponse(n)
|
|
5276
5281
|
if(!r)throw Error("Invalid token response from server")
|
|
5277
5282
|
this.pollingStatus=s.AUTHENTICATED,this.tokenResult=r,this.stopPolling(),t&&t(r)}else this.logger.debug("Not authenticated yet, continuing to poll",{tempCode:e.substring(0,4)+"***"})}catch(e){const t=(0,o.getErrorMessage)(e)
|
|
5278
|
-
throw Error(
|
|
5283
|
+
throw Error(`Error during polling: ${t}${/fetch failed|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|network/i.test(t)?" (remote may be unreachable \u2014 check your connection and try again)":""}`)}}catch(t){const r=(0,o.getErrorMessage)(t)
|
|
5279
5284
|
this.logger.error("Error polling for authentication",{tempCode:e.substring(0,4)+"***",error:r}),this.pollingStatus=s.ERROR,this.pollingError=r,this.stopPolling(),n&&n(r)}}
|
|
5280
5285
|
return i(),this.pollingIntervalId=setInterval(i,this.pollingIntervalMs),()=>this.stopPolling()}stopPolling(){this.pollingIntervalId&&(clearInterval(this.pollingIntervalId),this.pollingIntervalId=null,this.logger.debug("Stopped polling for authentication",{status:this.pollingStatus}))}getPollingStatus(){const e={status:this.pollingStatus}
|
|
5281
5286
|
return this.pollingStatus===s.AUTHENTICATED&&this.tokenResult?e.tokenInfo=this.tokenResult:this.pollingStatus===s.ERROR&&this.pollingError&&(e.error=this.pollingError),this.pollingStartTime>0&&(e.elapsedTimeMs=Date.now()-this.pollingStartTime),e}resetPollingState(){this.stopPolling(),this.pollingStatus=s.NOT_STARTED,this.pollingStartTime=0,this.tokenResult=null,this.pollingError=null}async startGoogleOAuthFlow(){this.logger.info("Starting Google OAuth authentication flow")
|
|
@@ -5352,9 +5357,9 @@ const w=await l.createReport({fromSessionId:m,toSessionId:y,status:u,summary:h,d
|
|
|
5352
5357
|
let k="agent"
|
|
5353
5358
|
try{const e=await fetch(`http://localhost:${g}/api/sessions/${encodeURIComponent(m)}/agent-type`)
|
|
5354
5359
|
if(e.ok){const t=await e.json()
|
|
5355
|
-
t.success&&t.agentType&&(k=t.agentType)}}catch{}const
|
|
5360
|
+
t.success&&t.agentType&&(k=t.agentType)}}catch{}const b=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]
|
|
5356
5361
|
return r.details&&(n.push(""),n.push(r.details)),n.join("\n")}(w,k),t,s)
|
|
5357
|
-
return{content:[{type:"text",text:`\u2705 Report submitted.${
|
|
5362
|
+
return{content:[{type:"text",text:`\u2705 Report submitted.${b?"\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)
|
|
5358
5363
|
throw new c.ValidationError(`Unknown message type: ${u}. Use "question" or "report".`)}(e,t,y,f,m)
|
|
5359
5364
|
case"reply":if(!e.messageCode)throw new c.ValidationError("reply operation requires messageCode")
|
|
5360
5365
|
return await async function(e,t,n,o){const{messageCode:a}=e
|
|
@@ -5381,9 +5386,9 @@ const w={sessionId:s,direction:l,limit:f,offset:m}
|
|
|
5381
5386
|
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)
|
|
5382
5387
|
const k=await y.listMessages(w)
|
|
5383
5388
|
if(0===k.length)return{content:[{type:"text",text:"No messages found matching the criteria."}]}
|
|
5384
|
-
const
|
|
5385
|
-
for(const e of k)
|
|
5386
|
-
return{content:[{type:"text",text:
|
|
5389
|
+
const b=[`Found ${k.length} message(s):\n`]
|
|
5390
|
+
for(const e of k)b.push("---\n"),b.push(a(e)),b.push("")
|
|
5391
|
+
return{content:[{type:"text",text:b.join("\n")}]}}(e.list||{},0,y,f,m)
|
|
5387
5392
|
case"get":if(!e.messageCode)throw new c.ValidationError("get operation requires messageCode")
|
|
5388
5393
|
return await async function(e,t,r){const{messageCode:n}=e
|
|
5389
5394
|
if(!n)throw new c.ValidationError("get operation requires messageCode")
|
|
@@ -5493,10 +5498,10 @@ continue}const t=(0,h.findMatches)(s,n,m,100,e.path)
|
|
|
5493
5498
|
if(a.matchesFound=t.length,0===t.length){a.error="No matches found"+(m?" (tried fuzzy matching)":""),a.success=!1
|
|
5494
5499
|
const e=(0,h.findSimilarMatches)(s,n,5,.3)
|
|
5495
5500
|
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
|
|
5496
|
-
const
|
|
5497
|
-
for(const e of p)for(const t of e.matches)
|
|
5498
|
-
|
|
5499
|
-
for(const{match:e,newText:t,repResult:n}of
|
|
5501
|
+
const b=[]
|
|
5502
|
+
for(const e of p)for(const t of e.matches)b.push({match:t,newText:e.newText,repResult:e.repResult})
|
|
5503
|
+
b.sort(((e,t)=>t.match.startPos-e.match.startPos))
|
|
5504
|
+
for(const{match:e,newText:t,repResult:n}of b)w=(0,h.replaceMatch)(w,e,t),n.success?(n.lines.push(e.line),n.details.push(r(e))):(n.success=!0,n.matchType=e.matchType,n.lines=[e.line],n.details=[r(e)],y.successfulReplacements++)
|
|
5500
5505
|
y.successfulReplacements>0&&(await l.default.writeFile(t,w,"utf8"),f&&(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)
|
|
5501
5506
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
5502
5507
|
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=[]
|
|
@@ -5505,44 +5510,44 @@ return t},o(e)},function(e){if(e&&e.__esModule)return e
|
|
|
5505
5510
|
var t={}
|
|
5506
5511
|
if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
5507
5512
|
return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
5508
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceInFiles=async function(e,r,o,s,i,a,c,
|
|
5513
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceInFiles=async function(e,r,o,s,i,a,c,b){const I=a.child({tool:"replace_in_files"}),v=Date.now()
|
|
5509
5514
|
let C,_=u.FileOperationPhase.VALIDATION
|
|
5510
5515
|
try{if(e&&"string"==typeof e.operations)try{e.operations=JSON.parse(e.operations)}catch{}if(e&&Array.isArray(e.operations))for(const t of e.operations)t.old&&t.new&&!t.replacements&&(t.replacements=[{old:t.old,new:t.new,match_mode:t.match_mode}],delete t.old,delete t.new,delete t.match_mode)
|
|
5511
5516
|
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
|
|
5512
|
-
|
|
5517
|
+
I.info("Replace in files batch operation",{taskId:S,operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,comment:j})
|
|
5513
5518
|
const R=T.filter((e=>e.documentId)).map((e=>e.documentId))
|
|
5514
|
-
if(R.length>0&&r.apiClient)try{await(0,m.ensureDocumentsNotLocked)(R,r.apiClient,
|
|
5519
|
+
if(R.length>0&&r.apiClient)try{await(0,m.ensureDocumentsNotLocked)(R,r.apiClient,I,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
5515
5520
|
throw e}_=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5516
5521
|
const x=T[0],M=x.documentId?"document:"+x.documentId:x.path
|
|
5517
5522
|
let O=Date.now()
|
|
5518
|
-
const D=await u.validateTaskId(S,M,o,
|
|
5523
|
+
const D=await u.validateTaskId(S,M,o,I,c,"replace_in_files")
|
|
5519
5524
|
Date.now()
|
|
5520
5525
|
const $=D?.requestId,A=T.some((e=>e.path))
|
|
5521
5526
|
let F=!1
|
|
5522
5527
|
if(A&&$){O=Date.now()
|
|
5523
|
-
const e=await u.validateWorkItemStates(S,M,o,i,r,
|
|
5528
|
+
const e=await u.validateWorkItemStates(S,M,o,i,r,I,c,"replace_in_files")
|
|
5524
5529
|
Date.now(),O=Date.now()
|
|
5525
|
-
const t=await u.autoPromoteTaskStatus(S,D.status,$,e.request?.status,M,o,i,
|
|
5526
|
-
t.taskPromoted&&
|
|
5527
|
-
const n=await u.ensureCorrectWorkspaceContext({taskPromoted:t.taskPromoted,requestId:$,context:r,operation:"replace_in_files",logger:
|
|
5530
|
+
const t=await u.autoPromoteTaskStatus(S,D.status,$,e.request?.status,M,o,i,I,c,"replace_in_files")
|
|
5531
|
+
t.taskPromoted&&I.info("Auto-promoted task to in_progress",{taskId:S,requestId:$,previousStatus:D.status,newStatus:t.newTaskStatus}),Date.now(),O=Date.now()
|
|
5532
|
+
const n=await u.ensureCorrectWorkspaceContext({taskPromoted:t.taskPromoted,requestId:$,context:r,operation:"replace_in_files",logger:I,metrics:c,metricsPrefix:"replace_in_files"})
|
|
5528
5533
|
if(!n.success){if(n.isLockConflict)return{content:[{type:"text",text:"\u274c "+n.error}],isError:!0}
|
|
5529
|
-
throw Error(n.error)}Date.now(),F=!0}if(R.length>0&&$)try{await(0,p.validateRequestStatusForDocumentOperation)($,i,
|
|
5534
|
+
throw Error(n.error)}Date.now(),F=!0}if(R.length>0&&$)try{await(0,p.validateRequestStatusForDocumentOperation)($,i,I,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
5530
5535
|
throw e}O=Date.now()
|
|
5531
5536
|
const N=new Map
|
|
5532
|
-
if(
|
|
5537
|
+
if(I.info("\u{1f50d} Starting external edit detection",{hasFileOperations:A,hasGit:!!r.git,operationCount:T.length}),A&&r.git)for(const e of T)if(e.path&&!e.documentId)try{const t=u.validateAndNormalizePath(e.path,r),n=await l.default.readFile(t.fullPath,"utf8"),o=void 0!==e.fuzzy_match?e.fuzzy_match:P,s=[]
|
|
5533
5538
|
for(const t of e.replacements){const r=(0,h.findMatches)(n,t.old,o,100,e.path)
|
|
5534
5539
|
s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,t.fullPath)
|
|
5535
|
-
|
|
5536
|
-
const i=await(0,w.detectExternalEdits)(r.git,o,
|
|
5537
|
-
|
|
5538
|
-
const e=await(0,f.commitUserChangesBeforeToolOperation)(r.git,"replace_in_files",{requestId:$,taskId:S,workspaceManager:r.workspaceManager},
|
|
5539
|
-
e.userChangesCommitted&&(
|
|
5540
|
-
const{toolRecordId:L}=await u.createFileOperationRecords(S,$,r.projectId,"replace-in-files",M,{operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,userComment:j},o,s,
|
|
5540
|
+
I.info("\u{1f50d} Checking for external edits",{path:t.normalizedPath,affectedLines:o.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),matchCount:s.length})
|
|
5541
|
+
const i=await(0,w.detectExternalEdits)(r.git,o,I)
|
|
5542
|
+
I.info("\u{1f50d} External edit detection result",{path:t.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?(N.set(e.path,{message:i.message,debugInfo:i.debugInfo}),I.warn("\u26a0\ufe0f External edits detected before auto-commit",{path:t.normalizedPath,conflictingLines:i.conflictingLines})):(i.debugInfo&&N.set(e.path,{message:"",debugInfo:i.debugInfo}),I.info("\u2705 No external edit conflicts detected",{path:t.normalizedPath}))}else I.info("\u2139\ufe0f No matches found for external edit detection",{path:t.normalizedPath}),N.set(e.path,{message:"",debugInfo:{detectionRan:!1,reason:"No matches found - patterns not found in file",affectedRegion:"none",uncommittedChanges:"not checked",overlapDetected:!1}})}catch(t){I.warn("Failed to check for external edits before auto-commit",{path:e.path,error:(0,k.getErrorMessage)(t)})}if(Date.now(),O=Date.now(),A&&r.git)try{I.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
|
|
5543
|
+
const e=await(0,f.commitUserChangesBeforeToolOperation)(r.git,"replace_in_files",{requestId:$,taskId:S,workspaceManager:r.workspaceManager},I,c)
|
|
5544
|
+
e.userChangesCommitted&&(I.debug("[REPLACE-IN-FILES] User changes committed",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),I.info("User changes committed before batch operation",{taskId:S,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){I.warn("Pre-tool user changes commit failed",{taskId:S,error:e instanceof Error?e.message:e+""})}Date.now(),O=Date.now(),_=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5545
|
+
const{toolRecordId:L}=await u.createFileOperationRecords(S,$,r.projectId,"replace-in-files",M,{operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,userComment:j},o,s,I,c,"replace_in_files",b)
|
|
5541
5546
|
C=L,Date.now(),O=Date.now(),_=u.FileOperationPhase.STRING_REPLACEMENT,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5542
5547
|
const z=[],H=[]
|
|
5543
5548
|
for(const e of T){const t=e.path?N.get(e.path):void 0,o=await n(e,P,r,0,0,t?.message,t?.debugInfo)
|
|
5544
5549
|
z.push(o),o.successfulReplacements>0&&"file"===o.type&&o.path&&H.push(o.path)}Date.now(),O=Date.now()
|
|
5545
|
-
const B=T.filter((e=>e.path&&!e.documentId)).map((e=>({path:e.path}))),U=await u.handleMultiFileGitCommit(S,B,z,H.length,{operationType:"Replace in files",toolRecordId:L||C||"unknown",successField:"successfulReplacements",logger:
|
|
5550
|
+
const B=T.filter((e=>e.path&&!e.documentId)).map((e=>({path:e.path}))),U=await u.handleMultiFileGitCommit(S,B,z,H.length,{operationType:"Replace in files",toolRecordId:L||C||"unknown",successField:"successfulReplacements",logger:I,metrics:c,metricsPrefix:"replace_in_files"},r),G=U.commitHash
|
|
5546
5551
|
Date.now(),Date.now()
|
|
5547
5552
|
const W=z.filter((e=>e.success)).length,V=z.length-W,J=z.reduce(((e,t)=>e+t.successfulReplacements),0),K=z.reduce(((e,t)=>e+t.failedReplacements),0),Y=z.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,replacements:e.replacements.map((e=>({old_str:e.old,new_str:e.new,success:e.success,error:e.error,matchesFound:e.matchesFound,matchType:e.matchType,lines:e.lines})))}))),Q=z.filter((e=>e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements}))),Z=z.filter((e=>!e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,error:e.error,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements})))
|
|
5548
5553
|
await s.updateToolRecord(C,{metadata:{path:M,status:0===V?"completed":"partial",operationCount:T.length,operations:Y,successfulFiles:Q,failedFiles:Z,successfulReplacements:J,failedReplacements:K,processingTime:Date.now()-v,userComment:j,...U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}}})
|
|
@@ -5559,7 +5564,7 @@ if(s.length>0){l+="\n**Failed Replacement Details:**\n"
|
|
|
5559
5564
|
for(const e of s)l+=`- \u274c \`${e.old.substring(0,40)}${e.old.length>40?"...":""}\` \u2192 \`${e.new.substring(0,40)}${e.new.length>40?"...":""}\`: ${e.error}\n`,e.details&&e.details.length>0&&(l+=" **Candidates found:**\n",l+=e.details.slice(0,5).map((e=>` - Line ${e.line}: \`${e.actually_matched.substring(0,40)}${e.actually_matched.length>40?"...":""}\` (${e.match_type})`)).join("\n")+"\n",e.details.length>5&&(l+=` ... and ${e.details.length-5} more matches\n`)),e.similarMatches&&e.similarMatches.length>0&&(l+=" **Did you mean? (Similar matches found):**\n",l+=e.similarMatches.map((e=>` - Line ${e.line}: \`${e.text.substring(0,60)}${e.text.length>60?"...":""}\` (${e.reason}, similarity: ${(100*e.similarity).toFixed(0)}%)`)).join("\n")+"\n")}l+="\n"}const d=e.filter((e=>"document"===e.type&&(e.success||e.successfulReplacements>0)))
|
|
5560
5565
|
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)
|
|
5561
5566
|
return{content:[{type:"text",text:X}],isError:0===J}}catch(e){const t=Date.now()-v
|
|
5562
|
-
if(
|
|
5567
|
+
if(I.error("Replace in files batch operation failed",{error:e instanceof Error?e.stack:e+"",duration:t,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{status:"failed",error:(0,k.getErrorMessage)(e),phase:_,duration:t}})}catch(e){}return c.incrementCounter("replace_in_files_errors",1,{phase:_}),{content:[{type:"text",text:"\u274c **Replace In Files Failed:** "+(0,k.getErrorMessage)(e)}],isError:!0}}},c(t(857))
|
|
5563
5568
|
const l=c(t(1943)),d=(a(t(9896)),a(t(6928)),c(t(6982)),t(6183)),u=a(t(5967)),h=t(3626),g=t(9860),p=t(5003),f=t(7478),m=t(9949),y=t(9947),w=t(1318),k=t(8824)},9470(e,exports){"use strict"
|
|
5564
5569
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseLineSpec=function(e){if(!e||""===e.trim())throw Error("Line specification cannot be empty")
|
|
5565
5570
|
const t=e.trim()
|