alchemylab 1.2.4 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/640.js +14 -0
- package/dist/cli.js +177 -90
- package/dist/http-server.js +619 -582
- package/dist/index.js +411 -374
- package/dist/mcp-direct.js +152 -115
- package/package.json +1 -1
package/dist/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,I=k.localId||k.id||"tas"+Date.now().toString().substring(5,11),b=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:I,requestId:_,title:b})
|
|
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:I,requestId:_,projectId:d,type:"create-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:b,taskDescription:v,taskStatus:C},note:"Created task "+b})
|
|
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:I,requestId:_})}g({success:!0,requestId:c.requestId,projectId:d}),h.info("Task created successfully",{taskId:I,requestId:_,title:b,projectId:d})
|
|
29
|
+
let S=`Created Task ${k.sequenceNumber&&_?(0,i.formatTaskRef)(_,k.sequenceNumber):I}: ${b}`
|
|
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),I=new Set,b=t(9860),v=t(1472),C=t(3328),_=t(8955),E=t(3217),q=t(5278),S=t(446),T=t(9060),P=t(8824),j=(0,p.createLogger)({serviceName:"stdout-capture",console:!1,logToFile:!1}),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(I.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,b.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")
|
|
@@ -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 I=g.limit||20,b=w.slice(0,I)
|
|
160
|
+
if(0===b.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 ${b.length} request${1===b.length?"":"s"} matching "${a}":\n\n`
|
|
162
|
+
for(const e of b){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:b.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 I=d.git
|
|
227
227
|
if(d.workspaceManager){const e=d.workspaceManager.getCurrentContext(d.currentSessionId)
|
|
228
228
|
if("multi-agent"===e.mode&&e.requestId){const{simpleGit}=t(3807)
|
|
229
|
-
|
|
230
|
-
if(
|
|
229
|
+
I=simpleGit({baseDir:e.basePath,binary:d.gitBinary}),p.debug("Using workspace-aware git instance for task completion",{taskId:h,mode:e.mode,requestId:e.requestId,basePath:e.basePath})}}let b=null
|
|
230
|
+
if(I)try{(await I.status()).isClean()||(b=(await I.commit(`Complete task ${h}: ${m}`)).commit,p.info("Created commit for task completion",{taskId:h,commitId:b}))}catch(e){p.warn("Failed to commit changes",{error:(0,c.getErrorMessage)(e)})}let v=null
|
|
231
231
|
try{const e=u.getToolRecordClient()
|
|
232
|
-
e&&(v={id:(await e.createToolRecord({taskId:h,requestId:k.requestId,projectId:y,type:"complete-task",metadata:{status:"completed",timestamp:(new Date).toISOString(),taskTitle:k.title,completionSummary: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:b,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:b,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}]`),b&&(a+="\nCommit: "+b.substring(0,8)),o)try{const e=await w.listTasks({requestId:o})
|
|
237
237
|
p.info("Raw tasks list response data",{responseData:JSON.stringify(e)}),p.debug("Tasks list response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
|
|
238
238
|
const t=(0,s.extractArrayFromResponse)(e,{logger:p,operationName:"listTasksForProgress",defaultValue:[]}),r=t.length,n=t.filter((e=>"completed"===e.status)).length
|
|
239
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 b.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,I.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,I.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,I.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),I=t(8824),b=t(2968),v=t(6153),C=t(1887),_=t(1666),E=t(9884),q=t(922),S=t(3328)},1253(e,exports,t){"use strict"
|
|
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"
|
|
@@ -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>=b||c>10)return a.debug("Stopping search in directory - hard cap or depth limit reached",{dir:e,matchesCount:o.length,hardCap:b,depth:c}),{filesCount:p,fileMatchesCount: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(I.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>=b)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>=b)return{filesCount:p,fileMatchesCount:f,subdirCount:m,subdirStats:y}
|
|
622
|
+
o.push(e)}}}}for(const{entry:e,fullPath:n}of C){if(o.length>=b)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<b;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 I=0
|
|
661
|
+
const b={searchDirectory:"",resolvedPath:"",patternInfo:{needle:"",regex:"",caseSensitive:!1,fileExtension:"",normalizedExtension:""},environmentInfo:{platform:process.platform,nodeVersion:process.version,hostname:p.default.hostname(),username:p.default.userInfo().username,workingDirectory:process.cwd(),contextBasePath:t?.basePath||"unknown"},startTime:u,endTime:0,phases:{initializationTime:0,searchTime:0,directoryListingTime:0},totalFiles:0,totalMatches:0,directoryStats:[],errors:[]}
|
|
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 b.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(b.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
|
+
b.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 b.errors.push(t),Error(t)}const E=v.maxResults||50,q=v.caseSensitive||!1,S=v.useRegex||!1,T=v.fileExtension,P=v.searchIn||"content"
|
|
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 b.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 b.errors.push(t),(0,f.createValidationError)(t)}if(b.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
|
+
b.initialScan={totalEntries:t.length,directories:r,files:n,firstFewFiles:n.slice(0,10),scanTime:Date.now()-e},b.phases.directoryListingTime=b.initialScan.scanTime}catch(e){const t="Failed to scan directory contents: "+(0,k.getErrorMessage)(e)
|
|
681
|
+
b.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}}),I=Date.now(),b.phases.initializationTime=I-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,b)
|
|
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`),b.phases.searchTime=Date.now()-O}catch(e){const t="Error during search: "+(0,k.getErrorMessage)(e)
|
|
705
|
+
b.errors.push(t),l.error(t),b.phases.searchTime=Date.now()-O}b.totalFiles=$,b.totalMatches=D.length,b.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:b})
|
|
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+""}),b.errors.push((0,k.getErrorMessage)(t)),b.endTime=Date.now(),l.debug("Search diagnostic information on error",{diagnostic:b})
|
|
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),I=["node_modules"],b=1e4,v=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore"]),C=1048576},1318(e,exports,t){"use strict"
|
|
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
|
|
@@ -804,41 +804,44 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
|
|
|
804
804
|
var t={}
|
|
805
805
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
806
806
|
return s(t,e),t})
|
|
807
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=void 0,exports.registerTools=function(e,
|
|
808
|
-
|
|
809
|
-
const
|
|
810
|
-
try{return await
|
|
811
|
-
|
|
807
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=void 0,exports.registerTools=function(e,n,o,s,i,g,m){const y=s.child({component:"tools"})
|
|
808
|
+
y.info("Registering tools...")
|
|
809
|
+
const w=!!g,k=async()=>{if(!w)return!0
|
|
810
|
+
try{return await g.hasValidToken()}catch(e){return y.error("Error checking authentication status",{error:(0,l.getErrorMessage)(e)}),!1}},I=async()=>{const e=(0,c.areTestsRequiredForCompletion)(),t=await k()
|
|
811
|
+
y.info(`Generating tools list with testsRequired=${e}, authenticated=${t}`)
|
|
812
812
|
const r={testsRequired:e,authenticated:t}
|
|
813
813
|
return(0,f.generateVisibleToolsList)(r)}
|
|
814
|
-
let b=
|
|
815
|
-
b.then((e=>{
|
|
816
|
-
let
|
|
817
|
-
e.setRequestHandler(a.CallToolRequestSchema,(async e=>{try{const{name:
|
|
818
|
-
const
|
|
814
|
+
let b=I(),v=[]
|
|
815
|
+
b.then((e=>{v=e})).catch((e=>{y.error("Error generating initial tools list",{error:(0,l.getErrorMessage)(e)}),v=[]})),e.setRequestHandler(a.ListToolsRequestSchema,(async()=>{try{return v=await I(),{tools:v}}catch(e){return y.error("Error generating tools list",{error:(0,l.getErrorMessage)(e)}),{tools:[]}}}))
|
|
816
|
+
let C=!1
|
|
817
|
+
e.setRequestHandler(a.CallToolRequestSchema,(async e=>{try{const{name:a,arguments:c={},_meta:g}=e.params;(0,p.logSessionIdentity)(a,"_meta-debug",{has_meta:!!g,sessionId:g?.sessionId||null,messageId:g?.messageId||null,paramKeys:Object.keys(e.params)}),y.info("Tool call received: "+a,{tool:a}),i.incrementCounter("tool_calls_total",1,{tool:a})
|
|
818
|
+
const I=i.startTimer("tool_execution_time")
|
|
819
819
|
Date.now()
|
|
820
820
|
let b=Date.now()
|
|
821
|
-
const
|
|
822
|
-
if(Date.now(),b=Date.now(),
|
|
823
|
-
if(Date.now(),!e)return
|
|
824
|
-
let
|
|
825
|
-
if(b=Date.now(),
|
|
826
|
-
if(
|
|
827
|
-
else{const
|
|
828
|
-
u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:
|
|
829
|
-
u.sessionIdentity.setCurrentCallOrigin(
|
|
830
|
-
const E
|
|
831
|
-
if(
|
|
832
|
-
try{const e=await(0,d.getServerUrl)(
|
|
833
|
-
e&&
|
|
834
|
-
if(e?.sessionId&&t){const r=t.match(/^requests\/(.+)$/),
|
|
835
|
-
if(r&&!
|
|
836
|
-
|
|
837
|
-
try{const{sessionTag:r}=(0,h.getGlobalClientInfo)(),o
|
|
838
|
-
await Promise.all([i,a])}catch(e){
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
821
|
+
const v=r(c)
|
|
822
|
+
if(Date.now(),b=Date.now(),w){const e=await k()
|
|
823
|
+
if(Date.now(),!e)return y.warn("Unauthenticated tool call attempt",{tool:a}),{content:[{type:"text",text:"Authentication required. Please run 'alchemylab setup' to authenticate and configure your project."}],isError:!0}}const _=(0,f.getToolByName)(a)
|
|
824
|
+
let E
|
|
825
|
+
if(b=Date.now(),o?(o.setOptions({createRecords:_?.createsRecords??!1}),y.info(`Setting record creation for tool ${a}: ${_?.createsRecords??!1}`)):y.debug(`No API client available for tool ${a} (minimal mode)`),Date.now(),Date.now(),b=Date.now(),g?.sessionId){const e=g.sessionId,t=g.messageId,r=u.sessionIdentity.getIdentity()
|
|
826
|
+
if(r)r.sessionId!==e&&((0,p.logSessionIdentity)(a,"_meta-session-switch",{prevSessionId:r.sessionId,prevAgentType:r.agentType,newSessionId:e}),u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:r.serverUrl}),n?.workspaceManager?.resetCurrentContext?.(e))
|
|
827
|
+
else{const t=await(0,d.getServerUrl)(n,y)
|
|
828
|
+
u.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:t||""})}E={providerId:"opencode",sessionId:e,messageId:t,createdAt:(new Date).toISOString()},(0,p.logSessionIdentity)(a,"_meta",{sessionId:e,messageId:t})}else y.warn("No _meta.sessionId on tool call \u2014 session identity unavailable",{tool:a})
|
|
829
|
+
u.sessionIdentity.setCurrentCallOrigin(E)
|
|
830
|
+
const q=E?.sessionId||g?.sessionId
|
|
831
|
+
if(n?.workspaceManager){b=Date.now()
|
|
832
|
+
try{const e=await(0,d.getServerUrl)(n,y)
|
|
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
|
|
834
|
+
if(e?.sessionId&&t){const r=t.match(/^requests\/(.+)$/),n="1"===process.env.ALCHEMY_ALLOW_PARALLEL
|
|
835
|
+
if(r&&!n){const t=r[1]
|
|
836
|
+
C=!0
|
|
837
|
+
try{const{sessionTag:r}=(0,h.getGlobalClientInfo)(),n=o.getSessionTagMappingClient(),s=o.getRequestClient(),i=n?n.getMappingByOpencodeSessionId(e.sessionId).then((t=>{t?((0,h.setSessionTag)(t.sessionTag),y.info("Recovered session tag from mapping",{opencodeSessionId:e.sessionId,sessionTag:t.sessionTag})):(n.createOrUpdateMapping(r,e.sessionId).catch((()=>{})),y.info("Registered session tag mapping",{opencodeSessionId:e.sessionId,sessionTag:r}))}),(e=>y.debug("Mapping lookup failed",{error:(0,l.getErrorMessage)(e)}))):Promise.resolve(),a=s.lockRequest?s.lockRequest(t,r).then((e=>{e.locked?y.info("Acquired request lock",{requestId:t,sessionTag:r}):y.warn("Failed to acquire request lock",{requestId:t,sessionTag:r})}),(e=>y.warn("Lock acquisition failed",{error:(0,l.getErrorMessage)(e)}))):Promise.resolve()
|
|
838
|
+
await Promise.all([i,a])}catch(e){y.warn("Error in session tag mapping / lock acquisition",{error:(0,l.getErrorMessage)(e)})}}}}n&&(n.currentSessionId=q||"__unknown__")
|
|
839
|
+
const S=`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,T=e=>{const{getActionServerBaseUrl:r}=t(9414)
|
|
840
|
+
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
|
+
let P
|
|
842
|
+
T("start")
|
|
843
|
+
try{if(_){const e={context:n,apiClient:o,logger:s,metrics:i,mcpServer:m,cliOrigin:E}
|
|
844
|
+
P=await _.handler(v,e)}else y.info(`Tool ${a} not found, returning negative response`),P={content:[{type:"text",text:`The tool '${a}' does not exist.`}]}}finally{T("end")}return Date.now(),Date.now(),I({tool:a,success:!0}),P}catch(t){y.error("Error executing tool:",{error:t instanceof Error?t.stack:t+"",tool:e.params.name}),i.incrementCounter("tool_errors_total",1,{tool:e.params.name,error:t instanceof Error?t.name:"unknown"})
|
|
842
845
|
let r="Unknown error"
|
|
843
846
|
if(t instanceof Error)r=t.message
|
|
844
847
|
else if("string"==typeof t)r=t
|
|
@@ -851,7 +854,7 @@ else if(e.body&&"string"==typeof e.body)try{const t=JSON.parse(e.body)
|
|
|
851
854
|
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))
|
|
852
855
|
if(t.length>0){const n=t[0]
|
|
853
856
|
r=`${n}: ${e[n]}`}else r="Unknown error (no readable properties)"}}else r=t+""
|
|
854
|
-
return{content:[{type:"text",text:"Error: "+r}],isError:!0}}})),
|
|
857
|
+
return{content:[{type:"text",text:"Error: "+r}],isError:!0}}})),y.info("Tools registration complete")}
|
|
855
858
|
const a=t(9150),c=t(2478),l=t(8824),d=t(7617),u=t(6688),h=t(5172)
|
|
856
859
|
i(t(9896)),i(t(6928))
|
|
857
860
|
var g=t(7280)
|
|
@@ -1189,12 +1192,12 @@ exports.def={name:"complete_task",description:"Mark a task as completed with a s
|
|
|
1189
1192
|
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
|
|
1190
1193
|
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}
|
|
1191
1194
|
try{const e=s?.sessionId
|
|
1192
|
-
let n=
|
|
1195
|
+
let n=I.sessionIdentity.getIdentity()?.agentType
|
|
1193
1196
|
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`
|
|
1194
1197
|
r(t,"Looking up agent type from action server",{sessionId:e,url:o})
|
|
1195
1198
|
const s=await fetch(o)
|
|
1196
1199
|
if(s.ok){const o=await s.json()
|
|
1197
|
-
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,
|
|
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,I.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)
|
|
1198
1201
|
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
|
|
1199
1202
|
try{const e=await async function(e){try{const t=`http://localhost:${T}/api/agents/by-name/${encodeURIComponent(e)}`,r=await fetch(t)
|
|
1200
1203
|
if(!r.ok)return null
|
|
@@ -1223,8 +1226,8 @@ if(r.data?.defaultModel){const[t,...n]=r.data.defaultModel.split("/")
|
|
|
1223
1226
|
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)})
|
|
1224
1227
|
if(!r.ok){const e=await r.text().catch((()=>"Unknown error"))
|
|
1225
1228
|
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")
|
|
1226
|
-
const o=p;(0,
|
|
1227
|
-
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:
|
|
1229
|
+
const o=p;(0,b.logSessionIdentity)("subagent_operations.spawn","_meta",{parentSessionId:o})
|
|
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:I.sessionIdentity.getIdentity()?.agentType}),signal:AbortSignal.timeout(15e3)})
|
|
1228
1231
|
if(!d.ok){const e=await d.text().catch((()=>"Unknown error"))
|
|
1229
1232
|
throw Error(`Spawn session endpoint failed: ${d.status} ${e}`)}const u=await d.json()
|
|
1230
1233
|
if(!u.success||!u.data)throw Error(u.error||"Spawn session returned unsuccessful")
|
|
@@ -1271,7 +1274,7 @@ let f={input:0,output:0,reasoning:0},m="",y=c(null,h.time.updated)
|
|
|
1271
1274
|
if(p.ok){const e=await p.json()
|
|
1272
1275
|
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)
|
|
1273
1276
|
const t=i(e)
|
|
1274
|
-
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,
|
|
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,I=y.isReady,b=f.input+f.output+f.reasoning
|
|
1275
1278
|
let v="",C="",_=null
|
|
1276
1279
|
if(o)try{const t=o.getSessionRequestAssociationClient()
|
|
1277
1280
|
if(t){const r=await t.getActiveRequestsForSession(e,!1)
|
|
@@ -1286,7 +1289,7 @@ if(e.trim())return l(e)}try{const t=n(`git log main --merges --oneline -n 50 --g
|
|
|
1286
1289
|
if(t){const e=t.split("\n")[0].split(" ")[0],o=n(`git diff ${e}^1...${e} --numstat`,{cwd:r,encoding:"utf8"})
|
|
1287
1290
|
if(o.trim())return{...l(o),merged:!0}}}catch{}return null}catch{return null}}(_,r.basePath)
|
|
1288
1291
|
if(e){const t=e.additions+e.deletions,r=e.merged?" (merged)":""
|
|
1289
|
-
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: ${
|
|
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: ${I?"Yes":"No"}\nAge: ${s(w)}\nTokens: ${b.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)
|
|
1290
1293
|
if(!n)throw new y.ValidationError("Could not determine OpenCode server URL")
|
|
1291
1294
|
r.info("Aborting subagent session",{sessionId:e})
|
|
1292
1295
|
try{const t=`${n.replace(/\/$/,"")}/session/${e}/abort`,o=await fetch(t,{method:"POST"})
|
|
@@ -1304,14 +1307,14 @@ const m=g.replace(/\/$/,"")+"/session/status",y=await fetch(m),w=y.ok?await y.js
|
|
|
1304
1307
|
let k=p
|
|
1305
1308
|
if(o&&(k=k.filter((e=>"idle"!==(w[e.id]?.type||"idle")))),void 0!==h){const e=36e5*h,t=Date.now()-e
|
|
1306
1309
|
k=k.filter((e=>e.time.created>=t))}if(0===k.length)return{content:[{type:"text",text:"No sessions match the specified filters."}]}
|
|
1307
|
-
let
|
|
1308
|
-
const
|
|
1310
|
+
let I={}
|
|
1311
|
+
const b=k.map((e=>e.id))
|
|
1309
1312
|
let v={},C=[]
|
|
1310
|
-
if("specialist"===n.agentType){const e=new Set(
|
|
1313
|
+
if("specialist"===n.agentType){const e=new Set(b)
|
|
1311
1314
|
for(const t of f){const r=t.parentId||t.parentID
|
|
1312
1315
|
r&&e.has(r)&&(v[r]||(v[r]=[]),v[r].push(t.id),C.push(t.id))}}if(r)try{const e=r.getCLISessionClient()
|
|
1313
|
-
if(e){const t=[...
|
|
1314
|
-
|
|
1316
|
+
if(e){const t=[...b,...C]
|
|
1317
|
+
I=await e.batchEnrich(t)}}catch{}const _=g.replace(/\/$/,""),E=await Promise.allSettled(k.map((e=>fetch(`${_}/session/${e.id}/message`).then((e=>e.ok?e.json():[])).catch((()=>[]))))),q=[]
|
|
1315
1318
|
for(let e=0;e<k.length;e++){const t=k[e],r=Date.now()-t.time.created
|
|
1316
1319
|
let o=0,s=null,l=[],h=c(null,t.time.updated)
|
|
1317
1320
|
const g=E[e],p="fulfilled"===g.status?g.value:[]
|
|
@@ -1320,24 +1323,24 @@ if(p.length>0){const e=i(p)
|
|
|
1320
1323
|
h=c(e.lastActivityTime,t.time.updated),s=e.current||null,l=e.recent}const f=h.status
|
|
1321
1324
|
if(void 0!==d&&d>o)continue
|
|
1322
1325
|
if(void 0!==u&&o>u)continue
|
|
1323
|
-
const m=
|
|
1326
|
+
const m=I[t.id]
|
|
1324
1327
|
if(n.agentType&&(!m||m.agentType!==n.agentType))continue
|
|
1325
1328
|
if("archived"===m?.status)continue
|
|
1326
1329
|
let y=""
|
|
1327
|
-
const
|
|
1330
|
+
const b=[],C=[]
|
|
1328
1331
|
m?.associations&&C.push(...m.associations)
|
|
1329
1332
|
const _=v[t.id]
|
|
1330
|
-
if(_)for(const e of _){const t=
|
|
1333
|
+
if(_)for(const e of _){const t=I[e]
|
|
1331
1334
|
if(t?.associations){const r=w[e]?.type||"idle",n="idle"===r||"stalled"===r
|
|
1332
1335
|
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
|
|
1333
1336
|
for(const t of C){const r=e.get(t.requestLocalId)
|
|
1334
1337
|
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))
|
|
1335
|
-
|
|
1338
|
+
b.push(...t,...r)
|
|
1336
1339
|
const n=[]
|
|
1337
1340
|
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
|
|
1338
|
-
n.push(`prev: ${t.join(", ")}${o>0?` +${o} more`:""}`)}n.length>0&&(y=` [${n.join(" | ")}]`)}if(a&&!
|
|
1341
|
+
n.push(`prev: ${t.join(", ")}${o>0?` +${o} more`:""}`)}n.length>0&&(y=` [${n.join(" | ")}]`)}if(a&&!b.includes(a))continue
|
|
1339
1342
|
const S=t.title||"Untitled",T=S.length>50?S.slice(0,47)+"...":S
|
|
1340
|
-
q.push({id:t.id,title:T,status:f,age:r,totalTokens:o,requestsInfo:y,allRequestIds:
|
|
1343
|
+
q.push({id:t.id,title:T,status:f,age:r,totalTokens:o,requestsInfo:y,allRequestIds:b,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."}]}
|
|
1341
1344
|
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(", "):""
|
|
1342
1345
|
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})`:""
|
|
1343
1346
|
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)
|
|
@@ -1380,7 +1383,7 @@ case"list-sessions":const s={activeOnly:r.activeOnly,requestId:r.requestId,limit
|
|
|
1380
1383
|
f=await h(t,c,i,s)
|
|
1381
1384
|
break
|
|
1382
1385
|
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}}}
|
|
1383
|
-
const y=t(9860),w=t(8035),k=t(7617),
|
|
1386
|
+
const y=t(9860),w=t(8035),k=t(7617),I=t(6688),b=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"
|
|
1384
1387
|
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}}
|
|
1385
1388
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectContext=void 0,exports.projectContextMiddleware=r
|
|
1386
1389
|
const o=n(t(9896)),s=n(t(6928)),i=t(4139),a=t(4055),c=t(8824)
|
|
@@ -1539,18 +1542,18 @@ try{const e=d(t.command,{cwd:h,timeout:1e3*t.timeout,encoding:"utf-8",stdio:["pi
|
|
|
1539
1542
|
p.push({name:t.name,command:t.command,exitCode:0,output:e.slice(-4e3),timedOut:!1})}catch(r){const n=!0===r.killed,o=((r.stdout||"")+"\n"+(r.stderr||"")).trim().slice(-4e3),s=r.status??1
|
|
1540
1543
|
if(p.push({name:t.name,command:t.command,exitCode:s,output:o,timedOut:n}),"setup"===e.commandName)break}}const f=p.every((e=>0===e.exitCode)),m=p.map((e=>{const t=e.timedOut?"\u23f1 TIMEOUT":0===e.exitCode?"\u2705 PASS":`\u274c FAIL (exit ${e.exitCode})`
|
|
1541
1544
|
return`### ${e.name}: ${t}\n\`\`\`\n$ ${e.command}\n${e.output}\n\`\`\``})).join("\n\n")
|
|
1542
|
-
return a({success:!0}),{content:[{type:"text",text:`## ${"setup"===e.commandName?"Setup":e.commandName} \u2014 ${f?"PASSED":"FAILED"}\n\n${m}`}]}}catch(e){return a({success:!1,error:"execution_error"}),{content:[{type:"text",text:"Failed to execute test command: "+(0,r.getErrorMessage)(e)}],isError:!0}}},exports.handleReportTestResults=async function(e,o,s,i,a){const
|
|
1543
|
-
try{const{sessionIdentity:
|
|
1544
|
-
if(!
|
|
1545
|
-
const
|
|
1546
|
-
if(!
|
|
1547
|
-
const f
|
|
1548
|
-
await s.proxyPatch(`/api/projects/${o.projectId}/test-runs/${
|
|
1549
|
-
const
|
|
1545
|
+
return a({success:!0}),{content:[{type:"text",text:`## ${"setup"===e.commandName?"Setup":e.commandName} \u2014 ${f?"PASSED":"FAILED"}\n\n${m}`}]}}catch(e){return a({success:!1,error:"execution_error"}),{content:[{type:"text",text:"Failed to execute test command: "+(0,r.getErrorMessage)(e)}],isError:!0}}},exports.handleReportTestResults=async function(e,o,s,i,a,c){const l=a.startTimer("tool_execution_time")
|
|
1546
|
+
try{const{sessionIdentity:d}=await Promise.resolve().then(t.bind(t,6688)),u=await d.getSessionRequestId(s,i,c?.sessionId)
|
|
1547
|
+
if(!u)return l({success:!1,error:"no_request_association"}),{content:[{type:"text",text:"Cannot report test results: this session is not associated with a request."}],isError:!0}
|
|
1548
|
+
const h=await s.proxyGet(`/api/projects/${o.projectId}/requests/${u}/test-runs`),g=h?.data||h||[],p=Array.isArray(g)?g:[],f=p.find((e=>"pending"===e.status||"running"===e.status))||p[0]
|
|
1549
|
+
if(!f)return l({success:!1,error:"no_test_run"}),{content:[{type:"text",text:`No test run found for request ${u}.`}],isError:!0}
|
|
1550
|
+
const m=f.id
|
|
1551
|
+
await s.proxyPatch(`/api/projects/${o.projectId}/test-runs/${m}`,{status:e.status,results:e.results})
|
|
1552
|
+
const y="passed"===e.status?"\u2705":"failed"===e.status?"\u274c":"\u26a0\ufe0f"
|
|
1550
1553
|
try{const t=s.getRequestClient()
|
|
1551
|
-
"passed"===e.status?(await t.updateRequest(
|
|
1552
|
-
try{const t=await(0,n.handleSessionMessageOperations)({operation:"send",type:"report",status:"passed"===e.status?"success":"failure",summary:
|
|
1553
|
-
return
|
|
1554
|
+
"passed"===e.status?(await t.updateRequest(u,{status:"ready_for_merge"}),i.info("Tests passed, set request to ready_for_merge",{requestId:u})):(await t.updateRequest(u,{status:"in_progress"}),i.info("Tests failed, set request back to in_progress",{requestId:u}))}catch(e){i.warn("Failed to update request status after test results",{requestId:u,error:(0,r.getErrorMessage)(e)})}const w="passed"===e.status?"\n\nAll tests passed \u2014 the coder can now call `merge` to merge this request.":"\n\nTests failed \u2014 the coder should fix the issues and call `complete` again.",k=`${y} Test run ${e.status} for request ${u}\n\n${e.results.summary}${w}`
|
|
1555
|
+
try{const t=await(0,n.handleSessionMessageOperations)({operation:"send",type:"report",status:"passed"===e.status?"success":"failure",summary:k,details:e.results.commands?.map((e=>`${"passed"===e.status?"\u2705":"\u274c"} ${e.name}: ${e.status}${e.diagnosis?" - "+e.diagnosis:""}`)).join("\n"),finish:!0},o,i,a,s,c),r=t?.content?.[0]?.text||"unknown",d=t?.isError
|
|
1556
|
+
return l({success:!0}),{content:[{type:"text",text:`Test run for request ${u} reported as **${e.status}**.${d?" Parent notification FAILED: "+r:" Parent session notified."}\n\n${e.results.summary}`}]}}catch(t){return l({success:!0}),{content:[{type:"text",text:`Test run for request ${u} reported as **${e.status}** but failed to notify parent: ${(0,r.getErrorMessage)(t)}\n\n${e.results.summary}`}]}}}catch(e){return l({success:!1,error:"api_error"}),{content:[{type:"text",text:"Failed to report test results: "+(0,r.getErrorMessage)(e)}],isError:!0}}},exports.handleTestingReference=async function(e,t,r,n,o){return o.startTimer("tool_execution_time")({success:!0}),{content:[{type:"text",text:'# Test Process Design Guide\n\n## Overview\n\nA test process defines how to verify code changes for a project. It consists of:\n- **Setup**: Commands to prepare the environment (install deps, link node_modules, etc.) \u2014 runs once per worktree\n- **Commands**: The actual test commands (build, lint, test, etc.) \u2014 the verification steps\n\n## Command Properties\n\n- **name**: Human-readable name (e.g., "Build", "Unit Tests")\n- **command**: Shell command to run (e.g., `npm test`)\n- **required** (default: true): If a required command fails, the request won\'t be merged\n- **timeout** (default: 300s): Maximum execution time. Exit code 0 = pass, non-zero = fail.\n\n## Scope (Monorepo Support)\n\nSet `scope` to a path prefix to limit when a process runs:\n- `scope: "packages/api/"` \u2192 only runs when files under packages/api/ change\n- `scope: null` \u2192 runs for all changes (global process)\n\nMultiple active processes per project are supported.\n\n## Common Patterns\n\n### Node.js / TypeScript\n```json\n{\n "setup": ["ln -s ../../node_modules node_modules"],\n "commands": [\n { "name": "Build", "command": "npm run build" },\n { "name": "Lint", "command": "npm run lint", "required": false },\n { "name": "Unit Tests", "command": "npm test" }\n ]\n}\n```\n\n### Python\n```json\n{\n "setup": ["pip install -e \'.[dev]\'"],\n "commands": [\n { "name": "Type Check", "command": "mypy src/" },\n { "name": "Lint", "command": "ruff check .", "required": false },\n { "name": "Tests", "command": "pytest" }\n ]\n}\n```\n\n### Go\n```json\n{\n "setup": ["go mod download"],\n "commands": [\n { "name": "Build", "command": "go build ./..." },\n { "name": "Vet", "command": "go vet ./...", "required": false },\n { "name": "Tests", "command": "go test ./..." }\n ]\n}\n```\n\n### Rust\n```json\n{\n "setup": ["cargo fetch"],\n "commands": [\n { "name": "Build", "command": "cargo build" },\n { "name": "Clippy", "command": "cargo clippy -- -D warnings", "required": false },\n { "name": "Tests", "command": "cargo test" }\n ]\n}\n```\n\n## Project Analysis Checklist\n\nWhen setting up testing for a new project, check for:\n1. **package.json** \u2192 Node.js/TypeScript (check "scripts" for test/build/lint commands)\n2. **Cargo.toml** \u2192 Rust\n3. **go.mod** \u2192 Go\n4. **pyproject.toml** / **requirements.txt** \u2192 Python\n5. **Makefile** \u2192 Custom build system (check for test/build targets)\n6. **.github/workflows/** \u2192 Existing CI configuration (great source of test commands)\n7. **.gitlab-ci.yml** \u2192 GitLab CI\n8. **tsconfig.json** \u2192 TypeScript type checking\n9. **.eslintrc** / **biome.json** \u2192 Linting configuration\n10. **vitest.config.ts** / **jest.config.ts** / **pytest.ini** \u2192 Test framework configuration'}]}}
|
|
1554
1557
|
const r=t(8824),n=t(9072)},2085(e,exports,t){"use strict"
|
|
1555
1558
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.getRequestTimelineForFile=async function(e,t,s,i){let a=`# File History: ${t}\n\n`
|
|
1556
1559
|
a+="**Context**: Main branch (request-level view)\n\n"
|
|
@@ -1595,7 +1598,29 @@ return e&&o[e]?o[e]:e?null:o}catch(t){return this.logger.debug("No user preferen
|
|
|
1595
1598
|
this.logger.info("Saving user tool preferences",{clientType:e,preset:t,disabledToolsCount:r?.length||0,allowedToolsCount:s?.length||0}),await n.default.mkdir(a,{recursive:!0})
|
|
1596
1599
|
let c={}
|
|
1597
1600
|
try{const e=await n.default.readFile(i,"utf-8")
|
|
1598
|
-
c=JSON.parse(e)}catch(e){}c[e]={preset:t,disabledTools:r||[],allowedAlchemyTools:s||[],updatedAt:(new Date).toISOString()},await n.default.writeFile(i,JSON.stringify(c,null,2),"utf-8"),this.logger.info("User tool preferences saved",{clientType:e,prefsFile:i})}}},
|
|
1601
|
+
c=JSON.parse(e)}catch(e){}c[e]={preset:t,disabledTools:r||[],allowedAlchemyTools:s||[],updatedAt:(new Date).toISOString()},await n.default.writeFile(i,JSON.stringify(c,null,2),"utf-8"),this.logger.info("User tool preferences saved",{clientType:e,prefsFile:i})}}},2113(e,exports,t){"use strict"
|
|
1602
|
+
async function r(e,t){const r=await fetch(`${e}/session/${t}/message`,{signal:AbortSignal.timeout(5e3)})
|
|
1603
|
+
if(!r.ok)throw Error("status "+r.status)
|
|
1604
|
+
return await r.json()}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCommitToViewedSession=async function(e,t){const a=Math.random().toString(36).slice(2,8),c=Date.now()
|
|
1605
|
+
let l
|
|
1606
|
+
t.info("commit_to_viewed_session:enter",{callId:a,enteredAt:c})
|
|
1607
|
+
try{l=n.CommitToViewedSessionSchema.parse(e).message}catch(e){return t.warn("commit_to_viewed_session:schema-fail",{callId:a,error:(0,o.getErrorMessage)(e)}),{content:[{type:"text",text:"Invalid commit: "+(0,o.getErrorMessage)(e)}],isError:!0}}t.info("commit_to_viewed_session:parsed",{callId:a,messagePreview:l.slice(0,80),messageLength:l.length})
|
|
1608
|
+
const d=s.sessionIdentity.getIdentity(),u=d?.sessionId,h=d?.serverUrl
|
|
1609
|
+
if(!u||!h)return t.warn("commit_to_viewed_session: missing session identity",{hasHeraldId:!!u,hasServerUrl:!!h}),{content:[{type:"text",text:"Commit failed: herald session identity unavailable."}],isError:!0}
|
|
1610
|
+
let g
|
|
1611
|
+
try{g=await r(h,u)}catch(e){return t.warn("commit_to_viewed_session: could not fetch herald messages",{heraldId:u,error:(0,o.getErrorMessage)(e)}),{content:[{type:"text",text:`Commit failed: unable to read herald context (${(0,o.getErrorMessage)(e)}).`}],isError:!0}}const p=function(e){for(let t=e.length-1;t>=0;t--){const r=e[t]
|
|
1612
|
+
if("user"===r.info?.role)for(const e of r.parts??[]){if("text"!==e.type||!e.text)continue
|
|
1613
|
+
const t=e.text.match(/<viewed_session\s+id="([^"]+)"\s*\/?>/)
|
|
1614
|
+
if(t)return t[1]}}return null}(g)
|
|
1615
|
+
if(!p)return{content:[{type:"text",text:"Commit failed: no <viewed_session/> tag in herald context. The UI must embed one in each dictation envelope."}],isError:!0}
|
|
1616
|
+
let f
|
|
1617
|
+
try{f=function(e){for(let t=e.length-1;t>=0;t--){const r=e[t]
|
|
1618
|
+
if("assistant"===r.info?.role&&r.info.agent)return r.info.agent}}(await r(h,p)),f||t.warn("commit_to_viewed_session: no agent resolvable for viewed session; omitting agent",{viewedId:p})}catch(e){t.warn("commit_to_viewed_session: could not fetch viewed messages; omitting agent",{viewedId:p,error:(0,o.getErrorMessage)(e)})}const m={parts:[{type:"text",text:`${i}${l}`}]}
|
|
1619
|
+
f&&(m.agent=f),t.info("commit_to_viewed_session:posting",{callId:a,viewedId:p,heraldId:u,agent:f})
|
|
1620
|
+
try{const e=await fetch(`${h}/session/${p}/prompt_async`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m),signal:AbortSignal.timeout(1e4)})
|
|
1621
|
+
if(t.info("commit_to_viewed_session:posted",{callId:a,status:e.status}),!e.ok){const t=await e.text().catch((()=>""))
|
|
1622
|
+
return{content:[{type:"text",text:`Commit failed: prompt_async returned ${e.status}${t?` (${t.slice(0,120)})`:""}.`}],isError:!0}}}catch(e){return t.warn("commit_to_viewed_session:post-failed",{callId:a,error:(0,o.getErrorMessage)(e)}),{content:[{type:"text",text:"Commit failed: "+(0,o.getErrorMessage)(e)}],isError:!0}}return t.info("Translator forwarded message to viewed session",{callId:a,heraldId:u,viewedId:p,agent:f,messageLength:l.length,preview:l.slice(0,120),durationMs:Date.now()-c}),{content:[{type:"text",text:"Committed."}]}}
|
|
1623
|
+
const n=t(6183),o=t(8824),s=t(6688),i="\x3c!-- via-herald --\x3e"},2140(e,exports,t){"use strict"
|
|
1599
1624
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSwitchToMainBranch=async function(e,t,i,a,c){const l=a.child({tool:"switch_to_main_branch"}),d=Date.now()
|
|
1600
1625
|
try{if(r.SwitchToMainBranchSchema.parse(e),l.info("Switching to main branch/repository"),!t.workspaceManager)throw(0,n.createServiceError)("WorkspaceManager not available",{phase:"workspace_manager_check"})
|
|
1601
1626
|
let a=null
|
|
@@ -1685,7 +1710,7 @@ var t={}
|
|
|
1685
1710
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
1686
1711
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1687
1712
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,r,n,o,s,i,f,m){const y=i.child({tool:"move_files"}),w=Date.now()
|
|
1688
|
-
let k,b
|
|
1713
|
+
let k,I,b=d.FileOperationPhase.VALIDATION
|
|
1689
1714
|
const v={toolName:"move-files",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"move-files",metricsPrefix:"move_files",successMessage:"Successfully moved files",failureMessage:"Failed to move files"}
|
|
1690
1715
|
try{const u=d.validateArgs(e,l.MoveFilesSchema),{operations:h,comment:C}=u,{resolveActiveTaskId:_}=await Promise.resolve().then(t.bind(t,3451)),E=e.taskId||await _(r,n,i)||"untracked"
|
|
1691
1716
|
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")
|
|
@@ -1694,7 +1719,7 @@ const q=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null
|
|
|
1694
1719
|
y.info("Initial branch context",{initialBranch:q.branch,initialRequestId:q.requestId,isMain:q.isMain})
|
|
1695
1720
|
const S=[]
|
|
1696
1721
|
for(const e of h){const{normalizedPath:t,fullPath:n}=d.validateAndNormalizePath(e.source,r),{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(e.destination,r)
|
|
1697
|
-
S.push({source:t,destination:o,fullSource:n,fullDestination:s})}
|
|
1722
|
+
S.push({source:t,destination:o,fullSource:n,fullDestination:s})}b=d.FileOperationPhase.TASK_VALIDATION,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1698
1723
|
const T=await d.validateTaskId(E,S[0].source,n,y,f,v.metricsPrefix),P=T?.requestId,j=await d.validateWorkItemStates(E,S[0].source,n,s,r,y,f,v.metricsPrefix),R=await d.autoPromoteTaskStatus(E,T.status,P,j.request?.status,S[0].source,n,s,y,f,v.metricsPrefix)
|
|
1699
1724
|
R.taskPromoted&&y.info(`Auto-promoted task ${E} (${T.title||"Untitled"}) to in_progress for file operations`,{taskId:E,taskTitle:T.title,previousStatus:T.status,newStatus:R.newTaskStatus,operationCount:h.length}),R.requestPromoted&&y.info(`Auto-promoted request ${P} to in_progress for file operations`,{requestId:P,previousStatus:j.request?.status,newStatus:R.newRequestStatus,triggeringTaskId:E})
|
|
1700
1725
|
const x=await d.ensureCorrectWorkspaceContext({taskPromoted:R.taskPromoted,requestId:P,context:r,operation:"move-files",logger:y,metrics:f,metricsPrefix:v.metricsPrefix})
|
|
@@ -1702,9 +1727,9 @@ if(!x.success){if(x.isLockConflict)return{content:[{type:"text",text:"\u274c "+x
|
|
|
1702
1727
|
throw Error(x.error)}let M={hadUserMods:!1,userModsCommitHash:void 0}
|
|
1703
1728
|
if(r.git)try{y.debug("[MOVE-FILES] Checking for user changes before move operations")
|
|
1704
1729
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"move-files",{requestId:P,taskId:E,workspaceManager:r.workspaceManager},y,f)
|
|
1705
|
-
e.userChangesCommitted&&(y.debug("[MOVE-FILES] User changes committed before move operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before move-files operation",{taskId:E,moveOperationsCount:S.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),M={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){y.debug("[MOVE-FILES] Pre-tool commit failed, continuing with move operations",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with move operation",{taskId:E,moveOperationsCount:S.length,error:e instanceof Error?e.message:e+""})}y.debug("[MOVE-FILES] Proceeding with move operations",{operationCount:S.length}),
|
|
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}),b=d.FileOperationPhase.RECORD_CREATION,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1706
1731
|
const{toolRecordId:O,localToolRecordId:D}=await d.createFileOperationRecords(E,P,r.projectId,v.recordType,S[0].source,{operationCount:h.length,operations:S.map((e=>({source:e.source,destination:e.destination}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},n,o,y,f,v.metricsPrefix,m)
|
|
1707
|
-
k=O,
|
|
1732
|
+
k=O,I=O,b=v.fileOperationPhase,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1708
1733
|
const $=[]
|
|
1709
1734
|
let A=0
|
|
1710
1735
|
for(const e of S){const t={operation:{source:e.source,destination:e.destination},success:!1}
|
|
@@ -1714,11 +1739,11 @@ const n=c.default.dirname(e.fullDestination)
|
|
|
1714
1739
|
try{await a.default.mkdir(n,{recursive:!0})}catch(e){throw Error("Failed to create destination directory: "+n)}try{throw await a.default.access(e.fullDestination),Error("Destination already exists: "+e.destination)}catch(e){if(!(e instanceof Error&&e.message.includes("ENOENT")))throw e}await a.default.rename(e.fullSource,e.fullDestination),t.success=!0,A++,y.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,p.getErrorMessage)(r),y.warn(`Failed to move ${e.source} to ${e.destination}`,{error:t.error})}$.push(t)}const F=Date.now()-w
|
|
1715
1740
|
f.recordValue("move_files_time",F),f.incrementCounter("move_files_operations_total",h.length),f.incrementCounter("move_files_operations_success",A),f.incrementCounter("move_files_operations_failed",h.length-A),A===h.length?f.incrementCounter("move_files_success",1):A>0?f.incrementCounter("move_files_partial_success",1):f.incrementCounter("move_files_total_failure",1)
|
|
1716
1741
|
let N=null
|
|
1717
|
-
if(A>0){
|
|
1742
|
+
if(A>0){b=d.FileOperationPhase.GIT_COMMIT,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1718
1743
|
const e=$.filter((e=>e.success)),t=1===e.length?`Move ${e[0].isDirectory?"directory":"file"} from ${e[0].operation.source} to ${e[0].operation.destination} - ${C}`:`Move ${e.length} ${1===e.length?"item":"items"} - ${C}`
|
|
1719
|
-
N=await d.commitToGit(E,S[0].destination,O,D,t,r,y,f,v.metricsPrefix)}
|
|
1744
|
+
N=await d.commitToGit(E,S[0].destination,O,D,t,r,y,f,v.metricsPrefix)}b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1720
1745
|
const L=$.filter((e=>e.success)),z=$.filter((e=>!e.success))
|
|
1721
|
-
await d.updateFileOperationRecords(E,k,
|
|
1746
|
+
await d.updateFileOperationRecords(E,k,I,S[0].source,v.recordType,A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,{status:A===h.length?"completed":"partial_success",commitHash:N?.commitHash,previousCommitHash:N?.previousCommitHash,operationCount:h.length,successCount:A,failureCount:h.length-A,successfulOperations:L.map((e=>({source:e.operation.source,destination:e.operation.destination,isDirectory:e.isDirectory}))),failedOperations:z.map((e=>({source:e.operation.source,destination:e.operation.destination,error:e.error}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,n,o,y,f,v.metricsPrefix)
|
|
1722
1747
|
const H=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
1723
1748
|
let B=""
|
|
1724
1749
|
if(A===h.length)B=`Successfully moved all ${h.length} ${1===h.length?"item":"items"}`
|
|
@@ -1726,16 +1751,16 @@ else if(A>0){const e=$.filter((e=>!e.success))
|
|
|
1726
1751
|
B=`Successfully moved ${A}/${h.length} items.\n\nFailed operations:\n`+e.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")}else B="All move operations failed:\n"+$.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")
|
|
1727
1752
|
if(N?.commitHash&&(B+="\nCommit: "+N.commitHash.substring(0,8)),H.requestId&&(B+="\nBranch: "+H.requestId),x.lockAcquired&&x.lockedRequestId){const e=r.workspaceManager?.getCurrentContext(r.currentSessionId)
|
|
1728
1753
|
e?.permanentBranch||(B+="\n\u{1f512} **Locked request:** "+x.lockedRequestId)}return{content:[{type:"text",text:B}],isError:0===A}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
|
|
1729
|
-
await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"move-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment,error:(0,p.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:
|
|
1730
|
-
if(f.recordValue("move_files_time",s),f.incrementCounter("move_files_errors",1),y.error("Error in move-files operation:",{error:(0,p.getErrorMessage)(t),time:s}),(k||
|
|
1731
|
-
try{await d.updateFileOperationRecords(e.taskId,k,
|
|
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:b,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:"Failed to move files - "+(0,p.getErrorMessage)(t)})}catch(t){y.error("Failed to create failure record for move-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,operationCount:e.operations?.length||0})}const s=Date.now()-w
|
|
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||I)&&e.taskId){b=d.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
1756
|
+
try{await d.updateFileOperationRecords(e.taskId,k,I,e.operations?.[0]?.source||"unknown",v.recordType,"Failed to move files",{status:"failed",error:(0,p.getErrorMessage)(t),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment},"Failed to move files",n,o,y,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,b,y,f,e,v)}}
|
|
1732
1757
|
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"
|
|
1733
1758
|
module.exports=require("@modelcontextprotocol/sdk/server/sse.js")},2425(e,exports,t){"use strict"
|
|
1734
1759
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
1735
1760
|
const r=t(6183),n=t(3707)
|
|
1736
1761
|
exports.def={name:"quick_manage",description:"Move, delete, or create directories. Wraps the change in a request/task workflow that auto-completes.\n\nProvide an array of operations, each with operationType and corresponding data:\n\u2022 create-directory: { createDirectory: { path } }\n\u2022 move-files: { moveFiles: { moves: [{ source, destination }] } }\n\u2022 delete-files: { deleteFiles: { targets: [{ path }] } }\n\nFor read-only operations like get-file-info, use manage_files instead.\n\nRequires: title, description, operations.",schema:r.QuickManageSchema,annotations:{title:"Quick Manage",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"manage",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},2462(e,exports,t){"use strict"
|
|
1737
1762
|
Object.defineProperty(exports,"__esModule",{value:!0})
|
|
1738
|
-
const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),f=t(260),m=t(2283),y=t(4165),w=t(7834),k=t(9373),
|
|
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),I=t(6111),b=t(700),v=t(2783),C=t(2601),_=t(1722),E=t(7257),q=t(9230),S=t(6064),T=t(5216),P=t(6473),j=t(4921),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)(I.def),(0,r.registerTool)(b.def),(0,r.registerTool)(v.def),(0,r.registerTool)(S.def),(0,r.registerTool)(C.def),(0,r.registerTool)(_.def),(0,r.registerTool)(E.def),(0,r.registerTool)(q.def),(0,r.registerTool)(T.def),(0,r.registerTool)(P.def),(0,r.registerTool)(j.def),(0,r.registerTool)(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"
|
|
1739
1764
|
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"
|
|
1740
1765
|
async function r(e,t,r){if(C.has(r)&&_>=t){if(0===t)return 0
|
|
1741
1766
|
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]"
|
|
@@ -1753,14 +1778,14 @@ if(30>s)return`${s} day${1===s?"":"s"} ago`
|
|
|
1753
1778
|
const i=Math.floor(s/30)
|
|
1754
1779
|
if(12>i)return`${i} month${1===i?"":"s"} ago`
|
|
1755
1780
|
const a=Math.floor(i/12)
|
|
1756
|
-
return`${a} year${1===a?"":"s"} ago`}(o.modified)} | ${(0,
|
|
1781
|
+
return`${a} year${1===a?"":"s"} ago`}(o.modified)} | ${(0,b.formatTimestamp)(o.modified)})`)
|
|
1757
1782
|
break
|
|
1758
1783
|
case"size":s||"number"!=typeof o.size||(l+=` (${function(e){if(0===e)return"0 bytes"
|
|
1759
1784
|
let t=e,r=0
|
|
1760
1785
|
for(;t>=1024&&4>r;)t/=1024,r++
|
|
1761
1786
|
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[]
|
|
1762
|
-
try{const{fullPath:d}=
|
|
1763
|
-
for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=
|
|
1787
|
+
try{const{fullPath:d}=I.validateAndNormalizePath(e,t),h=await y.default.readdir(d,{withFileTypes:!0}),g=[]
|
|
1788
|
+
for(const d of h)try{const u=w.default.join(e,d.name).replace(/\\/g,"/"),{fullPath:h}=I.validateAndNormalizePath(u,t),p=await y.default.stat(h),f=d.isFile()?w.default.extname(d.name).toLowerCase():""
|
|
1764
1789
|
let m
|
|
1765
1790
|
d.isFile()&&(m=await r(h,p.size,f))
|
|
1766
1791
|
const k={name:d.name,isDirectory:d.isDirectory(),depth:n,size:p.size,modified:p.mtime,extension:f,lineCount:m}
|
|
@@ -1769,8 +1794,8 @@ const o=[]
|
|
|
1769
1794
|
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?"/":""
|
|
1770
1795
|
if(o.push(`${r}${l}${d}${u}`),i.children&&i.children.length>0){const e=r+(c?" ":"\u2502 "),n=s(i.children,t,e)
|
|
1771
1796
|
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}
|
|
1772
|
-
try{const{fullPath:n}=
|
|
1773
|
-
for(const n of s)try{const s=w.default.join(e,n.name).replace(/\\/g,"/"),{fullPath:i}=
|
|
1797
|
+
try{const{fullPath:n}=I.validateAndNormalizePath(e,t),s=await y.default.readdir(n,{withFileTypes:!0})
|
|
1798
|
+
for(const n of s)try{const s=w.default.join(e,n.name).replace(/\\/g,"/"),{fullPath:i}=I.validateAndNormalizePath(s,t)
|
|
1774
1799
|
if(n.isDirectory())o.directories+=1
|
|
1775
1800
|
else{o.files+=1
|
|
1776
1801
|
const e=await y.default.stat(i),t=w.default.extname(n.name).toLowerCase(),s=await r(i,e.size,t)
|
|
@@ -1796,27 +1821,27 @@ var t={}
|
|
|
1796
1821
|
if(null!=e)for(var r=h(e),n=0;n<r.length;n++)"default"!==r[n]&&g(t,e,r[n])
|
|
1797
1822
|
return p(t,e),t}),m=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1798
1823
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListDirectory=async function(e,t,i,a){const h=Date.now()
|
|
1799
|
-
let g=
|
|
1800
|
-
|
|
1801
|
-
try{const p=
|
|
1824
|
+
let g=I.FileOperationPhase.VALIDATION
|
|
1825
|
+
I.FileOperationPhase.FILE_WRITE
|
|
1826
|
+
try{const p=I.validateArgs(e,k.ListDirectorySchema),{path:f,levels:m=1,sortBy:b="name"}=p
|
|
1802
1827
|
i.info("Listing directory: "+f)
|
|
1803
|
-
const{normalizedPath:C,fullPath:_}=
|
|
1804
|
-
g=
|
|
1828
|
+
const{normalizedPath:C,fullPath:_}=I.validateAndNormalizePath(f,t)
|
|
1829
|
+
g=I.FileOperationPhase.FILE_WRITE
|
|
1805
1830
|
try{if(!(await y.default.stat(_)).isDirectory())return{content:[{type:"text",text:"Path is not a directory: "+f}],isError:!0}
|
|
1806
1831
|
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
|
|
1807
|
-
if(m>1){i.info(`Building tree structure for: ${C} (levels: ${m}, sortBy: ${
|
|
1808
|
-
const e=await o(C,t,0,m,
|
|
1809
|
-
if(e.length>0){const t=s(e,
|
|
1832
|
+
if(m>1){i.info(`Building tree structure for: ${C} (levels: ${m}, sortBy: ${b})`)
|
|
1833
|
+
const e=await o(C,t,0,m,b,i)
|
|
1834
|
+
if(e.length>0){const t=s(e,b)
|
|
1810
1835
|
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=[]
|
|
1811
|
-
for(const n of e)try{const e=w.default.join(C,n.name).replace(/\\/g,"/"),{fullPath:s}=
|
|
1836
|
+
for(const n of e)try{const e=w.default.join(C,n.name).replace(/\\/g,"/"),{fullPath:s}=I.validateAndNormalizePath(e,t),i=await y.default.stat(s),a=n.isFile()?w.default.extname(n.name).toLowerCase():""
|
|
1812
1837
|
let c
|
|
1813
|
-
n.isFile()&&(c=await r(s,i.size,a)),o.push({name:n.name,isDirectory:n.isDirectory(),depth:0,size:i.size,modified:i.mtime,extension:a,lineCount:c})}catch(e){i.debug("Excluding directory entry from listing: "+n.name,{reason:(0,v.getErrorMessage)(e)})}const s=u(o,
|
|
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,b),a=s.map((e=>n({name:e.name,isDirectory(){return e.isDirectory},isFile(){return!e.isDirectory}},b,e)))
|
|
1814
1839
|
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)
|
|
1815
1840
|
E+="\n\nBranch: "+(S?.branchName||"unknown")
|
|
1816
1841
|
const T=Date.now()-h
|
|
1817
1842
|
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
|
|
1818
1843
|
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}}}
|
|
1819
|
-
const y=m(t(1943)),w=m(t(6928)),k=t(6183),
|
|
1844
|
+
const y=m(t(1943)),w=m(t(6928)),k=t(6183),I=f(t(5967)),b=t(3253),v=t(8824),C=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".scala",".c",".cpp",".h",".hpp",".cs",".html",".css",".scss",".sass",".less",".json",".yaml",".yml",".toml",".xml",".md",".txt",".csv",".sql",".sh",".bash",".zsh",".fish",".vim",".lua",".php",".swift",".m",".vue",".svelte",".astro",".env",".gitignore",".dockerignore",".config",".conf",".ini",".cfg"]),_=1048576},2568(e,exports,t){"use strict"
|
|
1820
1845
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1821
1846
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectSynchronizer=void 0
|
|
1822
1847
|
const n=r(t(6928)),o=t(8029),s=t(8824),i=t(2096)
|
|
@@ -2003,11 +2028,11 @@ const f=await Promise.all(p)
|
|
|
2003
2028
|
let m=""
|
|
2004
2029
|
if(t.workspaceManager)try{const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
2005
2030
|
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
|
|
2006
|
-
let
|
|
2007
|
-
m&&(
|
|
2031
|
+
let I="## Read Files/Documents\n\n"
|
|
2032
|
+
m&&(I+=m),I+=`**Total Requests:** ${k} - **Successful:** ${y} - **Failed:** ${w}\n\n`
|
|
2008
2033
|
for(let e=0;e<f.length;e++){const t=f[e]
|
|
2009
|
-
"file"===t.type?
|
|
2010
|
-
return i.info("Multiple file/document read completed",{duration:Date.now()-a,totalRequests:k,successfulReads:y,failedReads:w,success:
|
|
2034
|
+
"file"===t.type?I+=`File ${e+1}: ${t.path}\n`:(I+=`Document ${e+1}: ${t.documentId}`,t.filename&&(I+=` (${t.filename})`),I+="\n"),t.success?(I+="**Status:** Success\n",t.lineCount&&t.totalLines&&(I+=`Lines Read / Total Lines ${t.lineCount} / ${t.totalLines}\n`),t.originalRequest?.lines&&t.totalLines&&(I+=`**Lines:** ${t.originalRequest.lines}\n`),I+=`\n**Content:**\n\`\`\`\n${t.content}\n\`\`\`\n`):(I+="**Status:** Failed\n",I+=`**Error:** ${t.error}\n`),I+="\n"}const b=0===w
|
|
2035
|
+
return i.info("Multiple file/document read completed",{duration:Date.now()-a,totalRequests:k,successfulReads:y,failedReads:w,success:b}),s.incrementCounter("read_files_total",1,{success:b}),{content:[{type:"text",text:I}],isError:!b}}catch(e){const t=Date.now()-a
|
|
2011
2036
|
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}}}
|
|
2012
2037
|
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"
|
|
2013
2038
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.TaskClient=void 0
|
|
@@ -2121,12 +2146,12 @@ d.info("Generating journal for request",{requestId:c})
|
|
|
2121
2146
|
const h=t.projectId
|
|
2122
2147
|
if(!h)throw(0,n.createValidationError)("Project ID is required. Make sure you are in a project context.")
|
|
2123
2148
|
o.setProjectId(h),d.info("Fetching request data, tasks, and file history in parallel")
|
|
2124
|
-
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}),
|
|
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}),I="data"in k?k.data:k,b={id:I.id||c,title:I.title||"Unknown Request",description:I.description||"No description available",status:I.status||"unknown",type:I.type||"unknown",acceptanceCriteria:I.acceptanceCriteria||[],createdAt:I.createdAt||(new Date).toISOString(),updatedAt:I.updatedAt||(new Date).toISOString(),completedAt:I.completedAt},v=(0,s.extractDataFromResponse)(y,{logger:d,operationName:"listTasks",throwOnNoData:!1}),C=(Array.isArray(v)?v:"data"in v?v.data:[]).map((e=>({id:e.id,title:e.title||"Untitled Task",description:e.description||"No description",status:e.status||"unknown",createdAt:e.createdAt||(new Date).toISOString(),completedAt:e.metadata?.completedAt})))
|
|
2125
2150
|
d.info(`Fetched request, ${C.length} tasks, ${w.length} tool records`)
|
|
2126
2151
|
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()))
|
|
2127
2152
|
for(const e of o){const o=r(e),s=e.metadata?.comment||e.metadata?.userComment||"No comment"
|
|
2128
2153
|
n.push({type:e.type,timestamp:e.createdAt,comment:s,files:o,recordId:e.localId||e.id})
|
|
2129
|
-
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:
|
|
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:b,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:** ${b.title} (${c})\n**Status:** ${b.status}\n**Type:** ${b.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..."`
|
|
2130
2155
|
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}}}
|
|
2131
2156
|
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"
|
|
2132
2157
|
async function r(e,t,r,n){if(!r.lockOverrideManager||!r.configManager)return e
|
|
@@ -2250,7 +2275,7 @@ var t={}
|
|
|
2250
2275
|
if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
2251
2276
|
return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2252
2277
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceStrings=async function(e,r,o,s,i,a,c,y){const w=a.child({tool:"replace_strings"}),k=Date.now()
|
|
2253
|
-
let b,
|
|
2278
|
+
let I,b,v=u.FileOperationPhase.VALIDATION
|
|
2254
2279
|
const C={toolName:"replace-strings",operationName:"replace-string",fileOperationPhase:u.FileOperationPhase.STRING_REPLACEMENT,recordType:"replace-strings",metricsPrefix:"replace_strings",successMessage:"Successfully replaced strings across files and documents",failureMessage:"Failed to replace strings across files and documents"}
|
|
2255
2280
|
try{const _=u.validateArgs(e,d.ReplaceStringsSchema),{operations:E,comment:q}=_,{resolveActiveTaskId:S}=await Promise.resolve().then(t.bind(t,3451)),T=e.taskId||await S(r,o,a)||"untracked"
|
|
2256
2281
|
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")
|
|
@@ -2276,7 +2301,7 @@ for(let e=0;e<R.length;e++){const t=R[e],n=P[e],{normalizedPath:o,fullPath:s}=u.
|
|
|
2276
2301
|
R[e]={...t,path:o,fullPath:s}}}if(x.length>0&&D)try{await(0,g.validateRequestStatusForDocumentOperation)(D,i,w,c,"replace-strings-document")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2277
2302
|
throw e}v=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_strings_phase",1,{phase:v})
|
|
2278
2303
|
const N=[...R.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...x.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:L}=await u.createFileOperationRecords(T,D,r.projectId,C.recordType,M,{operationCount:E.length,fileOperations:R.length,documentOperations:x.length,operations:N,userComment:q},o,s,w,c,C.metricsPrefix,y)
|
|
2279
|
-
if(
|
|
2304
|
+
if(I=L,b=L,v=C.fileOperationPhase,c.incrementCounter("replace_strings_phase",1,{phase:v}),R.length>0&&r.git)try{w.debug("[REPLACE-STRINGS] Checking for user changes before replace operations")
|
|
2280
2305
|
const e=await(0,p.commitUserChangesBeforeToolOperation)(r.git,"replace-strings",{requestId:D,taskId:T,workspaceManager:r.workspaceManager},w,c)
|
|
2281
2306
|
e.userChangesCommitted&&(w.debug("[REPLACE-STRINGS] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before replace-strings operation",{taskId:T,fileOperationsCount:R.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[REPLACE-STRINGS] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:T,fileOperationsCount:R.length,error:e instanceof Error?e.message:e+""})}w.debug("[REPLACE-STRINGS] Proceeding with file operations",{fileCount:R.length})
|
|
2282
2307
|
const z=[]
|
|
@@ -2289,8 +2314,8 @@ try{const o=await r.documentFileManager.getDocumentAsFile(e.documentId),s=r.docu
|
|
|
2289
2314
|
t.filename=s?.filename
|
|
2290
2315
|
const i=await l.default.readFile(o,"utf8"),{newContent:a,results:c}=await n(i,e.replacements,e.mode)
|
|
2291
2316
|
t.replacements=c,t.successfulReplacements=c.filter((e=>e.success)).length,t.failedReplacements=c.filter((e=>!e.success)).length,a!==i?(await l.default.writeFile(o,a,"utf8"),r.documentFileManager.markForSync(e.documentId),t.success=!0,B++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,w.error("Document operation failed",{documentId:e.documentId,error:t.error})}z.push(t)}if(x.length>0)try{for(const e of x){const t=z.find((t=>t.documentId===e.documentId))
|
|
2292
|
-
t?.success&&await r.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const U=await u.handleMultiFileGitCommit(T,R,z,B,{operationType:"Replace strings",toolRecordId:
|
|
2293
|
-
try{await s.updateToolRecord(
|
|
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:b,successField:"successfulReplacements",logger:w,metrics:c,metricsPrefix:"replace_strings"},r),G=u.processMultiFileOperationResults(z,"successfulReplacements"),{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q}=G
|
|
2318
|
+
try{await s.updateToolRecord(b,{metadata:{path:R.length>0?R[0].path:"document:"+x[0]?.documentId,status:K?"completed":"failed",error:K?void 0:V+" operations failed",totalOperations:z.length,successfulFiles:Y,failedFiles:Q,operations:N,totalSuccessfulReplacements:J,totalFailedReplacements:H,operationsWithChanges:B,processingTime:Date.now()-k,userComment:q,...R.length>0&&U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}},note:K?`String replacement completed: ${W}/${z.length} operations successful${R.length>0?" (committed to git)":""}`:`String replacement partially failed: ${V}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}u.formatMultiFileToolResponse("String Replacement",{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q},U,F)
|
|
2294
2319
|
let Z="## String Replacement Results\n\n"
|
|
2295
2320
|
if(r.workspaceManager){const e=r.workspaceManager.getCurrentContext(r.currentSessionId)
|
|
2296
2321
|
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]
|
|
@@ -2300,7 +2325,7 @@ for(const e of z){if("file"===e.type?Z+=`### File: ${e.path}\n`:(Z+="### Documen
|
|
|
2300
2325
|
for(const t of e.replacements.filter((e=>!e.success)))Z+=` - "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}Z+="\n"}}x.length>0&&(Z+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
2301
2326
|
const X=Date.now()-k
|
|
2302
2327
|
return w.info("Replace strings operation completed",{duration:X,success:K,totalOperations:z.length,successfulOperations:W,failedOperations:V}),c.incrementCounter("replace_strings_total",1,{success:K}),{content:[{type:"text",text:Z}],isError:!K}}catch(t){const r=Date.now()-k
|
|
2303
|
-
if(w.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),
|
|
2328
|
+
if(w.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),b)try{await s.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,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}}}
|
|
2304
2329
|
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"
|
|
2305
2330
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
2306
2331
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
@@ -2370,11 +2395,11 @@ if(g.requestId)try{const e=a.getRequestClient()
|
|
|
2370
2395
|
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"
|
|
2371
2396
|
try{const t=new Date(e)
|
|
2372
2397
|
return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return d.warn("Invalid date format: "+e),"Unknown date"}},m=f(g.createdAt),y=f(g.updatedAt),w=g.requestId||g.requestLocalId,k=g.sequenceNumber&&w?(0,i.formatTaskRef)(w,g.sequenceNumber):r
|
|
2373
|
-
let
|
|
2374
|
-
if(
|
|
2375
|
-
|
|
2398
|
+
let I=`# Task: ${g.title} (${k})\n\n`
|
|
2399
|
+
if(I+=`**Status**: ${g.status}\n`,I+=`**Created**: ${m}\n`,I+=`**Updated**: ${y}\n`,g.requestId&&(I+="**Parent Request**: "+g.requestId,I+=p?` (${p.title})\n`:"\n"),g.metadata){const e=g.metadata
|
|
2400
|
+
I+="\n## Metadata\n\n",e.lastCommit&&(I+=`**Last Commit**: ${e.lastCommit}\n`),e.completedAt&&(I+=`**Completed At**: ${f(e.completedAt)}\n`),e.completionSummary&&(I+=`**Completion Summary**: ${e.completionSummary}\n`)
|
|
2376
2401
|
const t=["lastCommit","completedAt","completionSummary"]
|
|
2377
|
-
Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{
|
|
2402
|
+
Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{I+=`**${e}**: ${t}\n`}))}return I+="\n## Description\n\n",g.description&&g.description.trim().length>0?I+=g.description:I+="No description provided.",u({success:!0}),{content:[{type:"text",text:I}]}}catch(n){d.error("Failed to get task information",{error:n instanceof Error?n.stack:n+"",args:e})
|
|
2378
2403
|
try{const o=a.getToolRecordClient()
|
|
2379
2404
|
await(0,r.createFailureToolRecord)("get-task-information",n,{args:e},o,d,l,{taskId:e.taskId,projectId:t.projectId,note:"Failed to get task information: "+(0,s.getErrorMessage)(n)})}catch(e){d.warn("Failed to create failure record",{recordError:e instanceof Error?e.message:e+""})}u({success:!1,error:n instanceof Error?n.name:"unknown"})
|
|
2380
2405
|
let i=(0,s.getErrorMessage)(n)
|
|
@@ -2407,14 +2432,14 @@ const r=t(6183),n=t(8317)
|
|
|
2407
2432
|
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"
|
|
2408
2433
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2409
2434
|
Object.defineProperty(exports,"__esModule",{value:!0})
|
|
2410
|
-
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),
|
|
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),I=t(1253),b=process.argv.slice(2),v=b[0]||process.cwd(),C=n.default.resolve(v),_=parseInt(process.env.LOCAL_SERVER_PORT||b[1]||"3002",10),E=(0,c.createEnvLogger)({serviceName:"mcp-http-server"});(0,c.isDebugToolsEnabled)()?E.info("HTTP server initializing",{baseDir:C,preferredPort:_,debugLogging:process.env.DEBUG_LOGGING,debugLevel:process.env.DEBUG_LEVEL}):E.info("HTTP server starting",{port:_})
|
|
2411
2436
|
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")
|
|
2412
2437
|
E.info("Using remote server URL",{remoteServerUrl:S}),async function(){try{E.info("Finding available port...",{preferredPort:_,baseDir:C,remoteServerUrl:S})
|
|
2413
2438
|
const e=await(0,m.findAvailablePort)(_)
|
|
2414
2439
|
e!==_&&E.info(`Preferred port ${_} is in use, using port ${e} instead`),E.info("Starting HTTP API server...",{port:e,baseDir:C,remoteServerUrl:S})
|
|
2415
2440
|
const t=new l.ProjectRegistry(E),r=new u.DefaultProjectFileSystem(E),c=n.default.join(C,f.ALCHEMY_DIR_NAME)
|
|
2416
2441
|
E.info(`Checking ${f.ALCHEMY_DIR_NAME} directory`,{alchemyPath:c}),await r.ensureDirectoryExists(c)
|
|
2417
|
-
const h=new
|
|
2442
|
+
const h=new I.TokenManager(E,n.default.join(c,"auth-token.json")),b=(await y.ClientFactory.createClient(S,E,q,{tokenManager:h,workingDir:C,alchemyPath:c})).projectClient,v=new k.ProjectClientAdapter(b,E),T=new d.ProjectSynchronizer(E,t,v,r),P=await T.getOrCreateProject(C,{name:n.default.basename(C)||"Local Project",description:"Project for "+n.default.basename(C),status:"active",metadata:{basePath:C,alchemyPath:c,bootstrapped:!0}})
|
|
2418
2443
|
E.info("Using project",{projectId:P.id,projectName:P.name})
|
|
2419
2444
|
const j=(0,o.default)()
|
|
2420
2445
|
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))
|
|
@@ -2519,19 +2544,19 @@ try{const a=u.validateArgs(e,d.GetFileInfoSchema),{path:h}=a
|
|
|
2519
2544
|
n.info("Getting file info: "+h)
|
|
2520
2545
|
const{normalizedPath:f,fullPath:m}=u.validateAndNormalizePath(h,t)
|
|
2521
2546
|
i=u.FileOperationPhase.FILE_WRITE
|
|
2522
|
-
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},
|
|
2523
|
-
k.isFile&&w&&
|
|
2524
|
-
const
|
|
2525
|
-
return o.recordValue("get_file_info_time",
|
|
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},I=["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]
|
|
2548
|
+
k.isFile&&w&&I.push("Extension: "+w)
|
|
2549
|
+
const b=Date.now()-s
|
|
2550
|
+
return o.recordValue("get_file_info_time",b),o.incrementCounter("get_file_info_success",1),n.info("Successfully retrieved file info: "+f,{type:k.type,size:k.size,time:b}),{content:[{type:"text",text:I.join("\n")}]}}catch(t){const r=Date.now()-s
|
|
2526
2551
|
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}
|
|
2527
2552
|
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"
|
|
2528
2553
|
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()
|
|
2529
|
-
try{const y=u.getRequestClient(),w=u.getTaskClient(),k=u.getFileClient(),
|
|
2530
|
-
f.info("Starting quick_edit workflow",{title:
|
|
2554
|
+
try{const y=u.getRequestClient(),w=u.getTaskClient(),k=u.getFileClient(),I=u.getToolRecordClient(),{title:b,description:v,...C}=e,_=e.comment||b
|
|
2555
|
+
f.info("Starting quick_edit workflow",{title:b,operationType:t})
|
|
2531
2556
|
let E=!1
|
|
2532
2557
|
try{const e=await y.listRequests({limit:2,sortBy:"created_at",sortDirection:"desc"})
|
|
2533
2558
|
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")
|
|
2534
|
-
const q=await y.createRequest({title:
|
|
2559
|
+
const q=await y.createRequest({title:b,description:v,type:"quick-edit",acceptanceCriteria:["Quick change completed successfully"]})
|
|
2535
2560
|
if(!q||!q.id)throw Error("Failed to create request")
|
|
2536
2561
|
const S=q.id
|
|
2537
2562
|
let T
|
|
@@ -2539,24 +2564,24 @@ f.info("Created request",{requestId:S})
|
|
|
2539
2564
|
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)
|
|
2540
2565
|
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")
|
|
2541
2566
|
f.debug("Creating task")
|
|
2542
|
-
const e=await w.createTask({requestId:S,projectId:d.projectId,title:`Execute ${t} operation`,description:"Quick change: "+
|
|
2567
|
+
const e=await w.createTask({requestId:S,projectId:d.projectId,title:`Execute ${t} operation`,description:"Quick change: "+b})
|
|
2543
2568
|
if(!e||!e.id)throw Error("Failed to create task")
|
|
2544
2569
|
let v
|
|
2545
|
-
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,
|
|
2546
|
-
else if("replace"===t)v=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,
|
|
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,I,y,h,g,p)
|
|
2571
|
+
else if("replace"===t)v=await(0,o.handleReplaceInFiles)({taskId:T,...C,comment:_},d,w,I,y,h,g,p)
|
|
2547
2572
|
else{if("manage"!==t)throw new r.ValidationError("Unsupported operation type: "+t)
|
|
2548
|
-
v=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||
|
|
2573
|
+
v=await(0,s.handleManageFiles)({taskId:T,...C,comment:_||b},d,w,I,y,u,h,g,p)}if(v.isError){f.error("File operation failed, cleaning up request and task",{requestId:S,taskId:T})
|
|
2549
2574
|
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")
|
|
2550
2575
|
P?f.warn("File operation completed with partial failures",{requestId:S}):f.info("File operation completed successfully"),f.debug("Completing task")
|
|
2551
|
-
try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${
|
|
2576
|
+
try{await(0,i.handleCompleteTask)({taskId:T,summary:`Executed ${t} operation for quick fix: ${b}${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})
|
|
2552
2577
|
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")
|
|
2553
|
-
const j=P?`Quick change completed with partial success: ${
|
|
2578
|
+
const j=P?`Quick change completed with partial success: ${b}. Some replacements failed - see details below.`:"Quick change completed: "+b,R=P?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
|
|
2554
2579
|
let x=!1
|
|
2555
2580
|
try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:j,acceptanceEvidence:[{evidence:R}],testVerification:void 0},d,u,h,g,p)
|
|
2556
2581
|
if(e.isError)f.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text})
|
|
2557
2582
|
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
|
|
2558
2583
|
let O
|
|
2559
|
-
return f.info("Quick fix completed",{requestId:S,duration:M,hasPartialFailure:P}),O=P?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${
|
|
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:** ${b}\n**Operation:** ${t}\n**Duration:** ${M}ms\n**Status:** Some operations succeeded, some failed\n\nThe successful changes have been applied and automatically merged to main.\n**Active branch:** main\n\n**\u26a0\ufe0f Note:** This quick-fix had partial failures. See operation details below:\n\n`+q:`\u2705 Quick change completed successfully!\n\n**Request:** ${S}\n**Title:** ${b}\n**Operation:** ${t}\n**Duration:** ${M}ms\n\nThe change has been applied and automatically merged to main.\n**Active branch:** main`+(q.match(/\[RECORD:trec\d{6}\]/)?.[0]?"\n"+q.match(/\[RECORD:trec\d{6}\]/)?.[0]:""),E&&(O+="\n\n\u{1f4a1} **Recommendation:** You've created several quick-edits in a row. For better traceability and organization, consider creating a proper feature or bugfix request with multiple tasks for your next change."),{content:[{type:"text",text:O}]}}catch(e){if(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
|
|
2560
2585
|
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}}}
|
|
2561
2586
|
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"
|
|
2562
2587
|
module.exports=require("simple-git")},3884(e,exports,t){"use strict"
|
|
@@ -2636,7 +2661,7 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
2636
2661
|
var t={}
|
|
2637
2662
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2638
2663
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2639
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,r,n,o,s,i,m,y,w){const k=m.child({tool:"write_file"}),
|
|
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"}),I=y.startTimer("tool_execution_time"),b=Date.now()
|
|
2640
2665
|
let v,C,_=d.FileOperationPhase.VALIDATION
|
|
2641
2666
|
const E={toolName:"write_file",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"write-file",metricsPrefix:"write_file",successMessage:"Successfully wrote content",failureMessage:"Failed to write content"}
|
|
2642
2667
|
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
|
|
@@ -2672,11 +2697,11 @@ if(await c.default.mkdir(Q,{recursive:!0}),await c.default.writeFile(F,Y,"utf8")
|
|
|
2672
2697
|
try{await r.documentFileManager.syncDocument(q),k.info("Document synced successfully",{documentId:q})}catch(e){k.warn("Failed to sync document immediately",{documentId:q,error:e})}}let Z,X,ee=null,te=!1
|
|
2673
2698
|
if(O){if(_=d.FileOperationPhase.GIT_COMMIT,y.incrementCounter("write_file_phase",1,{phase:_}),r.workspaceManager){const e=r.workspaceManager.getCurrentContext(r.currentSessionId)
|
|
2674
2699
|
X=e.branchName,te=e.permanentBranch,k.debug("Retrieved branch name from workspace manager",{branchName:X,requestId:e.requestId,mode:e.mode,isMainBranch:e.isMainBranch})}try{const e=`${N?"Create":P?"Append to":"Update"} ${D} (${C})`,t=await d.commitToGit(x,D,C,C,e,r,k,y,E.metricsPrefix)
|
|
2675
|
-
Z=t.commitHash,ee=t.previousCommitHash,k.info("Changes committed to git via shared utility",{path:D,commitMessage:e,commitHash:Z?.substring(0,8),previousCommitHash:ee?.substring(0,8),branchName:X,toolRecordId:C})}catch(e){k.warn("Git operations failed via shared utility",{error:e})}}try{await s.updateToolRecord(C,{metadata:{path:O?D:"document:"+q,status:"completed",finalContentLength:Y.length,wasFileCreated:N,wasAppended:P&&L,operationType:M?"document":"file",processingTime:Date.now()-
|
|
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()-b,userComment:j,...O&&Z&&{commitHash:Z,previousCommitHash:ee||void 0}},note:"Write operation completed successfully"+(M?" (document synced)":" (committed to git)")})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let re=`**${N?"Created":P?"Appended to":"Updated"} ${M?`document ${q}${A?` (${A})`:""}`:"file "+D}**\n`
|
|
2676
2701
|
re+=`**Content Length:** ${Y.length} characters\n`,O&&X&&(te||(re+=`**Branch:** ${X}\n`)),V.lockAcquired&&V.lockedRequestId&&!te&&(re+=`**Locked request:** ${V.lockedRequestId}\n`),O&&Z&&(re+=`**Commit Hash:** ${Z.substring(0,8)}\n`,ee&&(re+=`**Previous Commit:** ${ee.substring(0,8)}\n`)),C&&(re+=`[RECORD:${C}]\n`),M&&(re+=`\n**Document Update:** The document content has been updated and synced back to the tracking system. You can continue editing using other file modification tools with documentId \`${q}\`.`)
|
|
2677
2702
|
const ne=Date.now()
|
|
2678
|
-
return k.info("Write operation completed successfully",{duration:ne-
|
|
2679
|
-
if(k.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{path:e?.path,status:"failed",error:(0,f.getErrorMessage)(t),phase:_,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,f.getErrorMessage)(t)})}catch(e){}return
|
|
2703
|
+
return k.info("Write operation completed successfully",{duration:ne-b,path:O?D:"document:"+q,contentLength:Y.length,wasCreated:N}),I({tool:"write_file",success:!0}),y.incrementCounter("write_file_total",1,{success:!0}),r.workspaceManager?.largeFileWarning&&(re+=r.workspaceManager.largeFileWarning,r.workspaceManager.largeFileWarning=""),{content:[{type:"text",text:re}]}}catch(t){const r=Date.now()-b
|
|
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 I({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}}}
|
|
2680
2705
|
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"
|
|
2681
2706
|
Object.defineProperty(exports,"__esModule",{value:!0})},4139(e,exports){"use strict"
|
|
2682
2707
|
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"
|
|
@@ -2803,12 +2828,12 @@ return l({success:!1,error:"not_found"}),{content:[{type:"text",text:`Command "$
|
|
|
2803
2828
|
e.grep&&(f=`${f} 2>&1 | grep -i ${JSON.stringify(e.grep)}`)
|
|
2804
2829
|
const m=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
|
|
2805
2830
|
i.info("Running command",{name:p.name,command:f,cwd:m})
|
|
2806
|
-
let y="",w="",k=0,
|
|
2807
|
-
try{y=(0,r.execSync)(f,{cwd:m,timeout:1e3*(p.timeout||60),encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"win32"===process.platform?"cmd.exe":"/bin/sh",env:{...process.env,FORCE_COLOR:"0"}})||""}catch(e){k=e.status??1,y=e.stdout||"",w=e.stderr||"",e.killed&&(
|
|
2808
|
-
y.length>
|
|
2809
|
-
const C=
|
|
2831
|
+
let y="",w="",k=0,I=!1
|
|
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&&(I=!0)}const b=8e3,v=4e3
|
|
2833
|
+
y.length>b&&(y="\u2026"+y.slice(-b)),w.length>v&&(w="\u2026"+w.slice(-v))
|
|
2834
|
+
const C=I?"TIMEOUT":null,_=[y,w].filter(Boolean).join("\n")||"(no output)"
|
|
2810
2835
|
let E
|
|
2811
|
-
if(c)try{const e=await c.createToolRecord({projectId:t.projectId,type:"run-command",metadata:{name:p.name,command:f,exitCode:k,timedOut:
|
|
2836
|
+
if(c)try{const e=await c.createToolRecord({projectId:t.projectId,type:"run-command",metadata:{name:p.name,command:f,exitCode:k,timedOut:I,status:I?"timeout":0===k?"success":"failed",timestamp:(new Date).toISOString()}})
|
|
2812
2837
|
E=e?.id}catch(e){i.debug("Failed to create tool record for command run",{error:(0,n.getErrorMessage)(e)})}l({success:!0})
|
|
2813
2838
|
const q=E?`\n[RECORD:${E}]`:""
|
|
2814
2839
|
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}}}
|
|
@@ -2872,7 +2897,7 @@ try{const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,t=o?.getSes
|
|
|
2872
2897
|
if(t&&e){const n=await d.sessionIdentity.getParentSessionId(e,o,h),s=r.description||r.prompt
|
|
2873
2898
|
await t.createQuestion({fromSessionId:e,toSessionId:n||void 0,questionType:"alternatives",question:"Planning requested: "+s,options:[{id:"auto",label:"Auto Plan",description:"Spawn an autonomous planner agent"},{id:"manual",label:"Manual Plan",description:"Open the interactive plan editor"},{id:"cancel",label:"Skip",description:"Dismiss this planning request"}],context:r.prompt,category:"action-required",priority:"high"}),h.info("planner-request: notification created",{fromSessionId:e})}else h.warn("planner-request: skipping notification",{hasClient:!!t,hasCallerSessionId:!!e})}catch(e){h.warn("planner-request: failed to create notification",{error:(0,l.getErrorMessage)(e)})}m={content:[{type:"text",text:"Planning request submitted. The user will choose the planning approach. This is non-blocking \u2014 continue with your other work.\nPLANNER_CHOICE_PENDING|"+JSON.stringify({prompt:r.prompt,description:r.description})}]}
|
|
2874
2899
|
break}const n="auto-planner"
|
|
2875
|
-
if(h.info("Spawning planner",{planningMode:e,agent:n}),m=await(0,u.handleSpawn)({agent:n,prompt:r.prompt,title:r.description},t,h,o),!m.isError&&m.content.length>0){const t=m.content[0].text
|
|
2900
|
+
if(h.info("Spawning planner",{planningMode:e,agent:n}),m=await(0,u.handleSpawn)({agent:n,prompt:r.prompt,title:r.description},t,h,o,s),!m.isError&&m.content.length>0){const t=m.content[0].text
|
|
2876
2901
|
m.content[0].text=`Planning mode: ${e} (agent: ${n}). Planning is running in the background \u2014 continue with your other work.\n${t}`}break}case"check-status":m=await(0,u.handleCheckStatus)(f,t,h,o)
|
|
2877
2902
|
break
|
|
2878
2903
|
case"list":const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,[n,a]=await Promise.all([(0,u.handleListSessions)(t,h,o,{activeOnly:r.activeOnly,limit:r.limit,agentType:"auto-planner",parentSessionId:e}),(0,u.handleListSessions)(t,h,o,{activeOnly:r.activeOnly,limit:r.limit,agentType:"planner",parentSessionId:e})]),c=n.content[0]?.text??"",g=a.content[0]?.text??""
|
|
@@ -2900,12 +2925,12 @@ return o(t,e),t})
|
|
|
2900
2925
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,r,n,o,s,g,p){const f=s.child({tool:"file_recover"}),m=g.startTimer("tool_execution_time"),y=Date.now()
|
|
2901
2926
|
try{let m
|
|
2902
2927
|
try{m=i.FileRecoverSchema.parse(e)}catch(t){if(t instanceof a.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
2903
|
-
return f.warn("Validation error",{error:r,args:e}),{content:[{type:"text",text:"\u274c "+r}],isError:!0}}throw t}const{path:w,commitHash:k,createBackup:
|
|
2904
|
-
return f.info("Recovering file to previous version",{taskId:v,filePath:w,commitHash:k,createBackup:
|
|
2905
|
-
try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:
|
|
2906
|
-
m=
|
|
2907
|
-
let
|
|
2908
|
-
try{await l.access(w),v=!0,n&&(
|
|
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:I}=m,{resolveActiveTaskId:b}=await Promise.resolve().then(t.bind(t,3451)),v=e.taskId||await b(r,n,s)||"untracked"
|
|
2929
|
+
return f.info("Recovering file to previous version",{taskId:v,filePath:w,commitHash:k,createBackup:I}),await async function(e,t,r,n,o,s,i,a,g,p,f){let m
|
|
2930
|
+
try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:I}=await d.createFileOperationRecords(e,k?.requestId,o.projectId,"file-recover",y,{operationType:"file",filePath:y,commitHash:r,createBackup:n},s.getTaskClient(),i,a,g,"file-recover",f)
|
|
2931
|
+
m=I
|
|
2932
|
+
let b,v=!1
|
|
2933
|
+
try{await l.access(w),v=!0,n&&(b=`${w}.backup-${(new Date).toISOString().replace(/[:.]/g,"-")}`,await l.copyFile(w,b),a.info("Created backup",{originalPath:w,backupPath:b}))}catch{v=!1}const C=o.git
|
|
2909
2934
|
if(!C)throw Error("Git is not available")
|
|
2910
2935
|
if(!(await(0,u.validateCommitHash)(C,r,a,"file-recover")).valid)throw Error(`Commit hash '${r}' is invalid or not found`)
|
|
2911
2936
|
let _
|
|
@@ -2914,9 +2939,9 @@ if(t.includes("does not exist")||t.includes("not found")||t.includes("Path"))thr
|
|
|
2914
2939
|
throw Error(`Failed to retrieve file '${y}' from commit '${r}': ${t}`)}await l.writeFile(w,_,"utf8")
|
|
2915
2940
|
let E={}
|
|
2916
2941
|
try{const t=`Recover ${y} from ${r.substring(0,8)}`
|
|
2917
|
-
E=await d.commitToGit(e,y,m,m,t,o,a,g,"file-recover"),a.info("Recovery committed via shared utility",{path:y,sourceCommitHash:r,newCommitHash:E.commitHash?.substring(0,8),commitMessage:t})}catch(e){a.warn("Failed to commit recovery via shared utility",{error:e})}if(m)try{await i.updateToolRecord(m,{metadata:{path:y,status:"completed",recoveredLength:_.length,hadBackup:n&&v,backupPath:
|
|
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:b,wasFileCreated:!v,processingTime:Date.now()-p,...E.commitHash&&{commitHash:E.commitHash,previousCommitHash:E.previousCommitHash||void 0}},note:"File recovered successfully from "+r.substring(0,8)})}catch(e){a.warn("Failed to update tool record",{recordError:e})}const q=v?"recovered":"created from recovery"
|
|
2918
2943
|
let S=`\u2705 **File ${q.charAt(0).toUpperCase()+q.slice(1)} Successfully**\n\n`
|
|
2919
|
-
return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&
|
|
2944
|
+
return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&b&&(S+=`**Backup created:** ${c.basename(b)}\n`),S+="**Git status:** Recovery committed\n",S+="\u{1f4a1} **Tip:** The file has been restored to its state at the specified commit.",a.info("File recovery completed successfully",{path:y,commitHash:r,duration:Date.now()-p}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(v,w,k,I,r,n,o,f,g,y,p)}catch(e){const t=Date.now()-y
|
|
2920
2945
|
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}}}
|
|
2921
2946
|
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"
|
|
2922
2947
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,u,h,g,p,f){const m=g.child({tool:"request_operations"})
|
|
@@ -3074,15 +3099,15 @@ if(/^\d+$/.test(e)){const t=parseInt(e,10)
|
|
|
3074
3099
|
return{start:t,end:t}}const t=e.match(/^(\d+)-(\d+)$/)
|
|
3075
3100
|
if(t)return{start:parseInt(t[1],10),end:parseInt(t[2],10)}
|
|
3076
3101
|
if(e.match(/^(\d+(?:,\d+)+)$/)){const t=e.split(",").map((e=>parseInt(e,10)))
|
|
3077
|
-
return{start:Math.min(...t),end:Math.max(...t)}}return null}(p),
|
|
3078
|
-
let
|
|
3079
|
-
k&&
|
|
3102
|
+
return{start:Math.min(...t),end:Math.max(...t)}}return null}(p),I=["blame","--porcelain"]
|
|
3103
|
+
let b
|
|
3104
|
+
k&&I.push(`-L${k.start},${k.end}`),f&&I.push(f),I.push("--",w),c.debug("Executing git blame",{args:I})
|
|
3080
3105
|
try{if(!t.git)throw Error("Git context not available")
|
|
3081
|
-
|
|
3106
|
+
b=await t.git.raw(I)}catch(e){const t=(0,h.getErrorMessage)(e)
|
|
3082
3107
|
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")
|
|
3083
3108
|
let n="",o="",s="",i=0,a=0,c=new Map
|
|
3084
3109
|
for(let e=0;e<r.length;e++){const l=r[e],d=l.match(/^([0-9a-f]{40})\s+\d+\s+(\d+)/)
|
|
3085
|
-
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}(
|
|
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}(b)
|
|
3086
3111
|
if(0===v.length)return{content:[{type:"text",text:"\u274c No blame information found for "+w}],isError:!0}
|
|
3087
3112
|
const C=function(e){if(0===e.length)return[]
|
|
3088
3113
|
const t=[]
|
|
@@ -3216,7 +3241,7 @@ var t={}
|
|
|
3216
3241
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3217
3242
|
return o(t,e),t})
|
|
3218
3243
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.testingDefs=void 0
|
|
3219
|
-
const i=s(t(6183)),a=t(2052),c=e=>(t,r)=>e(t,r.context,r.apiClient,r.logger,r.metrics)
|
|
3244
|
+
const i=s(t(6183)),a=t(2052),c=e=>(t,r)=>e(t,r.context,r.apiClient,r.logger,r.metrics,r.cliOrigin)
|
|
3220
3245
|
exports.testingDefs=[{name:"testing_process_list",description:"List all test processes for this project. Shows active/inactive status, command count, and scope.",schema:i.TestingProcessListSchema,annotations:{title:"List Test Processes",readOnlyHint:!0},readOnly:!0,handler:c(a.handleTestingProcessList)},{name:"testing_process_get",description:"Get detailed configuration of a test process including setup and test commands.",schema:i.TestingProcessGetSchema,annotations:{title:"Get Test Process",readOnlyHint:!0},readOnly:!0,handler:c(a.handleTestingProcessGet)},{name:"testing_process_create",description:"Create a new test process with optional setup commands and one or more test commands. Each command has a name, shell command, required flag, and timeout.",schema:i.TestingProcessCreateSchema,annotations:{title:"Create Test Process",readOnlyHint:!1},handler:c(a.handleTestingProcessCreate)},{name:"testing_process_update",description:"Update an existing test process. Can modify name, description, scope, active status, and test configuration.",schema:i.TestingProcessUpdateSchema,annotations:{title:"Update Test Process",readOnlyHint:!1},handler:c(a.handleTestingProcessUpdate)},{name:"testing_reference",description:"Get the test process design guide with patterns for Node.js, Python, Go, Rust, and monorepo setups.",schema:i.TestingReferenceSchema,annotations:{title:"Testing Reference",readOnlyHint:!0},readOnly:!0,handler:c(a.handleTestingReference)},{name:"execute_test_command",description:'Execute a specific command from a configured test process. Use commandName="setup" to run all setup commands, or specify a test command name to run it. Only commands defined in the test process can be executed.',schema:i.ExecuteTestCommandSchema,annotations:{title:"Execute Test Command",readOnlyHint:!1},handler:c(a.handleExecuteTestCommand)},{name:"report_test_results",description:"Report the results of a test run. Call this after running all test commands to record pass/fail status and per-command results. The test run is auto-discovered from the current request context.",schema:i.ReportTestResultsSchema,annotations:{title:"Report Test Results",readOnlyHint:!1},handler:c(a.handleReportTestResults)}]},5278(e,exports,t){"use strict"
|
|
3221
3246
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3222
3247
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.DocumentFileManager=void 0
|
|
@@ -3298,10 +3323,10 @@ const m=g.acceptanceCriteria||[],y={unverified:0,partial:0,verified:0,partially_
|
|
|
3298
3323
|
m.forEach((e=>{const t=e.status||"unverified"
|
|
3299
3324
|
t in y&&y[t]++}))
|
|
3300
3325
|
let w=g.testVerification||null
|
|
3301
|
-
const k=g.title,
|
|
3302
|
-
let
|
|
3303
|
-
return
|
|
3304
|
-
|
|
3326
|
+
const k=g.title,I=g.type
|
|
3327
|
+
let b=`# ${"feature"===I?"Feature":"quick-edit"===I?"Quick Edit":"Bug Fix"} Request: ${k} (${t})\nStatus: ${g.status}\nCreated: ${new Date(g.createdAt).toLocaleString()}\nUpdated: ${new Date(g.updatedAt).toLocaleString()}\n\n## Description\n${g.description||"_No description provided._"}\n\n## Progress Summary\n- Tasks: ${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`
|
|
3328
|
+
return b+=`\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`,b+="\n## Tasks\n",0===p.length?b+="No tasks found for this request.\n":p.forEach((e=>{b+=`**[${e.id}]** ${e.title} (Status: ${e.status})\n`})),d.info(`Added task listing with ${p.length} tasks`),b+="\n## Acceptance Criteria\n",b+=(0,i.formatCriteriaWithHashes)(m)+"\n","ready_for_review"===g.status&&m.some((e=>"verified"!==e.status))&&(b+="\n> **Status: ready_for_review** \u2014 Use the merge operation to verify criteria and merge to main.\n"),w&&(b+=`\n## Test Coverage\n- Test Cases: ${w.totalTestCases||0}\n- Criteria Tested: ${w.criteriaTestedCount||0}/${y.total}\n`,w.criterionCoverage&&Array.isArray(w.criterionCoverage)&&(b+="\n### Detailed Test Coverage:\n",w.criterionCoverage.forEach((e=>{b+=`- Criterion ${e.criterionId}: ${e.coverage} coverage\n`})))),g.recentActivity&&Array.isArray(g.recentActivity)&&(b+="\n## Recent Activity\n",g.recentActivity.slice(0,5).forEach((e=>{const t=new Date(e.timestamp).toLocaleString()
|
|
3329
|
+
b+=`- ${t}: ${e.description}\n`}))),u({success:!0}),{content:[{type:"text",text:b}]}}catch(t){return d.error("Error getting request information",{args:e,error:t instanceof Error?t.stack:t+""}),u({success:!1,error:t instanceof Error?t.name:"unknown"}),t instanceof n.ConnectionError?{content:[{type:"text",text:"Unable to get request information: Connection to the server failed. Please check your network connection and try again."}],isError:!0}:{content:[{type:"text",text:"Error getting request information: "+(0,s.getErrorMessage)(t)}],isError:!0}}}
|
|
3305
3330
|
const r=t(9860),n=t(5674),o=t(2960),s=t(8824),i=t(5454)},5454(e,exports){"use strict"
|
|
3306
3331
|
function t(e,t){let r=0
|
|
3307
3332
|
for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t)|0
|
|
@@ -3422,8 +3447,8 @@ var t={}
|
|
|
3422
3447
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3423
3448
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3424
3449
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDeleteFiles=async function(e,r,n,o,s,i){const m=o.child({tool:"delete_files"}),y=Date.now()
|
|
3425
|
-
let w,k,
|
|
3426
|
-
const
|
|
3450
|
+
let w,k,I=l.FileOperationPhase.VALIDATION
|
|
3451
|
+
const b={toolName:"delete-files",operationName:"delete",fileOperationPhase:l.FileOperationPhase.FILE_WRITE,recordType:"delete-files",metricsPrefix:"delete_files",successMessage:"Successfully deleted files",failureMessage:"Failed to delete files"}
|
|
3427
3452
|
try{const u=n.getTaskClient(),v=n.getToolRecordClient(),C=n.getRequestClient(),_=l.validateArgs(e,c.DeleteFilesSchema),{paths:E,operations:q,comment:S}=_,{resolveActiveTaskId:T}=await Promise.resolve().then(t.bind(t,3451)),P=e.taskId||await T(r,n,o)||"untracked"
|
|
3428
3453
|
let j=[]
|
|
3429
3454
|
if(E)j=E.map((e=>({type:"file",target:e})))
|
|
@@ -3432,22 +3457,22 @@ j=q.map((e=>{if(e.path)return{type:"file",target:e.path}
|
|
|
3432
3457
|
if(e.documentId)return{type:"document",target:e.documentId}
|
|
3433
3458
|
throw Error("Invalid operation: neither path nor documentId specified")}))}if(0===j.length)throw Error("At least one file or document must be specified for deletion")
|
|
3434
3459
|
const R=j.filter((e=>"file"===e.type)),x=j.filter((e=>"document"===e.type)),M=j.length
|
|
3435
|
-
m.info("Starting mixed file and document deletion operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,comment:S}),l.validateTaskIdFormat(P,m,s,
|
|
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,b.metricsPrefix)
|
|
3436
3461
|
const O=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3437
3462
|
m.info("Initial branch context",{initialBranch:O.branch,initialRequestId:O.requestId,isMain:O.isMain})
|
|
3438
3463
|
const D=[]
|
|
3439
3464
|
for(const e of R){const{normalizedPath:t,fullPath:n}=l.validateAndNormalizePath(e.target,r)
|
|
3440
|
-
D.push({normalized:t,full:n})}
|
|
3441
|
-
const $=D.length>0?D[0].normalized:"document_operations",A=await l.validateTaskId(P,$,u,m,s,
|
|
3465
|
+
D.push({normalized:t,full:n})}I=l.FileOperationPhase.TASK_VALIDATION,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3466
|
+
const $=D.length>0?D[0].normalized:"document_operations",A=await l.validateTaskId(P,$,u,m,s,b.metricsPrefix),F=A?.requestId,N=await l.validateWorkItemStates(P,$,u,C,r,m,s,b.metricsPrefix),L=await l.autoPromoteTaskStatus(P,A.status,F,N.request?.status,$,u,C,m,s,b.metricsPrefix)
|
|
3442
3467
|
L.taskPromoted&&m.info(`Auto-promoted task ${P} (${A.title||"Untitled"}) to in_progress for mixed operations`,{taskId:P,taskTitle:A.title,previousStatus:A.status,newStatus:L.newTaskStatus,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length}),L.requestPromoted&&m.info(`Auto-promoted request ${F} to in_progress for file operations`,{requestId:F,previousStatus:N.request?.status,newStatus:L.newRequestStatus,triggeringTaskId:P})
|
|
3443
|
-
const z=await l.ensureCorrectWorkspaceContext({taskPromoted:L.taskPromoted,requestId:F,context:r,operation:"delete-files",logger:m,metrics:s,metricsPrefix:
|
|
3468
|
+
const z=await l.ensureCorrectWorkspaceContext({taskPromoted:L.taskPromoted,requestId:F,context:r,operation:"delete-files",logger:m,metrics:s,metricsPrefix:b.metricsPrefix})
|
|
3444
3469
|
if(!z.success){if(z.isLockConflict)return{content:[{type:"text",text:"\u274c "+z.error}],isError:!0}
|
|
3445
3470
|
throw Error(z.error)}let H={hadUserMods:!1,userModsCommitHash:void 0}
|
|
3446
3471
|
if(r.git)try{m.debug("[DELETE-FILES] Checking for user changes before mixed delete operations")
|
|
3447
3472
|
const e=await(0,h.commitUserChangesBeforeToolOperation)(r.git,"delete-files",{requestId:F,taskId:P,workspaceManager:r.workspaceManager},m,s)
|
|
3448
|
-
e.userChangesCommitted&&(m.debug("[DELETE-FILES] User changes committed before mixed delete operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),m.info("User changes committed before mixed delete-files operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),H={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){m.debug("[DELETE-FILES] Pre-tool commit failed, continuing with mixed delete operations",{error:e instanceof Error?e.message:e+""}),m.warn("Pre-tool user changes commit failed, continuing with mixed delete operation",{taskId:P,totalOperations:j.length,fileOperations:R.length,documentOperations:x.length,error:e instanceof Error?e.message:e+""})}m.debug("[DELETE-FILES] Proceeding with mixed delete operations",{totalOperations:j.length,fileDeletes:R.length,documentDeletes:x.length}),
|
|
3449
|
-
const{toolRecordId:B,localToolRecordId:U}=await l.createFileOperationRecords(P,F,r.projectId,
|
|
3450
|
-
w=B,k=B,b
|
|
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}),I=l.FileOperationPhase.RECORD_CREATION,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3474
|
+
const{toolRecordId:B,localToolRecordId:U}=await l.createFileOperationRecords(P,F,r.projectId,b.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,b.metricsPrefix,i)
|
|
3475
|
+
w=B,k=B,I=b.fileOperationPhase,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3451
3476
|
const G=[]
|
|
3452
3477
|
let W=0
|
|
3453
3478
|
x.length>0&&n.setProjectId(r.projectId)
|
|
@@ -3462,12 +3487,12 @@ throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${
|
|
|
3462
3487
|
r.success=!0,r.filename=o.filename,W++,m.info("Document archived successfully",{documentId:o.id,filename:o.filename,archivedAt:o.archived_at})}catch(e){r.error=(0,f.getErrorMessage)(e),m.warn("Failed to delete document "+t,{error:r.error})}G.push(r)}const J=Date.now()-y
|
|
3463
3488
|
s.recordValue("delete_files_time",J),s.incrementCounter("delete_files_operations_total",M),s.incrementCounter("delete_files_operations_success",W),s.incrementCounter("delete_files_operations_failed",M-W),s.incrementCounter("delete_files_file_operations",R.length),s.incrementCounter("delete_files_document_operations",x.length),W===M?s.incrementCounter("delete_files_success",1):W>0?s.incrementCounter("delete_files_partial_success",1):s.incrementCounter("delete_files_total_failure",1)
|
|
3464
3489
|
let K=null
|
|
3465
|
-
if(W>0){
|
|
3490
|
+
if(W>0){I=l.FileOperationPhase.GIT_COMMIT,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3466
3491
|
const e=G.filter((e=>e.success)),t=e.filter((e=>"file"===e.type)).length,n=e.filter((e=>"document"===e.type)).length
|
|
3467
3492
|
let o
|
|
3468
|
-
o=t>0&&n>0?`Delete ${t} files and ${n} documents - ${S}`:t>0?1===t?"Delete file - "+S:`Delete ${t} files - ${S}`:1===n?"Delete document - "+S:`Delete ${n} documents - ${S}`,K=await l.commitToGit(P,$,B,U,o,r,m,s,
|
|
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,b.metricsPrefix)}I=l.FileOperationPhase.RECORD_UPDATE_SUCCESS,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3469
3494
|
const Y=G.filter((e=>e.success)),Q=G.filter((e=>!e.success))
|
|
3470
|
-
await l.updateFileOperationRecords(P,w,k,$,
|
|
3495
|
+
await l.updateFileOperationRecords(P,w,k,$,b.recordType,W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,{status:W===M?"completed":"partial_success",commitHash:K?.commitHash,previousCommitHash:K?.previousCommitHash,totalOperations:M,fileOperations: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,b.metricsPrefix)
|
|
3471
3496
|
const Z=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3472
3497
|
let X=""
|
|
3473
3498
|
if(W===M){const e=Y.filter((e=>"file"===e.type)).length,t=Y.filter((e=>"document"===e.type)).length
|
|
@@ -3476,10 +3501,10 @@ return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n"):"All delete operations
|
|
|
3476
3501
|
return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n")
|
|
3477
3502
|
if(K?.commitHash&&(X+="\nCommit: "+K.commitHash.substring(0,8)),Z.requestId&&(X+="\nBranch: "+Z.requestId),z.lockAcquired&&z.lockedRequestId){const e=r.workspaceManager?.getCurrentContext(r.currentSessionId)
|
|
3478
3503
|
e?.permanentBranch||(X+="\n\u{1f512} **Locked request:** "+z.lockedRequestId)}return{content:[{type:"text",text:X}],isError:0===W}}catch(t){if(e.taskId&&n)try{const o=n.getToolRecordClient(),s=t instanceof d.NotFoundError||t instanceof d.ValidationError||t instanceof u.ZodError
|
|
3479
|
-
await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:r.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,f.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:
|
|
3480
|
-
if(s.recordValue("delete_files_time",o),s.incrementCounter("delete_files_errors",1),m.error("Error in delete-files operation:",{error:(0,f.getErrorMessage)(t),time:o}),(w||k)&&e.taskId){
|
|
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:I,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
|
|
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){I=l.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
3481
3506
|
try{const r=n.getTaskClient(),o=n.getToolRecordClient()
|
|
3482
|
-
await l.updateFileOperationRecords(e.taskId,w,k,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",
|
|
3507
|
+
await l.updateFileOperationRecords(e.taskId,w,k,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",b.recordType,"Failed to delete operations",{status:"failed",error:(0,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,b.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,I,m,s,e,b)}}
|
|
3483
3508
|
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"
|
|
3484
3509
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
3485
3510
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
@@ -3545,7 +3570,7 @@ const n=await this.requestWithRetry("POST","/api/files/recover",t)
|
|
|
3545
3570
|
if(!(0,i.safeGetResponseData)(n,null))throw new r.ServiceError("Empty response when recovering file")
|
|
3546
3571
|
const o=(0,i.safeGetResponseData)(n,{success:!0,path:e.path,commitHash:e.commitHash,backupPath:void 0})
|
|
3547
3572
|
return this.logger.info("Successfully recovered file "+e.path,{path:o.path,commitHash:o.commitHash,backupPath:o.backupPath}),o}catch(t){throw this.logger.error("Failed to recover file "+e.path,{path:e.path,commitHash:e.commitHash,error:t instanceof Error?t.stack:t+""}),t}}}exports.FileOperationsClient=a},6183(e,exports,t){"use strict"
|
|
3548
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranchSchema=exports.PlanWriteSchema=exports.PlanReadSchema=exports.DocumentOperationsSchema=exports.SearchDocumentsSchema=exports.CreateDocumentSchema=exports.ReplaceLinesSchema=exports.InsertLinesSchema=exports.SwitchToRequestBranchSchema=exports.PlannerOpsSchema=exports.SpecialistOpsSchema=exports.SubagentOperationsSchema=exports.TaskOperationsSchema=exports.CompleteTaskSchema=exports.GetTaskInformationSchema=exports.GetRequestInformationSchema=exports.ListRequestsSchema=exports.ListTasksSchema=exports.SearchSchema=exports.QueryHistorySchema=exports.FileRecoverSchema=exports.FileHistorySchema=exports.DeleteFilesSchema=exports.DeleteFileSchema=exports.ReplaceInFilesSchema=exports.ReplaceStringsSchema=exports.ReplaceStringSchema=exports.MoveFilesSchema=exports.CreateDirectorySchema=exports.GetFileInfoSchema=exports.ListDirectorySchema=exports.ReadFilesSchema=exports.ViewAssetSchema=exports.WriteFileSchema=exports.UpdateTaskStatusSchema=exports.CreateTaskSchema=exports.CreateRequestSchema=exports.CompleteRequestSchema=exports.ExecutedTestSchema=exports.TestVerificationSchema=exports.TestDefinitionSchema=exports.AcceptanceCriterionSchema=exports.RecordTypeEnum=exports.EvidenceTypeEnum=exports.CriterionStatusEnum=exports.RequestStatusEnum=exports.TaskStatusEnum=exports.RequestTypeEnum=exports.TestCoverageTypeEnum=exports.CompletionStatusEnum=void 0,exports.UpdateSpecializationSchema=exports.SessionMessageOperationsSchema=exports.ReportTestResultsSchema=exports.CommandsSchema=exports.ExecuteTestCommandSchema=exports.TestingReferenceSchema=exports.TestingProcessUpdateSchema=exports.TestingProcessCreateSchema=exports.TestingProcessGetSchema=exports.TestingProcessListSchema=exports.MetaReferenceSchema=exports.MetaAgentListSchema=exports.MetaWorkflowRemoveRecipeSchema=exports.MetaWorkflowAddRecipeSchema=exports.MetaHookCreateSchema=exports.MetaHookListSchema=exports.MetaRecipeRemoveHookSchema=exports.MetaRecipeAddHookSchema=exports.MetaRecipeCreateSchema=exports.MetaRecipeGetSchema=exports.MetaRecipeListSchema=exports.MetaWorkflowUpdateSchema=exports.MetaWorkflowCreateSchema=exports.MetaWorkflowGetSchema=exports.MetaWorkflowListSchema=exports.GenerateRequestJournalSchema=exports.QuickManageSchema=exports.QuickReplaceSchema=exports.QuickWriteSchema=exports.RequestOperationsSchema=exports.ManageFilesSchema=exports.ModifyFileSchema=exports.RevertRequestSchema=exports.SwitchToBranchSchema=void 0
|
|
3573
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranchSchema=exports.PlanWriteSchema=exports.PlanReadSchema=exports.DocumentOperationsSchema=exports.SearchDocumentsSchema=exports.CreateDocumentSchema=exports.ReplaceLinesSchema=exports.InsertLinesSchema=exports.SwitchToRequestBranchSchema=exports.PlannerOpsSchema=exports.SpecialistOpsSchema=exports.SubagentOperationsSchema=exports.TaskOperationsSchema=exports.CompleteTaskSchema=exports.GetTaskInformationSchema=exports.GetRequestInformationSchema=exports.ListRequestsSchema=exports.ListTasksSchema=exports.SearchSchema=exports.QueryHistorySchema=exports.FileRecoverSchema=exports.FileHistorySchema=exports.DeleteFilesSchema=exports.DeleteFileSchema=exports.ReplaceInFilesSchema=exports.ReplaceStringsSchema=exports.ReplaceStringSchema=exports.MoveFilesSchema=exports.CreateDirectorySchema=exports.GetFileInfoSchema=exports.ListDirectorySchema=exports.ReadFilesSchema=exports.ViewAssetSchema=exports.WriteFileSchema=exports.UpdateTaskStatusSchema=exports.CreateTaskSchema=exports.CreateRequestSchema=exports.CompleteRequestSchema=exports.ExecutedTestSchema=exports.TestVerificationSchema=exports.TestDefinitionSchema=exports.AcceptanceCriterionSchema=exports.RecordTypeEnum=exports.EvidenceTypeEnum=exports.CriterionStatusEnum=exports.RequestStatusEnum=exports.TaskStatusEnum=exports.RequestTypeEnum=exports.TestCoverageTypeEnum=exports.CompletionStatusEnum=void 0,exports.CommitToViewedSessionSchema=exports.UpdateSpecializationSchema=exports.SessionMessageOperationsSchema=exports.ReportTestResultsSchema=exports.CommandsSchema=exports.ExecuteTestCommandSchema=exports.TestingReferenceSchema=exports.TestingProcessUpdateSchema=exports.TestingProcessCreateSchema=exports.TestingProcessGetSchema=exports.TestingProcessListSchema=exports.MetaReferenceSchema=exports.MetaAgentListSchema=exports.MetaWorkflowRemoveRecipeSchema=exports.MetaWorkflowAddRecipeSchema=exports.MetaHookCreateSchema=exports.MetaHookListSchema=exports.MetaRecipeRemoveHookSchema=exports.MetaRecipeAddHookSchema=exports.MetaRecipeCreateSchema=exports.MetaRecipeGetSchema=exports.MetaRecipeListSchema=exports.MetaWorkflowUpdateSchema=exports.MetaWorkflowCreateSchema=exports.MetaWorkflowGetSchema=exports.MetaWorkflowListSchema=exports.GenerateRequestJournalSchema=exports.QuickManageSchema=exports.QuickReplaceSchema=exports.QuickWriteSchema=exports.RequestOperationsSchema=exports.ManageFilesSchema=exports.ModifyFileSchema=exports.RevertRequestSchema=exports.SwitchToBranchSchema=void 0
|
|
3549
3574
|
const r=t(1569),n=t(8955),o=r.z.string().refine((e=>!(!e||!/^tas\d{6}$/.test(e)&&!/^req\d{6}#\d+$/.test(e))),{message:"Task ID must be req######+#NN (e.g. req000005#03) or tas###### format (e.g. tas000001)."}),s=r.z.string().refine((e=>!!e&&/^req\d{6}$/.test(e)),{message:"Request ID must match format: req###### (e.g. req000001)"}),i=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^(doc|plan|jour)\d{6}$/.test(e))),{message:"Document ID must match format: doc_[26 alphanumeric] (ULID) or doc######/plan######/jour###### (local ID)"})
|
|
3550
3575
|
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" }'})}))
|
|
3551
3576
|
const a=r.z.string().min(1).describe("OpenCode session ID")
|
|
@@ -3556,7 +3581,7 @@ exports.PlanReadSchema=r.z.object({operation:r.z.enum(["get","get-active","list"
|
|
|
3556
3581
|
const r=e.operation,n={complete:{field:"complete",hint:'Provide: { complete: { summary: "..." } }'},merge:{field:"merge",hint:'Provide: { merge: { verifications: [{key: "1a", evidence: "..."}] } }'},revert:{field:"revert",hint:'Provide: { revert: { reason: "..." } }'},search:{field:"search",hint:'Provide: { search: { query: "..." } }'}}[r]
|
|
3557
3582
|
n&&!e[n.field]&&t.addIssue({code:"custom",message:`'${r}' operation requires '${n.field}' data. ${n.hint}`})})),exports.QuickWriteSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional()}),exports.QuickReplaceSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1),fuzzy_match:r.z.boolean().optional()})).min(1),fuzzy_match:r.z.boolean().optional(),comment:r.z.string().min(1,"Comment describing the change is required")}),exports.QuickManageSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}))}).optional()})).min(1)}),exports.GenerateRequestJournalSchema=r.z.object({requestId:r.z.string().regex(/^req[_\d].+$/,"Invalid request ID format. Expected format: req_[26 chars] or req######")}),exports.MetaWorkflowListSchema=r.z.object({}),exports.MetaWorkflowGetSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to retrieve")}),exports.MetaWorkflowCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the workflow"),shortName:r.z.string().min(1).max(10).describe("Short display name (required, max 10 chars)"),description:r.z.string().optional().describe("Description of what the workflow does"),documentation:r.z.string().optional().describe("Detailed documentation"),defaultAgent:r.z.string().optional().describe("Default agent template to use"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior: auto-merge (default), auto-test-then-merge, or manual-review"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaWorkflowUpdateSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to update"),name:r.z.string().min(1).optional().describe("New name"),shortName:r.z.string().max(10).optional().describe("New short name (max 10 chars)"),description:r.z.string().optional().describe("New description"),documentation:r.z.string().optional().describe("New documentation"),defaultAgent:r.z.string().optional().describe("New default agent"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaRecipeListSchema=r.z.object({}),exports.MetaRecipeGetSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to retrieve")}),exports.MetaRecipeCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the recipe"),description:r.z.string().optional().describe("Description of what the recipe does"),documentation:r.z.string().optional().describe("Detailed documentation")}),exports.MetaRecipeAddHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to add the hook to"),hookId:r.z.string().describe("Hook template ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the recipe (0-based, appended if omitted)")}),exports.MetaRecipeRemoveHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to remove the hook from"),hookId:r.z.string().describe("Hook template ID to remove")}),exports.MetaHookListSchema=r.z.object({}),exports.MetaHookCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the hook"),description:r.z.string().optional().describe("Description of what the hook does"),eventType:r.z.string().describe("Event type that triggers this hook (e.g., session_idle, request_completed, custom:plan_ready)"),category:r.z.enum(["alchemy","session","message","editing","reading","file_management","documents","history","tool"]).default("session").describe("Hook category"),agent:r.z.string().describe("Agent template to execute when hook fires"),promptTemplate:r.z.string().describe("Prompt template with {{variable}} substitution"),condition:r.z.record(r.z.any()).optional().describe("Condition object for filtering when hook fires"),executionMode:r.z.enum(["same_session","sub_agent","background","notification","direct_report"]).default("background").describe("How to execute the hook"),timing:r.z.enum(["before","after"]).default("after").describe("When to fire relative to the event"),maxIterations:r.z.number().int().min(1).optional().describe("Maximum times to fire per session"),emitEvent:r.z.string().optional().describe("Custom event to emit on completion"),emitEventOnCondition:r.z.union([r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}),r.z.array(r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}))]).optional().describe("Conditional event emission based on output")}),exports.MetaWorkflowAddRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to add the recipe to"),recipeId:r.z.string().describe("Recipe ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the workflow (0-based, appended if omitted)")}),exports.MetaWorkflowRemoveRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to remove the recipe from"),recipeId:r.z.string().describe("Recipe ID to remove")}),exports.MetaAgentListSchema=r.z.object({}),exports.MetaReferenceSchema=r.z.object({}),exports.TestingProcessListSchema=r.z.object({}),exports.TestingProcessGetSchema=r.z.object({processId:r.z.string().describe("Test process ID to retrieve")})
|
|
3558
3583
|
const l=r.z.object({name:r.z.string().min(1).describe('Command name (e.g., "Build", "Unit Tests")'),command:r.z.string().min(1).describe('Shell command to run (e.g., "npm test")'),required:r.z.boolean().default(!0).describe("If true, failure blocks the request (default: true)"),timeout:r.z.number().int().min(10).max(3600).default(300).describe("Max execution time in seconds (default: 300)")})
|
|
3559
|
-
exports.TestingProcessCreateSchema=r.z.object({name:r.z.string().min(1).describe("Name for the test process"),description:r.z.string().optional().describe("Description of what this process verifies"),scope:r.z.string().optional().describe('Path prefix for monorepo scoping (e.g., "packages/api/"). Omit for global.'),setup:r.z.array(r.z.string()).optional().describe('Commands to prepare the environment (e.g., ["ln -s ../../node_modules node_modules"])'),commands:r.z.array(l).min(1).describe("Test commands to execute in order"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingProcessUpdateSchema=r.z.object({processId:r.z.string().describe("Test process ID to update"),name:r.z.string().min(1).optional().describe("New name"),description:r.z.string().optional().describe("New description"),scope:r.z.string().nullable().optional().describe("New scope (null to remove)"),isActive:r.z.boolean().optional().describe("Enable or disable the process"),setup:r.z.array(r.z.string()).optional().describe("New setup commands (replaces existing)"),commands:r.z.array(l).optional().describe("New test commands (replaces existing)"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingReferenceSchema=r.z.object({}),exports.ExecuteTestCommandSchema=r.z.object({processId:r.z.string().describe("Test process ID containing the command"),commandName:r.z.string().describe('Name of the test command to run, or "setup" to run all setup commands in sequence')}),exports.CommandsSchema=r.z.object({operation:r.z.enum(["run","list","add","remove"]).default("run").describe('"run" to execute a command, "list" to see available commands, "add" to register a new command, "remove" to delete one'),name:r.z.string().optional().describe('Command name (required for "run", "add", and "remove")'),args:r.z.string().optional().describe('Additional arguments appended to the base command (optional, for "run")'),grep:r.z.string().optional().describe('Filter output through grep (optional, for "run"). Pipes command output through grep -i with this pattern.'),command:r.z.string().optional().describe('Shell command to register (required for "add", e.g. "tsc --noEmit")'),description:r.z.string().optional().describe('What this command verifies (optional, for "add")'),timeout:r.z.number().optional().describe('Timeout in seconds (optional, for "add", default 60)')}),exports.ReportTestResultsSchema=r.z.object({status:r.z.enum(["passed","failed","error"]).describe("Overall result"),results:r.z.object({commands:r.z.array(r.z.object({name:r.z.string().describe("Command name"),status:r.z.enum(["passed","failed","skipped","error"]).describe("Command result"),output:r.z.string().optional().describe("Relevant output snippet"),diagnosis:r.z.string().optional().describe("Why it failed, if applicable")})).describe("Per-command results"),summary:r.z.string().describe("Brief overall summary"),acceptanceCriteria:r.z.array(r.z.object({criterion:r.z.string().describe("The acceptance criterion text"),status:r.z.enum(["verified","unverified","unclear"]),evidence:r.z.string().describe("How verified, or why not")})).optional().describe("AC verification results, if applicable")}).describe("Structured test results")}),exports.SessionMessageOperationsSchema=r.z.object({operation:r.z.enum(["send","reply","list","get","offer-handoff"]),type:r.z.enum(["question","report"]).optional().describe("Message type to send (required for send)"),toSessionId:r.z.string().optional().describe('Target session ID, or "parent" to auto-resolve to parent session (omit for broadcast questions)'),questionType:r.z.enum(["free-form","alternatives"]).optional().describe('Type of question (required for send type="question")'),questionContent:r.z.object({question:r.z.string().min(1).describe("The question text"),context:r.z.string().optional().describe("Additional context"),options:r.z.array(r.z.object({id:r.z.string(),label:r.z.string(),description:r.z.string().optional()})).optional().describe("Options for alternatives questions"),allowMultiple:r.z.boolean().optional().describe("Allow selecting multiple options")}).optional().describe('Question content (required for send type="question")'),priority:r.z.enum(["low","normal","high"]).optional().describe("Question priority"),expiresInHours:r.z.number().optional().describe("Question expiry in hours"),status:r.z.enum(["success","partial","failure","blocked"]).optional().describe('Report status (required for send type="report")'),summary:r.z.string().optional().describe('Report summary (required for send type="report")'),details:r.z.string().optional().describe("Report details"),finish:r.z.boolean().optional().describe("Release request associations after report"),messageCode:r.z.string().optional().describe("Message code (required for reply and get operations)"),respondedBySessionId:r.z.string().optional().describe("Session ID answering the question"),text:r.z.string().optional().describe("Text answer for free-form questions"),selectedOptions:r.z.array(r.z.string()).optional().describe("Selected option IDs for alternatives"),notes:r.z.string().optional().describe("Additional notes"),list:r.z.object({sessionId:r.z.string().optional().describe("Filter by session ID (auto-discovered if omitted)"),messageType:r.z.enum(["question","report","all"]).default("all").describe("Filter by message type"),direction:r.z.enum(["incoming","outgoing","all"]).default("all"),status:r.z.enum(["pending","answered","expired","success","partial","failure","blocked","all"]).default("all").describe("Filter by status"),readStatus:r.z.enum(["unread","read","acknowledged","all"]).default("all").describe("Filter by read status (reports only)"),limit:r.z.number().min(1).max(100).default(50),offset:r.z.number().min(0).default(0)}).optional().describe('List filters (operation: "list" only)'),offerHandoff:r.z.object({summary:r.z.string().describe("Summary of what was planned/created"),requestIds:r.z.array(r.z.string()).describe("Request IDs that were created from the plan")}).optional().describe('Handoff offer details (operation: "offer-handoff" only)')}).refine((e=>"send"===e.operation?!!e.type:"reply"===e.operation?!!e.messageCode:"list"===e.operation||("get"===e.operation?!!e.messageCode:"offer-handoff"===e.operation)),{message:"Invalid operation data: send requires type, reply requires messageCode, get requires messageCode"}),exports.UpdateSpecializationSchema=r.z.object({specialization:r.z.string().min(1).max(500).describe("Your updated specialization summary \u2014 a concise description of your accumulated domain expertise")})},6252(e,exports,t){"use strict"
|
|
3584
|
+
exports.TestingProcessCreateSchema=r.z.object({name:r.z.string().min(1).describe("Name for the test process"),description:r.z.string().optional().describe("Description of what this process verifies"),scope:r.z.string().optional().describe('Path prefix for monorepo scoping (e.g., "packages/api/"). Omit for global.'),setup:r.z.array(r.z.string()).optional().describe('Commands to prepare the environment (e.g., ["ln -s ../../node_modules node_modules"])'),commands:r.z.array(l).min(1).describe("Test commands to execute in order"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingProcessUpdateSchema=r.z.object({processId:r.z.string().describe("Test process ID to update"),name:r.z.string().min(1).optional().describe("New name"),description:r.z.string().optional().describe("New description"),scope:r.z.string().nullable().optional().describe("New scope (null to remove)"),isActive:r.z.boolean().optional().describe("Enable or disable the process"),setup:r.z.array(r.z.string()).optional().describe("New setup commands (replaces existing)"),commands:r.z.array(l).optional().describe("New test commands (replaces existing)"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingReferenceSchema=r.z.object({}),exports.ExecuteTestCommandSchema=r.z.object({processId:r.z.string().describe("Test process ID containing the command"),commandName:r.z.string().describe('Name of the test command to run, or "setup" to run all setup commands in sequence')}),exports.CommandsSchema=r.z.object({operation:r.z.enum(["run","list","add","remove"]).default("run").describe('"run" to execute a command, "list" to see available commands, "add" to register a new command, "remove" to delete one'),name:r.z.string().optional().describe('Command name (required for "run", "add", and "remove")'),args:r.z.string().optional().describe('Additional arguments appended to the base command (optional, for "run")'),grep:r.z.string().optional().describe('Filter output through grep (optional, for "run"). Pipes command output through grep -i with this pattern.'),command:r.z.string().optional().describe('Shell command to register (required for "add", e.g. "tsc --noEmit")'),description:r.z.string().optional().describe('What this command verifies (optional, for "add")'),timeout:r.z.number().optional().describe('Timeout in seconds (optional, for "add", default 60)')}),exports.ReportTestResultsSchema=r.z.object({status:r.z.enum(["passed","failed","error"]).describe("Overall result"),results:r.z.object({commands:r.z.array(r.z.object({name:r.z.string().describe("Command name"),status:r.z.enum(["passed","failed","skipped","error"]).describe("Command result"),output:r.z.string().optional().describe("Relevant output snippet"),diagnosis:r.z.string().optional().describe("Why it failed, if applicable")})).describe("Per-command results"),summary:r.z.string().describe("Brief overall summary"),acceptanceCriteria:r.z.array(r.z.object({criterion:r.z.string().describe("The acceptance criterion text"),status:r.z.enum(["verified","unverified","unclear"]),evidence:r.z.string().describe("How verified, or why not")})).optional().describe("AC verification results, if applicable")}).describe("Structured test results")}),exports.SessionMessageOperationsSchema=r.z.object({operation:r.z.enum(["send","reply","list","get","offer-handoff"]),type:r.z.enum(["question","report"]).optional().describe("Message type to send (required for send)"),toSessionId:r.z.string().optional().describe('Target session ID, or "parent" to auto-resolve to parent session (omit for broadcast questions)'),questionType:r.z.enum(["free-form","alternatives"]).optional().describe('Type of question (required for send type="question")'),questionContent:r.z.object({question:r.z.string().min(1).describe("The question text"),context:r.z.string().optional().describe("Additional context"),options:r.z.array(r.z.object({id:r.z.string(),label:r.z.string(),description:r.z.string().optional()})).optional().describe("Options for alternatives questions"),allowMultiple:r.z.boolean().optional().describe("Allow selecting multiple options")}).optional().describe('Question content (required for send type="question")'),priority:r.z.enum(["low","normal","high"]).optional().describe("Question priority"),expiresInHours:r.z.number().optional().describe("Question expiry in hours"),status:r.z.enum(["success","partial","failure","blocked"]).optional().describe('Report status (required for send type="report")'),summary:r.z.string().optional().describe('Report summary (required for send type="report")'),details:r.z.string().optional().describe("Report details"),finish:r.z.boolean().optional().describe("Release request associations after report"),messageCode:r.z.string().optional().describe("Message code (required for reply and get operations)"),respondedBySessionId:r.z.string().optional().describe("Session ID answering the question"),text:r.z.string().optional().describe("Text answer for free-form questions"),selectedOptions:r.z.array(r.z.string()).optional().describe("Selected option IDs for alternatives"),notes:r.z.string().optional().describe("Additional notes"),list:r.z.object({sessionId:r.z.string().optional().describe("Filter by session ID (auto-discovered if omitted)"),messageType:r.z.enum(["question","report","all"]).default("all").describe("Filter by message type"),direction:r.z.enum(["incoming","outgoing","all"]).default("all"),status:r.z.enum(["pending","answered","expired","success","partial","failure","blocked","all"]).default("all").describe("Filter by status"),readStatus:r.z.enum(["unread","read","acknowledged","all"]).default("all").describe("Filter by read status (reports only)"),limit:r.z.number().min(1).max(100).default(50),offset:r.z.number().min(0).default(0)}).optional().describe('List filters (operation: "list" only)'),offerHandoff:r.z.object({summary:r.z.string().describe("Summary of what was planned/created"),requestIds:r.z.array(r.z.string()).describe("Request IDs that were created from the plan")}).optional().describe('Handoff offer details (operation: "offer-handoff" only)')}).refine((e=>"send"===e.operation?!!e.type:"reply"===e.operation?!!e.messageCode:"list"===e.operation||("get"===e.operation?!!e.messageCode:"offer-handoff"===e.operation)),{message:"Invalid operation data: send requires type, reply requires messageCode, get requires messageCode"}),exports.UpdateSpecializationSchema=r.z.object({specialization:r.z.string().min(1).max(500).describe("Your updated specialization summary \u2014 a concise description of your accumulated domain expertise")}),exports.CommitToViewedSessionSchema=r.z.object({message:r.z.coerce.string().min(1).describe("The cleaned-up user message to post to the viewed session. Fix obvious dictation errors, add punctuation, but preserve the user's intent exactly.")})},6252(e,exports,t){"use strict"
|
|
3560
3585
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3561
3586
|
const r=t(6183),n=t(405)
|
|
3562
3587
|
exports.def={name:"plan_write",description:"Modify project plans.\n\nOperations:\n\u2022 update - Update plan content\n\u2022 append - Append content to an existing plan\n\u2022 replace - Find and replace text within a plan\n\u2022 create-snapshot - Create a version snapshot\n\u2022 restore - Restore to a previous version",schema:r.PlanWriteSchema,annotations:{title:"Plan Write",readOnlyHint:!1,destructiveHint:!1},handler(e,t){return(0,n.handlePlanWrite)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},6261(module){"use strict"
|
|
@@ -3600,8 +3625,7 @@ if(c("session fetch status="+t.status),t.ok){const e=(await t.json()).filter((e=
|
|
|
3600
3625
|
c(`siblings=${e.length}: ${e.join(", ")}`)
|
|
3601
3626
|
const r=(0,d.pickSpecialistName)(e)
|
|
3602
3627
|
i=r,c("picked name: "+r)}}else c("no serverUrl")}catch(e){c("error: "+(e instanceof Error?e.message:e+""))}else c("no parentId")
|
|
3603
|
-
|
|
3604
|
-
k=await(0,u.handleSpawn)({agent:"specialist",prompt:y,title:i,specialization:n.specialization},r,f,s,p)
|
|
3628
|
+
k=await(0,u.handleSpawn)({agent:"specialist",prompt:n.prompt,title:i,specialization:n.specialization},r,f,s,p)
|
|
3605
3629
|
break}case"follow-up":{const e=await(0,h.getServerUrl)(r,f)
|
|
3606
3630
|
if(e)try{const t=await fetch(e.replace(/\/$/,"")+"/session/status")
|
|
3607
3631
|
if(t.ok){const e=await t.json(),r=e[w]?.type
|
|
@@ -3698,7 +3722,7 @@ var t={}
|
|
|
3698
3722
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
3699
3723
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3700
3724
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleInsertLines=async function(e,n,o,s,i,a,m,y){const w=a.child({tool:"insert_lines"}),k=Date.now()
|
|
3701
|
-
let b,
|
|
3725
|
+
let I,b,v=d.FileOperationPhase.VALIDATION
|
|
3702
3726
|
const C={toolName:"insert-lines",operationName:"insert-lines",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"insert-lines",metricsPrefix:"insert_lines",successMessage:"Successfully inserted lines into files and documents",failureMessage:"Failed to insert lines into files and documents"}
|
|
3703
3727
|
try{const _=d.validateArgs(e,l.InsertLinesSchema),{operations:E,comment:q}=_,{resolveActiveTaskId:S}=await Promise.resolve().then(t.bind(t,3451)),T=e.taskId||await S(n,o,a)||"untracked"
|
|
3704
3728
|
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")
|
|
@@ -3724,7 +3748,7 @@ for(let e=0;e<R.length;e++){const t=R[e],r=P[e],{normalizedPath:o,fullPath:s}=d.
|
|
|
3724
3748
|
R[e]={...t,path:o,fullPath:s}}}if(x.length>0&&D)try{await(0,h.validateRequestStatusForDocumentOperation)(D,i,w,m,"insert-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3725
3749
|
throw e}v=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("insert_lines_phase",1,{phase:v})
|
|
3726
3750
|
const N=[...R.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...x.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:L}=await d.createFileOperationRecords(T,D,n.projectId,C.recordType,M,{operationCount:E.length,fileOperations:R.length,documentOperations:x.length,operations:N,userComment:q},o,s,w,m,C.metricsPrefix,y)
|
|
3727
|
-
if(
|
|
3751
|
+
if(I=L,b=L,v=C.fileOperationPhase,m.incrementCounter("insert_lines_phase",1,{phase:v}),R.length>0&&n.git)try{w.debug("[INSERT-LINES] Checking for user changes before insert operations")
|
|
3728
3752
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"insert-lines",{requestId:D,taskId:T,workspaceManager:n.workspaceManager},w,m)
|
|
3729
3753
|
e.userChangesCommitted&&(w.debug("[INSERT-LINES] User changes committed before insert operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before insert-lines operation",{taskId:T,fileOperationsCount:R.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[INSERT-LINES] Pre-tool commit failed, continuing with insertions",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with insert operation",{taskId:T,fileOperationsCount:R.length,error:e instanceof Error?e.message:e+""})}w.debug("[INSERT-LINES] Proceeding with file operations",{fileCount:R.length})
|
|
3730
3754
|
const z=[]
|
|
@@ -3737,8 +3761,8 @@ try{const o=await n.documentFileManager.getDocumentAsFile(e.documentId),s=n.docu
|
|
|
3737
3761
|
t.filename=s?.filename
|
|
3738
3762
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.insertions)
|
|
3739
3763
|
t.insertions=l,t.successfulInsertions=l.filter((e=>e.success)).length,t.failedInsertions=l.filter((e=>!e.success)).length,t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulInsertions>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,U++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedInsertions=e.insertions.length,H+=t.failedInsertions,w.error("Document operation failed",{documentId:e.documentId,error:t.error})}z.push(t)}if(x.length>0)try{for(const e of x){const t=z.find((t=>t.documentId===e.documentId))
|
|
3740
|
-
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const G=await d.handleMultiFileGitCommit(T,R,z,U,{operationType:"Insert lines",toolRecordId:
|
|
3741
|
-
try{await s.updateToolRecord(
|
|
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:b,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
|
|
3765
|
+
try{await s.updateToolRecord(b,{metadata:{path:R.length>0?R[0].path:"document:"+x[0]?.documentId,status:Y?"completed":"failed",error:Y?void 0:J+" operations failed",totalOperations:z.length,successfulFiles:Q,failedFiles:Z,operations:N,totalSuccessfulInsertions:K,totalFailedInsertions:H,totalLinesAdded:B,operationsWithChanges:U,processingTime:Date.now()-k,userComment:q,...R.length>0&&G.success&&G.commitHash&&{commitHash:G.commitHash,previousCommitHash:G.previousCommitHash||void 0}},note:Y?`Line insertion completed: ${V}/${z.length} operations successful${R.length>0?" (committed to git)":""}`:`Line insertion partially failed: ${J}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let X="## Line Insertion Results\n\n"
|
|
3742
3766
|
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
3743
3767
|
e.permanentBranch||(X+=`**Branch:** \`${e.branchName}\`\n\n`)}if(X+="**Summary:**\n",X+=`- **Files processed:** ${V+J}\n`,X+=`- **Successful operations:** ${V}\n`,X+=`- **Failed operations:** ${J}\n`,X+=`- **Total insertions:** ${K} successful, ${H} failed\n`,X+=`- **Total Lines Added:** ${B}\n`,X+="\n",G.success&&G.commitHash&&(X+="**Git Commit:**\n",X+=`- **Commit Hash:** ${G.commitHash.substring(0,8)}\n`,X+=`- **Files Committed:** ${G.filesCommitted.length}\n`,G.previousCommitHash&&(X+=`- **Previous Commit:** ${G.previousCommitHash.substring(0,8)}\n`),X+="\n"),F.lockAcquired&&F.lockedRequestId&&(n.workspaceManager?.getCurrentContext(n.currentSessionId)?.permanentBranch||(X+=`\u{1f512} **Locked request:** ${F.lockedRequestId}\n\n`)),1===z.length){const e=z[0]
|
|
3744
3768
|
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"
|
|
@@ -3749,33 +3773,33 @@ for(const t of e.insertions.filter((e=>!e.success))){const e="between"===t.type?
|
|
|
3749
3773
|
X+=` - ${t.type} insertion ${e}: ${t.error}\n`}}X+="\n"}}x.length>0&&(X+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3750
3774
|
const ee=Date.now()-k
|
|
3751
3775
|
return w.info("Insert lines operation completed",{duration:ee,success:Y,totalOperations:z.length,successfulOperations:V,failedOperations:J}),m.incrementCounter("insert_lines_total",1,{success:Y}),{content:[{type:"text",text:X}],isError:!Y}}catch(t){const r=Date.now()-k
|
|
3752
|
-
if(w.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),
|
|
3776
|
+
if(w.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),b)try{await s.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,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}}}
|
|
3753
3777
|
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"
|
|
3754
3778
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientFactory=void 0
|
|
3755
3779
|
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)
|
|
3756
3780
|
exports.ClientFactory=class{static async createClient(e,m,y,w={}){(m=m.child({component:"client-factory"})).info("Creating API client with components")
|
|
3757
3781
|
const k=w.tokenManager||new r.TokenManager(m,w.workingDir||process.cwd())
|
|
3758
3782
|
await k.initialize()
|
|
3759
|
-
const
|
|
3760
|
-
|
|
3783
|
+
const I=w.tokenSynchronizer||new i.ClientTokenSynchronizer(m),b=new s.AuthenticationManager(k,m,I),v=await b.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})
|
|
3784
|
+
I.registerClient(_),w.alchemyPath&&_.setAlchemyPath(w.alchemyPath)
|
|
3761
3785
|
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})
|
|
3762
|
-
|
|
3786
|
+
I.registerClient(E)
|
|
3763
3787
|
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})
|
|
3764
|
-
|
|
3788
|
+
I.registerClient(q),m.info("RequestClient constructor received token: "+(v?"present":"missing"))
|
|
3765
3789
|
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})
|
|
3766
|
-
|
|
3790
|
+
I.registerClient(S),m.info("RequestClient post-constructor token: "+(S.getAuthToken()?"present":"missing"))
|
|
3767
3791
|
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})
|
|
3768
|
-
|
|
3792
|
+
I.registerClient(T)
|
|
3769
3793
|
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})
|
|
3770
|
-
|
|
3794
|
+
I.registerClient(P)
|
|
3771
3795
|
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})
|
|
3772
|
-
if(
|
|
3796
|
+
if(I.registerClient(j),!w.alchemyPath)throw Error("alchemyPath is required for ProjectSynchronizer creation. Cannot create API client without project synchronization capabilities.")
|
|
3773
3797
|
try{m.info("Creating ProjectSynchronizer components")
|
|
3774
3798
|
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})
|
|
3775
3799
|
_.setProjectSynchronizer(n),m.info("ProjectSynchronizer created and connected to ProjectClient")}catch(e){const t="Failed to create required ProjectSynchronizer components: "+(0,h.getErrorMessage)(e)
|
|
3776
|
-
throw m.error(t,{error:e instanceof Error?e.stack:e+""}),Error(t)}const R=new o.ApiClient(
|
|
3800
|
+
throw m.error(t,{error:e instanceof Error?e.stack:e+""}),Error(t)}const R=new o.ApiClient(b,_,E,q,S,T,P,j,m)
|
|
3777
3801
|
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"})
|
|
3778
|
-
const x=
|
|
3802
|
+
const x=I.verifyAllClients()
|
|
3779
3803
|
x.success?m.info("Token consistency verified across all clients"):m.error(`Token inconsistency detected in ${x.failedClients.length} clients: ${x.failedClients.join(", ")}`)
|
|
3780
3804
|
const M=R.getAuthToken()
|
|
3781
3805
|
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"
|
|
@@ -3789,10 +3813,10 @@ Object.defineProperty(exports,"__esModule",{value:!0})
|
|
|
3789
3813
|
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)
|
|
3790
3814
|
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")
|
|
3791
3815
|
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)}))
|
|
3792
|
-
const
|
|
3793
|
-
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?
|
|
3816
|
+
const I=process.stdout.write
|
|
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?I.call(process.stdout,e,t,r):"function"==typeof t?I.call(process.stdout,e,void 0,t):I.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}))
|
|
3794
3818
|
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")
|
|
3795
|
-
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
|
|
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 b=(0,c.createMetricsCollector)(!1)
|
|
3796
3820
|
let v=process.env.REMOTE_SERVER_URL||"https://api.alchemylabcode.com"
|
|
3797
3821
|
const C=global.__serverInitialized
|
|
3798
3822
|
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)
|
|
@@ -3807,7 +3831,7 @@ try{const{createConfigManager:e}=await Promise.resolve().then(t.t.bind(t,9060,23
|
|
|
3807
3831
|
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"}()
|
|
3808
3832
|
try{const e=await(0,p.syncPlugins)(w,(0,f.isDevBuild)(),k)
|
|
3809
3833
|
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))
|
|
3810
|
-
const e=await(0,i.createServer)(w,k,
|
|
3834
|
+
const e=await(0,i.createServer)(w,k,b,v)
|
|
3811
3835
|
_=e,global.__serverInitialized=!0,(0,a.isDebugToolsEnabled)()&&k.info("MCP server created successfully")
|
|
3812
3836
|
const n=r()
|
|
3813
3837
|
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+""
|
|
@@ -3850,8 +3874,8 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3850
3874
|
var t={}
|
|
3851
3875
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
3852
3876
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3853
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceLines=async function(e,n,o,s,i,a,m,w){const k=a.child({tool:"replace_lines"}),
|
|
3854
|
-
let
|
|
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"}),I=Date.now()
|
|
3878
|
+
let b,v,C=d.FileOperationPhase.VALIDATION
|
|
3855
3879
|
const _={toolName:"replace-lines",operationName:"replace-lines",fileOperationPhase:d.FileOperationPhase.STRING_REPLACEMENT,recordType:"replace-lines",metricsPrefix:"replace_lines",successMessage:"Successfully replaced lines in files and documents",failureMessage:"Failed to replace lines in files and documents"}
|
|
3856
3880
|
try{const E=d.validateArgs(e,l.ReplaceLinesSchema),{operations:q,comment:S}=E,{resolveActiveTaskId:T}=await Promise.resolve().then(t.bind(t,3451)),P=e.taskId||await T(n,o,a)||"untracked"
|
|
3857
3881
|
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")
|
|
@@ -3877,7 +3901,7 @@ for(let e=0;e<x.length;e++){const t=x[e],r=j[e],{normalizedPath:o,fullPath:s}=d.
|
|
|
3877
3901
|
x[e]={...t,path:o,fullPath:s}}}if(M.length>0&&$)try{await(0,h.validateRequestStatusForDocumentOperation)($,i,k,m,"replace-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3878
3902
|
throw e}C=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("replace_lines_phase",1,{phase:C})
|
|
3879
3903
|
const L=[...x.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:z}=await d.createFileOperationRecords(P,$,n.projectId,_.recordType,O,{operationCount:q.length,fileOperations:x.length,documentOperations:M.length,operations:L,userComment:S},o,s,k,m,_.metricsPrefix,w)
|
|
3880
|
-
if(
|
|
3904
|
+
if(b=z,v=z,C=_.fileOperationPhase,m.incrementCounter("replace_lines_phase",1,{phase:C}),x.length>0&&n.git)try{k.debug("[REPLACE-LINES] Checking for user changes before replace operations")
|
|
3881
3905
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"replace-lines",{requestId:$,taskId:P,workspaceManager:n.workspaceManager},k,m)
|
|
3882
3906
|
e.userChangesCommitted&&(k.debug("[REPLACE-LINES] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),k.info("User changes committed before replace-lines operation",{taskId:P,fileOperationsCount:x.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){k.debug("[REPLACE-LINES] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),k.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:P,fileOperationsCount:x.length,error:e instanceof Error?e.message:e+""})}k.debug("[REPLACE-LINES] Proceeding with file operations",{fileCount:x.length})
|
|
3883
3907
|
const H=[]
|
|
@@ -3891,20 +3915,20 @@ t.filename=s?.filename
|
|
|
3891
3915
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.replacements)
|
|
3892
3916
|
t.replacements=l,t.successfulReplacements=l.filter((e=>e.success)).length,t.failedReplacements=l.filter((e=>!e.success)).length,t.totalLinesReplaced=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulReplacements>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,W++,k.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedReplacements=e.replacements.length,B+=t.failedReplacements,k.error("Document operation failed",{documentId:e.documentId,error:t.error})}H.push(t)}if(M.length>0)try{for(const e of M){const t=H.find((t=>t.documentId===e.documentId))
|
|
3893
3917
|
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){k.warn("Some documents may not have synced properly",{error:e})}const V=await d.handleMultiFileGitCommit(P,x,H,W,{operationType:"Replace lines",toolRecordId:v,successField:"successfulReplacements",logger:k,metrics:m,metricsPrefix:"replace_lines"},n),J=d.processMultiFileOperationResults(H,"successfulReplacements"),{successfulOperations:K,failedOperations:Y,totalSuccessfulChanges:Q,overallSuccess:Z,successfulFiles:X,failedFiles:ee}=J
|
|
3894
|
-
try{await s.updateToolRecord(v,{metadata:{path:x.length>0?x[0].path:"document:"+M[0]?.documentId,status:Z?"completed":"failed",error:Z?void 0:Y+" operations failed",totalOperations:H.length,successfulFiles:X,failedFiles:ee,operations:L,totalSuccessfulReplacements:Q,totalFailedReplacements:B,totalLinesReplaced:U,totalLinesAdded:G,operationsWithChanges:W,processingTime:Date.now()-
|
|
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()-I,userComment:S,...x.length>0&&V.success&&V.commitHash&&{commitHash:V.commitHash,previousCommitHash:V.previousCommitHash||void 0}},note:Z?`Line replacement completed: ${K}/${H.length} operations successful${x.length>0?" (committed to git)":""}`:`Line replacement partially failed: ${Y}/${H.length} operations failed`})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let te="## Line Replacement Results\n\n"
|
|
3895
3919
|
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
3896
3920
|
e.permanentBranch||(te+=`**Branch:** \`${e.branchName}\`\n\n`)}if(te+="**Summary:**\n",te+=`- **Files processed:** ${K+Y}\n`,te+=`- **Successful operations:** ${K}\n`,te+=`- **Failed operations:** ${Y}\n`,te+=`- **Total replacements:** ${Q} successful, ${B} failed\n`,te+=`- **Total Lines Replaced:** ${U}\n`,G>0&&(te+=`- **Total Lines Added:** ${G}\n`),te+="\n",V.success&&V.commitHash&&(te+="**Git Commit:**\n",te+=`- **Commit Hash:** ${V.commitHash.substring(0,8)}\n`,te+=`- **Files Committed:** ${V.filesCommitted.length}\n`,V.previousCommitHash&&(te+=`- **Previous Commit:** ${V.previousCommitHash.substring(0,8)}\n`),te+="\n"),N.lockAcquired&&N.lockedRequestId&&(n.workspaceManager?.getCurrentContext(n.currentSessionId)?.permanentBranch||(te+=`\u{1f512} **Locked request:** ${N.lockedRequestId}\n\n`)),1===H.length){const e=H[0]
|
|
3897
3921
|
if(te+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?te+=`**File:** ${e.path}\n`:(te+="**Document:** "+e.documentId,e.filename&&(te+=` (${e.filename})`),te+="\n"),e.error?te+=`**Error:** ${e.error}\n`:(te+=`**Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(te+=`, ${e.failedReplacements} failed`),te+="\n",te+=`**Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(te+=`**Lines Added:** ${e.totalLinesAdded}\n`)),e.replacements.some((e=>!e.success))){te+="**Failed Replacement Details:**\n"
|
|
3898
3922
|
for(const t of e.replacements.filter((e=>!e.success)))te+=`- Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}}else{te+="**Summary:**\n",te+=`- **Total Operations:** ${H.length}\n`,te+=`- **Successful:** ${K}\n`,te+=`- **Failed:** ${Y}\n`,te+=`- **Total Replacements:** ${Q} successful, ${B} failed\n`,te+=`- **Total Lines Replaced:** ${U}\n`,G>0&&(te+=`- **Total Lines Added:** ${G}\n`),te+="\n",te+="**Detailed Results:**\n\n"
|
|
3899
3923
|
for(const e of H){if("file"===e.type?te+=`### File: ${e.path}\n`:(te+="### Document: "+e.documentId,e.filename&&(te+=` (${e.filename})`),te+="\n"),te+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error&&(te+=`- **Error:** ${e.error}\n`),te+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(te+=`, ${e.failedReplacements} failed`),te+="\n",te+=`- **Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(te+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.replacements.some((e=>!e.success))){te+="- **Failed Replacement Details:**\n"
|
|
3900
3924
|
for(const t of e.replacements.filter((e=>!e.success)))te+=` - Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}te+="\n"}}M.length>0&&(te+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3901
|
-
const re=Date.now()-
|
|
3902
|
-
return k.info("Replace lines operation completed",{duration:re,success:Z,totalOperations:H.length,successfulOperations:K,failedOperations:Y}),m.incrementCounter("replace_lines_total",1,{success:Z}),{content:[{type:"text",text:te}],isError:!Z}}catch(t){const r=Date.now()-
|
|
3925
|
+
const re=Date.now()-I
|
|
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()-I
|
|
3903
3927
|
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}}}
|
|
3904
3928
|
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"
|
|
3905
3929
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.sessionIdentity=void 0
|
|
3906
3930
|
const r=t(9896),n=t(6928)
|
|
3907
|
-
exports.sessionIdentity=new class{constructor(){this.parentCache=new Map}setIdentity(e){const t=this.identity
|
|
3931
|
+
exports.sessionIdentity=new class{constructor(){this.parentCache=new Map,this.sessionRequestCache=new Map}setIdentity(e){const t=this.identity
|
|
3908
3932
|
this.identity=e,this.log("setIdentity",{sessionId:e.sessionId,serverUrl:e.serverUrl,agentType:e.agentType||null,prevSessionId:t?.sessionId||null,changed:t?.sessionId!==e.sessionId})}getIdentity(){return this.identity}updateIdentity(e){if(this.identity){const t={...this.identity}
|
|
3909
3933
|
this.identity={...this.identity,...e},this.log("updateIdentity",{sessionId:this.identity.sessionId,updates:Object.keys(e),agentTypeBefore:t.agentType||null,agentTypeAfter:this.identity.agentType||null})}}async getParentSessionId(e,t,r){if(this.parentCache.has(e)){const t=this.parentCache.get(e)
|
|
3910
3934
|
return this.log("getParentSessionId.cache-hit",{childExternalId:e,parentExternalId:t}),t}try{const n=t.getCLISessionClient()
|
|
@@ -3913,12 +3937,14 @@ const o=await n.getParent(e),s=o?.externalSessionId||null
|
|
|
3913
3937
|
return this.parentCache.set(e,s),this.log("getParentSessionId.resolved",{childExternalId:e,parentExternalId:s}),s||r.warn("Parent session not found",{sessionId:e}),s}catch(t){const n=t instanceof Error?t.message:t+""
|
|
3914
3938
|
return r.warn("Error getting parent session",{sessionId:e,error:n}),null}}setParentSessionId(e,t){this.parentCache.set(e,t)}async getSessionRequestId(e,t,r){const n=r||this.identity?.sessionId
|
|
3915
3939
|
if(!n)return t.warn("Cannot get session request: no session identity"),null
|
|
3940
|
+
const o=this.sessionRequestCache.get(n)
|
|
3941
|
+
if(o)return this.log("getSessionRequestId.cache-hit",{sessionId:n,requestId:o}),o
|
|
3916
3942
|
try{const r=e.getSessionRequestAssociationClient?.()
|
|
3917
3943
|
if(!r)return t.warn("Session request association client not available"),null
|
|
3918
3944
|
const o=await r.getActiveRequestsForSession(n)
|
|
3919
3945
|
if(o?.length>0){const e=o[0].requestLocalId||o[0].request_local_id
|
|
3920
|
-
return this.log("getSessionRequestId.resolved",{sessionId:n,requestId:e}),e||null}return this.log("getSessionRequestId.none",{sessionId:n}),null}catch(e){const r=e instanceof Error?e.message:e+""
|
|
3921
|
-
return t.warn("Error getting session request",{sessionId:n,error:r}),null}}buildCliOrigin(e){if(this.identity)return{providerId:this.identity.providerId,sessionId:this.identity.sessionId,messageId:e,createdAt:(new Date).toISOString()}}setCurrentCallOrigin(e){this.currentCallOrigin=e}getCurrentCallOrigin(){return this.currentCallOrigin||this.buildCliOrigin()}log(e,t){try{const o=process.env.ALCHEMY_PROJECT_PATH||process.cwd(),s=(0,n.join)(o,".alchemy_lab");(0,r.existsSync)(s)||(0,r.mkdirSync)(s,{recursive:!0})
|
|
3946
|
+
return e&&this.sessionRequestCache.set(n,e),this.log("getSessionRequestId.resolved",{sessionId:n,requestId:e}),e||null}return this.log("getSessionRequestId.none",{sessionId:n}),null}catch(e){const r=e instanceof Error?e.message:e+""
|
|
3947
|
+
return t.warn("Error getting session request",{sessionId:n,error:r}),null}}clearSessionRequestCache(e){e?this.sessionRequestCache.delete(e):this.sessionRequestCache.clear()}buildCliOrigin(e){if(this.identity)return{providerId:this.identity.providerId,sessionId:this.identity.sessionId,messageId:e,createdAt:(new Date).toISOString()}}setCurrentCallOrigin(e){this.currentCallOrigin=e}getCurrentCallOrigin(){return this.currentCallOrigin||this.buildCliOrigin()}log(e,t){try{const o=process.env.ALCHEMY_PROJECT_PATH||process.cwd(),s=(0,n.join)(o,".alchemy_lab");(0,r.existsSync)(s)||(0,r.mkdirSync)(s,{recursive:!0})
|
|
3922
3948
|
const i=(0,n.join)(s,"mcp-identity-debug.log"),a=(new Date).toISOString(),c=process.pid,l=t?" "+JSON.stringify(t):"";(0,r.appendFileSync)(i,`[${a}] [PID:${c}] identity.${e}${l}\n`)}catch{}}},exports.sessionIdentity.log("module-load",{ALCHEMY_SESSION_TAG:process.env.ALCHEMY_SESSION_TAG||null,ALCHEMY_INITIAL_BRANCH:process.env.ALCHEMY_INITIAL_BRANCH||null,ALCHEMY_ALLOW_PARALLEL:process.env.ALCHEMY_ALLOW_PARALLEL||null})},6756(e,exports){"use strict"
|
|
3923
3949
|
var t,r
|
|
3924
3950
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.TaskStatus=exports.RequestStatus=void 0,function(e){e.OPEN="open",e.IN_PROGRESS="in_progress",e.COMPLETED="completed",e.CONFLICTED="conflicted",e.READY_FOR_REVIEW="ready_for_review",e.PENDING_APPROVAL="pending_approval"}(t||(exports.RequestStatus=t={})),function(e){e.PENDING="pending",e.IN_PROGRESS="in_progress",e.READY_FOR_REVIEW="ready_for_review",e.COMPLETED="completed"}(r||(exports.TaskStatus=r={}))},6770(e,exports,t){"use strict"
|
|
@@ -3988,13 +4014,13 @@ s.info("Raw task response data",{responseDataType:typeof P,isArray:Array.isArray
|
|
|
3988
4014
|
try{const R=await m.getToolRecordsByTaskId(g)
|
|
3989
4015
|
if(s.info("Raw records response data",{responseDataType:typeof R,isArray:Array.isArray(R),hasData:null!=R,properties:R&&"object"==typeof R?Object.keys(R):[]}),k=(0,l.extractArrayFromResponse)(R,{logger:s,operationName:"searchRecords",defaultValue:[]}),k.length>0&&s.info("First record summary:",{id:k[0].id,type:k[0].type,hasMetadata:!!k[0].metadata,hasCommitHash:!!k[0].metadata?.commitHash}),s.info(`Extracted ${k.length} records for task ${g}`),k.length>0){const x={}
|
|
3990
4016
|
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}.`}]}
|
|
3991
|
-
function
|
|
4017
|
+
function I(e){const t=new Map,r=new Map,n=[]
|
|
3992
4018
|
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
|
|
3993
4019
|
if(e&&s){const i={source:e,destination:s,recordId:o.id,timestamp:o.createdAt,type:"move-file"}
|
|
3994
4020
|
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||[]]
|
|
3995
4021
|
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"}
|
|
3996
|
-
t.set(s.source,e),r.set(s.destination,e),n.push(e)}}return{sourceToMove:t,destToMove:r,allMoves:n}}const I
|
|
3997
|
-
s.info(`Detected ${
|
|
4022
|
+
t.set(s.source,e),r.set(s.destination,e),n.push(e)}}return{sourceToMove:t,destToMove:r,allMoves:n}}const b=I(k)
|
|
4023
|
+
s.info(`Detected ${b.allMoves.length} move operations`)
|
|
3998
4024
|
const v=k.filter((e=>{if(!e||"object"!=typeof e)return s.warn("Skipping invalid record (not an object)"),!1
|
|
3999
4025
|
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
|
|
4000
4026
|
if(!e.metadata)return s.warn("Skipping record without metadata: "+e.id),!1
|
|
@@ -4070,7 +4096,7 @@ continue}let pe
|
|
|
4070
4096
|
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")
|
|
4071
4097
|
try{const me=await t.git.show([`${G.commitHash}:${A}`]),ye=await t.git.show([`${H.commitHash}:${A}`])
|
|
4072
4098
|
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")
|
|
4073
|
-
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(
|
|
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(Ie){s.warn("Error in direct file comparison: "+(Ie instanceof Error?Ie.message:Ie+""))}}s.info(`Diff generation result for ${A}: hasDiff=${V}, length=${W.length}`)}}catch(be){if(s.warn("Error getting diff for "+A,{error:(0,u.getErrorMessage)(be),firstCommit:z.commitHash||"unknown",lastCommit:H.commitHash||"unknown"}),W="Error getting diff: "+(0,u.getErrorMessage)(be),"pre-task"!==z.status&&t.git)try{const ve=[`${H.commitHash}:${A}`]
|
|
4074
4100
|
s.info(`Trying fallback to show file content using git show: ${H.commitHash?H.commitHash.substring(0,8):"unknown"}:${A}`)
|
|
4075
4101
|
const Ce=await t.git.show(ve)
|
|
4076
4102
|
if(Ce&&Ce.trim().length>0){if(p){let _e=""
|
|
@@ -4082,14 +4108,14 @@ w&&"object"==typeof w&&(E+="## Task Information\n",E+=`- **Title**: ${w.title||"
|
|
|
4082
4108
|
const q=3e3
|
|
4083
4109
|
let S=0,T=!1
|
|
4084
4110
|
if(p){for(const Te of _.values())Te.hasDiff&&Te.diffText&&(S+=Te.diffText.split("\n").length)
|
|
4085
|
-
T=S>q,s.info(`Total diff size: ${S} lines (limit: ${q} lines)`),s.info(`Diffs ${T?"will be limited":"will be shown"} based on size`)}if(E+="## Summary\n",E+=`- **Files Modified**: ${C.size}\n`,E+=`- **Total File Operations**: ${v.length}\n`,E+="- **What's Shown**: For existing files, comparing state before task started with final state.\n",E+=" For files created during task, showing the entire file as created.\n",T?(E+=`- **Diff Display**: Limited (total diff size of ${S} lines exceeds limit of ${q} lines)\n`,E+=" Use file-history tool with individual files to see detailed changes\n\n"):E+=`- **Diff Display**: ${p?"Enabled":"Disabled"} (use showDiff=${!p} to ${p?"hide":"show"} diffs)\n\n`,
|
|
4086
|
-
for(const Pe of
|
|
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`,b.allMoves.length>0){E+="## Move Operations\n\n",E+=`Detected ${b.allMoves.length} file move operation(s):\n\n`
|
|
4112
|
+
for(const Pe of b.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"
|
|
4087
4113
|
for(const[je,Re]of _.entries()){const{normalizedPath:xe,fullPath:Me}=d.validateAndNormalizePath(je,t)
|
|
4088
4114
|
let Oe=!1
|
|
4089
4115
|
try{await a.access(Me),Oe=!0}catch{}E+=`### ${je} ${Oe?"":"(Deleted)"}\n\n`
|
|
4090
4116
|
const De=new Date(Re.firstChange.timestamp).toLocaleString(),$e=new Date(Re.lastChange.timestamp).toLocaleString()
|
|
4091
4117
|
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`)
|
|
4092
|
-
const Ae=
|
|
4118
|
+
const Ae=b.sourceToMove.get(je),Fe=b.destToMove.get(je)
|
|
4093
4119
|
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}}}
|
|
4094
4120
|
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"
|
|
4095
4121
|
module.exports=require("path")},6975(e,exports,t){"use strict"
|
|
@@ -4244,11 +4270,11 @@ r&&(y=(0,a.getApprovalMode)(r))}catch(e){g.warn("Failed to read project metadata
|
|
|
4244
4270
|
let k=h
|
|
4245
4271
|
if(h?.sessionId)try{const e=c.getCLISessionClient()
|
|
4246
4272
|
if(e){const t=await e.getByExternalId(h.sessionId)
|
|
4247
|
-
"planner"!==t?.agentType&&"auto-planner"!==t?.agentType||(k=void 0,g.info("Skipping cliOrigin for planner-created request",{agentType:t.agentType}))}}catch{}const
|
|
4273
|
+
"planner"!==t?.agentType&&"auto-planner"!==t?.agentType||(k=void 0,g.info("Skipping cliOrigin for planner-created request",{agentType:t.agentType}))}}catch{}const I={title:l.title,description:l.description,type:l.type,acceptanceCriteria:l.acceptanceCriteria,status:w,...l.planDocumentId&&{planDocumentId:l.planDocumentId},...k&&{cliOrigin:k}}
|
|
4248
4274
|
g.info("Creating request via request client",{projectId:f,title:l.title,type:l.type,criteriaCount:l.acceptanceCriteria.length})
|
|
4249
|
-
const
|
|
4250
|
-
g.debug("Create request response structure",{type:typeof
|
|
4251
|
-
const v=(0,o.extractDataFromResponse)(
|
|
4275
|
+
const b=await m.createRequest(I)
|
|
4276
|
+
g.debug("Create request response structure",{type:typeof b,isArray:Array.isArray(b),hasData:null!=b,properties:b?Object.keys(b):[],dataPreview:b?JSON.stringify(b).substring(0,200)+"...":"null"})
|
|
4277
|
+
const v=(0,o.extractDataFromResponse)(b,{logger:g,operationName:"createRequest",throwOnNoData:!0}),C="data"in v?v.data:v
|
|
4252
4278
|
let _,E={created:!1}
|
|
4253
4279
|
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})
|
|
4254
4280
|
g.info("Request created successfully",{requestId:C.id,title:C.title,branchCreated:E.created,branchName:E.branchName})
|
|
@@ -4279,21 +4305,21 @@ return o(t,e),t})
|
|
|
4279
4305
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,r,n,o,s,h,g,p){const f=h.child({tool:"modify_file"})
|
|
4280
4306
|
try{const u=a.validateArgs(e,i.ModifyFileSchema),{operations:m,comment:y}=u,{resolveActiveTaskId:w}=await Promise.resolve().then(t.bind(t,3451)),k=e.taskId||await w(r,n,h)||"untracked"
|
|
4281
4307
|
f.info("Processing modify-file operations",{taskId:k,operationCount:m.length,comment:y})
|
|
4282
|
-
const
|
|
4308
|
+
const I=[],b=[],v=[],C=[],_=[]
|
|
4283
4309
|
for(const e of m){const t={path:e.path,documentId:e.documentId}
|
|
4284
|
-
switch(e.operationType){case"replace-string":
|
|
4310
|
+
switch(e.operationType){case"replace-string":I.push({...t,replacements:e.replaceString.replacements,mode:e.replaceString.mode})
|
|
4285
4311
|
break
|
|
4286
|
-
case"insert-lines":
|
|
4312
|
+
case"insert-lines":b.push({...t,insertions:e.insertLines.insertions})
|
|
4287
4313
|
break
|
|
4288
4314
|
case"replace-lines":v.push({...t,replacements:e.replaceLines.replacements})
|
|
4289
4315
|
break
|
|
4290
4316
|
case"delete-string":C.push({...t,replacements:e.deleteString.patterns.map((e=>({old_str:e,new_str:""}))),mode:e.deleteString.mode||"all"})
|
|
4291
4317
|
break
|
|
4292
4318
|
case"delete-lines":_.push({...t,lines:e.deleteLines.lines})}}const E=[]
|
|
4293
|
-
if(
|
|
4294
|
-
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:
|
|
4295
|
-
E.push({type:"replace-string",result:e})}if(
|
|
4296
|
-
const e=await(0,l.handleInsertLines)({taskId:k,operations:
|
|
4319
|
+
if(I.length>0){f.info("Routing to replace-strings handler",{operationCount:I.length})
|
|
4320
|
+
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:I,comment:y+" [via modify-file: replace-string]"},r,n,o,s,f,g,p)
|
|
4321
|
+
E.push({type:"replace-string",result:e})}if(b.length>0){f.info("Routing to insert-lines handler",{operationCount:b.length})
|
|
4322
|
+
const e=await(0,l.handleInsertLines)({taskId:k,operations:b,comment:y+" [via modify-file: insert-lines]"},r,n,o,s,f,g,p)
|
|
4297
4323
|
E.push({type:"insert-lines",result:e})}if(v.length>0){f.info("Routing to replace-lines handler",{operationCount:v.length})
|
|
4298
4324
|
const e=await(0,d.handleReplaceLines)({taskId:k,operations:v,comment:y+" [via modify-file: replace-lines]"},r,n,o,s,f,g,p)
|
|
4299
4325
|
E.push({type:"replace-lines",result:e})}if(C.length>0){f.info("Routing delete-string to replace-strings handler",{operationCount:C.length})
|
|
@@ -4493,7 +4519,7 @@ return s.info("Plan updated",{planId:a}),{content:[{type:"text",text:`\u2705 **P
|
|
|
4493
4519
|
const r=t(8824)},7613(e,exports,t){"use strict"
|
|
4494
4520
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4495
4521
|
const r=t(6183),n=t(9072)
|
|
4496
|
-
exports.def={name:"session_message_operations",description:'Inter-session messaging (questions and reports).\n\nOperations:\n\u2022 send - Send a message (type: "question" or "report")\n\u2022 reply - Reply to a message (answer a question or acknowledge a report). Type inferred from code prefix (Q-/R-).\n\u2022 list - List messages (filter by messageType, direction, status)\n\u2022 get - Get a message by its code\n\u2022 offer-handoff - Present the user with a choice to start building or keep planning\n\nMessage codes: Q-{id}-{seq} for questions, R-{id}-{seq} for reports.',schema:r.SessionMessageOperationsSchema,annotations:{title:"Session Message Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSessionMessageOperations)(e,t.context,t.logger,t.metrics,t.apiClient??void 0)}}},7617(e,exports,t){"use strict"
|
|
4522
|
+
exports.def={name:"session_message_operations",description:'Inter-session messaging (questions and reports).\n\nOperations:\n\u2022 send - Send a message (type: "question" or "report")\n\u2022 reply - Reply to a message (answer a question or acknowledge a report). Type inferred from code prefix (Q-/R-).\n\u2022 list - List messages (filter by messageType, direction, status)\n\u2022 get - Get a message by its code\n\u2022 offer-handoff - Present the user with a choice to start building or keep planning\n\nMessage codes: Q-{id}-{seq} for questions, R-{id}-{seq} for reports.',schema:r.SessionMessageOperationsSchema,annotations:{title:"Session Message Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSessionMessageOperations)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},7617(e,exports,t){"use strict"
|
|
4497
4523
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.getServerUrl=async function(e,r){let n=process.env.OPENCODE_TUI_URL
|
|
4498
4524
|
if(!n)try{const{readFileSync:o}=await Promise.resolve().then(t.t.bind(t,9896,23)),{join:s}=await Promise.resolve().then(t.t.bind(t,6928,23)),i=o(s(e.basePath,".alchemy_lab","opencode.json"),"utf8"),a=JSON.parse(i)
|
|
4499
4525
|
a.port&&(n="http://127.0.0.1:"+a.port,r.debug("Discovered OpenCode server URL from .alchemy_lab/opencode.json",{serverUrl:n}))}catch(e){r.debug("Could not read .alchemy_lab/opencode.json",{error:e instanceof Error?e.message:e+""})}return n}},7621(e,exports,t){"use strict"
|
|
@@ -4691,8 +4717,8 @@ var t={}
|
|
|
4691
4717
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4692
4718
|
return o(t,e),t})
|
|
4693
4719
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,r,n,o,s,g,p,f,m){const y=p.child({tool:"manage_files"})
|
|
4694
|
-
try{const h=a.validateArgs(e,i.ManageFilesSchema),{operations:w,comment:k}=h,{resolveActiveTaskId:
|
|
4695
|
-
y.info("Processing manage-files operations",{taskId:
|
|
4720
|
+
try{const h=a.validateArgs(e,i.ManageFilesSchema),{operations:w,comment:k}=h,{resolveActiveTaskId:I}=await Promise.resolve().then(t.bind(t,3451)),b=e.taskId||await I(r,g,p)||"untracked"
|
|
4721
|
+
y.info("Processing manage-files operations",{taskId:b,operationCount:w.length,comment:k})
|
|
4696
4722
|
const v=[],C=[],_=[],E=[]
|
|
4697
4723
|
for(const e of w)switch(e.operationType){case"create-directory":v.push({path:e.createDirectory.path})
|
|
4698
4724
|
break
|
|
@@ -4702,11 +4728,11 @@ case"delete-files":_.push(...e.deleteFiles.targets)
|
|
|
4702
4728
|
break
|
|
4703
4729
|
case"get-file-info":E.push({path:e.getFileInfo.path})}const q=[]
|
|
4704
4730
|
for(const e of v){y.info("Routing to create-directory handler",{path:e.path})
|
|
4705
|
-
const t=await(0,c.handleCreateDirectory)({taskId:
|
|
4731
|
+
const t=await(0,c.handleCreateDirectory)({taskId:b,path:e.path,comment:k+" [via manage-files: create-directory]"},r,n,o,s,y,f,m)
|
|
4706
4732
|
q.push({type:"create-directory",result:t})}if(C.length>0){y.info("Routing to move-files handler",{operationCount:C.length})
|
|
4707
|
-
const e=await(0,l.handleMoveFiles)({taskId:
|
|
4733
|
+
const e=await(0,l.handleMoveFiles)({taskId:b,operations:C,comment:k+" [via manage-files: move-files]"},r,n,o,s,y,f,m)
|
|
4708
4734
|
q.push({type:"move-files",result:e})}if(_.length>0){y.info("Routing to delete-files handler",{operationCount:_.length})
|
|
4709
|
-
const e=await(0,u.handleDeleteFiles)({taskId:
|
|
4735
|
+
const e=await(0,u.handleDeleteFiles)({taskId:b,operations:_,comment:k+" [via manage-files: delete-files]"},r,g,y,f,m)
|
|
4710
4736
|
q.push({type:"delete-files",result:e})}for(const e of E){y.info("Routing to get-file-info handler",{path:e.path})
|
|
4711
4737
|
const t=await(0,d.handleGetFileInfo)({path:e.path},r,y,f)
|
|
4712
4738
|
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
|
|
@@ -4807,9 +4833,9 @@ const m=new Date,y=`${(m.getHours()+"").padStart(2,"0")}${(m.getMinutes()+"").pa
|
|
|
4807
4833
|
let k
|
|
4808
4834
|
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))
|
|
4809
4835
|
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})
|
|
4810
|
-
const
|
|
4836
|
+
const I=(0,i.join)(l||process.cwd(),".alchemy_lab"),b=(0,i.join)(I,"spawn-stderr.log")
|
|
4811
4837
|
let v
|
|
4812
|
-
try{v=(0,s.openSync)(
|
|
4838
|
+
try{v=(0,s.openSync)(b,"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})
|
|
4813
4839
|
return _.unref(),p&&p(_.pid),{success:!0,pid:_.pid}}catch(e){return{success:!1,error:(0,o.getErrorMessage)(e)}}}
|
|
4814
4840
|
const n=t(5317),o=t(8824),s=t(9896),i=t(6928),a=t(9068)},8037(e,exports,t){"use strict"
|
|
4815
4841
|
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")
|
|
@@ -4889,32 +4915,32 @@ var t={}
|
|
|
4889
4915
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4890
4916
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
4891
4917
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,r,n,o,s,i,p,f){const m=i.child({tool:"create_directory"}),y=Date.now()
|
|
4892
|
-
let w,k,
|
|
4893
|
-
const
|
|
4918
|
+
let w,k,I=d.FileOperationPhase.VALIDATION
|
|
4919
|
+
const b={toolName:"create-directory",operationName:"create",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"create-directory",metricsPrefix:"create_directory",successMessage:"Successfully created directory {path}",failureMessage:"Failed to create directory {path}"}
|
|
4894
4920
|
try{const u=d.validateArgs(e,l.CreateDirectorySchema),{path:h,comment:g}=u,{resolveActiveTaskId:v}=await Promise.resolve().then(t.bind(t,3451)),C=e.taskId||await v(r,n,i)||"untracked"
|
|
4895
|
-
m.info("Creating directory: "+h,{taskId:C,path:h,comment:g}),d.validateTaskIdFormat(C,m,p,
|
|
4921
|
+
m.info("Creating directory: "+h,{taskId:C,path:h,comment:g}),d.validateTaskIdFormat(C,m,p,b.metricsPrefix),r.getCurrentBranchContext&&await r.getCurrentBranchContext()
|
|
4896
4922
|
const{normalizedPath:_,fullPath:E}=d.validateAndNormalizePath(h,r)
|
|
4897
|
-
|
|
4898
|
-
const q=await d.validateTaskId(C,_,n,m,p,
|
|
4923
|
+
I=d.FileOperationPhase.TASK_VALIDATION,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4924
|
+
const q=await d.validateTaskId(C,_,n,m,p,b.metricsPrefix),S=q?.requestId,T=await d.validateWorkItemStates(C,_,n,s,r,m,p,b.metricsPrefix),P=await d.autoPromoteTaskStatus(C,q.status,S,T.request?.status,_,n,s,m,p,b.metricsPrefix)
|
|
4899
4925
|
P.taskPromoted&&m.info(`Auto-promoted task ${C} (${q.title||"Untitled"}) to in_progress for file operation`,{taskId:C,taskTitle:q.title,previousStatus:q.status,newStatus:P.newTaskStatus,path:_}),P.requestPromoted&&m.info(`Auto-promoted request ${S} to in_progress for file operation`,{requestId:S,previousStatus:T.request?.status,newStatus:P.newRequestStatus,triggeringTaskId:C})
|
|
4900
|
-
const j=await d.ensureCorrectWorkspaceContext({taskPromoted:P.taskPromoted,requestId:S,context:r,operation:"create-directory",logger:m,metrics:p,metricsPrefix:
|
|
4926
|
+
const j=await d.ensureCorrectWorkspaceContext({taskPromoted:P.taskPromoted,requestId:S,context:r,operation:"create-directory",logger:m,metrics:p,metricsPrefix:b.metricsPrefix})
|
|
4901
4927
|
if(!j.success){if(j.isLockConflict)return{content:[{type:"text",text:"\u274c "+j.error}],isError:!0}
|
|
4902
4928
|
throw Error(j.error)}let R=!1
|
|
4903
|
-
try{R=(await a.default.stat(E)).isDirectory()}catch{R=!1}
|
|
4904
|
-
const{toolRecordId:x,localToolRecordId:M}=await d.createFileOperationRecords(C,S,r.projectId,
|
|
4905
|
-
w=x,k=x,b
|
|
4929
|
+
try{R=(await a.default.stat(E)).isDirectory()}catch{R=!1}I=d.FileOperationPhase.RECORD_CREATION,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4930
|
+
const{toolRecordId:x,localToolRecordId:M}=await d.createFileOperationRecords(C,S,r.projectId,b.recordType,_,{directoryExists:R,userComment:g},n,o,m,p,b.metricsPrefix,f)
|
|
4931
|
+
w=x,k=x,I=b.fileOperationPhase,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4906
4932
|
let O=R
|
|
4907
4933
|
if(!R){await a.default.mkdir(E,{recursive:!0}),m.info("Successfully created directory "+_)
|
|
4908
4934
|
try{const e=c.default.join(E,".gitkeep")
|
|
4909
4935
|
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),O=!0,m.info("Created .gitkeep file for Git tracking")}catch(e){m.warn("Failed to create .gitkeep file",{error:e instanceof Error?e.message:e+""}),O=!1}}const D=Date.now()-y
|
|
4910
|
-
p.recordValue("create_directory_time",D),p.incrementCounter("create_directory_success",1),
|
|
4911
|
-
const $=`Create directory: ${_} - ${g||"Create directory"}`,A=!R&&O?_+"/.gitkeep":_,F=await d.commitToGit(C,A,x,M,$,r,m,p,
|
|
4912
|
-
|
|
4936
|
+
p.recordValue("create_directory_time",D),p.incrementCounter("create_directory_success",1),I=d.FileOperationPhase.GIT_COMMIT,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4937
|
+
const $=`Create directory: ${_} - ${g||"Create directory"}`,A=!R&&O?_+"/.gitkeep":_,F=await d.commitToGit(C,A,x,M,$,r,m,p,b.metricsPrefix)
|
|
4938
|
+
I=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,p.incrementCounter("create_directory_phase",1,{phase:I}),await d.updateFileOperationRecords(C,w,k,_,b.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,b.metricsPrefix)
|
|
4913
4939
|
const N=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
4914
4940
|
return{content:[{type:"text",text:R?"Directory already exists":`Successfully created directory${F.commitHash?"\nCommit: "+F.commitHash.substring(0,8):""}${N.requestId&&!N.permanentBranch?"\nBranch: "+N.requestId:""}${j.lockAcquired&&j.lockedRequestId&&!N.permanentBranch?"\n\u{1f512} **Locked request:** "+j.lockedRequestId:""}`}]}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
|
|
4915
|
-
await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"create-directory",metadata:{status:"failed",timestamp:(new Date).toISOString(),path:e.path,userComment:e.comment,error:(0,g.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:
|
|
4916
|
-
if(p.recordValue("create_directory_time",s),p.incrementCounter("create_directory_errors",1),m.error("Error creating directory:",{error:(0,g.getErrorMessage)(t),time:s}),(w||k)&&e.taskId){
|
|
4917
|
-
try{await d.updateFileOperationRecords(e.taskId,w,k,e.path,
|
|
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:I,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
|
|
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){I=d.FileOperationPhase.RECORD_UPDATE_FAILURE
|
|
4943
|
+
try{await d.updateFileOperationRecords(e.taskId,w,k,e.path,b.recordType,"Failed to create directory "+e.path,{status:"failed",error:(0,g.getErrorMessage)(t),userComment:e.comment},"Failed to create directory "+e.path,n,o,m,p,b.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,I,m,p,e,b)}}
|
|
4918
4944
|
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"
|
|
4919
4945
|
function r(e){const t=[]
|
|
4920
4946
|
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"
|
|
@@ -5020,7 +5046,10 @@ let u=`**${e} Operation Complete**\n\n`
|
|
|
5020
5046
|
return u+="**Summary:**\n",u+=`- **Files processed:** ${s+i}\n`,u+=`- **Successful operations:** ${s}\n`,u+=`- **Failed operations:** ${i}\n`,u+=`- **Total changes made:** ${a}\n\n`,r.success&&r.commitHash?(u+="**Git Commit:**\n",u+=`- **Commit Hash:** ${r.commitHash.substring(0,8)}\n`,u+=`- **Files Committed:** ${r.filesCommitted.length}\n`,r.previousCommitHash&&(u+=`- **Previous Commit:** ${r.previousCommitHash.substring(0,8)}\n`),u+="\n"):r.error&&(u+=`**Git Status:** Changes saved but commit failed - ${r.error}\n\n`),n?.lockAcquired&&n.lockedRequestId&&(u+=`\u{1f512} **Locked request:** ${n.lockedRequestId}\n\n`),l.length>0&&(u+="**\u2705 Successful Operations:**\n",l.slice(0,10).forEach((e=>{const t=o?e[o]||0:"completed",r=e.path||e.documentId||"unknown"
|
|
5021
5047
|
u+=`- \`${r}\`: ${t} changes\n`})),l.length>10&&(u+=`- ... and ${l.length-10} more files\n`),u+="\n"),d.length>0&&(u+="**\u274c Failed Operations:**\n",d.slice(0,5).forEach((e=>{const t=e.path||e.documentId||"unknown"
|
|
5022
5048
|
u+=`- \`${t}\`: ${e.error||"Unknown error"}\n`})),d.length>5&&(u+=`- ... and ${d.length-5} more failures\n`)),{content:[{type:"text",text:u}],isError:!c}}
|
|
5023
|
-
const r=t(8824)},
|
|
5049
|
+
const r=t(8824)},8456(e,exports,t){"use strict"
|
|
5050
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
5051
|
+
const r=t(6183),n=t(2113)
|
|
5052
|
+
exports.def={name:"commit_to_viewed_session",description:"Post a cleaned-up user message to the session the user is currently viewing. Translator-only. Call this when the dictation is clear and ready to forward.",schema:r.CommitToViewedSessionSchema,annotations:{title:"Commit to Viewed Session",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleCommitToViewedSession)(e,t.logger)}}},8485(e,exports){"use strict"
|
|
5024
5053
|
function t(e,t){const r=e.match(/^([ \t]*)(.*?)\s*$/)
|
|
5025
5054
|
if(!r)return e
|
|
5026
5055
|
const[,n,s]=r
|
|
@@ -5130,34 +5159,34 @@ return i(t,e),t})
|
|
|
5130
5159
|
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()
|
|
5131
5160
|
try{let o
|
|
5132
5161
|
try{o=d.FileHistorySchema.parse(e)}catch(t){if(t instanceof u.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
5133
|
-
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:
|
|
5134
|
-
return
|
|
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:I,commit:b,since:v}=o
|
|
5163
|
+
return b?(i.info("Getting diff for specific commit",{filePath:a,commit:b}),await async function(e,t,r,n){const o=r.git,s=c.normalize(e).replace(/\\/g,"/")
|
|
5135
5164
|
if(n.info("Getting full diff for commit",{filePath:e,commit:t}),!o)return{content:[{type:"text",text:"\u274c Git not initialized"}],isError:!0}
|
|
5136
5165
|
try{const r=await o.log({from:t,to:t,file:s,maxCount:1})
|
|
5137
5166
|
if(!r.all||0===r.all.length)return{content:[{type:"text",text:`No commit found with hash ${t} for file ${e}`}]}
|
|
5138
5167
|
const n=r.all[0],i=await o.diff([t+"^",t,"--",s])
|
|
5139
5168
|
let a="# File History - Commit Diff\n\n"
|
|
5140
|
-
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,
|
|
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,b,t,i)):(i.info("Getting file history with branch support",{filePath:a,limit:y,showDiff:w,showTraceability:k,branch:I}),await async function(e,t,n,o,s,i,a,c,d,u,p){try{const{normalizedPath:m,fullPath:y}=f.validateAndNormalizePath(e,a)
|
|
5141
5170
|
try{await l.access(y)}catch(e){throw Error("File not found: "+m)}const w=a.git
|
|
5142
5171
|
if(!w)throw Error("Git is not available in this context")
|
|
5143
5172
|
let k={branch:null,requestId:null,isMain:!0}
|
|
5144
|
-
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
|
|
5145
|
-
if(s)
|
|
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 I=[],b=""
|
|
5174
|
+
if(s)I=await r(w,m,t,n,o,s,i,c,d,u),b=`## File History: ${m} (Branch: ${s})\n\n`
|
|
5146
5175
|
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)}]}
|
|
5147
5176
|
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)}]}
|
|
5148
5177
|
{const e=await async function(e,t,n,o,s,i,a,c,l,d){const u=[],h=[]
|
|
5149
5178
|
if(!i.isMain&&i.branch){const g=await r(e,t,n,o,s,i.branch,a,c,l,d)
|
|
5150
5179
|
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)))
|
|
5151
5180
|
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)
|
|
5152
|
-
|
|
5153
|
-
const v=
|
|
5154
|
-
v>t?
|
|
5155
|
-
try{
|
|
5156
|
-
for(let e=0;e<
|
|
5157
|
-
if(
|
|
5181
|
+
I=e.versions,b=`## File History: ${m} (Combined View)\n\n`,b+=`**Current Context:** ${k.isMain?"main":`${k.branch} (${k.requestId})`}\n`,b+=`**History Sources:** ${e.sources.join(", ")}\n\n`}}if(0===I.length)return b+="\u274c **No history found**\n\nThis file has no git history. It may be:\n- A new file that hasn't been committed\n- Located outside the git repository\n- The path may be incorrect\n- No history exists in the specified branch context",{content:[{type:"text",text:b}]}
|
|
5182
|
+
const v=I.length,C=Math.min(I.length,t)
|
|
5183
|
+
v>t?b+=`\u{1f4ca} **Summary:** ${v} versions found, showing ${C} most recent\n\n`:v>0&&(b+=`\u{1f4ca} **Summary:** ${v} version${v>1?"s":""} found\n\n`),b+=`**Total Versions:** ${I.length}\n`,b+="**Current File Size:** "
|
|
5184
|
+
try{b+=(await l.stat(y)).size+" bytes\n"}catch{b+="Unknown\n"}b+="\n"
|
|
5185
|
+
for(let e=0;e<I.length;e++){const t=I[e]
|
|
5186
|
+
if(b+=`### Version ${e+1} (${t.hash.substring(0,8)})\n`,t.branch&&(b+=`- **Branch:** ${t.branch}\n`),b+=`- **Author:** ${t.author}\n`,b+=`- **Date:** ${t.date}\n`,b+=`- **Message:** ${t.message}\n`,o&&t.traceability&&(b+=`\n${(0,h.formatTraceabilityInfo)(t.traceability)}\n`),n&&t.diff){const e=t.diff.split("\n")
|
|
5158
5187
|
let r=0,n=0
|
|
5159
5188
|
for(const t of e)t.startsWith("+")&&!t.startsWith("+++")&&r++,t.startsWith("-")&&!t.startsWith("---")&&n++
|
|
5160
|
-
|
|
5189
|
+
b+=`\n**Changes:**${r>0||n>0?` (Added ${r} lines, removed ${n} lines)`:""}\n\`\`\`diff\n${t.diff}\n\`\`\`\n`}b+="\n"}return b+="\u{1f4a1} **Tips:**\n",b+="- Use `file-recover` with a commit hash to restore the file to a previous version\n",b+='- Use `{"branch": "main"}` to see only main branch history\n',b+='- Use `{"branch": "req123456"}` to see only request branch history\n\n',d.info("Branch-aware file history retrieved successfully",{path:m,versions:I.length,targetBranch:s,currentBranch:k.branch,duration:Date.now()-p}),u.incrementCounter("file_history_total",1,{success:!0,type:"file",mode:s?"single-branch":"combined"}),{content:[{type:"text",text:b}]}}catch(e){throw e}}(a,y,w,k,I,v,t,n,i,s,m))}catch(e){const t=Date.now()-m
|
|
5161
5190
|
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}}}
|
|
5162
5191
|
const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),p=t(8824),f=a(t(5967)),m=a(t(7478)),{getCurrentBranch:y}=m},8849(e,exports,t){"use strict"
|
|
5163
5192
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
@@ -5286,47 +5315,47 @@ e.success&&e.agentType&&(s=e.agentType)}}catch(t){n.warn("Agent type lookup fail
|
|
|
5286
5315
|
if(e.ok){const t=await e.json()
|
|
5287
5316
|
if(t.data?.defaultModel){const[e,...r]=t.data.defaultModel.split("/")
|
|
5288
5317
|
i={providerID:e,modelID:r.join("/")}}}}catch{}const a=`${o.replace(/\/$/,"")}/session/${e}/prompt_async`,c=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:[{type:"text",text:"\x3c!-- inserted-prompt --\x3e"+t}],...s?{agent:s}:{},...i?{model:i}:{}})})
|
|
5289
|
-
return c.ok?(n.info("Notified session",{sessionId:e}),!0):(n.warn("Failed to notify session",{sessionId:e,status:c.status}),!1)}catch(t){return n.warn("Error notifying session",{sessionId:e,error:(0,l.getErrorMessage)(t)}),!1}}function n(e,t,r){return u.sessionIdentity.getParentSessionId(e,t,r)}function o(e,t,r){const
|
|
5290
|
-
if(!
|
|
5291
|
-
return(0,h.logSessionIdentity)(""+r,"identity",{sessionId:
|
|
5318
|
+
return c.ok?(n.info("Notified session",{sessionId:e}),!0):(n.warn("Failed to notify session",{sessionId:e,status:c.status}),!1)}catch(t){return n.warn("Error notifying session",{sessionId:e,error:(0,l.getErrorMessage)(t)}),!1}}function n(e,t,r){return u.sessionIdentity.getParentSessionId(e,t,r)}function o(e,t,r,n,o){const s=o?.sessionId||u.sessionIdentity.getIdentity()?.sessionId
|
|
5319
|
+
if(!s)throw new c.ValidationError("No session identity available. Make sure you are running within an OpenCode session.")
|
|
5320
|
+
return(0,h.logSessionIdentity)(""+r,"identity",{sessionId:s,fromCliOrigin:!!o?.sessionId}),s}function s(e){const t=[],r=e.content||{}
|
|
5292
5321
|
if(t.push("**Message Code:** "+e.messageCode),t.push(`**Type:** question (${r.questionType})`),t.push("**Status:** "+e.status),t.push("**Priority:** "+e.priority),t.push("**From:** "+e.fromSessionId),t.push(e.toSessionId?"**To:** "+e.toSessionId:"**To:** (broadcast)"),t.push("**Created:** "+e.createdAt),t.push("**Expires:** "+e.expiresAt),t.push(""),t.push("**Question:** "+r.question),r.context&&t.push("**Context:** "+r.context),"alternatives"===r.questionType&&r.options){t.push(""),t.push("**Options:**")
|
|
5293
5322
|
for(const e of r.options)t.push(` - [${e.id}] ${e.label}${e.description?" - "+e.description:""}`)}return"responded"===e.status&&e.response&&(t.push(""),t.push("---"),t.push("**Answered by:** "+e.respondedBySessionId),t.push("**Answered at:** "+e.respondedAt),e.response.text&&t.push("**Answer:** "+e.response.text),e.response.selectedOptions&&t.push("**Selected:** "+e.response.selectedOptions.join(", ")),e.response.notes&&t.push("**Notes:** "+e.response.notes)),t.join("\n")}function i(e){const t=[],r=e.content||{}
|
|
5294
|
-
return t.push("**Status:** "+(r.reportStatus||"unknown")),t.push("**Summary:** "+(r.summary||"")),r.details&&(t.push(""),t.push("**Details:**"),t.push(r.details)),t.join("\n")}function a(e){return"question"===e.messageType?s(e):i(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSessionMessageOperations=async function(e,t,d,p,f){const
|
|
5323
|
+
return t.push("**Status:** "+(r.reportStatus||"unknown")),t.push("**Summary:** "+(r.summary||"")),r.details&&(t.push(""),t.push("**Details:**"),t.push(r.details)),t.join("\n")}function a(e){return"question"===e.messageType?s(e):i(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSessionMessageOperations=async function(e,t,d,p,f,m){const y=d.child({component:"session_message_operations"})
|
|
5295
5324
|
if(!f)throw new c.ValidationError("API client not available")
|
|
5296
|
-
const{operation:
|
|
5297
|
-
|
|
5298
|
-
try{switch(
|
|
5299
|
-
return await async function(e,t,a,l){const{type:
|
|
5300
|
-
if(!
|
|
5301
|
-
const
|
|
5302
|
-
if(!
|
|
5303
|
-
if("question"===
|
|
5304
|
-
if(!
|
|
5305
|
-
const
|
|
5325
|
+
const{operation:w}=e
|
|
5326
|
+
y.info("Session message operation",{operation:w}),p.incrementCounter("session_message_operations",1,{operation:w})
|
|
5327
|
+
try{switch(w){case"send":if(!e.type)throw new c.ValidationError('send operation requires type ("question" or "report")')
|
|
5328
|
+
return await async function(e,t,a,l,d){const{type:u}=e
|
|
5329
|
+
if(!u)throw new c.ValidationError('send operation requires type ("question" or "report")')
|
|
5330
|
+
const h=l.getSessionMessageClient()
|
|
5331
|
+
if(!h)throw new c.ValidationError("Session message client not available")
|
|
5332
|
+
if("question"===u)return await async function(e,t,i,a,l,d){const{toSessionId:u,questionType:h,questionContent:g,priority:p,expiresInHours:f}=e
|
|
5333
|
+
if(!h||!g?.question)throw new c.ValidationError("Question requires questionType and questionContent.question")
|
|
5334
|
+
const m=o(0,0,"session_message_operations",0,d),y=await async function(e,t,r,o){if("parent"===e){const e=await n(t,r,o)
|
|
5306
5335
|
if(!e)throw new c.ValidationError("Could not find parent session. Make sure this session was spawned as a subagent.")
|
|
5307
|
-
return o.info('Resolved toSessionId "parent" to actual ID',{parentId:e}),e}return e}(
|
|
5308
|
-
if(!("alternatives"!==
|
|
5309
|
-
i.info("Creating question",{fromSessionId:
|
|
5310
|
-
const
|
|
5311
|
-
let
|
|
5312
|
-
return
|
|
5336
|
+
return o.info('Resolved toSessionId "parent" to actual ID',{parentId:e}),e}return e}(u,m,a,i)
|
|
5337
|
+
if(!("alternatives"!==h||g.options&&Array.isArray(g.options)))throw new c.ValidationError("Alternatives questions require options array")
|
|
5338
|
+
i.info("Creating question",{fromSessionId:m,toSessionId:y,questionType:h})
|
|
5339
|
+
const w=await l.createQuestion({fromSessionId:m,toSessionId:y,questionType:h,question:g.question,options:g.options,context:g.context,allowMultiple:g.allowMultiple,priority:p,expiresInHours:f})
|
|
5340
|
+
let k=""
|
|
5341
|
+
return y&&(k=await r(y,function(e){const t=e.content||{},r=["\u{1f4e8} **You have a new question!**","","**Question Code:** "+e.messageCode,"**From:** "+e.fromSessionId,"**Priority:** "+e.priority,"","**Question:** "+t.question]
|
|
5313
5342
|
if(t.context&&r.push("**Context:** "+t.context),"alternatives"===t.questionType&&t.options){r.push(""),r.push("**Options:**")
|
|
5314
|
-
for(const e of t.options)r.push(` - [${e.id}] ${e.label}${e.description?" - "+e.description:""}`)}return r.push(""),r.push(`Use \`session_message_operations\` with \`reply\` operation and message code \`${e.messageCode}\` to respond.`),r.join("\n")}(
|
|
5315
|
-
if("report"===
|
|
5316
|
-
if(!
|
|
5317
|
-
const
|
|
5318
|
-
const t=await n(
|
|
5319
|
-
if(
|
|
5320
|
-
|
|
5321
|
-
s.info("Submitting report",{sessionId:
|
|
5322
|
-
const
|
|
5323
|
-
let
|
|
5324
|
-
try{const e=await fetch(`http://localhost:${g}/api/sessions/${encodeURIComponent(
|
|
5343
|
+
for(const e of t.options)r.push(` - [${e.id}] ${e.label}${e.description?" - "+e.description:""}`)}return r.push(""),r.push(`Use \`session_message_operations\` with \`reply\` operation and message code \`${e.messageCode}\` to respond.`),r.join("\n")}(w),t,i)?"\n\n\u{1f4ec} The target session has been notified.":"\n\n\u26a0\ufe0f Could not notify the target session (may be offline)."),{content:[{type:"text",text:`\u2705 Question created!${k}\n\n**Message Code: ${w.messageCode}**\n\nUse this code to check for answers or share with other sessions.\n\n${s(w)}`}]}}(e,t,a,l,h,d)
|
|
5344
|
+
if("report"===u)return await async function(e,t,s,a,l,d){const{status:u,summary:h,details:p,finish:f}=e
|
|
5345
|
+
if(!u||!h)throw new c.ValidationError("Report requires status and summary")
|
|
5346
|
+
const m=o(0,0,"session_message_operations",0,d),y=await(async()=>{if(e.toSessionId&&"parent"!==e.toSessionId)return s.info("Using explicit toSessionId for report",{parentSessionId:e.toSessionId}),e.toSessionId
|
|
5347
|
+
const t=await n(m,a,s)
|
|
5348
|
+
if(t)return s.info("Auto-resolved parent session",{parentSessionId:t}),t
|
|
5349
|
+
throw new c.ValidationError("Could not find parent session. Ensure this session was created with a parent link, or provide an explicit toSessionId.")})()
|
|
5350
|
+
s.info("Submitting report",{sessionId:m,parentSessionId:y,status:u})
|
|
5351
|
+
const w=await l.createReport({fromSessionId:m,toSessionId:y,status:u,summary:h,details:p})
|
|
5352
|
+
let k="agent"
|
|
5353
|
+
try{const e=await fetch(`http://localhost:${g}/api/sessions/${encodeURIComponent(m)}/agent-type`)
|
|
5325
5354
|
if(e.ok){const t=await e.json()
|
|
5326
|
-
t.success&&t.agentType&&(
|
|
5327
|
-
return r.details&&(n.push(""),n.push(r.details)),n.join("\n")}(
|
|
5328
|
-
return{content:[{type:"text",text:`\u2705 Report submitted.${
|
|
5329
|
-
throw new c.ValidationError(`Unknown message type: ${
|
|
5355
|
+
t.success&&t.agentType&&(k=t.agentType)}}catch{}const I=await r(y,function(e,t="agent"){const r=e.content||{},n=[`${{success:"\u2705",partial:"\u26a0\ufe0f",failure:"\u274c",blocked:"\u{1f6ab}"}[r.reportStatus]||"\u{1f4cb}"} **Report \u2014 ${r.reportStatus}**`,`from: ${t} (${e.fromSessionId})`,"",r.summary]
|
|
5356
|
+
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.${I?"\n\n\u{1f4ec} The parent session has been notified.":"\n\n\u26a0\ufe0f Could not notify the parent session (may be offline)."}\n\n${i(w)}`}]}}(e,t,a,l,h,d)
|
|
5358
|
+
throw new c.ValidationError(`Unknown message type: ${u}. Use "question" or "report".`)}(e,t,y,f,m)
|
|
5330
5359
|
case"reply":if(!e.messageCode)throw new c.ValidationError("reply operation requires messageCode")
|
|
5331
5360
|
return await async function(e,t,n,o){const{messageCode:a}=e
|
|
5332
5361
|
if(!a)throw new c.ValidationError("reply operation requires messageCode")
|
|
@@ -5337,24 +5366,24 @@ n.info("Answering question",{messageCode:a,respondedBySessionId:o})
|
|
|
5337
5366
|
const u=await l.answerQuestion(a,{respondedBySessionId:o,text:i,selectedOptions:c,notes:d})
|
|
5338
5367
|
return{content:[{type:"text",text:`\u2705 Question answered!${await r(u.fromSessionId,function(e){const t=e.content||{},r=e.response||{},n=["\u{1f4ec} **Your question has been answered!**","","**Question Code:** "+e.messageCode,"**Question:** "+t.question,"","---","**Answered by:** "+e.respondedBySessionId]
|
|
5339
5368
|
return r.text&&n.push("**Answer:** "+r.text),r.selectedOptions&&n.push("**Selected:** "+r.selectedOptions.join(", ")),r.notes&&n.push("**Notes:** "+r.notes),n.join("\n")}(u),t,n)?"\n\n\u{1f4ec} The asking session has been notified.":"\n\n\u26a0\ufe0f Could not notify the asking session (may be offline)."}\n\n${s(u)}`}]}}if(a.startsWith("R-"))return n.info("Acknowledging report",{messageCode:a}),{content:[{type:"text",text:"\u2705 Report acknowledged!\n\n"+i(await l.acknowledgeReport(a))}]}
|
|
5340
|
-
throw new c.ValidationError(`Cannot determine message type from code "${a}". Expected Q-xxx (question) or R-xxx (report).`)}(e,t,
|
|
5341
|
-
case"offer-handoff":{const t=e.offerHandoff||{summary:e.summary||"",requestIds:e.requestIds||[]}
|
|
5342
|
-
|
|
5343
|
-
try{
|
|
5344
|
-
if(e
|
|
5345
|
-
await e.createQuestion({fromSessionId:r,toSessionId:s||void 0,questionType:"alternatives",question:"Plan ready: "+(t.summary||"Plan complete"),options:[{id:"build",label:"Start Building",description:`Begin building ${n} request${1!==n?"s":""}`},{id:"plan",label:"Keep Planning",description:"Continue refining the plan"}],context:
|
|
5346
|
-
const
|
|
5347
|
-
if(!
|
|
5348
|
-
if(!
|
|
5349
|
-
if(!e
|
|
5350
|
-
|
|
5351
|
-
const
|
|
5352
|
-
|
|
5353
|
-
const
|
|
5354
|
-
if(0===
|
|
5355
|
-
const
|
|
5356
|
-
for(const e of
|
|
5357
|
-
return{content:[{type:"text",text:
|
|
5369
|
+
throw new c.ValidationError(`Cannot determine message type from code "${a}". Expected Q-xxx (question) or R-xxx (report).`)}(e,t,y,f)
|
|
5370
|
+
case"offer-handoff":{const t=e.offerHandoff||{summary:e.summary||"",requestIds:e.requestIds||[]},r=o(0,0,"session_message_operations",0,m),s=await n(r,f,y)
|
|
5371
|
+
s||y.warn("offer-handoff: no parent session found \u2014 notification will be global",{fromSessionId:r})
|
|
5372
|
+
try{const e=f.getSessionMessageClient()
|
|
5373
|
+
if(e){const n=t.requestIds?.length||0
|
|
5374
|
+
await e.createQuestion({fromSessionId:r,toSessionId:s||void 0,questionType:"alternatives",question:"Plan ready: "+(t.summary||"Plan complete"),options:[{id:"build",label:"Start Building",description:`Begin building ${n} request${1!==n?"s":""}`},{id:"plan",label:"Keep Planning",description:"Continue refining the plan"}],context:JSON.stringify({type:"plan-completion",plannerSessionId:r,parentSessionId:s,requestIds:t.requestIds,summary:t.summary}),category:"action-required",priority:"high"}),y.info("offer-handoff: notification question created",{fromSessionId:r,parentSessionId:s})}else y.warn("offer-handoff: skipping notification question \u2014 no message client")}catch(e){y.warn("offer-handoff: failed to create notification question",{error:(0,l.getErrorMessage)(e)})}return{content:[{type:"text",text:'Handoff offered to user. STOP here and wait \u2014 the user will choose "Start Building" or "Keep Planning". You will receive their choice as a new message. Do NOT generate any further output until then.\nPLAN_HANDOFF_PENDING|'+JSON.stringify({summary:t.summary,requestIds:t.requestIds,parentSessionId:s,fromSessionId:r})}],isError:!1}}case"list":return await async function(e,t,r,n,o){let{sessionId:s,messageType:i,direction:l,status:d,readStatus:g,reportStatus:p,limit:f,offset:m}=e
|
|
5375
|
+
const y=n.getSessionMessageClient()
|
|
5376
|
+
if(!y)throw new c.ValidationError("Session message client not available")
|
|
5377
|
+
if(!s){const e=o?.sessionId||u.sessionIdentity.getIdentity()?.sessionId
|
|
5378
|
+
if(!e)return r.warn("No session identity for list operation"),{content:[{type:"text",text:"\u26a0\ufe0f Could not determine current session ID. Unable to list messages without a session context."}]}
|
|
5379
|
+
s=e,(0,h.logSessionIdentity)("session_message_operations.list","identity",{sessionId:s,fromCliOrigin:!!o?.sessionId})}r.debug("Listing messages",{sessionId:s,messageType:i,direction:l,status:d,readStatus:g})
|
|
5380
|
+
const w={sessionId:s,direction:l,limit:f,offset:m}
|
|
5381
|
+
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
|
+
const k=await y.listMessages(w)
|
|
5383
|
+
if(0===k.length)return{content:[{type:"text",text:"No messages found matching the criteria."}]}
|
|
5384
|
+
const I=[`Found ${k.length} message(s):\n`]
|
|
5385
|
+
for(const e of k)I.push("---\n"),I.push(a(e)),I.push("")
|
|
5386
|
+
return{content:[{type:"text",text:I.join("\n")}]}}(e.list||{},0,y,f,m)
|
|
5358
5387
|
case"get":if(!e.messageCode)throw new c.ValidationError("get operation requires messageCode")
|
|
5359
5388
|
return await async function(e,t,r){const{messageCode:n}=e
|
|
5360
5389
|
if(!n)throw new c.ValidationError("get operation requires messageCode")
|
|
@@ -5362,9 +5391,9 @@ const o=r.getSessionMessageClient()
|
|
|
5362
5391
|
if(!o)throw new c.ValidationError("Session message client not available")
|
|
5363
5392
|
t.debug("Getting message",{messageCode:n})
|
|
5364
5393
|
const s=await o.getMessage(n)
|
|
5365
|
-
return s?{content:[{type:"text",text:a(s)}]}:{content:[{type:"text",text:`\u274c Message with code ${n} not found.`}],isError:!0}}(e,
|
|
5366
|
-
default:throw new c.ValidationError(`Unknown operation: ${
|
|
5367
|
-
const c=t(9860),l=t(8824),d=t(7617),u=t(6688),h=t(7280),g=
|
|
5394
|
+
return s?{content:[{type:"text",text:a(s)}]}:{content:[{type:"text",text:`\u274c Message with code ${n} not found.`}],isError:!0}}(e,y,f)
|
|
5395
|
+
default:throw new c.ValidationError(`Unknown operation: ${w}. Valid operations: send, reply, list, get`)}}catch(e){return y.error("Session message operation failed",{operation:w,error:(0,l.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c Error: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
|
|
5396
|
+
const c=t(9860),l=t(8824),d=t(7617),u=t(6688),h=t(7280),g=(0,t(9414).getActionServerPort)()},9080(e,exports,t){"use strict"
|
|
5368
5397
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
5369
5398
|
const r=t(6183),n=t(1281)
|
|
5370
5399
|
exports.def={name:"search",description:"Search for text patterns in files on the currently active branch. Supports regex patterns and sorts results by file modification time (newest first).\n\nFile extensions: 'ts', '.ts', '*.ts' (all valid). Use '*' for any file type.\n\nCONTEXT LINES: Use contextLines option (0-10) to show surrounding lines before and after matches, reducing need for follow-up reads.\n\nLIST-ALL MODE: Omit 'needle' to list all files in a directory with tree structure (like ls/tree). Options: levels (1-4 depth), sortBy (name/modified/size/type).",schema:r.SearchSchema,annotations:{title:"Search Files",readOnlyHint:!0},readOnly:!0,handler(e,t){return(0,n.handleSearch)(e,t.context,t.apiClient,t.logger,t.metrics)}}},9089(e,exports){"use strict"
|
|
@@ -5430,7 +5459,15 @@ exports.def={name:"list_tasks",description:"List and filter tasks",schema:r.List
|
|
|
5430
5459
|
module.exports=require("net")},9373(e,exports,t){"use strict"
|
|
5431
5460
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
5432
5461
|
const r=t(6183),n=t(6416)
|
|
5433
|
-
exports.def={name:"revert_request",description:"Cancel open/in-progress requests or revert completed requests.\n\nCancel (open/in-progress):\n\u2022 Status set to 'canceled', request becomes read-only\n\u2022 No git operations, branch preserved\n\nRevert (completed):\n\u2022 All file changes undone via git revert\n\u2022 Request/task status set to 'reverted'\n\u2022 Request branch deleted\n\u2022 Fails fast if conflicts detected\n\nPreserved: Documents, git history, tool records (for audit trail).",schema:r.RevertRequestSchema,annotations:{title:"Revert Request",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},hidden:!0,handler(e,t){return(0,n.handleRevertRequest)(e,t.context,t.apiClient,t.logger,t.metrics)}}},
|
|
5462
|
+
exports.def={name:"revert_request",description:"Cancel open/in-progress requests or revert completed requests.\n\nCancel (open/in-progress):\n\u2022 Status set to 'canceled', request becomes read-only\n\u2022 No git operations, branch preserved\n\nRevert (completed):\n\u2022 All file changes undone via git revert\n\u2022 Request/task status set to 'reverted'\n\u2022 Request branch deleted\n\u2022 Fails fast if conflicts detected\n\nPreserved: Documents, git history, tool records (for audit trail).",schema:r.RevertRequestSchema,annotations:{title:"Revert Request",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},hidden:!0,handler(e,t){return(0,n.handleRevertRequest)(e,t.context,t.apiClient,t.logger,t.metrics)}}},9414(e,exports,t){"use strict"
|
|
5463
|
+
function r(){const e=Date.now()
|
|
5464
|
+
if(null!==c&&d>e-l)return c
|
|
5465
|
+
const t=(0,o.join)(process.env.ALCHEMY_PROJECT_PATH||process.cwd(),i,a)
|
|
5466
|
+
if((0,n.existsSync)(t))try{const r=(0,n.readFileSync)(t,"utf-8"),o=JSON.parse(r)
|
|
5467
|
+
if("number"==typeof o.port&&o.port>0&&65536>o.port)return c=o.port,l=e,c}catch{}return c=s,l=e,c}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getActionServerPort=r,exports.getActionServerBaseUrl=function(){return"http://localhost:"+r()}
|
|
5468
|
+
const n=t(9896),o=t(6928),s=3456,i=".alchemy_lab",a="action-server.json"
|
|
5469
|
+
let c=null,l=0
|
|
5470
|
+
const d=5e3},9422(e,exports,t){"use strict"
|
|
5434
5471
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDebugRequestFileHistory=async function(e,t,n,o){const s=o.child({tool:"debug_request_file_history"})
|
|
5435
5472
|
try{const{requestId:n="req000046"}=e
|
|
5436
5473
|
if(!t.git)throw Error("Git integration not available")
|
|
@@ -5456,10 +5493,10 @@ continue}const t=(0,h.findMatches)(s,n,m,100,e.path)
|
|
|
5456
5493
|
if(a.matchesFound=t.length,0===t.length){a.error="No matches found"+(m?" (tried fuzzy matching)":""),a.success=!1
|
|
5457
5494
|
const e=(0,h.findSimilarMatches)(s,n,5,.3)
|
|
5458
5495
|
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
|
|
5459
|
-
const
|
|
5460
|
-
for(const e of p)for(const t of e.matches)
|
|
5461
|
-
|
|
5462
|
-
for(const{match:e,newText:t,repResult:n}of
|
|
5496
|
+
const I=[]
|
|
5497
|
+
for(const e of p)for(const t of e.matches)I.push({match:t,newText:e.newText,repResult:e.repResult})
|
|
5498
|
+
I.sort(((e,t)=>t.match.startPos-e.match.startPos))
|
|
5499
|
+
for(const{match:e,newText:t,repResult:n}of I)w=(0,h.replaceMatch)(w,e,t),n.success?(n.lines.push(e.line),n.details.push(r(e))):(n.success=!0,n.matchType=e.matchType,n.lines=[e.line],n.details=[r(e)],y.successfulReplacements++)
|
|
5463
5500
|
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)
|
|
5464
5501
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
5465
5502
|
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=[]
|
|
@@ -5468,44 +5505,44 @@ return t},o(e)},function(e){if(e&&e.__esModule)return e
|
|
|
5468
5505
|
var t={}
|
|
5469
5506
|
if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
5470
5507
|
return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
5471
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceInFiles=async function(e,r,o,s,i,a,c,
|
|
5508
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceInFiles=async function(e,r,o,s,i,a,c,I){const b=a.child({tool:"replace_in_files"}),v=Date.now()
|
|
5472
5509
|
let C,_=u.FileOperationPhase.VALIDATION
|
|
5473
5510
|
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)
|
|
5474
5511
|
const E=u.validateArgs(e,d.ReplaceInFilesSchema),{resolveActiveTaskId:q}=await Promise.resolve().then(t.bind(t,3451)),S=e.taskId||await q(r,o,a)||"untracked",{operations:T,fuzzy_match:P=!0,comment:j}=E
|
|
5475
|
-
|
|
5512
|
+
b.info("Replace in files batch operation",{taskId:S,operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,comment:j})
|
|
5476
5513
|
const R=T.filter((e=>e.documentId)).map((e=>e.documentId))
|
|
5477
|
-
if(R.length>0&&r.apiClient)try{await(0,m.ensureDocumentsNotLocked)(R,r.apiClient,
|
|
5514
|
+
if(R.length>0&&r.apiClient)try{await(0,m.ensureDocumentsNotLocked)(R,r.apiClient,b,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
5478
5515
|
throw e}_=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5479
5516
|
const x=T[0],M=x.documentId?"document:"+x.documentId:x.path
|
|
5480
5517
|
let O=Date.now()
|
|
5481
|
-
const D=await u.validateTaskId(S,M,o,
|
|
5518
|
+
const D=await u.validateTaskId(S,M,o,b,c,"replace_in_files")
|
|
5482
5519
|
Date.now()
|
|
5483
5520
|
const $=D?.requestId,A=T.some((e=>e.path))
|
|
5484
5521
|
let F=!1
|
|
5485
5522
|
if(A&&$){O=Date.now()
|
|
5486
|
-
const e=await u.validateWorkItemStates(S,M,o,i,r,
|
|
5523
|
+
const e=await u.validateWorkItemStates(S,M,o,i,r,b,c,"replace_in_files")
|
|
5487
5524
|
Date.now(),O=Date.now()
|
|
5488
|
-
const t=await u.autoPromoteTaskStatus(S,D.status,$,e.request?.status,M,o,i,
|
|
5489
|
-
t.taskPromoted&&
|
|
5490
|
-
const n=await u.ensureCorrectWorkspaceContext({taskPromoted:t.taskPromoted,requestId:$,context:r,operation:"replace_in_files",logger:
|
|
5525
|
+
const t=await u.autoPromoteTaskStatus(S,D.status,$,e.request?.status,M,o,i,b,c,"replace_in_files")
|
|
5526
|
+
t.taskPromoted&&b.info("Auto-promoted task to in_progress",{taskId:S,requestId:$,previousStatus:D.status,newStatus:t.newTaskStatus}),Date.now(),O=Date.now()
|
|
5527
|
+
const n=await u.ensureCorrectWorkspaceContext({taskPromoted:t.taskPromoted,requestId:$,context:r,operation:"replace_in_files",logger:b,metrics:c,metricsPrefix:"replace_in_files"})
|
|
5491
5528
|
if(!n.success){if(n.isLockConflict)return{content:[{type:"text",text:"\u274c "+n.error}],isError:!0}
|
|
5492
|
-
throw Error(n.error)}Date.now(),F=!0}if(R.length>0&&$)try{await(0,p.validateRequestStatusForDocumentOperation)($,i,
|
|
5529
|
+
throw Error(n.error)}Date.now(),F=!0}if(R.length>0&&$)try{await(0,p.validateRequestStatusForDocumentOperation)($,i,b,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
5493
5530
|
throw e}O=Date.now()
|
|
5494
5531
|
const N=new Map
|
|
5495
|
-
if(
|
|
5532
|
+
if(b.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=[]
|
|
5496
5533
|
for(const t of e.replacements){const r=(0,h.findMatches)(n,t.old,o,100,e.path)
|
|
5497
5534
|
s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,t.fullPath)
|
|
5498
|
-
|
|
5499
|
-
const i=await(0,w.detectExternalEdits)(r.git,o,
|
|
5500
|
-
|
|
5501
|
-
const e=await(0,f.commitUserChangesBeforeToolOperation)(r.git,"replace_in_files",{requestId:$,taskId:S,workspaceManager:r.workspaceManager},
|
|
5502
|
-
e.userChangesCommitted&&(
|
|
5503
|
-
const{toolRecordId:L}=await u.createFileOperationRecords(S,$,r.projectId,"replace-in-files",M,{operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,userComment:j},o,s,
|
|
5535
|
+
b.info("\u{1f50d} Checking for external edits",{path:t.normalizedPath,affectedLines:o.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),matchCount:s.length})
|
|
5536
|
+
const i=await(0,w.detectExternalEdits)(r.git,o,b)
|
|
5537
|
+
b.info("\u{1f50d} External edit detection result",{path:t.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?(N.set(e.path,{message:i.message,debugInfo:i.debugInfo}),b.warn("\u26a0\ufe0f External edits detected before auto-commit",{path:t.normalizedPath,conflictingLines:i.conflictingLines})):(i.debugInfo&&N.set(e.path,{message:"",debugInfo:i.debugInfo}),b.info("\u2705 No external edit conflicts detected",{path:t.normalizedPath}))}else b.info("\u2139\ufe0f No matches found for external edit detection",{path:t.normalizedPath}),N.set(e.path,{message:"",debugInfo:{detectionRan:!1,reason:"No matches found - patterns not found in file",affectedRegion:"none",uncommittedChanges:"not checked",overlapDetected:!1}})}catch(t){b.warn("Failed to check for external edits before auto-commit",{path:e.path,error:(0,k.getErrorMessage)(t)})}if(Date.now(),O=Date.now(),A&&r.git)try{b.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
|
|
5538
|
+
const e=await(0,f.commitUserChangesBeforeToolOperation)(r.git,"replace_in_files",{requestId:$,taskId:S,workspaceManager:r.workspaceManager},b,c)
|
|
5539
|
+
e.userChangesCommitted&&(b.debug("[REPLACE-IN-FILES] User changes committed",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),b.info("User changes committed before batch operation",{taskId:S,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){b.warn("Pre-tool user changes commit failed",{taskId:S,error:e instanceof Error?e.message:e+""})}Date.now(),O=Date.now(),_=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
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,b,c,"replace_in_files",I)
|
|
5504
5541
|
C=L,Date.now(),O=Date.now(),_=u.FileOperationPhase.STRING_REPLACEMENT,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5505
5542
|
const z=[],H=[]
|
|
5506
5543
|
for(const e of T){const t=e.path?N.get(e.path):void 0,o=await n(e,P,r,0,0,t?.message,t?.debugInfo)
|
|
5507
5544
|
z.push(o),o.successfulReplacements>0&&"file"===o.type&&o.path&&H.push(o.path)}Date.now(),O=Date.now()
|
|
5508
|
-
const B=T.filter((e=>e.path&&!e.documentId)).map((e=>({path:e.path}))),U=await u.handleMultiFileGitCommit(S,B,z,H.length,{operationType:"Replace in files",toolRecordId:L||C||"unknown",successField:"successfulReplacements",logger:
|
|
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:b,metrics:c,metricsPrefix:"replace_in_files"},r),G=U.commitHash
|
|
5509
5546
|
Date.now(),Date.now()
|
|
5510
5547
|
const W=z.filter((e=>e.success)).length,V=z.length-W,J=z.reduce(((e,t)=>e+t.successfulReplacements),0),K=z.reduce(((e,t)=>e+t.failedReplacements),0),Y=z.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,replacements:e.replacements.map((e=>({old_str:e.old,new_str:e.new,success:e.success,error:e.error,matchesFound:e.matchesFound,matchType:e.matchType,lines:e.lines})))}))),Q=z.filter((e=>e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements}))),Z=z.filter((e=>!e.success)).map((e=>({path:e.path,documentId:e.documentId,filename:e.filename,error:e.error,successfulReplacements:e.successfulReplacements,failedReplacements:e.failedReplacements})))
|
|
5511
5548
|
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}}})
|
|
@@ -5522,7 +5559,7 @@ if(s.length>0){l+="\n**Failed Replacement Details:**\n"
|
|
|
5522
5559
|
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)))
|
|
5523
5560
|
return d.length>0&&(l+=`\n**Document Changes:** ${d.length} modified document(s) synced back to tracking system.\n`),o.workspaceManager?.largeFileWarning&&(l+=o.workspaceManager.largeFileWarning,o.workspaceManager.largeFileWarning=""),l}(z,G,J,K,r,C)
|
|
5524
5561
|
return{content:[{type:"text",text:X}],isError:0===J}}catch(e){const t=Date.now()-v
|
|
5525
|
-
if(
|
|
5562
|
+
if(b.error("Replace in files batch operation failed",{error:e instanceof Error?e.stack:e+"",duration:t,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{status:"failed",error:(0,k.getErrorMessage)(e),phase:_,duration:t}})}catch(e){}return c.incrementCounter("replace_in_files_errors",1,{phase:_}),{content:[{type:"text",text:"\u274c **Replace In Files Failed:** "+(0,k.getErrorMessage)(e)}],isError:!0}}},c(t(857))
|
|
5526
5563
|
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"
|
|
5527
5564
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseLineSpec=function(e){if(!e||""===e.trim())throw Error("Line specification cannot be empty")
|
|
5528
5565
|
const t=e.trim()
|