alchemylab 1.3.0 → 1.3.2
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/http-server.js +61 -56
- package/dist/index.js +384 -379
- package/dist/mcp-direct.js +149 -144
- package/package.json +2 -2
package/dist/mcp-direct.js
CHANGED
|
@@ -34,9 +34,9 @@ let o=(0,s.getErrorMessage)(r),i=""
|
|
|
34
34
|
return r instanceof n.NotFoundError?o=`The request ID "${e.requestId}" was not found. Please provide a valid request ID.`:r instanceof n.ValidationError&&(o.includes("Project cannot accept new tasks")||o.includes("Project is inactive due to tier limits")?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
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
|
-
if(
|
|
38
|
-
const i=new
|
|
39
|
-
return
|
|
37
|
+
if(j.has(s))return t.child({component:"mcp-server-registry"}).debug("Using existing server for path",{path:s}),j.get(s)
|
|
38
|
+
const i=new $(s,t,r,n,o)
|
|
39
|
+
return j.set(s,i),i}var n,o=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
40
40
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
41
41
|
o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[]
|
|
42
42
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
@@ -47,7 +47,7 @@ return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModu
|
|
|
47
47
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.McpServer=void 0,exports.resetStdoutWrite=function(){process.stdout.write=P},exports.getMcpServer=r,exports.createServer=function(e,t,n,o,s={}){return r(e,t,n,o,s)}
|
|
48
48
|
const c=t(3807),l=t(8909),d=a(t(6928)),u=a(t(9896)),h=a(t(1943)),g=t(9567),p=t(3444),m=t(7660),f=t(1253),y=t(5172),w=i(t(7478)),k=t(4139),I=new Set,b=t(9860),v=t(1472),C=t(3328),_=t(8955),E=t(3217),q=t(5278),S=t(446),T=t(9060),x=t(8824),R=(0,p.createLogger)({serviceName:"stdout-capture",console:!1,logToFile:!1}),P=process.stdout.write,M=process.argv.includes("--stdio")||"true"===process.env.MCP_DIRECT_MODE
|
|
49
49
|
!(0,p.isDebugToolsEnabled)()||M&&"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&&R.debug("Stdout output",{content:e.substring(0,100),length:e.length}),P.call(process.stdout,e)}catch(e){return R.error("Error in safeStdoutWrite",{error:e+""}),!0}})
|
|
50
|
-
class
|
|
50
|
+
class ${constructor(e,t,r,n,o={}){this.git=null,this.currentSSEConnection=null,this.stdioTransport=null,this.isInitializing=!1,this.isInitialized=!1,this.logger=t.child({component:"mcp-server"}),this.logger.info("Creating McpServer instance",{basePath:e,remoteServerUrl:n,hasExistingProjectId:!!o.existingProjectId}),this.basePath=e,this.alchemyPath=d.default.join(e,k.ALCHEMY_DIR_NAME),this.metrics=r,this.remoteServerUrl=n,this.existingProjectId=o.existingProjectId,this.gitBinary=(0,l.detectGitBinary)(),this.logger.info("Detected git binary",{gitBinary:this.gitBinary,version:(0,l.getGitVersion)()}),this.projectContext=new m.ProjectContext(e,t),this.tokenManager=new f.TokenManager(t,e,{remoteServerUrl:n}),this.lockOverrideManager=new S.LockOverrideManager(t),this.configManager=new T.ConfigManager(t),this.logger.debug("Server paths initialized",{basePath:this.basePath,alchemyPath:this.alchemyPath}),this.server=new g.Server({name:"alchemy",version:"1.0.0"},{capabilities:{tools:{search:{},create_request:{},complete_task:{},get_task_information:{},complete_request:{},revert_request:{},get_request_information:{},list_tasks:{},list_requests:{},switch_to_branch:{},read_files:{},create_directory:{},move_files:{},write_file:{},replace_strings:{},insert_lines:{},replace_lines:{},delete_files:{},document_operations:{},file_history:{},task_file_history:{},request_file_history:{},quick_write:{},quick_replace:{},quick_manage:{}}}}),(0,y.setGlobalClientInfo)("OpenCode","1.0.0"),this.metrics.incrementCounter("mcp_server_init_started",1),this.logger.info("Starting initialization for server instance"),this.initializationPromise=this.initialize()}get branchState(){if(!this.workspaceManager)return{currentBranch:null,activeRequestId:null,isOnMainBranch:!0}
|
|
51
51
|
const e=this.workspaceManager.getCurrentContext("__server__")
|
|
52
52
|
return{currentBranch:e.branchName,activeRequestId:e.requestId,isOnMainBranch:e.isMainBranch}}async updateBranchState(e,t){this.logger.debug("updateBranchState called - managed by WorkspaceManager",{branch:e,requestId:t})}async getCurrentBranchContext(){if(!this.workspaceManager)return{branch:null,requestId:null,isMain:!0}
|
|
53
53
|
const e=this.workspaceManager.getCurrentContext("__server__")
|
|
@@ -124,11 +124,11 @@ const r=await w.switchToBranch(this.git,n.branchName,this.logger,this.metrics)
|
|
|
124
124
|
r.success?this.logger.info("Successfully switched workspace to correct branch",{requestId:e,branchName:n.branchName}):this.logger.error("Failed to switch workspace to correct branch",{requestId:e,expectedBranch:n.branchName,error:r.message})}}catch(t){this.logger.error("Failed to verify workspace branch status",{requestId:e,workspacePath:n.basePath,error:t instanceof Error?t.message:t+""})}return this.logger.info("Switched to request context",{requestId:e,workspacePath:n.basePath,branchName:n.branchName}),{success:!0,message:"Switched to workspace for request "+e,worktreePath:n.basePath}}catch(t){const r=(0,x.getErrorMessage)(t)
|
|
125
125
|
return this.logger.error("Failed to switch to request context",{requestId:e,error:r}),{success:!1,message:"Failed to switch context: "+r}}}async getEffectiveBasePath(e){if(!this.workspaceManager||!e)return this.basePath
|
|
126
126
|
const t=await this.workspaceManager.getWorkspaceInfo(e)
|
|
127
|
-
return t?.path||this.basePath}}exports.McpServer
|
|
128
|
-
const
|
|
127
|
+
return t?.path||this.basePath}}exports.McpServer=$
|
|
128
|
+
const j=new Map},213(e,exports,t){"use strict"
|
|
129
129
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
130
130
|
const r=t(6183),n=t(3707)
|
|
131
|
-
exports.def={name:"quick_write",description:"
|
|
131
|
+
exports.def={name:"quick_write",description:"WHEN TO USE: trivial single-file edits only. For multi-file or feature work, spawn a coder via subagent_operations.\n\nCreate or update a file or document. Wraps the change in a request/task workflow that auto-completes.\n\nUse 'path' for filesystem files or 'documentId' for tracked documents.\nSet append:true to add content to existing content.\n\nRequires: title, description, path/documentId, content.",schema:r.QuickWriteSchema,annotations:{title:"Quick Write",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"write",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},233(e,exports,t){"use strict"
|
|
132
132
|
function r(e,t){const r=e.toLowerCase().indexOf(t.toLowerCase())
|
|
133
133
|
return-1===r?e:`${e.substring(0,r)}**${e.substring(r,r+t.length)}**${e.substring(r+t.length)}`}function n(e,t,r){const n=e.toLowerCase().indexOf(t)
|
|
134
134
|
if(-1===n)return e.substring(0,r)+"..."
|
|
@@ -575,9 +575,9 @@ else if(T){let e=T;(e.startsWith("*.")||e.startsWith("*"))&&(e=e.substring(1)),M
|
|
|
575
575
|
throw b.errors.push(t),(0,m.createValidationError)(t)}if(b.patternInfo={needle:n,regex:P.toString(),caseSensitive:q,fileExtension:T,normalizedExtension:M},!_)try{const e=Date.now(),t=await g.default.readdir(C,{withFileTypes:!0}),r=[],n=[]
|
|
576
576
|
for(const e of t)e.isDirectory()?r.push(e.name):e.isFile()&&n.push(e.name)
|
|
577
577
|
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)
|
|
578
|
-
b.errors.push(t),l.error(t)}const
|
|
579
|
-
l.info(`Searching for "${n}" in ${
|
|
580
|
-
const
|
|
578
|
+
b.errors.push(t),l.error(t)}const $=_?"file":"directory"
|
|
579
|
+
l.info(`Searching for "${n}" in ${$} ${C} (mode: ${x})`,{needle:n,searchTarget:$,path:C,options:{maxResults:E,caseSensitive:q,fileExtension:M,searchIn:x}}),I=Date.now(),b.phases.initializationTime=I-u
|
|
580
|
+
const j=Date.now()
|
|
581
581
|
let O=[],D=0,A=0
|
|
582
582
|
try{const e=await async function(e,t,n,o,s,i){const{maxResults:a,fileExtension:c,searchIn:l,isFile:d,contextLines:u}=n,p=[]
|
|
583
583
|
if(s.info("performLocalSearch started",{searchPath:e,pattern:t.toString(),options:n}),d)return await async function(e,t,r,n,o,s=0){const i=[],a=h.default.basename(e)
|
|
@@ -598,8 +598,8 @@ return m.errors.push(r),i.directoryStats.push(m),i.errors.push(r),s.error(r,{err
|
|
|
598
598
|
O=e.matches,D=e.totalFiles
|
|
599
599
|
const t=1e3
|
|
600
600
|
O.length>0&&O.length<=t?(O.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 ${O.length} matches by modification time (newest first)`)):O.length>t&&l.info(`Skipped sorting ${O.length} matches (exceeds hard cap of ${t} for performance)`),A=O.length,O.length>E&&(O=O.slice(0,E),l.info(`Limited results to ${E} (from ${A} total matches)`)),O.forEach((e=>{e.relativePath=function(e,t){const r=h.default.relative(e,t)
|
|
601
|
-
return r?r===h.default.basename(t)?r:r.startsWith("./")?r.substring(2):r:h.default.basename(t)}(C,e.file)})),l.info(`Local search completed: found ${A||O.length} total matches in ${D} files, returning ${O.length} results`),b.phases.searchTime=Date.now()
|
|
602
|
-
b.errors.push(t),l.error(t),b.phases.searchTime=Date.now()
|
|
601
|
+
return r?r===h.default.basename(t)?r:r.startsWith("./")?r.substring(2):r:h.default.basename(t)}(C,e.file)})),l.info(`Local search completed: found ${A||O.length} total matches in ${D} files, returning ${O.length} results`),b.phases.searchTime=Date.now()-j}catch(e){const t="Error during search: "+(0,k.getErrorMessage)(e)
|
|
602
|
+
b.errors.push(t),l.error(t),b.phases.searchTime=Date.now()-j}b.totalFiles=D,b.totalMatches=O.length,b.endTime=Date.now()
|
|
603
603
|
let F,N=""
|
|
604
604
|
try{if(t.workspaceManager){const e=t.workspaceManager.getCurrentContext(t.currentSessionId)
|
|
605
605
|
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})
|
|
@@ -693,54 +693,62 @@ t.success?this.logger.info("Successfully cleaned up worktree after non-conflict
|
|
|
693
693
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
694
694
|
const r=t(6183),n=t(5626)
|
|
695
695
|
exports.def={name:"document_operations",description:"Manage tracked documents linked to requests.\n\nOperations:\n\u2022 create - Create new document with content\n\u2022 search - Find documents by content or metadata\n\u2022 create-snapshot - Create a version snapshot with optional label and summary\n\u2022 get-history - View version snapshots and change history\n\u2022 get-version - Retrieve a specific version's content\n\u2022 restore-version - Restore document to a previous version\n\nDocuments support markdown with syntax highlighting, Mermaid diagrams, GFM tables, and entity links ([RECORD:trec######], [DOC:doc######], [REQUEST:req######], [TASK:tas######]). Use JOURNAL-{requestId}.md naming for explanation documents.",schema:r.DocumentOperationsSchema,annotations:{title:"Document Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleDocumentOperations)(e,t.context,t.apiClient,t.logger,t.metrics,t.mcpServer,t.cliOrigin)}}},1472(e,exports,t){"use strict"
|
|
696
|
-
function r(e){if("string"==typeof e)try{return r(JSON.parse(e))}catch{return e}return Array.isArray(e)?e.map((e=>r(e))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e}
|
|
696
|
+
function r(e){if("string"==typeof e)try{return r(JSON.parse(e))}catch{return e}return Array.isArray(e)?e.map((e=>r(e))):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map((([e,t])=>[e,r(t)]))):e}function n(e,t){const r=e.path.length?e.path.join("."):"<root>",n=function(e,t){let r=e
|
|
697
|
+
for(const e of t){if(null==r)return
|
|
698
|
+
r=r[e]}return r}(t,e.path)
|
|
699
|
+
if("too_big"===e.code&&"string"===e.type&&"string"==typeof n){const t=+e.maximum,o=n.length
|
|
700
|
+
return`${r}: string too long \u2014 received ${o} chars, max ${t} (trim ${o-t})`}if("too_small"===e.code&&"string"===e.type&&"string"==typeof n){const t=+e.minimum
|
|
701
|
+
return`${r}: string too short \u2014 received ${n.length} chars, min ${t}`}if("too_big"===e.code&&"array"===e.type&&Array.isArray(n)){const t=+e.maximum
|
|
702
|
+
return`${r}: array too long \u2014 received ${n.length} items, max ${t}`}if("too_small"===e.code&&"array"===e.type&&Array.isArray(n)){const t=+e.minimum
|
|
703
|
+
return`${r}: array too short \u2014 received ${n.length} items, min ${t}`}return"too_big"===e.code&&"number"===e.type&&"number"==typeof n?`${r}: number too large \u2014 received ${n}, max ${+e.maximum}`:"too_small"===e.code&&"number"===e.type&&"number"==typeof n?`${r}: number too small \u2014 received ${n}, min ${+e.minimum}`:`${r}: ${e.message}`}var o,s=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r)
|
|
697
704
|
var o=Object.getOwnPropertyDescriptor(t,r)
|
|
698
|
-
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]}),
|
|
705
|
+
o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||(o=function(e){return o=Object.getOwnPropertyNames||function(e){var t=[]
|
|
699
706
|
for(var r in e)({}).hasOwnProperty.call(e,r)&&(t[t.length]=r)
|
|
700
|
-
return t},
|
|
707
|
+
return t},o(e)},function(e){if(e&&e.__esModule)return e
|
|
701
708
|
var t={}
|
|
702
|
-
if(null!=e)for(var r=
|
|
703
|
-
return
|
|
704
|
-
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=void 0,exports.registerTools=function(e,
|
|
705
|
-
|
|
706
|
-
const
|
|
707
|
-
try{return await
|
|
708
|
-
|
|
709
|
+
if(null!=e)for(var r=o(e),n=0;n<r.length;n++)"default"!==r[n]&&s(t,e,r[n])
|
|
710
|
+
return i(t,e),t})
|
|
711
|
+
Object.defineProperty(exports,"__esModule",{value:!0}),exports.logSessionIdentity=void 0,exports.registerTools=function(e,o,s,i,a,p,w){const k=i.child({component:"tools"})
|
|
712
|
+
k.info("Registering tools...")
|
|
713
|
+
const I=!!p,b=async()=>{if(!I)return!0
|
|
714
|
+
try{return await p.hasValidToken()}catch(e){return k.error("Error checking authentication status",{error:(0,d.getErrorMessage)(e)}),!1}},v=async()=>{const e=(0,l.areTestsRequiredForCompletion)(),t=await b()
|
|
715
|
+
k.info(`Generating tools list with testsRequired=${e}, authenticated=${t}`)
|
|
709
716
|
const r={testsRequired:e,authenticated:t}
|
|
710
|
-
return(0,
|
|
711
|
-
let
|
|
712
|
-
|
|
713
|
-
let
|
|
714
|
-
e.setRequestHandler(
|
|
715
|
-
const
|
|
717
|
+
return(0,f.generateVisibleToolsList)(r)}
|
|
718
|
+
let C=v(),_=[]
|
|
719
|
+
C.then((e=>{_=e})).catch((e=>{k.error("Error generating initial tools list",{error:(0,d.getErrorMessage)(e)}),_=[]})),e.setRequestHandler(c.ListToolsRequestSchema,(async()=>{try{return _=await v(),{tools:_}}catch(e){return k.error("Error generating tools list",{error:(0,d.getErrorMessage)(e)}),{tools:[]}}}))
|
|
720
|
+
let E=!1
|
|
721
|
+
e.setRequestHandler(c.CallToolRequestSchema,(async e=>{let c
|
|
722
|
+
try{const{name:n,arguments:l={},_meta:p}=e.params;(0,m.logSessionIdentity)(n,"_meta-debug",{has_meta:!!p,sessionId:p?.sessionId||null,messageId:p?.messageId||null,paramKeys:Object.keys(e.params)}),k.info("Tool call received: "+n,{tool:n}),a.incrementCounter("tool_calls_total",1,{tool:n})
|
|
723
|
+
const y=a.startTimer("tool_execution_time")
|
|
716
724
|
Date.now()
|
|
717
|
-
let
|
|
718
|
-
const
|
|
719
|
-
if(Date.now()
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
if(
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
e&&o&&await n.workspaceManager.ensureReadonlyBranchIfNeeded(e,a,o,q)}catch(e){y.debug("Error during workspace check",{error:(0,l.getErrorMessage)(e)})}Date.now()}if(!C&&o){const e=u.sessionIdentity.getIdentity(),t=process.env.ALCHEMY_INITIAL_BRANCH
|
|
725
|
+
let v=Date.now()
|
|
726
|
+
if(c=r(l),Date.now(),v=Date.now(),I){const e=await b()
|
|
727
|
+
if(Date.now(),!e)return k.warn("Unauthenticated tool call attempt",{tool:n}),{content:[{type:"text",text:"Authentication required. Please run 'alchemylab setup' to authenticate and configure your project."}],isError:!0}}const C=(0,f.getToolByName)(n)
|
|
728
|
+
let _
|
|
729
|
+
if(v=Date.now(),s?(s.setOptions({createRecords:C?.createsRecords??!1}),k.info(`Setting record creation for tool ${n}: ${C?.createsRecords??!1}`)):k.debug(`No API client available for tool ${n} (minimal mode)`),Date.now(),Date.now(),v=Date.now(),p?.sessionId){const e=p.sessionId,t=p.messageId,r=h.sessionIdentity.getIdentity()
|
|
730
|
+
if(r)r.sessionId!==e&&((0,m.logSessionIdentity)(n,"_meta-session-switch",{prevSessionId:r.sessionId,prevAgentType:r.agentType,newSessionId:e}),h.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:r.serverUrl}),o?.workspaceManager?.resetCurrentContext?.(e))
|
|
731
|
+
else{const t=await(0,u.getServerUrl)(o,k)
|
|
732
|
+
h.sessionIdentity.setIdentity({providerId:"opencode",sessionId:e,serverUrl:t||""})}_={providerId:"opencode",sessionId:e,messageId:t,createdAt:(new Date).toISOString()},(0,m.logSessionIdentity)(n,"_meta",{sessionId:e,messageId:t})}else k.warn("No _meta.sessionId on tool call \u2014 session identity unavailable",{tool:n})
|
|
733
|
+
h.sessionIdentity.setCurrentCallOrigin(_)
|
|
734
|
+
const q=_?.sessionId||p?.sessionId
|
|
735
|
+
if(o?.workspaceManager){v=Date.now()
|
|
736
|
+
try{const e=await(0,u.getServerUrl)(o,k)
|
|
737
|
+
e&&s&&await o.workspaceManager.ensureReadonlyBranchIfNeeded(e,n,s,q)}catch(e){k.debug("Error during workspace check",{error:(0,d.getErrorMessage)(e)})}Date.now()}if(!E&&s){const e=h.sessionIdentity.getIdentity(),t=process.env.ALCHEMY_INITIAL_BRANCH
|
|
731
738
|
if(e?.sessionId&&t){const r=t.match(/^requests\/(.+)$/),n="1"===process.env.ALCHEMY_ALLOW_PARALLEL
|
|
732
739
|
if(r&&!n){const t=r[1]
|
|
733
|
-
|
|
734
|
-
try{const{sessionTag:r}=(0,
|
|
735
|
-
await Promise.all([i,a])}catch(e){
|
|
740
|
+
E=!0
|
|
741
|
+
try{const{sessionTag:r}=(0,g.getGlobalClientInfo)(),n=s.getSessionTagMappingClient(),o=s.getRequestClient(),i=n?n.getMappingByOpencodeSessionId(e.sessionId).then((t=>{t?((0,g.setSessionTag)(t.sessionTag),k.info("Recovered session tag from mapping",{opencodeSessionId:e.sessionId,sessionTag:t.sessionTag})):(n.createOrUpdateMapping(r,e.sessionId).catch((()=>{})),k.info("Registered session tag mapping",{opencodeSessionId:e.sessionId,sessionTag:r}))}),(e=>k.debug("Mapping lookup failed",{error:(0,d.getErrorMessage)(e)}))):Promise.resolve(),a=o.lockRequest?o.lockRequest(t,r).then((e=>{e.locked?k.info("Acquired request lock",{requestId:t,sessionTag:r}):k.warn("Failed to acquire request lock",{requestId:t,sessionTag:r})}),(e=>k.warn("Lock acquisition failed",{error:(0,d.getErrorMessage)(e)}))):Promise.resolve()
|
|
742
|
+
await Promise.all([i,a])}catch(e){k.warn("Error in session tag mapping / lock acquisition",{error:(0,d.getErrorMessage)(e)})}}}}o&&(o.currentSessionId=q||"__unknown__")
|
|
736
743
|
const S=`${Date.now()}-${Math.random().toString(36).slice(2,10)}`,T=e=>{const{getActionServerBaseUrl:r}=t(9414)
|
|
737
744
|
fetch(r()+"/api/mcp/tool-call-event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,callId:S}),signal:AbortSignal.timeout(500)}).catch((()=>{}))}
|
|
738
745
|
let x
|
|
739
746
|
T("start")
|
|
740
|
-
try{if(
|
|
741
|
-
x=await
|
|
747
|
+
try{if(C){const e={context:o,apiClient:s,logger:i,metrics:a,mcpServer:w,cliOrigin:_}
|
|
748
|
+
x=await C.handler(c,e)}else k.info(`Tool ${n} not found, returning negative response`),x={content:[{type:"text",text:`The tool '${n}' does not exist.`}]}}finally{T("end")}return Date.now(),Date.now(),y({tool:n,success:!0}),x}catch(t){k.error("Error executing tool:",{error:t instanceof Error?t.stack:t+"",tool:e.params.name}),a.incrementCounter("tool_errors_total",1,{tool:e.params.name,error:t instanceof Error?t.name:"unknown"})
|
|
742
749
|
let r="Unknown error"
|
|
743
|
-
if(t instanceof
|
|
750
|
+
if(t instanceof y.ZodError)r=function(e,t){return 1===e.issues.length?n(e.issues[0],t):e.issues.map((e=>n(e,t))).join("; ")}(t,c)
|
|
751
|
+
else if(t instanceof Error)r=t.message
|
|
744
752
|
else if("string"==typeof t)r=t
|
|
745
753
|
else if(t&&"object"==typeof t){const e=t
|
|
746
754
|
if(e.message)r=e.message
|
|
@@ -751,15 +759,14 @@ else if(e.body&&"string"==typeof e.body)try{const t=JSON.parse(e.body)
|
|
|
751
759
|
r=t.error&&t.error.message?t.error.message:t.message?t.message:e.body.substring(0,200)}catch{r=e.body.substring(0,200)}else{const t=Object.keys(e).filter((t=>"string"==typeof e[t]&&e[t].length>0))
|
|
752
760
|
if(t.length>0){const n=t[0]
|
|
753
761
|
r=`${n}: ${e[n]}`}else r="Unknown error (no readable properties)"}}else r=t+""
|
|
754
|
-
return{content:[{type:"text",text:"Error: "+r}],isError:!0}}})),
|
|
755
|
-
const
|
|
756
|
-
|
|
757
|
-
var
|
|
758
|
-
Object.defineProperty(exports,"logSessionIdentity",{enumerable:!0,get(){return
|
|
759
|
-
const
|
|
762
|
+
return{content:[{type:"text",text:"Error: "+r}],isError:!0}}})),k.info("Tools registration complete")}
|
|
763
|
+
const c=t(9150),l=t(2478),d=t(8824),u=t(7617),h=t(6688),g=t(5172)
|
|
764
|
+
a(t(9896)),a(t(6928))
|
|
765
|
+
var p=t(7280)
|
|
766
|
+
Object.defineProperty(exports,"logSessionIdentity",{enumerable:!0,get(){return p.logSessionIdentity}})
|
|
767
|
+
const m=t(7280)
|
|
760
768
|
t(2462)
|
|
761
|
-
const
|
|
762
|
-
i(t(857))},1483(e,exports,t){"use strict"
|
|
769
|
+
const f=t(2245),y=(a(t(857)),t(1569))},1483(e,exports,t){"use strict"
|
|
763
770
|
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")
|
|
764
771
|
try{let i
|
|
765
772
|
try{i=r.SearchDocumentsSchema.parse(e)}catch(t){if(t instanceof n.ZodError){const r="Invalid arguments: "+t.errors.map((e=>e.message)).join(", ")
|
|
@@ -853,7 +860,7 @@ e&&t.projectId&&await e.createToolRecord({requestId:s,projectId:t.projectId,type
|
|
|
853
860
|
const r=t(9860),n=t(8824)},1540(e,exports,t){"use strict"
|
|
854
861
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
855
862
|
const r=t(6183),n=t(1725),o=t(8955)
|
|
856
|
-
exports.def={name:"subagent_operations",description:"
|
|
863
|
+
exports.def={name:"subagent_operations",description:"WHEN TO USE spawn (agent: coder): any change touching 2+ files, feature work, bug fixes, or anything needing acceptance-criteria verification.\n\nManage background subagents that work independently.\n\nOperations:\n\u2022 spawn - Create a new detached subagent to work in the background. Include a short 'description' for display in the UI.\n\u2022 continue - Send new instructions/feedback to an existing subagent session\n\u2022 check-status - Check if a subagent is idle or busy\n\u2022 abort - Stop a running subagent\n\u2022 read-messages - Fetch the latest messages from a subagent session\n\nThe spawned subagent runs as a separate OpenCode process.\n\nAvailable agents: "+(0,o.formatAgentsForDescription)(),schema:r.SubagentOperationsSchema,annotations:{title:"Subagent Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSubagentOperations)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},1569(module){"use strict"
|
|
857
864
|
module.exports=require("zod")},1572(e,exports,t){"use strict"
|
|
858
865
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleCreateDocument=async function(e,t,s,i,a,c,l){const d=i.child({tool:"create_document"}),u=a.startTimer("tool_execution_time")
|
|
859
866
|
try{let i
|
|
@@ -1604,12 +1611,12 @@ const T=await d.validateTaskId(E,S[0].source,n,y,m,v.metricsPrefix),x=T?.request
|
|
|
1604
1611
|
P.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:P.newTaskStatus,operationCount:h.length}),P.requestPromoted&&y.info(`Auto-promoted request ${x} to in_progress for file operations`,{requestId:x,previousStatus:R.request?.status,newStatus:P.newRequestStatus,triggeringTaskId:E})
|
|
1605
1612
|
const M=await d.ensureCorrectWorkspaceContext({taskPromoted:P.taskPromoted,requestId:x,context:r,operation:"move-files",logger:y,metrics:m,metricsPrefix:v.metricsPrefix})
|
|
1606
1613
|
if(!M.success){if(M.isLockConflict)return{content:[{type:"text",text:"\u274c "+M.error}],isError:!0}
|
|
1607
|
-
throw Error(M.error)}let
|
|
1614
|
+
throw Error(M.error)}let $={hadUserMods:!1,userModsCommitHash:void 0}
|
|
1608
1615
|
if(r.git)try{y.debug("[MOVE-FILES] Checking for user changes before move operations")
|
|
1609
1616
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"move-files",{requestId:x,taskId:E,workspaceManager:r.workspaceManager},y,m)
|
|
1610
|
-
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})
|
|
1611
|
-
const{toolRecordId
|
|
1612
|
-
k
|
|
1617
|
+
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}),$={hadUserMods:!0,userModsCommitHash:e.commitHash})}catch(e){y.debug("[MOVE-FILES] Pre-tool commit failed, continuing with move operations",{error:e instanceof Error?e.message:e+""}),y.warn("Pre-tool user changes commit failed, continuing with move operation",{taskId:E,moveOperationsCount:S.length,error:e instanceof Error?e.message:e+""})}y.debug("[MOVE-FILES] Proceeding with move operations",{operationCount:S.length}),b=d.FileOperationPhase.RECORD_CREATION,m.incrementCounter("move_files_phase",1,{phase:b})
|
|
1618
|
+
const{toolRecordId:j,localToolRecordId:O}=await d.createFileOperationRecords(E,x,r.projectId,v.recordType,S[0].source,{operationCount:h.length,operations:S.map((e=>({source:e.source,destination:e.destination}))),userComment:C,hadUserMods:$.hadUserMods,userModsCommitHash:$.userModsCommitHash},n,o,y,m,v.metricsPrefix,f)
|
|
1619
|
+
k=j,I=j,b=v.fileOperationPhase,m.incrementCounter("move_files_phase",1,{phase:b})
|
|
1613
1620
|
const D=[]
|
|
1614
1621
|
let A=0
|
|
1615
1622
|
for(const e of S){const t={operation:{source:e.source,destination:e.destination},success:!1}
|
|
@@ -1621,9 +1628,9 @@ m.recordValue("move_files_time",F),m.incrementCounter("move_files_operations_tot
|
|
|
1621
1628
|
let N=null
|
|
1622
1629
|
if(A>0){b=d.FileOperationPhase.GIT_COMMIT,m.incrementCounter("move_files_phase",1,{phase:b})
|
|
1623
1630
|
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}`
|
|
1624
|
-
N=await d.commitToGit(E,S[0].destination
|
|
1631
|
+
N=await d.commitToGit(E,S[0].destination,j,O,t,r,y,m,v.metricsPrefix)}b=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,m.incrementCounter("move_files_phase",1,{phase:b})
|
|
1625
1632
|
const L=D.filter((e=>e.success)),z=D.filter((e=>!e.success))
|
|
1626
|
-
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
|
|
1633
|
+
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:$.hadUserMods,userModsCommitHash:$.userModsCommitHash},A===h.length?`Successfully moved all ${h.length} items`:`Moved ${A}/${h.length} items successfully`,n,o,y,m,v.metricsPrefix)
|
|
1627
1634
|
const B=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
1628
1635
|
let H=""
|
|
1629
1636
|
if(A===h.length)H=`Successfully moved all ${h.length} ${1===h.length?"item":"items"}`
|
|
@@ -1638,9 +1645,9 @@ const a=i(t(1943)),c=i(t(6928)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(1569),g=t(7
|
|
|
1638
1645
|
module.exports=require("@modelcontextprotocol/sdk/server/sse.js")},2425(e,exports,t){"use strict"
|
|
1639
1646
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
1640
1647
|
const r=t(6183),n=t(3707)
|
|
1641
|
-
exports.def={name:"quick_manage",description:"
|
|
1648
|
+
exports.def={name:"quick_manage",description:"WHEN TO USE: trivial single-file edits only. For multi-file or feature work, spawn a coder via subagent_operations.\n\nMove, delete, or create directories. Wraps the change in a request/task workflow that auto-completes.\n\nProvide an array of operations, each with operationType and corresponding data:\n\u2022 create-directory: { createDirectory: { path } }\n\u2022 move-files: { moveFiles: { moves: [{ source, destination }] } }\n\u2022 delete-files: { deleteFiles: { targets: [{ path }] } }\n\nFor read-only operations like get-file-info, use manage_files instead.\n\nRequires: title, description, operations.",schema:r.QuickManageSchema,annotations:{title:"Quick Manage",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"manage",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},2462(e,exports,t){"use strict"
|
|
1642
1649
|
Object.defineProperty(exports,"__esModule",{value:!0})
|
|
1643
|
-
const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),m=t(260),f=t(2283),y=t(4165),w=t(7834),k=t(9373),I=t(6111),b=t(700),v=t(2783),C=t(2601),_=t(1722),E=t(7257),q=t(9230),S=t(6064),T=t(5216),x=t(6473),R=t(4921),P=t(8850),M=t(3556)
|
|
1650
|
+
const r=t(2245),n=t(9080),o=t(5692),s=t(9030),i=t(2903),a=t(4607),c=t(9499),l=t(6770),d=t(8045),u=t(9697),h=t(9196),g=t(5459),p=t(4805),m=t(260),f=t(2283),y=t(4165),w=t(7834),k=t(9373),I=t(6111),b=t(700),v=t(2783),C=t(2601),_=t(1722),E=t(7257),q=t(9230),S=t(6064),T=t(5216),x=t(6473),R=t(4921),P=t(8850),M=t(3556),$=t(1391),j=t(6315),O=t(7713),D=t(6252),A=t(213),F=t(7250),N=t(2425),L=t(1540),z=t(5767),B=t(4973),H=t(509),U=t(7613),G=t(8456),W=t(3322),V=t(5247),J=t(8849),K=t(542);(0,r.registerTool)(n.def),(0,r.registerTool)(o.def),(0,r.registerTool)(s.def),(0,r.registerTool)(i.def),(0,r.registerTool)(a.def),(0,r.registerTool)(c.def),(0,r.registerTool)(l.def),(0,r.registerTool)(d.def),(0,r.registerTool)(u.def),(0,r.registerTool)(h.def),(0,r.registerTool)(g.def),(0,r.registerTool)(p.def),(0,r.registerTool)(m.def),(0,r.registerTool)(f.def),(0,r.registerTool)(y.def),(0,r.registerTool)(w.def),(0,r.registerTool)(k.def),(0,r.registerTool)(I.def),(0,r.registerTool)(b.def),(0,r.registerTool)(v.def),(0,r.registerTool)(S.def),(0,r.registerTool)(C.def),(0,r.registerTool)(_.def),(0,r.registerTool)(E.def),(0,r.registerTool)(q.def),(0,r.registerTool)(T.def),(0,r.registerTool)(x.def),(0,r.registerTool)(R.def),(0,r.registerTool)(P.def),(0,r.registerTool)(M.def),(0,r.registerTool)($.def),(0,r.registerTool)(j.def),(0,r.registerTool)(O.def),(0,r.registerTool)(D.def),(0,r.registerTool)(A.def),(0,r.registerTool)(F.def),(0,r.registerTool)(N.def),(0,r.registerTool)(L.def),(0,r.registerTool)(z.def),(0,r.registerTool)(B.def),(0,r.registerTool)(H.def),(0,r.registerTool)(U.def),(0,r.registerTool)(G.def),(0,r.registerTools)(W.metaDefs),(0,r.registerTools)(V.testingDefs),(0,r.registerTools)(J.checkingDefs),(0,r.registerTools)(K.debugDefs),(0,t(2245).freezeRegistry)()},2478(e,exports){"use strict"
|
|
1644
1651
|
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"
|
|
1645
1652
|
async function r(e,t,r){if(C.has(r)&&_>=t){if(0===t)return 0
|
|
1646
1653
|
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]"
|
|
@@ -2095,18 +2102,18 @@ for(const e of R)M.push({type:"document",documentId:e.documentId,replacements:e.
|
|
|
2095
2102
|
if(M.length>0&&r.apiClient){const e=M.map((e=>e.documentId))
|
|
2096
2103
|
try{await(0,m.ensureDocumentsNotLocked)(e,r.apiClient,w,c,"replace-strings-documents")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2097
2104
|
throw e}}v=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_strings_phase",1,{phase:v})
|
|
2098
|
-
const
|
|
2105
|
+
const $=P.length>0?P[0].path:"document-operation",j=await u.validateTaskId(T,$,o,w,c,C.metricsPrefix),O=j?.requestId
|
|
2099
2106
|
let D=null
|
|
2100
2107
|
P.length>0&&O&&(D=await u.validateWorkItemStates(T,P[0].path,o,i,r,w,c,C.metricsPrefix))
|
|
2101
2108
|
let A={taskPromoted:!1,requestPromoted:!1}
|
|
2102
|
-
P.length>0&&O&&D&&(A=await u.autoPromoteTaskStatus(T
|
|
2109
|
+
P.length>0&&O&&D&&(A=await u.autoPromoteTaskStatus(T,j.status,O,D.request?.status,P[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:O,previousStatus:j.status,newStatus:A.newTaskStatus,triggeringOperation:"replace-strings"}))
|
|
2103
2110
|
const F=await u.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:O,context:r,operation:"replace-strings",logger:w,metrics:c,metricsPrefix:C.metricsPrefix})
|
|
2104
2111
|
if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
|
|
2105
2112
|
throw Error(F.error)}if(P.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:P.length,workspaceBasePath:r.workspaceManager?.getCurrentContext(r.currentSessionId).basePath})
|
|
2106
2113
|
for(let e=0;e<P.length;e++){const t=P[e],n=x[e],{normalizedPath:o,fullPath:s}=u.validateAndNormalizePath(n.path,r)
|
|
2107
2114
|
P[e]={...t,path:o,fullPath:s}}}if(M.length>0&&O)try{await(0,g.validateRequestStatusForDocumentOperation)(O,i,w,c,"replace-strings-document")}catch(e){if(e instanceof h.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
2108
2115
|
throw e}v=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_strings_phase",1,{phase:v})
|
|
2109
|
-
const N=[...P.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:L}=await u.createFileOperationRecords(T,O,r.projectId,C.recordType
|
|
2116
|
+
const N=[...P.map((e=>({type:"file",path:e.path,replacements:e.replacements,mode:e.mode}))),...M.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements,mode:e.mode})))],{toolRecordId:L}=await u.createFileOperationRecords(T,O,r.projectId,C.recordType,$,{operationCount:E.length,fileOperations:P.length,documentOperations:M.length,operations:N,userComment:q},o,s,w,c,C.metricsPrefix,y)
|
|
2110
2117
|
if(I=L,b=L,v=C.fileOperationPhase,c.incrementCounter("replace_strings_phase",1,{phase:v}),P.length>0&&r.git)try{w.debug("[REPLACE-STRINGS] Checking for user changes before replace operations")
|
|
2111
2118
|
const e=await(0,p.commitUserChangesBeforeToolOperation)(r.git,"replace-strings",{requestId:O,taskId:T,workspaceManager:r.workspaceManager},w,c)
|
|
2112
2119
|
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:P.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:P.length,error:e instanceof Error?e.message:e+""})}w.debug("[REPLACE-STRINGS] Proceeding with file operations",{fileCount:P.length})
|
|
@@ -2363,9 +2370,9 @@ const R=x?`Quick change completed with partial success: ${b}. Some replacements
|
|
|
2363
2370
|
let M=!1
|
|
2364
2371
|
try{const e=await(0,a.handleCompleteRequest)({requestId:S,summary:R,acceptanceEvidence:[{evidence:P}],testVerification:void 0},d,u,h,g,p)
|
|
2365
2372
|
if(e.isError)m.error("Request completion failed, attempting direct completion",{requestId:S,error:e.content[0].text})
|
|
2366
|
-
else{try{await y.updateRequest(S,{status:"completed",completionSummary:R}),m.info("Request finalized to completed",{requestId:S})}catch(e){m.warn("Failed to finalize request to completed, may be stuck at ready_for_merge",{requestId:S,error:(0,l.getErrorMessage)(e)})}M=!0,m.info("Request completed successfully",{requestId:S})}}catch(e){m.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!M)try{m.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:R}),M=!0,m.info("Request completed successfully via direct API call",{requestId:S})}catch(e){return m.error("Direct request completion also failed",{requestId:S,error:e instanceof Error?e.message:e+""}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but request completion failed.\n\n**Request:** ${S}\n**Status:** Still in 'in_progress' - please complete manually\n\nThe file operation was successful, but we couldn't automatically complete the request. Please use the complete-request tool manually.`}],isError:!0}}const
|
|
2367
|
-
let
|
|
2368
|
-
return m.info("Quick fix completed",{requestId:S,duration
|
|
2373
|
+
else{try{await y.updateRequest(S,{status:"completed",completionSummary:R}),m.info("Request finalized to completed",{requestId:S})}catch(e){m.warn("Failed to finalize request to completed, may be stuck at ready_for_merge",{requestId:S,error:(0,l.getErrorMessage)(e)})}M=!0,m.info("Request completed successfully",{requestId:S})}}catch(e){m.error("Request completion threw exception, attempting direct completion",{requestId:S,error:e instanceof Error?e.message:e+""})}if(!M)try{m.info("Attempting direct request completion via API",{requestId:S}),await y.updateRequest(S,{status:"completed",completionSummary:R}),M=!0,m.info("Request completed successfully via direct API call",{requestId:S})}catch(e){return m.error("Direct request completion also failed",{requestId:S,error:e instanceof Error?e.message:e+""}),{content:[{type:"text",text:`\u26a0\ufe0f Quick change operation succeeded but request completion failed.\n\n**Request:** ${S}\n**Status:** Still in 'in_progress' - please complete manually\n\nThe file operation was successful, but we couldn't automatically complete the request. Please use the complete-request tool manually.`}],isError:!0}}const $=Date.now()-f
|
|
2374
|
+
let j
|
|
2375
|
+
return m.info("Quick fix completed",{requestId:S,duration:$,hasPartialFailure:x}),j=x?`\u26a0\ufe0f Quick change completed with partial success\n\n**Request:** ${S}\n**Title:** ${b}\n**Operation:** ${t}\n**Duration:** ${$}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:** ${$}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&&(j+="\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:j}]}}catch(e){if(m.error("Quick change workflow failed after request creation, cleaning up",{requestId:S,error:(0,l.getErrorMessage)(e)}),T)try{await w.updateTaskStatus(T,"canceled"),m.info("Canceled task after workflow failure",{taskId:T})}catch(e){m.warn("Failed to cancel task during cleanup",{taskId:T,error:e instanceof Error?e.message:e+""})}try{await y.updateRequest(S,{status:"canceled"}),m.info("Canceled request after workflow failure",{requestId:S}),d.workspaceManager&&(await d.workspaceManager.cancelRequest(S),m.info("Cleaned up branch/worktree after workflow failure",{requestId:S}))}catch(e){m.warn("Failed to cancel request during cleanup",{requestId:S,error:e instanceof Error?e.message:e+""})}throw e}}catch(e){const t=Date.now()-f
|
|
2369
2376
|
return m.error("Quick change failed",{error:(0,l.getErrorMessage)(e),duration:t}),e instanceof r.ValidationError?{content:[{type:"text",text:"\u274c "+e.message}],isError:!0}:{content:[{type:"text",text:"\u274c Quick change failed: "+(0,l.getErrorMessage)(e)}],isError:!0}}}
|
|
2370
2377
|
const r=t(9860),n=t(4079),o=t(9442),s=t(7684),i=t(355),a=t(5715),c=t(7478),l=t(8824)},3807(module){"use strict"
|
|
2371
2378
|
module.exports=require("simple-git")},3895(e,exports,t){"use strict"
|
|
@@ -2434,43 +2441,43 @@ return o(t,e),t}),i=this&&this.__importDefault||function(e){return e&&e.__esModu
|
|
|
2434
2441
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleWriteFile=async function(e,r,n,o,s,i,f,y,w){const k=f.child({tool:"write_file"}),I=y.startTimer("tool_execution_time"),b=Date.now()
|
|
2435
2442
|
let v,C,_=d.FileOperationPhase.VALIDATION
|
|
2436
2443
|
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"}
|
|
2437
|
-
try{const n=d.validateArgs(e,l.WriteFileSchema),{path:m,documentId:q,content:S,format:T,append:x,comment:R}=n,{resolveActiveTaskId:P}=await Promise.resolve().then(t.bind(t,3451)),M=e.taskId||await P(r,o,f)||"untracked",j=!!
|
|
2438
|
-
k.info("Writing content to "+(
|
|
2444
|
+
try{const n=d.validateArgs(e,l.WriteFileSchema),{path:m,documentId:q,content:S,format:T,append:x,comment:R}=n,{resolveActiveTaskId:P}=await Promise.resolve().then(t.bind(t,3451)),M=e.taskId||await P(r,o,f)||"untracked",$=!!q,j=!!m
|
|
2445
|
+
k.info("Writing content to "+($?"document":"file"),{taskId:M,filePath:j?m:void 0,documentId:$?q:void 0,contentLength:"string"==typeof S?S.length:JSON.stringify(S).length,format:T,append:x,comment:R})
|
|
2439
2446
|
let O,D,A,F="",N=!1,L=!1
|
|
2440
|
-
const z
|
|
2441
|
-
if(
|
|
2447
|
+
const z=j?m:void 0
|
|
2448
|
+
if($){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}
|
|
2442
2449
|
throw e}if(!r.documentFileManager)throw Error("Document file manager not available")
|
|
2443
2450
|
F=await r.documentFileManager.getDocumentAsFile(q)
|
|
2444
2451
|
const e=r.documentFileManager.getCachedDocumentInfo(q)
|
|
2445
2452
|
A=e?.filename,L=!0,N=!1}_=d.FileOperationPhase.TASK_VALIDATION,y.incrementCounter("write_file_phase",1,{phase:_})
|
|
2446
|
-
const B
|
|
2453
|
+
const B=j?z:"document:"+q,H=await d.validateTaskId(M,B,o,k,y,E.metricsPrefix),U=H?.requestId
|
|
2447
2454
|
let G=null
|
|
2448
|
-
|
|
2455
|
+
j&&U&&(G=await d.validateWorkItemStates(M,B,o,i,r,k,y,E.metricsPrefix))
|
|
2449
2456
|
let W={taskPromoted:!1,requestPromoted:!1}
|
|
2450
|
-
|
|
2451
|
-
const V=await d.ensureCorrectWorkspaceContext({taskPromoted:W.taskPromoted,requestId:U,context:r,operation:"write_file",logger:k,metrics:y,metricsPrefix:E.metricsPrefix,requireRequestContext
|
|
2457
|
+
j&&U&&G&&(W=await d.autoPromoteTaskStatus(M,H.status,U,G.request?.status,B,o,i,k,y,E.metricsPrefix),W.taskPromoted&&k.info("Auto-promoted task to in_progress for file operation",{taskId:M,requestId:U,previousStatus:H.status,newStatus:W.newTaskStatus,triggeringOperation:"write_file"}))
|
|
2458
|
+
const V=await d.ensureCorrectWorkspaceContext({taskPromoted:W.taskPromoted,requestId:U,context:r,operation:"write_file",logger:k,metrics:y,metricsPrefix:E.metricsPrefix,requireRequestContext:j})
|
|
2452
2459
|
if(!V.success){if(V.isLockConflict)return{content:[{type:"text",text:"\u274c "+V.error}],isError:!0}
|
|
2453
|
-
throw Error(V.error)}if(V.switched&&k.info("Workspace context successfully established",{requestId:U,branchName:V.branchName,operation:"write_file"})
|
|
2460
|
+
throw Error(V.error)}if(V.switched&&k.info("Workspace context successfully established",{requestId:U,branchName:V.branchName,operation:"write_file"}),j&&z){const e=d.validateAndNormalizePath(z,r)
|
|
2454
2461
|
O=e.normalizedPath,D=e.fullPath,F=D
|
|
2455
|
-
try{await c.default.access(D),L=!0}catch{L=!1,N=!0}k.debug("Path validated with correct workspace context",{rawPath:z,normalizedPath:O,fullPath:D,workspaceBasePath:r.workspaceManager?.getCurrentContext(r.currentSessionId).basePath})}if(
|
|
2462
|
+
try{await c.default.access(D),L=!0}catch{L=!1,N=!0}k.debug("Path validated with correct workspace context",{rawPath:z,normalizedPath:O,fullPath:D,workspaceBasePath:r.workspaceManager?.getCurrentContext(r.currentSessionId).basePath})}if($&&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}
|
|
2456
2463
|
throw e}_=d.FileOperationPhase.RECORD_CREATION,y.incrementCounter("write_file_phase",1,{phase:_})
|
|
2457
|
-
const{toolRecordId:J}=await d.createFileOperationRecords(M,U,r.projectId,E.recordType,B,{operationType
|
|
2464
|
+
const{toolRecordId:J}=await d.createFileOperationRecords(M,U,r.projectId,E.recordType,B,{operationType:$?"document":"file",documentId:$?q:void 0,documentFilename:A,filePath:j?O:void 0,contentLength:"string"==typeof S?S.length:JSON.stringify(S).length,format:T||"text",append:x||!1,wasFileCreated:!L,userComment:R},o,s,k,y,E.metricsPrefix,w)
|
|
2458
2465
|
let K
|
|
2459
2466
|
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)
|
|
2460
2467
|
else K="string"==typeof S?S:JSON.stringify(S,null,2)
|
|
2461
2468
|
let Y=K
|
|
2462
|
-
if(
|
|
2469
|
+
if(j&&r.git)try{k.debug("[WRITE-FILE] Checking for user changes before write operation")
|
|
2463
2470
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(r.git,"write_file",{requestId:r.workspaceManager?.getCurrentContext(r.currentSessionId)?.requestId,taskId:M},k,y)
|
|
2464
2471
|
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:M,path:O,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:M,path:O,error:e instanceof Error?e.message:e+""})}if(!F)throw Error("Target path not properly initialized")
|
|
2465
2472
|
if(k.debug("[WRITE-FILE] Proceeding with file write operation",{targetPath:F}),x&&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)
|
|
2466
|
-
if(await c.default.mkdir(Q,{recursive:!0}),await c.default.writeFile(F,Y,"utf8"),k.info("Content written successfully",{path
|
|
2473
|
+
if(await c.default.mkdir(Q,{recursive:!0}),await c.default.writeFile(F,Y,"utf8"),k.info("Content written successfully",{path:j?O:"document:"+q,finalLength:Y.length,append:x,wasCreated:N}),$){r.documentFileManager.markForSync(q)
|
|
2467
2474
|
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
|
|
2468
|
-
if(
|
|
2475
|
+
if(j){if(_=d.FileOperationPhase.GIT_COMMIT,y.incrementCounter("write_file_phase",1,{phase:_}),r.workspaceManager){const e=r.workspaceManager.getCurrentContext(r.currentSessionId)
|
|
2469
2476
|
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":x?"Append to":"Update"} ${O} (${C})`,t=await d.commitToGit(M,O,C,C,e,r,k,y,E.metricsPrefix)
|
|
2470
|
-
Z=t.commitHash,ee=t.previousCommitHash,k.info("Changes committed to git via shared utility",{path:O,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
|
|
2471
|
-
re+=`**Content Length:** ${Y.length} characters\n
|
|
2477
|
+
Z=t.commitHash,ee=t.previousCommitHash,k.info("Changes committed to git via shared utility",{path:O,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:j?O:"document:"+q,status:"completed",finalContentLength:Y.length,wasFileCreated:N,wasAppended:x&&L,operationType:$?"document":"file",processingTime:Date.now()-b,userComment:R,...j&&Z&&{commitHash:Z,previousCommitHash:ee||void 0}},note:"Write operation completed successfully"+($?" (document synced)":" (committed to git)")})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let re=`**${N?"Created":x?"Appended to":"Updated"} ${$?`document ${q}${A?` (${A})`:""}`:"file "+O}**\n`
|
|
2478
|
+
re+=`**Content Length:** ${Y.length} characters\n`,j&&X&&(te||(re+=`**Branch:** ${X}\n`)),V.lockAcquired&&V.lockedRequestId&&!te&&(re+=`**Locked request:** ${V.lockedRequestId}\n`),j&&Z&&(re+=`**Commit Hash:** ${Z.substring(0,8)}\n`,ee&&(re+=`**Previous Commit:** ${ee.substring(0,8)}\n`)),C&&(re+=`[RECORD:${C}]\n`),$&&(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}\`.`)
|
|
2472
2479
|
const ne=Date.now()
|
|
2473
|
-
return k.info("Write operation completed successfully",{duration:ne-b,path
|
|
2480
|
+
return k.info("Write operation completed successfully",{duration:ne-b,path:j?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
|
|
2474
2481
|
if(k.error("Write operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:_}),C)try{await s.updateToolRecord(C,{metadata:{path:e?.path,status:"failed",error:(0,m.getErrorMessage)(t),phase:_,duration:r,userComment:e?.comment},note:"Write operation failed: "+(0,m.getErrorMessage)(t)})}catch(e){}return I({tool:"write_file",success:!1}),y.incrementCounter("write_file_errors",1,{phase:_}),{content:[{type:"text",text:"\u274c **Write Operation Failed:** "+(0,m.getErrorMessage)(t)}],isError:!0}}}
|
|
2475
2482
|
const a=i(t(6928)),c=i(t(1943)),l=t(6183),d=s(t(5967)),u=t(9860),h=t(5003),g=t(7478),p=t(9949),m=t(8824)},4139(e,exports){"use strict"
|
|
2476
2483
|
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"
|
|
@@ -2944,7 +2951,7 @@ return t.success?(this.logger.info("Successfully removed worktree",{requestId:e.
|
|
|
2944
2951
|
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"
|
|
2945
2952
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
2946
2953
|
const r=t(6183),n=t(4592)
|
|
2947
|
-
exports.def={name:"planner_ops",description:"
|
|
2954
|
+
exports.def={name:"planner_ops",description:"WHEN TO USE request: when asked to plan/design/architect. Do NOT manually create requests from the plan \u2014 the planner does that.\n\nRequest a planning session and check on planner progress.\n\nAll params are flat (no nested objects). The operation field determines which params apply.\n\nOperations:\n\u2022 request \u2014 prompt required. Optional: description\n\u2022 check-status \u2014 sessionId required\n\u2022 list \u2014 all optional: activeOnly, limit",schema:r.PlannerOpsSchema,annotations:{title:"Planner Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handlePlannerOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5003(e,exports,t){"use strict"
|
|
2948
2955
|
async function r(e,t,r,s,i){const a=r.child({requestId:e,operation:"request-status-validation"})
|
|
2949
2956
|
try{a.info("Validating request status for document operation",{requestId:e})
|
|
2950
2957
|
const r=await t.getRequest(e)
|
|
@@ -3193,7 +3200,7 @@ try{await(0,o.createFailureToolRecord)("complete-request",r,{error:s,details:i,r
|
|
|
3193
3200
|
const r=t(9860),n=t(1569),o=t(8616),s=t(8824),i=t(5454)},5767(e,exports,t){"use strict"
|
|
3194
3201
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3195
3202
|
const r=t(6183),n=t(6285)
|
|
3196
|
-
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
|
|
3203
|
+
exports.def={name:"specialist_ops",description:"Manage your pool of up to 10 specialists. Each has a specialization describing their domain. Reuse specialists via follow-up before spawning new ones.\n\nAll params are flat (no nested objects). The operation field determines which params apply.\n\nOperations:\n\u2022 delegate \u2014 prompt + specialization required. Optional: description, requestId\n\u2022 follow-up \u2014 prompt + sessionId required\n\u2022 check-status \u2014 sessionId required\n\u2022 list \u2014 all params optional: activeOnly, requestId (filter), limit\n\u2022 abort \u2014 sessionId required",schema:r.SpecialistOpsSchema,annotations:{title:"Specialist Operations",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleSpecialistOps)(e,t.context,t.logger,t.metrics,t.apiClient??void 0,t.cliOrigin)}}},5802(module){"use strict"
|
|
3197
3204
|
module.exports=require("@modelcontextprotocol/sdk/server/stdio.js")},5806(e,exports,t){"use strict"
|
|
3198
3205
|
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())}))})
|
|
3199
3206
|
return(0,o.areTestsRequiredForCompletion)()?e.extend({testVerification:t}):e}Object.defineProperty(exports,"__esModule",{value:!0}),exports.DynamicCompleteRequestSchema=void 0,exports.getDynamicCompleteRequestSchema=r
|
|
@@ -3223,10 +3230,10 @@ else{if(!q)throw Error("Either paths or operations must be specified")
|
|
|
3223
3230
|
R=q.map((e=>{if(e.path)return{type:"file",target:e.path}
|
|
3224
3231
|
if(e.documentId)return{type:"document",target:e.documentId}
|
|
3225
3232
|
throw Error("Invalid operation: neither path nor documentId specified")}))}if(0===R.length)throw Error("At least one file or document must be specified for deletion")
|
|
3226
|
-
const P=R.filter((e=>"file"===e.type)),M=R.filter((e=>"document"===e.type))
|
|
3233
|
+
const P=R.filter((e=>"file"===e.type)),M=R.filter((e=>"document"===e.type)),$=R.length
|
|
3227
3234
|
f.info("Starting mixed file and document deletion operation",{taskId:x,totalOperations:R.length,fileOperations:P.length,documentOperations:M.length,comment:S}),l.validateTaskIdFormat(x,f,s,b.metricsPrefix)
|
|
3228
|
-
const
|
|
3229
|
-
f.info("Initial branch context",{initialBranch
|
|
3235
|
+
const j=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3236
|
+
f.info("Initial branch context",{initialBranch:j.branch,initialRequestId:j.requestId,isMain:j.isMain})
|
|
3230
3237
|
const O=[]
|
|
3231
3238
|
for(const e of P){const{normalizedPath:t,fullPath:n}=l.validateAndNormalizePath(e.target,r)
|
|
3232
3239
|
O.push({normalized:t,full:n})}I=l.FileOperationPhase.TASK_VALIDATION,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
@@ -3252,18 +3259,18 @@ try{if(e=await V.getDocument(t),r.filename=e.filename,f.info("Document found for
|
|
|
3252
3259
|
throw e}try{await(0,p.ensureDocumentNotLocked)(t,n,f,s,"delete-document-archive")}catch(e){if(e instanceof d.ValidationError)throw Error(e.message)
|
|
3253
3260
|
throw e}}catch(e){throw Error(`Document not found or validation failed: ${t}. ${(0,m.getErrorMessage)(e)}`)}const o=await V.archiveDocument(t)
|
|
3254
3261
|
r.success=!0,r.filename=o.filename,W++,f.info("Document archived successfully",{documentId:o.id,filename:o.filename,archivedAt:o.archived_at})}catch(e){r.error=(0,m.getErrorMessage)(e),f.warn("Failed to delete document "+t,{error:r.error})}G.push(r)}const J=Date.now()-y
|
|
3255
|
-
s.recordValue("delete_files_time",J),s.incrementCounter("delete_files_operations_total"
|
|
3262
|
+
s.recordValue("delete_files_time",J),s.incrementCounter("delete_files_operations_total",$),s.incrementCounter("delete_files_operations_success",W),s.incrementCounter("delete_files_operations_failed",$-W),s.incrementCounter("delete_files_file_operations",P.length),s.incrementCounter("delete_files_document_operations",M.length),W===$?s.incrementCounter("delete_files_success",1):W>0?s.incrementCounter("delete_files_partial_success",1):s.incrementCounter("delete_files_total_failure",1)
|
|
3256
3263
|
let K=null
|
|
3257
3264
|
if(W>0){I=l.FileOperationPhase.GIT_COMMIT,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3258
3265
|
const e=G.filter((e=>e.success)),t=e.filter((e=>"file"===e.type)).length,n=e.filter((e=>"document"===e.type)).length
|
|
3259
3266
|
let o
|
|
3260
3267
|
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(x,D,H,U,o,r,f,s,b.metricsPrefix)}I=l.FileOperationPhase.RECORD_UPDATE_SUCCESS,s.incrementCounter("delete_files_phase",1,{phase:I})
|
|
3261
3268
|
const Y=G.filter((e=>e.success)),Q=G.filter((e=>!e.success))
|
|
3262
|
-
await l.updateFileOperationRecords(x,w,k,D,b.recordType,W
|
|
3269
|
+
await l.updateFileOperationRecords(x,w,k,D,b.recordType,W===$?`Successfully deleted all ${$} operations`:`Deleted ${W}/${$} operations successfully`,{status:W===$?"completed":"partial_success",commitHash:K?.commitHash,previousCommitHash:K?.previousCommitHash,totalOperations:$,fileOperations:P.length,documentOperations:M.length,successCount:W,failureCount:$-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:B.hadUserMods,userModsCommitHash:B.userModsCommitHash},W===$?`Successfully deleted all ${$} operations`:`Deleted ${W}/${$} operations successfully`,u,v,f,s,b.metricsPrefix)
|
|
3263
3270
|
const Z=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
3264
3271
|
let X=""
|
|
3265
|
-
if(W
|
|
3266
|
-
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}/${
|
|
3272
|
+
if(W===$){const e=Y.filter((e=>"file"===e.type)).length,t=Y.filter((e=>"document"===e.type)).length
|
|
3273
|
+
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}/${$} 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})`
|
|
3267
3274
|
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})`
|
|
3268
3275
|
return`\u2022 ${e.type}: ${t}: ${e.error}`})).join("\n")
|
|
3269
3276
|
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)
|
|
@@ -3341,7 +3348,7 @@ Object.defineProperty(exports,"__esModule",{value:!0}),exports.SwitchToMainBranc
|
|
|
3341
3348
|
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)"})
|
|
3342
3349
|
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" }'})}))
|
|
3343
3350
|
const a=r.z.string().min(1).describe("OpenCode session ID")
|
|
3344
|
-
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
|
|
3351
|
+
exports.SubagentOperationsSchema=r.z.object({sessionId:a.optional(),operation:r.z.enum(["spawn","continue","check-status","abort","read-messages","list-sessions"]),prompt:r.z.string().min(1).describe("Instructions for the subagent (required for spawn and continue)").optional(),agent:r.z.string().default("work").refine((e=>(0,n.isValidAgent)(e)),{message:"Invalid agent. Check tool description for available agents."}).describe("The subagent type to spawn (see tool description for available agents)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, spawn only)").optional(),requestId:r.z.string().describe("Request ID \u2014 associates work (spawn) or filters results (list-sessions)").optional(),allowParallel:r.z.boolean().describe("Allow spawning even if request already has active workers (spawn only)").optional(),useExistingSession:r.z.string().describe("Existing session ID to send prompt to instead of creating new session (spawn only)").optional(),limit:r.z.number().min(1).max(100).describe("Max items to return (read-messages: max 50, list-sessions: max 100)").optional(),activeOnly:r.z.boolean().describe("Only show sessions that are currently active/busy (list-sessions only)").optional(),minTokens:r.z.number().min(0).describe("Only show sessions with at least this many tokens (list-sessions only)").optional(),maxTokens:r.z.number().min(0).describe("Only show sessions with at most this many tokens (list-sessions only)").optional(),maxAgeHours:r.z.number().min(0).describe("Only show sessions newer than X hours (list-sessions only)").optional()}).refine((e=>"spawn"===e.operation?!!e.prompt:"continue"===e.operation?!!e.prompt&&!!e.sessionId:"check-status"===e.operation||"abort"===e.operation||"read-messages"===e.operation?!!e.sessionId:"list-sessions"===e.operation),{message:"spawn requires prompt; continue requires prompt+sessionId; check-status/abort/read-messages require sessionId"}),exports.SpecialistOpsSchema=r.z.object({operation:r.z.enum(["delegate","follow-up","check-status","list","abort"]),sessionId:a.optional(),prompt:r.z.string().min(1).describe("Instructions for the specialist (required for delegate and follow-up)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, delegate only)").optional(),specialization:r.z.string().max(500).describe('Domain description (e.g. "Frontend UI components"). Required for delegate').optional(),requestId:r.z.string().describe("Request ID \u2014 associates work (delegate) or filters results (list)").optional(),activeOnly:r.z.boolean().describe("Only show active/busy specialists (list only)").optional(),limit:r.z.number().min(1).max(100).describe("Max sessions to return (list only)").optional()}).refine((e=>"delegate"===e.operation?!!e.prompt&&!!e.specialization&&!e.sessionId:"follow-up"===e.operation?!!e.prompt&&!!e.sessionId:"check-status"===e.operation||"abort"===e.operation?!!e.sessionId:"list"===e.operation),{message:"delegate requires prompt+specialization; follow-up requires prompt+sessionId; check-status/abort require sessionId"}),exports.PlannerOpsSchema=r.z.object({operation:r.z.enum(["request","check-status","list"]),sessionId:a.optional(),prompt:r.z.string().min(1).describe("What to plan \u2014 feature description, architecture question, etc. (required for request)").optional(),description:r.z.string().max(60).describe("Brief label for the UI (max 60 chars, request only)").optional(),activeOnly:r.z.boolean().describe("Only show active/busy planning sessions (list only)").optional(),limit:r.z.number().min(1).max(100).describe("Max sessions to return (list only)").optional()}).refine((e=>"request"===e.operation?!!e.prompt:"check-status"===e.operation?!!e.sessionId:"list"===e.operation),{message:"request requires prompt; check-status requires sessionId"}),exports.SwitchToRequestBranchSchema=r.z.object({requestId:s}),exports.InsertLinesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),insertions:r.z.array(r.z.object({type:r.z.enum(["before","after","between"]),line:r.z.number().optional(),afterLine:r.z.number().optional(),beforeLine:r.z.number().optional(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}).refine((e=>"between"===e.type?void 0!==e.afterLine&&void 0!==e.beforeLine&&void 0===e.line:void 0!==e.line&&void 0===e.afterLine&&void 0===e.beforeLine),{message:"Invalid line parameters"}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.ReplaceLinesSchema=r.z.object({operations:r.z.array(r.z.object({path:r.z.string().optional(),documentId:i.optional(),replacements:r.z.array(r.z.object({lines:r.z.string(),content:r.z.union([r.z.string(),r.z.array(r.z.string())])}))}).refine((e=>e.path&&!e.documentId||!e.path&&e.documentId),{message:"path or documentId required"})),comment:r.z.string()}),exports.CreateDocumentSchema=r.z.object({requestId:s.optional(),filename:r.z.string().refine((e=>e.toLowerCase().endsWith(".md")),{message:"Filename must end with .md extension"}),content:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"],{errorMap(){return{message:"Document type must be one of: Report, Documentation, Plan, Other"}}}),comment:r.z.string()}),exports.SearchDocumentsSchema=r.z.object({query:r.z.string(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),requestId:s.optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both")}),exports.DocumentOperationsSchema=r.z.object({operation:r.z.enum(["create","search","create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"]),documentId:i.optional(),requestId:s.optional(),filename:r.z.string().optional(),content:r.z.string().optional(),type:r.z.enum(["Report","Documentation","Plan","Other"]).optional(),comment:r.z.string().optional(),query:r.z.string().optional(),includeArchived:r.z.boolean().default(!1),maxResults:r.z.number().min(1).max(100).default(20),dateFrom:r.z.string().optional(),dateTo:r.z.string().optional(),searchIn:r.z.enum(["content","filename","both"]).default("both"),versionLabel:r.z.string().optional(),changeSummary:r.z.string().optional(),versionNumber:r.z.number().int().min(1).optional(),selectedText:r.z.string().optional(),prefixContext:r.z.string().optional(),suffixContext:r.z.string().optional(),lineHint:r.z.number().int().optional(),body:r.z.string().optional(),annotationId:r.z.string().optional()}).superRefine(((e,t)=>{const r=e.operation;["create-snapshot","get-history","get-version","restore-version","list-annotations","create-annotation","reply-to-annotation","resolve-annotation"].includes(r)&&!e.documentId&&t.addIssue({code:"custom",message:`documentId is required for '${r}'. Example: { "operation": "${r}", "documentId": "doc000001" }`}),"create"===r&&(e.filename?e.filename.toLowerCase().endsWith(".md")||t.addIssue({code:"custom",message:"Filename must end with .md extension"}):t.addIssue({code:"custom",message:"filename is required for create (must end with .md)"}),e.content||t.addIssue({code:"custom",message:"content is required for create"}),e.type||t.addIssue({code:"custom",message:"type is required for create (Report, Documentation, Plan, or Other)"}),e.comment||t.addIssue({code:"custom",message:"comment is required for create"})),"search"!==r||e.query||t.addIssue({code:"custom",message:'query is required for search. Example: { "operation": "search", "query": "search term" }'}),"get-version"!==r&&"restore-version"!==r||e.versionNumber||t.addIssue({code:"custom",message:`versionNumber is required for '${r}'`}),"create-annotation"===r&&(e.selectedText||t.addIssue({code:"custom",message:"selectedText is required for create-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for create-annotation"})),"reply-to-annotation"===r&&(e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for reply-to-annotation"}),e.body||t.addIssue({code:"custom",message:"body is required for reply-to-annotation"})),"resolve-annotation"!==r||e.annotationId||t.addIssue({code:"custom",message:"annotationId is required for resolve-annotation"})}))
|
|
3345
3352
|
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)"})
|
|
3346
3353
|
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
|
|
3347
3354
|
"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
|
|
@@ -3364,8 +3371,8 @@ return o(t,e),t})
|
|
|
3364
3371
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.handleSpecialistOps=async function(e,r,n,o,s,p){const m=n.child({tool:"specialist_ops"}),f=o.startTimer("tool_execution_time")
|
|
3365
3372
|
try{if(e?.delegate&&"object"==typeof e.delegate){const t=e.delegate
|
|
3366
3373
|
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
|
|
3367
|
-
e.prompt=e.prompt||t.prompt,
|
|
3368
|
-
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))
|
|
3374
|
+
e.prompt=e.prompt||t.prompt,delete e.followUp}if(e?.list&&"object"==typeof e.list){const t=e.list
|
|
3375
|
+
e.activeOnly=e.activeOnly??t.activeOnly,e.requestId=e.requestId||t.requestId,e.limit=e.limit??t.limit,delete e.list}!e?.operation&&e&&(e.prompt&&!e.sessionId?e.operation="delegate":e.prompt&&e.sessionId?e.operation="follow-up":e.sessionId&&(e.operation="check-status")),e?.operation&&("delegate"===e.operation?(delete e.sessionId,delete e.activeOnly,delete e.limit):"follow-up"===e.operation?(delete e.description,delete e.specialization,delete e.activeOnly,delete e.limit):"check-status"===e.operation||"abort"===e.operation?(delete e.prompt,delete e.description,delete e.specialization,delete e.requestId,delete e.activeOnly,delete e.limit):"list"===e.operation&&(delete e.sessionId,delete e.prompt,delete e.description,delete e.specialization))
|
|
3369
3376
|
const n=c.validateArgs(e,a.SpecialistOpsSchema),{operation:y,sessionId:w}=n
|
|
3370
3377
|
let k
|
|
3371
3378
|
switch(m.info("Processing specialist_ops",{operation:y,sessionId:w}),y){case"delegate":{const e=10,o=p?.sessionId||g.sessionIdentity.getIdentity()?.sessionId
|
|
@@ -3398,9 +3405,7 @@ if(e)try{const t=await fetch(e.replace(/\/$/,"")+"/session/status")
|
|
|
3398
3405
|
if(t.ok){const e=await t.json(),r=e[w]?.type
|
|
3399
3406
|
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}
|
|
3400
3407
|
break}}}catch{}k=await(0,u.handleContinue)(w,n.prompt,r,m,s,"specialist",p)
|
|
3401
|
-
|
|
3402
|
-
if(t&&s)try{const e=s.getCLISessionClient()
|
|
3403
|
-
e&&(await e.createOrUpdateSession({externalSessionId:w,specialization:t}),k.content[0].text+="\nSpecialization updated to: "+t)}catch{}break}case"check-status":k=await(0,u.handleCheckStatus)(w,r,m,s)
|
|
3408
|
+
break}case"check-status":k=await(0,u.handleCheckStatus)(w,r,m,s)
|
|
3404
3409
|
break
|
|
3405
3410
|
case"abort":if(k=await(0,u.handleAbort)(w,r,m),!k.isError&&s)try{const e=s.getCLISessionClient()
|
|
3406
3411
|
e&&await e.createOrUpdateSession({externalSessionId:w,status:"archived"})}catch{}break
|
|
@@ -3492,18 +3497,18 @@ for(const e of R)M.push({type:"document",documentId:e.documentId,insertions:e.in
|
|
|
3492
3497
|
if(M.length>0&&n.apiClient){const e=M.map((e=>e.documentId))
|
|
3493
3498
|
try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,w,f,"insert-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3494
3499
|
throw e}}v=d.FileOperationPhase.TASK_VALIDATION,f.incrementCounter("insert_lines_phase",1,{phase:v})
|
|
3495
|
-
const
|
|
3500
|
+
const $=P.length>0?P[0].path:"document-operation",j=await d.validateTaskId(T,$,o,w,f,C.metricsPrefix),O=j?.requestId
|
|
3496
3501
|
let D=null
|
|
3497
3502
|
P.length>0&&O&&(D=await d.validateWorkItemStates(T,P[0].path,o,i,n,w,f,C.metricsPrefix))
|
|
3498
3503
|
let A={taskPromoted:!1,requestPromoted:!1}
|
|
3499
|
-
P.length>0&&O&&D&&(A=await d.autoPromoteTaskStatus(T
|
|
3504
|
+
P.length>0&&O&&D&&(A=await d.autoPromoteTaskStatus(T,j.status,O,D.request?.status,P[0].path,o,i,w,f,C.metricsPrefix),A.taskPromoted&&w.info("Auto-promoted task to in_progress for insert-lines operation",{taskId:T,requestId:O,previousStatus:j.status,newStatus:A.newTaskStatus,triggeringOperation:"insert-lines"}))
|
|
3500
3505
|
const F=await d.ensureCorrectWorkspaceContext({taskPromoted:A.taskPromoted,requestId:O,context:n,operation:"insert-lines",logger:w,metrics:f,metricsPrefix:C.metricsPrefix})
|
|
3501
3506
|
if(!F.success){if(F.isLockConflict)return{content:[{type:"text",text:"\u274c "+F.error}],isError:!0}
|
|
3502
3507
|
throw Error(F.error)}if(P.length>0){w.debug("Re-validating file paths with correct workspace context",{operationCount:P.length,workspaceBasePath:n.workspaceManager?.getCurrentContext(n.currentSessionId).basePath})
|
|
3503
3508
|
for(let e=0;e<P.length;e++){const t=P[e],r=x[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(r.path,n)
|
|
3504
3509
|
P[e]={...t,path:o,fullPath:s}}}if(M.length>0&&O)try{await(0,h.validateRequestStatusForDocumentOperation)(O,i,w,f,"insert-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3505
3510
|
throw e}v=d.FileOperationPhase.RECORD_CREATION,f.incrementCounter("insert_lines_phase",1,{phase:v})
|
|
3506
|
-
const N=[...P.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...M.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:L}=await d.createFileOperationRecords(T,O,n.projectId,C.recordType
|
|
3511
|
+
const N=[...P.map((e=>({type:"file",path:e.path,insertions:e.insertions}))),...M.map((e=>({type:"document",documentId:e.documentId,insertions:e.insertions})))],{toolRecordId:L}=await d.createFileOperationRecords(T,O,n.projectId,C.recordType,$,{operationCount:E.length,fileOperations:P.length,documentOperations:M.length,operations:N,userComment:q},o,s,w,f,C.metricsPrefix,y)
|
|
3507
3512
|
if(I=L,b=L,v=C.fileOperationPhase,f.incrementCounter("insert_lines_phase",1,{phase:v}),P.length>0&&n.git)try{w.debug("[INSERT-LINES] Checking for user changes before insert operations")
|
|
3508
3513
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"insert-lines",{requestId:O,taskId:T,workspaceManager:n.workspaceManager},w,f)
|
|
3509
3514
|
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:P.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:P.length,error:e instanceof Error?e.message:e+""})}w.debug("[INSERT-LINES] Proceeding with file operations",{fileCount:P.length})
|
|
@@ -3557,8 +3562,8 @@ throw f.error(t,{error:e instanceof Error?e.stack:e+""}),Error(t)}const P=new o.
|
|
|
3557
3562
|
f.info("API client initialized with specialized clients"),v?(P.setAuthToken(v),f.info("Auth token set on ApiClient during creation",{hasToken:!0,tokenLength:v.length})):f.warn("No auth token available during ApiClient creation",{info:"Client will need to authenticate before making requests"})
|
|
3558
3563
|
const M=I.verifyAllClients()
|
|
3559
3564
|
M.success?f.info("Token consistency verified across all clients"):f.error(`Token inconsistency detected in ${M.failedClients.length} clients: ${M.failedClients.join(", ")}`)
|
|
3560
|
-
const
|
|
3561
|
-
return v
|
|
3565
|
+
const $=P.getAuthToken()
|
|
3566
|
+
return v&&!$?(f.error("CRITICAL: ApiClient token was not set properly!"),P.setAuthToken(v)):$&&f.info("ApiClient token verified",{tokenLength:$.length,matches:$===v}),f.info("API client creation completed successfully"),P}}},6540(e,exports){"use strict"
|
|
3562
3567
|
var t
|
|
3563
3568
|
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={}))},6552(e,exports,t){"use strict"
|
|
3564
3569
|
async function r(){const e=new o.StdioServerTransport,t=(0,l.setupParentProcessDetection)((()=>{k.info("Parent process gone or orphan detected. Shutting down."),process.exit(0)}))
|
|
@@ -3639,13 +3644,13 @@ const R=q.filter((e=>e.path)),P=q.filter((e=>e.documentId))
|
|
|
3639
3644
|
k.info("Operation breakdown",{fileOperations:R.length,documentOperations:P.length})
|
|
3640
3645
|
const M=[]
|
|
3641
3646
|
for(const e of R){const{normalizedPath:t,fullPath:r}=d.validateAndNormalizePath(e.path,n)
|
|
3642
|
-
M.push({type:"file",path:t,fullPath:r,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})}const
|
|
3647
|
+
M.push({type:"file",path:t,fullPath:r,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})}const $=[]
|
|
3643
3648
|
if(P.length>0&&!n.documentFileManager)throw Error("Document file manager not available - cannot process document operations")
|
|
3644
|
-
for(const e of P)
|
|
3645
|
-
if(
|
|
3649
|
+
for(const e of P)$.push({type:"document",documentId:e.documentId,replacements:e.replacements.map((e=>({lines:(0,y.parseLineSpec)(e.lines),content:e.content})))})
|
|
3650
|
+
if($.length>0&&n.apiClient){const e=$.map((e=>e.documentId))
|
|
3646
3651
|
try{await(0,p.ensureDocumentsNotLocked)(e,n.apiClient,k,f,"replace-lines-documents")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3647
3652
|
throw e}}C=d.FileOperationPhase.TASK_VALIDATION,f.incrementCounter("replace_lines_phase",1,{phase:C})
|
|
3648
|
-
const
|
|
3653
|
+
const j=M.length>0?M[0].path:"document-operation",O=await d.validateTaskId(x,j,o,k,f,_.metricsPrefix),D=O?.requestId
|
|
3649
3654
|
let A=null
|
|
3650
3655
|
M.length>0&&D&&(A=await d.validateWorkItemStates(x,M[0].path,o,i,n,k,f,_.metricsPrefix))
|
|
3651
3656
|
let F={taskPromoted:!1,requestPromoted:!1}
|
|
@@ -3654,9 +3659,9 @@ const N=await d.ensureCorrectWorkspaceContext({taskPromoted:F.taskPromoted,reque
|
|
|
3654
3659
|
if(!N.success){if(N.isLockConflict)return{content:[{type:"text",text:"\u274c "+N.error}],isError:!0}
|
|
3655
3660
|
throw Error(N.error)}if(M.length>0){k.debug("Re-validating file paths with correct workspace context",{operationCount:M.length,workspaceBasePath:n.workspaceManager?.getCurrentContext(n.currentSessionId).basePath})
|
|
3656
3661
|
for(let e=0;e<M.length;e++){const t=M[e],r=R[e],{normalizedPath:o,fullPath:s}=d.validateAndNormalizePath(r.path,n)
|
|
3657
|
-
M[e]={...t,path:o,fullPath:s}}}if(
|
|
3662
|
+
M[e]={...t,path:o,fullPath:s}}}if($.length>0&&D)try{await(0,h.validateRequestStatusForDocumentOperation)(D,i,k,f,"replace-lines-document")}catch(e){if(e instanceof u.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
3658
3663
|
throw e}C=d.FileOperationPhase.RECORD_CREATION,f.incrementCounter("replace_lines_phase",1,{phase:C})
|
|
3659
|
-
const L=[...M.map((e=>({type:"file",path:e.path,replacements:e.replacements})))
|
|
3664
|
+
const L=[...M.map((e=>({type:"file",path:e.path,replacements:e.replacements}))),...$.map((e=>({type:"document",documentId:e.documentId,replacements:e.replacements})))],{toolRecordId:z}=await d.createFileOperationRecords(x,D,n.projectId,_.recordType,j,{operationCount:q.length,fileOperations:M.length,documentOperations:$.length,operations:L,userComment:S},o,s,k,f,_.metricsPrefix,w)
|
|
3660
3665
|
if(b=z,v=z,C=_.fileOperationPhase,f.incrementCounter("replace_lines_phase",1,{phase:C}),M.length>0&&n.git)try{k.debug("[REPLACE-LINES] Checking for user changes before replace operations")
|
|
3661
3666
|
const e=await(0,g.commitUserChangesBeforeToolOperation)(n.git,"replace-lines",{requestId:D,taskId:x,workspaceManager:n.workspaceManager},k,f)
|
|
3662
3667
|
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:x,fileOperationsCount:M.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:x,fileOperationsCount:M.length,error:e instanceof Error?e.message:e+""})}k.debug("[REPLACE-LINES] Proceeding with file operations",{fileCount:M.length})
|
|
@@ -3665,19 +3670,19 @@ let H=0,U=0,G=0,W=0
|
|
|
3665
3670
|
for(const e of M){const t={type:"file",path:e.path,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
|
|
3666
3671
|
try{if(await c.default.access(e.fullPath),!(await c.default.stat(e.fullPath)).isFile())throw Error("Path is not a file: "+e.path)
|
|
3667
3672
|
const n=await c.default.readFile(e.fullPath,"utf8"),{newContent:o,results:s}=await r(n,e.replacements)
|
|
3668
|
-
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),H+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,k.error("File operation failed",{path:e.path,error:t.error})}B.push(t)}for(const e of
|
|
3673
|
+
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),H+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,k.error("File operation failed",{path:e.path,error:t.error})}B.push(t)}for(const e of $){const t={type:"document",documentId:e.documentId,success:!1,replacements:[],successfulReplacements:0,failedReplacements:0,totalLinesReplaced:0,totalLinesAdded:0}
|
|
3669
3674
|
try{const o=await n.documentFileManager.getDocumentAsFile(e.documentId),s=n.documentFileManager.getCachedDocumentInfo(e.documentId)
|
|
3670
3675
|
t.filename=s?.filename
|
|
3671
3676
|
const i=await c.default.readFile(o,"utf8"),{newContent:a,results:l}=await r(i,e.replacements)
|
|
3672
|
-
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),H+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,k.error("Document operation failed",{documentId:e.documentId,error:t.error})}B.push(t)}if(
|
|
3677
|
+
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),H+=t.failedReplacements,U+=t.totalLinesReplaced,G+=t.totalLinesAdded}catch(r){t.error=(0,m.getErrorMessage)(r),t.failedReplacements=e.replacements.length,H+=t.failedReplacements,k.error("Document operation failed",{documentId:e.documentId,error:t.error})}B.push(t)}if($.length>0)try{for(const e of $){const t=B.find((t=>t.documentId===e.documentId))
|
|
3673
3678
|
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(x,M,B,W,{operationType:"Replace lines",toolRecordId:v,successField:"successfulReplacements",logger:k,metrics:f,metricsPrefix:"replace_lines"},n),J=d.processMultiFileOperationResults(B,"successfulReplacements"),{successfulOperations:K,failedOperations:Y,totalSuccessfulChanges:Q,overallSuccess:Z,successfulFiles:X,failedFiles:ee}=J
|
|
3674
|
-
try{await s.updateToolRecord(v,{metadata:{path:M.length>0?M[0].path:"document:"
|
|
3679
|
+
try{await s.updateToolRecord(v,{metadata:{path:M.length>0?M[0].path:"document:"+$[0]?.documentId,status:Z?"completed":"failed",error:Z?void 0:Y+" operations failed",totalOperations:B.length,successfulFiles:X,failedFiles:ee,operations:L,totalSuccessfulReplacements:Q,totalFailedReplacements:H,totalLinesReplaced:U,totalLinesAdded:G,operationsWithChanges:W,processingTime:Date.now()-I,userComment:S,...M.length>0&&V.success&&V.commitHash&&{commitHash:V.commitHash,previousCommitHash:V.previousCommitHash||void 0}},note:Z?`Line replacement completed: ${K}/${B.length} operations successful${M.length>0?" (committed to git)":""}`:`Line replacement partially failed: ${Y}/${B.length} operations failed`})}catch(e){k.warn("Failed to update tool record",{recordError:e})}let te="## Line Replacement Results\n\n"
|
|
3675
3680
|
if(n.workspaceManager){const e=n.workspaceManager.getCurrentContext(n.currentSessionId)
|
|
3676
3681
|
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, ${H} 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===B.length){const e=B[0]
|
|
3677
3682
|
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"
|
|
3678
3683
|
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:** ${B.length}\n`,te+=`- **Successful:** ${K}\n`,te+=`- **Failed:** ${Y}\n`,te+=`- **Total Replacements:** ${Q} successful, ${H} failed\n`,te+=`- **Total Lines Replaced:** ${U}\n`,G>0&&(te+=`- **Total Lines Added:** ${G}\n`),te+="\n",te+="**Detailed Results:**\n\n"
|
|
3679
3684
|
for(const e of B){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"
|
|
3680
|
-
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"}}
|
|
3685
|
+
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"}}$.length>0&&(te+="\u{1f4c4} **Document Changes:** Modified documents have been automatically synced back to the tracking system.\n\n")
|
|
3681
3686
|
const re=Date.now()-I
|
|
3682
3687
|
return k.info("Replace lines operation completed",{duration:re,success:Z,totalOperations:B.length,successfulOperations:K,failedOperations:Y}),f.incrementCounter("replace_lines_total",1,{success:Z}),{content:[{type:"text",text:te}],isError:!Z}}catch(t){const r=Date.now()-I
|
|
3683
3688
|
if(k.error("Replace lines operation failed",{error:t instanceof Error?t.stack:t+"",duration:r,phase:C}),v)try{await s.updateToolRecord(v,{metadata:{path:e?.operations?.[0]?.path||e?.operations?.[0]?.documentId,status:"failed",error:(0,m.getErrorMessage)(t),phase:C,duration:r,userComment:e?.comment},note:"Line replacement failed: "+(0,m.getErrorMessage)(t)})}catch(e){}return f.incrementCounter("replace_lines_errors",1,{phase:C}),{content:[{type:"text",text:"\u274c **Replace Lines Failed:** "+(0,m.getErrorMessage)(t)}],isError:!0}}}
|
|
@@ -3747,7 +3752,7 @@ try{const x=await m.getTask(g)
|
|
|
3747
3752
|
s.info("Raw task response data",{responseDataType:typeof x,isArray:Array.isArray(x),hasData:null!=x,properties:x&&"object"==typeof x?Object.keys(x):[]}),w=(0,l.extractDataFromResponse)(x,{logger:s,operationName:"getTask",defaultValue:{id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}),s.info("Found task: "+w.title)}catch(R){s.warn("Could not fetch task information: "+(0,u.getErrorMessage)(R)),w={id:g,title:"Unknown Task",status:"unknown",description:"No description available"}}let k=[]
|
|
3748
3753
|
try{const P=await f.getToolRecordsByTaskId(g)
|
|
3749
3754
|
if(s.info("Raw records response data",{responseDataType:typeof P,isArray:Array.isArray(P),hasData:null!=P,properties:P&&"object"==typeof P?Object.keys(P):[]}),k=(0,l.extractArrayFromResponse)(P,{logger:s,operationName:"searchRecords",defaultValue:[]}),k.length>0&&s.info("First record summary:",{id:k[0].id,type:k[0].type,hasMetadata:!!k[0].metadata,hasCommitHash:!!k[0].metadata?.commitHash}),s.info(`Extracted ${k.length} records for task ${g}`),k.length>0){const M={}
|
|
3750
|
-
k.forEach((e=>{M[e.type]=(M[e.type]||0)+1})),s.info("Record type distribution:",M)}}catch(
|
|
3755
|
+
k.forEach((e=>{M[e.type]=(M[e.type]||0)+1})),s.info("Record type distribution:",M)}}catch($){s.warn("Error fetching records for task "+g,{error:(0,u.getErrorMessage)($)}),k=[]}if(0===k.length)return h({success:!0,recordCount:0}),{content:[{type:"text",text:`No records found for task ${g}.`}]}
|
|
3751
3756
|
function I(e){const t=new Map,r=new Map,n=[]
|
|
3752
3757
|
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
|
|
3753
3758
|
if(e&&s){const i={source:e,destination:s,recordId:o.id,timestamp:o.createdAt,type:"move-file"}
|
|
@@ -3767,8 +3772,8 @@ let n=!1
|
|
|
3767
3772
|
if(t&&(n=e.metadata.successfulOperations.some((e=>e&&e.source&&e.destination))),!n&&r&&(n=e.metadata.failedOperations.some((e=>e&&e.source&&e.destination))),!n)return s.warn("Skipping move-files record without valid operation paths: "+e.id),!1}else if("delete-file"===e.type){if(!e.metadata.path)return s.warn("Skipping delete-file record without path metadata: "+e.id),!1}else if("delete-files"===e.type){const t=e.metadata.paths
|
|
3768
3773
|
if(!Array.isArray(t)||0===t.length)return s.warn("Skipping delete-files record without valid paths array: "+e.id),!1
|
|
3769
3774
|
if(!t.every((e=>"string"==typeof e&&e.trim().length>0)))return s.warn("Skipping delete-files record without valid file paths: "+e.id),!1}return!0}))
|
|
3770
|
-
if(s.info(`Found ${v.length} file operation records`),v.length>0){const
|
|
3771
|
-
v.forEach((e=>{
|
|
3775
|
+
if(s.info(`Found ${v.length} file operation records`),v.length>0){const j={}
|
|
3776
|
+
v.forEach((e=>{j[e.type]=(j[e.type]||0)+1})),s.info("Filtered record type distribution:",j)}if(0===v.length)return h({success:!0,fileChanges:0}),{content:[{type:"text",text:`No file changes found for task ${g}.`}]}
|
|
3772
3777
|
const C=new Map
|
|
3773
3778
|
v.forEach((e=>{let t=null
|
|
3774
3779
|
if(e.metadata){if(!e.metadata.commitHash){const t=["gitCommitId","commitId","commit","gitCommit"]
|
|
@@ -3844,9 +3849,9 @@ let S=0,T=!1
|
|
|
3844
3849
|
if(p){for(const Te of _.values())Te.hasDiff&&Te.diffText&&(S+=Te.diffText.split("\n").length)
|
|
3845
3850
|
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`
|
|
3846
3851
|
for(const xe of b.allMoves)E+=`- **${xe.source}** \u2192 **${xe.destination}**\n`,E+=` - Operation: ${xe.type}\n`,E+=` - Timestamp: ${new Date(xe.timestamp).toLocaleString()}\n`,E+=` - Record ID: ${xe.recordId}\n\n`}E+="## Modified Files\n\n"
|
|
3847
|
-
for(const[Re,Pe]of _.entries()){const{normalizedPath:Me,fullPath
|
|
3848
|
-
let
|
|
3849
|
-
try{await a.access(je
|
|
3852
|
+
for(const[Re,Pe]of _.entries()){const{normalizedPath:Me,fullPath:$e}=d.validateAndNormalizePath(Re,t)
|
|
3853
|
+
let je=!1
|
|
3854
|
+
try{await a.access($e),je=!0}catch{}E+=`### ${Re} ${je?"":"(Deleted)"}\n\n`
|
|
3850
3855
|
const Oe=new Date(Pe.firstChange.timestamp).toLocaleString(),De=new Date(Pe.lastChange.timestamp).toLocaleString()
|
|
3851
3856
|
E+=`**First Change**: ${Oe}\n`,E+=`**Last Change**: ${De}\n`,"pre-task"===Pe.firstChange.status&&Pe.firstChange.commitHash?E+=`**Pre-Task Commit**: ${Pe.firstChange.commitHash.substring(0,8)}\n`:Pe.firstChange.commitHash&&(E+=`**File Created During Task**: ${Pe.firstChange.commitHash.substring(0,8)}\n`),Pe.lastChange.commitHash&&(E+=`**Final Commit**: ${Pe.lastChange.commitHash.substring(0,8)}\n`)
|
|
3852
3857
|
const Ae=b.sourceToMove.get(Re),Fe=b.destToMove.get(Re)
|
|
@@ -3966,7 +3971,7 @@ this.logger.debug("Branch creation failed, retrying",{attempt:n,maxRetries:t,req
|
|
|
3966
3971
|
this.logger.debug("Branch creation attempt failed, retrying",{attempt:n,maxRetries:t,requestId:e.requestId,error:(0,a.getErrorMessage)(o)}),await new Promise((e=>setTimeout(e,r*n)))}throw Error("Unexpected end of retry loop")}}exports.SharedBranchManager=c},7250(e,exports,t){"use strict"
|
|
3967
3972
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3968
3973
|
const r=t(6183),n=t(3707)
|
|
3969
|
-
exports.def={name:"quick_replace",description:"
|
|
3974
|
+
exports.def={name:"quick_replace",description:"WHEN TO USE: trivial single-file edits only. For multi-file or feature work, spawn a coder via subagent_operations.\n\nReplace text in files or documents. Wraps the change in a request/task workflow that auto-completes.\n\nProvide an array of operations, each with path/documentId and replacements [{old, new}].\nSupports fuzzy matching (default: true) and match_mode ('unique' or 'all').\n\nRequires: title, description, comment, operations.",schema:r.QuickReplaceSchema,annotations:{title:"Quick Replace",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1},handler(e,t){return(0,n.handleQuickChange)(e,"replace",t.context,t.apiClient,t.logger,t.metrics,t.mcpServer)}}},7257(e,exports,t){"use strict"
|
|
3970
3975
|
Object.defineProperty(exports,"__esModule",{value:!0}),exports.def=void 0
|
|
3971
3976
|
const r=t(6183),n=t(3420)
|
|
3972
3977
|
exports.def={name:"get_task_information",description:"Get detailed information about a specific task.",schema:r.GetTaskInformationSchema,annotations:{title:"Get Task Information",readOnlyHint:!0},hidden:!0,readOnly:!0,handler(e,t){return(0,n.handleGetTaskInformation)(e,t.context,t.apiClient,t.logger,t.metrics)}}},7280(e,exports,t){"use strict"
|
|
@@ -4624,14 +4629,14 @@ const R=await d.ensureCorrectWorkspaceContext({taskPromoted:x.taskPromoted,reque
|
|
|
4624
4629
|
if(!R.success){if(R.isLockConflict)return{content:[{type:"text",text:"\u274c "+R.error}],isError:!0}
|
|
4625
4630
|
throw Error(R.error)}let P=!1
|
|
4626
4631
|
try{P=(await a.default.stat(E)).isDirectory()}catch{P=!1}I=d.FileOperationPhase.RECORD_CREATION,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4627
|
-
const{toolRecordId:M,localToolRecordId
|
|
4632
|
+
const{toolRecordId:M,localToolRecordId:$}=await d.createFileOperationRecords(C,S,r.projectId,b.recordType,_,{directoryExists:P,userComment:g},n,o,f,p,b.metricsPrefix,m)
|
|
4628
4633
|
w=M,k=M,I=b.fileOperationPhase,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4629
|
-
let
|
|
4634
|
+
let j=P
|
|
4630
4635
|
if(!P){await a.default.mkdir(E,{recursive:!0}),f.info("Successfully created directory "+_)
|
|
4631
4636
|
try{const e=c.default.join(E,".gitkeep")
|
|
4632
|
-
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n")
|
|
4637
|
+
await a.default.writeFile(e,"# This file makes the directory trackable by Git\n"),j=!0,f.info("Created .gitkeep file for Git tracking")}catch(e){f.warn("Failed to create .gitkeep file",{error:e instanceof Error?e.message:e+""}),j=!1}}const O=Date.now()-y
|
|
4633
4638
|
p.recordValue("create_directory_time",O),p.incrementCounter("create_directory_success",1),I=d.FileOperationPhase.GIT_COMMIT,p.incrementCounter("create_directory_phase",1,{phase:I})
|
|
4634
|
-
const D=`Create directory: ${_} - ${g||"Create directory"}`,A=!P
|
|
4639
|
+
const D=`Create directory: ${_} - ${g||"Create directory"}`,A=!P&&j?_+"/.gitkeep":_,F=await d.commitToGit(C,A,M,$,D,r,f,p,b.metricsPrefix)
|
|
4635
4640
|
I=d.FileOperationPhase.RECORD_UPDATE_SUCCESS,p.incrementCounter("create_directory_phase",1,{phase:I}),await d.updateFileOperationRecords(C,w,k,_,b.recordType,`Successfully ${P?"verified":"created"} directory: ${_}`,{status:"completed",commitHash:F.commitHash,previousCommitHash:F.previousCommitHash,directoryExists:P,isDirectory:!0,userComment:g},`Successfully ${P?"verified":"created"} directory: ${_}`,n,o,f,p,b.metricsPrefix)
|
|
4636
4641
|
const N=r.getCurrentBranchContext?await r.getCurrentBranchContext():{branch:null,requestId:null,isMain:!0}
|
|
4637
4642
|
return{content:[{type:"text",text:P?"Directory already exists":`Successfully created directory${F.commitHash?"\nCommit: "+F.commitHash.substring(0,8):""}${N.requestId&&!N.permanentBranch?"\nBranch: "+N.requestId:""}${R.lockAcquired&&R.lockedRequestId&&!N.permanentBranch?"\n\u{1f512} **Locked request:** "+R.lockedRequestId:""}`}]}}catch(t){if(e.taskId&&o)try{const n=t instanceof u.NotFoundError||t instanceof u.ValidationError||t instanceof h.ZodError
|
|
@@ -5208,39 +5213,39 @@ b.info("Replace in files batch operation",{taskId:S,operationCount:T.length,tota
|
|
|
5208
5213
|
const P=T.filter((e=>e.documentId)).map((e=>e.documentId))
|
|
5209
5214
|
if(P.length>0&&r.apiClient)try{await(0,f.ensureDocumentsNotLocked)(P,r.apiClient,b,c,"replace_in_files-documents")}catch(e){if(e instanceof g.ValidationError)return{content:[{type:"text",text:e.message}],isError:!0}
|
|
5210
5215
|
throw e}_=u.FileOperationPhase.TASK_VALIDATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5211
|
-
const M=T[0]
|
|
5212
|
-
let
|
|
5213
|
-
const O=await u.validateTaskId(S
|
|
5216
|
+
const M=T[0],$=M.documentId?"document:"+M.documentId:M.path
|
|
5217
|
+
let j=Date.now()
|
|
5218
|
+
const O=await u.validateTaskId(S,$,o,b,c,"replace_in_files")
|
|
5214
5219
|
Date.now()
|
|
5215
5220
|
const D=O?.requestId,A=T.some((e=>e.path))
|
|
5216
5221
|
let F=!1
|
|
5217
|
-
if(A&&D){
|
|
5218
|
-
const e=await u.validateWorkItemStates(S
|
|
5219
|
-
Date.now()
|
|
5220
|
-
const t=await u.autoPromoteTaskStatus(S,O.status,D,e.request?.status
|
|
5221
|
-
t.taskPromoted&&b.info("Auto-promoted task to in_progress",{taskId:S,requestId:D,previousStatus:O.status,newStatus:t.newTaskStatus}),Date.now()
|
|
5222
|
+
if(A&&D){j=Date.now()
|
|
5223
|
+
const e=await u.validateWorkItemStates(S,$,o,i,r,b,c,"replace_in_files")
|
|
5224
|
+
Date.now(),j=Date.now()
|
|
5225
|
+
const t=await u.autoPromoteTaskStatus(S,O.status,D,e.request?.status,$,o,i,b,c,"replace_in_files")
|
|
5226
|
+
t.taskPromoted&&b.info("Auto-promoted task to in_progress",{taskId:S,requestId:D,previousStatus:O.status,newStatus:t.newTaskStatus}),Date.now(),j=Date.now()
|
|
5222
5227
|
const n=await u.ensureCorrectWorkspaceContext({taskPromoted:t.taskPromoted,requestId:D,context:r,operation:"replace_in_files",logger:b,metrics:c,metricsPrefix:"replace_in_files"})
|
|
5223
5228
|
if(!n.success){if(n.isLockConflict)return{content:[{type:"text",text:"\u274c "+n.error}],isError:!0}
|
|
5224
5229
|
throw Error(n.error)}Date.now(),F=!0}if(P.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}
|
|
5225
|
-
throw e}
|
|
5230
|
+
throw e}j=Date.now()
|
|
5226
5231
|
const N=new Map
|
|
5227
5232
|
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:x,s=[]
|
|
5228
5233
|
for(const t of e.replacements){const r=(0,h.findMatches)(n,t.old,o,100,e.path)
|
|
5229
5234
|
s.push(...r)}if(s.length>0){const o=(0,y.calculateReplacementRegion)(n,s,t.fullPath)
|
|
5230
5235
|
b.info("\u{1f50d} Checking for external edits",{path:t.normalizedPath,affectedLines:o.lineRanges.map((e=>`${e.start}-${e.end}`)).join(", "),matchCount:s.length})
|
|
5231
5236
|
const i=await(0,w.detectExternalEdits)(r.git,o,b)
|
|
5232
|
-
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()
|
|
5237
|
+
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(),j=Date.now(),A&&r.git)try{b.debug("[REPLACE-IN-FILES] Checking for user changes before batch operation")
|
|
5233
5238
|
const e=await(0,m.commitUserChangesBeforeToolOperation)(r.git,"replace_in_files",{requestId:D,taskId:S,workspaceManager:r.workspaceManager},b,c)
|
|
5234
|
-
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()
|
|
5235
|
-
const{toolRecordId:L}=await u.createFileOperationRecords(S,D,r.projectId,"replace-in-files"
|
|
5236
|
-
C=L,Date.now()
|
|
5239
|
+
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(),j=Date.now(),_=u.FileOperationPhase.RECORD_CREATION,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5240
|
+
const{toolRecordId:L}=await u.createFileOperationRecords(S,D,r.projectId,"replace-in-files",$,{operationCount:T.length,totalReplacements:T.reduce(((e,t)=>e+t.replacements.length),0),globalFuzzyMatch:x,userComment:R},o,s,b,c,"replace_in_files",I)
|
|
5241
|
+
C=L,Date.now(),j=Date.now(),_=u.FileOperationPhase.STRING_REPLACEMENT,c.incrementCounter("replace_in_files_phase",1,{phase:_})
|
|
5237
5242
|
const z=[],B=[]
|
|
5238
5243
|
for(const e of T){const t=e.path?N.get(e.path):void 0,o=await n(e,x,r,0,0,t?.message,t?.debugInfo)
|
|
5239
|
-
z.push(o),o.successfulReplacements>0&&"file"===o.type&&o.path&&B.push(o.path)}Date.now()
|
|
5244
|
+
z.push(o),o.successfulReplacements>0&&"file"===o.type&&o.path&&B.push(o.path)}Date.now(),j=Date.now()
|
|
5240
5245
|
const H=T.filter((e=>e.path&&!e.documentId)).map((e=>({path:e.path}))),U=await u.handleMultiFileGitCommit(S,H,z,B.length,{operationType:"Replace in files",toolRecordId:L||C||"unknown",successField:"successfulReplacements",logger:b,metrics:c,metricsPrefix:"replace_in_files"},r),G=U.commitHash
|
|
5241
5246
|
Date.now(),Date.now()
|
|
5242
5247
|
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})))
|
|
5243
|
-
await s.updateToolRecord(C,{metadata:{path
|
|
5248
|
+
await s.updateToolRecord(C,{metadata:{path:$,status:0===V?"completed":"partial",operationCount:T.length,operations:Y,successfulFiles:Q,failedFiles:Z,successfulReplacements:J,failedReplacements:K,processingTime:Date.now()-v,userComment:R,...U.success&&U.commitHash&&{commitHash:U.commitHash,previousCommitHash:U.previousCommitHash||void 0}}})
|
|
5244
5249
|
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
|
|
5245
5250
|
let l="## Replace In Files - Batch Results\n\n"
|
|
5246
5251
|
if(o.workspaceManager)try{const e=o.workspaceManager.getCurrentContext(o.currentSessionId)
|