alchemylab 1.1.1 → 1.2.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/cli.js +355 -233
- package/dist/http-server.js +822 -692
- package/dist/index.js +822 -692
- package/dist/mcp-direct.js +1716 -1586
- package/dist/plugins/inject-session.js +3 -2
- package/package.json +4 -3
package/dist/http-server.js
CHANGED
|
@@ -2,37 +2,37 @@
|
|
|
2
2
|
if(void 0!==r)return r.exports
|
|
3
3
|
var module=s[t]={exports:{}}
|
|
4
4
|
return o[t].call(module.exports,module,module.exports,e),module.exports}var t,r,n,o={76(e,exports,t){"use strict"
|
|
5
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateTask=async function(e,t,
|
|
6
|
-
|
|
7
|
-
const
|
|
8
|
-
try{const
|
|
9
|
-
if(!
|
|
10
|
-
let
|
|
11
|
-
|
|
12
|
-
try{const e=
|
|
13
|
-
|
|
14
|
-
const r=(0,o.extractDataFromResponse)(t,{logger:
|
|
15
|
-
|
|
16
|
-
throw
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
let
|
|
25
|
-
|
|
26
|
-
try{const e=
|
|
27
|
-
if(e){const t=await e.createToolRecord({taskId:
|
|
28
|
-
|
|
29
|
-
let
|
|
30
|
-
return
|
|
31
|
-
else{const n=
|
|
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){
|
|
33
|
-
let o=(0,s.getErrorMessage)(r),
|
|
34
|
-
return r instanceof n.NotFoundError?o=`The request ID "${e.requestId}" was not found. Please provide a valid request ID.`:r instanceof n.ValidationError&&(o.includes("Project cannot accept new tasks")||o.includes("Project is inactive due to tier limits")?
|
|
35
|
-
const r=t(6183),n=t(9860),o=t(2960),s=t(8824)},184(e,exports,t){"use strict"
|
|
5
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateTask=async function(e,t,a,c,l,d,u){const h=c.child({tool:"create_task"})
|
|
6
|
+
h.info("Creating new task",{args:e})
|
|
7
|
+
const g=l.startTimer("tool_handler_duration")
|
|
8
|
+
try{const c=function(e){try{return r.CreateTaskSchema.parse(e)}catch(t){throw new n.ValidationError("Invalid input: "+(0,s.getErrorMessage)(t),{args:e,error:t})}}(e),d=t.projectId
|
|
9
|
+
if(!d)throw h.error("Missing project ID in context",{contextKeys:Object.keys(t)}),new n.ValidationError("Project ID is required for creating tasks with the new API structure")
|
|
10
|
+
let p
|
|
11
|
+
h.info("Using project ID from context",{projectId:d}),l.incrementCounter("create_task_attempts",1,{requestId:c.requestId,projectId:d}),a.setProjectId(d)
|
|
12
|
+
try{const e=a.getRequestClient(),t=await e.getRequest(c.requestId)
|
|
13
|
+
h.info("Raw request verification response data",{responseData:JSON.stringify(t)})
|
|
14
|
+
const r=(0,o.extractDataFromResponse)(t,{logger:h,operationName:"verifyRequestExists",throwOnNoData:!0})
|
|
15
|
+
p="object"==typeof r&&null!==r&&"data"in r?r.data:r,h.info(`Verified request ${c.requestId} exists`,{requestId:c.requestId,projectId:d,requestStatus:p.status})}catch(e){throw new n.NotFoundError(`Request ${c.requestId} not found in project ${d}. Please provide a valid request ID.`,{requestId:c.requestId,projectId:d,originalError:e})}if(["pending_approval","completed","canceled","ready_for_review","ready_for_merge","reverted"].includes(p.status)){const e={pending_approval:"is pending approval. Approve the request before creating tasks.",completed:"is already completed and merged. Create a new request for additional changes.",canceled:"was canceled. Create a new request or reopen this one if needed.",ready_for_review:"is being tested. Wait for test results before making changes.",ready_for_merge:"is ready to merge. Call merge to complete it.",reverted:"was reverted and cannot accept new tasks. Re-complete the request first or create a new request."}[p.status]||`has status '${p.status}' and cannot accept new tasks.`
|
|
16
|
+
throw h.warn(`Task creation blocked on ${p.status} request`,{requestId:c.requestId,requestStatus:p.status,projectId:d}),new n.ValidationError(`The request ID "${c.requestId}" ${e}`,{requestId:c.requestId,requestStatus:p.status,reason:"request_"+p.status})}h.info("Request status validation passed for "+c.requestId,{requestId:c.requestId,requestStatus:p.status,projectId:d})
|
|
17
|
+
const f=a.getTaskClient()
|
|
18
|
+
h.info("Creating task with project context",{projectId:d})
|
|
19
|
+
const m={requestId:c.requestId,projectId:d,title:c.title,description:c.description,status:"pending",...u&&{cliOrigin:u}}
|
|
20
|
+
h.info("Task input prepared",{taskInput:JSON.stringify(m)}),h.info("Creating task via task client",{projectId:d,requestId:c.requestId,title:c.title})
|
|
21
|
+
const y=await f.createTask(m)
|
|
22
|
+
h.debug("Task creation response structure",{type:typeof y,isArray:Array.isArray(y),hasData:null!=y,properties:y?Object.keys(y):[],dataPreview:y?JSON.stringify(y).substring(0,200)+"...":"null"})
|
|
23
|
+
const w=(0,o.extractDataFromResponse)(y,{logger:h,operationName:"createTask",defaultValue:{id:"tas"+Date.now().toString().substring(5,11),title:m.title,description:m.description,status:"pending",requestId:m.requestId,projectId:d,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}}),k="data"in w?w.data:w,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
|
+
let E,q="unknown"
|
|
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
|
+
try{const e=a.getToolRecordClient()
|
|
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
|
+
return E&&(S+=`\n[RECORD:${E}]`),{content:[{type:"text",text:S}]}}catch(r){if(h.error("Failed to create task",{error:r instanceof Error?r.stack:r+"",args:e}),t.projectId)try{if(r instanceof Error&&(r.message.includes("Project is disabled")||r.message.includes("Project cannot accept new tasks")||r.message.includes("disabled due to tier limits")||r.message.includes("Project is inactive due to tier limits")))h.info("Skipping tool record creation for disabled project error",{projectId:t.projectId,error:r.message})
|
|
31
|
+
else{const n=a.getToolRecordClient()
|
|
32
|
+
n&&await n.createToolRecord({requestId:e.requestId,projectId:t.projectId,type:"create-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.title,taskDescription:e.description?.substring(0,100)+(e.description?.length>100?"...":""),error:(0,s.getErrorMessage)(r),errorDetails:r instanceof Error?r.stack:r+""},note:"Failed to create task: "+e.title})}}catch(e){h.error("Failed to create failure record for task creation",{error:e instanceof Error?e.message:e+""})}g({success:!1,error:r instanceof Error?r.name:"unknown"})
|
|
33
|
+
let o=(0,s.getErrorMessage)(r),i=""
|
|
34
|
+
return r instanceof n.NotFoundError?o=`The request ID "${e.requestId}" was not found. Please provide a valid request ID.`:r instanceof n.ValidationError&&(o.includes("Project cannot accept new tasks")||o.includes("Project is inactive due to tier limits")?i="\n\nThis project is currently inactive due to tier limits. Only your oldest projects can accept new tasks. Please use an active project or upgrade your tier for more simultaneous projects.":o="Invalid input: "+o),c.error("Detailed error when creating task",{error:(0,s.getErrorMessage)(r),stack:r instanceof Error?r.stack:void 0}),a.isOffline,a.apiClient,{content:[{type:"text",text:`Error: ${o}${i}`}],isError:!0}}}
|
|
35
|
+
const r=t(6183),n=t(9860),o=t(2960),s=t(8824),i=t(4466)},184(e,exports,t){"use strict"
|
|
36
36
|
function r(e,t,r,n,o={}){const s=d.default.resolve(e)
|
|
37
37
|
if(O.has(s))return t.child({component:"mcp-server-registry"}).debug("Using existing server for path",{path:s}),O.get(s)
|
|
38
38
|
const i=new M(s,t,r,n,o)
|
|
@@ -44,14 +44,14 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
|
|
|
44
44
|
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
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.McpServer=void 0,exports.resetStdoutWrite=function(){process.stdout.write=
|
|
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}),
|
|
49
|
-
!(0,p.isDebugToolsEnabled)()||
|
|
47
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.McpServer=void 0,exports.resetStdoutWrite=function(){process.stdout.write=x},exports.getMcpServer=r,exports.createServer=function(e,t,n,o,s={}){return r(e,t,n,o,s)}
|
|
48
|
+
const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),p=t(3444),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}),x=process.stdout.write,R=process.argv.includes("--stdio")||"true"===process.env.MCP_DIRECT_MODE
|
|
49
|
+
!(0,p.isDebugToolsEnabled)()||R&&"true"!==process.env.DEBUG_STDOUT_CAPTURE||(process.stdout.write=function(e){try{return(0,p.isDebugToolsEnabled)()&&"true"===process.env.DEBUG_LOGGING?.toLowerCase()&&"string"==typeof e&&!e.trim().startsWith('{"jsonrpc":"2.0"')&&e.trim().length>0&&j.debug("Stdout output",{content:e.substring(0,100),length:e.length}),x.call(process.stdout,e)}catch(e){return j.error("Error in safeStdoutWrite",{error:e+""}),!0}})
|
|
50
50
|
class M{constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,k.ALCHEMY_DIR_NAME),this.metrics=r,this.remoteServerUrl=n,this.existingProjectId=o.existingProjectId,this.gitBinary=(0,l.detectGitBinary)(),this.logger.info("Detected git binary",{gitBinary:this.gitBinary,version:(0,l.getGitVersion)()}),this.projectContext=new f.ProjectContext(e,t),this.tokenManager=new m.TokenManager(t,e,{remoteServerUrl:n}),this.lockOverrideManager=new S.LockOverrideManager(t),this.configManager=new T.ConfigManager(t),this.logger.debug("Server paths initialized",{basePath:this.basePath,alchemyPath:this.alchemyPath}),this.server=new g.Server({name:"alchemy",version:"1.0.0"},{capabilities:{tools:{search:{},create_request:{},complete_task:{},get_task_information:{},complete_request:{},revert_request:{},get_request_information:{},list_tasks:{},list_requests:{},switch_to_branch:{},read_files:{},create_directory:{},move_files:{},write_file:{},replace_strings:{},insert_lines:{},replace_lines:{},delete_files:{},document_operations:{},file_history:{},task_file_history:{},request_file_history:{},quick_write:{},quick_replace:{},quick_manage:{}}}}),(0,y.setGlobalClientInfo)("OpenCode","1.0.0"),this.metrics.incrementCounter("mcp_server_init_started",1),this.logger.info("Starting initialization for server instance"),this.initializationPromise=this.initialize()}get branchState(){if(!this.workspaceManager)return{currentBranch:null,activeRequestId:null,isOnMainBranch:!0}
|
|
51
|
-
const e=this.workspaceManager.getCurrentContext()
|
|
51
|
+
const e=this.workspaceManager.getCurrentContext("__server__")
|
|
52
52
|
return{currentBranch:e.branchName,activeRequestId:e.requestId,isOnMainBranch:e.isMainBranch}}async updateBranchState(e,t){this.logger.debug("updateBranchState called - managed by WorkspaceManager",{branch:e,requestId:t})}async getCurrentBranchContext(){if(!this.workspaceManager)return{branch:null,requestId:null,isMain:!0}
|
|
53
|
-
const e=this.workspaceManager.getCurrentContext()
|
|
54
|
-
return{branch:e.branchName,requestId:e.requestId,isMain:e.isMainBranch}}async syncBranchState(){this.logger.debug("syncBranchState called - managed by WorkspaceManager")}async switchToMainContext(){return this.workspaceManager?this.workspaceManager.switchToMain():{success:!1,message:"WorkspaceManager not available"}}getCurrentRequestId(){return this.workspaceManager?.getCurrentContext().requestId||null}async getNextId(e){try{const t=this.metrics.startTimer("remote_id_generation"),r=this.apiClient.getProjectClient()
|
|
53
|
+
const e=this.workspaceManager.getCurrentContext("__server__")
|
|
54
|
+
return{branch:e.branchName,requestId:e.requestId,isMain:e.isMainBranch,permanentBranch:e.permanentBranch}}async syncBranchState(){this.logger.debug("syncBranchState called - managed by WorkspaceManager")}async switchToMainContext(){return this.workspaceManager?this.workspaceManager.switchToMain("__server__"):{success:!1,message:"WorkspaceManager not available"}}getCurrentRequestId(){return this.workspaceManager?.getCurrentContext("__server__").requestId||null}async getNextId(e){try{const t=this.metrics.startTimer("remote_id_generation"),r=this.apiClient.getProjectClient()
|
|
55
55
|
if(!r||"function"!=typeof r.getNextId)throw Error("Project client or getNextId method not available")
|
|
56
56
|
const n=await r.getNextId(e)
|
|
57
57
|
return t({success:!0,type:e}),this.metrics.incrementCounter("remote_id_success",1,{type:e}),n}catch(t){throw this.metrics.incrementCounter("remote_id_failure",1,{type:e,error:t instanceof Error?t.name:"unknown"}),this.logger.warn("Failed to get ID from remote server, unable to perform operation",{type:e,error:(0,P.getErrorMessage)(t)}),Error("Failed to get ID from remote server.")}}async initialize(){const e=this.remoteServerUrl||"https://api.alchemylabcode.com"
|
|
@@ -106,17 +106,17 @@ const r=new g.SSEServerTransport("/sse",e)
|
|
|
106
106
|
this.currentSSEConnection={transport:r,response:e}
|
|
107
107
|
try{await this.server.connect(r),this.logger.info("SSE transport connected successfully")}catch(e){this.logger.error("Error connecting SSE transport",{error:(0,P.getErrorMessage)(e)})}return r}async connectStdio(){await this.waitForInitialization(),this.logger.debug("Connecting stdio transport"),this.stdioTransport=new g.StdioServerTransport
|
|
108
108
|
try{await this.server.connect(this.stdioTransport),this.logger.info("STDIO transport connected successfully")}catch(e){this.logger.error("Error connecting stdio transport",{error:(0,P.getErrorMessage)(e)})}}getCurrentSSEConnection(){return this.currentSSEConnection}setCurrentSSEConnection(e){this.currentSSEConnection=e}getServer(){return this.server}getCurrentGitInstance(){if(!this.workspaceManager)return this.git||void 0
|
|
109
|
-
const e=this.workspaceManager.getCurrentContext()
|
|
109
|
+
const e=this.workspaceManager.getCurrentContext("__server__")
|
|
110
110
|
return"multi-agent"===e.mode&&e.requestId?this.workspaceManager.getCurrentGit():this.git||void 0}getContext(){if(!this.workspaceManager)throw Error("WorkspaceManager not initialized")
|
|
111
|
-
return{mainBasePath:this.basePath,alchemyPath:this.alchemyPath,basePath:this.workspaceManager.getCurrentContext().basePath,projectId:this.getProjectId(),git:this.getCurrentGitInstance(),gitBinary:this.gitBinary,apiClient:this.apiClient,workspaceManager:this.workspaceManager,documentFileManager:this.documentFileManager,lockOverrideManager:this.lockOverrideManager,configManager:this.configManager,getNextId:this.getNextId.bind(this),getCurrentBranchContext:this.getCurrentBranchContext.bind(this),syncBranchState:this.syncBranchState.bind(this),switchToMainContext:this.switchToMainContext.bind(this),getCurrentRequestId:this.getCurrentRequestId.bind(this),updateBranchState:this.updateBranchState.bind(this)}}isMainBranch(e){return"main"===e||"master"===e}extractRequestIdFromBranch(e){const t=e.match(/^feature\/req(\d+)-/)
|
|
111
|
+
return{mainBasePath:this.basePath,alchemyPath:this.alchemyPath,basePath:this.workspaceManager.getCurrentContext("__server__").basePath,projectId:this.getProjectId(),git:this.getCurrentGitInstance(),gitBinary:this.gitBinary,currentSessionId:"__server__",apiClient:this.apiClient,workspaceManager:this.workspaceManager,documentFileManager:this.documentFileManager,lockOverrideManager:this.lockOverrideManager,configManager:this.configManager,getNextId:this.getNextId.bind(this),getCurrentBranchContext:this.getCurrentBranchContext.bind(this),syncBranchState:this.syncBranchState.bind(this),switchToMainContext:this.switchToMainContext.bind(this),getCurrentRequestId:this.getCurrentRequestId.bind(this),updateBranchState:this.updateBranchState.bind(this)}}isMainBranch(e){return"main"===e||"master"===e}extractRequestIdFromBranch(e){const t=e.match(/^feature\/req(\d+)-/)
|
|
112
112
|
return t?"req"+t[1]:null}async getEnhancedContext(){return{...this.getContext(),branchInfo:await this.getCurrentBranchInfo()}}getTokenManager(){return this.tokenManager}getProjectId(){try{return this.projectContext.getProjectId()}catch(e){return this.logger.debug("ProjectContext not initialized, using fallback project ID",{error:(0,P.getErrorMessage)(e)}),"INITIALIZING"}}generateSessionId(){return`session_${Date.now().toString(36)}_${Math.random().toString(36).substring(2,8)}_${process.pid.toString(36)}`}async getActiveWorktrees(){return await this.workspaceManager.listActiveWorkspaces()}async initializeWorkspaceManager(){try{if(this.logger.debug("initializeWorkspaceManager called",{basePath:this.basePath}),!this.git)throw Error("Git must be initialized before WorkspaceManager")
|
|
113
113
|
this.workspaceManager=(0,E.createWorkspaceManager)(this.basePath,this.logger,this.git,this.metrics,this.apiClient),this.logger.debug("WorkspaceManager created successfully"),this.logger.info("Initialized unified workspace manager",{mode:"multi-agent",basePath:this.basePath})}catch(e){throw this.logger.error("Failed to initialize workspace manager",{error:e}),e}}async switchToRequestContext(e){return this.logger.debug("switchToRequestContext called",{requestId:e,hasWorkspaceManager:!!this.workspaceManager}),this.workspaceManager?this.switchToWorktreeContext(e):{success:!1,message:"Workspace manager not available"}}async switchToWorktreeContext(e){if(this.logger.debug("Using worktree context switching for multi-agent mode",{requestId:e}),!this.workspaceManager)return{success:!1,message:"Workspace manager not available"}
|
|
114
114
|
try{let t="request-"+e
|
|
115
115
|
try{this.logger.debug("Attempting to fetch request title from API",{requestId:e})
|
|
116
116
|
const r=this.apiClient.getRequestClient(),n=await r.getRequest(e)
|
|
117
117
|
n&&n.title?(t=n.title,this.logger.debug("Successfully fetched request title for worktree",{requestId:e,actualTitle:n.title})):this.logger.warn("Request info found but no title, using fallback",{requestId:e,requestInfo:n?"exists":"null",fallbackTitle:t})}catch(r){this.logger.warn("Failed to fetch request title, using fallback",{requestId:e,fallbackTitle:t,error:(0,P.getErrorMessage)(r),errorStack:r instanceof Error?r.stack:void 0})}const r=this.generateSessionId()
|
|
118
|
-
this.logger.info("Creating worktree for request using WorkspaceManager",{requestId:e,requestTitle:t,sessionId:r}),await this.workspaceManager.ensureWorkspaceReady(e)
|
|
119
|
-
const n=this.workspaceManager.getCurrentContext()
|
|
118
|
+
this.logger.info("Creating worktree for request using WorkspaceManager",{requestId:e,requestTitle:t,sessionId:r}),await this.workspaceManager.ensureWorkspaceReady(e,"__server__")
|
|
119
|
+
const n=this.workspaceManager.getCurrentContext("__server__")
|
|
120
120
|
this.git=(0,c.simpleGit)({baseDir:n.basePath,binary:this.gitBinary})
|
|
121
121
|
try{const t=await w.getCurrentBranch(this.git,this.logger,this.metrics)
|
|
122
122
|
if(this.logger.info("Workspace Git instance branch status",{requestId:e,currentBranch:t,expectedBranch:n.branchName,workspacePath:n.basePath,isMainBranch:n.isMainBranch}),t!==n.branchName&&!n.isMainBranch){this.logger.warn("Workspace not on expected branch, attempting to switch",{requestId:e,currentBranch:t,expectedBranch:n.branchName})
|
|
@@ -196,49 +196,52 @@ default:t="open"}else t="open"
|
|
|
196
196
|
const n=Array.isArray(e.acceptanceCriteria)?e.acceptanceCriteria.map(r):[]
|
|
197
197
|
return{id:e.id,title:e.title,description:e.description,type:e.type,status:t,acceptanceCriteria:n,createdAt:e.createdAt,updatedAt:e.updatedAt,...e.projectId?{projectId:e.projectId}:{},...e.completionSummary?{completionSummary:e.completionSummary}:{},...e.completedAt?{completedAt:e.completedAt}:{},...e.metadata?{metadata:e.metadata}:{},...e.lockInfo?{lockInfo:e.lockInfo}:{}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.adaptApiAcceptanceCriterionToDomain=r,exports.adaptApiRequestToDomain=n,exports.adaptApiRequestsToDomain=function(e){return e.map(n)}
|
|
198
198
|
const o=t(6756)},355(e,exports,t){"use strict"
|
|
199
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteTask=async function(e,
|
|
200
|
-
|
|
201
|
-
const
|
|
202
|
-
try{const
|
|
199
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCompleteTask=async function(e,d,u,h,g){const p=h.child({tool:"complete_task"})
|
|
200
|
+
p.info("Completing task",{args:e})
|
|
201
|
+
const f=g.startTimer("tool_handler_duration")
|
|
202
|
+
try{const o=function(e){if(void 0!==e.verificationSteps){const{verificationSteps:t,...r}=e
|
|
203
203
|
e=r}try{return r.CompleteTaskSchema.parse(e)}catch(e){if(e instanceof i.ZodError&&e.errors.length>0)throw new n.ValidationError(e.errors[0].message)
|
|
204
|
-
throw new n.ValidationError("Invalid input: "+(0,c.getErrorMessage)(e))}}(e)
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
throw
|
|
219
|
-
const r=await e.
|
|
220
|
-
if(
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
204
|
+
throw new n.ValidationError("Invalid input: "+(0,c.getErrorMessage)(e))}}(e)
|
|
205
|
+
let h=o.taskId
|
|
206
|
+
const m=o.summary;(0,l.isTaskRef)(h)&&(h=await(0,l.resolveTaskRef)(h,u,p))
|
|
207
|
+
const y=d.projectId
|
|
208
|
+
if(!y)throw new n.ValidationError("Project ID is required for completing tasks with the new API structure")
|
|
209
|
+
g.incrementCounter("complete_task_attempts",1,{taskId:h}),u.setProjectId(y)
|
|
210
|
+
const w=u.getTaskClient()
|
|
211
|
+
let k
|
|
212
|
+
try{const e=await w.getTask(h)
|
|
213
|
+
p.info("Raw task response data",{responseData:JSON.stringify(e)}),p.debug("Task response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
|
|
214
|
+
const t=(0,s.extractDataFromResponse)(e,{logger:p,operationName:"getTask",throwOnNoData:!0})
|
|
215
|
+
k="data"in t?t.data:t,p.info("Current task status: "+k.status,{taskId:h,currentStatus:k.status})}catch(e){if(e instanceof n.ValidationError)throw e
|
|
216
|
+
throw new n.NotFoundError(`Task ${h} not found in project ${y}. Please provide a valid task ID.`,{taskId:h,projectId:y,originalError:e})}if("completed"===k.status){const e="Task is already completed."
|
|
217
|
+
throw p.warn(e,{taskId:h,currentStatus:k.status}),new n.ValidationError(e)}if("canceled"===k.status){const e="Task is canceled and can not be completed."
|
|
218
|
+
throw p.warn(e,{taskId:h,currentStatus:k.status}),new n.ValidationError(e)}if(k.requestId){p.debug("Checking request lock for task operation",{taskId:h,requestId:k.requestId})
|
|
219
|
+
try{const e=u.getRequestClient(),{sessionTag:t}=(0,a.getGlobalClientInfo)(),r=await e.getRequestLockStatus(k.requestId)
|
|
220
|
+
if(r.isLocked){if(r.lockedBySessionTag!==t){let e=`Request ${k.requestId} is locked by another agent (${r.lockedBySessionTag}). `
|
|
221
|
+
throw r.isExpired?e+="Lock has expired but cleanup may be pending. ":e+=`Lock expires in: ${r.timeRemainingFormatted}. `,e+="Only the agent that locked the request can modify its tasks.",new n.ValidationError(e,{taskId:h,requestId:k.requestId,lockedByAgent:r.lockedBySessionTag,currentAgent:t,timeRemainingMs:r.timeRemainingMs,isExpired:r.isExpired})}}else{p.debug("Lock not held, auto-acquiring for task completion",{requestId:k.requestId,sessionTag:t})
|
|
222
|
+
const r=await e.lockRequest(k.requestId,t)
|
|
223
|
+
if(!r.locked)throw new n.ValidationError(`Failed to acquire lock for request ${k.requestId}. Another agent may have just locked it. Try again shortly.`,{taskId:h,requestId:k.requestId})
|
|
224
|
+
p.info("Auto-acquired lock for task completion",{requestId:k.requestId,sessionTag:t,lockedAt:r.lockedAt})}p.info("Request lock validation passed",{taskId:h,requestId:k.requestId,sessionTag:t})}catch(e){if(e instanceof n.ValidationError)throw e
|
|
225
|
+
throw p.error("Failed to check request lock status",{taskId:h,requestId:k.requestId,error:(0,c.getErrorMessage)(e)}),new n.ValidationError("Failed to verify request lock status: "+(0,c.getErrorMessage)(e),{taskId:h,requestId:k.requestId})}}else p.debug("Task without requestId: skipping lock check",{taskId:h,hasRequestId:!!k.requestId})
|
|
226
|
+
let I=d.git
|
|
227
|
+
if(d.workspaceManager){const e=d.workspaceManager.getCurrentContext(d.currentSessionId)
|
|
225
228
|
if("multi-agent"===e.mode&&e.requestId){const{simpleGit}=t(3807)
|
|
226
|
-
|
|
227
|
-
if(
|
|
228
|
-
try{const e=
|
|
229
|
-
e&&(
|
|
230
|
-
|
|
231
|
-
const i=
|
|
232
|
-
let a=`Task ${
|
|
233
|
-
if(
|
|
234
|
-
|
|
235
|
-
const t=(0,s.extractArrayFromResponse)(e,{logger:
|
|
236
|
-
|
|
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
|
+
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: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
|
+
p.info("Raw task update response data",{responseData:JSON.stringify(n)}),p.debug("Task update response structure",{type:typeof n,isArray:Array.isArray(n),hasData:null!=n,properties:n?Object.keys(n):[],dataPreview:n?JSON.stringify(n).substring(0,200)+"...":"null"}),(0,s.extractDataFromResponse)(n,{logger:p,operationName:"updateTask",defaultValue:{id:h,status:"completed"}}),p.info("Successfully completed task",{taskId:h,recordId:v?.id})
|
|
234
|
+
const o=k.requestId,i=k.requestId
|
|
235
|
+
let a=`Task ${k.sequenceNumber&&i?(0,l.formatTaskRef)(i,k.sequenceNumber):h} (${k.title}) has been marked as completed.`
|
|
236
|
+
if(v?.id&&(a+=`\n[RECORD:${v.id}]`),b&&(a+="\nCommit: "+b.substring(0,8)),o)try{const e=await w.listTasks({requestId:o})
|
|
237
|
+
p.info("Raw tasks list response data",{responseData:JSON.stringify(e)}),p.debug("Tasks list response structure",{type:typeof e,isArray:Array.isArray(e),hasData:null!=e,properties:e?Object.keys(e):[],dataPreview:e?JSON.stringify(e).substring(0,200)+"...":"null"})
|
|
238
|
+
const t=(0,s.extractArrayFromResponse)(e,{logger:p,operationName:"listTasksForProgress",defaultValue:[]}),r=t.length,n=t.filter((e=>"completed"===e.status)).length
|
|
239
|
+
p.info("Task progress check",{requestId:o,totalTasks:r,completedTasks:n}),a+=`\n\nTask Progress: ${n}/${r} tasks completed`,n===r&&(a+=`\n\nAll tasks for request ${o} are now completed! You may consider marking the request as completed using the complete-request tool.`)}catch(e){p.warn("Failed to check task progress",{error:(0,c.getErrorMessage)(e),requestId:o})}return f({success:!0}),{content:[{type:"text",text:a}]}}catch(e){throw p.error("Failed to complete task",{error:e instanceof Error?e.stack:e+"",taskId:h}),Error("Failed to complete task: "+(0,c.getErrorMessage)(e))}}catch(t){if(p.error("Failed to complete task",{error:t instanceof Error?t.stack:t+"",args:e}),d.projectId)try{const r=u.getToolRecordClient()
|
|
237
240
|
if(r){const o=t instanceof n.NotFoundError||t instanceof n.ValidationError||t instanceof i.ZodError
|
|
238
|
-
await r.createToolRecord({...o?{}:{taskId:e.taskId},projectId:
|
|
241
|
+
await r.createToolRecord({...o?{}:{taskId:e.taskId},projectId:d.projectId,type:"complete-task",metadata:{status:"failed",timestamp:(new Date).toISOString(),taskTitle:e.summary?.substring(0,100)+(e.summary?.length>100?"...":""),error:(0,c.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",attemptedTaskId:e.taskId,taskIdValidationFailed:o},note:"Failed to complete task "+e.taskId})}}catch(e){p.error("Failed to create failure record for task completion",{error:e instanceof Error?e.message:e+""})}f({success:!1,error:t instanceof Error?t.name:"unknown"})
|
|
239
242
|
let r=(0,c.getErrorMessage)(t)
|
|
240
243
|
return t instanceof n.NotFoundError&&(r=`The task ID "${e.taskId}" was not found. Please provide a valid task ID.`),t instanceof o.ConnectionError&&(r="Unable to complete task: Connection to the server failed. Please check your network connection and try again."),t instanceof i.ZodError&&t.errors.length>0&&(r=t.errors[0].message),{content:[{type:"text",text:"Error: "+r}],isError:!0}}}
|
|
241
|
-
const r=t(6183),n=t(9860),o=t(5674),s=t(2960),i=t(1569),a=t(5172),c=t(8824)},405(e,exports,t){"use strict"
|
|
244
|
+
const r=t(6183),n=t(9860),o=t(5674),s=t(2960),i=t(1569),a=t(5172),c=t(8824),l=t(4466)},405(e,exports,t){"use strict"
|
|
242
245
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
243
246
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
244
247
|
o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[]
|
|
@@ -274,14 +277,18 @@ if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
|
274
277
|
return o(t,e),t})
|
|
275
278
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleTaskOperations=async function(e,t,r,n,o){const s=n.child({tool:"task_operations"})
|
|
276
279
|
try{e?.list?.filters&&"object"==typeof e.list.filters?(Object.assign(e,e.list.filters),delete e.list):e?.list&&"object"==typeof e.list&&(Object.assign(e,e.list),delete e.list)
|
|
277
|
-
const n=a.validateArgs(e,i.TaskOperationsSchema),{taskId:
|
|
278
|
-
let
|
|
279
|
-
switch(s.info("Processing task_operations",{taskId:
|
|
280
|
+
const n=a.validateArgs(e,i.TaskOperationsSchema),{taskId:h,operation:g}=n
|
|
281
|
+
let p
|
|
282
|
+
switch(s.info("Processing task_operations",{taskId:h,operation:g}),g){case"create":s.info("Routing to create-task handler",{requestId:n.requestId,title:n.title}),p=await(0,u.handleCreateTask)({requestId:n.requestId,title:n.title,description:n.description},t,r,s,o)
|
|
280
283
|
break
|
|
281
|
-
case"
|
|
284
|
+
case"complete":s.info("Routing to complete-task handler",{taskId:h}),p=await(0,c.handleCompleteTask)({taskId:h,summary:n.summary},t,r,s,o)
|
|
282
285
|
break
|
|
283
|
-
|
|
284
|
-
|
|
286
|
+
case"get-info":s.info("Routing to get-task-information handler",{taskId:h}),p=await(0,l.handleGetTaskInformation)({taskId:h},t,r,s,o)
|
|
287
|
+
break
|
|
288
|
+
case"list":s.info("Routing to list-tasks handler",{requestId:n.requestId}),p=await(0,d.handleListTasks)({requestId:n.requestId,filters:{status:n.status,limit:n.limit,offset:n.offset,sortBy:n.sortBy,sortDirection:n.sortDirection}},t,r,s,o)
|
|
289
|
+
break
|
|
290
|
+
default:throw Error(`Unknown operation: ${g}. Valid operations: create, complete, get-info, list`)}return s.info("task_operations completed",{taskId:h,operation:g,success:!p.isError}),o.incrementCounter("task_operations_total",1,{operation:g,success:!p.isError}),p}catch(e){return s.error("task_operations failed",{error:e instanceof Error?e.stack:e+""}),o.incrementCounter("task_operations_errors",1),{content:[{type:"text",text:"\u274c **Task Operations Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
|
|
291
|
+
const i=t(6183),a=s(t(5967)),c=t(355),l=t(3420),d=t(9863),u=t(76),h=t(8824)},441(e,exports){"use strict"
|
|
285
292
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.BAD_REQUEST=exports.INTERNAL_ERROR=exports.NOT_FOUND=exports.FORBIDDEN=exports.UNAUTHORIZED=exports.VALIDATION_ERROR=exports.MCP_PROTOCOL_ERROR=exports.REQUEST_VALIDATION_FAILED=exports.REQUEST_ID_INVALID_FORMAT=exports.REQUEST_NOT_FOUND=exports.CONNECTION_ERROR=exports.SERVICE_UNAVAILABLE=exports.CONNECTION_TIMEOUT=exports.SERVER_ERROR=exports.NETWORK_ERROR=exports.TASK_VALIDATION_FAILED=exports.TASK_ID_INVALID_FORMAT=exports.TASK_NOT_FOUND=void 0,exports.TASK_NOT_FOUND="TASK_NOT_FOUND",exports.TASK_ID_INVALID_FORMAT="TASK_ID_INVALID_FORMAT",exports.TASK_VALIDATION_FAILED="TASK_VALIDATION_FAILED",exports.NETWORK_ERROR="NETWORK_ERROR",exports.SERVER_ERROR="SERVER_ERROR",exports.CONNECTION_TIMEOUT="CONNECTION_TIMEOUT",exports.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",exports.CONNECTION_ERROR="CONNECTION_ERROR",exports.REQUEST_NOT_FOUND="REQUEST_NOT_FOUND",exports.REQUEST_ID_INVALID_FORMAT="REQUEST_ID_INVALID_FORMAT",exports.REQUEST_VALIDATION_FAILED="REQUEST_VALIDATION_FAILED",exports.MCP_PROTOCOL_ERROR="MCP_PROTOCOL_ERROR",exports.VALIDATION_ERROR="VALIDATION_ERROR",exports.UNAUTHORIZED="UNAUTHORIZED",exports.FORBIDDEN="FORBIDDEN",exports.NOT_FOUND="NOT_FOUND",exports.INTERNAL_ERROR="INTERNAL_ERROR",exports.BAD_REQUEST="BAD_REQUEST"},446(e,exports,t){"use strict"
|
|
286
293
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.LockOverrideManager=void 0,exports.createLockOverrideManager=function(e){return new n(e)}
|
|
287
294
|
const r=t(6982)
|
|
@@ -367,22 +374,23 @@ var t={}
|
|
|
367
374
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
368
375
|
return o(t,e),t})
|
|
369
376
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleQueryHistory=async function(e,r,n,o,s,g){const p=o.child({tool:"query_history"})
|
|
370
|
-
try{const
|
|
371
|
-
let
|
|
372
|
-
switch(p.info("Processing query_history request",{queryType:
|
|
377
|
+
try{const h=a.validateArgs(e,i.QueryHistorySchema),{queryType:f}=h
|
|
378
|
+
let m
|
|
379
|
+
switch(p.info("Processing query_history request",{queryType:f}),f){case"file-history":p.info("Routing to file-history handler",{path:h.fileHistory.path}),m=await(0,c.handleFileHistory)({path:h.fileHistory.path,limit:h.fileHistory.limit,showDiff:h.fileHistory.showDiff,showTraceability:h.fileHistory.showTraceability,branch:h.fileHistory.branch,since:h.fileHistory.since},r,n,p,s)
|
|
373
380
|
break
|
|
374
|
-
case"request-file-history":p.info("Routing to request-file-history handler",{requestId:
|
|
381
|
+
case"request-file-history":p.info("Routing to request-file-history handler",{requestId:h.requestHistory.requestId}),m=await(0,l.handleRequestFileHistory)({requestId:h.requestHistory.requestId,showDiff:h.requestHistory.showDiff,detailLevel:h.requestHistory.detailLevel,taskId:h.requestHistory.taskId,fileFilter:h.requestHistory.fileFilter},r,n,p,s)
|
|
375
382
|
break
|
|
376
|
-
case"recover":p.info("Routing to file-recover handler",{
|
|
377
|
-
let
|
|
378
|
-
if(!
|
|
379
|
-
try{const{execSync:r}=await Promise.resolve().then(t.t.bind(t,5317,23)),o=r(`git log --format=%H -n 2 -- "${
|
|
380
|
-
if(
|
|
381
|
-
p.info("Auto-resolved previous version",{filePath:
|
|
383
|
+
case"recover":p.info("Routing to file-recover handler",{path:h.recover.path,commitHash:h.recover.commitHash})
|
|
384
|
+
let i=h.recover.commitHash
|
|
385
|
+
if(!i){const e=h.recover.path,n=r.workspaceManager?.getCurrentContext(r.currentSessionId)?.basePath||r.basePath||process.cwd(),{resolve:o}=await Promise.resolve().then(t.t.bind(t,6928,23)),s=o(n,e)
|
|
386
|
+
try{const{execSync:r}=await Promise.resolve().then(t.t.bind(t,5317,23)),o=r(`git log --format=%H -n 2 -- "${s}"`,{cwd:n,encoding:"utf8"}).trim().split("\n").filter(Boolean)
|
|
387
|
+
if(i=o[1]||o[0],!i)return{content:[{type:"text",text:"No previous versions found for "+e}],isError:!0}
|
|
388
|
+
p.info("Auto-resolved previous version",{filePath:e,commitHash:i})}catch{return{content:[{type:"text",text:"Could not find previous versions of "+e}],isError:!0}}}m=await(0,d.handleFileRecover)({taskId:e.recover?.taskId||await(async()=>{const{resolveActiveTaskId:e}=await Promise.resolve().then(t.bind(t,3451))
|
|
389
|
+
return await e(r,n,o)||"untracked"})(),path:h.recover.path,commitHash:i,createBackup:h.recover.createBackup},r,n,n.getToolRecordClient(),p,s,g)
|
|
382
390
|
break
|
|
383
|
-
case"blame":p.info("Routing to file-blame handler",{path:
|
|
391
|
+
case"blame":p.info("Routing to file-blame handler",{path:h.blame.path,lines:h.blame.lines}),m=await(0,u.handleFileBlame)({path:h.blame.path,lines:h.blame.lines,branch:h.blame.branch},r,n,p,s)
|
|
384
392
|
break
|
|
385
|
-
default:throw Error("Unknown query type: "+
|
|
393
|
+
default:throw Error("Unknown query type: "+f)}return p.info("query_history request completed",{queryType:f,success:!m.isError}),s.incrementCounter("query_history_total",1,{success:!m.isError,queryType:f}),m}catch(e){return p.error("query_history request failed",{error:e instanceof Error?e.stack:e+""}),s.incrementCounter("query_history_errors",1),{content:[{type:"text",text:"\u274c **Query History Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
|
|
386
394
|
const i=t(6183),a=s(t(5967)),c=t(8828),l=t(8317),d=t(4640),u=t(4811),h=t(8824)},1038(e,exports){"use strict"
|
|
387
395
|
function t(e){let t
|
|
388
396
|
if("string"==typeof e.metadata&&e.metadata)try{t=JSON.parse(e.metadata)}catch(e){t=void 0}else e.metadata&&"object"==typeof e.metadata&&(t=e.metadata)
|
|
@@ -440,21 +448,21 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
440
448
|
var t={}
|
|
441
449
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
442
450
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
443
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerApiRoutes=async function(e,r,n,o){const s=n.child({component:"api"}),i=r.getTokenManager(),T=process.env.REMOTE_SERVER_URL||"https://api.alchemylabcode.com",P=new m.AuthenticationManager(i,n.child({component:"auth-manager"})),j=P.getTokenSynchronizer(),
|
|
451
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.registerApiRoutes=async function(e,r,n,o){const s=n.child({component:"api"}),i=r.getTokenManager(),T=process.env.REMOTE_SERVER_URL||"https://api.alchemylabcode.com",P=new m.AuthenticationManager(i,n.child({component:"auth-manager"})),j=P.getTokenSynchronizer(),x=await P.getTokenString()||void 0
|
|
444
452
|
n.debug("Token retrieved from authentication manager")
|
|
445
|
-
const
|
|
453
|
+
const R=new k.ConnectionStatusManager(T,n.child({component:"connection-status-manager"}),o,{checkIntervalMs:3e4,timeoutMs:5e3}),M=new w.ProjectClient(T,n.child({component:"project-client"}),o,R,x)
|
|
446
454
|
j.registerClient(M)
|
|
447
|
-
const O=new b.TaskClient(T,n.child({component:"task-client"}),o,M,x
|
|
455
|
+
const O=new b.TaskClient(T,n.child({component:"task-client"}),o,M,R,x)
|
|
448
456
|
j.registerClient(O)
|
|
449
|
-
const $=new v.FileOperationsClient(T,n.child({component:"file-client"}),o,M,R
|
|
457
|
+
const $=new v.FileOperationsClient(T,n.child({component:"file-client"}),o,M,x,R)
|
|
450
458
|
j.registerClient($)
|
|
451
|
-
const D=new C.ProxyClient(T,n.child({component:"proxy-client"}),o,M,R
|
|
459
|
+
const D=new C.ProxyClient(T,n.child({component:"proxy-client"}),o,M,x,R)
|
|
452
460
|
j.registerClient(D)
|
|
453
|
-
const A=new _.RequestClient(T,n.child({component:"request-client"}),o,M,R
|
|
454
|
-
A.setAuthToken(
|
|
455
|
-
const F=new E.DocumentClient(T,n.child({component:"document-client"}),o,M,R
|
|
461
|
+
const A=new _.RequestClient(T,n.child({component:"request-client"}),o,M,x,R)
|
|
462
|
+
A.setAuthToken(x),(0,d.isDebugToolsEnabled)()&&n.debug("Explicitly set token on RequestClient",{tokenPresent:!!x}),j.registerClient(A)
|
|
463
|
+
const F=new E.DocumentClient(T,n.child({component:"document-client"}),o,M,x,R)
|
|
456
464
|
j.registerClient(F)
|
|
457
|
-
const N=new q.ToolRecordClient(T,n.child({component:"tool-record-client"}),o,M,R
|
|
465
|
+
const N=new q.ToolRecordClient(T,n.child({component:"tool-record-client"}),o,M,x,R)
|
|
458
466
|
j.registerClient(N)
|
|
459
467
|
const L=new S.ApiClient(P,M,O,$,A,F,N,D,n.child({component:"api-client"})),z=a.default.Router();(0,h.registerAuthRoutes)(z,{projectClient:M,taskClient:O,fileClient:$,authManager:P,apiClient:L},i,n)
|
|
460
468
|
const H=r.getContext();(0,g.registerConfigRoutes)(z,n,H.basePath),e.use("/api",z)
|
|
@@ -510,7 +518,7 @@ e({endpoint:"git/status",method:"GET",success:!0}),t.json({success:!0,data:{curr
|
|
|
510
518
|
const s=B("api_request_duration"),i=r.getContext(),{message:a,taskId:c}=e.body
|
|
511
519
|
if(!a)throw(0,u.createValidationError)("Commit message is required")
|
|
512
520
|
let l=i.git
|
|
513
|
-
if(i.workspaceManager){const e=i.workspaceManager.getCurrentContext()
|
|
521
|
+
if(i.workspaceManager){const e=i.workspaceManager.getCurrentContext(i.currentSessionId)
|
|
514
522
|
if("multi-agent"===e.mode&&e.requestId){if(!e.basePath.includes("/worktrees/")&&!e.basePath.includes("\\worktrees\\"))throw(0,u.createValidationError)(`Multi-agent mode error: Cannot commit from main repo context. Expected worktree path but got: ${e.basePath}. This would commit to main branch instead of request branch.`)
|
|
515
523
|
const{simpleGit}=t(3807)
|
|
516
524
|
l=simpleGit(e.basePath)}}if(!l)throw s({endpoint:"git/commit",method:"POST",success:!1,error:"no_git"}),(0,u.createValidationError)("Git is not available for this workspace")
|
|
@@ -654,22 +662,22 @@ if(!n||""===n.trim())return l.info("Empty needle detected, switching to list-all
|
|
|
654
662
|
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")
|
|
655
663
|
let C
|
|
656
664
|
if(b.searchDirectory=p||".",p){const{normalizedPath:e,fullPath:r}=m.validateAndNormalizePath(p,t)
|
|
657
|
-
C=r}else C=t.basePath
|
|
665
|
+
C=r}else C=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
|
|
658
666
|
b.resolvedPath=C
|
|
659
667
|
let _=!1
|
|
660
668
|
try{_=(await g.default.stat(C)).isFile()}catch(e){const t=`Cannot access path ${C}: ${(0,k.getErrorMessage)(e)}`
|
|
661
669
|
throw b.errors.push(t),Error(t)}const E=v.maxResults||50,q=v.caseSensitive||!1,S=v.useRegex||!1,T=v.fileExtension,P=v.searchIn||"content"
|
|
662
670
|
let j=void 0!==v.contextLines?v.contextLines:0
|
|
663
671
|
if(0>j?j=0:j>10&&(l.warn(`contextLines ${j} exceeds maximum of 10, clamping to 10`),j=10),!_&&!T)throw b.errors.push('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")'),(0,f.createValidationError)('File extension is required for directory search (use "*" for any extension, or formats like "ts", ".ts", "*.ts")')
|
|
664
|
-
let R
|
|
665
|
-
if(_)
|
|
666
|
-
else if("*"===T)
|
|
667
|
-
else if(T){let e=T;(e.startsWith("*.")||e.startsWith("*"))&&(e=e.substring(1)),
|
|
668
|
-
throw b.errors.push(t),(0,f.createValidationError)(t)}if(b.patternInfo={needle:n,regex:
|
|
672
|
+
let x,R=""
|
|
673
|
+
if(_)R="*"
|
|
674
|
+
else if("*"===T)R="*"
|
|
675
|
+
else if(T){let e=T;(e.startsWith("*.")||e.startsWith("*"))&&(e=e.substring(1)),R=e.startsWith(".")?e:"."+e}try{x=S?q?RegExp(n):RegExp(n,"i"):q?RegExp(o(n)):RegExp(o(n),"i")}catch(e){const t=`Invalid ${S?"regex":"search"} pattern: ${(0,k.getErrorMessage)(e)}`
|
|
676
|
+
throw b.errors.push(t),(0,f.createValidationError)(t)}if(b.patternInfo={needle:n,regex:x.toString(),caseSensitive:q,fileExtension:T,normalizedExtension:R},!_)try{const e=Date.now(),t=await g.default.readdir(C,{withFileTypes:!0}),r=[],n=[]
|
|
669
677
|
for(const e of t)e.isDirectory()?r.push(e.name):e.isFile()&&n.push(e.name)
|
|
670
678
|
b.initialScan={totalEntries:t.length,directories:r,files:n,firstFewFiles:n.slice(0,10),scanTime:Date.now()-e},b.phases.directoryListingTime=b.initialScan.scanTime}catch(e){const t="Failed to scan directory contents: "+(0,k.getErrorMessage)(e)
|
|
671
679
|
b.errors.push(t),l.error(t)}const M=_?"file":"directory"
|
|
672
|
-
l.info(`Searching for "${n}" in ${M} ${C} (mode: ${P})`,{needle:n,searchTarget:M,path:C,options:{maxResults:E,caseSensitive:q,fileExtension:
|
|
680
|
+
l.info(`Searching for "${n}" in ${M} ${C} (mode: ${P})`,{needle:n,searchTarget:M,path:C,options:{maxResults:E,caseSensitive:q,fileExtension:R,searchIn:P}}),I=Date.now(),b.phases.initializationTime=I-u
|
|
673
681
|
const O=Date.now()
|
|
674
682
|
let $=[],D=0,A=0
|
|
675
683
|
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=[]
|
|
@@ -687,15 +695,15 @@ o.errors.push(r),n.error(r)}return{matches:i,totalFiles:1}}(e,t,l,s,i,u)
|
|
|
687
695
|
const f={path:e,filesProcessed:0,filesMatched:0,subdirectories:0,errors:[]}
|
|
688
696
|
try{const{filesCount:n,fileMatchesCount:c,subdirCount:d,subdirStats:h}=await r(e,t,p,a,o,s,0,f,l,u)
|
|
689
697
|
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)
|
|
690
|
-
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,
|
|
698
|
+
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,x,{maxResults:E,fileExtension:R,searchIn:P,isFile:_,contextLines:j},R,l,b)
|
|
691
699
|
$=e.matches,D=e.totalFiles
|
|
692
700
|
const t=1e3
|
|
693
701
|
$.length>0&&$.length<=t?($.sort(((e,t)=>void 0!==e.modifiedTime&&void 0!==t.modifiedTime?t.modifiedTime-e.modifiedTime:void 0!==e.modifiedTime&&void 0===t.modifiedTime?-1:void 0===e.modifiedTime&&void 0!==t.modifiedTime?1:0)),l.info(`Sorted ${$.length} matches by modification time (newest first)`)):$.length>t&&l.info(`Skipped sorting ${$.length} matches (exceeds hard cap of ${t} for performance)`),A=$.length,$.length>E&&($=$.slice(0,E),l.info(`Limited results to ${E} (from ${A} total matches)`)),$.forEach((e=>{e.relativePath=function(e,t){const r=h.default.relative(e,t)
|
|
694
702
|
return r?r===h.default.basename(t)?r:r.startsWith("./")?r.substring(2):r:h.default.basename(t)}(C,e.file)})),l.info(`Local search completed: found ${A||$.length} total matches in ${D} files, returning ${$.length} results`),b.phases.searchTime=Date.now()-O}catch(e){const t="Error during search: "+(0,k.getErrorMessage)(e)
|
|
695
703
|
b.errors.push(t),l.error(t),b.phases.searchTime=Date.now()-O}b.totalFiles=D,b.totalMatches=$.length,b.endTime=Date.now()
|
|
696
704
|
let F,N=""
|
|
697
|
-
try{if(t.
|
|
698
|
-
e.
|
|
705
|
+
try{if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
706
|
+
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})
|
|
699
707
|
const L="content"===P?"content":"filename"===P?"filenames":"content and filenames"
|
|
700
708
|
if(A>$.length?(F=`Found ${A} results for "${n}" (searching ${L})`,p&&(F+=" in "+p),T&&(F+=" with extension "+T),F+=`${N}. Showing first ${$.length}:\n\n`):(F=`Found ${$.length} results for "${n}" (searching ${L})`,p&&(F+=" in "+p),T&&(F+=" with extension "+T),F+=N+":\n\n"),$.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))
|
|
701
709
|
if(0===n.length)return{filenameMatches:r,mergedGroups:[]}
|
|
@@ -826,7 +834,7 @@ if(r&&!o){const t=r[1]
|
|
|
826
834
|
v=!0
|
|
827
835
|
try{const{sessionTag:r}=(0,h.getGlobalClientInfo)(),o=n.getSessionTagMappingClient(),s=n.getRequestClient(),i=o?o.getMappingByOpencodeSessionId(e.sessionId).then((t=>{t?((0,h.setSessionTag)(t.sessionTag),m.info("Recovered session tag from mapping",{opencodeSessionId:e.sessionId,sessionTag:t.sessionTag})):(o.createOrUpdateMapping(r,e.sessionId).catch((()=>{})),m.info("Registered session tag mapping",{opencodeSessionId:e.sessionId,sessionTag:r}))}),(e=>m.debug("Mapping lookup failed",{error:(0,l.getErrorMessage)(e)}))):Promise.resolve(),a=s.lockRequest?s.lockRequest(t,r).then((e=>{e.locked?m.info("Acquired request lock",{requestId:t,sessionTag:r}):m.warn("Failed to acquire request lock",{requestId:t,sessionTag:r})}),(e=>m.warn("Lock acquisition failed",{error:(0,l.getErrorMessage)(e)}))):Promise.resolve()
|
|
828
836
|
await Promise.all([i,a])}catch(e){m.warn("Error in session tag mapping / lock acquisition",{error:(0,l.getErrorMessage)(e)})}}}}let q
|
|
829
|
-
if(C){const e={context:t,apiClient:n,logger:o,metrics:s,mcpServer:g,cliOrigin:_}
|
|
837
|
+
if(t&&(t.currentSessionId=E||"__unknown__"),C){const e={context:t,apiClient:n,logger:o,metrics:s,mcpServer:g,cliOrigin:_}
|
|
830
838
|
q=await C.handler(b,e)}else m.info(`Tool ${i} not found, returning negative response`),q={content:[{type:"text",text:`The tool '${i}' does not exist.`}]}
|
|
831
839
|
return Date.now(),Date.now(),k({tool:i,success:!0}),q}catch(t){m.error("Error executing tool:",{error:t instanceof Error?t.stack:t+"",tool:e.params.name}),s.incrementCounter("tool_errors_total",1,{tool:e.params.name,error:t instanceof Error?t.name:"unknown"})
|
|
832
840
|
let r="Unknown error"
|
|
@@ -848,7 +856,8 @@ var g=t(7280)
|
|
|
848
856
|
Object.defineProperty(exports,"logSessionIdentity",{enumerable:!0,get(){return g.logSessionIdentity}})
|
|
849
857
|
const p=t(7280)
|
|
850
858
|
t(2462)
|
|
851
|
-
const f=t(2245)
|
|
859
|
+
const f=t(2245)
|
|
860
|
+
i(t(857))},1483(e,exports,t){"use strict"
|
|
852
861
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSearchDocuments=async function(e,t,s,i,a){const c=i.child({tool:"search_documents"}),l=a.startTimer("tool_execution_time")
|
|
853
862
|
try{let i
|
|
854
863
|
try{i=r.SearchDocumentsSchema.parse(e)}catch(t){if(t instanceof n.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
@@ -1193,7 +1202,7 @@ if(u=e?.requestContextMode,!u){const e=(0,S.getBuiltInAgentConfig)(i)
|
|
|
1193
1202
|
u=e?.requestContextMode}}catch{}if(u&&"none"!==u&&!c)return{content:[{type:"text",text:`\u274c Agent '${i}' requires a requestId to be provided.\n\nThis agent has requestContextMode: '${u}' which means it needs to work in the context of a specific request.\n\nPlease provide a requestId when spawning this agent.`}],isError:!0}
|
|
1194
1203
|
const h=await(0,k.getServerUrl)(t,n)
|
|
1195
1204
|
r(t,"serverUrl resolved",{serverUrl:h})
|
|
1196
|
-
const g=t.basePath
|
|
1205
|
+
const g=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
|
|
1197
1206
|
if(!g)throw new y.ValidationError("Working directory not available in context")
|
|
1198
1207
|
const p=s?.sessionId
|
|
1199
1208
|
let f=""
|
|
@@ -1338,18 +1347,22 @@ var t={}
|
|
|
1338
1347
|
if(null!=e)for(var r=g(e),n=0;n<r.length;n++)"default"!==r[n]&&p(t,e,r[n])
|
|
1339
1348
|
return f(t,e),t})
|
|
1340
1349
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpawn=n,exports.handleContinue=o,exports.handleCheckStatus=d,exports.handleAbort=u,exports.handleListSessions=h,exports.handleSubagentOperations=async function(e,t,r,s,i,a){const c=r.child({tool:"subagent_operations"}),l=s.startTimer("tool_execution_time")
|
|
1341
|
-
try{if(e
|
|
1350
|
+
try{if(e?.spawn&&"object"==typeof e.spawn){const t=e.spawn
|
|
1351
|
+
e.agent=e.agent||t.agent,e.prompt=e.prompt||t.prompt,e.description=e.description||t.description,e.requestId=e.requestId||t.requestId,e.allowParallel=e.allowParallel??t.allowParallel,e.useExistingSession=e.useExistingSession||t.useExistingSession,delete e.spawn}if(e?.continue&&"object"==typeof e.continue){const t=e.continue
|
|
1352
|
+
e.prompt=e.prompt||t.prompt,delete e.continue}if(e?.readMessages&&"object"==typeof e.readMessages){const t=e.readMessages
|
|
1353
|
+
e.limit=e.limit??t.limit,delete e.readMessages}if(e?.listSessions&&"object"==typeof e.listSessions){const t=e.listSessions
|
|
1354
|
+
e.activeOnly=e.activeOnly??t.activeOnly,e.requestId=e.requestId||t.requestId,e.limit=e.limit??t.limit,e.minTokens=e.minTokens??t.minTokens,e.maxTokens=e.maxTokens??t.maxTokens,e.maxAgeHours=e.maxAgeHours??t.maxAgeHours,delete e.listSessions}!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="spawn":e.prompt&&e.sessionId?e.operation="continue":e.sessionId&&(e.operation="check-status")),e?.operation&&("spawn"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours):"continue"===e.operation?(delete e.agent,delete e.description,delete e.allowParallel,delete e.useExistingSession,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours,delete e.limit):"check-status"===e.operation||"abort"===e.operation?(delete e.agent,delete e.prompt,delete e.description,delete e.requestId,delete e.allowParallel,delete e.useExistingSession,delete e.limit,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours):"read-messages"===e.operation?(delete e.agent,delete e.prompt,delete e.description,delete e.requestId,delete e.allowParallel,delete e.useExistingSession,delete e.activeOnly,delete e.minTokens,delete e.maxTokens,delete e.maxAgeHours):"list-sessions"===e.operation&&(delete e.sessionId,delete e.agent,delete e.prompt,delete e.description,delete e.allowParallel,delete e.useExistingSession))
|
|
1342
1355
|
const r=C.validateArgs(e,v.SubagentOperationsSchema),{sessionId:g,operation:p}=r
|
|
1343
1356
|
let f
|
|
1344
|
-
switch(c.info("Processing subagent_operations",{operation:p,sessionId:g}),p){case"spawn":f=await n(r.
|
|
1357
|
+
switch(c.info("Processing subagent_operations",{operation:p,sessionId:g}),p){case"spawn":f=await n({agent:r.agent,prompt:r.prompt,requestId:r.requestId,allowParallel:r.allowParallel,useExistingSession:r.useExistingSession},t,c,i,a)
|
|
1345
1358
|
break
|
|
1346
|
-
case"continue":f=await o(g,r.
|
|
1359
|
+
case"continue":f=await o(g,r.prompt,t,c,i,void 0,a)
|
|
1347
1360
|
break
|
|
1348
1361
|
case"check-status":f=await d(g,t,c,i)
|
|
1349
1362
|
break
|
|
1350
1363
|
case"abort":f=await u(g,t,c)
|
|
1351
1364
|
break
|
|
1352
|
-
case"read-messages":const e=r.
|
|
1365
|
+
case"read-messages":const e=r.limit??1
|
|
1353
1366
|
f=await async function(e,t,r,n){const o=await(0,k.getServerUrl)(r,n)
|
|
1354
1367
|
if(!o)throw new y.ValidationError("Could not determine OpenCode server URL")
|
|
1355
1368
|
n.info("Reading messages from subagent session",{sessionId:e,limit:t})
|
|
@@ -1361,7 +1374,7 @@ const i=s.map(((e,t)=>{const r="user"===e.info.role?"USER":"ASSISTANT",n=e.parts
|
|
|
1361
1374
|
return`[${t+1}] ${r} (${new Date(e.info.time.created).toLocaleTimeString()}):\n${o}`})).join("\n\n---\n\n")
|
|
1362
1375
|
return{content:[{type:"text",text:`Session ${e} - Last ${s.length} messages:\n\n${i}`}]}}catch(e){throw Error("Failed to read messages: "+(0,_.getErrorMessage)(e))}}(g,e,t,c)
|
|
1363
1376
|
break
|
|
1364
|
-
case"list-sessions":const s={activeOnly:r.
|
|
1377
|
+
case"list-sessions":const s={activeOnly:r.activeOnly,requestId:r.requestId,limit:r.limit,minTokens:r.minTokens,maxTokens:r.maxTokens,maxAgeHours:r.maxAgeHours,parentSessionId:a?.sessionId}
|
|
1365
1378
|
f=await h(t,c,i,s)
|
|
1366
1379
|
break
|
|
1367
1380
|
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}}}
|
|
@@ -1520,7 +1533,7 @@ if(g.push("reqId: "+(t||"NONE")),t){const e=await o.proxyGet(`/api/projects/${n.
|
|
|
1520
1533
|
g.push(`runs: ${Array.isArray(r)?r.length:0}, withWorktree: ${s?.id||"NONE"}, path: ${s?.worktreePath||s?.worktree_path||"NONE"}`),s&&(h=s.worktreePath||s.worktree_path,c.info("Using test worktree from request test run",{worktreePath:h,reqId:t}))}}}catch(e){c.warn("Failed to resolve test worktree",{error:(0,r.getErrorMessage)(e)})}if(!h)return a({success:!1,error:"no_worktree"}),{content:[{type:"text",text:`No test worktree found.\n\nDiagnostics:\n${g.length>0?g.map((e=>"\u2022 "+e)).join("\n"):"\u2022 No session identity found"}\n\nEnsure this session is linked to a test process and a test run has been created.`}],isError:!0}
|
|
1521
1534
|
const p=[]
|
|
1522
1535
|
for(const t of l){c.info("Executing test command",{name:t.name,command:t.command,timeout:t.timeout,cwd:h})
|
|
1523
|
-
try{const e=d(t.command,{cwd:h,timeout:1e3*t.timeout,encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"/bin/sh",env:{...u.env,FORCE_COLOR:"0"}})
|
|
1536
|
+
try{const e=d(t.command,{cwd:h,timeout:1e3*t.timeout,encoding:"utf-8",stdio:["pipe","pipe","pipe"],shell:"win32"===process.platform?"cmd.exe":"/bin/sh",env:{...u.env,FORCE_COLOR:"0"}})
|
|
1524
1537
|
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
|
|
1525
1538
|
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})`
|
|
1526
1539
|
return`### ${e.name}: ${t}\n\`\`\`\n$ ${e.command}\n${e.output}\n\`\`\``})).join("\n\n")
|
|
@@ -1585,10 +1598,10 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSwitchToMai
|
|
|
1585
1598
|
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"})
|
|
1586
1599
|
let a=null
|
|
1587
1600
|
l.info("Checking for requests to unlock")
|
|
1588
|
-
try{const{sessionTag:e}=(0,o.getGlobalClientInfo)(),r=t.workspaceManager.getCurrentContext()
|
|
1601
|
+
try{const{sessionTag:e}=(0,o.getGlobalClientInfo)(),r=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
1589
1602
|
if(r.requestId&&"main"!==r.requestId){l.info("Unlocking current request before switching to main",{requestId:r.requestId,sessionTag:e})
|
|
1590
1603
|
try{const t=await i.unlockRequest(r.requestId,e)
|
|
1591
|
-
!1===t.locked?(a=r.requestId,l.info("Successfully unlocked request",{requestId:r.requestId,unlockedAt:t.unlockedAt})):l.warn("Request unlock returned unexpected result",{requestId:r.requestId,result:t})}catch(t){l.warn("Failed to unlock request (continuing with switch to main)",{requestId:r.requestId,sessionTag:e,error:t instanceof Error?t.message:t+""})}}else l.debug("No request context to unlock",{currentRequestId:r.requestId})}catch(e){l.warn("Error during request unlock check (continuing with switch)",{error:(0,s.getErrorMessage)(e)})}const u=await t.workspaceManager.switchToMain()
|
|
1604
|
+
!1===t.locked?(a=r.requestId,l.info("Successfully unlocked request",{requestId:r.requestId,unlockedAt:t.unlockedAt})):l.warn("Request unlock returned unexpected result",{requestId:r.requestId,result:t})}catch(t){l.warn("Failed to unlock request (continuing with switch to main)",{requestId:r.requestId,sessionTag:e,error:t instanceof Error?t.message:t+""})}}else l.debug("No request context to unlock",{currentRequestId:r.requestId})}catch(e){l.warn("Error during request unlock check (continuing with switch)",{error:(0,s.getErrorMessage)(e)})}const u=await t.workspaceManager.switchToMain(t.currentSessionId)
|
|
1592
1605
|
if(!u.success)throw(0,n.createServiceError)("Failed to switch to main: "+u.message,{error:u.message})
|
|
1593
1606
|
const h=Date.now()-d
|
|
1594
1607
|
c.recordValue("switch_to_main_branch_time",h),c.incrementCounter("switch_to_main_branch_success",1)
|
|
@@ -1669,57 +1682,58 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
1669
1682
|
var t={}
|
|
1670
1683
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
1671
1684
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
1672
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleMoveFiles=async function(e,
|
|
1673
|
-
let
|
|
1674
|
-
const
|
|
1675
|
-
try{const
|
|
1676
|
-
if(
|
|
1677
|
-
d.validateTaskIdFormat(
|
|
1678
|
-
const
|
|
1679
|
-
|
|
1680
|
-
const
|
|
1681
|
-
for(const e of h){const{normalizedPath:
|
|
1682
|
-
|
|
1683
|
-
const
|
|
1684
|
-
|
|
1685
|
-
const
|
|
1686
|
-
if(!
|
|
1687
|
-
throw Error(
|
|
1688
|
-
if(
|
|
1689
|
-
const e=await(0,g.commitUserChangesBeforeToolOperation)(
|
|
1690
|
-
e.userChangesCommitted&&(
|
|
1691
|
-
const{toolRecordId:
|
|
1692
|
-
|
|
1693
|
-
const
|
|
1694
|
-
let
|
|
1695
|
-
for(const e of
|
|
1685
|
+
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()
|
|
1686
|
+
let k,I,b=d.FileOperationPhase.VALIDATION
|
|
1687
|
+
const v={toolName:"move-files",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"move-files",metricsPrefix:"move_files",successMessage:"Successfully moved files",failureMessage:"Failed to move files"}
|
|
1688
|
+
try{const u=d.validateArgs(e,l.MoveFilesSchema),{operations:h,comment:C}=u,{resolveActiveTaskId:_}=await Promise.resolve().then(t.bind(t,3451)),E=e.taskId||await _(r,n,i)||"untracked"
|
|
1689
|
+
if(y.info("Moving multiple files and directories",{taskId:E,operationCount:h.length,comment:C}),!h||0===h.length)throw Error("At least one move operation must be specified")
|
|
1690
|
+
d.validateTaskIdFormat(E,y,f,v.metricsPrefix)
|
|
1691
|
+
const q=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
1692
|
+
y.info("Initial branch context",{initialBranch:q.branch,initialRequestId:q.requestId,isMain:q.isMain})
|
|
1693
|
+
const S=[]
|
|
1694
|
+
for(const e of h){const{normalizedPath:t,fullPath:n}=d.validateAndNormalizePath(e.source,r),{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(e.destination,r)
|
|
1695
|
+
S.push({source:t,destination:o,fullSource:n,fullDestination:s})}b=d.FileOperationPhase.TASK_VALIDATION,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1696
|
+
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),x=await d.autoPromoteTaskStatus(E,T.status,P,j.request?.status,S[0].source,n,s,y,f,v.metricsPrefix)
|
|
1697
|
+
x.taskPromoted&&y.info(`Auto-promoted task ${E} (${T.title||"Untitled"}) to in_progress for file operations`,{taskId:E,taskTitle:T.title,previousStatus:T.status,newStatus:x.newTaskStatus,operationCount:h.length}),x.requestPromoted&&y.info(`Auto-promoted request ${P} to in_progress for file operations`,{requestId:P,previousStatus:j.request?.status,newStatus:x.newRequestStatus,triggeringTaskId:E})
|
|
1698
|
+
const R=await d.ensureCorrectWorkspaceContext({taskPromoted:x.taskPromoted,requestId:P,context:r,operation:"move-files",logger:y,metrics:f,metricsPrefix:v.metricsPrefix})
|
|
1699
|
+
if(!R.success){if(R.isLockConflict)return{content:[{type:"text",text:"\u274c "+R.error}],isError:!0}
|
|
1700
|
+
throw Error(R.error)}let M={hadUserMods:!1,userModsCommitHash:void 0}
|
|
1701
|
+
if(r.git)try{y.debug("[MOVE-FILES] Checking for user changes before move operations")
|
|
1702
|
+
const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"move-files",{requestId:P,taskId:E,workspaceManager:r.workspaceManager},y,f)
|
|
1703
|
+
e.userChangesCommitted&&(y.debug("[MOVE-FILES] User changes committed before move operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),y.info("User changes committed before move-files operation",{taskId:E,moveOperationsCount:S.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}),M={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){y.debug("[MOVE-FILES] Pre-tool commit failed, continuing with move operations",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with move operation",{taskId:E,moveOperationsCount:S.length,error:e instanceof Error?e.message:e+""})}y.debug("[MOVE-FILES] Proceeding with move operations",{operationCount:S.length}),b=d.FileOperationPhase.RECORD_CREATION,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1704
|
+
const{toolRecordId:O,localToolRecordId:$}=await d.createFileOperationRecords(E,P,r.projectId,v.recordType,S[0].source,{operationCount:h.length,operations:S.map((e=>({source:e.source,destination:e.destination}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},n,o,y,f,v.metricsPrefix,m)
|
|
1705
|
+
k=O,I=O,b=v.fileOperationPhase,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1706
|
+
const D=[]
|
|
1707
|
+
let A=0
|
|
1708
|
+
for(const e of S){const t={operation:{source:e.source,destination:e.destination},success:!1}
|
|
1696
1709
|
try{try{await a.default.access(e.fullSource)}catch(t){throw Error("Source path not accessible: "+e.source)}const r=(await a.default.stat(e.fullSource)).isDirectory()
|
|
1697
1710
|
t.isDirectory=r
|
|
1698
1711
|
const n=c.default.dirname(e.fullDestination)
|
|
1699
|
-
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,
|
|
1700
|
-
|
|
1701
|
-
let
|
|
1702
|
-
if(
|
|
1703
|
-
const e=
|
|
1704
|
-
|
|
1705
|
-
const
|
|
1706
|
-
await d.updateFileOperationRecords(
|
|
1707
|
-
const
|
|
1708
|
-
let
|
|
1709
|
-
if(
|
|
1710
|
-
else if(
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1712
|
+
try{await a.default.mkdir(n,{recursive:!0})}catch(e){throw Error("Failed to create destination directory: "+n)}try{throw await a.default.access(e.fullDestination),Error("Destination already exists: "+e.destination)}catch(e){if(!(e instanceof Error&&e.message.includes("ENOENT")))throw e}await a.default.rename(e.fullSource,e.fullDestination),t.success=!0,A++,y.info("Successfully moved "+(r?"directory":"file"),{source:e.source,destination:e.destination,isDirectory:r})}catch(r){t.error=(0,p.getErrorMessage)(r),y.warn(`Failed to move ${e.source} to ${e.destination}`,{error:t.error})}D.push(t)}const F=Date.now()-w
|
|
1713
|
+
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)
|
|
1714
|
+
let N=null
|
|
1715
|
+
if(A>0){b=d.FileOperationPhase.GIT_COMMIT,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1716
|
+
const e=D.filter((e=>e.success)),t=1===e.length?`Move ${e[0].isDirectory?"directory":"file"} from ${e[0].operation.source} to ${e[0].operation.destination} - ${C}`:`Move ${e.length} ${1===e.length?"item":"items"} - ${C}`
|
|
1717
|
+
N=await d.commitToGit(E,S[0].destination,O,$,t,r,y,f,v.metricsPrefix)}b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,f.incrementCounter("move_files_phase",1,{phase:b})
|
|
1718
|
+
const L=D.filter((e=>e.success)),z=D.filter((e=>!e.success))
|
|
1719
|
+
await d.updateFileOperationRecords(E,k,I,S[0].source,v.recordType,A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,{status:A===h.length?"completed":"partial_success",commitHash:N?.commitHash,previousCommitHash:N?.previousCommitHash,operationCount:h.length,successCount:A,failureCount:h.length-A,successfulOperations:L.map((e=>({source:e.operation.source,destination:e.operation.destination,isDirectory:e.isDirectory}))),failedOperations:z.map((e=>({source:e.operation.source,destination:e.operation.destination,error:e.error}))),userComment:C,hadUserMods:M.hadUserMods,userModsCommitHash:M.userModsCommitHash},A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,n,o,y,f,v.metricsPrefix)
|
|
1720
|
+
const H=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
1721
|
+
let B=""
|
|
1722
|
+
if(A===h.length)B=`Successfully moved all ${h.length} ${1===h.length?"item":"items"}`
|
|
1723
|
+
else if(A>0){const e=D.filter((e=>!e.success))
|
|
1724
|
+
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"+D.map((e=>`\u2022 ${e.operation.source} \u2192 ${e.operation.destination}: ${e.error}`)).join("\n")
|
|
1725
|
+
if(N?.commitHash&&(B+="\nCommit: "+N.commitHash.substring(0,8)),H.requestId&&(B+="\nBranch: "+H.requestId),R.lockAcquired&&R.lockedRequestId){const e=r.workspaceManager?.getCurrentContext(r.currentSessionId)
|
|
1726
|
+
e?.permanentBranch||(B+="\n\u{1f512} **Locked request:** "+R.lockedRequestId)}return{content:[{type:"text",text:B}],isError:0===A}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
|
|
1727
|
+
await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"move-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment,error:(0,p.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:b,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:"Failed to move files - "+(0,p.getErrorMessage)(t)})}catch(t){y.error("Failed to create failure record for move-files operation",{error:t instanceof Error?t.message:t+"",taskId:e.taskId,operationCount:e.operations?.length||0})}const s=Date.now()-w
|
|
1728
|
+
if(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
|
|
1729
|
+
try{await d.updateFileOperationRecords(e.taskId,k,I,e.operations?.[0]?.source||"unknown",v.recordType,"Failed to move files",{status:"failed",error:(0,p.getErrorMessage)(t),operationCount:e.operations?.length||0,operations:e.operations||[],userComment:e.comment},"Failed to move files",n,o,y,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)}}
|
|
1716
1730
|
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"
|
|
1717
1731
|
module.exports=require("@modelcontextprotocol/sdk/server/sse.js")},2425(e,exports,t){"use strict"
|
|
1718
1732
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
1719
1733
|
const r=t(6183),n=t(3707)
|
|
1720
1734
|
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"
|
|
1721
1735
|
Object.defineProperty(exports,"__esModule",{value:!0})
|
|
1722
|
-
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(
|
|
1736
|
+
const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),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),x=t(8850),R=t(3556),M=t(1391),O=t(6315),$=t(7713),D=t(6252),A=t(213),F=t(7250),N=t(2425),L=t(1540),z=t(5767),H=t(4973),B=t(509),U=t(7613),G=t(3322),W=t(5247),V=t(8849),J=t(542);(0,r.registerTool)(n.def),(0,r.registerTool)(o.def),(0,r.registerTool)(s.def),(0,r.registerTool)(i.def),(0,r.registerTool)(a.def),(0,r.registerTool)(c.def),(0,r.registerTool)(l.def),(0,r.registerTool)(d.def),(0,r.registerTool)(u.def),(0,r.registerTool)(h.def),(0,r.registerTool)(g.def),(0,r.registerTool)(p.def),(0,r.registerTool)(f.def),(0,r.registerTool)(m.def),(0,r.registerTool)(y.def),(0,r.registerTool)(w.def),(0,r.registerTool)(k.def),(0,r.registerTool)(I.def),(0,r.registerTool)(b.def),(0,r.registerTool)(v.def),(0,r.registerTool)(S.def),(0,r.registerTool)(C.def),(0,r.registerTool)(_.def),(0,r.registerTool)(E.def),(0,r.registerTool)(q.def),(0,r.registerTool)(T.def),(0,r.registerTool)(P.def),(0,r.registerTool)(j.def),(0,r.registerTool)(x.def),(0,r.registerTool)(R.def),(0,r.registerTool)(M.def),(0,r.registerTool)(O.def),(0,r.registerTool)($.def),(0,r.registerTool)(D.def),(0,r.registerTool)(A.def),(0,r.registerTool)(F.def),(0,r.registerTool)(N.def),(0,r.registerTool)(L.def),(0,r.registerTool)(z.def),(0,r.registerTool)(H.def),(0,r.registerTool)(B.def),(0,r.registerTool)(U.def),(0,r.registerTools)(G.metaDefs),(0,r.registerTools)(W.testingDefs),(0,r.registerTools)(V.checkingDefs),(0,r.registerTools)(J.debugDefs),(0,t(2245).freezeRegistry)()},2478(e,exports){"use strict"
|
|
1723
1737
|
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"
|
|
1724
1738
|
async function r(e,t,r){if(C.has(r)&&_>=t){if(0===t)return 0
|
|
1725
1739
|
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]"
|
|
@@ -1795,7 +1809,7 @@ E=`Directory tree for ${C} (${m} levels):\n${l(c(e))}\n\n${t}`,q=d(e)}else E=`Di
|
|
|
1795
1809
|
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():""
|
|
1796
1810
|
let c
|
|
1797
1811
|
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)))
|
|
1798
|
-
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()
|
|
1812
|
+
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)
|
|
1799
1813
|
E+="\n\nBranch: "+(S?.branchName||"unknown")
|
|
1800
1814
|
const T=Date.now()-h
|
|
1801
1815
|
return a.recordValue("list_directory_time",T),a.recordValue("list_directory_entries",q),a.incrementCounter("list_directory_success",1),i.info("Successfully listed directory: "+C,{entryCount:q,levels:m,time:T}),{content:[{type:"text",text:E}]}}catch(e){const t=Date.now()-h
|
|
@@ -1930,7 +1944,7 @@ return`${r} ${i}${a} [${e.toUpperCase()}]: ${t}${c}`}))),g=n({logToFile:!1,conso
|
|
|
1930
1944
|
exports.default=g},2783(e,exports,t){"use strict"
|
|
1931
1945
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
1932
1946
|
const r=t(6183),n=t(410)
|
|
1933
|
-
exports.def={name:"task_operations",description:"Perform operations on
|
|
1947
|
+
exports.def={name:"task_operations",description:"Perform operations on tasks.\n\nOperations:\n\u2022 create - Create a task under a request (requestId + title + description)\n\u2022 complete - Mark a task as completed (taskId + summary)\n\u2022 get-info - Get detailed information about a task (taskId)\n\u2022 list - List and filter tasks for a request (requestId)\n\nTask IDs use req######+#NN format (e.g. req000005#03).",schema:r.TaskOperationsSchema,annotations:{title:"Task Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleTaskOperations)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},2903(e,exports,t){"use strict"
|
|
1934
1948
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
1935
1949
|
const r=t(6183),n=t(9442)
|
|
1936
1950
|
exports.def={name:"replace_in_files",description:'Replace text in multiple files/documents with progressive fuzzy matching in batch operations.\n\nAPI:\n\u2022 operations (required) - Array of file operations\n - path or documentId (required per operation) - Target file or document\n - replacements (required) - Array of {old, new, match_mode?} replacements\n - fuzzy_match (optional) - Override global fuzzy setting for this file\n\u2022 fuzzy_match (optional, default true) - Global fuzzy matching default\n\u2022 comment (required) - Description of changes\n\nSTRUCTURE: Each operation MUST contain a `replacements` array. Do NOT put old/new directly on the operation object.\n\nFUZZY MATCHING (progressive strategies):\n1. exact - Literal match\n2. whitespace_normalized - Collapse/trim whitespace\n3. whitespace_agnostic - Ignore all whitespace\n\nMATCH MODES (per replacement):\n\u2022 \'unique\' (default, safe) - Must find exactly 1 match. Fails with helpful candidates if multiple found.\n\u2022 \'all\' - Replaces all occurrences, returns details for each\n\nRETURNS:\nPer-operation, per-replacement results with line numbers, match types, and success/error details.\n\nEXAMPLES:\n- Single file: {"operations": [{"path": "file.ts", "replacements": [{"old": "oldAPI", "new": "newAPI"}]}], "comment": "Update API"}\n- Multi-file: {"operations": [{"path": "a.ts", "replacements": [...]}, {"path": "b.ts", "replacements": [...]}], "comment": "Refactor"}',schema:r.ReplaceInFilesSchema,annotations:{title:"Replace In Files (Fuzzy Batch)",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},createsRecords:!0,handler(e,t){return(0,n.handleReplaceInFiles)(e,t.context,t.apiClient.getTaskClient(),t.apiClient.getToolRecordClient(),t.apiClient.getRequestClient(),t.logger,t.metrics,t.mcpServer)}}},2960(e,exports){"use strict"
|
|
@@ -1985,8 +1999,8 @@ for(const e of h)p.push(r(e,t,0,l))
|
|
|
1985
1999
|
for(const e of g)p.push(n(e,t,0,l))
|
|
1986
2000
|
const f=await Promise.all(p)
|
|
1987
2001
|
let m=""
|
|
1988
|
-
if(t.
|
|
1989
|
-
e.
|
|
2002
|
+
if(t.workspaceManager)try{const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
2003
|
+
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
|
|
1990
2004
|
let I="## Read Files/Documents\n\n"
|
|
1991
2005
|
m&&(I+=m),I+=`**Total Requests:** ${k} - **Successful:** ${y} - **Failed:** ${w}\n\n`
|
|
1992
2006
|
for(let e=0;e<f.length;e++){const t=f[e]
|
|
@@ -2139,7 +2153,7 @@ if(!t.locked)return{content:[{type:"text",text:`\u274c Failed to acquire lock fo
|
|
|
2139
2153
|
d.info("Successfully acquired request lock",{requestId:h,sessionTag:e,lockedAt:t.lockedAt})}catch(t){d.error("Failed to acquire request lock",{requestId:h,sessionTag:e,error:t instanceof Error?t.message:t+""})
|
|
2140
2154
|
const r=t instanceof Error?t.message:t+""
|
|
2141
2155
|
return r.includes("already locked")?{content:[{type:"text",text:`\u274c Request ${h} is already locked by another agent. ${r}`}],isError:!0}:{content:[{type:"text",text:`\u274c Failed to acquire lock for request ${h}: ${r}`}],isError:!0}}}}catch(e){return d.error("Error checking/acquiring request lock",{requestId:h,error:(0,i.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c Failed to check request lock status: "+(0,i.getErrorMessage)(e)}],isError:!0}}d.info("Using unified workspace switching",{requestId:h})
|
|
2142
|
-
const p=await t.workspaceManager.switchToRequest(h,{isCompleted:"completed"===g.status})
|
|
2156
|
+
const p=await t.workspaceManager.switchToRequest(h,{isCompleted:"completed"===g.status,sessionId:t.currentSessionId})
|
|
2143
2157
|
if(!p.success){try{const{sessionTag:e}=(0,s.getGlobalClientInfo)()
|
|
2144
2158
|
d.warn("Workspace switch failed, attempting to release acquired lock",{requestId:h,sessionTag:e,switchError:p.message}),await a.unlockRequest(h,e),d.info("Successfully released lock after workspace switch failure",{requestId:h})}catch(e){d.error("Failed to release lock after workspace switch failure",{requestId:h,unlockError:e instanceof Error?e.message:e+""})}const e=p.message||"Unknown error"
|
|
2145
2159
|
if(e.includes("does not exist")||e.includes("Branch for request"))return{content:[{type:"text",text:`\u274c Branch for request ${h} does not exist. This can happen if:\n- Request was reverted (branch deleted during revert)\n- Request was completed and branch was cleaned up\n- Branch was manually deleted\n\nUse 'get-request-information' to check the request status.`}],isError:!0}
|
|
@@ -2229,57 +2243,58 @@ return t},o(e)},function(e){if(e&&e.__esModule)return e
|
|
|
2229
2243
|
var t={}
|
|
2230
2244
|
if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
2231
2245
|
return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2232
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceStrings=async function(e,
|
|
2233
|
-
let
|
|
2234
|
-
const
|
|
2235
|
-
try{const
|
|
2236
|
-
if(
|
|
2237
|
-
const
|
|
2238
|
-
|
|
2239
|
-
const
|
|
2240
|
-
for(const e of
|
|
2241
|
-
|
|
2242
|
-
if(
|
|
2243
|
-
for(const e of
|
|
2244
|
-
if(
|
|
2245
|
-
try{await(0,f.ensureDocumentsNotLocked)(e,
|
|
2246
|
-
throw e}}
|
|
2247
|
-
const
|
|
2248
|
-
let
|
|
2249
|
-
|
|
2250
|
-
let
|
|
2251
|
-
|
|
2252
|
-
const
|
|
2253
|
-
if(
|
|
2254
|
-
throw Error(
|
|
2255
|
-
for(let e=0;e<
|
|
2256
|
-
|
|
2257
|
-
throw e}
|
|
2258
|
-
const
|
|
2259
|
-
if(
|
|
2260
|
-
const e=await(0,p.commitUserChangesBeforeToolOperation)(
|
|
2261
|
-
e.userChangesCommitted&&(
|
|
2262
|
-
const
|
|
2263
|
-
let
|
|
2264
|
-
for(const e of
|
|
2246
|
+
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()
|
|
2247
|
+
let I,b,v=u.FileOperationPhase.VALIDATION
|
|
2248
|
+
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"}
|
|
2249
|
+
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"
|
|
2250
|
+
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")
|
|
2251
|
+
const P=E.filter((e=>e.path)),j=E.filter((e=>e.documentId))
|
|
2252
|
+
w.info("Operation breakdown",{fileOperations:P.length,documentOperations:j.length})
|
|
2253
|
+
const x=[]
|
|
2254
|
+
for(const e of P){const{normalizedPath:t,fullPath:n}=u.validateAndNormalizePath(e.path,r)
|
|
2255
|
+
x.push({type:"file",path:t,fullPath:n,replacements:e.replacements,mode:e.mode||"unique"})}const R=[]
|
|
2256
|
+
if(j.length>0&&!r.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
2257
|
+
for(const e of j)R.push({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode||"unique"})
|
|
2258
|
+
if(R.length>0&&r.apiClient){const e=R.map((e=>e.documentId))
|
|
2259
|
+
try{await(0,f.ensureDocumentsNotLocked)(e,r.apiClient,w,c,"replace-strings-documents")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2260
|
+
throw e}}v=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_strings_phase",1,{phase:v})
|
|
2261
|
+
const M=x.length>0?x[0].path:"document-operation",O=await u.validateTaskId(T,M,o,w,c,C.metricsPrefix),$=O?.requestId
|
|
2262
|
+
let D=null
|
|
2263
|
+
x.length>0&&$&&(D=await u.validateWorkItemStates(T,x[0].path,o,i,r,w,c,C.metricsPrefix))
|
|
2264
|
+
let A={taskPromoted:!1,requestPromoted:!1}
|
|
2265
|
+
x.length>0&&$&&D&&(A=await u.autoPromoteTaskStatus(T,O.status,$,D.request?.status,x[0].path,o,i,w,c,C.metricsPrefix),A.taskPromoted&&w.info("Auto-promoted task to in_progress for replace-strings operation",{taskId:T,requestId:$,previousStatus:O.status,newStatus:A.newTaskStatus,triggeringOperation:"replace-strings"}))
|
|
2266
|
+
const F=await u.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:$,context:r,operation:"replace-strings",logger:w,metrics:c,metricsPrefix:C.metricsPrefix})
|
|
2267
|
+
if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
|
|
2268
|
+
throw Error(F.error)}if(x.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:x.length,workspaceBasePath:r.workspaceManager?.getCurrentContext(r.currentSessionId).basePath})
|
|
2269
|
+
for(let e=0;e<x.length;e++){const t=x[e],n=P[e],{normalizedPath:o,fullPath:s}=u.validateAndNormalizePath(n.path,r)
|
|
2270
|
+
x[e]={...t,path:o,fullPath:s}}}if(R.length>0&&$)try{await(0,g.validateRequestStatusForDocumentOperation)($,i,w,c,"replace-strings-document")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2271
|
+
throw e}v=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_strings_phase",1,{phase:v})
|
|
2272
|
+
const N=[...x.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...R.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:L}=await u.createFileOperationRecords(T,$,r.projectId,C.recordType,M,{operationCount:E.length,fileOperations:x.length,documentOperations:R.length,operations:N,userComment:q},o,s,w,c,C.metricsPrefix,y)
|
|
2273
|
+
if(I=L,b=L,v=C.fileOperationPhase,c.incrementCounter("replace_strings_phase",1,{phase:v}),x.length>0&&r.git)try{w.debug("[REPLACE-STRINGS] Checking for user changes before replace operations")
|
|
2274
|
+
const e=await(0,p.commitUserChangesBeforeToolOperation)(r.git,"replace-strings",{requestId:$,taskId:T,workspaceManager:r.workspaceManager},w,c)
|
|
2275
|
+
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:x.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:x.length,error:e instanceof Error?e.message:e+""})}w.debug("[REPLACE-STRINGS] Proceeding with file operations",{fileCount:x.length})
|
|
2276
|
+
const z=[]
|
|
2277
|
+
let H=0,B=0
|
|
2278
|
+
for(const e of x){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
2265
2279
|
try{if(await l.default.access(e.fullPath),!(await l.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
|
|
2266
2280
|
const r=await l.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await n(r,e.replacements,e.mode)
|
|
2267
|
-
t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,o!==r?(await l.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,
|
|
2268
|
-
try{const o=await
|
|
2269
|
-
|
|
2281
|
+
t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,o!==r?(await l.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,B++,w.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,w.error("File operation failed",{path:e.path,error:t.error})}z.push(t)}for(const e of R){const t={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
2282
|
+
try{const o=await r.documentFileManager.getDocumentAsFile(e.documentId),s=r.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
2283
|
+
t.filename=s?.filename
|
|
2270
2284
|
const i=await l.default.readFile(o,"utf8"),{newContent:a,results:c}=await n(i,e.replacements,e.mode)
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
try{await
|
|
2274
|
-
let
|
|
2275
|
-
if(
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
for(const
|
|
2279
|
-
for(const
|
|
2280
|
-
const
|
|
2281
|
-
|
|
2282
|
-
|
|
2285
|
+
t.replacements=c,t.successfulReplacements=c.filter((e=>e.success)).length,t.failedReplacements=c.filter((e=>!e.success)).length,a!==i?(await l.default.writeFile(o,a,"utf8"),r.documentFileManager.markForSync(e.documentId),t.success=!0,B++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements})):0===t.failedReplacements&&(t.success=!0),H+=t.failedReplacements}catch(r){t.error=(0,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(R.length>0)try{for(const e of R){const t=z.find((t=>t.documentId===e.documentId))
|
|
2286
|
+
t?.success&&await r.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const U=await u.handleMultiFileGitCommit(T,x,z,B,{operationType:"Replace strings",toolRecordId:b,successField:"successfulReplacements",logger:w,metrics:c,metricsPrefix:"replace_strings"},r),G=u.processMultiFileOperationResults(z,"successfulReplacements"),{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q}=G
|
|
2287
|
+
try{await s.updateToolRecord(b,{metadata:{path:x.length>0?x[0].path:"document:"+R[0]?.documentId,status:K?"completed":"failed",error:K?void 0:V+" operations failed",totalOperations:z.length,successfulFiles:Y,failedFiles:Q,operations:N,totalSuccessfulReplacements:J,totalFailedReplacements:H,operationsWithChanges:B,processingTime:Date.now()-k,userComment:q,...x.length>0&&U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}},note:K?`String replacement completed: ${W}/${z.length} operations successful${x.length>0?" (committed to git)":""}`:`String replacement partially failed: ${V}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}u.formatMultiFileToolResponse("String Replacement",{successfulOperations:W,failedOperations:V,totalSuccessfulChanges:J,overallSuccess:K,successfulFiles:Y,failedFiles:Q},U,F)
|
|
2288
|
+
let Z="## String Replacement Results\n\n"
|
|
2289
|
+
if(r.workspaceManager){const e=r.workspaceManager.getCurrentContext(r.currentSessionId)
|
|
2290
|
+
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]
|
|
2291
|
+
if(Z+=`**Operation:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,"file"===e.type?Z+=`**File:** ${e.path}\n`:(Z+="**Document:** "+e.documentId,e.filename&&(Z+=` (${e.filename})`),Z+="\n"),e.error?Z+=`**Error:** ${e.error}\n`:(Z+=`**Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(Z+=`, ${e.failedReplacements} failed`),Z+="\n"),e.replacements.some((e=>!e.success))){Z+="**Failed Replacement Details:**\n"
|
|
2292
|
+
for(const t of e.replacements.filter((e=>!e.success)))Z+=`- "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}}else{Z+="**Summary:**\n",Z+=`- **Total Operations:** ${z.length}\n`,Z+=`- **Successful:** ${W}\n`,Z+=`- **Failed:** ${V}\n`,Z+=`- **Total Replacements:** ${J} successful, ${H} failed\n\n`,Z+="**Detailed Results:**\n\n"
|
|
2293
|
+
for(const e of z){if("file"===e.type?Z+=`### File: ${e.path}\n`:(Z+="### Document: "+e.documentId,e.filename&&(Z+=` (${e.filename})`),Z+="\n"),Z+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error?Z+=`- **Error:** ${e.error}\n`:(Z+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(Z+=`, ${e.failedReplacements} failed`),Z+="\n"),e.replacements.some((e=>!e.success))){Z+="- **Failed Replacement Details:**\n"
|
|
2294
|
+
for(const t of e.replacements.filter((e=>!e.success)))Z+=` - "${t.old_str}" \u2192 "${t.new_str}": ${t.error}\n`}Z+="\n"}}R.length>0&&(Z+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
2295
|
+
const X=Date.now()-k
|
|
2296
|
+
return w.info("Replace strings operation completed",{duration:X,success:K,totalOperations:z.length,successfulOperations:W,failedOperations:V}),c.incrementCounter("replace_strings_total",1,{success:K}),{content:[{type:"text",text:Z}],isError:!K}}catch(t){const r=Date.now()-k
|
|
2297
|
+
if(w.error("Replace strings operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),b)try{await s.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,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}}}
|
|
2283
2298
|
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"
|
|
2284
2299
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
2285
2300
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
@@ -2324,40 +2339,41 @@ var m=t(6539)
|
|
|
2324
2339
|
Object.defineProperty(exports,"ClientFactory",{enumerable:!0,get(){return m.ClientFactory}})
|
|
2325
2340
|
const y=t(6539)
|
|
2326
2341
|
exports.default={ClientFactory:y.ClientFactory}},3420(e,exports,t){"use strict"
|
|
2327
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleGetTaskInformation=async function(e,t,
|
|
2328
|
-
|
|
2329
|
-
const
|
|
2330
|
-
try{
|
|
2331
|
-
|
|
2332
|
-
c.
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2342
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleGetTaskInformation=async function(e,t,a,c,l){const d=c.child({tool:"get_task_information"})
|
|
2343
|
+
d.info("Getting task information",{args:e})
|
|
2344
|
+
const u=l.startTimer("tool_handler_duration")
|
|
2345
|
+
try{let{taskId:r}=function(e){try{return n.GetTaskInformationSchema.parse(e)}catch(t){throw new o.ValidationError("Invalid input: "+(0,s.getErrorMessage)(t),{args:e,error:t})}}(e);(0,i.isTaskRef)(r)&&(r=await(0,i.resolveTaskRef)(r,a,d))
|
|
2346
|
+
const c=t.projectId
|
|
2347
|
+
if(!c)throw new o.ValidationError("Project ID is required for getting task information with the new API structure")
|
|
2348
|
+
l.incrementCounter("get_task_information_attempts",1,{taskId:r}),a.setProjectId(c)
|
|
2349
|
+
const h=a.getTaskClient()
|
|
2350
|
+
let g
|
|
2351
|
+
d.info("Getting information for task "+r,{taskId:r,projectId:c})
|
|
2352
|
+
try{d.debug("Fetching task information",{taskId:r,projectId:c})
|
|
2353
|
+
const e=await h.getTask(r)
|
|
2354
|
+
d.info("Raw task response data",{taskId:r,responseData:JSON.stringify(e)})
|
|
2339
2355
|
let t=null
|
|
2340
2356
|
e&&"object"==typeof e&&(t="success"in e&&"data"in e||"data"in e?e.data:e)
|
|
2341
2357
|
let n=!1
|
|
2342
|
-
if(t&&"object"==typeof t&&(n="description"in t&&!!t.description),t){const e={id:r,title:"Untitled Task",description:"No description available.",status:"pending",projectId:
|
|
2358
|
+
if(t&&"object"==typeof t&&(n="description"in t&&!!t.description),t){const e={id:r,title:"Untitled Task",description:"No description available.",status:"pending",projectId:c,requestId:"",createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}
|
|
2343
2359
|
"id"in t&&t.id&&(e.id=t.id+""),"title"in t&&t.title&&(e.title=t.title+""),"description"in t&&void 0!==t.description&&(null===t.description?e.description="":e.description=t.description+""),"status"in t&&t.status&&(e.status=t.status),"projectId"in t&&t.projectId&&(e.projectId=t.projectId+""),"requestId"in t&&t.requestId&&(e.requestId=t.requestId+""),"createdAt"in t&&t.createdAt&&(e.createdAt=t.createdAt+""),"updatedAt"in t&&t.updatedAt&&(e.updatedAt=t.updatedAt+"")
|
|
2344
2360
|
const n=e
|
|
2345
|
-
"metadata"in t&&t.metadata&&(n.metadata=t.metadata),
|
|
2346
|
-
|
|
2347
|
-
if(
|
|
2348
|
-
|
|
2361
|
+
"metadata"in t&&t.metadata&&(n.metadata=t.metadata),g=n}else g={id:r,title:"Untitled Task",description:"No description available.",status:"pending",projectId:c,requestId:"",createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()}
|
|
2362
|
+
d.info("Retrieved task information",{taskId:r,title:g.title,status:g.status})}catch(e){throw new o.NotFoundError(`Task ${r} not found in project ${c}. Please provide a valid task ID.`,{taskId:r,projectId:c,originalError:e})}let p=null
|
|
2363
|
+
if(g.requestId)try{const e=a.getRequestClient()
|
|
2364
|
+
p=await e.getRequest(g.requestId),d.info("Retrieved parent request information",{taskId:r,requestId:g.requestId})}catch(e){d.warn("Failed to retrieve parent request",{error:(0,s.getErrorMessage)(e),taskId:r,requestId:g.requestId})}const f=e=>{if(!e)return"Unknown date"
|
|
2349
2365
|
try{const t=new Date(e)
|
|
2350
|
-
return isNaN(t.getTime())?"Unknown date":t.toLocaleString()}catch(t){return
|
|
2351
|
-
let
|
|
2352
|
-
if(
|
|
2353
|
-
|
|
2366
|
+
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
|
|
2367
|
+
let I=`# Task: ${g.title} (${k})\n\n`
|
|
2368
|
+
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
|
|
2369
|
+
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`)
|
|
2354
2370
|
const t=["lastCommit","completedAt","completionSummary"]
|
|
2355
|
-
Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{
|
|
2356
|
-
try{const o=
|
|
2357
|
-
await(0,r.createFailureToolRecord)("get-task-information",n,{args:e},o,l,
|
|
2358
|
-
let
|
|
2359
|
-
return n instanceof o.NotFoundError&&(
|
|
2360
|
-
const r=t(8616),n=t(6183),o=t(9860),s=t(8824)},3444(e,exports,t){"use strict"
|
|
2371
|
+
Object.entries(e).filter((([e])=>!t.includes(e))).forEach((([e,t])=>{I+=`**${e}**: ${t}\n`}))}return I+="\n## Description\n\n",g.description&&g.description.trim().length>0?I+=g.description:I+="No description provided.",u({success:!0}),{content:[{type:"text",text:I}]}}catch(n){d.error("Failed to get task information",{error:n instanceof Error?n.stack:n+"",args:e})
|
|
2372
|
+
try{const o=a.getToolRecordClient()
|
|
2373
|
+
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"})
|
|
2374
|
+
let i=(0,s.getErrorMessage)(n)
|
|
2375
|
+
return n instanceof o.NotFoundError&&(i=`The task ID "${e.taskId}" was not found. Please provide a valid task ID.`),{content:[{type:"text",text:"Error: "+i}],isError:!0}}}
|
|
2376
|
+
const r=t(8616),n=t(6183),o=t(9860),s=t(8824),i=t(4466)},3444(e,exports,t){"use strict"
|
|
2361
2377
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2362
2378
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.LogLevel=exports.defaultLogger=exports.isDebugToolsEnabled=exports.getDebugLevelFromEnv=exports.isDebugLoggingEnabled=exports.createEnvLogger=exports.createLogger=void 0
|
|
2363
2379
|
const n=t(2782)
|
|
@@ -2365,7 +2381,21 @@ Object.defineProperty(exports,"createLogger",{enumerable:!0,get(){return n.creat
|
|
|
2365
2381
|
const o=r(t(2782))
|
|
2366
2382
|
exports.defaultLogger=o.default
|
|
2367
2383
|
const s=t(6540)
|
|
2368
|
-
Object.defineProperty(exports,"LogLevel",{enumerable:!0,get(){return s.LogLevel}}),exports.default=o.default},
|
|
2384
|
+
Object.defineProperty(exports,"LogLevel",{enumerable:!0,get(){return s.LogLevel}}),exports.default=o.default},3451(e,exports,t){"use strict"
|
|
2385
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.resolveActiveTaskId=async function(e,t,s){const i=e.currentSessionId
|
|
2386
|
+
if(n&&o===i)return n
|
|
2387
|
+
try{if(!i||"__unknown__"===i||"__server__"===i)return
|
|
2388
|
+
const a="getTaskClient"in t?t.getTaskClient():t
|
|
2389
|
+
let c=null
|
|
2390
|
+
if("getTaskClient"in t)c=await r.sessionIdentity.getSessionRequestId(t,s,i)
|
|
2391
|
+
else{const t=e.workspaceManager?.getCurrentContext(i)
|
|
2392
|
+
c=t?.requestId||null}if(!c)return
|
|
2393
|
+
const l=await a.listTasks({requestId:c,status:"in_progress"})
|
|
2394
|
+
if(0===l.length)return
|
|
2395
|
+
const d=l[0].localId||l[0].id
|
|
2396
|
+
return n=d,o=i,d}catch(e){return void s.debug("Could not resolve active task",{error:e+""})}},exports.clearActiveTaskCache=function(){n=null,o=null}
|
|
2397
|
+
const r=t(6688)
|
|
2398
|
+
let n=null,o=null},3556(e,exports,t){"use strict"
|
|
2369
2399
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
2370
2400
|
const r=t(6183),n=t(8317)
|
|
2371
2401
|
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"
|
|
@@ -2514,11 +2544,11 @@ try{await w.updateTaskStatus(T,"canceled"),f.info("Canceled task after operation
|
|
|
2514
2544
|
P?f.warn("File operation completed with partial failures",{requestId:S}):f.info("File operation completed successfully"),f.debug("Completing task")
|
|
2515
2545
|
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})
|
|
2516
2546
|
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")
|
|
2517
|
-
const j=P?`Quick change completed with partial success: ${b}. Some replacements failed - see details below.`:"Quick change completed: "+b,
|
|
2518
|
-
let
|
|
2519
|
-
try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:j,acceptanceEvidence:[{evidence:
|
|
2547
|
+
const j=P?`Quick change completed with partial success: ${b}. Some replacements failed - see details below.`:"Quick change completed: "+b,x=P?t+" operation partially completed - some operations succeeded, some failed":t+" operation executed successfully"
|
|
2548
|
+
let R=!1
|
|
2549
|
+
try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:j,acceptanceEvidence:[{evidence:x}],testVerification:void 0},d,u,h,g,p)
|
|
2520
2550
|
if(e.isError)f.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text})
|
|
2521
|
-
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)})}
|
|
2551
|
+
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)})}R=!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(!R)try{f.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:j}),R=!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
|
|
2522
2552
|
let O
|
|
2523
2553
|
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
|
|
2524
2554
|
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}}}
|
|
@@ -2600,47 +2630,47 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
2600
2630
|
var t={}
|
|
2601
2631
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2602
2632
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2603
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,
|
|
2604
|
-
let
|
|
2605
|
-
const
|
|
2606
|
-
try{const
|
|
2607
|
-
|
|
2608
|
-
let
|
|
2609
|
-
const
|
|
2610
|
-
if(
|
|
2611
|
-
throw e}if(!
|
|
2612
|
-
|
|
2613
|
-
const e=
|
|
2614
|
-
|
|
2615
|
-
const
|
|
2616
|
-
let
|
|
2617
|
-
|
|
2618
|
-
let
|
|
2619
|
-
|
|
2620
|
-
const
|
|
2621
|
-
if(!
|
|
2622
|
-
throw Error(
|
|
2623
|
-
|
|
2624
|
-
try{await c.default.access(
|
|
2625
|
-
throw e}
|
|
2626
|
-
const{toolRecordId:
|
|
2627
|
-
let
|
|
2628
|
-
if(
|
|
2629
|
-
else
|
|
2630
|
-
let
|
|
2631
|
-
if(
|
|
2632
|
-
const e=await(0,g.commitUserChangesBeforeToolOperation)(
|
|
2633
|
-
e.userChangesCommitted&&(
|
|
2634
|
-
if(
|
|
2635
|
-
if(await c.default.mkdir(
|
|
2636
|
-
try{await
|
|
2637
|
-
if(
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
const
|
|
2642
|
-
return
|
|
2643
|
-
if(
|
|
2633
|
+
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()
|
|
2634
|
+
let v,C,_=d.FileOperationPhase.VALIDATION
|
|
2635
|
+
const E={toolName:"write_file",operationName:"write",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"write-file",metricsPrefix:"write_file",successMessage:"Successfully wrote content",failureMessage:"Failed to write content"}
|
|
2636
|
+
try{const n=d.validateArgs(e,l.WriteFileSchema),{path:f,documentId:q,content:S,format:T,append:P,comment:j}=n,{resolveActiveTaskId:x}=await Promise.resolve().then(t.bind(t,3451)),R=e.taskId||await x(r,o,m)||"untracked",M=!!q,O=!!f
|
|
2637
|
+
k.info("Writing content to "+(M?"document":"file"),{taskId:R,filePath:O?f:void 0,documentId:M?q:void 0,contentLength:"string"==typeof S?S.length:JSON.stringify(S).length,format:T,append:P,comment:j})
|
|
2638
|
+
let $,D,A,F="",N=!1,L=!1
|
|
2639
|
+
const z=O?f:void 0
|
|
2640
|
+
if(M){if(r.apiClient)try{await(0,p.ensureDocumentNotLocked)(q,r.apiClient,k,y,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2641
|
+
throw e}if(!r.documentFileManager)throw Error("Document file manager not available")
|
|
2642
|
+
F=await r.documentFileManager.getDocumentAsFile(q)
|
|
2643
|
+
const e=r.documentFileManager.getCachedDocumentInfo(q)
|
|
2644
|
+
A=e?.filename,L=!0,N=!1}_=d.FileOperationPhase.TASK_VALIDATION,y.incrementCounter("write_file_phase",1,{phase:_})
|
|
2645
|
+
const H=O?z:"document:"+q,B=await d.validateTaskId(R,H,o,k,y,E.metricsPrefix),U=B?.requestId
|
|
2646
|
+
let G=null
|
|
2647
|
+
O&&U&&(G=await d.validateWorkItemStates(R,H,o,i,r,k,y,E.metricsPrefix))
|
|
2648
|
+
let W={taskPromoted:!1,requestPromoted:!1}
|
|
2649
|
+
O&&U&&G&&(W=await d.autoPromoteTaskStatus(R,B.status,U,G.request?.status,H,o,i,k,y,E.metricsPrefix),W.taskPromoted&&k.info("Auto-promoted task to in_progress for file operation",{taskId:R,requestId:U,previousStatus:B.status,newStatus:W.newTaskStatus,triggeringOperation:"write_file"}))
|
|
2650
|
+
const V=await d.ensureCorrectWorkspaceContext({taskPromoted:W.taskPromoted,requestId:U,context:r,operation:"write_file",logger:k,metrics:y,metricsPrefix:E.metricsPrefix,requireRequestContext:O})
|
|
2651
|
+
if(!V.success){if(V.isLockConflict)return{content:[{type:"text",text:"\u274c "+V.error}],isError:!0}
|
|
2652
|
+
throw Error(V.error)}if(V.switched&&k.info("Workspace context successfully established",{requestId:U,branchName:V.branchName,operation:"write_file"}),O&&z){const e=d.validateAndNormalizePath(z,r)
|
|
2653
|
+
$=e.normalizedPath,D=e.fullPath,F=D
|
|
2654
|
+
try{await c.default.access(D),L=!0}catch{L=!1,N=!0}k.debug("Path validated with correct workspace context",{rawPath:z,normalizedPath:$,fullPath:D,workspaceBasePath:r.workspaceManager?.getCurrentContext(r.currentSessionId).basePath})}if(M&&U)try{await(0,h.validateRequestStatusForDocumentOperation)(U,i,k,y,"write_file-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2655
|
+
throw e}_=d.FileOperationPhase.RECORD_CREATION,y.incrementCounter("write_file_phase",1,{phase:_})
|
|
2656
|
+
const{toolRecordId:J}=await d.createFileOperationRecords(R,U,r.projectId,E.recordType,H,{operationType:M?"document":"file",documentId:M?q:void 0,documentFilename:A,filePath:O?$:void 0,contentLength:"string"==typeof S?S.length:JSON.stringify(S).length,format:T||"text",append:P||!1,wasFileCreated:!L,userComment:j},o,s,k,y,E.metricsPrefix,w)
|
|
2657
|
+
let K
|
|
2658
|
+
if(v=J,C=J,_=E.fileOperationPhase,y.incrementCounter("write_file_phase",1,{phase:_}),"json"===T)if("string"==typeof S)try{JSON.parse(S),K=S}catch(e){throw new u.ValidationError("Content is not valid JSON")}else K=JSON.stringify(S,null,2)
|
|
2659
|
+
else K="string"==typeof S?S:JSON.stringify(S,null,2)
|
|
2660
|
+
let Y=K
|
|
2661
|
+
if(O&&r.git)try{k.debug("[WRITE-FILE] Checking for user changes before write operation")
|
|
2662
|
+
const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"write_file",{requestId:r.workspaceManager?.getCurrentContext(r.currentSessionId)?.requestId,taskId:R},k,y)
|
|
2663
|
+
e.userChangesCommitted&&(k.debug("[WRITE-FILE] User changes committed before write operation",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),k.info("User changes committed before write-file operation",{taskId:R,path:$,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){k.debug("[WRITE-FILE] Pre-tool commit failed, continuing with write",{error:e instanceof Error?e.message:e+""}),k.warn("Pre-tool user changes commit failed, continuing with write operation",{taskId:R,path:$,error:e instanceof Error?e.message:e+""})}if(!F)throw Error("Target path not properly initialized")
|
|
2664
|
+
if(k.debug("[WRITE-FILE] Proceeding with file write operation",{targetPath:F}),P&&L)try{Y=await c.default.readFile(F,"utf8")+K}catch(e){k.warn("Failed to read existing content for append",{error:e})}const Q=a.default.dirname(F)
|
|
2665
|
+
if(await c.default.mkdir(Q,{recursive:!0}),await c.default.writeFile(F,Y,"utf8"),k.info("Content written successfully",{path:O?$:"document:"+q,finalLength:Y.length,append:P,wasCreated:N}),M){r.documentFileManager.markForSync(q)
|
|
2666
|
+
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
|
|
2667
|
+
if(O){if(_=d.FileOperationPhase.GIT_COMMIT,y.incrementCounter("write_file_phase",1,{phase:_}),r.workspaceManager){const e=r.workspaceManager.getCurrentContext(r.currentSessionId)
|
|
2668
|
+
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"} ${$} (${C})`,t=await d.commitToGit(R,$,C,C,e,r,k,y,E.metricsPrefix)
|
|
2669
|
+
Z=t.commitHash,ee=t.previousCommitHash,k.info("Changes committed to git via shared utility",{path:$,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?$:"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 "+$}**\n`
|
|
2670
|
+
re+=`**Content Length:** ${Y.length} characters\n`,O&&X&&(te||(re+=`**Branch:** ${X}\n`)),V.lockAcquired&&V.lockedRequestId&&!te&&(re+=`**Locked request:** ${V.lockedRequestId}\n`),O&&Z&&(re+=`**Commit Hash:** ${Z.substring(0,8)}\n`,ee&&(re+=`**Previous Commit:** ${ee.substring(0,8)}\n`)),C&&(re+=`[RECORD:${C}]\n`),M&&(re+=`\n**Document Update:** The document content has been updated and synced back to the tracking system. You can continue editing using other file modification tools with documentId \`${q}\`.`)
|
|
2671
|
+
const ne=Date.now()
|
|
2672
|
+
return k.info("Write operation completed successfully",{duration:ne-b,path:O?$:"document:"+q,contentLength:Y.length,wasCreated:N}),I({tool:"write_file",success:!0}),y.incrementCounter("write_file_total",1,{success:!0}),r.workspaceManager?.largeFileWarning&&(re+=r.workspaceManager.largeFileWarning,r.workspaceManager.largeFileWarning=""),{content:[{type:"text",text:re}]}}catch(t){const r=Date.now()-b
|
|
2673
|
+
if(k.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{path:e?.path,status:"failed",error:(0,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}}}
|
|
2644
2674
|
const a=i(t(6928)),c=i(t(1943)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824)},4139(e,exports){"use strict"
|
|
2645
2675
|
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"
|
|
2646
2676
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
@@ -2648,7 +2678,7 @@ const r=t(6183),n=t(4648)
|
|
|
2648
2678
|
exports.def={name:"request_operations",description:"Perform operations on existing requests.\n\nOperations:\n\u2022 complete - Begin completion: provide summary, get criteria keys for verification\n\u2022 verify-criteria - Verify acceptance criteria with evidence per key (triggers merge when all verified)\n\u2022 finalize - Approve and merge a request that is ready for review\n\u2022 approve - Approve a pending request so work can begin\n\u2022 revert - Completely revert a completed request, undoing all changes\n\u2022 get-info - Get comprehensive request information\n\u2022 list - List and filter requests\n\u2022 delete-empty - Delete a request that has no tasks (safe cleanup for mistaken or obsolete requests)\n\nCompletion is two-phase: first call complete with a summary, then call verify-criteria with evidence for each criterion key.\n\nNote: To create a new request, use the separate create-request tool.",schema:r.RequestOperationsSchema,annotations:{title:"Request Operations",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},handler(e,t){return(0,n.handleRequestOperations)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},4192(e,exports,t){"use strict"
|
|
2649
2679
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.BaseApiClient=void 0
|
|
2650
2680
|
const r=t(7163)
|
|
2651
|
-
exports.BaseApiClient=class{constructor(e,t,n,o,s){this.failureCount=0,this.circuitState="closed",this.circuitResetTimeout=null,this.baseUrl=e,this.logger=t,this.metrics=n,this.authToken=o,this.options={retryAttempts:3,retryDelay:1e3,timeout:1e4,circuitBreakerThreshold:
|
|
2681
|
+
exports.BaseApiClient=class{constructor(e,t,n,o,s){this.failureCount=0,this.circuitState="closed",this.circuitResetTimeout=null,this.baseUrl=e,this.logger=t,this.metrics=n,this.authToken=o,this.options={retryAttempts:3,retryDelay:1e3,timeout:1e4,circuitBreakerThreshold:10,circuitBreakerResetTime:1e4,...s},this.logger.debug("BaseApiClient constructor options:",{providedOptions:s?JSON.stringify(s):"undefined",mergedOptions:JSON.stringify(this.options)})
|
|
2652
2682
|
try{(0,r.debugTokenAccess)(this,"BaseApiClient constructor")}catch(e){}}setAuthToken(e){this.authToken=e||void 0,this.logger.debug("Auth token updated",{hasToken:!!e,tokenLength:e?e.length:0})}getAuthToken(){return this.authToken}async requestWithRetry(e,t,r,n,o){if("open"===this.circuitState)throw this.logger.warn(`Circuit breaker open - rejecting request to ${e} ${t}`),Error("Service unavailable - circuit breaker open")
|
|
2653
2683
|
const s=t.startsWith("/")?t:"/"+t
|
|
2654
2684
|
let i=`${this.baseUrl}${s}`
|
|
@@ -2665,7 +2695,7 @@ const t={method:e,headers:{...a},signal:AbortSignal.timeout(this.options.timeout
|
|
|
2665
2695
|
if("GET"!==e&&void 0!==r&&(t.body=JSON.stringify(r)),this.logger.debug("Request details",{method:e,url:i}),t.headers){const e={}
|
|
2666
2696
|
Object.entries(t.headers).forEach((([t,r])=>{"authorization"===t.toLowerCase()?e[t]="Bearer [redacted]":e[t]=r})),this.logger.debug("Request headers",{headers:e})}if("GET"!==e&&t.body){const e="string"==typeof t.body?t.body:JSON.stringify(t.body)
|
|
2667
2697
|
this.logger.debug("Request body",{bodyPreview:e.substring(0,200)+(e.length>200?"...":""),bodyLength:e.length})}const n=await fetch(i,t)
|
|
2668
|
-
if(!n.ok){if(this.incrementFailureCount(),this.logger.error("API request failed with status "+n.status,{method:e,url:i,status:n.status,statusText:n.statusText,attempt:l}),401===n.status)throw g({success:!1,status:n.status,retries:l-1}),Error("Authentication failed - invalid or expired token")
|
|
2698
|
+
if(!n.ok){if(500>n.status||this.incrementFailureCount(),this.logger.error("API request failed with status "+n.status,{method:e,url:i,status:n.status,statusText:n.statusText,attempt:l}),401===n.status)throw g({success:!1,status:n.status,retries:l-1}),Error("Authentication failed - invalid or expired token")
|
|
2669
2699
|
if(429===n.status){const e=n.headers.get("Retry-After"),t=e?1e3*parseInt(e):2*(this.options.retryDelay||1e3)
|
|
2670
2700
|
if(this.logger.warn(`Rate limited (429), retrying after ${t}ms`,{attempt:l,maxAttempts:d,retryAfter:e}),d>l){await new Promise((e=>setTimeout(e,t)))
|
|
2671
2701
|
continue}}if(n.status>=500&&d>l){const e=(this.options.retryDelay||1e3)*Math.pow(2,l-1)
|
|
@@ -2685,7 +2715,7 @@ return g({success:!0,status:n.status,retries:l-1,standardFormat:!1}),e}if(o&&"ob
|
|
|
2685
2715
|
throw this.logger.error("API returned error response",{errorCode:e.error?.code,errorMessage:e.error?.message,statusCode:e.error?.statusCode}),g({success:!1,status:n.status,retries:l-1,errorCode:e.error?.code}),Error(`API error: ${e.error?.code}: ${e.error?.message}`)}if(o&&"object"==typeof o&&"success"in o&&!0===o.success&&"data"in o){const t=o
|
|
2686
2716
|
return g({success:!0,status:n.status,retries:l-1,standardFormat:!0}),this.logger.debug("API request succeeded with status "+n.status,{method:e,url:i,status:n.status,retries:l-1,hasMetadata:"metadata"in t}),t}return this.logger.warn("Invalid API response format: Unexpected structure",{responseType:typeof o,responseKeys:"object"==typeof o?Object.keys(o):[]}),{success:!0,data:o}}catch(t){if(l>=d)throw this.incrementFailureCount(),this.logger.error(`API request failed after ${l} attempts`,{method:e,url:i,error:t.message||t+"",status:t.status}),g({success:!1,error:!0,retries:l-1}),t
|
|
2687
2717
|
const r=Math.min((this.options.retryDelay||1e3)*Math.pow(2,l-1),5e3)
|
|
2688
|
-
this.logger.warn(`API request failed, retrying in ${r}ms`,{method:e,url:i,error:t.message||t+"",attempt:l,maxAttempts:d}),await new Promise((e=>setTimeout(e,r)))}}throw Error("Unexpected end of requestWithRetry")}incrementFailureCount(){this.failureCount++,this.metrics.setGauge("api_failure_count",this.failureCount),"half-open"!==this.circuitState
|
|
2718
|
+
this.logger.warn(`API request failed, retrying in ${r}ms`,{method:e,url:i,error:t.message||t+"",attempt:l,maxAttempts:d}),await new Promise((e=>setTimeout(e,r)))}}throw Error("Unexpected end of requestWithRetry")}incrementFailureCount(){this.failureCount++,this.metrics.setGauge("api_failure_count",this.failureCount),"half-open"!==this.circuitState?this.failureCount<this.options.circuitBreakerThreshold||"closed"!==this.circuitState||this.openCircuit():this.logger.warn("Half-open probe failed, will retry on next request")}resetFailureCount(){const e="closed"!==this.circuitState
|
|
2689
2719
|
this.failureCount=0,this.circuitState="closed",this.metrics.setGauge("api_failure_count",0),this.metrics.setGauge("circuit_breaker_open",0),this.circuitResetTimeout&&(clearTimeout(this.circuitResetTimeout),this.circuitResetTimeout=null),e&&this.logger.info("Circuit breaker closed after successful request")}openCircuit(){this.circuitState="open",this.metrics.setGauge("circuit_breaker_open",1),this.logger.warn(`Circuit breaker opened after ${this.failureCount} failures`),this.circuitResetTimeout&&clearTimeout(this.circuitResetTimeout)
|
|
2690
2720
|
const e=this.options.circuitBreakerResetTime||5e3
|
|
2691
2721
|
this.circuitResetTimeout=setTimeout((()=>{this.circuitState="half-open",this.logger.info("Circuit breaker half-open, next request will probe")}),e)}async get(e,t,r){return this.requestWithRetry("GET",e,void 0,r,t)}async post(e,t,r){return this.requestWithRetry("POST",e,t,r)}async put(e,t,r){return this.requestWithRetry("PUT",e,t,r)}async delete(e,t){return this.requestWithRetry("DELETE",e,void 0,t)}async patch(e,t,r){return this.requestWithRetry("PATCH",e,t,r)}}},4221(e,exports,t){"use strict"
|
|
@@ -2723,7 +2753,7 @@ return d({success:!1,error:"validation_failed"}),{content:[{type:"text",text:"Fa
|
|
|
2723
2753
|
return a.blockedByTasks?.length&&(e+="\n**Tasks that must be completed first:**\n",a.blockedByTasks.forEach(((t,r)=>{e+=`${r+1}. **${t.taskId}** - ${t.title} (${t.status})\n`}))),d({success:!1,reason:"server_blocked"}),{content:[{type:"text",text:e}],isError:!0}}if(!t.workspaceManager)throw Error("WorkspaceManager not available")
|
|
2724
2754
|
let g="workspace-manager"
|
|
2725
2755
|
const p=await e.getRequest(u),f=p?.title||"Request "+u,m="resolving_conflicts"===p?.status
|
|
2726
|
-
try{m?(l.info("Merge retry (resolving_conflicts) \u2014 using -X theirs",{requestId:u}),c=await t.workspaceManager.completeRequest(u,f,{skipConflictDetection:!0}),g="retry-theirs"):(c=await t.workspaceManager.completeRequest(u,f),g=c.autoMergeInfo?.strategy||"workspace-manager"),l.info("Merge completed",{requestId:u,mergeCommitHash:c.mergeCommitHash,mergeMethod:g})}catch(r){if(r.conflictInfo){const o=r.conflictInfo,a=o.workingDirectory||t.workspaceManager?.getCurrentContext()?.basePath||process.cwd(),c=(0,n.createConflictResolutionManager)(l,i,a,t.git),h=await c.handleConflicts(o)
|
|
2756
|
+
try{m?(l.info("Merge retry (resolving_conflicts) \u2014 using -X theirs",{requestId:u}),c=await t.workspaceManager.completeRequest(u,f,{skipConflictDetection:!0}),g="retry-theirs"):(c=await t.workspaceManager.completeRequest(u,f),g=c.autoMergeInfo?.strategy||"workspace-manager"),l.info("Merge completed",{requestId:u,mergeCommitHash:c.mergeCommitHash,mergeMethod:g})}catch(r){if(r.conflictInfo){const o=r.conflictInfo,a=o.workingDirectory||t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||process.cwd(),c=(0,n.createConflictResolutionManager)(l,i,a,t.git),h=await c.handleConflicts(o)
|
|
2727
2757
|
try{await e.updateRequest(u,{status:"resolving_conflicts"}),l.info("Set status to resolving_conflicts",{requestId:u})}catch(e){l.error("Failed to set resolving_conflicts status",{requestId:u,error:(0,s.getErrorMessage)(e)})}return d({success:!1,reason:"merge_conflicts"}),{content:[{type:"text",text:h.userMessage}],isError:!1}}const o=(0,s.getErrorMessage)(r)
|
|
2728
2758
|
return d({success:!1,error:"merge_failure"}),{content:[{type:"text",text:"Merge failed: "+o}],isError:!0}}try{await i.proxyPost(`/api/projects/${t.projectId}/requests/${u}/finalize-completion`,{summary:p?.completionSummary||"Merged request "+u,acceptanceEvidence:h.map((e=>({evidence:e.evidence}))),mergeResult:{mergeCommitHash:c.mergeCommitHash,mergedFiles:c.mergedFiles,cleanedUp:c.cleanedUp,method:g}})}catch(e){const t=(0,s.getErrorMessage)(e)
|
|
2729
2759
|
return l.error("CRITICAL: Merge succeeded but server finalization failed",{requestId:u,mergeCommitHash:c.mergeCommitHash,error:t}),d({success:!1,error:"api_update_failed"}),{content:[{type:"text",text:`CRITICAL: Code was merged (commit: ${c.mergeCommitHash.substring(0,8)}) but failed to update server: ${t}`}],isError:!0}}return d({success:!0}),{content:[{type:"text",text:`Request ${u} merged successfully.\nCommit: ${c.mergeCommitHash.substring(0,8)}`}]}}catch(e){const r=(0,s.getErrorMessage)(e)
|
|
@@ -2744,7 +2774,38 @@ const s=(n.content||"")+e.content,i={content:s}
|
|
|
2744
2774
|
e.name&&(i.filename=e.name.replace(/\.md$/i,"")+".md")
|
|
2745
2775
|
const a=await r.updateDocument(e.planId,i),c=a.localId||a.id
|
|
2746
2776
|
return o.info("Plan appended",{planId:c,appendedLength:e.content.length}),{content:[{type:"text",text:`\u2705 **Plan Appended**\n\n**Plan ID:** ${c}\n**Appended:** ${e.content.length} characters\n**Total Length:** ${s.length} characters`}]}}catch(e){return o.error("Failed to append to plan",{error:(0,r.getErrorMessage)(e)}),{content:[{type:"text",text:"\u274c **Failed to append to plan:** "+(0,r.getErrorMessage)(e)}],isError:!0}}}
|
|
2747
|
-
const r=t(8824)},
|
|
2777
|
+
const r=t(8824)},4425(e,exports,t){"use strict"
|
|
2778
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCommands=async function(e,t,s,i,a,c){const l=a.startTimer("tool_execution_time"),d=e.operation||"run"
|
|
2779
|
+
try{const a=await s.proxyGet(`/api/projects/${t.projectId}/check-commands`),u=a?.data||a||[],h=u.filter((e=>e.isActive)),g=u.filter((e=>!e.isActive))
|
|
2780
|
+
if("list"===d){if(0===u.length)return l({success:!0}),{content:[{type:"text",text:'No commands configured for this project yet.\n\nUse `commands({ operation: "add", name: "typecheck", command: "tsc --noEmit" })` to add one.'}]}
|
|
2781
|
+
const e=[]
|
|
2782
|
+
return h.length>0&&(e.push(`## Available Commands (${h.length})\n`),e.push(...h.map((e=>`- **${e.name}**: \`${e.command}\`${e.description?" \u2014 "+e.description:""}`)))),g.length>0&&(e.push(`\n## Pending Approval (${g.length})\n`),e.push(...g.map((e=>`- **${e.name}**: \`${e.command}\` \u2014 \u23f3 waiting for user approval`)))),e.push('\nRun: `commands({ name: "name" })`\nAdd: `commands({ operation: "add", name: "...", command: "..." })`\nRemove: `commands({ operation: "remove", name: "..." })`'),l({success:!0}),{content:[{type:"text",text:e.join("\n")}]}}if("add"===d){if(!e.name?.trim())return l({success:!1,error:"missing_name"}),{content:[{type:"text",text:"Error: `name` is required when adding a command."}],isError:!0}
|
|
2783
|
+
if(!e.command?.trim())return l({success:!1,error:"missing_command"}),{content:[{type:"text",text:"Error: `command` is required when adding a command."}],isError:!0}
|
|
2784
|
+
const r=u.find((t=>t.name.toLowerCase()===e.name.toLowerCase()))
|
|
2785
|
+
if(r)return l({success:!1,error:"duplicate"}),{content:[{type:"text",text:`Command "${e.name}" already exists: \`${r.command}\`${r.isActive?"":" (pending approval)"}`}],isError:!0}
|
|
2786
|
+
try{const r=await s.proxyPost(`/api/projects/${t.projectId}/check-commands`,{name:e.name.trim(),command:e.command.trim(),description:e.description?.trim(),timeout:e.timeout||60}),n=r?.data?.id||r?.id
|
|
2787
|
+
n&&await s.proxyPatch(`/api/projects/${t.projectId}/check-commands/${n}`,{isActive:!1})
|
|
2788
|
+
const a=s.getSessionMessageClient(),c=o.sessionIdentity.getIdentity(),d=c?.sessionId||"unknown"
|
|
2789
|
+
return a&&await a.createQuestion({fromSessionId:d,questionType:"alternatives",question:`Command approval: \`${e.command.trim()}\``,options:[{id:"approve",label:"Approve",description:`Add "${e.name.trim()}" to project commands`},{id:"deny",label:"Deny",description:"Reject this command"}],context:JSON.stringify({type:"command-approval",commandId:n,name:e.name.trim(),command:e.command.trim()}),category:"action-required",priority:"high"}),i.info("Command approval requested",{name:e.name,command:e.command,commandId:n}),l({success:!0}),{content:[{type:"text",text:`Command **${e.name}** (\`${e.command}\`) submitted for user approval.\n\nUse \`commands({ operation: "list" })\` to check status.`}]}}catch(e){return l({success:!1,error:"add_failed"}),{content:[{type:"text",text:"Failed to request command approval: "+(0,n.getErrorMessage)(e)}],isError:!0}}}if("remove"===d){if(!e.name?.trim())return l({success:!1,error:"missing_name"}),{content:[{type:"text",text:"Error: `name` is required when removing a command."}],isError:!0}
|
|
2790
|
+
const r=u.find((t=>t.name.toLowerCase()===e.name.toLowerCase()))
|
|
2791
|
+
if(!r)return l({success:!1,error:"not_found"}),{content:[{type:"text",text:`Command "${e.name}" not found.`}],isError:!0}
|
|
2792
|
+
try{return await s.proxyDelete(`/api/projects/${t.projectId}/check-commands/${r.id}`),i.info("Removed command",{name:r.name,id:r.id}),l({success:!0}),{content:[{type:"text",text:`Removed command **${r.name}**.`}]}}catch(e){return l({success:!1,error:"remove_failed"}),{content:[{type:"text",text:"Failed to remove command: "+(0,n.getErrorMessage)(e)}],isError:!0}}}if(!e.name){const e=h.map((e=>e.name)).join(", ")
|
|
2793
|
+
return l({success:!1,error:"missing_name"}),{content:[{type:"text",text:"Error: `name` is required when running a command.\n\nAvailable commands: "+(e||"(none configured)")}],isError:!0}}const p=h.find((t=>t.name.toLowerCase()===e.name.toLowerCase()))
|
|
2794
|
+
if(!p){const t=h.map((e=>e.name)).join(", ")
|
|
2795
|
+
return l({success:!1,error:"not_found"}),{content:[{type:"text",text:`Command "${e.name}" not found.\n\nAvailable commands: ${t||"(none configured)"}`}],isError:!0}}let f=e.args?`${p.command} ${e.args}`:p.command
|
|
2796
|
+
e.grep&&(f=`${f} 2>&1 | grep -i ${JSON.stringify(e.grep)}`)
|
|
2797
|
+
const m=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath
|
|
2798
|
+
i.info("Running command",{name:p.name,command:f,cwd:m})
|
|
2799
|
+
let y="",w="",k=0,I=!1
|
|
2800
|
+
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
|
|
2801
|
+
y.length>b&&(y="\u2026"+y.slice(-b)),w.length>v&&(w="\u2026"+w.slice(-v))
|
|
2802
|
+
const C=I?"TIMEOUT":null,_=[y,w].filter(Boolean).join("\n")||"(no output)"
|
|
2803
|
+
let E
|
|
2804
|
+
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()}})
|
|
2805
|
+
E=e?.id}catch(e){i.debug("Failed to create tool record for command run",{error:(0,n.getErrorMessage)(e)})}l({success:!0})
|
|
2806
|
+
const q=E?`\n[RECORD:${E}]`:""
|
|
2807
|
+
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}}}
|
|
2808
|
+
const r=t(5317),n=t(8824),o=t(6688)},4465(e,exports,t){"use strict"
|
|
2748
2809
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.SessionTagMappingClient=void 0
|
|
2749
2810
|
const r=t(7645),n=t(2161)
|
|
2750
2811
|
class o extends r.ConnectionAwareClient{constructor(e,t,r,n,o,s,i){const a=t.child({component:"session-tag-mapping-client"}),c=s||{isInOfflineMode(){return!1},isOffline(){return!1},setOfflineMode(){},async checkConnectivity(){return!0},getHealthCheckStats(){return{isOffline:!1,consecutiveFailures:0,currentBackoffMs:0,lastCheckTime:0}},cleanup(){}}
|
|
@@ -2763,7 +2824,15 @@ if(!t)throw Error("Project ID is required for mapping operations")
|
|
|
2763
2824
|
this.logger.debug("Getting mapping by OpenCode session ID",{opencodeSessionId:e,projectId:t})
|
|
2764
2825
|
try{const r=await this.requestWithRetry("GET",`/api/projects/${t}/session-tag-mappings/by-opencode/${encodeURIComponent(e)}`)
|
|
2765
2826
|
return(0,n.safeGetResponseData)(r,null,this.logger)}catch(e){if(404===e.statusCode||e.message?.includes("404"))return null
|
|
2766
|
-
throw e}}}exports.SessionTagMappingClient=o},
|
|
2827
|
+
throw e}}}exports.SessionTagMappingClient=o},4466(e,exports){"use strict"
|
|
2828
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.isTaskRef=function(e){return t.test(e)},exports.formatTaskRef=function(e,t){return`${e}#${t.toString().padStart(2,"0")}`},exports.resolveTaskRef=async function(e,r){const n=e.match(t)
|
|
2829
|
+
if(!n)throw Error(`Invalid task reference: ${e}. Expected format: req######+#NN (e.g. req000005#03)`)
|
|
2830
|
+
const[,o,s]=n,i=parseInt(s,10)
|
|
2831
|
+
if(1>i)throw Error(`Invalid task number in ${e}: must be >= 1`)
|
|
2832
|
+
const a=r.getTaskClient(),c=await a.listTasks({requestId:o,sortBy:"created",sortDirection:"asc"}),l=c.find((e=>e.sequenceNumber===i))||c[i-1]
|
|
2833
|
+
if(!l){const e=c.length
|
|
2834
|
+
throw Error(`Task #${i} not found in request ${o} (${e} task${1===e?"":"s"} exist).`)}return l.localId||l.id}
|
|
2835
|
+
const t=/^(req\d{6})#(\d+)$/},4592(e,exports,t){"use strict"
|
|
2767
2836
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
2768
2837
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
2769
2838
|
o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[]
|
|
@@ -2773,7 +2842,9 @@ var t={}
|
|
|
2773
2842
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2774
2843
|
return o(t,e),t})
|
|
2775
2844
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handlePlannerOps=async function(e,t,r,n,o,s){const h=r.child({tool:"planner_ops"}),g=n.startTimer("tool_execution_time")
|
|
2776
|
-
try{if(e?.request&&"
|
|
2845
|
+
try{if(e?.request&&"object"==typeof e.request){const t=e.request
|
|
2846
|
+
e.prompt=e.prompt||t.prompt,e.description=e.description||t.description,delete e.request}if(e?.list&&"object"==typeof e.list){const t=e.list
|
|
2847
|
+
e.activeOnly=e.activeOnly??t.activeOnly,e.limit=e.limit??t.limit,delete e.list}!e?.operation&&e&&(e.prompt?e.operation="request":e.sessionId&&(e.operation="check-status")),e?.operation&&("request"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.limit):"check-status"===e.operation?(delete e.prompt,delete e.description,delete e.activeOnly,delete e.limit):"list"===e.operation&&(delete e.sessionId,delete e.prompt,delete e.description))
|
|
2777
2848
|
const r=c.validateArgs(e,a.PlannerOpsSchema),{operation:p,sessionId:f}=r
|
|
2778
2849
|
let m
|
|
2779
2850
|
switch(h.info("Processing planner_ops",{operation:p,sessionId:f}),p){case"request":{const e=await async function(e,t,r){if(!e)return"ask"
|
|
@@ -2791,13 +2862,13 @@ if("ask"===n)return"ask"
|
|
|
2791
2862
|
if("interactive"===n)return"interactive"}catch(e){t.warn("Failed to read project metadata for planningMode fallback",{error:(0,l.getErrorMessage)(e)})}return"ask"}catch(e){return t.warn("Failed to read planningMode from workflow, defaulting to ask",{error:(0,l.getErrorMessage)(e)}),"ask"}}(o,h,s)
|
|
2792
2863
|
if("ask"===e||"interactive"===e){h.info("Returning planner choice pending",{planningMode:e})
|
|
2793
2864
|
try{const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,t=o?.getSessionMessageClient()
|
|
2794
|
-
if(t&&e){const n=await d.sessionIdentity.getParentSessionId(e,o,h),s=r.
|
|
2795
|
-
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.
|
|
2865
|
+
if(t&&e){const n=await d.sessionIdentity.getParentSessionId(e,o,h),s=r.description||r.prompt
|
|
2866
|
+
await t.createQuestion({fromSessionId:e,toSessionId:n||void 0,questionType:"alternatives",question:"Planning requested: "+s,options:[{id:"auto",label:"Auto Plan",description:"Spawn an autonomous planner agent"},{id:"manual",label:"Manual Plan",description:"Open the interactive plan editor"},{id:"cancel",label:"Skip",description:"Dismiss this planning request"}],context:r.prompt,category:"action-required",priority:"high"}),h.info("planner-request: notification created",{fromSessionId:e})}else h.warn("planner-request: skipping notification",{hasClient:!!t,hasCallerSessionId:!!e})}catch(e){h.warn("planner-request: failed to create notification",{error:(0,l.getErrorMessage)(e)})}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})}]}
|
|
2796
2867
|
break}const n="auto-planner"
|
|
2797
|
-
if(h.info("Spawning planner",{planningMode:e,agent:n}),m=await(0,u.handleSpawn)({agent:n,prompt:r.
|
|
2868
|
+
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
|
|
2798
2869
|
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)
|
|
2799
2870
|
break
|
|
2800
|
-
case"list":const e=s?.sessionId||d.sessionIdentity.getIdentity()?.sessionId,[n,a]=await Promise.all([(0,u.handleListSessions)(t,h,o,{activeOnly:r.
|
|
2871
|
+
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??""
|
|
2801
2872
|
if(c.trim()||g.trim()){const e=[]
|
|
2802
2873
|
c.trim()&&e.push("## Auto-planner sessions\n"+c),g.trim()&&e.push("## Interactive plan sessions\n"+g),m={content:[{type:"text",text:e.join("\n\n")}]}}else m={content:[{type:"text",text:"No planning sessions found."}]}
|
|
2803
2874
|
break
|
|
@@ -2818,11 +2889,11 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
2818
2889
|
var t={}
|
|
2819
2890
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
2820
2891
|
return o(t,e),t})
|
|
2821
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileRecover=async function(e,
|
|
2822
|
-
try{let
|
|
2823
|
-
try{
|
|
2824
|
-
return
|
|
2825
|
-
return
|
|
2892
|
+
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()
|
|
2893
|
+
try{let m
|
|
2894
|
+
try{m=i.FileRecoverSchema.parse(e)}catch(t){if(t instanceof a.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
2895
|
+
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"
|
|
2896
|
+
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
|
|
2826
2897
|
try{const{normalizedPath:y,fullPath:w}=d.validateAndNormalizePath(t,o),k=await d.validateTaskId(e,y,s.getTaskClient(),a,g,"file-recover"),{toolRecordId:I}=await d.createFileOperationRecords(e,k?.requestId,o.projectId,"file-recover",y,{operationType:"file",filePath:y,commitHash:r,createBackup:n},s.getTaskClient(),i,a,g,"file-recover",f)
|
|
2827
2898
|
m=I
|
|
2828
2899
|
let b,v=!1
|
|
@@ -2837,29 +2908,32 @@ let E={}
|
|
|
2837
2908
|
try{const t=`Recover ${y} from ${r.substring(0,8)}`
|
|
2838
2909
|
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"
|
|
2839
2910
|
let S=`\u2705 **File ${q.charAt(0).toUpperCase()+q.slice(1)} Successfully**\n\n`
|
|
2840
|
-
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}}(
|
|
2841
|
-
return
|
|
2911
|
+
return S+=`**File:** ${y}\n`,S+=`**Recovered from:** ${r.substring(0,8)}\n`,S+=`**Content length:** ${_.length} characters\n`,n&&v&&b&&(S+=`**Backup created:** ${c.basename(b)}\n`),S+="**Git status:** Recovery committed\n",S+="\u{1f4a1} **Tip:** The file has been restored to its state at the specified commit.",a.info("File recovery completed successfully",{path:y,commitHash:r,duration:Date.now()-p}),g.incrementCounter("file_recover_total",1,{success:!0,type:"file"}),{content:[{type:"text",text:S}]}}catch(e){throw e}}(v,w,k,I,r,n,o,f,g,y,p)}catch(e){const t=Date.now()-y
|
|
2912
|
+
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}}}
|
|
2842
2913
|
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"
|
|
2843
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,
|
|
2844
|
-
try{for(const t of["complete","verifyCriteria","merge","revert","search","list"])if(e&&"string"==typeof e[t])try{e[t]=JSON.parse(e[t])}catch{}"complete"===e?.operation&&e?.summary&&!e?.complete&&(e.complete={summary:e.summary},delete e.summary),"complete"!==e?.operation||e?.complete||e?.summary||(e.complete={summary:""}),"merge"===e?.operation&&e?.verifications&&!e?.merge&&(e.merge={verifications:e.verifications},delete e.verifications),e?.merge&&Array.isArray(e.merge)&&(e.merge={verifications:e.merge}),"verify-criteria"===e?.operation&&(e.operation="merge",e.verifyCriteria&&!e.merge&&(e.merge=e.verifyCriteria,delete e.verifyCriteria)),"finalize"===e?.operation&&(e.operation="merge",e.merge||(e.merge={verifications:[]})),"revert"===e?.operation&&e?.reason&&!e?.revert&&(e.revert={reason:e.reason,confirmDestructive:e.confirmDestructive},delete e.reason,delete e.confirmDestructive),"search"===e?.operation&&e?.query&&!e?.search&&(e.search={query:e.query,searchIn:e.searchIn||"all",filters:e.filters},delete e.query,delete e.searchIn,delete e.filters)
|
|
2845
|
-
const
|
|
2846
|
-
|
|
2847
|
-
const
|
|
2848
|
-
|
|
2849
|
-
case"
|
|
2850
|
-
const e={requestId:y}
|
|
2851
|
-
return await(0,
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
return
|
|
2914
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleRequestOperations=async function(e,u,h,g,p,f){const m=g.child({tool:"request_operations"})
|
|
2915
|
+
try{for(const t of["complete","verifyCriteria","merge","revert","search","list"])if(e&&"string"==typeof e[t])try{e[t]=JSON.parse(e[t])}catch{}if("complete"===e?.operation&&e?.summary&&!e?.complete&&(e.complete={summary:e.summary},delete e.summary),"complete"!==e?.operation||e?.complete||e?.summary||(e.complete={summary:""}),"merge"===e?.operation&&e?.verifications&&!e?.merge&&(e.merge={verifications:e.verifications},delete e.verifications),e?.merge&&Array.isArray(e.merge)&&(e.merge={verifications:e.merge}),"verify-criteria"===e?.operation&&(e.operation="merge",e.verifyCriteria&&!e.merge&&(e.merge=e.verifyCriteria,delete e.verifyCriteria)),"finalize"===e?.operation&&(e.operation="merge",e.merge||(e.merge={verifications:[]})),"revert"===e?.operation&&e?.reason&&!e?.revert&&(e.revert={reason:e.reason,confirmDestructive:e.confirmDestructive},delete e.reason,delete e.confirmDestructive),"search"===e?.operation&&e?.query&&!e?.search&&(e.search={query:e.query,searchIn:e.searchIn||"all",filters:e.filters},delete e.query,delete e.searchIn,delete e.filters),e?.operation){const t=e.operation,r=["complete","merge","revert","list","search","approve"],n={complete:"complete",merge:"merge",revert:"revert",list:"list",search:"search",approve:void 0,"get-info":void 0,"delete-empty":void 0}[t]
|
|
2916
|
+
for(const t of r)t!==n&&delete e[t]}const y=r.RequestOperationsSchema.parse(e)
|
|
2917
|
+
let{requestId:w}=y
|
|
2918
|
+
const{operation:k}=y
|
|
2919
|
+
if(!w){const{sessionIdentity:e}=await Promise.resolve().then(t.bind(t,6688)),r=u.currentSessionId
|
|
2920
|
+
if(r&&"__unknown__"!==r&&"__server__"!==r&&(w=await e.getSessionRequestId(h,m,r)||void 0),!w)return{content:[{type:"text",text:`Error: requestId is required for '${k}' and could not be resolved from session`}],isError:!0}}switch(m.info("Processing request operation",{requestId:w,operation:k}),k){case"complete":{m.info("Routing to complete-request handler")
|
|
2921
|
+
const e={requestId:w,summary:y.complete.summary}
|
|
2922
|
+
return await(0,n.handleCompleteRequest)(e,u,h,g,p,f)}case"merge":return m.info("Routing to merge handler"),await(0,l.handleMergeRequest)({requestId:w,verifications:y.merge?.verifications||[]},u,h,g,p,f)
|
|
2923
|
+
case"approve":{m.info("Routing to approve-request handler")
|
|
2924
|
+
const e={requestId:w}
|
|
2925
|
+
return await(0,c.handleApproveRequest)(e,u,h,g,p,f)}case"revert":{m.info("Routing to revert-request handler")
|
|
2926
|
+
const e={requestId:w,reason:y.revert.reason,confirmDestructive:y.revert.confirmDestructive}
|
|
2927
|
+
return await(0,o.handleRevertRequest)(e,u,h,g,p)}case"get-info":{m.info("Routing to get-request-information handler")
|
|
2928
|
+
const e={requestId:w}
|
|
2929
|
+
return await(0,s.handleGetRequestInformation)(e,u,h,g,p)}case"list":{m.info("Routing to list-requests handler")
|
|
2930
|
+
const e={filters:y.list?.filters}
|
|
2931
|
+
return await(0,i.handleListRequests)(e,u,h,g,p)}case"search":{m.info("Routing to search-requests handler")
|
|
2932
|
+
const e={search:y.search}
|
|
2933
|
+
return await(0,a.handleSearchRequests)(e,u,h,g,p)}case"delete-empty":if(m.info("Routing to delete-empty handler"),!w)return{content:[{type:"text",text:"\u274c **Request Operations Failed:** requestId is required for delete-empty"}],isError:!0}
|
|
2934
|
+
try{const e=h.getProxyClient(),t=await e.proxyGet(`/api/projects/${u.projectId}/tasks`,{requestLocalId:w,limit:1}),r=t?.data||t||[]
|
|
2935
|
+
return(Array.isArray(r)?r.length:0)>0?{content:[{type:"text",text:`\u274c Cannot delete ${w}: it has tasks. Only empty requests (no tasks created) can be deleted.`}],isError:!0}:(await e.proxyDelete(`/api/projects/${u.projectId}/requests/${w}`),m.info("Empty request deleted",{requestId:w}),{content:[{type:"text",text:`\u2705 Request ${w} deleted (had no tasks).`}]})}catch(e){return{content:[{type:"text",text:"\u274c **Failed to delete request:** "+(0,d.getErrorMessage)(e)}],isError:!0}}default:{const e="Unknown operation type: "+k
|
|
2936
|
+
return m.error(e),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+e}],isError:!0}}}}catch(e){return m.error("Request operations failed",{error:e instanceof Error?e.stack:e+""}),p.incrementCounter("request_operations_errors",1),{content:[{type:"text",text:"\u274c **Request Operations Failed:** "+(0,d.getErrorMessage)(e)}],isError:!0}}}
|
|
2863
2937
|
const r=t(6183),n=t(5715),o=t(6416),s=t(5434),i=t(8037),a=t(233),c=t(1537),l=t(4306),d=t(8824)},4710(e,exports,t){"use strict"
|
|
2864
2938
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
2865
2939
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectClient=void 0
|
|
@@ -2986,7 +3060,7 @@ return a(t,e),t})
|
|
|
2986
3060
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleFileBlame=async function(e,t,s,i,a){const c=i.child({tool:"file_blame"}),g=Date.now()
|
|
2987
3061
|
try{const{path:i,lines:p,branch:f}=e
|
|
2988
3062
|
c.info("Processing blame request",{filePath:i,lines:p,branch:f})
|
|
2989
|
-
const m=t.basePath,y=d.isAbsolute(i)?i:d.join(m,i),w=d.relative(m,y)
|
|
3063
|
+
const m=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.basePath||t.basePath,y=d.isAbsolute(i)?i:d.join(m,i),w=d.relative(m,y)
|
|
2990
3064
|
try{await u.access(y)}catch{return{content:[{type:"text",text:"\u274c File not found: "+w}],isError:!0}}const k=function(e){if(!e)return null
|
|
2991
3065
|
if(/^\d+$/.test(e)){const t=parseInt(e,10)
|
|
2992
3066
|
return{start:t,end:t}}const t=e.match(/^(\d+)-(\d+)$/)
|
|
@@ -3069,7 +3143,7 @@ return t.success?(this.logger.info("Successfully removed worktree",{requestId:e.
|
|
|
3069
3143
|
return await this.worktreeManager.getWorktreeInfo(t)||null}catch(t){return this.logger.warn("Failed to get worktree info",{requestId:e,error:(0,i.getErrorMessage)(t)}),null}}getMainGit(){return this.mainGit}}},4973(e,exports,t){"use strict"
|
|
3070
3144
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3071
3145
|
const r=t(6183),n=t(4592)
|
|
3072
|
-
exports.def={name:"planner_ops",description:"Request a planning session and check on planner progress.\n\
|
|
3146
|
+
exports.def={name:"planner_ops",description:"Request a planning session and check on planner progress.\n\nAll params are flat (no nested objects). The operation field determines which params apply.\n\nOperations:\n\u2022 request \u2014 prompt required. Optional: description\n\u2022 check-status \u2014 sessionId required\n\u2022 list \u2014 all optional: activeOnly, limit",schema:r.PlannerOpsSchema,annotations:{title:"Planner Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handlePlannerOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5003(e,exports,t){"use strict"
|
|
3073
3147
|
async function r(e,t,r,s,i){const a=r.child({requestId:e,operation:"request-status-validation"})
|
|
3074
3148
|
try{a.info("Validating request status for document operation",{requestId:e})
|
|
3075
3149
|
const r=await t.getRequest(e)
|
|
@@ -3318,7 +3392,7 @@ try{await(0,o.createFailureToolRecord)("complete-request",r,{error:s,details:i,r
|
|
|
3318
3392
|
const r=t(9860),n=t(1569),o=t(8616),s=t(8824),i=t(5454)},5767(e,exports,t){"use strict"
|
|
3319
3393
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3320
3394
|
const r=t(6183),n=t(6285)
|
|
3321
|
-
exports.def={name:"specialist_ops",description:"Manage your pool of up to 10 specialists. Each has a specialization describing their domain. Reuse specialists via follow-up before spawning new ones.\n\
|
|
3395
|
+
exports.def={name:"specialist_ops",description:"Manage your pool of up to 10 specialists. Each has a specialization describing their domain. Reuse specialists via follow-up before spawning new ones.\n\nAll params are flat (no nested objects). The operation field determines which params apply.\n\nOperations:\n\u2022 delegate \u2014 prompt + specialization required. Optional: description, requestId\n\u2022 follow-up \u2014 prompt + sessionId required. Optional: specialization (to update focus)\n\u2022 check-status \u2014 sessionId required\n\u2022 list \u2014 all params optional: activeOnly, requestId (filter), limit\n\u2022 abort \u2014 sessionId required",schema:r.SpecialistOpsSchema,annotations:{title:"Specialist Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSpecialistOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5802(module){"use strict"
|
|
3322
3396
|
module.exports=require("@modelcontextprotocol/sdk/server/stdio.js")},5806(e,exports,t){"use strict"
|
|
3323
3397
|
function r(){const e=n.z.object({requestId:n.z.string(),summary:n.z.string(),acceptanceEvidence:n.z.array(n.z.object({evidence:n.z.string()}))}),t=n.z.object({testRecords:n.z.array(n.z.string()),coverage:n.z.object({criteriaTestedCount:n.z.number(),totalTestCases:n.z.number()}),criterionCoverage:n.z.array(n.z.object({coverage:n.z.enum(["none","partial","full"]),testRecords:n.z.array(n.z.string())}))})
|
|
3324
3398
|
return(0,o.areTestsRequiredForCompletion)()?e.extend({testVerification:t}):e}Object.defineProperty(exports,"__esModule",{value:!0}),exports.DynamicCompleteRequestSchema=void 0,exports.getDynamicCompleteRequestSchema=r
|
|
@@ -3338,64 +3412,65 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3338
3412
|
var t={}
|
|
3339
3413
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3340
3414
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3341
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleDeleteFiles=async function(e,
|
|
3342
|
-
let
|
|
3343
|
-
const
|
|
3344
|
-
try{const n
|
|
3345
|
-
let
|
|
3346
|
-
if(
|
|
3347
|
-
else{if(!
|
|
3348
|
-
|
|
3415
|
+
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()
|
|
3416
|
+
let w,k,I=l.FileOperationPhase.VALIDATION
|
|
3417
|
+
const b={toolName:"delete-files",operationName:"delete",fileOperationPhase:l.FileOperationPhase.FILE_WRITE,recordType:"delete-files",metricsPrefix:"delete_files",successMessage:"Successfully deleted files",failureMessage:"Failed to delete files"}
|
|
3418
|
+
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"
|
|
3419
|
+
let j=[]
|
|
3420
|
+
if(E)j=E.map((e=>({type:"file",target:e})))
|
|
3421
|
+
else{if(!q)throw Error("Either paths or operations must be specified")
|
|
3422
|
+
j=q.map((e=>{if(e.path)return{type:"file",target:e.path}
|
|
3349
3423
|
if(e.documentId)return{type:"document",target:e.documentId}
|
|
3350
|
-
throw Error("Invalid operation: neither path nor documentId specified")}))}if(0===
|
|
3351
|
-
const
|
|
3352
|
-
|
|
3353
|
-
const
|
|
3354
|
-
|
|
3355
|
-
const
|
|
3356
|
-
for(const e of
|
|
3357
|
-
|
|
3358
|
-
const
|
|
3359
|
-
|
|
3360
|
-
const
|
|
3361
|
-
if(!
|
|
3362
|
-
throw Error(
|
|
3363
|
-
if(
|
|
3364
|
-
const e=await(0,h.commitUserChangesBeforeToolOperation)(
|
|
3365
|
-
e.userChangesCommitted&&(
|
|
3366
|
-
const{toolRecordId:
|
|
3367
|
-
|
|
3368
|
-
const
|
|
3369
|
-
let
|
|
3370
|
-
|
|
3371
|
-
for(let e=0;e
|
|
3424
|
+
throw Error("Invalid operation: neither path nor documentId specified")}))}if(0===j.length)throw Error("At least one file or document must be specified for deletion")
|
|
3425
|
+
const x=j.filter((e=>"file"===e.type)),R=j.filter((e=>"document"===e.type)),M=j.length
|
|
3426
|
+
m.info("Starting mixed file and document deletion operation",{taskId:P,totalOperations:j.length,fileOperations:x.length,documentOperations:R.length,comment:S}),l.validateTaskIdFormat(P,m,s,b.metricsPrefix)
|
|
3427
|
+
const O=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3428
|
+
m.info("Initial branch context",{initialBranch:O.branch,initialRequestId:O.requestId,isMain:O.isMain})
|
|
3429
|
+
const $=[]
|
|
3430
|
+
for(const e of x){const{normalizedPath:t,fullPath:n}=l.validateAndNormalizePath(e.target,r)
|
|
3431
|
+
$.push({normalized:t,full:n})}I=l.FileOperationPhase.TASK_VALIDATION,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3432
|
+
const D=$.length>0?$[0].normalized:"document_operations",A=await l.validateTaskId(P,D,u,m,s,b.metricsPrefix),F=A?.requestId,N=await l.validateWorkItemStates(P,D,u,C,r,m,s,b.metricsPrefix),L=await l.autoPromoteTaskStatus(P,A.status,F,N.request?.status,D,u,C,m,s,b.metricsPrefix)
|
|
3433
|
+
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:x.length,documentOperations:R.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})
|
|
3434
|
+
const z=await l.ensureCorrectWorkspaceContext({taskPromoted:L.taskPromoted,requestId:F,context:r,operation:"delete-files",logger:m,metrics:s,metricsPrefix:b.metricsPrefix})
|
|
3435
|
+
if(!z.success){if(z.isLockConflict)return{content:[{type:"text",text:"\u274c "+z.error}],isError:!0}
|
|
3436
|
+
throw Error(z.error)}let H={hadUserMods:!1,userModsCommitHash:void 0}
|
|
3437
|
+
if(r.git)try{m.debug("[DELETE-FILES] Checking for user changes before mixed delete operations")
|
|
3438
|
+
const e=await(0,h.commitUserChangesBeforeToolOperation)(r.git,"delete-files",{requestId:F,taskId:P,workspaceManager:r.workspaceManager},m,s)
|
|
3439
|
+
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:x.length,documentOperations:R.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:x.length,documentOperations:R.length,error:e instanceof Error?e.message:e+""})}m.debug("[DELETE-FILES] Proceeding with mixed delete operations",{totalOperations:j.length,fileDeletes:x.length,documentDeletes:R.length}),I=l.FileOperationPhase.RECORD_CREATION,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3440
|
+
const{toolRecordId:B,localToolRecordId:U}=await l.createFileOperationRecords(P,F,r.projectId,b.recordType,D,{totalOperations:j.length,fileOperations:x.length,documentOperations:R.length,filePaths:$.map((e=>e.normalized)),documentIds:R.map((e=>e.target)),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},u,v,m,s,b.metricsPrefix,i)
|
|
3441
|
+
w=B,k=B,I=b.fileOperationPhase,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3442
|
+
const G=[]
|
|
3443
|
+
let W=0
|
|
3444
|
+
R.length>0&&n.setProjectId(r.projectId)
|
|
3445
|
+
for(let e=0;e<$.length;e++){const t=$[e],r={type:"file",path:t.normalized,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
3372
3446
|
try{try{await a.default.access(t.full)}catch(e){throw Error("File not found: "+t.normalized)}if((await a.default.stat(t.full)).isDirectory())throw Error("Cannot 'delete' a directory: "+t.normalized)
|
|
3373
|
-
await a.default.unlink(t.full),r.success=!0,
|
|
3374
|
-
for(const e of
|
|
3447
|
+
await a.default.unlink(t.full),r.success=!0,W++,m.info("Successfully deleted file",{path:t.normalized})}catch(e){r.error=(0,f.getErrorMessage)(e),m.warn("Failed to delete file "+t.normalized,{error:r.error})}G.push(r)}const V=R.length>0?n.getDocumentClient():null
|
|
3448
|
+
for(const e of R){const t=e.target,r={type:"document",documentId:t,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0}
|
|
3375
3449
|
try{let e
|
|
3376
|
-
try{if(e=await
|
|
3377
|
-
throw e}try{await(0,p.ensureDocumentNotLocked)(t,
|
|
3378
|
-
throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,f.getErrorMessage)(e)}`)}const
|
|
3379
|
-
|
|
3380
|
-
|
|
3381
|
-
let
|
|
3382
|
-
if(
|
|
3383
|
-
const e=
|
|
3384
|
-
let
|
|
3385
|
-
|
|
3386
|
-
const
|
|
3387
|
-
await l.updateFileOperationRecords(
|
|
3388
|
-
const
|
|
3389
|
-
let
|
|
3390
|
-
if(
|
|
3391
|
-
|
|
3392
|
-
return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n"):"All delete operations failed:\n"+
|
|
3450
|
+
try{if(e=await V.getDocument(t),r.filename=e.filename,m.info("Document found for archival",{documentId:e.id,filename:e.filename,type:e.type,requestId:e.requestId}),e.requestId)try{await(0,g.validateRequestStatusForDocumentOperation)(e.requestId,C,m,s,"delete-document")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
|
|
3451
|
+
throw e}try{await(0,p.ensureDocumentNotLocked)(t,n,m,s,"delete-document-archive")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
|
|
3452
|
+
throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,f.getErrorMessage)(e)}`)}const o=await V.archiveDocument(t)
|
|
3453
|
+
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
|
|
3454
|
+
s.recordValue("delete_files_time",J),s.incrementCounter("delete_files_operations_total",M),s.incrementCounter("delete_files_operations_success",W),s.incrementCounter("delete_files_operations_failed",M-W),s.incrementCounter("delete_files_file_operations",x.length),s.incrementCounter("delete_files_document_operations",R.length),W===M?s.incrementCounter("delete_files_success",1):W>0?s.incrementCounter("delete_files_partial_success",1):s.incrementCounter("delete_files_total_failure",1)
|
|
3455
|
+
let K=null
|
|
3456
|
+
if(W>0){I=l.FileOperationPhase.GIT_COMMIT,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3457
|
+
const e=G.filter((e=>e.success)),t=e.filter((e=>"file"===e.type)).length,n=e.filter((e=>"document"===e.type)).length
|
|
3458
|
+
let o
|
|
3459
|
+
o=t>0&&n>0?`Delete ${t} files and ${n} documents - ${S}`:t>0?1===t?"Delete file - "+S:`Delete ${t} files - ${S}`:1===n?"Delete document - "+S:`Delete ${n} documents - ${S}`,K=await l.commitToGit(P,D,B,U,o,r,m,s,b.metricsPrefix)}I=l.FileOperationPhase.RECORD_UPDATE_SUCCESS,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3460
|
+
const Y=G.filter((e=>e.success)),Q=G.filter((e=>!e.success))
|
|
3461
|
+
await l.updateFileOperationRecords(P,w,k,D,b.recordType,W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,{status:W===M?"completed":"partial_success",commitHash:K?.commitHash,previousCommitHash:K?.previousCommitHash,totalOperations:M,fileOperations:x.length,documentOperations:R.length,successCount:W,failureCount:M-W,successfulOperations:Y.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename}))),failedOperations:Q.map((e=>({type:e.type,path:e.path,documentId:e.documentId,filename:e.filename,error:e.error}))),userComment:S,hadUserMods:H.hadUserMods,userModsCommitHash:H.userModsCommitHash},W===M?`Successfully deleted all ${M} operations`:`Deleted ${W}/${M} operations successfully`,u,v,m,s,b.metricsPrefix)
|
|
3462
|
+
const Z=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3463
|
+
let X=""
|
|
3464
|
+
if(W===M){const e=Y.filter((e=>"file"===e.type)).length,t=Y.filter((e=>"document"===e.type)).length
|
|
3465
|
+
X=e>0&&t>0?`Successfully deleted ${e} files and ${t} documents`:e>0?`Successfully deleted all ${e} ${1===e?"file":"files"}`:`Successfully archived all ${t} ${1===t?"document":"documents"}`}else X=W>0?`Successfully deleted ${W}/${M} operations.\n\nFailed operations:\n`+G.filter((e=>!e.success)).map((e=>{const t="file"===e.type?e.path:`${e.filename||e.documentId} (${e.documentId})`
|
|
3466
|
+
return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n"):"All delete operations failed:\n"+G.map((e=>{const t="file"===e.type?e.path:`${e.filename||e.documentId} (${e.documentId})`
|
|
3393
3467
|
return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n")
|
|
3394
|
-
|
|
3395
|
-
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3468
|
+
if(K?.commitHash&&(X+="\nCommit: "+K.commitHash.substring(0,8)),Z.requestId&&(X+="\nBranch: "+Z.requestId),z.lockAcquired&&z.lockedRequestId){const e=r.workspaceManager?.getCurrentContext(r.currentSessionId)
|
|
3469
|
+
e?.permanentBranch||(X+="\n\u{1f512} **Locked request:** "+z.lockedRequestId)}return{content:[{type:"text",text:X}],isError:0===W}}catch(t){if(e.taskId&&n)try{const o=n.getToolRecordClient(),s=t instanceof d.NotFoundError||t instanceof d.ValidationError||t instanceof u.ZodError
|
|
3470
|
+
await o.createToolRecord({...s?{}:{taskId:e.taskId},projectId:r.projectId,type:"delete-files",metadata:{status:"failed",timestamp:(new Date).toISOString(),totalOperations:e.operations?.length||e.paths?.length||0,fileOperations:e.paths?.length||e.operations?.filter((e=>e.path))?.length||0,documentOperations:e.operations?.filter((e=>e.documentId))?.length||0,paths:e.paths||e.operations?.filter((e=>e.path))?.map((e=>e.path))||[],documentIds:e.operations?.filter((e=>e.documentId))?.map((e=>e.documentId))||[],userComment:e.comment,error:(0,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
|
|
3471
|
+
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
|
|
3472
|
+
try{const r=n.getTaskClient(),o=n.getToolRecordClient()
|
|
3473
|
+
await l.updateFileOperationRecords(e.taskId,w,k,e.paths?.[0]||e.operations?.[0]?.path||e.operations?.[0]?.documentId||"unknown",b.recordType,"Failed to delete operations",{status:"failed",error:(0,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)}}
|
|
3399
3474
|
const a=i(t(1943)),c=t(6183),l=s(t(5967)),d=t(9860),u=t(1569),h=t(7478),g=t(5003),p=t(9949),f=t(8824)},5997(e,exports,t){"use strict"
|
|
3400
3475
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
3401
3476
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
@@ -3405,13 +3480,16 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3405
3480
|
var t={}
|
|
3406
3481
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3407
3482
|
return o(t,e),t})
|
|
3408
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.DebugMultiAgentTool=void 0,exports.handleDebugMultiAgentStatus=async function(e,r,n){try{const e={environmentVariables:{MULTI_AGENT_MODE:"always enabled",ALCHEMY_LOCK_TIMEOUT:process.env.ALCHEMY_LOCK_TIMEOUT},workspaceManager:{available:!!r.workspaceManager,currentContext:r.workspaceManager?.getCurrentContext()||null,activeWorkspaces:r.workspaceManager?.listActiveWorkspaces()||[]},basePath:r.basePath,alchemyPath:a.join(r.basePath,c.ALCHEMY_DIR_NAME),multiAgentMode:!0,fileSystemChecks:{}},n=a.join(r.basePath,c.ALCHEMY_DIR_NAME),o=a.join(n,"worktrees")
|
|
3483
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.DebugMultiAgentTool=void 0,exports.handleDebugMultiAgentStatus=async function(e,r,n){try{const e={environmentVariables:{MULTI_AGENT_MODE:"always enabled",ALCHEMY_LOCK_TIMEOUT:process.env.ALCHEMY_LOCK_TIMEOUT},workspaceManager:{available:!!r.workspaceManager,currentContext:r.workspaceManager?.getCurrentContext(r.currentSessionId)||null,activeWorkspaces:r.workspaceManager?.listActiveWorkspaces()||[]},basePath:r.basePath,alchemyPath:a.join(r.basePath,c.ALCHEMY_DIR_NAME),multiAgentMode:!0,fileSystemChecks:{}},n=a.join(r.basePath,c.ALCHEMY_DIR_NAME),o=a.join(n,"worktrees")
|
|
3409
3484
|
if(e.fileSystemChecks={alchemyLabExists:i.existsSync(n),worktreeBaseExists:i.existsSync(o),worktreeContents:[]},e.fileSystemChecks.worktreeBaseExists)try{const t=i.readdirSync(o)
|
|
3410
3485
|
e.fileSystemChecks.worktreeContents=t}catch(t){e.fileSystemChecks.worktreeReadError=(0,l.getErrorMessage)(t)}try{const t=r.workspaceManager.listActiveWorkspaces()
|
|
3411
3486
|
e.activeWorkspaces=t}catch(t){e.workspaceManagerError=(0,l.getErrorMessage)(t)}try{const n=t(3807)(r.basePath),o=await n.status()
|
|
3412
3487
|
e.gitStatus={current:o.current,tracking:o.tracking,ahead:o.ahead,behind:o.behind,files:o.files.length}}catch(t){e.gitError=(0,l.getErrorMessage)(t)}return JSON.stringify(e,null,2)}catch(e){return n.error("Error in debug_multi_agent_status",{error:(0,l.getErrorMessage)(e)}),"Error generating debug information: "+(0,l.getErrorMessage)(e)}}
|
|
3413
3488
|
const i=s(t(9896)),a=s(t(6928)),c=t(4139),l=t(8824)
|
|
3414
|
-
exports.DebugMultiAgentTool={name:"debug_multi_agent_status",description:"Check multi-agent mode status, worktree state, and configuration for debugging",inputSchema:{type:"object",properties:{},required:[]}}},
|
|
3489
|
+
exports.DebugMultiAgentTool={name:"debug_multi_agent_status",description:"Check multi-agent mode status, worktree state, and configuration for debugging",inputSchema:{type:"object",properties:{},required:[]}}},6064(e,exports,t){"use strict"
|
|
3490
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=exports.TasksSchema=void 0
|
|
3491
|
+
const r=t(1569),n=t(7561)
|
|
3492
|
+
exports.TasksSchema=r.z.object({operation:r.z.enum(["create","done","list"]).describe("Operation to perform:\n\u2022 create - Create a new task (requestId auto-resolved from session)\n\u2022 done - Complete the active (in_progress) task with a summary\n\u2022 list - List tasks for the current request"),title:r.z.string().optional().describe("Task title (required for create)"),description:r.z.string().optional().describe("Task description (required for create)"),summary:r.z.string().optional().describe("Completion summary (required for done)")}),exports.def={name:"subtasks",description:"Manage subtasks for your current request.\n\n\u2022 create { title, description } \u2014 creates a task. First task auto-starts.\n\u2022 done { summary } \u2014 completes the active task. Next pending task auto-starts.\n\u2022 list \u2014 shows all tasks and their status.\n\nNo requestId or taskId needed \u2014 resolved automatically from your session.",schema:exports.TasksSchema,annotations:{title:"Tasks",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleTasks)(e,t.context,t.apiClient,t.logger,t.metrics,t.cliOrigin)}}},6111(e,exports,t){"use strict"
|
|
3415
3493
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3416
3494
|
const r=t(6183),n=t(5434)
|
|
3417
3495
|
exports.def={name:"get_request_information",description:"Get comprehensive request information",schema:r.GetRequestInformationSchema,annotations:{title:"Get Request Information",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleGetRequestInformation)(e,t.context,t.apiClient,t.logger,t.metrics)}}},6153(e,exports,t){"use strict"
|
|
@@ -3458,22 +3536,18 @@ const n=await this.requestWithRetry("POST","/api/files/recover",t)
|
|
|
3458
3536
|
if(!(0,i.safeGetResponseData)(n,null))throw new r.ServiceError("Empty response when recovering file")
|
|
3459
3537
|
const o=(0,i.safeGetResponseData)(n,{success:!0,path:e.path,commitHash:e.commitHash,backupPath:void 0})
|
|
3460
3538
|
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"
|
|
3461
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranchSchema=exports.PlanWriteSchema=exports.PlanReadSchema=exports.DocumentOperationsSchema=exports.SearchDocumentsSchema=exports.CreateDocumentSchema=exports.ReplaceLinesSchema=exports.InsertLinesSchema=exports.SwitchToRequestBranchSchema=exports.PlannerOpsSchema=exports.SpecialistOpsSchema=exports.SubagentOperationsSchema=exports.TaskOperationsSchema=exports.CompleteTaskSchema=exports.GetTaskInformationSchema=exports.GetRequestInformationSchema=exports.ListRequestsSchema=exports.ListTasksSchema=exports.SearchSchema=exports.QueryHistorySchema=exports.FileRecoverSchema=exports.FileHistorySchema=exports.DeleteFilesSchema=exports.DeleteFileSchema=exports.ReplaceInFilesSchema=exports.ReplaceStringsSchema=exports.ReplaceStringSchema=exports.MoveFilesSchema=exports.CreateDirectorySchema=exports.GetFileInfoSchema=exports.ListDirectorySchema=exports.ReadFilesSchema=exports.ViewAssetSchema=exports.WriteFileSchema=exports.UpdateTaskStatusSchema=exports.CreateTaskSchema=exports.CreateRequestSchema=exports.CompleteRequestSchema=exports.ExecutedTestSchema=exports.TestVerificationSchema=exports.TestDefinitionSchema=exports.AcceptanceCriterionSchema=exports.RecordTypeEnum=exports.EvidenceTypeEnum=exports.CriterionStatusEnum=exports.RequestStatusEnum=exports.TaskStatusEnum=exports.RequestTypeEnum=exports.TestCoverageTypeEnum=exports.CompletionStatusEnum=void 0,exports.UpdateSpecializationSchema=exports.SessionMessageOperationsSchema=exports.ReportTestResultsSchema=exports.ExecuteTestCommandSchema=exports.TestingReferenceSchema=exports.TestingProcessUpdateSchema=exports.TestingProcessCreateSchema=exports.TestingProcessGetSchema=exports.TestingProcessListSchema=exports.MetaReferenceSchema=exports.MetaAgentListSchema=exports.MetaWorkflowRemoveRecipeSchema=exports.MetaWorkflowAddRecipeSchema=exports.MetaHookCreateSchema=exports.MetaHookListSchema=exports.MetaRecipeRemoveHookSchema=exports.MetaRecipeAddHookSchema=exports.MetaRecipeCreateSchema=exports.MetaRecipeGetSchema=exports.MetaRecipeListSchema=exports.MetaWorkflowUpdateSchema=exports.MetaWorkflowCreateSchema=exports.MetaWorkflowGetSchema=exports.MetaWorkflowListSchema=exports.GenerateRequestJournalSchema=exports.QuickManageSchema=exports.QuickReplaceSchema=exports.QuickWriteSchema=exports.RequestOperationsSchema=exports.ManageFilesSchema=exports.ModifyFileSchema=exports.RevertRequestSchema=exports.SwitchToBranchSchema=void 0
|
|
3462
|
-
const r=t(1569),n=t(8955),o=r.z.string().refine((e
|
|
3463
|
-
exports.CompletionStatusEnum=r.z.enum(["complete","incomplete","partial"]),exports.TestCoverageTypeEnum=r.z.enum(["unit","e2e","integration","manual"]),exports.RequestTypeEnum=r.z.enum(["feature","bugfix","quick-edit"]),exports.TaskStatusEnum=r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]),exports.RequestStatusEnum=r.z.enum(["open","in_progress","ready_for_review","ready_for_merge","completed","canceled","reverted","conflicted"]),exports.CriterionStatusEnum=r.z.enum(["unverified","verified"]),exports.EvidenceTypeEnum=r.z.enum(["test","manual","other"]),exports.RecordTypeEnum=r.z.enum(["write","modify","blocker","resolution","discovery","test","delete"]),exports.AcceptanceCriterionSchema=r.z.object({description:r.z.string(),status:r.z.enum(["unverified","verified"]).default("unverified"),evidence:r.z.string().nullable().optional(),evidenceType:r.z.enum(["test","manual","other"]).nullable().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.TestDefinitionSchema=r.z.object({id:r.z.string(),description:r.z.string(),status:exports.CompletionStatusEnum,coverageType:exports.TestCoverageTypeEnum,accepts:r.z.array(r.z.string())}),exports.TestVerificationSchema=r.z.object({criteria:r.z.array(r.z.string()),tests:r.z.array(r.z.string()),coverageType:exports.TestCoverageTypeEnum,coverageRatio:r.z.number(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional()}),exports.ExecutedTestSchema=r.z.object({id:r.z.string(),testId:r.z.string(),status:exports.CompletionStatusEnum,results:r.z.string(),coverage:r.z.array(r.z.string()),executedAt:r.z.string()}),exports.CompleteRequestSchema=r.z.object({status:exports.RequestStatusEnum,acceptanceCriteria:r.z.array(exports.AcceptanceCriterionSchema),testVerification:exports.TestVerificationSchema.optional(),completionSummary:r.z.string().optional()}),exports.CreateRequestSchema=r.z.object({title:r.z.string(),type:r.z.enum(["feature","bugfix"]),description:r.z.string(),acceptanceCriteria:r.z.array(r.z.string()),planDocumentId:r.z.string().optional()}),exports.CreateTaskSchema=r.z.object({requestId:s,title:r.z.string(),description:r.z.string()}),exports.UpdateTaskStatusSchema=r.z.object({taskId:o,status:exports.TaskStatusEnum,note:r.z.string()}),exports.WriteFileSchema=r.z.object({taskId:o,path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional(),comment:r.z.string()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}),exports.ViewAssetSchema=r.z.object({filename:r.z.string().describe("The asset filename (e.g., 01JMXYZ.png)")}),exports.ReadFilesSchema=r.z.object({paths:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),lines:r.z.string().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),encoding:r.z.enum(["utf8","utf-8","ascii","binary"]).optional()}),exports.ListDirectorySchema=r.z.object({path:r.z.string(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}),exports.GetFileInfoSchema=r.z.object({path:r.z.string()}),exports.CreateDirectorySchema=r.z.object({path:r.z.string(),taskId:o,comment:r.z.string().optional()}),exports.MoveFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()})),comment:r.z.string()}),exports.ReplaceStringSchema=r.z.object({taskId:o,path:r.z.string(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional(),comment:r.z.string()}),exports.ReplaceStringsSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceInFilesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1,"old string cannot be empty"),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1,"At least one replacement required"),fuzzy_match:r.z.boolean().optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"Either path or documentId is required, but not both"})).min(1,"At least one operation required"),fuzzy_match:r.z.boolean().optional().default(!0),comment:r.z.string()}),exports.DeleteFileSchema=r.z.object({taskId:o,path:r.z.string(),comment:r.z.string()}),exports.DeleteFilesSchema=r.z.object({taskId:o,paths:r.z.array(r.z.string()).optional(),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})).optional(),comment:r.z.string()}).refine((e=>e.paths&&!e.operations||!e.paths&&e.operations),{message:"paths or operations required"}).refine((e=>e.paths?.length||e.operations?.length),{message:"path/operation required"}),exports.FileHistorySchema=r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}),exports.FileRecoverSchema=r.z.object({taskId:o,path:r.z.string(),commitHash:r.z.string(),createBackup:r.z.boolean().default(!0)}),exports.QueryHistorySchema=r.z.object({queryType:r.z.enum(["file-history","request-file-history","recover","blame"],{errorMap(){return{message:"Invalid queryType. Valid options: file-history, request-file-history, recover, blame"}}}),fileHistory:r.z.object({path:r.z.string(),limit:r.z.number().min(1).max(100).default(10),showDiff:r.z.boolean().default(!1),showTraceability:r.z.boolean().default(!0),branch:r.z.string().optional(),commit:r.z.string().optional(),since:r.z.string().optional()}).optional(),requestHistory:r.z.object({requestId:s,detailLevel:r.z.enum(["summary","detailed"]).default("summary"),taskId:o.optional(),showDiff:r.z.boolean().optional(),fileFilter:r.z.string().optional()}).optional(),recover:r.z.object({taskId:o,path:r.z.string(),commitHash:r.z.string().optional(),createBackup:r.z.boolean().default(!0)}).optional(),blame:r.z.object({path:r.z.string(),lines:r.z.string().optional(),branch:r.z.string().optional()}).optional()}).refine((e=>"file-history"===e.queryType?e.fileHistory&&!e.requestHistory&&!e.recover:"request-file-history"===e.queryType?e.requestHistory&&!e.fileHistory&&!e.recover:"recover"===e.queryType?e.recover&&!e.fileHistory&&!e.requestHistory&&!e.blame:"blame"===e.queryType&&e.blame&&!e.fileHistory&&!e.requestHistory&&!e.recover),{message:"Invalid query data"}),exports.SearchSchema=r.z.object({needle:r.z.string().optional(),directory:r.z.string().optional(),options:r.z.object({caseSensitive:r.z.boolean().optional(),fileExtension:r.z.string().optional(),maxResults:r.z.number().optional(),useRegex:r.z.boolean().optional(),searchIn:r.z.enum(["content","filename","both"]).default("content").optional(),contextLines:r.z.number().min(0).max(10).optional(),levels:r.z.number().min(1).max(4).optional(),sortBy:r.z.enum(["name","modified","size","type"]).optional()}).optional()}),exports.ListTasksSchema=r.z.object({requestId:s,filters:r.z.object({status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.ListRequestsSchema=r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["open","in_progress","ready_for_review","completed","canceled"]).optional(),planDocumentId:r.z.string().optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}),exports.GetRequestInformationSchema=r.z.object({requestId:s}),exports.GetTaskInformationSchema=r.z.object({taskId:o}),exports.CompleteTaskSchema=r.z.object({taskId:o,summary:r.z.string()}),exports.TaskOperationsSchema=r.z.object({operation:r.z.enum(["get-info","list"]),taskId:o.optional(),requestId:s.optional(),status:r.z.enum(["pending","in_progress","ready_for_review","completed","canceled","reverted"]).optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).superRefine(((e,t)=>{"get-info"!==e.operation||e.taskId||t.addIssue({code:"custom",message:'taskId is required for get-info. Example: { "operation": "get-info", "taskId": "tas000001" }'}),"list"!==e.operation||e.requestId||t.addIssue({code:"custom",message:'requestId is required for list. Example: { "operation": "list", "requestId": "req000001" }'})}))
|
|
3539
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranchSchema=exports.PlanWriteSchema=exports.PlanReadSchema=exports.DocumentOperationsSchema=exports.SearchDocumentsSchema=exports.CreateDocumentSchema=exports.ReplaceLinesSchema=exports.InsertLinesSchema=exports.SwitchToRequestBranchSchema=exports.PlannerOpsSchema=exports.SpecialistOpsSchema=exports.SubagentOperationsSchema=exports.TaskOperationsSchema=exports.CompleteTaskSchema=exports.GetTaskInformationSchema=exports.GetRequestInformationSchema=exports.ListRequestsSchema=exports.ListTasksSchema=exports.SearchSchema=exports.QueryHistorySchema=exports.FileRecoverSchema=exports.FileHistorySchema=exports.DeleteFilesSchema=exports.DeleteFileSchema=exports.ReplaceInFilesSchema=exports.ReplaceStringsSchema=exports.ReplaceStringSchema=exports.MoveFilesSchema=exports.CreateDirectorySchema=exports.GetFileInfoSchema=exports.ListDirectorySchema=exports.ReadFilesSchema=exports.ViewAssetSchema=exports.WriteFileSchema=exports.UpdateTaskStatusSchema=exports.CreateTaskSchema=exports.CreateRequestSchema=exports.CompleteRequestSchema=exports.ExecutedTestSchema=exports.TestVerificationSchema=exports.TestDefinitionSchema=exports.AcceptanceCriterionSchema=exports.RecordTypeEnum=exports.EvidenceTypeEnum=exports.CriterionStatusEnum=exports.RequestStatusEnum=exports.TaskStatusEnum=exports.RequestTypeEnum=exports.TestCoverageTypeEnum=exports.CompletionStatusEnum=void 0,exports.UpdateSpecializationSchema=exports.SessionMessageOperationsSchema=exports.ReportTestResultsSchema=exports.CommandsSchema=exports.ExecuteTestCommandSchema=exports.TestingReferenceSchema=exports.TestingProcessUpdateSchema=exports.TestingProcessCreateSchema=exports.TestingProcessGetSchema=exports.TestingProcessListSchema=exports.MetaReferenceSchema=exports.MetaAgentListSchema=exports.MetaWorkflowRemoveRecipeSchema=exports.MetaWorkflowAddRecipeSchema=exports.MetaHookCreateSchema=exports.MetaHookListSchema=exports.MetaRecipeRemoveHookSchema=exports.MetaRecipeAddHookSchema=exports.MetaRecipeCreateSchema=exports.MetaRecipeGetSchema=exports.MetaRecipeListSchema=exports.MetaWorkflowUpdateSchema=exports.MetaWorkflowCreateSchema=exports.MetaWorkflowGetSchema=exports.MetaWorkflowListSchema=exports.GenerateRequestJournalSchema=exports.QuickManageSchema=exports.QuickReplaceSchema=exports.QuickWriteSchema=exports.RequestOperationsSchema=exports.ManageFilesSchema=exports.ModifyFileSchema=exports.RevertRequestSchema=exports.SwitchToBranchSchema=void 0
|
|
3540
|
+
const r=t(1569),n=t(8955),o=r.z.string().refine((e=>!(!e||!/^tas\d{6}$/.test(e)&&!/^req\d{6}#\d+$/.test(e))),{message:"Task ID must be req######+#NN (e.g. req000005#03) or tas###### format (e.g. tas000001)."}),s=r.z.string().refine((e=>!!e&&/^req\d{6}$/.test(e)),{message:"Request ID must match format: req###### (e.g. req000001)"}),i=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^(doc|plan|jour)\d{6}$/.test(e))),{message:"Document ID must match format: doc_[26 alphanumeric] (ULID) or doc######/plan######/jour###### (local ID)"})
|
|
3541
|
+
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" }'})}))
|
|
3464
3542
|
const a=r.z.string().min(1).describe("OpenCode session ID")
|
|
3465
|
-
exports.SubagentOperationsSchema=r.z.object({sessionId:a.optional(),operation:r.z.enum(["spawn","continue","check-status","abort","read-messages","list-sessions"]),
|
|
3466
|
-
return"spawn"===e.operation?r&&!n&&!o:"continue"===e.operation?n&&!r&&!o&&t:"check-status"===e.operation||"abort"===e.operation?!r&&!n&&!o&&t:"read-messages"===e.operation?!r&&!n&&t:"list-sessions"===e.operation&&!(r||n||o||t)}),{message:"Invalid operation data: spawn requires spawn object, continue/check-status/abort/read-messages require sessionId"}),exports.SpecialistOpsSchema=r.z.object({operation:r.z.enum(["delegate","follow-up","check-status","list","abort"]),sessionId:a.optional(),delegate:r.z.object({prompt:r.z.string().min(1).describe("Detailed instructions for the specialist"),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars)"),requestId:r.z.string().regex(/^req\d{6}$/).describe("Request ID to associate with the work").optional(),specialization:r.z.string().max(500).describe('Domain description for the specialist (e.g. "Frontend UI components", "Database migrations")')}).optional(),followUp:r.z.object({prompt:r.z.string().min(1).describe("Follow-up instructions or feedback for the specialist"),specialization:r.z.string().max(500).describe("Update the specialist's domain description if their focus has shifted").optional()}).optional(),list:r.z.object({activeOnly:r.z.boolean().default(!1).describe("Only show active/busy specialists"),requestId:r.z.string().optional().describe("Filter to specialists working on a specific request"),limit:r.z.number().min(1).max(100).optional().describe("Max sessions to return")}).optional()}).refine((e=>{const t=!!e.sessionId,r=!!e.delegate,n=!!e.followUp
|
|
3467
|
-
return"delegate"===e.operation?r&&!n&&!t:"follow-up"===e.operation?n&&!r&&t:"check-status"===e.operation||"abort"===e.operation?!r&&!n&&t:"list"===e.operation&&!r&&!n&&!t}),{message:"Invalid operation data: delegate requires delegate object, follow-up/check-status/abort require sessionId"}),exports.PlannerOpsSchema=r.z.object({operation:r.z.enum(["request","check-status","list"]),request:r.z.object({prompt:r.z.string().min(1).describe("What to plan \u2014 feature description, architecture question, etc."),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars)")}).optional(),sessionId:a.optional(),list:r.z.object({activeOnly:r.z.boolean().default(!1).describe("Only show active/busy planning sessions"),limit:r.z.number().min(1).max(100).optional().describe("Max sessions to return")}).optional()}).refine((e=>{const t=!!e.request,r=!!e.sessionId
|
|
3468
|
-
return"request"===e.operation?t&&!r:"check-status"===e.operation?!t&&r:"list"===e.operation&&!t&&!r}),{message:"Invalid operation data: request requires request object, check-status requires sessionId"}),exports.SwitchToRequestBranchSchema=r.z.object({requestId:s}),exports.InsertLinesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceLinesSchema=r.z.object({taskId:o,operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.CreateDocumentSchema=r.z.object({requestId:s.optional(),filename:r.z.string().refine((e=>e.toLowerCase().endsWith(".md")),{message:"Filename must end with .md extension"}),content:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"],{errorMap(){return{message:"Document type must be one of: Report, Documentation, Plan, Other"}}}),comment:r.z.string()}),exports.SearchDocumentsSchema=r.z.object({query:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),requestId:s.optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both")}),exports.DocumentOperationsSchema=r.z.object({operation:r.z.enum(["create","search","create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"]),documentId:i.optional(),requestId:s.optional(),filename:r.z.string().optional(),content:r.z.string().optional(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),comment:r.z.string().optional(),query:r.z.string().optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional(),selectedText:r.z.string().optional(),prefixContext:r.z.string().optional(),suffixContext:r.z.string().optional(),lineHint:r.z.number().int().optional(),body:r.z.string().optional(),annotationId:r.z.string().optional()}).superRefine(((e,t)=>{const r=e.operation;["create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"].includes(r)&&!e.documentId&&t.addIssue({code:"custom",message:`documentId is required for '${r}'. Example: { "operation": "${r}", "documentId": "doc000001" }`}),"create"===r&&(e.filename?e.filename.toLowerCase().endsWith(".md")||t.addIssue({code:"custom",message:"Filename must end with .md extension"}):t.addIssue({code:"custom",message:"filename is required for create (must end with .md)"}),e.content||t.addIssue({code:"custom",message:"content is required for create"}),e.type||t.addIssue({code:"custom",message:"type is required for create (Report, Documentation, Plan, or Other)"}),e.comment||t.addIssue({code:"custom",message:"comment is required for create"})),"search"!==r||e.query||t.addIssue({code:"custom",message:'query is required for search. Example: { "operation": "search", "query": "search term" }'}),"get-version"!==r&&"restore-version"!==r||e.versionNumber||t.addIssue({code:"custom",message:`versionNumber is required for '${r}'`}),"create-annotation"===r&&(e.selectedText||t.addIssue({code:"custom",message:"selectedText is required for create-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for create-annotation"})),"reply-to-annotation"===r&&(e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for reply-to-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for reply-to-annotation"})),"resolve-annotation"!==r||e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for resolve-annotation"})}))
|
|
3543
|
+
exports.SubagentOperationsSchema=r.z.object({sessionId:a.optional(),operation:r.z.enum(["spawn","continue","check-status","abort","read-messages","list-sessions"]),prompt:r.z.string().min(1).describe("Instructions for the subagent (required for spawn and continue)").optional(),agent:r.z.string().default("work").refine((e=>(0,n.isValidAgent)(e)),{message:"Invalid agent. Check tool description for available agents."}).describe("The subagent type to spawn (see tool description for available agents)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, spawn only)").optional(),requestId:r.z.string().describe("Request ID \u2014 associates work (spawn) or filters results (list-sessions)").optional(),allowParallel:r.z.boolean().describe("Allow spawning even if request already has active workers (spawn only)").optional(),useExistingSession:r.z.string().describe("Existing session ID to send prompt to instead of creating new session (spawn only)").optional(),limit:r.z.number().min(1).max(100).describe("Max items to return (read-messages: max 50, list-sessions: max 100)").optional(),activeOnly:r.z.boolean().describe("Only show sessions that are currently active/busy (list-sessions only)").optional(),minTokens:r.z.number().min(0).describe("Only show sessions with at least this many tokens (list-sessions only)").optional(),maxTokens:r.z.number().min(0).describe("Only show sessions with at most this many tokens (list-sessions only)").optional(),maxAgeHours:r.z.number().min(0).describe("Only show sessions newer than X hours (list-sessions only)").optional()}).refine((e=>"spawn"===e.operation?!!e.prompt:"continue"===e.operation?!!e.prompt&&!!e.sessionId:"check-status"===e.operation||"abort"===e.operation||"read-messages"===e.operation?!!e.sessionId:"list-sessions"===e.operation),{message:"spawn requires prompt; continue requires prompt+sessionId; check-status/abort/read-messages require sessionId"}),exports.SpecialistOpsSchema=r.z.object({operation:r.z.enum(["delegate","follow-up","check-status","list","abort"]),sessionId:a.optional(),prompt:r.z.string().min(1).describe("Instructions for the specialist (required for delegate and follow-up)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, delegate only)").optional(),specialization:r.z.string().max(500).describe('Domain description (e.g. "Frontend UI components"). Required for delegate, optional update for follow-up').optional(),requestId:r.z.string().describe("Request ID \u2014 associates work (delegate) or filters results (list)").optional(),activeOnly:r.z.boolean().describe("Only show active/busy specialists (list only)").optional(),limit:r.z.number().min(1).max(100).describe("Max sessions to return (list only)").optional()}).refine((e=>"delegate"===e.operation?!!e.prompt&&!!e.specialization&&!e.sessionId:"follow-up"===e.operation?!!e.prompt&&!!e.sessionId:"check-status"===e.operation||"abort"===e.operation?!!e.sessionId:"list"===e.operation),{message:"delegate requires prompt+specialization; follow-up requires prompt+sessionId; check-status/abort require sessionId"}),exports.PlannerOpsSchema=r.z.object({operation:r.z.enum(["request","check-status","list"]),sessionId:a.optional(),prompt:r.z.string().min(1).describe("What to plan \u2014 feature description, architecture question, etc. (required for request)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, request only)").optional(),activeOnly:r.z.boolean().describe("Only show active/busy planning sessions (list only)").optional(),limit:r.z.number().min(1).max(100).describe("Max sessions to return (list only)").optional()}).refine((e=>"request"===e.operation?!!e.prompt:"check-status"===e.operation?!!e.sessionId:"list"===e.operation),{message:"request requires prompt; check-status requires sessionId"}),exports.SwitchToRequestBranchSchema=r.z.object({requestId:s}),exports.InsertLinesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceLinesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.CreateDocumentSchema=r.z.object({requestId:s.optional(),filename:r.z.string().refine((e=>e.toLowerCase().endsWith(".md")),{message:"Filename must end with .md extension"}),content:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"],{errorMap(){return{message:"Document type must be one of: Report, Documentation, Plan, Other"}}}),comment:r.z.string()}),exports.SearchDocumentsSchema=r.z.object({query:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),requestId:s.optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both")}),exports.DocumentOperationsSchema=r.z.object({operation:r.z.enum(["create","search","create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"]),documentId:i.optional(),requestId:s.optional(),filename:r.z.string().optional(),content:r.z.string().optional(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),comment:r.z.string().optional(),query:r.z.string().optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional(),selectedText:r.z.string().optional(),prefixContext:r.z.string().optional(),suffixContext:r.z.string().optional(),lineHint:r.z.number().int().optional(),body:r.z.string().optional(),annotationId:r.z.string().optional()}).superRefine(((e,t)=>{const r=e.operation;["create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"].includes(r)&&!e.documentId&&t.addIssue({code:"custom",message:`documentId is required for '${r}'. Example: { "operation": "${r}", "documentId": "doc000001" }`}),"create"===r&&(e.filename?e.filename.toLowerCase().endsWith(".md")||t.addIssue({code:"custom",message:"Filename must end with .md extension"}):t.addIssue({code:"custom",message:"filename is required for create (must end with .md)"}),e.content||t.addIssue({code:"custom",message:"content is required for create"}),e.type||t.addIssue({code:"custom",message:"type is required for create (Report, Documentation, Plan, or Other)"}),e.comment||t.addIssue({code:"custom",message:"comment is required for create"})),"search"!==r||e.query||t.addIssue({code:"custom",message:'query is required for search. Example: { "operation": "search", "query": "search term" }'}),"get-version"!==r&&"restore-version"!==r||e.versionNumber||t.addIssue({code:"custom",message:`versionNumber is required for '${r}'`}),"create-annotation"===r&&(e.selectedText||t.addIssue({code:"custom",message:"selectedText is required for create-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for create-annotation"})),"reply-to-annotation"===r&&(e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for reply-to-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for reply-to-annotation"})),"resolve-annotation"!==r||e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for resolve-annotation"})}))
|
|
3469
3544
|
const c=r.z.string().refine((e=>!!e&&(/^doc_[0-9A-Z]{26}$/i.test(e)||/^plan\d{6}$/.test(e))),{message:"Plan ID must match format: doc_[26 alphanumeric] (ULID) or plan###### (local ID)"})
|
|
3470
3545
|
exports.PlanReadSchema=r.z.object({operation:r.z.enum(["get","get-active","list","get-history","get-requests"]),planId:c.optional(),searchQuery:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["createdAt","updatedAt","filename"]).default("updatedAt"),sortDirection:r.z.enum(["ASC","DESC"]).default("DESC")}).superRefine(((e,t)=>{["get","get-history","get-requests"].includes(e.operation)&&!e.planId&&t.addIssue({code:"custom",message:`planId is required for '${e.operation}'. Example: { "operation": "${e.operation}", "planId": "plan000001" }`})})),exports.PlanWriteSchema=r.z.object({operation:r.z.enum(["update","append","replace","create-snapshot","restore","set-active"]),planId:c,content:r.z.string().optional(),name:r.z.string().optional().describe("Optional new name for the plan"),old:r.z.string().optional().describe("Text to find in the plan (for replace)"),new:r.z.string().optional().describe("Replacement text (for replace)"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional()}).superRefine(((e,t)=>{const r=e.operation
|
|
3471
|
-
"update"!==r&&"append"!==r||e.content||t.addIssue({code:"custom",message:`content is required for '${r}'. Example: { "operation": "${r}", "planId": "plan000001", "content": "..." }`}),"replace"===r&&(e.old||t.addIssue({code:"custom",message:'old is required for replace. Example: { "operation": "replace", "planId": "plan000001", "old": "find this", "new": "replace with" }'}),void 0===e.new&&t.addIssue({code:"custom",message:"new is required for replace"})),"restore"!==r||e.versionNumber||t.addIssue({code:"custom",message:'versionNumber is required for restore. Example: { "operation": "restore", "planId": "plan000001", "versionNumber": 1 }'})})),exports.SwitchToMainBranchSchema=r.z.object({}),exports.SwitchToBranchSchema=r.z.object({branch:r.z.string().optional(),password:r.z.string().optional()}),exports.RevertRequestSchema=r.z.object({requestId:s,reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}),exports.ModifyFileSchema=r.z.object({
|
|
3472
|
-
|
|
3473
|
-
|
|
3474
|
-
o&&!e[o.field]&&t.addIssue({code:"custom",message:`'${n}' operation requires '${o.field}' data. ${o.hint}`})})),exports.QuickWriteSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),path:r.z.string().optional(),documentId:i.optional(),content:r.z.union([r.z.string(),r.z.record(r.z.any()),r.z.array(r.z.unknown())]),format:r.z.enum(["text","json"]).optional(),append:r.z.boolean().optional()}),exports.QuickReplaceSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({old:r.z.string().min(1),new:r.z.string(),match_mode:r.z.enum(["unique","all"]).optional()})).min(1),fuzzy_match:r.z.boolean().optional()})).min(1),fuzzy_match:r.z.boolean().optional(),comment:r.z.string().min(1,"Comment describing the change is required")}),exports.QuickManageSchema=r.z.object({title:r.z.string().min(1,"Title is required"),description:r.z.string().min(1,"Description is required"),operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}))}).optional()})).min(1)}),exports.GenerateRequestJournalSchema=r.z.object({requestId:r.z.string().regex(/^req[_\d].+$/,"Invalid request ID format. Expected format: req_[26 chars] or req######")}),exports.MetaWorkflowListSchema=r.z.object({}),exports.MetaWorkflowGetSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to retrieve")}),exports.MetaWorkflowCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the workflow"),shortName:r.z.string().min(1).max(10).describe("Short display name (required, max 10 chars)"),description:r.z.string().optional().describe("Description of what the workflow does"),documentation:r.z.string().optional().describe("Detailed documentation"),defaultAgent:r.z.string().optional().describe("Default agent template to use"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior: auto-merge (default), auto-test-then-merge, or manual-review"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaWorkflowUpdateSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to update"),name:r.z.string().min(1).optional().describe("New name"),shortName:r.z.string().max(10).optional().describe("New short name (max 10 chars)"),description:r.z.string().optional().describe("New description"),documentation:r.z.string().optional().describe("New documentation"),defaultAgent:r.z.string().optional().describe("New default agent"),completionMode:r.z.enum(["auto-merge","auto-test-then-merge","manual-review"]).optional().describe("Request completion behavior"),approvalMode:r.z.enum(["none","require-approval"]).optional().describe("Pre-work approval: none (default) or require-approval")}),exports.MetaRecipeListSchema=r.z.object({}),exports.MetaRecipeGetSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to retrieve")}),exports.MetaRecipeCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the recipe"),description:r.z.string().optional().describe("Description of what the recipe does"),documentation:r.z.string().optional().describe("Detailed documentation")}),exports.MetaRecipeAddHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to add the hook to"),hookId:r.z.string().describe("Hook template ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the recipe (0-based, appended if omitted)")}),exports.MetaRecipeRemoveHookSchema=r.z.object({recipeId:r.z.string().describe("Recipe ID to remove the hook from"),hookId:r.z.string().describe("Hook template ID to remove")}),exports.MetaHookListSchema=r.z.object({}),exports.MetaHookCreateSchema=r.z.object({name:r.z.string().min(1).describe("Unique name for the hook"),description:r.z.string().optional().describe("Description of what the hook does"),eventType:r.z.string().describe("Event type that triggers this hook (e.g., session_idle, request_completed, custom:plan_ready)"),category:r.z.enum(["alchemy","session","message","editing","reading","file_management","documents","history","tool"]).default("session").describe("Hook category"),agent:r.z.string().describe("Agent template to execute when hook fires"),promptTemplate:r.z.string().describe("Prompt template with {{variable}} substitution"),condition:r.z.record(r.z.any()).optional().describe("Condition object for filtering when hook fires"),executionMode:r.z.enum(["same_session","sub_agent","background","notification","direct_report"]).default("background").describe("How to execute the hook"),timing:r.z.enum(["before","after"]).default("after").describe("When to fire relative to the event"),maxIterations:r.z.number().int().min(1).optional().describe("Maximum times to fire per session"),emitEvent:r.z.string().optional().describe("Custom event to emit on completion"),emitEventOnCondition:r.z.union([r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}),r.z.array(r.z.object({condition:r.z.object({field:r.z.string(),operator:r.z.enum(["contains","not_contains","equals","not_equals","matches","not_matches"]),value:r.z.string()}),event:r.z.string()}))]).optional().describe("Conditional event emission based on output")}),exports.MetaWorkflowAddRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to add the recipe to"),recipeId:r.z.string().describe("Recipe ID to add"),position:r.z.number().int().min(0).optional().describe("Position in the workflow (0-based, appended if omitted)")}),exports.MetaWorkflowRemoveRecipeSchema=r.z.object({workflowId:r.z.string().describe("Workflow ID to remove the recipe from"),recipeId:r.z.string().describe("Recipe ID to remove")}),exports.MetaAgentListSchema=r.z.object({}),exports.MetaReferenceSchema=r.z.object({}),exports.TestingProcessListSchema=r.z.object({}),exports.TestingProcessGetSchema=r.z.object({processId:r.z.string().describe("Test process ID to retrieve")})
|
|
3546
|
+
"update"!==r&&"append"!==r||e.content||t.addIssue({code:"custom",message:`content is required for '${r}'. Example: { "operation": "${r}", "planId": "plan000001", "content": "..." }`}),"replace"===r&&(e.old||t.addIssue({code:"custom",message:'old is required for replace. Example: { "operation": "replace", "planId": "plan000001", "old": "find this", "new": "replace with" }'}),void 0===e.new&&t.addIssue({code:"custom",message:"new is required for replace"})),"restore"!==r||e.versionNumber||t.addIssue({code:"custom",message:'versionNumber is required for restore. Example: { "operation": "restore", "planId": "plan000001", "versionNumber": 1 }'})})),exports.SwitchToMainBranchSchema=r.z.object({}),exports.SwitchToBranchSchema=r.z.object({branch:r.z.string().optional(),password:r.z.string().optional()}),exports.RevertRequestSchema=r.z.object({requestId:s,reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}),exports.ModifyFileSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),operationType:r.z.enum(["replace-string","insert-lines","replace-lines","delete-string","delete-lines"]),replaceString:r.z.object({replacements:r.z.array(r.z.object({old_str:r.z.string(),new_str:r.z.string()})),mode:r.z.enum(["unique","all"]).optional()}).optional(),insertLines:r.z.object({insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).optional(),replaceLines:r.z.object({replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).optional(),deleteString:r.z.object({patterns:r.z.array(r.z.string()),mode:r.z.enum(["all","unique"]).optional()}).optional(),deleteLines:r.z.object({lines:r.z.string()}).optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}).refine((e=>"replace-string"===e.operationType?e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"insert-lines"===e.operationType?e.insertLines&&!e.replaceString&&!e.replaceLines&&!e.deleteString&&!e.deleteLines:"replace-lines"===e.operationType?e.replaceLines&&!e.replaceString&&!e.insertLines&&!e.deleteString&&!e.deleteLines:"delete-string"===e.operationType?e.deleteString&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteLines:"delete-lines"===e.operationType&&e.deleteLines&&!e.replaceString&&!e.insertLines&&!e.replaceLines&&!e.deleteString),{message:"Invalid operation data"})),comment:r.z.string()}),exports.ManageFilesSchema=r.z.object({operations:r.z.array(r.z.object({operationType:r.z.enum(["create-directory","move-files","delete-files","get-file-info"]),createDirectory:r.z.object({path:r.z.string()}).optional(),moveFiles:r.z.object({moves:r.z.array(r.z.object({source:r.z.string(),destination:r.z.string()}))}).optional(),deleteFiles:r.z.object({targets:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional()}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"}))}).optional(),getFileInfo:r.z.object({path:r.z.string()}).optional()}).refine((e=>"create-directory"===e.operationType?e.createDirectory&&!e.moveFiles&&!e.deleteFiles&&!e.getFileInfo:"move-files"===e.operationType?e.moveFiles&&!e.createDirectory&&!e.deleteFiles&&!e.getFileInfo:"delete-files"===e.operationType?e.deleteFiles&&!e.createDirectory&&!e.moveFiles&&!e.getFileInfo:"get-file-info"===e.operationType&&e.getFileInfo&&!e.createDirectory&&!e.moveFiles&&!e.deleteFiles),{message:"Invalid operation data"})),comment:r.z.string()}),exports.RequestOperationsSchema=r.z.object({requestId:s.optional(),operation:r.z.enum(["complete","merge","approve","revert","get-info","list","search","delete-empty"]),complete:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({summary:r.z.string()})).optional(),merge:r.z.preprocess((e=>"string"==typeof e?(()=>{try{return JSON.parse(e)}catch{return e}})():e),r.z.object({verifications:r.z.array(r.z.object({key:r.z.string().min(2).max(4),evidence:r.z.string().min(1)})).min(1)})).optional(),revert:r.z.object({reason:r.z.string(),confirmDestructive:r.z.boolean().optional()}).optional(),list:r.z.object({filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0),sortBy:r.z.enum(["created","updated"]).default("updated"),sortDirection:r.z.enum(["asc","desc"]).default("desc")}).optional()}).optional(),search:r.z.object({query:r.z.string().min(1),searchIn:r.z.enum(["title","description","criteria","all"]).default("all"),filters:r.z.object({type:r.z.enum(["feature","bugfix"]).optional(),status:r.z.enum(["pending_approval","open","in_progress","ready_for_review","ready_for_merge","resolving_conflicts","completed","canceled"]).optional(),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),limit:r.z.number().min(1).max(100).default(20),offset:r.z.number().min(0).default(0)}).optional()}).optional(),approve:r.z.object({}).optional()}).superRefine(((e,t)=>{e.requestId
|
|
3547
|
+
const r=e.operation,n={complete:{field:"complete",hint:'Provide: { complete: { summary: "..." } }'},merge:{field:"merge",hint:'Provide: { merge: { verifications: [{key: "1a", evidence: "..."}] } }'},revert:{field:"revert",hint:'Provide: { revert: { reason: "..." } }'},search:{field:"search",hint:'Provide: { search: { query: "..." } }'}}[r]
|
|
3548
|
+
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")})
|
|
3475
3549
|
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)")})
|
|
3476
|
-
exports.TestingProcessCreateSchema=r.z.object({name:r.z.string().min(1).describe("Name for the test process"),description:r.z.string().optional().describe("Description of what this process verifies"),scope:r.z.string().optional().describe('Path prefix for monorepo scoping (e.g., "packages/api/"). Omit for global.'),setup:r.z.array(r.z.string()).optional().describe('Commands to prepare the environment (e.g., ["ln -s ../../node_modules node_modules"])'),commands:r.z.array(l).min(1).describe("Test commands to execute in order"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingProcessUpdateSchema=r.z.object({processId:r.z.string().describe("Test process ID to update"),name:r.z.string().min(1).optional().describe("New name"),description:r.z.string().optional().describe("New description"),scope:r.z.string().nullable().optional().describe("New scope (null to remove)"),isActive:r.z.boolean().optional().describe("Enable or disable the process"),setup:r.z.array(r.z.string()).optional().describe("New setup commands (replaces existing)"),commands:r.z.array(l).optional().describe("New test commands (replaces existing)"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingReferenceSchema=r.z.object({}),exports.ExecuteTestCommandSchema=r.z.object({processId:r.z.string().describe("Test process ID containing the command"),commandName:r.z.string().describe('Name of the test command to run, or "setup" to run all setup commands in sequence')}),exports.ReportTestResultsSchema=r.z.object({status:r.z.enum(["passed","failed","error"]).describe("Overall result"),results:r.z.object({commands:r.z.array(r.z.object({name:r.z.string().describe("Command name"),status:r.z.enum(["passed","failed","skipped","error"]).describe("Command result"),output:r.z.string().optional().describe("Relevant output snippet"),diagnosis:r.z.string().optional().describe("Why it failed, if applicable")})).describe("Per-command results"),summary:r.z.string().describe("Brief overall summary"),acceptanceCriteria:r.z.array(r.z.object({criterion:r.z.string().describe("The acceptance criterion text"),status:r.z.enum(["verified","unverified","unclear"]),evidence:r.z.string().describe("How verified, or why not")})).optional().describe("AC verification results, if applicable")}).describe("Structured test results")}),exports.SessionMessageOperationsSchema=r.z.object({operation:r.z.enum(["send","reply","list","get","offer-handoff"]),type:r.z.enum(["question","report"]).optional().describe("Message type to send (required for send)"),toSessionId:r.z.string().optional().describe('Target session ID, or "parent" to auto-resolve to parent session (omit for broadcast questions)'),questionType:r.z.enum(["free-form","alternatives"]).optional().describe('Type of question (required for send type="question")'),questionContent:r.z.object({question:r.z.string().min(1).describe("The question text"),context:r.z.string().optional().describe("Additional context"),options:r.z.array(r.z.object({id:r.z.string(),label:r.z.string(),description:r.z.string().optional()})).optional().describe("Options for alternatives questions"),allowMultiple:r.z.boolean().optional().describe("Allow selecting multiple options")}).optional().describe('Question content (required for send type="question")'),priority:r.z.enum(["low","normal","high"]).optional().describe("Question priority"),expiresInHours:r.z.number().optional().describe("Question expiry in hours"),status:r.z.enum(["success","partial","failure","blocked"]).optional().describe('Report status (required for send type="report")'),summary:r.z.string().optional().describe('Report summary (required for send type="report")'),details:r.z.string().optional().describe("Report details"),finish:r.z.boolean().optional().describe("Release request associations after report"),messageCode:r.z.string().optional().describe("Message code (required for reply and get operations)"),respondedBySessionId:r.z.string().optional().describe("Session ID answering the question"),text:r.z.string().optional().describe("Text answer for free-form questions"),selectedOptions:r.z.array(r.z.string()).optional().describe("Selected option IDs for alternatives"),notes:r.z.string().optional().describe("Additional notes"),list:r.z.object({sessionId:r.z.string().optional().describe("Filter by session ID (auto-discovered if omitted)"),messageType:r.z.enum(["question","report","all"]).default("all").describe("Filter by message type"),direction:r.z.enum(["incoming","outgoing","all"]).default("all"),status:r.z.enum(["pending","answered","expired","success","partial","failure","blocked","all"]).default("all").describe("Filter by status"),readStatus:r.z.enum(["unread","read","acknowledged","all"]).default("all").describe("Filter by read status (reports only)"),limit:r.z.number().min(1).max(100).default(50),offset:r.z.number().min(0).default(0)}).optional().describe('List filters (operation: "list" only)'),offerHandoff:r.z.object({summary:r.z.string().describe("Summary of what was planned/created"),requestIds:r.z.array(r.z.string()).describe("Request IDs that were created from the plan")}).optional().describe('Handoff offer details (operation: "offer-handoff" only)')}).refine((e=>"send"===e.operation?!!e.type:"reply"===e.operation?!!e.messageCode:"list"===e.operation||("get"===e.operation?!!e.messageCode:"offer-handoff"===e.operation)),{message:"Invalid operation data: send requires type, reply requires messageCode, get requires messageCode"}),exports.UpdateSpecializationSchema=r.z.object({specialization:r.z.string().min(1).max(500).describe("Your updated specialization summary \u2014 a concise description of your accumulated domain expertise")})},6252(e,exports,t){"use strict"
|
|
3550
|
+
exports.TestingProcessCreateSchema=r.z.object({name:r.z.string().min(1).describe("Name for the test process"),description:r.z.string().optional().describe("Description of what this process verifies"),scope:r.z.string().optional().describe('Path prefix for monorepo scoping (e.g., "packages/api/"). Omit for global.'),setup:r.z.array(r.z.string()).optional().describe('Commands to prepare the environment (e.g., ["ln -s ../../node_modules node_modules"])'),commands:r.z.array(l).min(1).describe("Test commands to execute in order"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingProcessUpdateSchema=r.z.object({processId:r.z.string().describe("Test process ID to update"),name:r.z.string().min(1).optional().describe("New name"),description:r.z.string().optional().describe("New description"),scope:r.z.string().nullable().optional().describe("New scope (null to remove)"),isActive:r.z.boolean().optional().describe("Enable or disable the process"),setup:r.z.array(r.z.string()).optional().describe("New setup commands (replaces existing)"),commands:r.z.array(l).optional().describe("New test commands (replaces existing)"),verifyAcceptanceCriteria:r.z.boolean().optional().describe("When true, auto-tester verifies request acceptance criteria after running commands")}),exports.TestingReferenceSchema=r.z.object({}),exports.ExecuteTestCommandSchema=r.z.object({processId:r.z.string().describe("Test process ID containing the command"),commandName:r.z.string().describe('Name of the test command to run, or "setup" to run all setup commands in sequence')}),exports.CommandsSchema=r.z.object({operation:r.z.enum(["run","list","add","remove"]).default("run").describe('"run" to execute a command, "list" to see available commands, "add" to register a new command, "remove" to delete one'),name:r.z.string().optional().describe('Command name (required for "run", "add", and "remove")'),args:r.z.string().optional().describe('Additional arguments appended to the base command (optional, for "run")'),grep:r.z.string().optional().describe('Filter output through grep (optional, for "run"). Pipes command output through grep -i with this pattern.'),command:r.z.string().optional().describe('Shell command to register (required for "add", e.g. "tsc --noEmit")'),description:r.z.string().optional().describe('What this command verifies (optional, for "add")'),timeout:r.z.number().optional().describe('Timeout in seconds (optional, for "add", default 60)')}),exports.ReportTestResultsSchema=r.z.object({status:r.z.enum(["passed","failed","error"]).describe("Overall result"),results:r.z.object({commands:r.z.array(r.z.object({name:r.z.string().describe("Command name"),status:r.z.enum(["passed","failed","skipped","error"]).describe("Command result"),output:r.z.string().optional().describe("Relevant output snippet"),diagnosis:r.z.string().optional().describe("Why it failed, if applicable")})).describe("Per-command results"),summary:r.z.string().describe("Brief overall summary"),acceptanceCriteria:r.z.array(r.z.object({criterion:r.z.string().describe("The acceptance criterion text"),status:r.z.enum(["verified","unverified","unclear"]),evidence:r.z.string().describe("How verified, or why not")})).optional().describe("AC verification results, if applicable")}).describe("Structured test results")}),exports.SessionMessageOperationsSchema=r.z.object({operation:r.z.enum(["send","reply","list","get","offer-handoff"]),type:r.z.enum(["question","report"]).optional().describe("Message type to send (required for send)"),toSessionId:r.z.string().optional().describe('Target session ID, or "parent" to auto-resolve to parent session (omit for broadcast questions)'),questionType:r.z.enum(["free-form","alternatives"]).optional().describe('Type of question (required for send type="question")'),questionContent:r.z.object({question:r.z.string().min(1).describe("The question text"),context:r.z.string().optional().describe("Additional context"),options:r.z.array(r.z.object({id:r.z.string(),label:r.z.string(),description:r.z.string().optional()})).optional().describe("Options for alternatives questions"),allowMultiple:r.z.boolean().optional().describe("Allow selecting multiple options")}).optional().describe('Question content (required for send type="question")'),priority:r.z.enum(["low","normal","high"]).optional().describe("Question priority"),expiresInHours:r.z.number().optional().describe("Question expiry in hours"),status:r.z.enum(["success","partial","failure","blocked"]).optional().describe('Report status (required for send type="report")'),summary:r.z.string().optional().describe('Report summary (required for send type="report")'),details:r.z.string().optional().describe("Report details"),finish:r.z.boolean().optional().describe("Release request associations after report"),messageCode:r.z.string().optional().describe("Message code (required for reply and get operations)"),respondedBySessionId:r.z.string().optional().describe("Session ID answering the question"),text:r.z.string().optional().describe("Text answer for free-form questions"),selectedOptions:r.z.array(r.z.string()).optional().describe("Selected option IDs for alternatives"),notes:r.z.string().optional().describe("Additional notes"),list:r.z.object({sessionId:r.z.string().optional().describe("Filter by session ID (auto-discovered if omitted)"),messageType:r.z.enum(["question","report","all"]).default("all").describe("Filter by message type"),direction:r.z.enum(["incoming","outgoing","all"]).default("all"),status:r.z.enum(["pending","answered","expired","success","partial","failure","blocked","all"]).default("all").describe("Filter by status"),readStatus:r.z.enum(["unread","read","acknowledged","all"]).default("all").describe("Filter by read status (reports only)"),limit:r.z.number().min(1).max(100).default(50),offset:r.z.number().min(0).default(0)}).optional().describe('List filters (operation: "list" only)'),offerHandoff:r.z.object({summary:r.z.string().describe("Summary of what was planned/created"),requestIds:r.z.array(r.z.string()).describe("Request IDs that were created from the plan")}).optional().describe('Handoff offer details (operation: "offer-handoff" only)')}).refine((e=>"send"===e.operation?!!e.type:"reply"===e.operation?!!e.messageCode:"list"===e.operation||("get"===e.operation?!!e.messageCode:"offer-handoff"===e.operation)),{message:"Invalid operation data: send requires type, reply requires messageCode, get requires messageCode"}),exports.UpdateSpecializationSchema=r.z.object({specialization:r.z.string().min(1).max(500).describe("Your updated specialization summary \u2014 a concise description of your accumulated domain expertise")})},6252(e,exports,t){"use strict"
|
|
3477
3551
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3478
3552
|
const r=t(6183),n=t(405)
|
|
3479
3553
|
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"
|
|
@@ -3487,12 +3561,14 @@ var t={}
|
|
|
3487
3561
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
3488
3562
|
return o(t,e),t})
|
|
3489
3563
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,p){const f=n.child({tool:"specialist_ops"}),m=o.startTimer("tool_execution_time")
|
|
3490
|
-
try{if(
|
|
3491
|
-
e.
|
|
3564
|
+
try{if(e?.delegate&&"object"==typeof e.delegate){const t=e.delegate
|
|
3565
|
+
e.prompt=e.prompt||t.prompt,e.description=e.description||t.description,e.specialization=e.specialization||t.specialization,e.requestId=e.requestId||t.requestId,delete e.delegate}if(e?.followUp&&"object"==typeof e.followUp){const t=e.followUp
|
|
3566
|
+
e.prompt=e.prompt||t.prompt,e.specialization=e.specialization||t.specialization,delete e.followUp}if(e?.list&&"object"==typeof e.list){const t=e.list
|
|
3567
|
+
e.activeOnly=e.activeOnly??t.activeOnly,e.requestId=e.requestId||t.requestId,e.limit=e.limit??t.limit,delete e.list}!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="delegate":e.prompt&&e.sessionId?e.operation="follow-up":e.sessionId&&(e.operation="check-status")),e?.operation&&("delegate"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.limit):"follow-up"===e.operation?(delete e.description,delete e.activeOnly,delete e.limit):"check-status"===e.operation||"abort"===e.operation?(delete e.prompt,delete e.description,delete e.specialization,delete e.requestId,delete e.activeOnly,delete e.limit):"list"===e.operation&&(delete e.sessionId,delete e.prompt,delete e.description,delete e.specialization))
|
|
3492
3568
|
const n=c.validateArgs(e,a.SpecialistOpsSchema),{operation:y,sessionId:w}=n
|
|
3493
3569
|
let k
|
|
3494
|
-
switch(f.info("Processing specialist_ops",{operation:y,sessionId:w}),y){case"delegate":{const e=
|
|
3495
|
-
if(
|
|
3570
|
+
switch(f.info("Processing specialist_ops",{operation:y,sessionId:w}),y){case"delegate":{const e=10,o=p?.sessionId||g.sessionIdentity.getIdentity()?.sessionId
|
|
3571
|
+
if(o&&s){const t=await async function(e,t,r,n,o){n.info("enforcePoolLimit called",{parentSessionId:e,maxPoolSize:t})
|
|
3496
3572
|
const s=await(0,h.getServerUrl)(r,n)
|
|
3497
3573
|
if(s)try{const r=await fetch(s.replace(/\/$/,"")+"/session")
|
|
3498
3574
|
if(!r.ok)return
|
|
@@ -3505,31 +3581,31 @@ return"specialist"===t?.agentType&&"archived"!==t?.status}))
|
|
|
3505
3581
|
if(n.info("Pool check: specialist count",{specialistCount:h.length,maxPoolSize:t}),h.length<t)return
|
|
3506
3582
|
const g=h.map((e=>{const t=l[e.id],r=u[e.id]?.type||"idle",n=t?.specialization||"(none)"
|
|
3507
3583
|
return` \u2022 ${e.id} \u2014 ${n} [${r}]`})).join("\n")
|
|
3508
|
-
return{content:[{type:"text",text:`\u274c Specialist pool is full (${h.length}/${t}).\nAbort an idle specialist first with \`specialist_ops abort\`, then delegate again.\n\nCurrent pool:\n`+g}],isError:!0}}catch(e){return void n.warn("Pool limit check failed, allowing spawn",{error:(0,l.getErrorMessage)(e)})}}(
|
|
3509
|
-
if(
|
|
3510
|
-
break}}let
|
|
3511
|
-
const
|
|
3512
|
-
if(
|
|
3513
|
-
if(
|
|
3514
|
-
if(
|
|
3515
|
-
|
|
3584
|
+
return{content:[{type:"text",text:`\u274c Specialist pool is full (${h.length}/${t}).\nAbort an idle specialist first with \`specialist_ops abort\`, then delegate again.\n\nCurrent pool:\n`+g}],isError:!0}}catch(e){return void n.warn("Pool limit check failed, allowing spawn",{error:(0,l.getErrorMessage)(e)})}}(o,e,r,f,s)
|
|
3585
|
+
if(t){k=t
|
|
3586
|
+
break}}let i=n.description||n.prompt.slice(0,60)
|
|
3587
|
+
const a=await Promise.resolve().then(t.t.bind(t,9896,23)),c=e=>a.appendFileSync(t(6928).join(t(857).tmpdir(),"specialist-name-debug.log"),`${(new Date).toISOString()} ${e}\n`)
|
|
3588
|
+
if(o)try{const e=await(0,h.getServerUrl)(r,f)
|
|
3589
|
+
if(c(`serverUrl=${e}, parentId=${o}`),e){const t=await fetch(e.replace(/\/$/,"")+"/session")
|
|
3590
|
+
if(c("session fetch status="+t.status),t.ok){const e=(await t.json()).filter((e=>(e.parentId||e.parentID)===o)).map((e=>e.title||""))
|
|
3591
|
+
c(`siblings=${e.length}: ${e.join(", ")}`)
|
|
3516
3592
|
const r=(0,d.pickSpecialistName)(e)
|
|
3517
|
-
|
|
3518
|
-
const
|
|
3519
|
-
k=await(0,u.handleSpawn)({agent:"specialist",prompt:
|
|
3593
|
+
i=r,c("picked name: "+r)}}else c("no serverUrl")}catch(e){c("error: "+(e instanceof Error?e.message:e+""))}else c("no parentId")
|
|
3594
|
+
const m=n.requestId,y=m?`Working on request ${m}.\n\n${n.prompt}`:n.prompt
|
|
3595
|
+
k=await(0,u.handleSpawn)({agent:"specialist",prompt:y,title:i,specialization:n.specialization},r,f,s,p)
|
|
3520
3596
|
break}case"follow-up":{const e=await(0,h.getServerUrl)(r,f)
|
|
3521
3597
|
if(e)try{const t=await fetch(e.replace(/\/$/,"")+"/session/status")
|
|
3522
3598
|
if(t.ok){const e=await t.json(),r=e[w]?.type
|
|
3523
3599
|
if(r&&"idle"!==r&&"prompting"!==r){k={content:[{type:"text",text:`\u274c Specialist ${w} is currently busy (status: ${r}).\nUse \`delegate\` to spawn a new specialist instead.`}],isError:!0}
|
|
3524
|
-
break}}}catch{}k=await(0,u.handleContinue)(w,n.
|
|
3525
|
-
const t=n.
|
|
3600
|
+
break}}}catch{}k=await(0,u.handleContinue)(w,n.prompt,r,f,s,"specialist",p)
|
|
3601
|
+
const t=n.specialization
|
|
3526
3602
|
if(t&&s)try{const e=s.getCLISessionClient()
|
|
3527
3603
|
e&&(await e.createOrUpdateSession({externalSessionId:w,specialization:t}),k.content[0].text+="\nSpecialization updated to: "+t)}catch{}break}case"check-status":k=await(0,u.handleCheckStatus)(w,r,f,s)
|
|
3528
3604
|
break
|
|
3529
3605
|
case"abort":if(k=await(0,u.handleAbort)(w,r,f),!k.isError&&s)try{const e=s.getCLISessionClient()
|
|
3530
3606
|
e&&await e.createOrUpdateSession({externalSessionId:w,status:"archived"})}catch{}break
|
|
3531
3607
|
case"list":{const e=p?.sessionId||g.sessionIdentity.getIdentity()?.sessionId
|
|
3532
|
-
k=await(0,u.handleListSessions)(r,f,s,{activeOnly:n.
|
|
3608
|
+
k=await(0,u.handleListSessions)(r,f,s,{activeOnly:n.activeOnly,requestId:n.requestId,limit:n.limit,agentType:"specialist",parentSessionId:e})
|
|
3533
3609
|
break}default:throw new i.ValidationError("Unknown operation: "+y)}return m({success:!0}),o.incrementCounter(`specialist_ops_${y}_success`,1),k}catch(e){return f.error("Specialist ops failed",{error:e instanceof Error?e.stack:e+""}),m({success:!1}),o.incrementCounter("specialist_ops_errors",1),{content:[{type:"text",text:"Specialist operation failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
|
|
3534
3610
|
const i=t(9860),a=t(6183),c=s(t(5967)),l=t(8824),d=t(9089),u=t(1725),h=t(7617),g=t(6688)},6315(e,exports,t){"use strict"
|
|
3535
3611
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
@@ -3612,58 +3688,59 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3612
3688
|
var t={}
|
|
3613
3689
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
3614
3690
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3615
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleInsertLines=async function(e,
|
|
3616
|
-
let
|
|
3617
|
-
const
|
|
3618
|
-
try{const
|
|
3619
|
-
if(
|
|
3620
|
-
const
|
|
3621
|
-
|
|
3622
|
-
const
|
|
3623
|
-
for(const e of
|
|
3624
|
-
|
|
3625
|
-
if(
|
|
3626
|
-
for(const e of
|
|
3627
|
-
if(
|
|
3628
|
-
try{await(0,p.ensureDocumentsNotLocked)(e,
|
|
3629
|
-
throw e}}
|
|
3630
|
-
const
|
|
3631
|
-
let
|
|
3632
|
-
|
|
3633
|
-
let
|
|
3634
|
-
|
|
3635
|
-
const
|
|
3636
|
-
if(
|
|
3637
|
-
throw Error(
|
|
3638
|
-
for(let e=0;e<
|
|
3639
|
-
|
|
3640
|
-
throw e}
|
|
3641
|
-
const
|
|
3642
|
-
if(
|
|
3643
|
-
const e=await(0,g.commitUserChangesBeforeToolOperation)(
|
|
3644
|
-
e.userChangesCommitted&&(
|
|
3645
|
-
const
|
|
3646
|
-
let
|
|
3647
|
-
for(const e of
|
|
3691
|
+
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()
|
|
3692
|
+
let I,b,v=d.FileOperationPhase.VALIDATION
|
|
3693
|
+
const C={toolName:"insert-lines",operationName:"insert-lines",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"insert-lines",metricsPrefix:"insert_lines",successMessage:"Successfully inserted lines into files and documents",failureMessage:"Failed to insert lines into files and documents"}
|
|
3694
|
+
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"
|
|
3695
|
+
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")
|
|
3696
|
+
const P=E.filter((e=>e.path)),j=E.filter((e=>e.documentId))
|
|
3697
|
+
w.info("Operation breakdown",{fileOperations:P.length,documentOperations:j.length})
|
|
3698
|
+
const x=[]
|
|
3699
|
+
for(const e of P){const{normalizedPath:t,fullPath:r}=d.validateAndNormalizePath(e.path,n)
|
|
3700
|
+
x.push({type:"file",path:t,fullPath:r,insertions:e.insertions})}const R=[]
|
|
3701
|
+
if(j.length>0&&!n.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
3702
|
+
for(const e of j)R.push({type:"document",documentId:e.documentId,insertions:e.insertions})
|
|
3703
|
+
if(R.length>0&&n.apiClient){const e=R.map((e=>e.documentId))
|
|
3704
|
+
try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,w,m,"insert-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3705
|
+
throw e}}v=d.FileOperationPhase.TASK_VALIDATION,m.incrementCounter("insert_lines_phase",1,{phase:v})
|
|
3706
|
+
const M=x.length>0?x[0].path:"document-operation",O=await d.validateTaskId(T,M,o,w,m,C.metricsPrefix),$=O?.requestId
|
|
3707
|
+
let D=null
|
|
3708
|
+
x.length>0&&$&&(D=await d.validateWorkItemStates(T,x[0].path,o,i,n,w,m,C.metricsPrefix))
|
|
3709
|
+
let A={taskPromoted:!1,requestPromoted:!1}
|
|
3710
|
+
x.length>0&&$&&D&&(A=await d.autoPromoteTaskStatus(T,O.status,$,D.request?.status,x[0].path,o,i,w,m,C.metricsPrefix),A.taskPromoted&&w.info("Auto-promoted task to in_progress for insert-lines operation",{taskId:T,requestId:$,previousStatus:O.status,newStatus:A.newTaskStatus,triggeringOperation:"insert-lines"}))
|
|
3711
|
+
const F=await d.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:$,context:n,operation:"insert-lines",logger:w,metrics:m,metricsPrefix:C.metricsPrefix})
|
|
3712
|
+
if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
|
|
3713
|
+
throw Error(F.error)}if(x.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:x.length,workspaceBasePath:n.workspaceManager?.getCurrentContext(n.currentSessionId).basePath})
|
|
3714
|
+
for(let e=0;e<x.length;e++){const t=x[e],r=P[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(r.path,n)
|
|
3715
|
+
x[e]={...t,path:o,fullPath:s}}}if(R.length>0&&$)try{await(0,h.validateRequestStatusForDocumentOperation)($,i,w,m,"insert-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3716
|
+
throw e}v=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("insert_lines_phase",1,{phase:v})
|
|
3717
|
+
const N=[...x.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...R.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:L}=await d.createFileOperationRecords(T,$,n.projectId,C.recordType,M,{operationCount:E.length,fileOperations:x.length,documentOperations:R.length,operations:N,userComment:q},o,s,w,m,C.metricsPrefix,y)
|
|
3718
|
+
if(I=L,b=L,v=C.fileOperationPhase,m.incrementCounter("insert_lines_phase",1,{phase:v}),x.length>0&&n.git)try{w.debug("[INSERT-LINES] Checking for user changes before insert operations")
|
|
3719
|
+
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"insert-lines",{requestId:$,taskId:T,workspaceManager:n.workspaceManager},w,m)
|
|
3720
|
+
e.userChangesCommitted&&(w.debug("[INSERT-LINES] User changes committed before insert operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),w.info("User changes committed before insert-lines operation",{taskId:T,fileOperationsCount:x.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){w.debug("[INSERT-LINES] Pre-tool commit failed, continuing with insertions",{error:e instanceof Error?e.message:e+""}),w.warn("Pre-tool user changes commit failed, continuing with insert operation",{taskId:T,fileOperationsCount:x.length,error:e instanceof Error?e.message:e+""})}w.debug("[INSERT-LINES] Proceeding with file operations",{fileCount:x.length})
|
|
3721
|
+
const z=[]
|
|
3722
|
+
let H=0,B=0,U=0
|
|
3723
|
+
for(const e of x){const t={type:"file",path:e.path,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
|
|
3648
3724
|
try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
|
|
3649
3725
|
const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.insertions)
|
|
3650
|
-
t.insertions=s,t.successfulInsertions=s.filter((e=>e.success)).length,t.failedInsertions=s.filter((e=>!e.success)).length,t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulInsertions>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,
|
|
3651
|
-
try{const o=await
|
|
3652
|
-
|
|
3726
|
+
t.insertions=s,t.successfulInsertions=s.filter((e=>e.success)).length,t.failedInsertions=s.filter((e=>!e.success)).length,t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulInsertions>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,U++,w.info("File updated successfully",{path:e.path,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedInsertions=e.insertions.length,H+=t.failedInsertions,w.error("File operation failed",{path:e.path,error:t.error})}z.push(t)}for(const e of R){const t={type:"document",documentId:e.documentId,success:!1,insertions:[],successfulInsertions:0,failedInsertions:0,totalLinesAdded:0}
|
|
3727
|
+
try{const o=await n.documentFileManager.getDocumentAsFile(e.documentId),s=n.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
3728
|
+
t.filename=s?.filename
|
|
3653
3729
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.insertions)
|
|
3654
|
-
|
|
3655
|
-
|
|
3656
|
-
try{await
|
|
3657
|
-
if(
|
|
3658
|
-
|
|
3730
|
+
t.insertions=l,t.successfulInsertions=l.filter((e=>e.success)).length,t.failedInsertions=l.filter((e=>!e.success)).length,t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulInsertions>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,U++,w.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulInsertions:t.successfulInsertions,failedInsertions:t.failedInsertions,linesAdded:t.totalLinesAdded})):0===t.failedInsertions&&(t.success=!0),H+=t.failedInsertions,B+=t.totalLinesAdded}catch(r){t.error=(0,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(R.length>0)try{for(const e of R){const t=z.find((t=>t.documentId===e.documentId))
|
|
3731
|
+
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){w.warn("Some documents may not have synced properly",{error:e})}const G=await d.handleMultiFileGitCommit(T,x,z,U,{operationType:"Insert lines",toolRecordId:b,successField:"successfulInsertions",logger:w,metrics:m,metricsPrefix:"insert_lines"},n),W=d.processMultiFileOperationResults(z,"successfulInsertions"),{successfulOperations:V,failedOperations:J,totalSuccessfulChanges:K,overallSuccess:Y,successfulFiles:Q,failedFiles:Z}=W
|
|
3732
|
+
try{await s.updateToolRecord(b,{metadata:{path:x.length>0?x[0].path:"document:"+R[0]?.documentId,status:Y?"completed":"failed",error:Y?void 0:J+" operations failed",totalOperations:z.length,successfulFiles:Q,failedFiles:Z,operations:N,totalSuccessfulInsertions:K,totalFailedInsertions:H,totalLinesAdded:B,operationsWithChanges:U,processingTime:Date.now()-k,userComment:q,...x.length>0&&G.success&&G.commitHash&&{commitHash:G.commitHash,previousCommitHash:G.previousCommitHash||void 0}},note:Y?`Line insertion completed: ${V}/${z.length} operations successful${x.length>0?" (committed to git)":""}`:`Line insertion partially failed: ${J}/${z.length} operations failed`})}catch(e){w.warn("Failed to update tool record",{recordError:e})}let X="## Line Insertion Results\n\n"
|
|
3733
|
+
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
3734
|
+
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]
|
|
3735
|
+
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"
|
|
3659
3736
|
for(const t of e.insertions.filter((e=>!e.success))){const e="between"===t.type?`between lines ${t.afterLine} and ${t.beforeLine}`:`${t.type} line ${t.line}`
|
|
3660
|
-
|
|
3661
|
-
for(const e of
|
|
3737
|
+
X+=`- ${t.type} insertion ${e}: ${t.error}\n`}}}else{X+="**Summary:**\n",X+=`- **Total Operations:** ${z.length}\n`,X+=`- **Successful:** ${V}\n`,X+=`- **Failed:** ${J}\n`,X+=`- **Total Insertions:** ${K} successful, ${H} failed\n`,X+=`- **Total Lines Added:** ${B}\n\n`,X+="**Detailed Results:**\n\n"
|
|
3738
|
+
for(const e of z){if("file"===e.type?X+=`### File: ${e.path}\n`:(X+="### Document: "+e.documentId,e.filename&&(X+=` (${e.filename})`),X+="\n"),X+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error?X+=`- **Error:** ${e.error}\n`:(X+=`- **Insertions:** ${e.successfulInsertions} successful`,e.failedInsertions>0&&(X+=`, ${e.failedInsertions} failed`),X+="\n",X+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.insertions.some((e=>!e.success))){X+="- **Failed Insertion Details:**\n"
|
|
3662
3739
|
for(const t of e.insertions.filter((e=>!e.success))){const e="between"===t.type?`between lines ${t.afterLine} and ${t.beforeLine}`:`${t.type} line ${t.line}`
|
|
3663
|
-
|
|
3664
|
-
const
|
|
3665
|
-
return
|
|
3666
|
-
if(
|
|
3740
|
+
X+=` - ${t.type} insertion ${e}: ${t.error}\n`}}X+="\n"}}R.length>0&&(X+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3741
|
+
const ee=Date.now()-k
|
|
3742
|
+
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
|
|
3743
|
+
if(w.error("Insert lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:v}),b)try{await s.updateToolRecord(b,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,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}}}
|
|
3667
3744
|
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824),m=t(3255)},6539(e,exports,t){"use strict"
|
|
3668
3745
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ClientFactory=void 0
|
|
3669
3746
|
const r=t(1253),n=t(5681),o=t(6595),s=t(3895),i=t(6848),a=t(6153),c=t(4710),l=t(6975),d=t(1887),u=t(1666),h=t(8824),g=t(9884),p=t(2968),f=t(922)
|
|
@@ -3687,12 +3764,12 @@ if(I.registerClient(j),!w.alchemyPath)throw Error("alchemyPath is required for P
|
|
|
3687
3764
|
try{m.info("Creating ProjectSynchronizer components")
|
|
3688
3765
|
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})
|
|
3689
3766
|
_.setProjectSynchronizer(n),m.info("ProjectSynchronizer created and connected to ProjectClient")}catch(e){const t="Failed to create required ProjectSynchronizer components: "+(0,h.getErrorMessage)(e)
|
|
3690
|
-
throw m.error(t,{error:e instanceof Error?e.stack:e+""}),Error(t)}const
|
|
3691
|
-
m.info("API client initialized with specialized clients"),v?(
|
|
3692
|
-
const
|
|
3693
|
-
|
|
3694
|
-
const M=
|
|
3695
|
-
return v&&!M?(m.error("CRITICAL: ApiClient token was not set properly!"),
|
|
3767
|
+
throw m.error(t,{error:e instanceof Error?e.stack:e+""}),Error(t)}const x=new o.ApiClient(b,_,E,q,S,T,P,j,m)
|
|
3768
|
+
m.info("API client initialized with specialized clients"),v?(x.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"})
|
|
3769
|
+
const R=I.verifyAllClients()
|
|
3770
|
+
R.success?m.info("Token consistency verified across all clients"):m.error(`Token inconsistency detected in ${R.failedClients.length} clients: ${R.failedClients.join(", ")}`)
|
|
3771
|
+
const M=x.getAuthToken()
|
|
3772
|
+
return v&&!M?(m.error("CRITICAL: ApiClient token was not set properly!"),x.setAuthToken(v)):M&&m.info("ApiClient token verified",{tokenLength:M.length,matches:M===v}),m.info("API client creation completed successfully"),x}}},6540(e,exports){"use strict"
|
|
3696
3773
|
var t
|
|
3697
3774
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.LogLevel=void 0,function(e){e.ERROR="error",e.WARN="warn",e.INFO="info",e.DEBUG="debug"}(t||(exports.LogLevel=t={}))},6595(e,exports,t){"use strict"
|
|
3698
3775
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ApiClient=void 0
|
|
@@ -3732,56 +3809,57 @@ return t},n(e)},function(e){if(e&&e.__esModule)return e
|
|
|
3732
3809
|
var t={}
|
|
3733
3810
|
if(null!=e)for(var r=n(e),i=0;i<r.length;i++)"default"!==r[i]&&o(t,e,r[i])
|
|
3734
3811
|
return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
3735
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceLines=async function(e,
|
|
3736
|
-
let
|
|
3737
|
-
const
|
|
3738
|
-
try{const
|
|
3739
|
-
if(
|
|
3740
|
-
const
|
|
3741
|
-
|
|
3742
|
-
const
|
|
3743
|
-
for(const e of
|
|
3744
|
-
|
|
3745
|
-
if(
|
|
3746
|
-
for(const e of
|
|
3747
|
-
if(
|
|
3748
|
-
try{await(0,p.ensureDocumentsNotLocked)(e,
|
|
3749
|
-
throw e}}
|
|
3750
|
-
const R
|
|
3751
|
-
let
|
|
3752
|
-
|
|
3753
|
-
let
|
|
3754
|
-
|
|
3755
|
-
const
|
|
3756
|
-
if(!
|
|
3757
|
-
throw Error(
|
|
3758
|
-
for(let e=0;e<
|
|
3759
|
-
|
|
3760
|
-
throw e}
|
|
3761
|
-
const
|
|
3762
|
-
if(
|
|
3763
|
-
const e=await(0,g.commitUserChangesBeforeToolOperation)(
|
|
3764
|
-
e.userChangesCommitted&&(
|
|
3765
|
-
const
|
|
3766
|
-
let
|
|
3767
|
-
for(const e of
|
|
3812
|
+
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()
|
|
3813
|
+
let b,v,C=d.FileOperationPhase.VALIDATION
|
|
3814
|
+
const _={toolName:"replace-lines",operationName:"replace-lines",fileOperationPhase:d.FileOperationPhase.STRING_REPLACEMENT,recordType:"replace-lines",metricsPrefix:"replace_lines",successMessage:"Successfully replaced lines in files and documents",failureMessage:"Failed to replace lines in files and documents"}
|
|
3815
|
+
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"
|
|
3816
|
+
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")
|
|
3817
|
+
const j=q.filter((e=>e.path)),x=q.filter((e=>e.documentId))
|
|
3818
|
+
k.info("Operation breakdown",{fileOperations:j.length,documentOperations:x.length})
|
|
3819
|
+
const R=[]
|
|
3820
|
+
for(const e of j){const{normalizedPath:t,fullPath:r}=d.validateAndNormalizePath(e.path,n)
|
|
3821
|
+
R.push({type:"file",path:t,fullPath:r,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})}const M=[]
|
|
3822
|
+
if(x.length>0&&!n.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
3823
|
+
for(const e of x)M.push({type:"document",documentId:e.documentId,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})
|
|
3824
|
+
if(M.length>0&&n.apiClient){const e=M.map((e=>e.documentId))
|
|
3825
|
+
try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,k,m,"replace-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3826
|
+
throw e}}C=d.FileOperationPhase.TASK_VALIDATION,m.incrementCounter("replace_lines_phase",1,{phase:C})
|
|
3827
|
+
const O=R.length>0?R[0].path:"document-operation",$=await d.validateTaskId(P,O,o,k,m,_.metricsPrefix),D=$?.requestId
|
|
3828
|
+
let A=null
|
|
3829
|
+
R.length>0&&D&&(A=await d.validateWorkItemStates(P,R[0].path,o,i,n,k,m,_.metricsPrefix))
|
|
3830
|
+
let F={taskPromoted:!1,requestPromoted:!1}
|
|
3831
|
+
R.length>0&&D&&A&&(F=await d.autoPromoteTaskStatus(P,$.status,D,A.request?.status,R[0].path,o,i,k,m,_.metricsPrefix),F.taskPromoted&&k.info("Auto-promoted task to in_progress for replace-lines operation",{taskId:P,requestId:D,previousStatus:$.status,newStatus:F.newTaskStatus,triggeringOperation:"replace-lines"}))
|
|
3832
|
+
const N=await d.ensureCorrectWorkspaceContext({taskPromoted:F.taskPromoted,requestId:D,context:n,operation:"replace-lines",logger:k,metrics:m,metricsPrefix:_.metricsPrefix})
|
|
3833
|
+
if(!N.success){if(N.isLockConflict)return{content:[{type:"text",text:"\u274c "+N.error}],isError:!0}
|
|
3834
|
+
throw Error(N.error)}if(R.length>0){k.debug("Re-validating file paths with correct workspace context",{operationCount:R.length,workspaceBasePath:n.workspaceManager?.getCurrentContext(n.currentSessionId).basePath})
|
|
3835
|
+
for(let e=0;e<R.length;e++){const t=R[e],r=j[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(r.path,n)
|
|
3836
|
+
R[e]={...t,path:o,fullPath:s}}}if(M.length>0&&D)try{await(0,h.validateRequestStatusForDocumentOperation)(D,i,k,m,"replace-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3837
|
+
throw e}C=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("replace_lines_phase",1,{phase:C})
|
|
3838
|
+
const L=[...R.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:z}=await d.createFileOperationRecords(P,D,n.projectId,_.recordType,O,{operationCount:q.length,fileOperations:R.length,documentOperations:M.length,operations:L,userComment:S},o,s,k,m,_.metricsPrefix,w)
|
|
3839
|
+
if(b=z,v=z,C=_.fileOperationPhase,m.incrementCounter("replace_lines_phase",1,{phase:C}),R.length>0&&n.git)try{k.debug("[REPLACE-LINES] Checking for user changes before replace operations")
|
|
3840
|
+
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"replace-lines",{requestId:D,taskId:P,workspaceManager:n.workspaceManager},k,m)
|
|
3841
|
+
e.userChangesCommitted&&(k.debug("[REPLACE-LINES] User changes committed before replace operations",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),k.info("User changes committed before replace-lines operation",{taskId:P,fileOperationsCount:R.length,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){k.debug("[REPLACE-LINES] Pre-tool commit failed, continuing with replacements",{error:e instanceof Error?e.message:e+""}),k.warn("Pre-tool user changes commit failed, continuing with replace operation",{taskId:P,fileOperationsCount:R.length,error:e instanceof Error?e.message:e+""})}k.debug("[REPLACE-LINES] Proceeding with file operations",{fileCount:R.length})
|
|
3842
|
+
const H=[]
|
|
3843
|
+
let B=0,U=0,G=0,W=0
|
|
3844
|
+
for(const e of R){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
|
|
3768
3845
|
try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
|
|
3769
3846
|
const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.replacements)
|
|
3770
|
-
t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,t.totalLinesReplaced=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulReplacements>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,
|
|
3771
|
-
try{const o=await
|
|
3772
|
-
|
|
3847
|
+
t.replacements=s,t.successfulReplacements=s.filter((e=>e.success)).length,t.failedReplacements=s.filter((e=>!e.success)).length,t.totalLinesReplaced=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=s.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),o!==n&&t.successfulReplacements>0?(await c.default.writeFile(e.fullPath,o,"utf8"),t.success=!0,W++,k.info("File updated successfully",{path:e.path,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,f.getErrorMessage)(r),t.failedReplacements=e.replacements.length,B+=t.failedReplacements,k.error("File operation failed",{path:e.path,error:t.error})}H.push(t)}for(const e of M){const t={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
|
|
3848
|
+
try{const o=await n.documentFileManager.getDocumentAsFile(e.documentId),s=n.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
3849
|
+
t.filename=s?.filename
|
|
3773
3850
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.replacements)
|
|
3774
|
-
|
|
3775
|
-
|
|
3776
|
-
try{await
|
|
3777
|
-
if(
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
for(const
|
|
3781
|
-
for(const
|
|
3782
|
-
const
|
|
3783
|
-
|
|
3784
|
-
|
|
3851
|
+
t.replacements=l,t.successfulReplacements=l.filter((e=>e.success)).length,t.failedReplacements=l.filter((e=>!e.success)).length,t.totalLinesReplaced=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesReplaced||0)),0),t.totalLinesAdded=l.filter((e=>e.success)).reduce(((e,t)=>e+(t.linesAdded||0)),0),a!==i&&t.successfulReplacements>0?(await c.default.writeFile(o,a,"utf8"),n.documentFileManager.markForSync(e.documentId),t.success=!0,W++,k.info("Document updated successfully",{documentId:e.documentId,filename:t.filename,successfulReplacements:t.successfulReplacements,failedReplacements:t.failedReplacements,linesReplaced:t.totalLinesReplaced,linesAdded:t.totalLinesAdded})):0===t.failedReplacements&&(t.success=!0),B+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,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))
|
|
3852
|
+
t?.success&&await n.documentFileManager.syncDocument(e.documentId)}}catch(e){k.warn("Some documents may not have synced properly",{error:e})}const V=await d.handleMultiFileGitCommit(P,R,H,W,{operationType:"Replace lines",toolRecordId:v,successField:"successfulReplacements",logger:k,metrics:m,metricsPrefix:"replace_lines"},n),J=d.processMultiFileOperationResults(H,"successfulReplacements"),{successfulOperations:K,failedOperations:Y,totalSuccessfulChanges:Q,overallSuccess:Z,successfulFiles:X,failedFiles:ee}=J
|
|
3853
|
+
try{await s.updateToolRecord(v,{metadata:{path:R.length>0?R[0].path:"document:"+M[0]?.documentId,status:Z?"completed":"failed",error:Z?void 0:Y+" operations failed",totalOperations:H.length,successfulFiles:X,failedFiles:ee,operations:L,totalSuccessfulReplacements:Q,totalFailedReplacements:B,totalLinesReplaced:U,totalLinesAdded:G,operationsWithChanges:W,processingTime:Date.now()-I,userComment:S,...R.length>0&&V.success&&V.commitHash&&{commitHash:V.commitHash,previousCommitHash:V.previousCommitHash||void 0}},note:Z?`Line replacement completed: ${K}/${H.length} operations successful${R.length>0?" (committed to git)":""}`:`Line replacement partially failed: ${Y}/${H.length} operations failed`})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let te="## Line Replacement Results\n\n"
|
|
3854
|
+
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
3855
|
+
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]
|
|
3856
|
+
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"
|
|
3857
|
+
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"
|
|
3858
|
+
for(const e of H){if("file"===e.type?te+=`### File: ${e.path}\n`:(te+="### Document: "+e.documentId,e.filename&&(te+=` (${e.filename})`),te+="\n"),te+=`- **Status:** ${e.success?"\u2705 Success":"\u274c Failed"}\n`,e.error&&(te+=`- **Error:** ${e.error}\n`),te+=`- **Replacements:** ${e.successfulReplacements} successful`,e.failedReplacements>0&&(te+=`, ${e.failedReplacements} failed`),te+="\n",te+=`- **Lines Replaced:** ${e.totalLinesReplaced}\n`,e.totalLinesAdded>0&&(te+=`- **Lines Added:** ${e.totalLinesAdded}\n`),e.replacements.some((e=>!e.success))){te+="- **Failed Replacement Details:**\n"
|
|
3859
|
+
for(const t of e.replacements.filter((e=>!e.success)))te+=` - Replace ${"number"==typeof t.lines?"line "+t.lines:Array.isArray(t.lines)?`lines [${t.lines.join(", ")}]`:`lines ${t.lines.start}-${t.lines.end}`}: ${t.error}\n`}te+="\n"}}M.length>0&&(te+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3860
|
+
const re=Date.now()-I
|
|
3861
|
+
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
|
|
3862
|
+
if(k.error("Replace lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:C}),v)try{await s.updateToolRecord(v,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,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}}}
|
|
3785
3863
|
const c=a(t(1943)),l=t(6183),d=i(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),f=t(8824),m=t(3255),y=t(9470)},6688(e,exports,t){"use strict"
|
|
3786
3864
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.sessionIdentity=void 0
|
|
3787
3865
|
const r=t(9896),n=t(6928)
|
|
@@ -3866,9 +3944,9 @@ let w
|
|
|
3866
3944
|
r.setProjectId(y)
|
|
3867
3945
|
try{const P=await f.getTask(g)
|
|
3868
3946
|
s.info("Raw task response data",{responseDataType:typeof P,isArray:Array.isArray(P),hasData:null!=P,properties:P&&"object"==typeof P?Object.keys(P):[]}),w=(0,l.extractDataFromResponse)(P,{logger:s,operationName:"getTask",defaultValue:{id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}),s.info("Found task: "+w.title)}catch(j){s.warn("Could not fetch task information: "+(0,u.getErrorMessage)(j)),w={id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}let k=[]
|
|
3869
|
-
try{const
|
|
3870
|
-
if(s.info("Raw records response data",{responseDataType:typeof
|
|
3871
|
-
k.forEach((e=>{
|
|
3947
|
+
try{const x=await m.getToolRecordsByTaskId(g)
|
|
3948
|
+
if(s.info("Raw records response data",{responseDataType:typeof x,isArray:Array.isArray(x),hasData:null!=x,properties:x&&"object"==typeof x?Object.keys(x):[]}),k=(0,l.extractArrayFromResponse)(x,{logger:s,operationName:"searchRecords",defaultValue:[]}),k.length>0&&s.info("First record summary:",{id:k[0].id,type:k[0].type,hasMetadata:!!k[0].metadata,hasCommitHash:!!k[0].metadata?.commitHash}),s.info(`Extracted ${k.length} records for task ${g}`),k.length>0){const R={}
|
|
3949
|
+
k.forEach((e=>{R[e.type]=(R[e.type]||0)+1})),s.info("Record type distribution:",R)}}catch(M){s.warn("Error fetching records for task "+g,{error:(0,u.getErrorMessage)(M)}),k=[]}if(0===k.length)return h({success:!0,recordCount:0}),{content:[{type:"text",text:`No records found for task ${g}.`}]}
|
|
3872
3950
|
function I(e){const t=new Map,r=new Map,n=[]
|
|
3873
3951
|
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
|
|
3874
3952
|
if(e&&s){const i={source:e,destination:s,recordId:o.id,timestamp:o.createdAt,type:"move-file"}
|
|
@@ -3965,13 +4043,13 @@ let S=0,T=!1
|
|
|
3965
4043
|
if(p){for(const Te of _.values())Te.hasDiff&&Te.diffText&&(S+=Te.diffText.split("\n").length)
|
|
3966
4044
|
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`
|
|
3967
4045
|
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"
|
|
3968
|
-
for(const[je,
|
|
4046
|
+
for(const[je,xe]of _.entries()){const{normalizedPath:Re,fullPath:Me}=d.validateAndNormalizePath(je,t)
|
|
3969
4047
|
let Oe=!1
|
|
3970
4048
|
try{await a.access(Me),Oe=!0}catch{}E+=`### ${je} ${Oe?"":"(Deleted)"}\n\n`
|
|
3971
|
-
const $e=new Date(
|
|
3972
|
-
E+=`**First Change**: ${$e}\n`,E+=`**Last Change**: ${De}\n`,"pre-task"===
|
|
4049
|
+
const $e=new Date(xe.firstChange.timestamp).toLocaleString(),De=new Date(xe.lastChange.timestamp).toLocaleString()
|
|
4050
|
+
E+=`**First Change**: ${$e}\n`,E+=`**Last Change**: ${De}\n`,"pre-task"===xe.firstChange.status&&xe.firstChange.commitHash?E+=`**Pre-Task Commit**: ${xe.firstChange.commitHash.substring(0,8)}\n`:xe.firstChange.commitHash&&(E+=`**File Created During Task**: ${xe.firstChange.commitHash.substring(0,8)}\n`),xe.lastChange.commitHash&&(E+=`**Final Commit**: ${xe.lastChange.commitHash.substring(0,8)}\n`)
|
|
3973
4051
|
const Ae=b.sourceToMove.get(je),Fe=b.destToMove.get(je)
|
|
3974
|
-
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?
|
|
4052
|
+
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?xe.hasDiff?(E+="\n**Changes**:\n",E+="```diff\n",E+=xe.diffText,E+="\n```\n\n"):E+=`\n**Note**: ${xe.diffText}\n\n`:T&&xe.hasDiff?(E+=`\n**Note**: File has changes (${xe.diffText?xe.diffText.split("\n").length:0} lines). `,E+=`Compare ${xe.firstChange.commitHash?xe.firstChange.commitHash.substring(0,8):"unknown"}..${xe.lastChange.commitHash?xe.lastChange.commitHash.substring(0,8):"unknown"} to see changes.\n\n`):xe.hasDiff?E+="\n**Note**: File has changes. Use showDiff=true to see the diff.\n\n":E+=`\n**Note**: ${xe.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}}}
|
|
3975
4053
|
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"
|
|
3976
4054
|
module.exports=require("path")},6975(e,exports,t){"use strict"
|
|
3977
4055
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.ProjectClientAdapter=void 0
|
|
@@ -4100,11 +4178,11 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
4100
4178
|
var t={}
|
|
4101
4179
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4102
4180
|
return o(t,e),t})
|
|
4103
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=function(e,t,r={}){try{const n=a.join(
|
|
4181
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=function(e,t,r={}){try{const n=a.join(c.homedir(),".alchemy_lab"),o=a.join(n,"session-identity.log")
|
|
4104
4182
|
i.existsSync(n)||i.mkdirSync(n,{recursive:!0})
|
|
4105
|
-
const s=(new Date).toISOString(),
|
|
4106
|
-
i.appendFileSync(o,`[${s}] ${e} | ${t}${
|
|
4107
|
-
const i=s(t(9896)),a=s(t(6928))},7334(e,exports,t){"use strict"
|
|
4183
|
+
const s=(new Date).toISOString(),l=Object.keys(r).length?" "+JSON.stringify(r):""
|
|
4184
|
+
i.appendFileSync(o,`[${s}] ${e} | ${t}${l}\n`)}catch(e){}}
|
|
4185
|
+
const i=s(t(9896)),a=s(t(6928)),c=s(t(857))},7334(e,exports,t){"use strict"
|
|
4108
4186
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateRequest=async function(e,t,c,l,d,u,h){const g=l.child({tool:"create_request"})
|
|
4109
4187
|
g.info("Creating new request",{args:e})
|
|
4110
4188
|
const p=d.startTimer("tool_handler_duration")
|
|
@@ -4157,35 +4235,35 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
4157
4235
|
var t={}
|
|
4158
4236
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4159
4237
|
return o(t,e),t})
|
|
4160
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleModifyFile=async function(e,
|
|
4161
|
-
try{const
|
|
4162
|
-
|
|
4163
|
-
const
|
|
4164
|
-
for(const e of
|
|
4165
|
-
switch(e.operationType){case"replace-string":
|
|
4238
|
+
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"})
|
|
4239
|
+
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"
|
|
4240
|
+
f.info("Processing modify-file operations",{taskId:k,operationCount:m.length,comment:y})
|
|
4241
|
+
const I=[],b=[],v=[],C=[],_=[]
|
|
4242
|
+
for(const e of m){const t={path:e.path,documentId:e.documentId}
|
|
4243
|
+
switch(e.operationType){case"replace-string":I.push({...t,replacements:e.replaceString.replacements,mode:e.replaceString.mode})
|
|
4166
4244
|
break
|
|
4167
|
-
case"insert-lines":
|
|
4245
|
+
case"insert-lines":b.push({...t,insertions:e.insertLines.insertions})
|
|
4168
4246
|
break
|
|
4169
|
-
case"replace-lines":
|
|
4247
|
+
case"replace-lines":v.push({...t,replacements:e.replaceLines.replacements})
|
|
4170
4248
|
break
|
|
4171
|
-
case"delete-string":
|
|
4249
|
+
case"delete-string":C.push({...t,replacements:e.deleteString.patterns.map((e=>({old_str:e,new_str:""}))),mode:e.deleteString.mode||"all"})
|
|
4172
4250
|
break
|
|
4173
|
-
case"delete-lines":
|
|
4174
|
-
if(
|
|
4175
|
-
const e=await(0,c.handleReplaceStrings)({taskId:
|
|
4176
|
-
|
|
4177
|
-
const e=await(0,l.handleInsertLines)({taskId:
|
|
4178
|
-
|
|
4179
|
-
const e=await(0,d.handleReplaceLines)({taskId:
|
|
4180
|
-
|
|
4181
|
-
const e=await(0,c.handleReplaceStrings)({taskId:
|
|
4182
|
-
|
|
4183
|
-
const e=
|
|
4184
|
-
|
|
4185
|
-
let
|
|
4186
|
-
|
|
4187
|
-
for(const{type:e,result:t}of
|
|
4188
|
-
return
|
|
4251
|
+
case"delete-lines":_.push({...t,lines:e.deleteLines.lines})}}const E=[]
|
|
4252
|
+
if(I.length>0){f.info("Routing to replace-strings handler",{operationCount:I.length})
|
|
4253
|
+
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:I,comment:y+" [via modify-file: replace-string]"},r,n,o,s,f,g,p)
|
|
4254
|
+
E.push({type:"replace-string",result:e})}if(b.length>0){f.info("Routing to insert-lines handler",{operationCount:b.length})
|
|
4255
|
+
const e=await(0,l.handleInsertLines)({taskId:k,operations:b,comment:y+" [via modify-file: insert-lines]"},r,n,o,s,f,g,p)
|
|
4256
|
+
E.push({type:"insert-lines",result:e})}if(v.length>0){f.info("Routing to replace-lines handler",{operationCount:v.length})
|
|
4257
|
+
const e=await(0,d.handleReplaceLines)({taskId:k,operations:v,comment:y+" [via modify-file: replace-lines]"},r,n,o,s,f,g,p)
|
|
4258
|
+
E.push({type:"replace-lines",result:e})}if(C.length>0){f.info("Routing delete-string to replace-strings handler",{operationCount:C.length})
|
|
4259
|
+
const e=await(0,c.handleReplaceStrings)({taskId:k,operations:C,comment:y+" [via modify-file: delete-string]"},r,n,o,s,f,g,p)
|
|
4260
|
+
E.push({type:"delete-string",result:e})}if(_.length>0){f.info("Processing delete-lines operations",{operationCount:_.length})
|
|
4261
|
+
const e=_.map((e=>({path:e.path,documentId:e.documentId,replacements:[{lines:e.lines,content:[]}]}))),t=await(0,d.handleReplaceLines)({taskId:k,operations:e,comment:y+" [via modify-file: delete-lines]"},r,n,o,s,f,g,p)
|
|
4262
|
+
E.push({type:"delete-lines",result:t})}const q=E.some((e=>e.result.isError)),S=E.filter((e=>!e.result.isError)).length,T=E.filter((e=>e.result.isError)).length
|
|
4263
|
+
let P="## Modify File Results\n\n"
|
|
4264
|
+
P+="**Summary:**\n",P+=`- **Total operation types:** ${E.length}\n`,P+=`- **Successful:** ${S}\n`,P+=`- **Failed:** ${T}\n\n`
|
|
4265
|
+
for(const{type:e,result:t}of E)P+=`### ${e} operations\n`,P+=t.content[0].text+"\n\n"
|
|
4266
|
+
return f.info("Modify-file operations completed",{totalOperationTypes:E.length,successCount:S,errorCount:T}),g.incrementCounter("modify_file_total",1,{success:!q}),{content:[{type:"text",text:P}],isError:q}}catch(e){return f.error("Modify-file operation failed",{error:e instanceof Error?e.stack:e+""}),g.incrementCounter("modify_file_errors",1),{content:[{type:"text",text:"\u274c **Modify File Failed:** "+(0,u.getErrorMessage)(e)}],isError:!0}}}
|
|
4189
4267
|
const i=t(6183),a=s(t(5967)),c=t(3306),l=t(6486),d=t(6651),u=t(8824)},7478(e,exports,t){"use strict"
|
|
4190
4268
|
async function r(e,t,r){const n=r.startTimer("git_get_current_branch_duration")
|
|
4191
4269
|
try{const o=(await e.status()).current
|
|
@@ -4300,7 +4378,7 @@ throw n.error("Failed to commit user changes",{requestId:t,error:i,uncommittedFi
|
|
|
4300
4378
|
try{let c=Date.now()
|
|
4301
4379
|
o.debug("Checking for user changes before tool operation",{toolName:r})
|
|
4302
4380
|
let l=e
|
|
4303
|
-
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext()
|
|
4381
|
+
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
4304
4382
|
if("multi-agent"===e.mode&&e.requestId){const{simpleGit}=t(3807)
|
|
4305
4383
|
l=simpleGit(e.basePath),o.debug("Using worktree git instance for user changes",{requestId:e.requestId,basePath:e.basePath,toolName:r})}}if(Date.now(),n.workspaceManager?.workspaceKnownClean)return o.debug("Skipping uncommitted changes check - workspace known to be clean",{toolName:r,requestId:n.requestId}),n.workspaceManager.workspaceKnownClean=!1,i({success:!0,reason:"known_clean"}),{userChangesCommitted:!1}
|
|
4306
4384
|
c=Date.now()
|
|
@@ -4322,7 +4400,45 @@ const t=e.reduce(((e,t)=>e+t.sizeMB),0)
|
|
|
4322
4400
|
let r=`\n\n\u26a0\ufe0f **Performance Warning**: Large untracked files detected (${Math.round(t)} MB total) that may slow git operations:\n`
|
|
4323
4401
|
for(const t of e.slice(0,5))r+=`- \`${t.path}\` (${t.sizeMB} MB)\n`
|
|
4324
4402
|
return e.length>5&&(r+=`- ... and ${e.length-5} more large files\n`),r+="\nConsider adding these to `.gitignore` or moving them outside the repository.",r}
|
|
4325
|
-
const h=t(3444),g=t(9860),p=t(3922),f=t(8824),m=u(t(9896)),y=u(t(6928))
|
|
4403
|
+
const h=t(3444),g=t(9860),p=t(3922),f=t(8824),m=u(t(9896)),y=u(t(6928))
|
|
4404
|
+
t(857)},7561(e,exports,t){"use strict"
|
|
4405
|
+
async function r(e,t){const r=e.getTaskClient(),n=await r.listTasks({requestId:t,status:"in_progress"})
|
|
4406
|
+
if(0===n.length)return null
|
|
4407
|
+
const o=n[0]
|
|
4408
|
+
return{taskId:o.localId||o.id,title:o.title,sequenceNumber:o.sequenceNumber}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleTasks=async function(e,t,i,a,c,l){const d=a.child({tool:"tasks"}),{operation:u}=e
|
|
4409
|
+
try{const c=t.projectId
|
|
4410
|
+
if(!c)throw Error("Project ID not available")
|
|
4411
|
+
i.setProjectId(c)
|
|
4412
|
+
const h=await async function(e,t,r,o){const s=o?.sessionId||e.currentSessionId
|
|
4413
|
+
if(!s||"__unknown__"===s||"__server__"===s)throw Error("Cannot resolve request: no session identity available")
|
|
4414
|
+
const i=await n.sessionIdentity.getSessionRequestId(t,r,s)
|
|
4415
|
+
if(!i)throw Error("No request associated with session "+s)
|
|
4416
|
+
return i}(t,i,a,l)
|
|
4417
|
+
switch(u){case"create":{const{title:t,description:n}=e
|
|
4418
|
+
if(!t)return{content:[{type:"text",text:"Error: title is required for create"}],isError:!0}
|
|
4419
|
+
if(!n)return{content:[{type:"text",text:"Error: description is required for create"}],isError:!0}
|
|
4420
|
+
const s=i.getTaskClient(),a=await s.createTask({requestId:h,projectId:c,title:t,description:n}),l=a.localId||a.id,u=await r(i,h)
|
|
4421
|
+
let g=!1
|
|
4422
|
+
if(!u)try{await s.updateTaskStatus(l,"in_progress"),g=!0}catch(e){d.debug("Could not auto-start task",{taskId:l,error:(0,o.getErrorMessage)(e)})}const p=a.sequenceNumber??null
|
|
4423
|
+
let f=p?`Created #${p}: ${t}`:`Created ${l}: ${t}`
|
|
4424
|
+
return g&&(f+=" (started)"),{content:[{type:"text",text:f}]}}case"done":{const{summary:t}=e
|
|
4425
|
+
if(!t)return{content:[{type:"text",text:"Error: summary is required for done"}],isError:!0}
|
|
4426
|
+
const n=await r(i,h)
|
|
4427
|
+
if(!n)return{content:[{type:"text",text:"No active (in_progress) task to complete."}],isError:!0}
|
|
4428
|
+
const a=i.getTaskClient()
|
|
4429
|
+
await a.updateTaskStatus(n.taskId,"completed"),(0,s.clearActiveTaskCache)()
|
|
4430
|
+
const c=await async function(e,t){const r=e.getTaskClient(),n=await r.listTasks({requestId:t,status:"pending",sortBy:"created",sortDirection:"asc"})
|
|
4431
|
+
if(0===n.length)return null
|
|
4432
|
+
const o=n[0]
|
|
4433
|
+
return{taskId:o.localId||o.id,title:o.title,sequenceNumber:o.sequenceNumber}}(i,h),l=n.sequenceNumber
|
|
4434
|
+
let u=l?`Completed #${l}: ${n.title}`:`Completed ${n.taskId}: ${n.title}`
|
|
4435
|
+
if(c)try{await a.updateTaskStatus(c.taskId,"in_progress")
|
|
4436
|
+
const e=c.sequenceNumber
|
|
4437
|
+
u+=e?`\nStarted #${e}: ${c.title}`:`\nStarted ${c.taskId}: ${c.title}`}catch(e){d.debug("Could not auto-start next task",{taskId:c.taskId,error:(0,o.getErrorMessage)(e)})}else u+="\nAll tasks completed."
|
|
4438
|
+
return{content:[{type:"text",text:u}]}}case"list":{const e=i.getTaskClient(),t=await e.listTasks({requestId:h,sortBy:"created",sortDirection:"asc"})
|
|
4439
|
+
return 0===t.length?{content:[{type:"text",text:"No tasks."}]}:{content:[{type:"text",text:t.map(((e,t)=>{const r=e.sequenceNumber??t+1
|
|
4440
|
+
return`[${"in_progress"===e.status?"\u25b6 in_progress":e.status}] #${r}: ${e.title}`})).join("\n")}]}}default:return{content:[{type:"text",text:"Unknown operation: "+u}],isError:!0}}}catch(e){return d.error("tasks operation failed",{operation:u,error:(0,o.getErrorMessage)(e)}),{content:[{type:"text",text:"Error: "+(0,o.getErrorMessage)(e)}],isError:!0}}}
|
|
4441
|
+
const n=t(6688),o=t(8824),s=t(3451)},7575(e,exports){"use strict"
|
|
4326
4442
|
var t
|
|
4327
4443
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.FileOperationPhase=exports.RequestLockError=void 0,exports.RequestLockError=class extends Error{constructor(e,t,r,n){super(e),this.requestId=t,this.lockedByAgent=r,this.lockedAt=n,this.name="RequestLockError"}},function(e){e.VALIDATION="validation",e.TASK_VALIDATION="task_validation",e.RECORD_CREATION="record_creation",e.FILE_WRITE="file_write",e.STRING_REPLACEMENT="string_replacement",e.GIT_COMMIT="git_commit",e.RECORD_UPDATE_SUCCESS="record_update_success",e.RECORD_UPDATE_FAILURE="record_update_failure"}(t||(exports.FileOperationPhase=t={}))},7609(e,exports,t){"use strict"
|
|
4328
4444
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleUpdatePlan=async function(e,t,n,o){const s=o.child({tool:"plan_operations",operation:"update"})
|
|
@@ -4353,8 +4469,8 @@ let a=!1,c=Date.now()
|
|
|
4353
4469
|
try{n.syncBranchState&&await n.syncBranchState(),Date.now(),c=Date.now()
|
|
4354
4470
|
const e=n.getCurrentBranchContext?await n.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
4355
4471
|
if(Date.now(),e.requestId===r)return o.debug("Already in correct request context",{requestId:r,currentBranch:e.branch}),{switched:!1,branchName:e.branch||void 0,message:`Already in request ${r} context`,lockAcquired:!1}
|
|
4356
|
-
if(n.workspaceManager){o.debug("Using WorkspaceManager for request context switching",{requestId:r,currentMode:n.workspaceManager.getCurrentContext().mode})
|
|
4357
|
-
try{if("multi-agent"===n.workspaceManager.getCurrentContext().mode)if(o.debug("Multi-agent mode: checking request lock before auto-switch",{requestId:r}),n.apiClient)try{const e=n.apiClient.getRequestClient(),{sessionTag:t}=(0,h.getGlobalClientInfo)()
|
|
4472
|
+
if(n.workspaceManager){o.debug("Using WorkspaceManager for request context switching",{requestId:r,currentMode:n.workspaceManager.getCurrentContext(n.currentSessionId).mode})
|
|
4473
|
+
try{if("multi-agent"===n.workspaceManager.getCurrentContext(n.currentSessionId).mode)if(o.debug("Multi-agent mode: checking request lock before auto-switch",{requestId:r}),n.apiClient)try{const e=n.apiClient.getRequestClient(),{sessionTag:t}=(0,h.getGlobalClientInfo)()
|
|
4358
4474
|
c=Date.now()
|
|
4359
4475
|
const s=await e.getRequestLockStatus(r)
|
|
4360
4476
|
if(Date.now(),s.isLocked&&s.lockedBySessionTag!==t){o.warn("Auto-switch blocked by request lock",{requestId:r,lockedByAgent:s.lockedBySessionTag,currentAgent:t,lockedAt:s.lockedAt})
|
|
@@ -4364,16 +4480,16 @@ t.lockOverride.enabled&&(e+=`\n\n**To take over this request (only if safe to do
|
|
|
4364
4480
|
const n=await e.lockRequest(r,t)
|
|
4365
4481
|
if(Date.now(),!n.locked){const e=`Failed to acquire lock for request ${r} during auto-switch`
|
|
4366
4482
|
throw o.warn("Auto-switch lock acquisition failed",{requestId:r}),Error(e)}o.info("Successfully acquired lock for auto-switch",{requestId:r,sessionTag:t,lockedAt:n.lockedAt}),a=!0}}catch(e){throw o.error("Lock check/acquisition failed during auto-switch",{requestId:r,error:e instanceof Error?e.message:e+""}),e}else o.warn("Multi-agent mode but no API client available for locking",{requestId:r})
|
|
4367
|
-
o.debug("Ensuring workspace is ready for file operations",{requestId:r,reason:"first-file-operation"}),c=Date.now(),await n.workspaceManager.ensureWorkspaceReady(r),Date.now()
|
|
4368
|
-
const e=n.workspaceManager.getCurrentContext()
|
|
4483
|
+
o.debug("Ensuring workspace is ready for file operations",{requestId:r,reason:"first-file-operation"}),c=Date.now(),await n.workspaceManager.ensureWorkspaceReady(r,n.currentSessionId),Date.now()
|
|
4484
|
+
const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
4369
4485
|
if(e.basePath&&(n.git=(0,d.simpleGit)(e.basePath),o.info("Updated git instance to worktree path",{requestId:r,gitWorkingDirectory:e.basePath,mode:e.mode,branchName:e.branchName})),e.requestId!==r){const t=`Workspace switch validation failed. Expected requestId: ${r}, but got: ${e.requestId}`
|
|
4370
|
-
throw o.error("Post-switch context validation failed",{requestId:r,expectedRequestId:r,actualRequestId:e.requestId,actualBasePath:e.basePath,mode:e.mode}),Error(t)}o.info("Workspace is ready via WorkspaceManager",{requestId:r,mode:n.workspaceManager.getCurrentContext().mode,workflow:"hybrid-creation-lazy-worktree",validation:"context_validated"})
|
|
4486
|
+
throw o.error("Post-switch context validation failed",{requestId:r,expectedRequestId:r,actualRequestId:e.requestId,actualBasePath:e.basePath,mode:e.mode}),Error(t)}o.info("Workspace is ready via WorkspaceManager",{requestId:r,mode:n.workspaceManager.getCurrentContext(n.currentSessionId).mode,workflow:"hybrid-creation-lazy-worktree",validation:"context_validated"})
|
|
4371
4487
|
try{const{findLargeUntrackedFiles:s,formatLargeFileWarning:i}=await Promise.resolve().then(t.t.bind(t,7478,23)),a=await s(e.basePath)
|
|
4372
4488
|
if(a.length>0){const e=i(a)
|
|
4373
|
-
n.workspaceManager.largeFileWarning=e,o.warn("Large untracked files detected",{requestId:r,fileCount:a.length,files:a.map((e=>({path:e.path,sizeMB:e.sizeMB})))})}}catch(e){o.debug("Large file check failed",{error:e})}return s.incrementCounter(i+"_auto_context_switch_success",1),{switched:!0,branchName:n.workspaceManager.getCurrentContext().branchName,message:"Workspace ready for request "+r,lockAcquired:a,lockedRequestId:a?r:void 0}}catch(e){if(e instanceof p.RequestLockError)throw o.warn("Auto-switch blocked by request lock, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
|
|
4489
|
+
n.workspaceManager.largeFileWarning=e,o.warn("Large untracked files detected",{requestId:r,fileCount:a.length,files:a.map((e=>({path:e.path,sizeMB:e.sizeMB})))})}}catch(e){o.debug("Large file check failed",{error:e})}return s.incrementCounter(i+"_auto_context_switch_success",1),{switched:!0,branchName:n.workspaceManager.getCurrentContext(n.currentSessionId).branchName,message:"Workspace ready for request "+r,lockAcquired:a,lockedRequestId:a?r:void 0}}catch(e){if(e instanceof p.RequestLockError)throw o.warn("Auto-switch blocked by request lock, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
|
|
4374
4490
|
return o.error("Error switching to request context",{requestId:r,error:(0,g.getErrorMessage)(e)}),s.incrementCounter(i+"_auto_context_switch_error",1),{switched:!1,message:"Context switch error: "+(0,g.getErrorMessage)(e)}}}return o.error("WorkspaceManager not available - this should not happen",{requestId:r}),{switched:!1,message:"WorkspaceManager not available"}}catch(e){if(e instanceof p.RequestLockError)throw o.warn("Auto-switch blocked by request lock, re-throwing lock error",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,lockedAt:e.lockedAt}),e
|
|
4375
4491
|
return o.error("Error during auto-switch to request branch",{requestId:r,error:(0,g.getErrorMessage)(e)}),s.incrementCounter(i+"_auto_branch_switch_error",1),{switched:!1,message:"Error during switch: "+(0,g.getErrorMessage)(e)}}}function s(e,t,r,n){if(!e.workspaceManager)return n.debug("No workspace manager available, skipping context validation",{operation:r,requestId:t}),{isValid:!0}
|
|
4376
|
-
const o=e.workspaceManager.getCurrentContext()
|
|
4492
|
+
const o=e.workspaceManager.getCurrentContext(e.currentSessionId)
|
|
4377
4493
|
if(!t)return n.debug("File operation without requestId in multi-agent mode",{operation:r,currentContext:o.requestId,mode:o.mode,basePath:o.basePath}),{isValid:!0}
|
|
4378
4494
|
if(o.requestId!==t){const e=`Workspace context mismatch for ${r}. Expected requestId: ${t}, but current context is: ${o.requestId}. This suggests workspace switching failed or didn't occur. Current basePath: ${o.basePath}, branch: ${o.branchName}`
|
|
4379
4495
|
return n.error("Workspace context validation failed - context mismatch",{operation:r,expectedRequestId:t,currentRequestId:o.requestId,currentBasePath:o.basePath,currentBranchName:o.branchName,currentIsMainBranch:o.isMainBranch,mode:o.mode,issue:"request_id_mismatch"}),{isValid:!1,errorMessage:e}}if(o.isMainBranch&&t){const e=`File operation ${r} attempted with requestId ${t} but workspace is still in main branch (${o.branchName}). This indicates workspace switching to request context failed.`
|
|
@@ -4421,7 +4537,7 @@ if(e.switched&&a.info(`Auto-switched to request workspace during ${i} operation`
|
|
|
4421
4537
|
if(!t.isValid)return a.error("Workspace context validation failed for "+i,{requestId:r,operation:i,error:t.errorMessage}),{success:!1,switched:e.switched,branchName:e.branchName,error:t.errorMessage,lockAcquired:e.lockAcquired,lockedRequestId:e.lockedRequestId}}return a.debug("Workspace context successfully ensured for "+i,{requestId:r,operation:i,switched:e.switched,branchName:e.branchName}),{success:!0,switched:e.switched,branchName:e.branchName,lockAcquired:e.lockAcquired,lockedRequestId:e.lockedRequestId}}catch(e){const t=(0,g.getErrorMessage)(e)
|
|
4422
4538
|
return e instanceof p.RequestLockError?(a.warn(i+" operation blocked by request lock",{requestId:e.requestId,lockedByAgent:e.lockedByAgent,operation:i}),{success:!1,switched:!1,error:e.message,isLockConflict:!0}):(a.error("Error ensuring workspace context for "+i,{requestId:r,operation:i,error:t}),{success:!1,switched:!1,error:t})}}
|
|
4423
4539
|
const d=t(3807),u=l(t(7478)),h=t(5172),g=t(8824),p=t(7575)
|
|
4424
|
-
l(t(9896)),l(t(6928))},7634(e,exports,t){"use strict"
|
|
4540
|
+
l(t(9896)),l(t(6928)),l(t(857))},7634(e,exports,t){"use strict"
|
|
4425
4541
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.RequestLockManager=exports.WorktreeManager=void 0
|
|
4426
4542
|
var r=t(1502)
|
|
4427
4543
|
Object.defineProperty(exports,"WorktreeManager",{enumerable:!0,get(){return r.WorktreeManager}})
|
|
@@ -4430,9 +4546,10 @@ Object.defineProperty(exports,"RequestLockManager",{enumerable:!0,get(){return n
|
|
|
4430
4546
|
var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
4431
4547
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.MultiAgentWorkspaceManager=void 0
|
|
4432
4548
|
const n=r(t(6928)),o=t(3807),s=t(7634),i=t(8824),a=t(7075),c=t(1387),l=t(4968)
|
|
4433
|
-
class d{getSession(e){
|
|
4549
|
+
class d{getSession(e){e||this.logger.warn("getSession called without sessionId \u2014 using __default__. This may cause cross-session contamination.",{stack:Error().stack?.split("\n").slice(1,4).join(" <- ")})
|
|
4550
|
+
const t=e||d.DEFAULT_SESSION
|
|
4434
4551
|
let r=this.sessions.get(t)
|
|
4435
|
-
return r||(r={requestId:null,worktreePath:null,git:this.mainGit,readonlyBranchCheckDone:!1,workspaceKnownClean:!1,largeFileWarning:""},this.sessions.set(t,r)),r}constructor(e,t,r,n,o){this.basePath=e,this.logger=t,this.mainGit=r,this.metrics=n,this.workspaceStates=new Map,this.sessions=new Map,this.apiClient=o
|
|
4552
|
+
return r||(r={requestId:null,worktreePath:null,git:this.mainGit,readonlyBranchCheckDone:!1,workspaceKnownClean:!1,largeFileWarning:"",permanentBranch:!1},this.sessions.set(t,r)),r}constructor(e,t,r,n,o){this.basePath=e,this.logger=t,this.mainGit=r,this.metrics=n,this.workspaceStates=new Map,this.sessions=new Map,this.apiClient=o
|
|
4436
4553
|
const i=a.ConflictResolutionUtils.initializeDetectors(r,t)
|
|
4437
4554
|
this.conflictDetector=i.conflictDetector,this.safetyAnalyzer=i.safetyAnalyzer,this.conflictResolver=i.conflictResolver,this.worktreeManager=new s.WorktreeManager(e,t,n),this.gitAdapter=new l.WorktreeGitAdapter(r,this.worktreeManager,this.conflictDetector,t,n),this.requestProcessor=new c.WorkspaceRequestProcessor(this.gitAdapter,this.conflictDetector,this.safetyAnalyzer,this.conflictResolver,t),this.initializeWorktreeManager(),this.initializeFromEnv()}async initializeFromEnv(){const e=process.env.ALCHEMY_INITIAL_BRANCH
|
|
4438
4555
|
if(!e)return
|
|
@@ -4441,8 +4558,8 @@ if(!t)return void this.logger.warn("ALCHEMY_INITIAL_BRANCH set but not a request
|
|
|
4441
4558
|
const r=t[1]
|
|
4442
4559
|
this.logger.info("ALCHEMY_INITIAL_BRANCH set, switching to worktree",{initialBranch:e,requestId:r})
|
|
4443
4560
|
try{await this.ensureWorkspaceReady(r)
|
|
4444
|
-
const e=this.getSession()
|
|
4445
|
-
e.readonlyBranchCheckDone=!0,this.logger.info("Successfully switched to worktree from ALCHEMY_INITIAL_BRANCH",{requestId:r,worktreePath:e.worktreePath})}catch(t){this.logger.warn("Failed to switch to worktree from ALCHEMY_INITIAL_BRANCH",{initialBranch:e,requestId:r,error:(0,i.getErrorMessage)(t)})}}hasExactConflictMarkers(e){return!(!e||!e.trim())&&[/^\s*<{7}(?:\s|$)/m,/^\s*={7}(?:\s|$)/m,/^\s*>{7}(?:\s|$)/m].some((t=>t.test(e)))}async initializeWorktreeManager(){try{await this.worktreeManager.initialize(),this.logger.debug("Initialized multi-agent workspace manager with worktrees")}catch(e){throw this.logger.error("Failed to initialize worktree manager",{error:e}),e}}setTaskCreator(e){this.taskCreator=e}async initializeRequest(e,t){const r=Date.now(),n=a.WorkspaceValidation.validateRequestId(e)
|
|
4561
|
+
const e=this.getSession("__init__")
|
|
4562
|
+
e.readonlyBranchCheckDone=!0,e.permanentBranch=!0,this.logger.info("Successfully switched to worktree from ALCHEMY_INITIAL_BRANCH",{requestId:r,worktreePath:e.worktreePath})}catch(t){this.logger.warn("Failed to switch to worktree from ALCHEMY_INITIAL_BRANCH",{initialBranch:e,requestId:r,error:(0,i.getErrorMessage)(t)})}}hasExactConflictMarkers(e){return!(!e||!e.trim())&&[/^\s*<{7}(?:\s|$)/m,/^\s*={7}(?:\s|$)/m,/^\s*>{7}(?:\s|$)/m].some((t=>t.test(e)))}async initializeWorktreeManager(){try{await this.worktreeManager.initialize(),this.logger.debug("Initialized multi-agent workspace manager with worktrees")}catch(e){throw this.logger.error("Failed to initialize worktree manager",{error:e}),e}}setTaskCreator(e){this.taskCreator=e}async initializeRequest(e,t){const r=Date.now(),n=a.WorkspaceValidation.validateRequestId(e)
|
|
4446
4563
|
if(!n.isValid)throw Error("Invalid request ID: "+n.errors.join(", "))
|
|
4447
4564
|
const o=n.sanitized
|
|
4448
4565
|
try{this.workspaceStates.set(o,"initialized")
|
|
@@ -4500,7 +4617,7 @@ const r=t.sanitized
|
|
|
4500
4617
|
try{for(const[e,t]of this.sessions)t.requestId===r&&(t.requestId=null,t.worktreePath=null,t.git=this.mainGit)
|
|
4501
4618
|
const e=await this.worktreeManager.removeWorktree(r,!1)
|
|
4502
4619
|
if(!e.success)throw Error(e.message||"Failed to remove worktree")
|
|
4503
|
-
this.logger.info("Successfully cancelled request",{requestId:r})}catch(e){throw this.logger.error("Failed to cancel request",{requestId:r,error:(0,i.getErrorMessage)(e)}),e}}getCurrentContext(e){const t=this.getSession(e),r={requestId:t.requestId,basePath:t.worktreePath||this.basePath,branchName:t.requestId?"requests/"+t.requestId:"main",isMainBranch:!t.requestId,mode:"multi-agent"}
|
|
4620
|
+
this.logger.info("Successfully cancelled request",{requestId:r})}catch(e){throw this.logger.error("Failed to cancel request",{requestId:r,error:(0,i.getErrorMessage)(e)}),e}}getCurrentContext(e){const t=this.getSession(e),r={requestId:t.requestId,basePath:t.worktreePath||this.basePath,branchName:t.requestId?"requests/"+t.requestId:"main",isMainBranch:!t.requestId,mode:"multi-agent",permanentBranch:t.permanentBranch}
|
|
4504
4621
|
return this.logger.debug("getCurrentContext returning",{context:r,sessionId:e}),r}resetCurrentContext(e){const t=this.getSession(e)
|
|
4505
4622
|
t.requestId&&this.logger.info("Resetting workspace context (session switch)",{prevRequestId:t.requestId,prevWorktreePath:t.worktreePath,sessionId:e}),t.requestId=null,t.worktreePath=null,t.git=this.mainGit,t.readonlyBranchCheckDone=!1}async getWorkspaceInfo(e){try{const t=a.WorkspaceValidation.validateRequestId(e)
|
|
4506
4623
|
if(!t.isValid)return null
|
|
@@ -4510,7 +4627,7 @@ return t?t[1]:null}convertWorktreeInfoToWorkspaceInfo(e){return{requestId:e.requ
|
|
|
4510
4627
|
return this.worktreeManager.getWorktreeInfo(t)}catch(t){return void this.logger.warn("Failed to get worktree info",{requestId:e,error:(0,i.getErrorMessage)(t)})}}getMainGit(){return this.gitAdapter.getMainGit()}getCurrentGit(e){return this.getSession(e).git}get readonlyBranchCheckDone(){return this.getSession().readonlyBranchCheckDone}set readonlyBranchCheckDone(e){this.getSession().readonlyBranchCheckDone=e}get workspaceKnownClean(){return this.getSession().workspaceKnownClean}set workspaceKnownClean(e){this.getSession().workspaceKnownClean=e}get largeFileWarning(){return this.getSession().largeFileWarning}set largeFileWarning(e){this.getSession().largeFileWarning=e}async ensureReadonlyBranchIfNeeded(e,r,n,o){const s=this.getSession(o)
|
|
4511
4628
|
if(s.readonlyBranchCheckDone)return
|
|
4512
4629
|
if(s.readonlyBranchCheckDone=!0,o&&n)try{const{sessionIdentity:e}=await Promise.resolve().then(t.bind(t,6688)),r=await e.getSessionRequestId(n,this.logger,o)
|
|
4513
|
-
if(r)return await this.ensureWorkspaceReady(r,o),void this.logger.info("ensureReadonlyBranchIfNeeded: workspace ready from session DB lookup",{requestId:r,sessionId:o})}catch(e){this.logger.warn("ensureReadonlyBranchIfNeeded: session DB lookup failed, falling back to env var",{error:(0,i.getErrorMessage)(e)})}const a=process.env.ALCHEMY_INITIAL_BRANCH
|
|
4630
|
+
if(r)return await this.ensureWorkspaceReady(r,o),s.permanentBranch=!0,void this.logger.info("ensureReadonlyBranchIfNeeded: workspace ready from session DB lookup",{requestId:r,sessionId:o,permanentBranch:!0})}catch(e){this.logger.warn("ensureReadonlyBranchIfNeeded: session DB lookup failed, falling back to env var",{error:(0,i.getErrorMessage)(e)})}const a=process.env.ALCHEMY_INITIAL_BRANCH
|
|
4514
4631
|
if(a){const e=a.match(/^requests\/(.+)$/)
|
|
4515
4632
|
if(e){const t=e[1]
|
|
4516
4633
|
try{await this.ensureWorkspaceReady(t,o),this.logger.info("ensureReadonlyBranchIfNeeded: workspace ready from env var",{requestId:t})}catch(e){this.logger.warn("ensureReadonlyBranchIfNeeded: failed to ensure workspace",{requestId:t,error:(0,i.getErrorMessage)(e)})}}}}isActiveForAnySession(e){for(const[,t]of this.sessions)if(t.requestId===e)return!0
|
|
@@ -4532,30 +4649,30 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
4532
4649
|
var t={}
|
|
4533
4650
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4534
4651
|
return o(t,e),t})
|
|
4535
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleManageFiles=async function(e,
|
|
4536
|
-
try{const h=a.validateArgs(e,i.ManageFilesSchema),{
|
|
4537
|
-
|
|
4538
|
-
const
|
|
4539
|
-
for(const e of
|
|
4652
|
+
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"})
|
|
4653
|
+
try{const h=a.validateArgs(e,i.ManageFilesSchema),{operations:w,comment:k}=h,{resolveActiveTaskId:I}=await Promise.resolve().then(t.bind(t,3451)),b=e.taskId||await I(r,g,p)||"untracked"
|
|
4654
|
+
y.info("Processing manage-files operations",{taskId:b,operationCount:w.length,comment:k})
|
|
4655
|
+
const v=[],C=[],_=[],E=[]
|
|
4656
|
+
for(const e of w)switch(e.operationType){case"create-directory":v.push({path:e.createDirectory.path})
|
|
4540
4657
|
break
|
|
4541
|
-
case"move-files":for(const t of e.moveFiles.moves)
|
|
4658
|
+
case"move-files":for(const t of e.moveFiles.moves)C.push(t)
|
|
4542
4659
|
break
|
|
4543
|
-
case"delete-files":
|
|
4660
|
+
case"delete-files":_.push(...e.deleteFiles.targets)
|
|
4544
4661
|
break
|
|
4545
|
-
case"get-file-info":
|
|
4546
|
-
for(const e of
|
|
4547
|
-
const
|
|
4548
|
-
|
|
4549
|
-
const e=await(0,l.handleMoveFiles)({taskId:
|
|
4550
|
-
|
|
4551
|
-
const e=await(0,u.handleDeleteFiles)({taskId:
|
|
4552
|
-
|
|
4553
|
-
const
|
|
4554
|
-
|
|
4555
|
-
let
|
|
4556
|
-
|
|
4557
|
-
for(const{type:e,result:t}of
|
|
4558
|
-
return
|
|
4662
|
+
case"get-file-info":E.push({path:e.getFileInfo.path})}const q=[]
|
|
4663
|
+
for(const e of v){y.info("Routing to create-directory handler",{path:e.path})
|
|
4664
|
+
const t=await(0,c.handleCreateDirectory)({taskId:b,path:e.path,comment:k+" [via manage-files: create-directory]"},r,n,o,s,y,f,m)
|
|
4665
|
+
q.push({type:"create-directory",result:t})}if(C.length>0){y.info("Routing to move-files handler",{operationCount:C.length})
|
|
4666
|
+
const e=await(0,l.handleMoveFiles)({taskId:b,operations:C,comment:k+" [via manage-files: move-files]"},r,n,o,s,y,f,m)
|
|
4667
|
+
q.push({type:"move-files",result:e})}if(_.length>0){y.info("Routing to delete-files handler",{operationCount:_.length})
|
|
4668
|
+
const e=await(0,u.handleDeleteFiles)({taskId:b,operations:_,comment:k+" [via manage-files: delete-files]"},r,g,y,f,m)
|
|
4669
|
+
q.push({type:"delete-files",result:e})}for(const e of E){y.info("Routing to get-file-info handler",{path:e.path})
|
|
4670
|
+
const t=await(0,d.handleGetFileInfo)({path:e.path},r,y,f)
|
|
4671
|
+
q.push({type:"get-file-info",result:t})}const S=q.some((e=>e.result.isError)),T=q.filter((e=>!e.result.isError)).length,P=q.filter((e=>e.result.isError)).length
|
|
4672
|
+
let j="## Manage Files Results\n\n"
|
|
4673
|
+
j+="**Summary:**\n",j+=`- **Total operation types:** ${q.length}\n`,j+=`- **Successful:** ${T}\n`,j+=`- **Failed:** ${P}\n\n`
|
|
4674
|
+
for(const{type:e,result:t}of q)j+=`### ${e} operations\n`,j+=t.content[0].text+"\n\n"
|
|
4675
|
+
return y.info("Manage-files operations completed",{totalOperationTypes:q.length,successCount:T,errorCount:P}),f.incrementCounter("manage_files_total",1,{success:!S}),{content:[{type:"text",text:j}],isError:S}}catch(e){return y.error("Manage-files operation failed",{error:e instanceof Error?e.stack:e+""}),f.incrementCounter("manage_files_errors",1),{content:[{type:"text",text:"\u274c **Manage Files Failed:** "+(0,h.getErrorMessage)(e)}],isError:!0}}}
|
|
4559
4676
|
const i=t(6183),a=s(t(5967)),c=t(8309),l=t(2414),d=t(3628),u=t(5992),h=t(8824)},7713(e,exports,t){"use strict"
|
|
4560
4677
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4561
4678
|
const r=t(6183),n=t(5303)
|
|
@@ -4590,7 +4707,7 @@ return t?.success&&t[c]>0})).map((e=>e.path)).filter((e=>e))
|
|
|
4590
4707
|
if(0===n.length)return l.debug("No files to commit to Git"),{filesCommitted:[],success:!0}
|
|
4591
4708
|
l.info("Staging modified files for git commit",{files:n,count:n.length,operationType:s})
|
|
4592
4709
|
let d=o.git
|
|
4593
|
-
if(o.workspaceManager){const t=o.workspaceManager.getCurrentContext()
|
|
4710
|
+
if(o.workspaceManager){const t=o.workspaceManager.getCurrentContext(o.currentSessionId)
|
|
4594
4711
|
"multi-agent"===t.mode&&t.requestId&&(d=(0,a.simpleGit)(t.basePath),l.debug("Using WorkspaceManager git instance for multi-file commit",{taskId:e,mode:t.mode,requestId:t.requestId,basePath:t.basePath,branchName:t.branchName,filesCount:n.length}))}if(!d)return l.debug("No git repository available, skipping commit"),{filesCommitted:[],success:!0}
|
|
4595
4712
|
let g=null
|
|
4596
4713
|
try{g=(await d.revparse(["HEAD"])).trim()}catch(e){l.warn("Failed to get current commit hash",{error:e})}for(const e of n)await d.add(e)
|
|
@@ -4603,13 +4720,13 @@ l.debug("createFileOperationRecords called",{taskId:e,requestId:t,projectId:n||"
|
|
|
4603
4720
|
try{const a=await r(e,t,n,o,s,i,c,l,u,h)
|
|
4604
4721
|
return p=a.recordId,f=a.localRecordId,l.info("Created tool record for file operation: "+o,{taskId:e,path:s,toolRecordId:p,localToolRecordId:f}),{toolRecordId:p,localToolRecordId:f}}catch(r){throw l.error("Failed to create tool record for file operation: "+o,{error:(0,d.getErrorMessage)(r),errorStack:r instanceof Error?r.stack:void 0,taskId:e,requestId:t,projectId:n||"<empty>",projectIdType:typeof n,path:s}),u.recordValue(h+"_record_creation_time",Date.now()-g),u.incrementCounter(h+"_record_creation_error",1),r}},exports.updateFileOperationRecords=async function(e,t,r,o,s,i,a,c,l,u,h,g,p){try{t&&h.info("Task record update skipped (task records removed): "+t,{taskId:e,path:o}),r&&await n(r,o,s,a,c,u,h,g,p)}catch(t){h.warn("Error updating tool record for operation: "+s,{error:(0,d.getErrorMessage)(t),taskId:e,normalizedPath:o,toolRecordId:r})}},exports.checkAndCommitUserMods=async function(e,t,r,n,o){if(!t.git)return{hadUserMods:!1}
|
|
4605
4722
|
try{let s=t.git
|
|
4606
|
-
if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext()
|
|
4723
|
+
if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
4607
4724
|
"multi-agent"===e.mode&&e.requestId&&(s=(0,a.simpleGit)(e.basePath))}if((await s.diff(["--name-only","HEAD","--",e])).trim().length>0){r.info(`File ${e} has uncommitted changes, preserving user modifications`),await s.add(e)
|
|
4608
4725
|
const t=await s.commit("[USER-MODS] Preserve user modifications before tool operation: "+e)
|
|
4609
4726
|
return r.info("Created user modifications commit",{filePath:e,userModsCommitHash:t.commit}),n.incrementCounter(o+"_user_mods_commits_created",1),{hadUserMods:!0,userModsCommitHash:t.commit}}return{hadUserMods:!1}}catch(t){return r.warn("Failed to check/preserve user modifications for "+e,{error:(0,d.getErrorMessage)(t)}),n.incrementCounter(o+"_user_mods_check_failures",1),{hadUserMods:!1}}},exports.commitToGit=async function(e,t,r,n,o,s,i,c,u){const h=Date.now()
|
|
4610
4727
|
let g,p=null
|
|
4611
4728
|
try{let f=s.git
|
|
4612
|
-
if(s.workspaceManager){const t=s.workspaceManager.getCurrentContext()
|
|
4729
|
+
if(s.workspaceManager){const t=s.workspaceManager.getCurrentContext(s.currentSessionId)
|
|
4613
4730
|
if("multi-agent"===t.mode&&t.requestId){if(!t.basePath.includes("/worktrees/")&&!t.basePath.includes("\\worktrees\\"))throw i.error("CRITICAL BUG: Multi-agent mode but basePath is not a worktree path",{taskId:e,requestId:t.requestId,basePath:t.basePath,expectedPattern:"should contain /worktrees/ or \\worktrees\\",issue:"workspace_context_incorrect"}),Error(`Multi-agent mode context error: basePath '${t.basePath}' is not a worktree path. This will cause commits to go to main branch instead of the request branch.`)
|
|
4614
4731
|
f=(0,a.simpleGit)(t.basePath),i.debug("Using WorkspaceManager git instance for commit",{taskId:e,mode:t.mode,requestId:t.requestId,basePath:t.basePath,branchName:t.branchName,worktreeValidated:!0})}}if(f){i.info("commitToGit called with:",{taskId:e,recordId:r,localRecordId:n,hasLocalRecordId:!!n,localRecordIdType:typeof n,normalizedPath:t})
|
|
4615
4732
|
let a=!1,m=""
|
|
@@ -4685,17 +4802,17 @@ var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:
|
|
|
4685
4802
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.validateArgs=function(e,t){if(e&&"object"==typeof e)for(const t of Object.keys(e)){const r=e[t]
|
|
4686
4803
|
if("string"==typeof r&&(r.startsWith("[")||r.startsWith("{")))try{e[t]=JSON.parse(r)}catch{}}try{return t.parse(e)}catch(e){if(e instanceof o.z.ZodError){const t=e.issues.map((e=>`${e.path.join(".")}: ${e.message}`)).join(", ")
|
|
4687
4804
|
throw(0,s.createValidationError)("Invalid arguments: "+t)}throw e}},exports.validateAndNormalizePath=function(e,t){let r=e.replace(/\\/g,"/")
|
|
4688
|
-
const o=function(e){return e.workspaceManager?e.workspaceManager.getCurrentContext().basePath:e.basePath}(t)
|
|
4805
|
+
const o=function(e){return e.workspaceManager?e.workspaceManager.getCurrentContext(e.currentSessionId).basePath:e.basePath}(t)
|
|
4689
4806
|
if(n.default.isAbsolute(r)){const e=n.default.normalize(r)
|
|
4690
4807
|
if(e.startsWith(o))r=n.default.relative(o,e),r=r.replace(/\\/g,"/")
|
|
4691
4808
|
else{const i=t.basePath
|
|
4692
|
-
if(!i||!e.startsWith(i)){const r=t.workspaceManager?.getCurrentContext()?.mode||"unknown",n=t.workspaceManager?.getCurrentContext()?.requestId||"none"
|
|
4809
|
+
if(!i||!e.startsWith(i)){const r=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.mode||"unknown",n=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.requestId||"none"
|
|
4693
4810
|
throw(0,s.createValidationError)(`File path is outside the allowed directory\n Requested path (absolute): ${e}\n Allowed base (current workspace): ${o}\n Allowed base (main repo): ${i||"N/A"}\n Workspace mode: ${r}\n Current request: ${n}\n Note: Use relative paths (e.g., 'src/file.txt') instead of absolute paths`)}r=n.default.relative(i,e),r=r.replace(/\\/g,"/")}}if(function(e){const t=e.replace(/\\/g,"/").replace(/^\//g,"")
|
|
4694
4811
|
for(const e of i)if(t===e||t.startsWith(e+"/"))return!0
|
|
4695
4812
|
for(const e of a)if(t===e||t.endsWith("/"+e))return!0
|
|
4696
4813
|
return!1}(r))throw(0,s.createValidationError)(`Access to '${r}' is not allowed - this directory contains system files`)
|
|
4697
4814
|
const c=n.default.resolve(o,r)
|
|
4698
|
-
if(!c.startsWith(o)){const e=t.workspaceManager?.getCurrentContext()?.mode||"unknown",n=t.workspaceManager?.getCurrentContext()?.requestId||"none"
|
|
4815
|
+
if(!c.startsWith(o)){const e=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.mode||"unknown",n=t.workspaceManager?.getCurrentContext(t.currentSessionId)?.requestId||"none"
|
|
4699
4816
|
throw(0,s.createValidationError)(`File path is outside the allowed directory\n Requested path: ${r}\n Resolved to: ${c}\n Allowed base: ${o}\n Workspace mode: ${e}\n Current request: `+n)}return{normalizedPath:r,fullPath:c}},exports.validateTaskIdFormat=function(e,t,r,n){e&&/^tas\d{6}$/.test(e)||(t.warn("Invalid task ID format provided",{taskId:e}),r.incrementCounter(n+"_invalid_task_format",1))}
|
|
4700
4817
|
const n=r(t(6928)),o=t(1569),s=t(9860),i=[t(4139).ALCHEMY_DIR_NAME,".opencode",".git"],a=[".mcp-server.lock"]},8309(e,exports,t){"use strict"
|
|
4701
4818
|
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
@@ -4706,33 +4823,33 @@ return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
|
4706
4823
|
var t={}
|
|
4707
4824
|
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
4708
4825
|
return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
4709
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDirectory=async function(e,
|
|
4710
|
-
let
|
|
4711
|
-
const
|
|
4712
|
-
try{const
|
|
4713
|
-
|
|
4714
|
-
const{normalizedPath:
|
|
4715
|
-
|
|
4716
|
-
const
|
|
4717
|
-
|
|
4718
|
-
const
|
|
4719
|
-
if(!
|
|
4720
|
-
throw Error(
|
|
4721
|
-
try{
|
|
4722
|
-
const{toolRecordId:
|
|
4723
|
-
|
|
4724
|
-
let
|
|
4725
|
-
if(!
|
|
4726
|
-
try{const e=c.default.join(
|
|
4727
|
-
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),
|
|
4728
|
-
|
|
4729
|
-
const
|
|
4730
|
-
|
|
4731
|
-
const
|
|
4732
|
-
return{content:[{type:"text",text:
|
|
4733
|
-
await
|
|
4734
|
-
if(
|
|
4735
|
-
try{await d.updateFileOperationRecords(e.taskId,
|
|
4826
|
+
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()
|
|
4827
|
+
let w,k,I=d.FileOperationPhase.VALIDATION
|
|
4828
|
+
const b={toolName:"create-directory",operationName:"create",fileOperationPhase:d.FileOperationPhase.FILE_WRITE,recordType:"create-directory",metricsPrefix:"create_directory",successMessage:"Successfully created directory {path}",failureMessage:"Failed to create directory {path}"}
|
|
4829
|
+
try{const u=d.validateArgs(e,l.CreateDirectorySchema),{path:h,comment:g}=u,{resolveActiveTaskId:v}=await Promise.resolve().then(t.bind(t,3451)),C=e.taskId||await v(r,n,i)||"untracked"
|
|
4830
|
+
m.info("Creating directory: "+h,{taskId:C,path:h,comment:g}),d.validateTaskIdFormat(C,m,p,b.metricsPrefix),r.getCurrentBranchContext&&await r.getCurrentBranchContext()
|
|
4831
|
+
const{normalizedPath:_,fullPath:E}=d.validateAndNormalizePath(h,r)
|
|
4832
|
+
I=d.FileOperationPhase.TASK_VALIDATION,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4833
|
+
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)
|
|
4834
|
+
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})
|
|
4835
|
+
const j=await d.ensureCorrectWorkspaceContext({taskPromoted:P.taskPromoted,requestId:S,context:r,operation:"create-directory",logger:m,metrics:p,metricsPrefix:b.metricsPrefix})
|
|
4836
|
+
if(!j.success){if(j.isLockConflict)return{content:[{type:"text",text:"\u274c "+j.error}],isError:!0}
|
|
4837
|
+
throw Error(j.error)}let x=!1
|
|
4838
|
+
try{x=(await a.default.stat(E)).isDirectory()}catch{x=!1}I=d.FileOperationPhase.RECORD_CREATION,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4839
|
+
const{toolRecordId:R,localToolRecordId:M}=await d.createFileOperationRecords(C,S,r.projectId,b.recordType,_,{directoryExists:x,userComment:g},n,o,m,p,b.metricsPrefix,f)
|
|
4840
|
+
w=R,k=R,I=b.fileOperationPhase,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4841
|
+
let O=x
|
|
4842
|
+
if(!x){await a.default.mkdir(E,{recursive:!0}),m.info("Successfully created directory "+_)
|
|
4843
|
+
try{const e=c.default.join(E,".gitkeep")
|
|
4844
|
+
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),O=!0,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 $=Date.now()-y
|
|
4845
|
+
p.recordValue("create_directory_time",$),p.incrementCounter("create_directory_success",1),I=d.FileOperationPhase.GIT_COMMIT,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4846
|
+
const D=`Create directory: ${_} - ${g||"Create directory"}`,A=!x&&O?_+"/.gitkeep":_,F=await d.commitToGit(C,A,R,M,D,r,m,p,b.metricsPrefix)
|
|
4847
|
+
I=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,p.incrementCounter("create_directory_phase",1,{phase:I}),await d.updateFileOperationRecords(C,w,k,_,b.recordType,`Successfully ${x?"verified":"created"} directory: ${_}`,{status:"completed",commitHash:F.commitHash,previousCommitHash:F.previousCommitHash,directoryExists:x,isDirectory:!0,userComment:g},`Successfully ${x?"verified":"created"} directory: ${_}`,n,o,m,p,b.metricsPrefix)
|
|
4848
|
+
const N=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
4849
|
+
return{content:[{type:"text",text:x?"Directory already exists":`Successfully created directory${F.commitHash?"\nCommit: "+F.commitHash.substring(0,8):""}${N.requestId&&!N.permanentBranch?"\nBranch: "+N.requestId:""}${j.lockAcquired&&j.lockedRequestId&&!N.permanentBranch?"\n\u{1f512} **Locked request:** "+j.lockedRequestId:""}`}]}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
|
|
4850
|
+
await o.createToolRecord({...n?{}:{taskId:e.taskId},projectId:r.projectId,type:"create-directory",metadata:{status:"failed",timestamp:(new Date).toISOString(),path:e.path,userComment:e.comment,error:(0,g.getErrorMessage)(t),errorDetails:t instanceof Error?t.stack:t+"",phase:I,attemptedTaskId:e.taskId,taskIdValidationFailed:n},note:`Failed to create directory ${e.path} - ${(0,g.getErrorMessage)(t)}`})}catch(t){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
|
|
4851
|
+
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
|
|
4852
|
+
try{await d.updateFileOperationRecords(e.taskId,w,k,e.path,b.recordType,"Failed to create directory "+e.path,{status:"failed",error:(0,g.getErrorMessage)(t),userComment:e.comment},"Failed to create directory "+e.path,n,o,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)}}
|
|
4736
4853
|
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"
|
|
4737
4854
|
function r(e){const t=[]
|
|
4738
4855
|
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"
|
|
@@ -4958,7 +5075,19 @@ let r=0,n=0
|
|
|
4958
5075
|
for(const t of e)t.startsWith("+")&&!t.startsWith("+++")&&r++,t.startsWith("-")&&!t.startsWith("---")&&n++
|
|
4959
5076
|
b+=`\n**Changes:**${r>0||n>0?` (Added ${r} lines, removed ${n} lines)`:""}\n\`\`\`diff\n${t.diff}\n\`\`\`\n`}b+="\n"}return b+="\u{1f4a1} **Tips:**\n",b+="- Use `file-recover` with a commit hash to restore the file to a previous version\n",b+='- Use `{"branch": "main"}` to see only main branch history\n',b+='- Use `{"branch": "req123456"}` to see only request branch history\n\n',d.info("Branch-aware file history retrieved successfully",{path: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
|
|
4960
5077
|
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}}}
|
|
4961
|
-
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},
|
|
5078
|
+
const c=a(t(6928)),l=a(t(1943)),d=t(6183),u=t(1569),h=t(1181),g=t(2085),p=t(8824),f=a(t(5967)),m=a(t(7478)),{getCurrentBranch:y}=m},8849(e,exports,t){"use strict"
|
|
5079
|
+
var r,n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
5080
|
+
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
5081
|
+
o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[]
|
|
5082
|
+
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
5083
|
+
return t},r(e)},function(e){if(e&&e.__esModule)return e
|
|
5084
|
+
var t={}
|
|
5085
|
+
if(null!=e)for(var s=r(e),i=0;i<s.length;i++)"default"!==s[i]&&n(t,e,s[i])
|
|
5086
|
+
return o(t,e),t})
|
|
5087
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkingDefs=void 0
|
|
5088
|
+
const i=s(t(6183)),a=t(4425)
|
|
5089
|
+
var c
|
|
5090
|
+
exports.checkingDefs=[{name:"commands",description:'Manage and run project commands (typecheck, lint, build, etc.) to verify your work. Operations: "list" to see available commands, "run" to execute one by name, "add" to register a new command for this project.',schema:i.CommandsSchema,annotations:{title:"Commands",readOnlyHint:!1},createsRecords:!0,handler:(c=a.handleCommands,(e,t)=>c(e,t.context,t.apiClient,t.logger,t.metrics,t.apiClient?.getToolRecordClient?.()))}]},8850(e,exports,t){"use strict"
|
|
4962
5091
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
4963
5092
|
const r=t(6183),n=t(6891)
|
|
4964
5093
|
exports.def={name:"task_file_history",description:"See all file changes made during a task. Use query_history tool instead.",schema:r.QueryHistorySchema,annotations:{title:"Task File History",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleTaskFileHistory)(e,t.context,t.apiClient,t.logger,t.metrics)}}},8909(e,exports,t){"use strict"
|
|
@@ -5251,51 +5380,51 @@ return t},o(e)},function(e){if(e&&e.__esModule)return e
|
|
|
5251
5380
|
var t={}
|
|
5252
5381
|
if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
5253
5382
|
return i(t,e),t}),c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}}
|
|
5254
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleReplaceInFiles=async function(e,
|
|
5255
|
-
let
|
|
5383
|
+
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()
|
|
5384
|
+
let C,_=u.FileOperationPhase.VALIDATION
|
|
5256
5385
|
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)
|
|
5257
|
-
const
|
|
5258
|
-
|
|
5259
|
-
const T
|
|
5260
|
-
if(
|
|
5261
|
-
throw e}
|
|
5262
|
-
const
|
|
5263
|
-
let
|
|
5264
|
-
const
|
|
5386
|
+
const E=u.validateArgs(e,d.ReplaceInFilesSchema),{resolveActiveTaskId:q}=await Promise.resolve().then(t.bind(t,3451)),S=e.taskId||await q(r,o,a)||"untracked",{operations:T,fuzzy_match:P=!0,comment:j}=E
|
|
5387
|
+
b.info("Replace in files batch operation",{taskId:S,operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,comment:j})
|
|
5388
|
+
const x=T.filter((e=>e.documentId)).map((e=>e.documentId))
|
|
5389
|
+
if(x.length>0&&r.apiClient)try{await(0,m.ensureDocumentsNotLocked)(x,r.apiClient,b,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
5390
|
+
throw e}_=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5391
|
+
const R=T[0],M=R.documentId?"document:"+R.documentId:R.path
|
|
5392
|
+
let O=Date.now()
|
|
5393
|
+
const $=await u.validateTaskId(S,M,o,b,c,"replace_in_files")
|
|
5265
5394
|
Date.now()
|
|
5266
|
-
const
|
|
5267
|
-
let
|
|
5268
|
-
if(
|
|
5269
|
-
const e=await u.validateWorkItemStates(
|
|
5270
|
-
Date.now(),
|
|
5271
|
-
const
|
|
5272
|
-
|
|
5273
|
-
const
|
|
5274
|
-
if(!
|
|
5275
|
-
throw Error(
|
|
5276
|
-
throw e}
|
|
5277
|
-
const
|
|
5278
|
-
if(
|
|
5395
|
+
const D=$?.requestId,A=T.some((e=>e.path))
|
|
5396
|
+
let F=!1
|
|
5397
|
+
if(A&&D){O=Date.now()
|
|
5398
|
+
const e=await u.validateWorkItemStates(S,M,o,i,r,b,c,"replace_in_files")
|
|
5399
|
+
Date.now(),O=Date.now()
|
|
5400
|
+
const t=await u.autoPromoteTaskStatus(S,$.status,D,e.request?.status,M,o,i,b,c,"replace_in_files")
|
|
5401
|
+
t.taskPromoted&&b.info("Auto-promoted task to in_progress",{taskId:S,requestId:D,previousStatus:$.status,newStatus:t.newTaskStatus}),Date.now(),O=Date.now()
|
|
5402
|
+
const n=await u.ensureCorrectWorkspaceContext({taskPromoted:t.taskPromoted,requestId:D,context:r,operation:"replace_in_files",logger:b,metrics:c,metricsPrefix:"replace_in_files"})
|
|
5403
|
+
if(!n.success){if(n.isLockConflict)return{content:[{type:"text",text:"\u274c "+n.error}],isError:!0}
|
|
5404
|
+
throw Error(n.error)}Date.now(),F=!0}if(x.length>0&&D)try{await(0,p.validateRequestStatusForDocumentOperation)(D,i,b,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
5405
|
+
throw e}O=Date.now()
|
|
5406
|
+
const N=new Map
|
|
5407
|
+
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=[]
|
|
5279
5408
|
for(const t of e.replacements){const r=(0,h.findMatches)(n,t.old,o,100,e.path)
|
|
5280
|
-
s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,
|
|
5281
|
-
|
|
5282
|
-
const i=await(0,w.detectExternalEdits)(
|
|
5283
|
-
|
|
5284
|
-
const e=await(0,f.commitUserChangesBeforeToolOperation)(
|
|
5285
|
-
e.userChangesCommitted&&(
|
|
5286
|
-
const{toolRecordId:
|
|
5287
|
-
|
|
5288
|
-
const
|
|
5289
|
-
for(const e of
|
|
5290
|
-
|
|
5291
|
-
const
|
|
5409
|
+
s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,t.fullPath)
|
|
5410
|
+
b.info("\u{1f50d} Checking for external edits",{path:t.normalizedPath,affectedLines:o.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),matchCount:s.length})
|
|
5411
|
+
const i=await(0,w.detectExternalEdits)(r.git,o,b)
|
|
5412
|
+
b.info("\u{1f50d} External edit detection result",{path:t.normalizedPath,hasExternalEdits:i.hasExternalEdits,conflictingLines:i.conflictingLines,hasMessage:!!i.message}),i.hasExternalEdits&&i.message?(N.set(e.path,{message:i.message,debugInfo:i.debugInfo}),b.warn("\u26a0\ufe0f External edits detected before auto-commit",{path:t.normalizedPath,conflictingLines:i.conflictingLines})):(i.debugInfo&&N.set(e.path,{message:"",debugInfo:i.debugInfo}),b.info("\u2705 No external edit conflicts detected",{path:t.normalizedPath}))}else b.info("\u2139\ufe0f No matches found for external edit detection",{path:t.normalizedPath}),N.set(e.path,{message:"",debugInfo:{detectionRan:!1,reason:"No matches found - patterns not found in file",affectedRegion:"none",uncommittedChanges:"not checked",overlapDetected:!1}})}catch(t){b.warn("Failed to check for external edits before auto-commit",{path:e.path,error:(0,k.getErrorMessage)(t)})}if(Date.now(),O=Date.now(),A&&r.git)try{b.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
|
|
5413
|
+
const e=await(0,f.commitUserChangesBeforeToolOperation)(r.git,"replace_in_files",{requestId:D,taskId:S,workspaceManager:r.workspaceManager},b,c)
|
|
5414
|
+
e.userChangesCommitted&&(b.debug("[REPLACE-IN-FILES] User changes committed",{commitHash:e.commitHash?.substring(0,8),filesCommitted:e.filesCommitted}),b.info("User changes committed before batch operation",{taskId:S,userCommitHash:e.commitHash?.substring(0,8),userFilesCommitted:e.filesCommitted}))}catch(e){b.warn("Pre-tool user changes commit failed",{taskId:S,error:e instanceof Error?e.message:e+""})}Date.now(),O=Date.now(),_=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5415
|
+
const{toolRecordId:L}=await u.createFileOperationRecords(S,D,r.projectId,"replace-in-files",M,{operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:P,userComment:j},o,s,b,c,"replace_in_files",I)
|
|
5416
|
+
C=L,Date.now(),O=Date.now(),_=u.FileOperationPhase.STRING_REPLACEMENT,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5417
|
+
const z=[],H=[]
|
|
5418
|
+
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)
|
|
5419
|
+
z.push(o),o.successfulReplacements>0&&"file"===o.type&&o.path&&H.push(o.path)}Date.now(),O=Date.now()
|
|
5420
|
+
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
|
|
5292
5421
|
Date.now(),Date.now()
|
|
5293
|
-
const
|
|
5294
|
-
await
|
|
5295
|
-
const
|
|
5422
|
+
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})))
|
|
5423
|
+
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}}})
|
|
5424
|
+
const X=await async function(e,t,r,n,o,s){const i=e.filter((e=>e.success)).length,a=e.length-i,c=e.filter((e=>!e.success&&!e.error&&e.successfulReplacements>0)).length
|
|
5296
5425
|
let l="## Replace In Files - Batch Results\n\n"
|
|
5297
|
-
if(o.
|
|
5298
|
-
e.
|
|
5426
|
+
if(o.workspaceManager)try{const e=o.workspaceManager.getCurrentContext(o.currentSessionId)
|
|
5427
|
+
e.branchName&&!e.permanentBranch&&(l+=`**Current Branch:** ${e.branchName}\n\n`)}catch(e){}l+="**Summary:**\n",l+=`- **Files/Documents:** ${e.length} total`,l+=c>0?` (\u2705 ${i} fully succeeded, \u26a0\ufe0f ${c} partial, \u274c ${a-c} failed)\n`:` (\u2705 ${i} successful, \u274c ${a} failed)\n`,l+=`- **Replacements:** ${r+n} total (\u2705 ${r} successful, \u274c ${n} failed)\n`,t&&(l+=`- **Git Commit:** ${t.substring(0,8)}\n`),s&&(l+=`[RECORD:${s}]\n`),l+="\n---\n\n"
|
|
5299
5428
|
for(let t=0;t<e.length;t++){const r=e[t],n="document"===r.type?""+(r.filename||r.documentId):r.path
|
|
5300
5429
|
l+=`### ${"document"===r.type?"DOC":"FILE"} ${n}\n\n`,r.error?(l+="- **Status:** \u274c Failed\n",l+="- **File Modified:** No\n",l+=`- **Error:** ${r.error}\n\n`):r.success?(l+="- **Status:** \u2705 Success\n",l+="- **File Modified:** Yes\n",l+=`- **Replacements:** ${r.successfulReplacements} successful\n`):(r.successfulReplacements>0?(l+="- **Status:** \u26a0\ufe0f Partial Success\n",l+="- **File Modified:** Yes (partial changes applied)\n"):(l+="- **Status:** \u274c Failed\n",l+="- **File Modified:** No\n"),l+=`- **Replacements:** ${r.successfulReplacements} successful, ${r.failedReplacements} failed\n`),r.externalEditWarning&&(l+=`\n${r.externalEditWarning}\n`)
|
|
5301
5430
|
const o=r.replacements.filter((e=>e.success))
|
|
@@ -5303,9 +5432,9 @@ if(o.length>0){l+="\n**Successful Replacements:**\n"
|
|
|
5303
5432
|
for(const e of o)l+=`- \u2705 \`${e.old.substring(0,40)}${e.old.length>40?"...":""}\` \u2192 \`${e.new.substring(0,40)}${e.new.length>40?"...":""}\``,e.matchesFound&&(l+=` (${e.matchesFound} occurrence${e.matchesFound>1?"s":""})`),e.lines&&e.lines.length>0&&3>=e.lines.length?l+=` at line${e.lines.length>1?"s":""} ${e.lines.join(", ")}`:e.lines&&e.lines.length>3&&(l+=` at ${e.lines.length} locations`),l+="\n"}const s=r.replacements.filter((e=>!e.success))
|
|
5304
5433
|
if(s.length>0){l+="\n**Failed Replacement Details:**\n"
|
|
5305
5434
|
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)))
|
|
5306
|
-
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}(
|
|
5307
|
-
return{content:[{type:"text",text:
|
|
5308
|
-
if(
|
|
5435
|
+
return d.length>0&&(l+=`\n**Document Changes:** ${d.length} modified document(s) synced back to tracking system.\n`),o.workspaceManager?.largeFileWarning&&(l+=o.workspaceManager.largeFileWarning,o.workspaceManager.largeFileWarning=""),l}(z,G,J,K,r,C)
|
|
5436
|
+
return{content:[{type:"text",text:X}],isError:0===J}}catch(e){const t=Date.now()-v
|
|
5437
|
+
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))
|
|
5309
5438
|
const l=c(t(1943)),d=(a(t(9896)),a(t(6928)),c(t(6982)),t(6183)),u=a(t(5967)),h=t(3626),g=t(9860),p=t(5003),f=t(7478),m=t(9949),y=t(9947),w=t(1318),k=t(8824)},9470(e,exports){"use strict"
|
|
5310
5439
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseLineSpec=function(e){if(!e||""===e.trim())throw Error("Line specification cannot be empty")
|
|
5311
5440
|
const t=e.trim()
|
|
@@ -5365,30 +5494,31 @@ o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(
|
|
|
5365
5494
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.UnauthorizedError=exports.McpProtocolError=exports.FileOperationError=exports.ServiceError=exports.DatabaseError=exports.AuthorizationError=exports.AuthenticationError=exports.ValidationError=exports.NotFoundError=exports.AppError=exports.ErrorUtils=exports.ERROR_TYPE_PROPERTIES=exports.isRetryableError=exports.errorToResponse=exports.isAppError=exports.createMcpProtocolError=exports.createFileOperationError=exports.createServiceError=exports.createDatabaseError=exports.createAuthorizationError=exports.createAuthenticationError=exports.createValidationError=exports.createNotFoundError=exports.createAppError=exports.createErrorResponse=void 0
|
|
5366
5495
|
const o=t(8625)
|
|
5367
5496
|
Object.defineProperty(exports,"createErrorResponse",{enumerable:!0,get(){return o.createErrorResponse}}),Object.defineProperty(exports,"createAppError",{enumerable:!0,get(){return o.createAppError}}),Object.defineProperty(exports,"createNotFoundError",{enumerable:!0,get(){return o.createNotFoundError}}),Object.defineProperty(exports,"createValidationError",{enumerable:!0,get(){return o.createValidationError}}),Object.defineProperty(exports,"createAuthenticationError",{enumerable:!0,get(){return o.createAuthenticationError}}),Object.defineProperty(exports,"createAuthorizationError",{enumerable:!0,get(){return o.createAuthorizationError}}),Object.defineProperty(exports,"createDatabaseError",{enumerable:!0,get(){return o.createDatabaseError}}),Object.defineProperty(exports,"createServiceError",{enumerable:!0,get(){return o.createServiceError}}),Object.defineProperty(exports,"createFileOperationError",{enumerable:!0,get(){return o.createFileOperationError}}),Object.defineProperty(exports,"createMcpProtocolError",{enumerable:!0,get(){return o.createMcpProtocolError}}),Object.defineProperty(exports,"isAppError",{enumerable:!0,get(){return o.isAppError}}),Object.defineProperty(exports,"errorToResponse",{enumerable:!0,get(){return o.errorToResponse}}),Object.defineProperty(exports,"isRetryableError",{enumerable:!0,get(){return o.isRetryableError}}),Object.defineProperty(exports,"ERROR_TYPE_PROPERTIES",{enumerable:!0,get(){return o.ERROR_TYPE_PROPERTIES}}),Object.defineProperty(exports,"ErrorUtils",{enumerable:!0,get(){return o.ErrorUtils}}),Object.defineProperty(exports,"AppError",{enumerable:!0,get(){}}),Object.defineProperty(exports,"NotFoundError",{enumerable:!0,get(){return o.NotFoundError}}),Object.defineProperty(exports,"ValidationError",{enumerable:!0,get(){return o.ValidationError}}),Object.defineProperty(exports,"AuthenticationError",{enumerable:!0,get(){return o.AuthenticationError}}),Object.defineProperty(exports,"AuthorizationError",{enumerable:!0,get(){return o.AuthorizationError}}),Object.defineProperty(exports,"DatabaseError",{enumerable:!0,get(){return o.DatabaseError}}),Object.defineProperty(exports,"ServiceError",{enumerable:!0,get(){return o.ServiceError}}),Object.defineProperty(exports,"FileOperationError",{enumerable:!0,get(){return o.FileOperationError}}),Object.defineProperty(exports,"McpProtocolError",{enumerable:!0,get(){return o.McpProtocolError}}),Object.defineProperty(exports,"UnauthorizedError",{enumerable:!0,get(){return o.UnauthorizedError}}),n(t(441),exports)},9863(e,exports,t){"use strict"
|
|
5368
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListTasks=async function(e,t,
|
|
5369
|
-
|
|
5370
|
-
const
|
|
5371
|
-
try{const{requestId:
|
|
5497
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleListTasks=async function(e,t,i,a,c){const l=a.child({tool:"list_tasks"})
|
|
5498
|
+
l.info("Listing tasks",{args:e})
|
|
5499
|
+
const d=c.startTimer("tool_handler_duration")
|
|
5500
|
+
try{const{requestId:a,filters:u}=function(e){try{const t=r.ListTasksSchema.parse(e),{requestId:n}=t,o=t.filters||{},s={}
|
|
5372
5501
|
if(o.status&&void 0!==o.status){const e=o.status+""
|
|
5373
5502
|
"undefined"!==e&&(s.status=e)}s.limit=o.limit??20,s.offset=o.offset??0,s.sortBy="created"===o.sortBy?"created_at":(o.sortBy,"updated_at")
|
|
5374
5503
|
const i=o.sortDirection??"desc"
|
|
5375
|
-
return s.sortDirection="asc"===i||"desc"===i?i:"desc",{requestId:n,filters:s}}catch(t){throw new n.ValidationError("Invalid input: "+(0,o.getErrorMessage)(t),{args:e,error:t})}}(e),
|
|
5376
|
-
if(!
|
|
5377
|
-
|
|
5378
|
-
const
|
|
5379
|
-
|
|
5380
|
-
const
|
|
5381
|
-
|
|
5382
|
-
let
|
|
5383
|
-
|
|
5384
|
-
const m
|
|
5385
|
-
if(
|
|
5386
|
-
return e=
|
|
5387
|
-
|
|
5388
|
-
|
|
5504
|
+
return s.sortDirection="asc"===i||"desc"===i?i:"desc",{requestId:n,filters:s}}catch(t){throw new n.ValidationError("Invalid input: "+(0,o.getErrorMessage)(t),{args:e,error:t})}}(e),h=t.projectId
|
|
5505
|
+
if(!h)throw new n.ValidationError("Project ID is required for listing tasks with the new API structure")
|
|
5506
|
+
c.incrementCounter("list_tasks_attempts",1,{hasRequestId:!!a,hasFilters:Object.keys(u).length>0}),i.setProjectId(h)
|
|
5507
|
+
const g=i.getTaskClient(),p=u
|
|
5508
|
+
a&&(p.requestId=a),l.info("Listing tasks with filters",{projectId:h,taskFilters:p})
|
|
5509
|
+
const f=await g.listTasks(p)
|
|
5510
|
+
l.info("Raw tasks response data",{responseData:JSON.stringify(f)}),l.info("Tasks response structure",{type:typeof f,isArray:Array.isArray(f),hasData:null!=f,properties:f?Object.keys(f):[],dataPreview:f?JSON.stringify(f).substring(0,200)+"...":"null"})
|
|
5511
|
+
let m=[]
|
|
5512
|
+
f&&"object"==typeof f?"success"in f&&"data"in f?Array.isArray(f.data)?(m=f.data,l.info("Extracted tasks from success/data wrapper",{count:m.length})):f.data&&"object"==typeof f.data&&(m=[f.data],l.info("Extracted single task from success/data wrapper")):"data"in f?Array.isArray(f.data)?(m=f.data,l.info("Extracted tasks from data wrapper",{count:m.length})):f.data&&"object"==typeof f.data&&(m=[f.data],l.info("Extracted single task from data wrapper")):Array.isArray(f)?(m=f,l.info("Tasks response is direct array",{count:m.length})):(m=[f],l.info("Tasks response is single object")):(l.warn("Unexpected response format, using empty array",{responseType:typeof f}),m=[])
|
|
5513
|
+
const y=m
|
|
5514
|
+
if(l.info(`Retrieved ${y.length} tasks`,{count:y.length,requestId:a,projectId:h}),0===y.length){let e=""
|
|
5515
|
+
return e=a?`No tasks found for request ${a}.`:`No tasks found for project ${h} with the specified filters.`,d({success:!0,taskCount:0}),{content:[{type:"text",text:e}]}}const w=y.map(((e,t)=>{const r=e.sequenceNumber??t+1
|
|
5516
|
+
return`**[${a?(0,s.formatTaskRef)(a,r):e.localId||e.id}]** ${e.title}\nStatus: ${e.status}\nCreated: ${new Date(e.createdAt).toLocaleString()}\nUpdated: ${new Date(e.updatedAt).toLocaleString()}`})).join("\n\n")
|
|
5517
|
+
let k
|
|
5518
|
+
return k=a?`Found ${y.length} task${1===y.length?"":"s"} for request ${a}:`:`Found ${y.length} task${1===y.length?"":"s"} for project ${h}:`,d({success:!0,taskCount:y.length}),{content:[{type:"text",text:`${k}\n\n${w}`}]}}catch(t){l.error("Failed to list tasks",{error:t instanceof Error?t.stack:t+"",args:e}),d({success:!1,error:t instanceof Error?t.name:"unknown"})
|
|
5389
5519
|
let r=(0,o.getErrorMessage)(t)
|
|
5390
5520
|
return t instanceof n.NotFoundError&&(r=`The request ID "${e.requestId}" was not found. Please provide a valid request ID.`),{content:[{type:"text",text:"Error: "+r}],isError:!0}}}
|
|
5391
|
-
const r=t(6183),n=t(9860),o=t(8824)},9884(e,exports,t){"use strict"
|
|
5521
|
+
const r=t(6183),n=t(9860),o=t(8824),s=t(4466)},9884(e,exports,t){"use strict"
|
|
5392
5522
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.DocumentClient=void 0
|
|
5393
5523
|
const r=t(7645),n=t(2161),o=t(9949),s=t(9860),i=t(8824)
|
|
5394
5524
|
class a extends r.ConnectionAwareClient{constructor(e,t,r,n,o,s,i,a){const c=t.child({component:"document-client"}),l=s||{isInOfflineMode(){return!1},isOffline(){return!1},setOfflineMode(){},async checkConnectivity(){return!0},getHealthCheckStats(){return{isOffline:!1,consecutiveFailures:0,currentBackoffMs:0,lastCheckTime:0}},cleanup(){}}
|