aws-runtime-bridge 1.9.183 → 1.9.185

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/dist/adapter/AcodeSdkAdapter.d.ts +30 -1
  3. package/dist/adapter/AcodeSdkAdapter.js +3 -3
  4. package/dist/adapter/ClaudeSdkAdapter.d.ts +3 -1
  5. package/dist/adapter/ClaudeSdkAdapter.js +3 -3
  6. package/dist/adapter/CodexSdkAdapter.d.ts +3 -1
  7. package/dist/adapter/CodexSdkAdapter.js +2 -2
  8. package/dist/adapter/OpencodeSdkAdapter.d.ts +3 -1
  9. package/dist/adapter/OpencodeSdkAdapter.js +3 -3
  10. package/dist/adapter/types.d.ts +7 -1
  11. package/dist/index.js +1 -1
  12. package/dist/routes/terminal.d.ts +13 -0
  13. package/dist/routes/terminal.js +28 -28
  14. package/dist/services/agent-ownership.d.ts +16 -0
  15. package/dist/services/agent-ownership.js +2 -2
  16. package/dist/services/auto-register.js +1 -1
  17. package/dist/services/bridge-pairing.js +1 -1
  18. package/dist/services/plugin-deployment.d.ts +14 -0
  19. package/dist/services/plugin-deployment.js +2 -2
  20. package/dist/services/plugin-manager.d.ts +3 -0
  21. package/dist/services/plugin-manager.js +4 -4
  22. package/dist/services/plugin-runtime.d.ts +10 -2
  23. package/dist/services/user-scope.d.ts +1 -0
  24. package/dist/services/user-scope.js +1 -1
  25. package/package/acode/dist/background-command-manager.d.ts +22 -0
  26. package/package/acode/dist/background-command-manager.js +5 -5
  27. package/package/acode/dist/built-in-file-tools.js +2 -2
  28. package/package/acode/dist/hibernation-journal.d.ts +67 -0
  29. package/package/acode/dist/hibernation-journal.js +2 -0
  30. package/package/acode/dist/index.d.ts +1 -0
  31. package/package/acode/dist/index.js +1 -1
  32. package/package/acode/dist/runtime-environment.d.ts +4 -1
  33. package/package/acode/dist/runtime-environment.js +3 -3
  34. package/package/aws-client-agent-mcp/dist/agent-client.d.ts +7 -0
  35. package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
  36. package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +2 -0
  37. package/package/aws-client-agent-mcp/dist/mcp-server.js +4 -4
  38. package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +8 -0
  39. package/package/aws-client-agent-mcp/dist/mcp-tools.js +20 -20
  40. package/package/aws-client-agent-mcp/dist/types.d.ts +5 -0
  41. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import{randomUUID as pt}from"node:crypto";import{promises as p,createReadStream as Q}from"node:fs";import gt from"node:os";import u from"node:path";import tt from"node:readline";import{runShellCommand as wt}from"./builtins/shellCommandRunner.js";import{createOutputEventCollector as yt}from"./builtins/commandOutputEvents.js";import{buildCommandOutputSpilloverContent as _t,COMMAND_OUTPUT_SPILLOVER_LINE_LIMIT as bt,countOutputLines as et,formatCommandOutputSpilloverStdout as kt,writeCommandArtifactFile as Et}from"./builtins/commandArtifacts.js";import{symbolsTool as vt}from"./built-in-symbols-tool.js";import{buildRevisionId as W,checkFileFreshForWrite as ot,createReadFileEntry as D,STALE_FILE_WRITE_REASON as it,toStateKey as C}from"./read-file-state.js";import{createListBackgroundCommandsTool as Pt,createKillBackgroundCommandTool as St,createReadBackgroundOutputTool as Mt}from"./background-command-tools.js";import{detectImageFormatFromBuffer as xt,formatBytes as M,imageMediaType as at,readImageDimensions as Tt,tryCompressImageWithSharp as Rt,tryResizeWithSharp as $t}from"./image-utils.js";const It=2e3,F=2e3,nt=50*1024,rt=4096,Ot=.3,Lt=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".tiff",".tif",".zip",".gz",".tar",".rar",".7z",".bz2",".xz",".lz",".exe",".dll",".so",".dylib",".bin",".o",".a",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".mp3",".mp4",".avi",".mov",".wav",".flv",".mkv",".ogg",".woff",".woff2",".ttf",".otf",".eot",".class",".jar",".war",".ear",".pyc",".pyo",".node",".sqlite",".db",".mdb",".wasm"]),At=new Set(["png","jpg","jpeg","gif","webp"]),st=20*1024*1024,B=10*1024*1024,Y=Math.floor(3.75*1024*1024),z=2e3,Ft=50*1024,Bt=100*1024,ct=15e3,Nt=process.env.ACODE_IMAGE_DEBUG==="1",Ct={Accept:"image/webp,image/png,image/jpeg,image/gif,*/*;q=0.8","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"},Ut=1e3,Wt=1024*1024,Dt=256*1024,zt=1e3,jt=new Set([".git","node_modules","dist","build",".next",".nuxt",".cache",".turbo",".output","coverage",".nyc_output"]),Ie={fileReadOutside:"allow",commandExecution:"allow",fileModification:"allow",fileModificationOutside:"allow"};async function N(t,e,o){if(!t)return;const i=t.getLevel(e);if(i==="deny")throw new Error(`Operation blocked by tool permission policy (${e} = deny). Explain this restriction to the user if needed.`);if(i==="ask"&&!await t.requestPermission(e,o))throw new Error(`Operation denied by the user (${e}). Do not retry the same operation without asking the user.`)}function R(t){return t.replace(/\\/g,"/")}async function G(t){try{return await p.access(t),!0}catch{return!1}}function qt(t,e){if(!e)return 0;let o=0,i=t.indexOf(e);for(;i>=0;)o+=1,i=t.indexOf(e,i+e.length);return o}function O(t,e,o){for(const i of e){const a=t[i];if(typeof a=="string")return a}throw new Error(`${o} is required`)}function L(t,e){for(const o of e){const i=t[o];if(typeof i=="string"&&i.trim())return i}}function j(t,e,o){for(const i of e){const a=t[i],n=typeof a=="number"?a:typeof a=="string"?Number(a):NaN;if(Number.isFinite(n)&&n>0)return Math.floor(n)}return o}function Kt(t,e,o){for(const i of e){const a=t[i],n=typeof a=="number"?a:typeof a=="string"?Number(a):NaN;if(Number.isFinite(n)&&n>0)return Math.floor(n);if(Number.isFinite(n)&&n===0)return 0}return o}function Xt(t){const e=t.compress;if(e==null)return"auto";if(typeof e=="boolean")return e;if(e==="auto")return"auto";if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid compress argument: ${JSON.stringify(e)} (expected true, false, or "auto")`)}async function lt(t){const e=u.extname(t).toLowerCase();if(Lt.has(e))return!0;const o=await p.open(t,"r");try{const i=Buffer.alloc(rt),{bytesRead:a}=await o.read(i,0,rt,0);if(a===0)return!1;const n=i.subarray(0,a);if(n.includes(0))return!0;let r=0;for(let c=0;c<a;c++){const s=n[c];(s<9||s>13&&s<32)&&r++}return r/a>Ot}finally{await o.close()}}function A(t,e){const o=u.resolve(e),i=u.relative(t,o);if(i.startsWith("..")||u.isAbsolute(i))throw new Error(`Target path is outside workspace: ${o}`);return o}function Yt(t,e){const o=u.resolve(String(t||"").trim()),i=U(String(e??"").trim());return`file:${(u.isAbsolute(i)?u.resolve(i):u.resolve(o,i)).replace(/\\/g,"/")}`}function q(t,e,o){return{key:Yt(t,e),access:o}}function K(t){const e=t.file_path??t.filePath;if(typeof e!="string")return null;const o=e.trim();return o.length>0?o:null}function U(t){return t==="~"||t.startsWith("~/")?u.join(gt.homedir(),t.slice(1)):t}async function Gt(t,e){const o=u.resolve(String(t||"").trim()),i=await p.realpath(o);if(!(await p.stat(i)).isDirectory())throw new Error(`Workspace path is not a directory: ${o}`);if(!e?.trim())return{workspaceRoot:i,cwd:i};const n=U(e.trim()),r=u.isAbsolute(n)?u.resolve(n):u.resolve(o,n),c=u.relative(o,r);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Command cwd is outside workspace: ${r}`);const s=A(i,await p.realpath(r));if(!(await p.stat(s)).isDirectory())throw new Error(`Command cwd is not a directory: ${s}`);return{workspaceRoot:i,cwd:s}}async function Ht(t){try{if((await p.lstat(t)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${t}`)}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)!=="ENOENT")throw e}}async function Vt(t,e){const o=await p.realpath(u.dirname(e));A(t,o);try{if((await p.lstat(e)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${e}`)}catch(i){if((typeof i=="object"&&i!==null?Reflect.get(i,"code"):void 0)!=="ENOENT")throw i}}async function ut(t,e){const o=u.resolve(String(t||"").trim()),i=await p.realpath(o);if(!(await p.stat(i)).isDirectory())throw new Error(`Workspace path is not a directory: ${o}`);const n=U(e.trim());if(!n)throw new Error("file_path is required");const r=u.isAbsolute(n)?u.resolve(n):u.resolve(o,n),c=u.relative(o,r);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Target path is outside workspace: ${r}`);return{workspaceRoot:i,requestedPath:r,targetPath:A(i,u.join(i,c))}}async function dt(t,e,o){const i=u.resolve(String(t||"").trim()),a=await p.realpath(i);if(!(await p.stat(a)).isDirectory())throw new Error(`Workspace path is not a directory: ${i}`);const r=U(e.trim());if(!r)throw new Error("file_path is required");const c=u.isAbsolute(r)?u.resolve(r):u.resolve(i,r),s=u.relative(i,c),d=await p.realpath(c).catch(()=>c),l=u.relative(a,d);if(s.startsWith("..")||u.isAbsolute(s)||l.startsWith("..")||u.isAbsolute(l)){if(!o)throw new Error(`Target path is outside workspace: ${c}`);return await N(o,"fileReadOutside",{path:c}),{workspaceRoot:a,requestedPath:c,targetPath:d}}return{workspaceRoot:a,requestedPath:c,targetPath:A(a,d)}}async function Jt(t,e){let o=u.dirname(t);for(;;){const i=u.dirname(o);try{return await p.realpath(o)}catch{if(i===o)return e;o=i}}}async function H(t,e,o,i){const a=u.resolve(String(t||"").trim()),n=await p.realpath(a);if(!(await p.stat(n)).isDirectory())throw new Error(`Workspace path is not a directory: ${a}`);const c=U(e.trim());if(!c)throw new Error("file_path is required");const s=u.isAbsolute(c)?u.resolve(c):u.resolve(a,c),d=u.relative(a,s),l=d.startsWith("..")||u.isAbsolute(d),m=await p.realpath(s).catch(async()=>Jt(s,n)),w=u.relative(n,m),g=w.startsWith("..")||u.isAbsolute(w);if(!l&&!g)return{workspaceRoot:n,requestedPath:s,targetPath:A(n,u.join(n,d))};if(!i)throw new Error(`Target path is outside workspace: ${s}`);await N(i,"fileModificationOutside",{operation:o,path:s});const f=await G(s);return{workspaceRoot:n,requestedPath:s,targetPath:f?m:s,outsideWorkspace:!0}}async function mt(t,e){const o=u.dirname(t.targetPath),i=!await G(o);await p.mkdir(o,{recursive:!0}),t.outsideWorkspace?await Ht(t.targetPath):await Vt(t.workspaceRoot,t.targetPath);const a=u.join(o,`.${u.basename(t.targetPath)}.${process.pid}.${pt()}.tmp`);try{await p.writeFile(a,e,"utf-8"),await p.rename(a,t.targetPath)}catch(n){throw await p.rm(a,{force:!0}),n}return{workspaceRoot:t.workspaceRoot,targetPath:t.targetPath,bytes:Buffer.byteLength(e,"utf-8"),createdParentDirectory:i,outsideWorkspace:t.outsideWorkspace===!0}}async function Zt(t,e){const o=await ut(t,e),i=A(o.workspaceRoot,await p.realpath(o.targetPath)),a=await p.stat(i);if(!a.isFile())throw new Error(`Path is not a file: ${i}`);return{workspaceRoot:o.workspaceRoot,targetPath:i,content:await p.readFile(i,"utf-8"),stat:{mtimeMs:a.mtimeMs,size:a.size}}}async function Qt(t){const e=await p.realpath(t).catch(()=>t),o=await p.stat(e);if(!o.isFile())throw new Error(`Path is not a file: ${e}`);return{workspaceRoot:u.dirname(e),targetPath:e,content:await p.readFile(e,"utf-8"),stat:{mtimeMs:o.mtimeMs,size:o.size}}}async function ht(t,e,o){if(t?.tracker)try{const i=await p.realpath(e),a=await p.stat(i);t.tracker.record(C(i),D(a,o,!1))}catch{}}async function te(t,e,o,i,a){const n=await dt(t,e,a),r=n.targetPath,c=await p.stat(r);if(!c.isFile())throw new Error(`Path is not a file: ${r}`);if(await lt(r))return{workspaceRoot:n.workspaceRoot,targetPath:r,content:"[Binary file, content skipped]",isBinary:!0,truncated:!1,totalLines:0,shownFromLine:0,shownToLine:0,mtimeMs:c.mtimeMs,sizeBytes:c.size};const s=Q(r,{encoding:"utf-8"}),d=tt.createInterface({input:s,crlfDelay:1/0});try{const l=[];let m=0,w=0,g=0,f=!1,h=!1;const k=o-1;for await(const _ of d){if(w++,m<k){m++;continue}if(l.length>=i){f=!0,m++;continue}let P=_;P.length>F&&(P=P.slice(0,F)+`... (line truncated to ${F} chars)`);const x=`${m+1}: ${P}`,b=Buffer.byteLength(x,"utf-8")+1;if(g+b>nt){h=!0;break}l.push(x),g+=b,m++}if(w>0&&l.length===0&&!f&&!h&&k>=w)throw new Error(`offset ${o} exceeds total line count ${w} in file: ${r}`);const y=l.length>0?o:0,E=l.length>0?o+l.length-1:0;let v;h?v=`Output capped at 50 KB. Showing lines ${y}-${E}. Use offset=${E+1} to continue.`:f?v=`Showing lines ${y}-${E} of ${w}. Use offset=${E+1} to continue.`:v=`End of file - total ${w} lines`;const S=l.length>0?l.join(`
1
+ import{randomUUID as pt}from"node:crypto";import{promises as p,createReadStream as Q}from"node:fs";import gt from"node:os";import u from"node:path";import tt from"node:readline";import{runShellCommand as wt}from"./builtins/shellCommandRunner.js";import{createOutputEventCollector as yt}from"./builtins/commandOutputEvents.js";import{buildCommandOutputSpilloverContent as _t,COMMAND_OUTPUT_SPILLOVER_LINE_LIMIT as bt,countOutputLines as et,formatCommandOutputSpilloverStdout as kt,writeCommandArtifactFile as vt}from"./builtins/commandArtifacts.js";import{symbolsTool as Et}from"./built-in-symbols-tool.js";import{buildRevisionId as D,checkFileFreshForWrite as ot,createReadFileEntry as z,STALE_FILE_WRITE_REASON as it,toStateKey as U}from"./read-file-state.js";import{createListBackgroundCommandsTool as Pt,createKillBackgroundCommandTool as St,createReadBackgroundOutputTool as xt}from"./background-command-tools.js";import{detectImageFormatFromBuffer as Mt,formatBytes as x,imageMediaType as nt,readImageDimensions as Tt,tryCompressImageWithSharp as Rt,tryResizeWithSharp as $t}from"./image-utils.js";const Lt=2e3,B=2e3,at=50*1024,rt=4096,It=.3,Ot=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".tiff",".tif",".zip",".gz",".tar",".rar",".7z",".bz2",".xz",".lz",".exe",".dll",".so",".dylib",".bin",".o",".a",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".mp3",".mp4",".avi",".mov",".wav",".flv",".mkv",".ogg",".woff",".woff2",".ttf",".otf",".eot",".class",".jar",".war",".ear",".pyc",".pyo",".node",".sqlite",".db",".mdb",".wasm"]),At=new Set(["png","jpg","jpeg","gif","webp"]),st=20*1024*1024,F=10*1024*1024,G=Math.floor(3.75*1024*1024),j=2e3,Bt=50*1024,Ft=100*1024,ct=15e3,Ct=process.env.ACODE_IMAGE_DEBUG==="1",Nt={Accept:"image/webp,image/png,image/jpeg,image/gif,*/*;q=0.8","User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"},Ut=1e3,Wt=1024*1024,Dt=256*1024,zt=1e3,jt=new Set([".git","node_modules","dist","build",".next",".nuxt",".cache",".turbo",".output","coverage",".nyc_output"]),Le={fileReadOutside:"allow",commandExecution:"allow",fileModification:"allow",fileModificationOutside:"allow"};async function C(t,e,i){if(!t)return;const o=t.getLevel(e);if(o==="deny")throw new Error(`Operation blocked by tool permission policy (${e} = deny). Explain this restriction to the user if needed.`);if(o==="ask"&&!await t.requestPermission(e,i))throw new Error(`Operation denied by the user (${e}). Do not retry the same operation without asking the user.`)}function R(t){return t.replace(/\\/g,"/")}async function H(t){try{return await p.access(t),!0}catch{return!1}}function qt(t,e){if(!e)return 0;let i=0,o=t.indexOf(e);for(;o>=0;)i+=1,o=t.indexOf(e,o+e.length);return i}function I(t,e,i){for(const o of e){const n=t[o];if(typeof n=="string")return n}throw new Error(`${i} is required`)}function O(t,e){for(const i of e){const o=t[i];if(typeof o=="string"&&o.trim())return o}}function q(t,e,i){for(const o of e){const n=t[o],a=typeof n=="number"?n:typeof n=="string"?Number(n):NaN;if(Number.isFinite(a)&&a>0)return Math.floor(a)}return i}function Kt(t,e,i){for(const o of e){const n=t[o],a=typeof n=="number"?n:typeof n=="string"?Number(n):NaN;if(Number.isFinite(a)&&a>0)return Math.floor(a);if(Number.isFinite(a)&&a===0)return 0}return i}function Xt(t){const e=t.compress;if(e==null)return"auto";if(typeof e=="boolean")return e;if(e==="auto")return"auto";if(e==="true")return!0;if(e==="false")return!1;throw new Error(`Invalid compress argument: ${JSON.stringify(e)} (expected true, false, or "auto")`)}async function lt(t){const e=u.extname(t).toLowerCase();if(Ot.has(e))return!0;const i=await p.open(t,"r");try{const o=Buffer.alloc(rt),{bytesRead:n}=await i.read(o,0,rt,0);if(n===0)return!1;const a=o.subarray(0,n);if(a.includes(0))return!0;let r=0;for(let c=0;c<n;c++){const s=a[c];(s<9||s>13&&s<32)&&r++}return r/n>It}finally{await i.close()}}function A(t,e){const i=u.resolve(e),o=u.relative(t,i);if(o.startsWith("..")||u.isAbsolute(o))throw new Error(`Target path is outside workspace: ${i}`);return i}function Yt(t,e){const i=u.resolve(String(t||"").trim()),o=W(String(e??"").trim());return`file:${(u.isAbsolute(o)?u.resolve(o):u.resolve(i,o)).replace(/\\/g,"/")}`}function K(t,e,i){return{key:Yt(t,e),access:i}}function X(t){const e=t.file_path??t.filePath;if(typeof e!="string")return null;const i=e.trim();return i.length>0?i:null}function W(t){return t==="~"||t.startsWith("~/")?u.join(gt.homedir(),t.slice(1)):t}async function Gt(t,e){const i=u.resolve(String(t||"").trim()),o=await p.realpath(i);if(!(await p.stat(o)).isDirectory())throw new Error(`Workspace path is not a directory: ${i}`);if(!e?.trim())return{workspaceRoot:o,cwd:o};const a=W(e.trim()),r=u.isAbsolute(a)?u.resolve(a):u.resolve(i,a),c=u.relative(i,r);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Command cwd is outside workspace: ${r}`);const s=A(o,await p.realpath(r));if(!(await p.stat(s)).isDirectory())throw new Error(`Command cwd is not a directory: ${s}`);return{workspaceRoot:o,cwd:s}}async function Ht(t){try{if((await p.lstat(t)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${t}`)}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)!=="ENOENT")throw e}}async function Vt(t,e){const i=await p.realpath(u.dirname(e));A(t,i);try{if((await p.lstat(e)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${e}`)}catch(o){if((typeof o=="object"&&o!==null?Reflect.get(o,"code"):void 0)!=="ENOENT")throw o}}async function ut(t,e){const i=u.resolve(String(t||"").trim()),o=await p.realpath(i);if(!(await p.stat(o)).isDirectory())throw new Error(`Workspace path is not a directory: ${i}`);const a=W(e.trim());if(!a)throw new Error("file_path is required");const r=u.isAbsolute(a)?u.resolve(a):u.resolve(i,a),c=u.relative(i,r);if(c.startsWith("..")||u.isAbsolute(c))throw new Error(`Target path is outside workspace: ${r}`);return{workspaceRoot:o,requestedPath:r,targetPath:A(o,u.join(o,c))}}async function dt(t,e,i){const o=u.resolve(String(t||"").trim()),n=await p.realpath(o);if(!(await p.stat(n)).isDirectory())throw new Error(`Workspace path is not a directory: ${o}`);const r=W(e.trim());if(!r)throw new Error("file_path is required");const c=u.isAbsolute(r)?u.resolve(r):u.resolve(o,r),s=u.relative(o,c),d=await p.realpath(c).catch(()=>c),l=u.relative(n,d);if(s.startsWith("..")||u.isAbsolute(s)||l.startsWith("..")||u.isAbsolute(l)){if(!i)throw new Error(`Target path is outside workspace: ${c}`);return await C(i,"fileReadOutside",{path:c}),{workspaceRoot:n,requestedPath:c,targetPath:d}}return{workspaceRoot:n,requestedPath:c,targetPath:A(n,d)}}async function Jt(t,e){let i=u.dirname(t);for(;;){const o=u.dirname(i);try{return await p.realpath(i)}catch{if(o===i)return e;i=o}}}async function V(t,e,i,o){const n=u.resolve(String(t||"").trim()),a=await p.realpath(n);if(!(await p.stat(a)).isDirectory())throw new Error(`Workspace path is not a directory: ${n}`);const c=W(e.trim());if(!c)throw new Error("file_path is required");const s=u.isAbsolute(c)?u.resolve(c):u.resolve(n,c),d=u.relative(n,s),l=d.startsWith("..")||u.isAbsolute(d),m=await p.realpath(s).catch(async()=>Jt(s,a)),w=u.relative(a,m),g=w.startsWith("..")||u.isAbsolute(w);if(!l&&!g)return{workspaceRoot:a,requestedPath:s,targetPath:A(a,u.join(a,d))};if(!o)throw new Error(`Target path is outside workspace: ${s}`);await C(o,"fileModificationOutside",{operation:i,path:s});const f=await H(s);return{workspaceRoot:a,requestedPath:s,targetPath:f?m:s,outsideWorkspace:!0}}async function mt(t,e){const i=u.dirname(t.targetPath),o=!await H(i);await p.mkdir(i,{recursive:!0}),t.outsideWorkspace?await Ht(t.targetPath):await Vt(t.workspaceRoot,t.targetPath);const n=u.join(i,`.${u.basename(t.targetPath)}.${process.pid}.${pt()}.tmp`);try{await p.writeFile(n,e,"utf-8"),await p.rename(n,t.targetPath)}catch(a){throw await p.rm(n,{force:!0}),a}return{workspaceRoot:t.workspaceRoot,targetPath:t.targetPath,bytes:Buffer.byteLength(e,"utf-8"),createdParentDirectory:o,outsideWorkspace:t.outsideWorkspace===!0}}async function Zt(t,e){const i=await ut(t,e),o=A(i.workspaceRoot,await p.realpath(i.targetPath)),n=await p.stat(o);if(!n.isFile())throw new Error(`Path is not a file: ${o}`);return{workspaceRoot:i.workspaceRoot,targetPath:o,content:await p.readFile(o,"utf-8"),stat:{mtimeMs:n.mtimeMs,size:n.size}}}async function Qt(t){const e=await p.realpath(t).catch(()=>t),i=await p.stat(e);if(!i.isFile())throw new Error(`Path is not a file: ${e}`);return{workspaceRoot:u.dirname(e),targetPath:e,content:await p.readFile(e,"utf-8"),stat:{mtimeMs:i.mtimeMs,size:i.size}}}async function ht(t,e,i){if(t?.tracker)try{const o=await p.realpath(e),n=await p.stat(o);t.tracker.record(U(o),z(n,i,!1))}catch{}}async function te(t,e,i,o,n){const a=await dt(t,e,n),r=a.targetPath,c=await p.stat(r);if(!c.isFile())throw new Error(`Path is not a file: ${r}`);if(await lt(r))return{workspaceRoot:a.workspaceRoot,targetPath:r,content:"[Binary file, content skipped]",isBinary:!0,truncated:!1,totalLines:0,shownFromLine:0,shownToLine:0,mtimeMs:c.mtimeMs,sizeBytes:c.size};const s=Q(r,{encoding:"utf-8"}),d=tt.createInterface({input:s,crlfDelay:1/0});try{const l=[];let m=0,w=0,g=0,f=!1,h=!1;const k=i-1;for await(const P of d){if(w++,m<k){m++;continue}if(l.length>=o){f=!0,m++;continue}let y=P;y.length>B&&(y=y.slice(0,B)+`... (line truncated to ${B} chars)`);const S=`${m+1}: ${y}`,b=Buffer.byteLength(S,"utf-8")+1;if(g+b>at){h=!0;break}l.push(S),g+=b,m++}if(w>0&&l.length===0&&!f&&!h&&k>=w)throw new Error(`offset ${i} exceeds total line count ${w} in file: ${r}`);const _=l.length>0?i:0,v=l.length>0?i+l.length-1:0;let E;h?E=`Output capped at 50 KB. Showing lines ${_}-${v}. Use offset=${v+1} to continue.`:f?E=`Showing lines ${_}-${v} of ${w}. Use offset=${v+1} to continue.`:E=`End of file - total ${w} lines`;const $=l.length>0?l.join(`
2
2
  `)+`
3
- `+v:v;return{workspaceRoot:n.workspaceRoot,targetPath:r,content:S,isBinary:!1,truncated:f||h,totalLines:h?-1:w,shownFromLine:y,shownToLine:E,mtimeMs:Math.trunc(c.mtimeMs),sizeBytes:c.size}}finally{d.close(),s.destroy()}}function X(t){return/^https?:\/\//i.test(t)}function ee(t){try{const e=new URL(t);return`${e.origin}${e.pathname}`}catch{return"(invalid-url)"}}function I(t,e){if(!Nt)return;const o=e?` ${JSON.stringify(e)}`:"";console.error(`[acode:image] ${t}${o}`)}function oe(t){return!t||t.startsWith("image/")||t==="application/octet-stream"||t==="binary/octet-stream"?!1:t.startsWith("text/")||t==="application/json"||t.endsWith("+json")||t==="application/xml"||t.endsWith("+xml")}async function ie(t){let e;try{e=new URL(t)}catch{throw new Error(`Invalid image URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsupported image URL protocol: ${e.protocol} (only http/https)`);const o=ee(t),i=Date.now();I("url fetch start",{url:o,timeoutMs:ct});let a;try{a=await fetch(t,{headers:Ct,signal:AbortSignal.timeout(ct)})}catch(m){const w=m instanceof Error?m.message:String(m);throw I("url fetch failed",{url:o,reason:w,elapsedMs:Date.now()-i}),new Error(`Image URL fetch failed: ${t} (${w})`)}if(!a.ok)throw I("url fetch failed",{url:o,status:a.status,elapsedMs:Date.now()-i}),new Error(`Image URL fetch failed: ${t} (HTTP ${a.status})`);const n=(a.headers.get("content-type")||"").split(";")[0]?.trim().toLowerCase()||"";if(oe(n))throw I("url fetch rejected: non-image content-type",{url:o,contentType:n,elapsedMs:Date.now()-i}),new Error(`URL did not return an image (content-type: ${n}): ${t}`);const r=Number(a.headers.get("content-length")||"");if(I("url fetch response",{url:o,status:a.status,contentType:n||"(none)",contentLength:Number.isFinite(r)?r:null,elapsedMs:Date.now()-i}),Number.isFinite(r)&&r>B)throw I("url fetch rejected: too large",{url:o,contentLength:r,elapsedMs:Date.now()-i}),new Error(`Image too large to fetch: ${t} (${M(r)} > ${M(B)})`);const c=a.body;if(!c){const m=await a.arrayBuffer();if(m.byteLength>B)throw I("url fetch rejected: too large",{url:o,bytes:m.byteLength,elapsedMs:Date.now()-i}),new Error(`Image too large to fetch: ${t} (${M(m.byteLength)} > ${M(B)})`);return I("url fetch done",{url:o,bytes:m.byteLength,elapsedMs:Date.now()-i}),{buffer:Buffer.from(m),contentType:n}}const s=c.getReader(),d=[];let l=0;for(;;){const{done:m,value:w}=await s.read();if(m)break;if(w){if(l+=w.byteLength,l>B)throw s.cancel().catch(()=>{}),I("url fetch rejected: too large",{url:o,bytes:l,elapsedMs:Date.now()-i}),new Error(`Image too large to fetch: ${t} (${M(l)} > ${M(B)})`);d.push(Buffer.from(w))}}return I("url fetch done",{url:o,bytes:l,elapsedMs:Date.now()-i}),{buffer:Buffer.concat(d,l),contentType:n}}async function ae(t,e,o,i="auto",a){let n,r,c;if(X(e)){const b=await ie(e);n=b.buffer,c=b.contentType,r=e}else{const $=(await dt(t,e,o)).targetPath,T=await p.stat($);if(!T.isFile())throw new Error(`Path is not a file: ${$}`);if(T.size>st)throw new Error(`Image file too large to read: ${R($)} (${M(T.size)} > ${M(st)}). Downscale it first.`);n=await p.readFile($),r=R($),a?.tracker&&a.tracker.record(C($),D(T,null,!0))}if(n.length===0)throw new Error(`Image file is empty: ${r}`);const s=xt(n);if(!s)throw I("image decode failed",{path:r,bytes:n.length,contentType:c||"(local file)"}),new Error(c!==void 0?`URL did not return a supported image (content-type: ${c||"unknown"}, unrecognized format): ${r}`:`Unsupported or corrupt image (unrecognized format): ${r}`);const d=Tt(n);let l=s,m=n,w=d?.width,g=d?.height,f=null;if(i!==!1){const b=await Rt(n,s,{normalMaxBytes:Ft,clearMaxBytes:Bt});b?.compressed&&(m=b.buffer,l=b.mediaType,w=b.width,g=b.height,f={level:b.level,originalSize:b.originalSize})}let h=!1;const k=await $t(m,l,{maxWidth:z,maxHeight:z,maxBytes:Y});if(k)m=k.buffer,l=k.mediaType,w=k.width,g=k.height,h=k.changed;else if(m.length>Y)throw new Error(`Image too large to inline: ${r} (${M(m.length)} > ${M(Y)}). Downscale it first, e.g. via Bash: magick "${e}" -resize ${z}x${z} "${e}". Installing sharp enables automatic downscaling.`);const y=w&&g?`${w}x${g}`:"unknown dimensions",E=h&&d&&d.width!==w?` (resized from ${d.width}x${d.height})`:h?" (resized)":"",v=f!==null?f.level:null,S=f!==null?Math.max(1,Math.round((1-m.length/f.originalSize)*100)):0,_=f!==null?`${M(m.length)} (compressed from ${M(f.originalSize)}, saved ${S}%, ${v} level)`:M(m.length),P=`[Image: ${r}, ${y}${E}, ${_}]`,x=X(e)?u.basename(new URL(e).pathname)||"image":u.basename(r);return{ok:!0,filePath:r,content:P,isBinary:!1,image:{mediaType:at(l),width:w??null,height:g??null,originalWidth:d?.width??null,originalHeight:d?.height??null,resized:h,size:m.length,compressed:f!==null,compressionLevel:v,compressionRatio:f!==null?Math.round((1-m.length/f.originalSize)*100)/100:null,originalSize:n.length},attachments:[{type:"image",name:x,mediaType:at(l),base64Data:m.toString("base64")}]}}function ft(t){let e="",o=0;for(;o<t.length;){const i=t[o];if(i==="*")e+="[^/]*";else if(i==="?")e+="[^/]";else if(i==="{"){const a=t.indexOf("}",o);if(a>=0){const n=t.slice(o+1,a);e+=`(${n.split(",").join("|")})`,o=a}else e+="\\{"}else if(i==="["){const a=t.indexOf("]",o);a>=0?(e+=t.slice(o,a+1),o=a):e+="\\["}else"+^$.()|\\".includes(i)?e+="\\"+i:e+=i;o++}return new RegExp(`^${e}$`)}async function ne(t,e,o,i){const a=[];async function n(r){if(a.length>=i)return;const c=await p.readdir(r,{withFileTypes:!0});for(const s of c){if(a.length>=i)return;if(s.name.startsWith(".")&&s.isDirectory())continue;const d=u.join(r,s.name);if(s.isDirectory()){if(jt.has(s.name))continue;await n(d)}else if(s.isFile()){if(e&&!e.test(s.name)||o&&o.test(s.name))continue;a.push(d)}}}return await n(t),a}async function re(t,e,o){if((await p.stat(t)).size>Wt)return{matches:[],count:0};if(await lt(t))return{matches:[],count:0};const a=u.relative(e,t).replace(/\\/g,"/"),n=[];let r=0;const c=Q(t,{encoding:"utf-8"}),s=tt.createInterface({input:c,crlfDelay:1/0});try{let d=0;for await(const l of s)if(d++,o.regex.test(l)){if(r++,o.collectContent){let m=l;if(m.length>F&&(m=m.slice(0,F)+`... (line truncated to ${F} chars)`),n.push({file:a,line:d,content:m}),n.length>=o.maxResults)break}if(o.stopOnFirstMatch)break}}finally{s.close(),c.destroy()}return{matches:n,count:r}}const se=12*60*6e4,ce=3*6e4,le=6e4,ue=10*6e4;function de(t,e,o,i){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",concurrencyMode:"write",resourceKeys:a=>{const n=K(a);return n?[q(t,n,"write")]:[]},description:"Create or overwrite a UTF-8 text file inside the current workspace. Parent directories are created automatically.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to write."},content:{type:"string",description:"Complete UTF-8 file content."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","content"],additionalProperties:!1},async execute(a){const n=O(a,["file_path","filePath"],"file_path"),r=O(a,["content"],"content"),c=L(a,["reason"]),s=await H(t,n,"write",o);await N(o,"fileModification",{operation:"write",path:s.targetPath});const d=await G(s.targetPath),l=d?await p.readFile(s.targetPath,"utf-8").catch(()=>null):null,m=d?await p.realpath(s.targetPath).catch(()=>s.targetPath):s.targetPath;let w=null;if(i?.enabled&&d){const f=await p.stat(m);w=W(f.mtimeMs,f.size);const h=ot(i.tracker,C(m),f,l);if(!h.ok)throw new Error(h.reason)}if(i?.enabled&&w){const f=await p.stat(m).catch(()=>null);if(!f||W(f.mtimeMs,f.size)!==w)throw new Error(it)}const g=await mt(s,r);if(await ht(i,g.targetPath,r),e&&!g.outsideWorkspace){const f=u.relative(g.workspaceRoot,g.targetPath).replace(/\\/g,"/");await e({filePath:f,operation:d?"UPDATE":"CREATE",beforeContent:l,afterContent:r,reason:c})}return{ok:!0,filePath:R(g.targetPath),bytes:g.bytes,createdParentDirectory:g.createdParentDirectory}}}}const me=15*1024;function Oe(t){if(typeof t!="object"||t===null)return;const e=Reflect.get(t,"editFailureSnapshot");if(typeof e=="object"&&e!==null&&typeof Reflect.get(e,"content")=="string")return e}function he(t,e,o,i){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",concurrencyMode:"write",resourceKeys:a=>{const n=K(a);return n?[q(t,n,"write")]:[]},description:"Replace exactly one occurrence of old_string with new_string in a UTF-8 workspace text file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to edit."},old_string:{type:"string",description:"Existing text to replace. Must occur exactly once."},new_string:{type:"string",description:"Replacement text."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","old_string","new_string"],additionalProperties:!1},async execute(a){const n=O(a,["file_path","filePath"],"file_path"),r=O(a,["old_string","oldString"],"old_string"),c=O(a,["new_string","newString"],"new_string"),s=L(a,["reason"]);if(!r)throw new Error("old_string must not be empty");const d=await H(t,n,"edit",o);await N(o,"fileModification",{operation:"edit",path:d.targetPath});const l=d.outsideWorkspace?await Qt(d.targetPath):await Zt(t,n),m=C(l.targetPath);let w;try{if(i?.enabled){const h=ot(i.tracker,m,l.stat,l.content);if(!h.ok)throw new Error(h.reason)}const f=qt(l.content,r);if(f===0)throw new Error("old_string was not found in file");if(f>1)throw new Error(`old_string occurs ${f} times; provide a unique match`);if(w=l.content.replace(r,c),i?.enabled){const h=await p.stat(l.targetPath).catch(()=>null);if(!h||W(h.mtimeMs,h.size)!==W(l.stat.mtimeMs,l.stat.size))throw new Error(it)}}catch(f){throw f instanceof Error&&l.stat.size<=me&&(i?.tracker.record(m,D(l.stat,l.content,!1)),f.editFailureSnapshot={path:R(l.targetPath),bytes:l.stat.size,content:l.content}),f}const g=await mt(d,w);if(await ht(i,g.targetPath,w),e&&!g.outsideWorkspace){const f=u.relative(g.workspaceRoot,g.targetPath).replace(/\\/g,"/");await e({filePath:f,operation:"UPDATE",beforeContent:l.content,afterContent:w,reason:s})}return{ok:!0,filePath:R(g.targetPath),bytes:g.bytes}}}}function fe(t,e,o){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",concurrencyMode:"write",resourceKeys:i=>{const a=K(i);return a?[q(t,a,"write")]:[]},description:"Delete a file inside the current workspace. Returns an error if the file does not exist.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to delete."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path"],additionalProperties:!1},async execute(i){const a=O(i,["file_path","filePath"],"file_path"),n=L(i,["reason"]),r=await H(t,a,"delete",o);await N(o,"fileModification",{operation:"delete",path:r.targetPath});const c=r.outsideWorkspace?await p.realpath(r.targetPath).catch(()=>r.targetPath):A(r.workspaceRoot,await p.realpath(r.targetPath).catch(()=>r.targetPath)),s=await p.stat(c).catch(()=>null);if(!s)throw new Error(`File does not exist: ${c}`);if(!s.isFile())throw new Error(`Path is not a file: ${c}`);const d=await p.readFile(c,"utf-8").catch(()=>null);if(await p.rm(c,{force:!0}),e&&!r.outsideWorkspace){const l=u.relative(r.workspaceRoot,c).replace(/\\/g,"/");await e({filePath:l,operation:"DELETE",beforeContent:d,afterContent:null,reason:n})}return{ok:!0,filePath:R(c),deleted:!0}}}}function pe(t,e,o){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",concurrencyMode:"read",resourceKeys:i=>{const a=K(i);return!a||X(a)?[]:[q(t,a,"read")]},description:"Read a UTF-8 text file inside the current workspace. Returns content with line numbers in the format '<line>: <content>'. Supports offset (1-indexed line number to start from) and limit (max lines to return, default 2000). Output is capped at 2000 lines or 50 KB, whichever is reached first. Individual lines longer than 2000 characters are truncated. Avoid tiny repeated slices (e.g. 30-line chunks); read a larger window if more context is needed. Images (.png/.jpg/.jpeg/.gif/.webp) and http(s) image URLs are also supported: the image is inlined into the conversation so you can see it (requires a model with image input). When an image is already available at an http(s) URL (including signed URLs with query strings), pass the URL directly as file_path \u2014 the runtime fetches it in memory and never writes it to disk; do NOT download it with Bash/curl first. offset/limit are ignored for images. By default (compress='auto') images are compressed before inlining using a tiered ladder that judges by the compressed result, not the original size: lossless first (pixel-exact, dimensions preserved), then high-quality lossy downscaling only if the lossless result is still over 50 KB (normal level), then more aggressive downscaling if still over 100 KB (clear level). When compression applies, the result reports the compression level, compressed size, and compression ratio (e.g. saved 80%). Pass compress=true to also attempt compression, or compress=false to disable it (images exceeding the hard 2000px / 3.75MB inline limits are still auto-downscaled when sharp is available). You may issue several read_file calls in ONE message; independent reads run in parallel.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to read. For images, also accepts an http(s) URL (including signed URLs with query strings), which is fetched in memory without writing to disk."},offset:{type:"number",description:"Line number to start reading from (1-indexed). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to return. Defaults to 2000."},compress:{anyOf:[{type:"boolean"},{type:"string",enum:["auto"]}],description:'Image compression mode (ignored for text files). "auto" (default): compress with a tiered ladder driven by the compressed result \u2014 lossless, then high-quality downscale if still >50 KB, then more aggressive if still >100 KB. true: same as auto. false: skip tiered compression entirely (hard inline limits still apply).'}},required:["file_path"],additionalProperties:!1},async execute(i){const a=O(i,["file_path","filePath"],"file_path"),n=u.extname(a).toLowerCase().slice(1);if(X(a)||At.has(n))return await ae(t,a,e,Xt(i),o);const r=j(i,["offset"],1),c=j(i,["limit"],It),s=await te(t,a,r,c,e);if(o?.tracker){let d=null,l=r!==1||s.truncated||s.isBinary;l||(d=await p.readFile(s.targetPath,"utf-8").catch(()=>null),(d==null||d.length>nt)&&(d=null,l=!0)),o.tracker.record(C(s.targetPath),D({mtimeMs:s.mtimeMs,size:s.sizeBytes},d,l))}return{ok:!0,filePath:R(s.targetPath),content:s.content,isBinary:s.isBinary,truncated:s.truncated,totalLines:s.totalLines,shownFromLine:s.shownFromLine,shownToLine:s.shownToLine}}}}function ge(t,e,o,i){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",concurrencyMode:"write",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${u.resolve(String(t||"").trim()).replace(/\\/g,"/")}`,access:"write"}],description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded total timeout (timeout_ms) measured from command start \u2014 by default 3 minutes, after which the process is force-terminated; timeout_ms can raise this (up to 12 hours) or set 0 to disable. The tool returns stdout, stderr, exit code, and (if converted to background) a task_id. By default (wait_seconds omitted or -1) the command runs in the FOREGROUND and streams output in real time; if the 5-minute adapter watchdog fires while it is still running, the command is moved to the BACKGROUND and the tool returns a task_id plus an explanation (backgrounded=true, reason=watchdog_timeout). The background command stays bound by the same total timeout (timeout_ms, default 3 minutes, still measured from command start) and can be managed via await_complete / list_background_commands / read_background_output / kill_background_command. For immediate backgrounding use wait_seconds=0, or wait_seconds=n>0 to wait n seconds then background.",inputSchema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute."},cwd:{type:"string",description:"Optional workspace-relative working directory. Defaults to the workspace root."},timeout_ms:{type:"number",description:"Optional total command timeout in milliseconds, measured from command start. Defaults to 180000 (3 minutes) and is capped at 43200000 (12 hours). Set 0 to disable the timeout entirely (run until finished or killed)."},inactivity_timeout_ms:{type:"number",description:"Optional no-output timeout in milliseconds. Defaults to 60000 and is capped at 600000."},wait_seconds:{type:"number",description:"How to wait for the command to finish. Omitted values (or -1, the default): run in the FOREGROUND until completion; if the 5-minute adapter watchdog fires first, the command is moved to the background and a task_id is returned (backgrounded=true, reason=watchdog_timeout). 0: spawn and immediately execute in the background, return task_id. n>0: wait up to n seconds; if still running, move to the background and return task_id. The command remains bound by the total timeout (timeout_ms, default 3 minutes, measured from command start) whether foreground or background; inactivity_timeout_ms is ignored once backgrounded.",minimum:-1},description:{type:"string",description:"Short reason for running this command (what it does and why it is needed), shown to the user in the background commands panel. Always provide a concise reason, e.g. 'Start local dev server for manual verification'."}},required:["command"],additionalProperties:!1},async execute(a,n){const r=O(a,["command"],"command").trim();if(!r)throw new Error("command must not be empty");const c=Kt(a,["timeout_ms","timeoutMs"],ce),s=c===0?0:Math.min(c,se),d=j(a,["inactivity_timeout_ms","inactivityTimeoutMs"],le),l=Math.min(d,ue),m=L(a,["cwd"]),w=L(a,["description"]),g=await Gt(t,m);await N(i,"commandExecution",{command:r,cwd:R(g.cwd)});const f=a.wait_seconds,k=typeof f=="number"&&Number.isFinite(f)?f:-1;if(o)return await we({deps:o,command:r,agentId:e,workspaceRoot:g.workspaceRoot,cwd:g.cwd,timeoutMs:s,inactivityTimeoutMs:l,waitSeconds:k,description:w,onOutput:n?.onOutput,settleSignal:n?.settleSignal});const y=await wt({commandText:r,agentId:e,workspaceRoot:g.workspaceRoot,cwd:g.cwd,timeoutMs:s,inactivityTimeoutMs:l,onOutput:n?.onOutput,watchdogSignal:n?.settleSignal}),E={ok:y.exitCode===0&&!y.timedOut,tool:"Bash",command:r,cwd:R(g.cwd),exitCode:y.exitCode,signal:y.signal,timedOut:y.timedOut,inactivityTimedOut:y.inactivityTimedOut,watchdogInterrupted:y.watchdogInterrupted,timeoutMs:s,inactivityTimeoutMs:l,durationMs:y.durationMs,outputSpilled:y.outputSpilled,outputFilePath:y.outputFilePath,outputLineCount:y.outputLineCount,commandFilePath:y.commandFilePath,commandLineCount:y.commandLineCount,stdout:y.stdout,stderr:y.stderr};return y.watchdogInterrupted?{...E,message:"Command was interrupted by the adapter watchdog after ~5 minutes of synchronous (foreground) execution. Only the partial output produced so far is returned above"+(y.outputFilePath?` (full output spilled to "${y.outputFilePath}"; read it if you need more)`:"")+". For long-running commands, re-run with wait_seconds=0 (or n>0) to execute in the background, then manage via await_complete / list_background_commands / read_background_output / kill_background_command."}:E}}}async function we(t){const{deps:e,command:o,agentId:i,workspaceRoot:a,cwd:n,timeoutMs:r,inactivityTimeoutMs:c,waitSeconds:s,description:d,onOutput:l,settleSignal:m}=t,w=l?yt({cwd:n,commandLineCount:0,onOutput:l}):void 0;let g=!!w;const f=()=>{g&&(g=!1,w?.close())};try{const{taskId:h,completion:k}=e.manager.startCommand({commandText:o,agentId:i,workspaceRoot:a,cwd:n,description:d,timeoutMs:r,inactivityTimeoutMs:c,onOutput:g?S=>{g&&w?.push(S.stream,S.text)}:void 0,onCompleted:e.emitCompleted});if(s===0)return e.manager.disableInactivityTimeout(i,h),await e.manager.markBackgrounded(i,h).catch(()=>{}),f(),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:h,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, read_background_output(task_id="${h}", mode="tail") to read output, list_background_commands to view all, or kill_background_command(task_id="${h}") to stop.`};const y=s===-1?0:Math.max(0,Math.floor(s*1e3)),E=[k];let v;s!==-1&&E.push(new Promise(S=>{v=setTimeout(()=>S("__timeout__"),y),v.unref?.()})),m&&E.push(m.then(()=>"__settle__"));try{const S=await Promise.race(E);if(S==="__settle__")return e.manager.disableInactivityTimeout(i,h),await e.manager.markBackgrounded(i,h).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:h,status:"backgrounded",reason:"watchdog_timeout",waitedMs:y,message:`Command still running after watchdog timeout; moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, read_background_output(task_id="${h}", mode="tail") to read output, or kill_background_command(task_id="${h}") to stop.`};if(S==="__timeout__")return e.manager.disableInactivityTimeout(i,h),await e.manager.markBackgrounded(i,h).catch(()=>{}),{ok:!0,tool:"Bash",command:o,backgrounded:!0,taskId:h,status:"backgrounded",reason:"timeout",waitedMs:y,message:`Command still running after ${s}s; moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, or read_background_output(task_id="${h}", mode="tail") / kill_background_command(task_id="${h}") to inspect.`};const _=S;let P=_.stdout,x=_.stderr,b=_.outputSpilled,$=_.outputFilePath;if(!b&&et(`${_.stdout}${_.stderr}`)>bt){const T=await Et(i,"cmd","out",_t({commandText:o,commandFilePath:_.commandFilePath,commandLineCount:_.commandLineCount,cwd:n,startedAt:new Date(Date.now()-_.durationMs),endedAt:new Date,exitCode:_.exitCode,signal:_.signal??null,timedOut:_.timedOut,inactivityTimedOut:_.inactivityTimedOut??!1,stdout:P,stderr:x}));P=kt(R(T),et(`${_.stdout}${_.stderr}`)),b=!0,$=R(T)}return{ok:_.exitCode===0&&!_.timedOut,tool:"Bash",command:o,backgrounded:!1,taskId:h,exitCode:_.exitCode,signal:_.signal,timedOut:_.timedOut,inactivityTimedOut:_.inactivityTimedOut,timeoutMs:_.timeoutMs,inactivityTimeoutMs:_.inactivityTimeoutMs,durationMs:_.durationMs,outputSpilled:b,outputFilePath:$,outputLineCount:_.outputLineCount,commandFilePath:_.commandFilePath,commandLineCount:_.commandLineCount,stdout:P,stderr:x}}finally{v&&clearTimeout(v),f()}}catch(h){if(h?.code==="too_many_tasks"||h?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:o,backgrounded:!1,status:"not_executed",error:h.code,message:`Command was NOT executed: ${h.message}. Wait for some background tasks to finish/cleanup (per-agent limit 16, global 256), or reduce concurrent background commands, then retry.`};throw h}}function ye(t){return{kind:"builtin",toolName:"grep",exposedName:"grep",concurrencyMode:"read",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${u.resolve(String(t||"").trim()).replace(/\\/g,"/")}`,access:"read"}],description:"Search file contents using regular expressions within the workspace. Returns matched lines with file paths and line numbers. Supports include/exclude glob patterns, case-insensitive matching, and three output modes (content, files_with_matches, count). Searches recursively through directories, skipping binary files, hidden directories, and common build/dependency directories (node_modules, .git, dist, etc.). You may issue several grep/read_file calls in ONE message; independent searches run in parallel.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Regular expression pattern to search for in file contents."},path:{type:"string",description:"Workspace-relative file or directory path to search in. Defaults to the workspace root."},include:{type:"string",description:"Glob pattern to filter files by name (e.g. '*.ts', '*.{js,ts}'). Only matching files are searched."},exclude:{type:"string",description:"Glob pattern to exclude files by name (e.g. '*.test.ts'). Matching files are skipped."},case_insensitive:{type:"boolean",description:"Case-insensitive matching. Default false."},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output format: 'content' returns matched lines with line numbers (default), 'files_with_matches' returns only file paths with matches, 'count' returns match counts per file."},max_results:{type:"number",description:"Maximum number of matched lines to return (content mode). Default 1000."}},required:["pattern"],additionalProperties:!1},async execute(e){const o=O(e,["pattern"],"pattern"),i=L(e,["path"])||".",a=L(e,["include"]),n=L(e,["exclude"]),r=e.case_insensitive===!0,c=(()=>{const b=e.output_mode;return b==="files_with_matches"||b==="count"?b:"content"})(),s=j(e,["max_results"],zt),d=r?"i":"";let l;try{l=new RegExp(o,d)}catch(b){throw new Error(`Invalid regex pattern: ${b instanceof Error?b.message:String(b)}`)}const m=a?ft(a):null,w=n?ft(n):null,g=await ut(t,i),f=A(g.workspaceRoot,await p.realpath(g.targetPath)),h=await p.stat(f);let k;if(h.isFile())k=[f];else if(h.isDirectory())k=await ne(f,m,w,Ut);else throw new Error(`Path is neither a file nor a directory: ${f}`);const y=[],E=[],v=[];let S=0,_=0,P=!1;for(const b of k){if(c==="content"&&y.length>=s){P=!0;break}const $={regex:l,maxResults:c==="content"?s-y.length:Number.MAX_SAFE_INTEGER,collectContent:c==="content",stopOnFirstMatch:c==="files_with_matches"},T=await re(b,g.workspaceRoot,$);if(T.count>0){const V=u.relative(g.workspaceRoot,b).replace(/\\/g,"/");if(v.push(V),S+=T.count,c==="content"){for(const J of T.matches){const Z=Buffer.byteLength(J.content,"utf-8")+64;if(_+Z>Dt){P=!0;break}_+=Z,y.push(J)}if(P)break;if(y.length>=s){P=!0;break}}else c==="count"&&E.push({file:V,count:T.count})}}const x={ok:!0,tool:"grep",pattern:o,searchPath:R(g.targetPath),outputMode:c,filesSearched:k.length,filesMatched:v.length,totalMatches:S,truncated:P};return c==="content"?x.matches=y:c==="files_with_matches"?x.matches=v:x.matches=E,x}}}function Le(t,e,o,i,a,n){const r=e||"unknown",c=[pe(t,a,n),de(t,o,a,n),he(t,o,a,n),fe(t,o,a),ye(t),ge(t,r,i,a),vt(t)];return i&&c.push(Pt(r,i),St(r,i),Mt(r,i)),c}export{Ie as DEFAULT_TOOL_PERMISSION_POLICY,me as EDIT_FAILURE_SNAPSHOT_MAX_BYTES,Yt as buildFileResourceKey,Le as createBuiltInFileTools,A as ensureInsideWorkspace,q as fileResourceClaim,Oe as getEditFailureSnapshot,ut as resolveWorkspaceTarget};
3
+ `+E:E;return{workspaceRoot:a.workspaceRoot,targetPath:r,content:$,isBinary:!1,truncated:f||h,totalLines:h?-1:w,shownFromLine:_,shownToLine:v,mtimeMs:Math.trunc(c.mtimeMs),sizeBytes:c.size}}finally{d.close(),s.destroy()}}function Y(t){return/^https?:\/\//i.test(t)}function ee(t){try{const e=new URL(t);return`${e.origin}${e.pathname}`}catch{return"(invalid-url)"}}function L(t,e){if(!Ct)return;const i=e?` ${JSON.stringify(e)}`:"";console.error(`[acode:image] ${t}${i}`)}function oe(t){return!t||t.startsWith("image/")||t==="application/octet-stream"||t==="binary/octet-stream"?!1:t.startsWith("text/")||t==="application/json"||t.endsWith("+json")||t==="application/xml"||t.endsWith("+xml")}async function ie(t){let e;try{e=new URL(t)}catch{throw new Error(`Invalid image URL: ${t}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`Unsupported image URL protocol: ${e.protocol} (only http/https)`);const i=ee(t),o=Date.now();L("url fetch start",{url:i,timeoutMs:ct});let n;try{n=await fetch(t,{headers:Nt,signal:AbortSignal.timeout(ct)})}catch(m){const w=m instanceof Error?m.message:String(m);throw L("url fetch failed",{url:i,reason:w,elapsedMs:Date.now()-o}),new Error(`Image URL fetch failed: ${t} (${w})`)}if(!n.ok)throw L("url fetch failed",{url:i,status:n.status,elapsedMs:Date.now()-o}),new Error(`Image URL fetch failed: ${t} (HTTP ${n.status})`);const a=(n.headers.get("content-type")||"").split(";")[0]?.trim().toLowerCase()||"";if(oe(a))throw L("url fetch rejected: non-image content-type",{url:i,contentType:a,elapsedMs:Date.now()-o}),new Error(`URL did not return an image (content-type: ${a}): ${t}`);const r=Number(n.headers.get("content-length")||"");if(L("url fetch response",{url:i,status:n.status,contentType:a||"(none)",contentLength:Number.isFinite(r)?r:null,elapsedMs:Date.now()-o}),Number.isFinite(r)&&r>F)throw L("url fetch rejected: too large",{url:i,contentLength:r,elapsedMs:Date.now()-o}),new Error(`Image too large to fetch: ${t} (${x(r)} > ${x(F)})`);const c=n.body;if(!c){const m=await n.arrayBuffer();if(m.byteLength>F)throw L("url fetch rejected: too large",{url:i,bytes:m.byteLength,elapsedMs:Date.now()-o}),new Error(`Image too large to fetch: ${t} (${x(m.byteLength)} > ${x(F)})`);return L("url fetch done",{url:i,bytes:m.byteLength,elapsedMs:Date.now()-o}),{buffer:Buffer.from(m),contentType:a}}const s=c.getReader(),d=[];let l=0;for(;;){const{done:m,value:w}=await s.read();if(m)break;if(w){if(l+=w.byteLength,l>F)throw s.cancel().catch(()=>{}),L("url fetch rejected: too large",{url:i,bytes:l,elapsedMs:Date.now()-o}),new Error(`Image too large to fetch: ${t} (${x(l)} > ${x(F)})`);d.push(Buffer.from(w))}}return L("url fetch done",{url:i,bytes:l,elapsedMs:Date.now()-o}),{buffer:Buffer.concat(d,l),contentType:a}}async function ne(t,e,i,o="auto",n){let a,r,c;if(Y(e)){const b=await ie(e);a=b.buffer,c=b.contentType,r=e}else{const M=(await dt(t,e,i)).targetPath,T=await p.stat(M);if(!T.isFile())throw new Error(`Path is not a file: ${M}`);if(T.size>st)throw new Error(`Image file too large to read: ${R(M)} (${x(T.size)} > ${x(st)}). Downscale it first.`);a=await p.readFile(M),r=R(M),n?.tracker&&n.tracker.record(U(M),z(T,null,!0))}if(a.length===0)throw new Error(`Image file is empty: ${r}`);const s=Mt(a);if(!s)throw L("image decode failed",{path:r,bytes:a.length,contentType:c||"(local file)"}),new Error(c!==void 0?`URL did not return a supported image (content-type: ${c||"unknown"}, unrecognized format): ${r}`:`Unsupported or corrupt image (unrecognized format): ${r}`);const d=Tt(a);let l=s,m=a,w=d?.width,g=d?.height,f=null;if(o!==!1){const b=await Rt(a,s,{normalMaxBytes:Bt,clearMaxBytes:Ft});b?.compressed&&(m=b.buffer,l=b.mediaType,w=b.width,g=b.height,f={level:b.level,originalSize:b.originalSize})}let h=!1;const k=await $t(m,l,{maxWidth:j,maxHeight:j,maxBytes:G});if(k)m=k.buffer,l=k.mediaType,w=k.width,g=k.height,h=k.changed;else if(m.length>G)throw new Error(`Image too large to inline: ${r} (${x(m.length)} > ${x(G)}). Downscale it first, e.g. via Bash: magick "${e}" -resize ${j}x${j} "${e}". Installing sharp enables automatic downscaling.`);const _=w&&g?`${w}x${g}`:"unknown dimensions",v=h&&d&&d.width!==w?` (resized from ${d.width}x${d.height})`:h?" (resized)":"",E=f!==null?f.level:null,$=f!==null?Math.max(1,Math.round((1-m.length/f.originalSize)*100)):0,P=f!==null?`${x(m.length)} (compressed from ${x(f.originalSize)}, saved ${$}%, ${E} level)`:x(m.length),y=`[Image: ${r}, ${_}${v}, ${P}]`,S=Y(e)?u.basename(new URL(e).pathname)||"image":u.basename(r);return{ok:!0,filePath:r,content:y,isBinary:!1,image:{mediaType:nt(l),width:w??null,height:g??null,originalWidth:d?.width??null,originalHeight:d?.height??null,resized:h,size:m.length,compressed:f!==null,compressionLevel:E,compressionRatio:f!==null?Math.round((1-m.length/f.originalSize)*100)/100:null,originalSize:a.length},attachments:[{type:"image",name:S,mediaType:nt(l),base64Data:m.toString("base64")}]}}function ft(t){let e="",i=0;for(;i<t.length;){const o=t[i];if(o==="*")e+="[^/]*";else if(o==="?")e+="[^/]";else if(o==="{"){const n=t.indexOf("}",i);if(n>=0){const a=t.slice(i+1,n);e+=`(${a.split(",").join("|")})`,i=n}else e+="\\{"}else if(o==="["){const n=t.indexOf("]",i);n>=0?(e+=t.slice(i,n+1),i=n):e+="\\["}else"+^$.()|\\".includes(o)?e+="\\"+o:e+=o;i++}return new RegExp(`^${e}$`)}async function ae(t,e,i,o){const n=[];async function a(r){if(n.length>=o)return;const c=await p.readdir(r,{withFileTypes:!0});for(const s of c){if(n.length>=o)return;if(s.name.startsWith(".")&&s.isDirectory())continue;const d=u.join(r,s.name);if(s.isDirectory()){if(jt.has(s.name))continue;await a(d)}else if(s.isFile()){if(e&&!e.test(s.name)||i&&i.test(s.name))continue;n.push(d)}}}return await a(t),n}async function re(t,e,i){if((await p.stat(t)).size>Wt)return{matches:[],count:0};if(await lt(t))return{matches:[],count:0};const n=u.relative(e,t).replace(/\\/g,"/"),a=[];let r=0;const c=Q(t,{encoding:"utf-8"}),s=tt.createInterface({input:c,crlfDelay:1/0});try{let d=0;for await(const l of s)if(d++,i.regex.test(l)){if(r++,i.collectContent){let m=l;if(m.length>B&&(m=m.slice(0,B)+`... (line truncated to ${B} chars)`),a.push({file:n,line:d,content:m}),a.length>=i.maxResults)break}if(i.stopOnFirstMatch)break}}finally{s.close(),c.destroy()}return{matches:a,count:r}}const se=12*60*6e4,ce=3*6e4,le=6e4,ue=10*6e4;function de(t,e,i,o){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",concurrencyMode:"write",resourceKeys:n=>{const a=X(n);return a?[K(t,a,"write")]:[]},description:"Create or overwrite a UTF-8 text file inside the current workspace. Parent directories are created automatically.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to write."},content:{type:"string",description:"Complete UTF-8 file content."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","content"],additionalProperties:!1},async execute(n){const a=I(n,["file_path","filePath"],"file_path"),r=I(n,["content"],"content"),c=O(n,["reason"]),s=await V(t,a,"write",i);await C(i,"fileModification",{operation:"write",path:s.targetPath});const d=await H(s.targetPath),l=d?await p.readFile(s.targetPath,"utf-8").catch(()=>null):null,m=d?await p.realpath(s.targetPath).catch(()=>s.targetPath):s.targetPath;let w=null;if(o?.enabled&&d){const f=await p.stat(m);w=D(f.mtimeMs,f.size);const h=ot(o.tracker,U(m),f,l);if(!h.ok)throw new Error(h.reason)}if(o?.enabled&&w){const f=await p.stat(m).catch(()=>null);if(!f||D(f.mtimeMs,f.size)!==w)throw new Error(it)}const g=await mt(s,r);if(await ht(o,g.targetPath,r),e&&!g.outsideWorkspace){const f=u.relative(g.workspaceRoot,g.targetPath).replace(/\\/g,"/");await e({filePath:f,operation:d?"UPDATE":"CREATE",beforeContent:l,afterContent:r,reason:c})}return{ok:!0,filePath:R(g.targetPath),bytes:g.bytes,createdParentDirectory:g.createdParentDirectory}}}}const me=15*1024;function Ie(t){if(typeof t!="object"||t===null)return;const e=Reflect.get(t,"editFailureSnapshot");if(typeof e=="object"&&e!==null&&typeof Reflect.get(e,"content")=="string")return e}function he(t,e,i,o){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",concurrencyMode:"write",resourceKeys:n=>{const a=X(n);return a?[K(t,a,"write")]:[]},description:"Replace exactly one occurrence of old_string with new_string in a UTF-8 workspace text file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to edit."},old_string:{type:"string",description:"Existing text to replace. Must occur exactly once."},new_string:{type:"string",description:"Replacement text."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","old_string","new_string"],additionalProperties:!1},async execute(n){const a=I(n,["file_path","filePath"],"file_path"),r=I(n,["old_string","oldString"],"old_string"),c=I(n,["new_string","newString"],"new_string"),s=O(n,["reason"]);if(!r)throw new Error("old_string must not be empty");const d=await V(t,a,"edit",i);await C(i,"fileModification",{operation:"edit",path:d.targetPath});const l=d.outsideWorkspace?await Qt(d.targetPath):await Zt(t,a),m=U(l.targetPath);let w;try{if(o?.enabled){const h=ot(o.tracker,m,l.stat,l.content);if(!h.ok)throw new Error(h.reason)}const f=qt(l.content,r);if(f===0)throw new Error("old_string was not found in file");if(f>1)throw new Error(`old_string occurs ${f} times; provide a unique match`);if(w=l.content.replace(r,c),o?.enabled){const h=await p.stat(l.targetPath).catch(()=>null);if(!h||D(h.mtimeMs,h.size)!==D(l.stat.mtimeMs,l.stat.size))throw new Error(it)}}catch(f){throw f instanceof Error&&l.stat.size<=me&&(o?.tracker.record(m,z(l.stat,l.content,!1)),f.editFailureSnapshot={path:R(l.targetPath),bytes:l.stat.size,content:l.content}),f}const g=await mt(d,w);if(await ht(o,g.targetPath,w),e&&!g.outsideWorkspace){const f=u.relative(g.workspaceRoot,g.targetPath).replace(/\\/g,"/");await e({filePath:f,operation:"UPDATE",beforeContent:l.content,afterContent:w,reason:s})}return{ok:!0,filePath:R(g.targetPath),bytes:g.bytes}}}}function fe(t,e,i){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",concurrencyMode:"write",resourceKeys:o=>{const n=X(o);return n?[K(t,n,"write")]:[]},description:"Delete a file inside the current workspace. Returns an error if the file does not exist.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to delete."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path"],additionalProperties:!1},async execute(o){const n=I(o,["file_path","filePath"],"file_path"),a=O(o,["reason"]),r=await V(t,n,"delete",i);await C(i,"fileModification",{operation:"delete",path:r.targetPath});const c=r.outsideWorkspace?await p.realpath(r.targetPath).catch(()=>r.targetPath):A(r.workspaceRoot,await p.realpath(r.targetPath).catch(()=>r.targetPath)),s=await p.stat(c).catch(()=>null);if(!s)throw new Error(`File does not exist: ${c}`);if(!s.isFile())throw new Error(`Path is not a file: ${c}`);const d=await p.readFile(c,"utf-8").catch(()=>null);if(await p.rm(c,{force:!0}),e&&!r.outsideWorkspace){const l=u.relative(r.workspaceRoot,c).replace(/\\/g,"/");await e({filePath:l,operation:"DELETE",beforeContent:d,afterContent:null,reason:a})}return{ok:!0,filePath:R(c),deleted:!0}}}}function pe(t,e,i){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",concurrencyMode:"read",resourceKeys:o=>{const n=X(o);return!n||Y(n)?[]:[K(t,n,"read")]},description:"Read a UTF-8 text file inside the current workspace. Returns content with line numbers in the format '<line>: <content>'. Supports offset (1-indexed line number to start from) and limit (max lines to return, default 2000). Output is capped at 2000 lines or 50 KB, whichever is reached first. Individual lines longer than 2000 characters are truncated. Avoid tiny repeated slices (e.g. 30-line chunks); read a larger window if more context is needed. Images (.png/.jpg/.jpeg/.gif/.webp) and http(s) image URLs are also supported: the image is inlined into the conversation so you can see it (requires a model with image input). When an image is already available at an http(s) URL (including signed URLs with query strings), pass the URL directly as file_path \u2014 the runtime fetches it in memory and never writes it to disk; do NOT download it with Bash/curl first. offset/limit are ignored for images. By default (compress='auto') images are compressed before inlining using a tiered ladder that judges by the compressed result, not the original size: lossless first (pixel-exact, dimensions preserved), then high-quality lossy downscaling only if the lossless result is still over 50 KB (normal level), then more aggressive downscaling if still over 100 KB (clear level). When compression applies, the result reports the compression level, compressed size, and compression ratio (e.g. saved 80%). Pass compress=true to also attempt compression, or compress=false to disable it (images exceeding the hard 2000px / 3.75MB inline limits are still auto-downscaled when sharp is available). You may issue several read_file calls in ONE message; independent reads run in parallel.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to read. For images, also accepts an http(s) URL (including signed URLs with query strings), which is fetched in memory without writing to disk."},offset:{type:"number",description:"Line number to start reading from (1-indexed). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to return. Defaults to 2000."},compress:{anyOf:[{type:"boolean"},{type:"string",enum:["auto"]}],description:'Image compression mode (ignored for text files). "auto" (default): compress with a tiered ladder driven by the compressed result \u2014 lossless, then high-quality downscale if still >50 KB, then more aggressive if still >100 KB. true: same as auto. false: skip tiered compression entirely (hard inline limits still apply).'}},required:["file_path"],additionalProperties:!1},async execute(o){const n=I(o,["file_path","filePath"],"file_path"),a=u.extname(n).toLowerCase().slice(1);if(Y(n)||At.has(a))return await ne(t,n,e,Xt(o),i);const r=q(o,["offset"],1),c=q(o,["limit"],Lt),s=await te(t,n,r,c,e);if(i?.tracker){let d=null,l=r!==1||s.truncated||s.isBinary;l||(d=await p.readFile(s.targetPath,"utf-8").catch(()=>null),(d==null||d.length>at)&&(d=null,l=!0)),i.tracker.record(U(s.targetPath),z({mtimeMs:s.mtimeMs,size:s.sizeBytes},d,l))}return{ok:!0,filePath:R(s.targetPath),content:s.content,isBinary:s.isBinary,truncated:s.truncated,totalLines:s.totalLines,shownFromLine:s.shownFromLine,shownToLine:s.shownToLine}}}}function ge(t,e,i,o){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",concurrencyMode:"write",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${u.resolve(String(t||"").trim()).replace(/\\/g,"/")}`,access:"write"}],description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded total timeout (timeout_ms) measured from command start \u2014 by default 3 minutes, after which the process is force-terminated; timeout_ms can raise this (up to 12 hours) or set 0 to disable. The tool returns stdout, stderr, exit code, and (if converted to background) a task_id. By default (wait_seconds omitted or -1) the command runs in the FOREGROUND and streams output in real time; if the 5-minute adapter watchdog fires while it is still running, the command is moved to the BACKGROUND and the tool returns a task_id plus an explanation (backgrounded=true, reason=watchdog_timeout). The background command stays bound by the same total timeout (timeout_ms, default 3 minutes, still measured from command start) and can be managed via await_complete / list_background_commands / read_background_output / kill_background_command. For immediate backgrounding use wait_seconds=0, or wait_seconds=n>0 to wait n seconds then background. Every result includes remainingBackgroundCommandSlots and backgroundCommandLimit: a per-agent cap on concurrent background commands (running and recently finished ones both occupy slots). When the cap is reached the command fails as not_executed \u2014 stop existing background commands via kill_background_command to free slots, then retry.",inputSchema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute."},cwd:{type:"string",description:"Optional workspace-relative working directory. Defaults to the workspace root."},timeout_ms:{type:"number",description:"Optional total command timeout in milliseconds, measured from command start. Defaults to 180000 (3 minutes) and is capped at 43200000 (12 hours). Set 0 to disable the timeout entirely (run until finished or killed)."},inactivity_timeout_ms:{type:"number",description:"Optional no-output timeout in milliseconds. Defaults to 60000 and is capped at 600000."},wait_seconds:{type:"number",description:"How to wait for the command to finish. Omitted values (or -1, the default): run in the FOREGROUND until completion; if the 5-minute adapter watchdog fires first, the command is moved to the background and a task_id is returned (backgrounded=true, reason=watchdog_timeout). 0: spawn and immediately execute in the background, return task_id. n>0: wait up to n seconds; if still running, move to the background and return task_id. The command remains bound by the total timeout (timeout_ms, default 3 minutes, measured from command start) whether foreground or background; inactivity_timeout_ms is ignored once backgrounded.",minimum:-1},description:{type:"string",description:"Short reason for running this command (what it does and why it is needed), shown to the user in the background commands panel. Always provide a concise reason, e.g. 'Start local dev server for manual verification'."}},required:["command"],additionalProperties:!1},async execute(n,a){const r=I(n,["command"],"command").trim();if(!r)throw new Error("command must not be empty");const c=Kt(n,["timeout_ms","timeoutMs"],ce),s=c===0?0:Math.min(c,se),d=q(n,["inactivity_timeout_ms","inactivityTimeoutMs"],le),l=Math.min(d,ue),m=O(n,["cwd"]),w=O(n,["description"]),g=await Gt(t,m);await C(o,"commandExecution",{command:r,cwd:R(g.cwd)});const f=n.wait_seconds,k=typeof f=="number"&&Number.isFinite(f)?f:-1;if(i)return await we({deps:i,command:r,agentId:e,workspaceRoot:g.workspaceRoot,cwd:g.cwd,timeoutMs:s,inactivityTimeoutMs:l,waitSeconds:k,description:w,onOutput:a?.onOutput,settleSignal:a?.settleSignal});const _=await wt({commandText:r,agentId:e,workspaceRoot:g.workspaceRoot,cwd:g.cwd,timeoutMs:s,inactivityTimeoutMs:l,onOutput:a?.onOutput,watchdogSignal:a?.settleSignal}),v={ok:_.exitCode===0&&!_.timedOut,tool:"Bash",command:r,cwd:R(g.cwd),exitCode:_.exitCode,signal:_.signal,timedOut:_.timedOut,inactivityTimedOut:_.inactivityTimedOut,watchdogInterrupted:_.watchdogInterrupted,timeoutMs:s,inactivityTimeoutMs:l,durationMs:_.durationMs,outputSpilled:_.outputSpilled,outputFilePath:_.outputFilePath,outputLineCount:_.outputLineCount,commandFilePath:_.commandFilePath,commandLineCount:_.commandLineCount,stdout:_.stdout,stderr:_.stderr};return _.watchdogInterrupted?{...v,message:"Command was interrupted by the adapter watchdog after ~5 minutes of synchronous (foreground) execution. Only the partial output produced so far is returned above"+(_.outputFilePath?` (full output spilled to "${_.outputFilePath}"; read it if you need more)`:"")+". For long-running commands, re-run with wait_seconds=0 (or n>0) to execute in the background, then manage via await_complete / list_background_commands / read_background_output / kill_background_command."}:v}}}async function we(t){const{deps:e,command:i,agentId:o,workspaceRoot:n,cwd:a,timeoutMs:r,inactivityTimeoutMs:c,waitSeconds:s,description:d,onOutput:l,settleSignal:m}=t,w=l?yt({cwd:a,commandLineCount:0,onOutput:l}):void 0;let g=!!w;const f=()=>{g&&(g=!1,w?.close())};try{const{taskId:h,completion:k}=e.manager.startCommand({commandText:i,agentId:o,workspaceRoot:n,cwd:a,description:d,timeoutMs:r,inactivityTimeoutMs:c,onOutput:g?P=>{g&&w?.push(P.stream,P.text)}:void 0,onCompleted:e.emitCompleted}),_=e.manager.taskCapacity(o);if(s===0)return e.manager.disableInactivityTimeout(o,h),await e.manager.markBackgrounded(o,h).catch(()=>{}),f(),{ok:!0,tool:"Bash",command:i,backgrounded:!0,taskId:h,status:"backgrounded",reason:"immediate",remainingBackgroundCommandSlots:_.remaining,backgroundCommandLimit:_.limit,message:`Command moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, read_background_output(task_id="${h}", mode="tail") to read output, list_background_commands to view all, or kill_background_command(task_id="${h}") to stop.`};const v=s===-1?0:Math.max(0,Math.floor(s*1e3)),E=[k];let $;s!==-1&&E.push(new Promise(P=>{$=setTimeout(()=>P("__timeout__"),v),$.unref?.()})),m&&E.push(m.then(()=>"__settle__"));try{const P=await Promise.race(E);if(P==="__settle__")return e.manager.disableInactivityTimeout(o,h),await e.manager.markBackgrounded(o,h).catch(()=>{}),{ok:!0,tool:"Bash",command:i,backgrounded:!0,taskId:h,status:"backgrounded",reason:"watchdog_timeout",waitedMs:v,remainingBackgroundCommandSlots:_.remaining,backgroundCommandLimit:_.limit,message:`Command still running after watchdog timeout; moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, read_background_output(task_id="${h}", mode="tail") to read output, or kill_background_command(task_id="${h}") to stop.`};if(P==="__timeout__")return e.manager.disableInactivityTimeout(o,h),await e.manager.markBackgrounded(o,h).catch(()=>{}),{ok:!0,tool:"Bash",command:i,backgrounded:!0,taskId:h,status:"backgrounded",reason:"timeout",waitedMs:v,remainingBackgroundCommandSlots:_.remaining,backgroundCommandLimit:_.limit,message:`Command still running after ${s}s; moved to background. Use await_complete(bg_cmd_ids=["${h}"]) to block until it finishes, or read_background_output(task_id="${h}", mode="tail") / kill_background_command(task_id="${h}") to inspect.`};const y=P;let S=y.stdout,b=y.stderr,M=y.outputSpilled,T=y.outputFilePath;if(!M&&et(`${y.stdout}${y.stderr}`)>bt){const N=await vt(o,"cmd","out",_t({commandText:i,commandFilePath:y.commandFilePath,commandLineCount:y.commandLineCount,cwd:a,startedAt:new Date(Date.now()-y.durationMs),endedAt:new Date,exitCode:y.exitCode,signal:y.signal??null,timedOut:y.timedOut,inactivityTimedOut:y.inactivityTimedOut??!1,stdout:S,stderr:b}));S=kt(R(N),et(`${y.stdout}${y.stderr}`)),M=!0,T=R(N)}return{ok:y.exitCode===0&&!y.timedOut,tool:"Bash",command:i,backgrounded:!1,taskId:h,remainingBackgroundCommandSlots:_.remaining,backgroundCommandLimit:_.limit,exitCode:y.exitCode,signal:y.signal,timedOut:y.timedOut,inactivityTimedOut:y.inactivityTimedOut,timeoutMs:y.timeoutMs,inactivityTimeoutMs:y.inactivityTimeoutMs,durationMs:y.durationMs,outputSpilled:M,outputFilePath:T,outputLineCount:y.outputLineCount,commandFilePath:y.commandFilePath,commandLineCount:y.commandLineCount,stdout:S,stderr:b}}finally{$&&clearTimeout($),f()}}catch(h){if(h?.code==="too_many_tasks"||h?.code==="global_limit_reached"){const k=e.manager.taskCapacity(o);return{ok:!1,tool:"Bash",command:i,backgrounded:!1,status:"not_executed",error:h.code,remainingBackgroundCommandSlots:k.remaining,backgroundCommandLimit:k.limit,message:`Command was NOT executed: ${h.message} To run new commands, stop existing background commands via kill_background_command(task_id=...) to free slots, then retry.`}}throw h}}function ye(t){return{kind:"builtin",toolName:"grep",exposedName:"grep",concurrencyMode:"read",resourceScope:"workspace",resourceKeys:()=>[{key:`workspace:${u.resolve(String(t||"").trim()).replace(/\\/g,"/")}`,access:"read"}],description:"Search file contents using regular expressions within the workspace. Returns matched lines with file paths and line numbers. Supports include/exclude glob patterns, case-insensitive matching, and three output modes (content, files_with_matches, count). Searches recursively through directories, skipping binary files, hidden directories, and common build/dependency directories (node_modules, .git, dist, etc.). You may issue several grep/read_file calls in ONE message; independent searches run in parallel.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Regular expression pattern to search for in file contents."},path:{type:"string",description:"Workspace-relative file or directory path to search in. Defaults to the workspace root."},include:{type:"string",description:"Glob pattern to filter files by name (e.g. '*.ts', '*.{js,ts}'). Only matching files are searched."},exclude:{type:"string",description:"Glob pattern to exclude files by name (e.g. '*.test.ts'). Matching files are skipped."},case_insensitive:{type:"boolean",description:"Case-insensitive matching. Default false."},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output format: 'content' returns matched lines with line numbers (default), 'files_with_matches' returns only file paths with matches, 'count' returns match counts per file."},max_results:{type:"number",description:"Maximum number of matched lines to return (content mode). Default 1000."}},required:["pattern"],additionalProperties:!1},async execute(e){const i=I(e,["pattern"],"pattern"),o=O(e,["path"])||".",n=O(e,["include"]),a=O(e,["exclude"]),r=e.case_insensitive===!0,c=(()=>{const b=e.output_mode;return b==="files_with_matches"||b==="count"?b:"content"})(),s=q(e,["max_results"],zt),d=r?"i":"";let l;try{l=new RegExp(i,d)}catch(b){throw new Error(`Invalid regex pattern: ${b instanceof Error?b.message:String(b)}`)}const m=n?ft(n):null,w=a?ft(a):null,g=await ut(t,o),f=A(g.workspaceRoot,await p.realpath(g.targetPath)),h=await p.stat(f);let k;if(h.isFile())k=[f];else if(h.isDirectory())k=await ae(f,m,w,Ut);else throw new Error(`Path is neither a file nor a directory: ${f}`);const _=[],v=[],E=[];let $=0,P=0,y=!1;for(const b of k){if(c==="content"&&_.length>=s){y=!0;break}const M={regex:l,maxResults:c==="content"?s-_.length:Number.MAX_SAFE_INTEGER,collectContent:c==="content",stopOnFirstMatch:c==="files_with_matches"},T=await re(b,g.workspaceRoot,M);if(T.count>0){const N=u.relative(g.workspaceRoot,b).replace(/\\/g,"/");if(E.push(N),$+=T.count,c==="content"){for(const J of T.matches){const Z=Buffer.byteLength(J.content,"utf-8")+64;if(P+Z>Dt){y=!0;break}P+=Z,_.push(J)}if(y)break;if(_.length>=s){y=!0;break}}else c==="count"&&v.push({file:N,count:T.count})}}const S={ok:!0,tool:"grep",pattern:i,searchPath:R(g.targetPath),outputMode:c,filesSearched:k.length,filesMatched:E.length,totalMatches:$,truncated:y};return c==="content"?S.matches=_:c==="files_with_matches"?S.matches=E:S.matches=v,S}}}function Oe(t,e,i,o,n,a){const r=e||"unknown",c=[pe(t,n,a),de(t,i,n,a),he(t,i,n,a),fe(t,i,n),ye(t),ge(t,r,o,n),Et(t)];return o&&c.push(Pt(r,o),St(r,o),xt(r,o)),c}export{Le as DEFAULT_TOOL_PERMISSION_POLICY,me as EDIT_FAILURE_SNAPSHOT_MAX_BYTES,Yt as buildFileResourceKey,Oe as createBuiltInFileTools,A as ensureInsideWorkspace,K as fileResourceClaim,Ie as getEditFailureSnapshot,ut as resolveWorkspaceTarget};
4
4
 
@@ -0,0 +1,67 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+ export declare const HIBERNATION_JOURNAL_VERSION = 1;
19
+
20
+ export type HibernationJournalReason = "periodic" | "clean";
21
+ export interface HibernationJournal {
22
+ version: number;
23
+ agentId: string;
24
+
25
+ sessionId: string;
26
+
27
+ savedAt: string;
28
+ reason: HibernationJournalReason;
29
+ messageCount: number;
30
+
31
+ transcript: unknown[];
32
+
33
+ tokenUsage?: {
34
+ inputTokens?: number | null;
35
+ outputTokens?: number | null;
36
+ totalInputTokens?: number | null;
37
+ totalOutputTokens?: number | null;
38
+ cacheHitTokens?: number | null;
39
+ cacheMissTokens?: number | null;
40
+ };
41
+ }
42
+
43
+
44
+
45
+ export declare function writeJournal(agentId: string, payload: {
46
+ sessionId: string;
47
+ reason: HibernationJournalReason;
48
+ transcript: unknown[];
49
+ tokenUsage?: HibernationJournal["tokenUsage"];
50
+ }): Promise<void>;
51
+
52
+
53
+
54
+
55
+ export declare function readJournal(agentId: string): Promise<HibernationJournal | null>;
56
+
57
+
58
+
59
+ export declare function deleteJournal(agentId: string): Promise<void>;
60
+
61
+ export declare const HIBERNATION_JOURNAL_TTL_MS: number;
62
+
63
+
64
+
65
+
66
+
67
+ export declare function sweepExpiredJournals(maxAgeMs?: number): Promise<number>;
@@ -0,0 +1,2 @@
1
+ import{promises as o}from"node:fs";import f from"node:path";import{renameWithRetry as A}from"./fs-utils.js";import{resolveAcodeHome as y}from"./paths.js";const m=1,p=4e3,d=16*1024*1024;function v(t){return String(t).replace(/[^a-zA-Z0-9_-]/g,"_")}function u(){return f.join(y(),"hibernation")}function g(t){return f.join(u(),`${v(t)}.json`)}function N(t){if(t.length<=p){let n=0;for(const e of t)if(n+=JSON.stringify(e??null).length,n>d)return S(t,I(t,n));return t}return t.slice(t.length-p)}function S(t,n){return n>=t.length?t.slice(-1):t.slice(n)}function I(t,n){const e=n-d,r=Math.max(1,Math.floor(n/t.length));return Math.min(t.length-1,Math.ceil(e/r*1.2))}const l=new Map;async function j(t,n){const e=g(t),r=N(n.transcript??[]),s={version:m,agentId:t,sessionId:n.sessionId,savedAt:new Date().toISOString(),reason:n.reason,messageCount:r.length,transcript:r,...n.tokenUsage?{tokenUsage:n.tokenUsage}:{}},c=(l.get(t)??Promise.resolve()).then(async()=>{await o.mkdir(u(),{recursive:!0});const a=`${e}.tmp`;await o.writeFile(a,JSON.stringify(s),"utf-8"),await A(a,e)});l.set(t,c.catch(()=>{})),await c}async function M(t){const n=g(t);let e;try{e=await o.readFile(n,"utf-8")}catch(i){return i?.code==="ENOENT",null}let r;try{r=JSON.parse(e)}catch{return await w(n,e),null}const s=x(r,t);return s||(await w(n,e),null)}function x(t,n){if(typeof t!="object"||t===null)return null;const e=t;return e.version!==m||typeof e.agentId!="string"||!e.agentId||typeof e.savedAt!="string"||!e.savedAt||!Array.isArray(e.transcript)||e.transcript.length===0?null:{version:m,agentId:e.agentId,sessionId:typeof e.sessionId=="string"?e.sessionId:"",savedAt:e.savedAt,reason:e.reason==="clean"?"clean":"periodic",messageCount:typeof e.messageCount=="number"?e.messageCount:e.transcript.length,transcript:e.transcript,tokenUsage:typeof e.tokenUsage=="object"&&e.tokenUsage!==null?e.tokenUsage:void 0}}async function w(t,n){try{await o.writeFile(`${t}.corrupt-${Date.now()}`,n,"utf-8")}catch{}}async function k(t){const e=(l.get(t)??Promise.resolve()).catch(()=>{}).then(async()=>{await o.rm(g(t),{force:!0})});l.set(t,e.catch(()=>{})),await e}const T=7*24*60*60*1e3;async function E(t=T){let n=0,e;try{e=await o.readdir(u())}catch{return 0}const r=Date.now();for(const s of e){if(!s.endsWith(".json"))continue;const i=f.join(u(),s);try{const c=await o.readFile(i,"utf-8");let a=0;try{const h=JSON.parse(c);typeof h.savedAt=="string"&&(a=Date.parse(h.savedAt))}catch{}(!Number.isFinite(a)||r-a>t)&&(await o.rm(i,{force:!0}),n+=1)}catch{}}return n}export{T as HIBERNATION_JOURNAL_TTL_MS,m as HIBERNATION_JOURNAL_VERSION,k as deleteJournal,M as readJournal,E as sweepExpiredJournals,j as writeJournal};
2
+
@@ -24,3 +24,4 @@ export * from './parsers/language-queries.js';
24
24
  export * from './parsers/symbol-extractor.js';
25
25
  export * from './parsers/file-index.js';
26
26
  export * from './built-in-symbols-tool.js';
27
+ export * from './hibernation-journal.js';
@@ -1,2 +1,2 @@
1
- export*from"./commands/commandRegistry.js";export*from"./commands/commandLoader.js";export*from"./commands/commandParser.js";export*from"./config.js";export*from"./hooks/hookBus.js";export*from"./runtime.js";export*from"./runtime-environment.js";export*from"./types.js";export*from"./sub-agent-types.js";export*from"./sub-agent-store.js";export*from"./sub-agent-manager.js";export*from"./sub-agent-tools.js";export*from"./built-in-file-tools.js";export*from"./read-file-state.js";export*from"./tool-concurrency/index.js";export*from"./terminal-types.js";export*from"./plugin-types.js";export*from"./tool-group-manager.js";export*from"./parsers/types.js";export*from"./parsers/tree-sitter-loader.js";export*from"./parsers/ast-cache.js";export*from"./parsers/language-detector.js";export*from"./parsers/language-queries.js";export*from"./parsers/symbol-extractor.js";export*from"./parsers/file-index.js";export*from"./built-in-symbols-tool.js";
1
+ export*from"./commands/commandRegistry.js";export*from"./commands/commandLoader.js";export*from"./commands/commandParser.js";export*from"./config.js";export*from"./hooks/hookBus.js";export*from"./runtime.js";export*from"./runtime-environment.js";export*from"./types.js";export*from"./sub-agent-types.js";export*from"./sub-agent-store.js";export*from"./sub-agent-manager.js";export*from"./sub-agent-tools.js";export*from"./built-in-file-tools.js";export*from"./read-file-state.js";export*from"./tool-concurrency/index.js";export*from"./terminal-types.js";export*from"./plugin-types.js";export*from"./tool-group-manager.js";export*from"./parsers/types.js";export*from"./parsers/tree-sitter-loader.js";export*from"./parsers/ast-cache.js";export*from"./parsers/language-detector.js";export*from"./parsers/language-queries.js";export*from"./parsers/symbol-extractor.js";export*from"./parsers/file-index.js";export*from"./built-in-symbols-tool.js";export*from"./hibernation-journal.js";
2
2
 
@@ -18,4 +18,7 @@ export declare function buildRuntimeEnvironmentPrompt(platform?: NodeJS.Platform
18
18
 
19
19
 
20
20
 
21
- export declare function buildResumeContextBlock(snapshot: string): string;
21
+
22
+
23
+
24
+ export declare function buildResumeContextBlock(snapshot: string, wakeNotice?: string): string;
@@ -1,4 +1,4 @@
1
- import r from"node:os";import l from"node:path";import{shellExecutable as a}from"./builtins/shellCommandPreparation.js";function c(e=process.platform,n=r.release(),t=a()){const o=e==="win32"?"Windows":e==="darwin"?"macOS":e==="linux"?"Linux":e,i=l.basename(t.command).toLowerCase(),s=e==="win32"?`Shell: ${i} (Windows) \u2014 commands run in a Windows shell, not a POSIX shell; Unix-only commands (rm, grep, sed, ...) may be unavailable, prefer Windows equivalents (rd, findstr, ...) or the built-in file tools.`:`Shell: ${i} \u2014 commands run in a POSIX shell.`;return["[Runtime Environment]",`Platform: ${o} (${e}, release ${n})`,s,"Images: if an image is already at an http(s) URL (including signed URLs with query strings), call read_file with that URL directly \u2014 it is fetched in memory and never written to disk. Do NOT download it with Bash/curl/wget first."].join(`
2
- `)}function h(e){const n=e.trim();return n?["[Resume Context]","\u4EE5\u4E0B\u5185\u5BB9\u53D6\u81EA\u4F60\u4E0A\u4E00\u6B21\u8FD0\u884C\u5230\u8BE5\u5B9E\u4F8B\u4F11\u7720\u4E3A\u6B62\u7684\u8FDB\u5EA6\u5FEB\u7167\uFF08\u7531\u7CFB\u7EDF\u5728\u4F11\u7720\u65F6\u81EA\u52A8\u4FDD\u5B58\uFF09\u3002","\u5B83\u4E0D\u662F\u65B0\u7684\u7528\u6237\u6D88\u606F\uFF0C\u4E5F\u4E0D\u662F\u65B0\u7684\u4EFB\u52A1\u6307\u4EE4\uFF0C\u800C\u662F\u4F60\u81EA\u5DF1\u7684\u8BB0\u5FC6\u63A5\u7EED\u70B9\u3002","","\u63A5\u7EED\u89C4\u5219\uFF1A","1. \u4E0A\u8FF0\u5FEB\u7167\u91CC\u5DF2\u7ECF\u5B8C\u6210\u7684\u5DE5\u4F5C\u4E0D\u8981\u91CD\u505A\uFF0C\u5DF2\u786E\u8BA4\u7684\u7ED3\u8BBA\u76F4\u63A5\u6CBF\u7528\u3002","2. \u5FEB\u7167\u4E2D\u6807\u6CE8\u4E3A\u5F85\u5904\u7406/\u8FDB\u884C\u4E2D\u7684\u4E8B\u9879\uFF0C\u662F\u4F60\u8981\u7EE7\u7EED\u63A8\u8FDB\u7684\u76EE\u6807\u3002","3. \u82E5\u5FEB\u7167\u4FE1\u606F\u4E0D\u8DB3\u4EE5\u5224\u65AD\u4E0B\u4E00\u6B65\uFF0C\u5148\u8BFB\u53D6\u76F8\u5173\u6587\u4EF6\u6216\u8C03\u7528 poll_message \u83B7\u53D6\u6700\u65B0\u6D88\u606F\uFF0C\u518D\u884C\u52A8\u3002","","--- \u8FDB\u5EA6\u5FEB\u7167\u5F00\u59CB ---",n,"--- \u8FDB\u5EA6\u5FEB\u7167\u7ED3\u675F ---"].join(`
3
- `):""}export{h as buildResumeContextBlock,c as buildRuntimeEnvironmentPrompt};
1
+ import r from"node:os";import l from"node:path";import{shellExecutable as a}from"./builtins/shellCommandPreparation.js";function c(e=process.platform,t=r.release(),n=a()){const i=e==="win32"?"Windows":e==="darwin"?"macOS":e==="linux"?"Linux":e,o=l.basename(n.command).toLowerCase(),s=e==="win32"?`Shell: ${o} (Windows) \u2014 commands run in a Windows shell, not a POSIX shell; Unix-only commands (rm, grep, sed, ...) may be unavailable, prefer Windows equivalents (rd, findstr, ...) or the built-in file tools.`:`Shell: ${o} \u2014 commands run in a POSIX shell.`;return["[Runtime Environment]",`Platform: ${i} (${e}, release ${t})`,s,"Images: if an image is already at an http(s) URL (including signed URLs with query strings), call read_file with that URL directly \u2014 it is fetched in memory and never written to disk. Do NOT download it with Bash/curl/wget first."].join(`
2
+ `)}function h(e,t){const n=e.trim();if(!n)return"";const i=t?.trim();return["[Resume Context]","\u4EE5\u4E0B\u5185\u5BB9\u53D6\u81EA\u4F60\u4E0A\u4E00\u6B21\u8FD0\u884C\u5230\u8BE5\u5B9E\u4F8B\u4F11\u7720\u4E3A\u6B62\u7684\u8FDB\u5EA6\u5FEB\u7167\uFF08\u7531\u7CFB\u7EDF\u5728\u4F11\u7720\u65F6\u81EA\u52A8\u4FDD\u5B58\uFF09\u3002","\u5B83\u4E0D\u662F\u65B0\u7684\u7528\u6237\u6D88\u606F\uFF0C\u4E5F\u4E0D\u662F\u65B0\u7684\u4EFB\u52A1\u6307\u4EE4\uFF0C\u800C\u662F\u4F60\u81EA\u5DF1\u7684\u8BB0\u5FC6\u63A5\u7EED\u70B9\u3002","","\u63A5\u7EED\u89C4\u5219\uFF1A","1. \u4E0A\u8FF0\u5FEB\u7167\u91CC\u5DF2\u7ECF\u5B8C\u6210\u7684\u5DE5\u4F5C\u4E0D\u8981\u91CD\u505A\uFF0C\u5DF2\u786E\u8BA4\u7684\u7ED3\u8BBA\u76F4\u63A5\u6CBF\u7528\u3002","2. \u5FEB\u7167\u4E2D\u6807\u6CE8\u4E3A\u5F85\u5904\u7406/\u8FDB\u884C\u4E2D\u7684\u4E8B\u9879\uFF0C\u662F\u4F60\u8981\u7EE7\u7EED\u63A8\u8FDB\u7684\u76EE\u6807\u3002","3. \u82E5\u5FEB\u7167\u4FE1\u606F\u4E0D\u8DB3\u4EE5\u5224\u65AD\u4E0B\u4E00\u6B65\uFF0C\u5148\u8BFB\u53D6\u76F8\u5173\u6587\u4EF6\u6216\u8C03\u7528 poll_message \u83B7\u53D6\u6700\u65B0\u6D88\u606F\uFF0C\u518D\u884C\u52A8\u3002","","--- \u8FDB\u5EA6\u5FEB\u7167\u5F00\u59CB ---",n,"--- \u8FDB\u5EA6\u5FEB\u7167\u7ED3\u675F ---",...i?["",i]:[]].join(`
3
+ `)}export{h as buildResumeContextBlock,c as buildRuntimeEnvironmentPrompt};
4
4
 
@@ -137,6 +137,13 @@ export declare class AgentClient {
137
137
 
138
138
 
139
139
 
140
+
141
+
142
+
143
+ getDmSendStatus(ticket: string): Promise<unknown>;
144
+
145
+
146
+
140
147
  sendCallAndWaitReply(targetId: string, content: string, timeoutMs?: number): Promise<DirectMessage>;
141
148
 
142
149
 
@@ -1,2 +1,2 @@
1
- import{configManager as h}from"./config.js";import{MESSAGE_POLL_INTERVAL_MS as I}from"./constants.js";import{HttpClient as f}from"./http-client.js";import{logger as i,setMcpNodeLogSink as w,updateStartupLogIdentity as u}from"./logger.js";import{claimRuntimeLaunchBindingDetailed as m}from"./runtime-launch-binding.js";import{StatusReporter as A}from"./status-reporter.js";import{WebSocketClient as p}from"./websocket-client.js";class T extends Error{constructor(e){super(e),this.name="PollLongPollTimeoutError"}}const C=27e4;class N{wsClient;httpClient;agentConfig;serverConfig;agentId=null;displayName=null;projectId=null;isRunning=!1;isDegradedMode=!1;messageHandler=null;profileHandler=null;configHandler=null;systemNotifyHandler=null;pollTimer=null;statusReporter=null;newCharacterHandler=null;runtimeTokenRefreshTimer=null;pendingLaunchBindingClaim=!1;cachedProfile=null;constructor(){h.loadConfig(),this.agentConfig=h.getAgentConfig(),this.serverConfig=h.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async initialize(){const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed"){this.applyLaunchBinding(e.binding);return}if(e.status==="unreachable"){this.pendingLaunchBindingClaim=!0,i.warn("[AgentClient] runtime-bridge \u672A\u5C31\u7EEA\uFF0C\u542F\u52A8\u7ED1\u5B9A\u8BA4\u9886\u5DF2\u6302\u8D77\uFF0C\u5C06\u5728\u6CE8\u518C\u91CD\u8BD5\u4E2D\u91CD\u65B0\u8BA4\u9886: %s",e.message);return}this.serverConfig.runtimeBridgeBaseUrl=void 0}applyLaunchBinding(e){h.applyRuntimeLaunchBinding(e),this.agentConfig=h.getAgentConfig(),this.serverConfig=h.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async retryPendingLaunchBindingClaim(){if(!this.pendingLaunchBindingClaim)return!0;const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed")return this.pendingLaunchBindingClaim=!1,i.info("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u6210\u529F\uFF0C\u7EE7\u7EED\u6CE8\u518C\u6D41\u7A0B"),this.applyLaunchBinding(e.binding),!0;if(e.status==="missing")return this.pendingLaunchBindingClaim=!1,this.serverConfig.runtimeBridgeBaseUrl=void 0,i.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u672A\u627E\u5230\u5F85\u8BA4\u9886\u8BB0\u5F55\uFF0C\u6309\u65E0\u7ED1\u5B9A\u6A21\u5F0F\u7EE7\u7EED\u6CE8\u518C"),!1;const t=e.status==="unreachable"?e.message:e.reason;return i.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u5931\u8D25\uFF0C\u4FDD\u7559\u6302\u8D77\u72B6\u6001\u7B49\u5F85\u4E0B\u6B21\u6CE8\u518C\u91CD\u8BD5: %s",t),!1}setupWebSocketListeners(){this.wsClient.on("directMessage",e=>{this.handleIncomingDm(e)}),this.wsClient.on("groupMessage",e=>{this.handleIncomingGroup(e)}),this.wsClient.on("meetingMessage",e=>{this.handleIncomingMeeting(e)}),this.wsClient.on("systemNotify",e=>{this.systemNotifyHandler?.(e)}),this.wsClient.on("profileInfo",e=>{i.info(`[AgentClient] WebSocket profileInfo \u4E8B\u4EF6\u89E6\u53D1\uFF0CdisplayName: ${e.displayName}`),this.handleProfileInfo(e)}),this.wsClient.on("agentConfig",e=>{i.info("[AgentClient] WebSocket agentConfig \u4E8B\u4EF6\u89E6\u53D1"),this.configHandler&&this.configHandler(e??{})}),this.wsClient.on("agentStatus",e=>{i.info(`[AgentClient] WebSocket agentStatus \u4E8B\u4EF6\u89E6\u53D1: ${e.status}`)}),this.wsClient.on("disconnected",(e,t)=>{const n=t?.toString()||"";i.warn("[AgentClient] WebSocket \u65AD\u5F00\u8FDE\u63A5: code=%s, reason=%s, agentId=%s, \u6B63\u5728\u81EA\u52A8\u91CD\u8FDE",e,n,this.agentId)}),this.wsClient.on("error",e=>{i.error("[AgentClient] WebSocket \u9519\u8BEF: %s, stack=%s",e.message,e.stack)}),this.wsClient.on("reconnectFailed",()=>{i.error("[AgentClient] \u91CD\u8FDE\u5931\u8D25\uFF08\u5DF2\u8FBE\u91CD\u8BD5\u4E0A\u9650\uFF09\uFF0C\u505C\u6B62\u6D88\u606F\u5FAA\u73AF, agentId=%s",this.agentId),this.stop()}),this.wsClient.on("tokenRejected",()=>{i.error("[AgentClient] runtime token \u88AB 1008 \u62D2\u7EDD\u4E14\u5237\u65B0\u65E0\u53D8\u5316\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85\u65B0 token \u7B7E\u53D1: agentId=%s",this.agentId)}),this.wsClient.on("tokenRefreshFailed",e=>{i.error("[AgentClient] runtime token \u5237\u65B0\u8FDE\u7EED\u5931\u8D25 %s \u6B21\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85 bridge \u6062\u590D: agentId=%s",e,this.agentId)})}async register(){return i.info("[AgentClient] \u6B63\u5728\u6CE8\u518C Agent..."),await this.retryPendingLaunchBindingClaim(),this.hasPresetAgentId()?await this.registerWithExistingAgentId():await this.registerAsNewAgent()}hasPresetAgentId(){return!!(this.agentConfig.agentId&&this.agentConfig.agentId.trim().length>0)}async registerWithExistingAgentId(){const e=this.agentConfig.agentId;if(!e)throw new Error("Preset agentId is missing");this.agentId=e.trim();let t;try{t=await this.getProfileByAgentId(this.agentId)}catch(r){throw i.error("[AgentClient] getProfileByAgentId \u5931\u8D25 (presetAgentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}this.displayName=t.displayName,this.projectId=t.projectId||null,i.info(`[AgentClient] \u4F7F\u7528\u9884\u8BBE AgentID \u7ED1\u5B9A\u5B9E\u4F8B: ${this.displayName} (${this.agentId})`),i.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`);try{await this.wsClient.connect(this.agentId)}catch(r){throw i.error("[AgentClient] WebSocket \u8FDE\u63A5\u5931\u8D25 (agentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}i.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter();const n=await this.getProfileByAgentId(this.agentId);return this.displayName=n.displayName,this.projectId=n.projectId||null,u(n.roleName||"unknown-role",n.instanceName||this.agentId),{agentId:this.agentId,displayName:this.displayName,status:n.isOnline?"online":"offline",projectId:n.projectId,workspacePath:n.workspacePath,runtimeStatus:n.runtimeStatus,runtimeSessionId:n.runtimeSessionId}}async registerAsNewAgent(){const e=await this.httpClient.callTool("register",{roleName:this.agentConfig.roleName,projectId:this.agentConfig.projectId,workspacePath:this.agentConfig.workspacePath,prompt:this.agentConfig.prompt,runtimeBridgeBaseUrl:this.serverConfig.runtimeBridgeBaseUrl}),t=e.agentId;if(!t)throw new Error("Registration failed: agentId was not returned");return this.agentId=t,this.displayName=e.displayName,this.projectId=e.projectId||null,u(this.agentConfig.roleName||"unknown-role",e.instanceName||t),i.info(`[AgentClient] \u6CE8\u518C\u6210\u529F: ${this.displayName} (${this.agentId})`),i.info(`[AgentClient] \u72B6\u6001: ${e.status}`),i.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`),await this.wsClient.connect(this.agentId),i.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter(),e.isExisting===!1&&this.newCharacterHandler&&this.newCharacterHandler(),e}async unregister(){i.info("[AgentClient] \u6B63\u5728\u6CE8\u9500 Agent..."),this.agentId&&await this.httpClient.callTool("unregister",{agentId:this.agentId}),this.stopRuntimeTokenRefresh(),this.wsClient.disconnect(),this.agentId=null,this.displayName=null,this.projectId=null,this.isRunning=!1,i.info("[AgentClient] \u5DF2\u6CE8\u9500")}async discoverColleagues(){return await this.httpClient.callTool("discover_colleague",{agentId:this.agentId})}async discoverGroupRooms(){return this.ensureRegistered(),await this.httpClient.callTool("discover_group_rooms",{agentId:this.agentId})}async listProjectMembers(){return this.ensureRegistered(),await this.httpClient.callTool("list_project_members",{agentId:this.agentId})}async hireColleague(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleague",{...e,agentId:this.agentId})}async callAgentScopedTool(e,t){this.ensureRegistered();const n={...t,agentId:this.agentId};if(e==="create_meeting"){const r=typeof t.waitTimeoutMs=="number"?t.waitTimeoutMs:Number.NaN,s=Number.isFinite(r)&&r>0?Math.min(r,C):C;return await this.httpClient.callToolOnce(e,{...n,waitTimeoutMs:s},0)}return await this.httpClient.callTool(e,n)}async reportMemoryStats(e){await this.callAgentScopedTool("report_memory_stats",{memoryStats:e})}async sendGroupMessage(e,t,n,r,s,a){this.ensureRegistered();const c=t||this.projectId||this.agentConfig.projectId;return await this.httpClient.callTool("send_group_message",{agentId:this.agentId,projectId:c,roomId:n,content:e,card:r,replyTo:s,...a?{voice:a}:{}})}async sendDirectMessage(e,t,n=!1,r,s,a,c,g,o){this.ensureRegistered();const l={agentId:this.agentId,targetId:e,content:t,requireReply:n,waitReply:n,replyToCallId:r,card:a,replyTo:c};if(typeof s=="number"&&s>0&&(l.timeoutMs=s),g?.priority&&g.priority!=="normal"&&(l.priority=g.priority,l.force=g.priority==="force",g.intent&&(l.intent=g.intent),g.ref&&(l.ref=g.ref),g.reason&&(l.reason=g.reason)),o&&(l.voice=o),n){const d=typeof s=="number"&&s>0?s+3e4:0;return await this.httpClient.callToolOnce("send_dm",l,d)}return await this.httpClient.callTool("send_dm",l)}async sendCallAndWaitReply(e,t,n=6e4){const r=await this.sendDirectMessage(e,t,!0,void 0,n);if(r.reply)return r.reply;throw new Error("No reply received for call-style direct message before timeout")}async replyToCall(e,t,n){return await this.sendDirectMessage(t,n,!1,e)}async sendEmail(e){return await this.callAgentScopedTool("send_email",e)}async listEmails(e){return await this.callAgentScopedTool("list_emails",e)}async readEmail(e){return await this.callAgentScopedTool("read_email",{mailId:e})}async replyEmail(e){return await this.callAgentScopedTool("reply_email",e)}async ackEmail(e){return await this.callAgentScopedTool("ack_email",{mailId:e})}async getDmHistory(e,t=50,n){this.ensureRegistered();const r={agentId:this.agentId,targetUserId:e,limit:t};return n&&(r.since=n),await this.httpClient.callTool("get_dm_history",r)}async getGroupHistory(e=50,t,n){if(this.ensureRegistered(),t){const o={projectId:this.projectId||this.agentConfig.projectId,roomId:t,limit:e};return n&&(o.since=n),await this.httpClient.callTool("get_group_history",o)}const r=await this.discoverGroupRooms(),s=this.projectId||this.agentConfig.projectId,a=this.collectRoomIds(r,s);if(a.length===0)return{messages:[],count:0};const g=(await Promise.all(a.map(async o=>{const l={projectId:s,roomId:o,limit:e};return n&&(l.since=n),await this.httpClient.callTool("get_group_history",l)}))).flatMap(o=>o.messages).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime());return{messages:g,count:g.length}}async fetchUnreadMessages(e={}){this.ensureRegistered();const t=this.projectId||this.agentConfig.projectId,n={agentId:this.agentId,blockIfEmpty:e.blockIfEmpty??!1};e.since&&(n.since=e.since),e.blockTimeoutMs&&e.blockTimeoutMs>0&&(n.blockTimeoutMs=e.blockTimeoutMs),e.preemptiveJoinWaitMs!==void 0&&e.preemptiveJoinWaitMs!==null&&e.preemptiveJoinWaitMs>=0&&(n.preemptiveJoinWaitMs=e.preemptiveJoinWaitMs);const r=e.includePipelineTasks?"poll_message":"get_dm_messages";i.info("[AgentClient] fetchUnreadMessages \u5165\u53E3: tool=%s, blockIfEmpty=%s, blockTimeoutMs=%s, pollMessageTimeoutMs=%s, skipGroupMessages=%s, preemptiveJoinWaitMs=%s, agentId=%s",r,String(e.blockIfEmpty??!1),String(e.blockTimeoutMs??"-"),String(e.pollMessageTimeoutMs??"-"),String(e.skipGroupMessages??!1),String(e.preemptiveJoinWaitMs??"-"),this.agentId);const s=await this.fetchDirectMessagesWithRecovery(r,n,e.pollMessageTimeoutMs,e.propagatePollTimeout===!0);if(i.info("[AgentClient] fetchUnreadMessages \u79C1\u4FE1\u9636\u6BB5\u8FD4\u56DE: %s \u6761",Array.isArray(s.messages)?s.messages.length:0),e.skipGroupMessages)return i.info("[AgentClient] \u4F1A\u8BAE\u5FEB\u901F hydrate \u5DF2\u53D6\u5F97\u79C1\u4FE1\u54CD\u5E94\uFF0C\u8DF3\u8FC7\u7FA4\u804A\u53D1\u73B0\u5E76\u7ACB\u5373\u8FD4\u56DE: directMessages=%s",Array.isArray(s.messages)?s.messages.length:0),{directMessages:Array.isArray(s.messages)?s.messages:[],groupMessages:[]};let a;try{a=await this.discoverGroupRooms()}catch(o){i.warn("[AgentClient] \u53D1\u73B0\u7FA4\u623F\u95F4\u5931\u8D25\uFF0C\u672C\u6B21\u6309\u65E0\u7FA4\u6D88\u606F\u5904\u7406\uFF08\u5DF2\u53D6\u5230\u7684\u79C1\u4FE1\u4E0D\u53D7\u5F71\u54CD\uFF09: %s",o instanceof Error?o.message:String(o)),a={groups:[]}}const c=this.collectRoomIds(a,t),g=await Promise.all(c.map(async o=>{const l={agentId:this.agentId,projectId:t,roomId:o};e.since&&(l.since=e.since);try{return await this.httpClient.callTool("get_group_messages",l)}catch(d){return i.warn("[AgentClient] \u8DF3\u8FC7\u7FA4\u623F\u95F4\u672A\u8BFB\u8865\u62C9\u5931\u8D25: roomId=%s, error=%s",o,d instanceof Error?d.message:String(d)),{messages:[],currentReadPos:0,hasMore:!1}}}));return{directMessages:Array.isArray(s.messages)?s.messages:[],groupMessages:g.flatMap(o=>this.normalizeGroupMessages(o)).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime())}}async markDmRead(e){if(e.length===0)return new Set;this.ensureRegistered();try{const t=await this.httpClient.callTool("mark_dm_read",{agentId:this.agentId,msgIds:e}),n=new Set(Array.isArray(t?.deliverableMsgIds)?t.deliverableMsgIds:[]),r=e.filter(s=>!n.has(s));return r.length>0?i.warn("[AgentClient] mark_dm_read \u786E\u8BA4\u540E\u5C06\u6709 %d \u6761\u6D88\u606F\u88AB\u4E22\u5F03\u4E0D\u4EA4\u4ED8: \u8BF7\u6C42=%s, \u53EF\u4EA4\u4ED8=%s, \u88AB\u4E22\u5F03=%s",r.length,JSON.stringify(e),JSON.stringify([...n]),JSON.stringify(r)):i.info("[AgentClient] mark_dm_read \u786E\u8BA4\u5B8C\u6210: %d \u6761\u5168\u90E8\u53EF\u4EA4\u4ED8",e.length),n}catch(t){throw i.warn("[AgentClient] mark_dm_read \u8BF7\u6C42\u5931\u8D25\uFF08\u5C06\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8\uFF09: %s",t instanceof Error?t.message:String(t)),t}}async markForceInjected(e){if(e.length===0)return new Set;this.ensureRegistered();try{const t=await this.httpClient.callTool("mark_force_injected",{agentId:this.agentId,msgIds:e}),n=new Set(Array.isArray(t?.deliverableMsgIds)?t.deliverableMsgIds:[]),r=e.filter(s=>!n.has(s));return r.length>0?i.warn("[AgentClient] mark_force_injected \u786E\u8BA4\u540E\u5C06\u6709 %d \u6761\u5F3A\u5236\u6D88\u606F\u88AB\u4E22\u5F03\u4E0D\u4EA4\u4ED8: \u8BF7\u6C42=%s, \u53EF\u4EA4\u4ED8=%s",r.length,JSON.stringify(e),JSON.stringify([...n])):i.info("[AgentClient] mark_force_injected \u786E\u8BA4\u5B8C\u6210: %d \u6761\u5F3A\u5236\u6D88\u606F\u5DF2\u6CE8\u5165",e.length),n}catch(t){throw i.warn("[AgentClient] mark_force_injected \u8BF7\u6C42\u5931\u8D25\uFF08\u5C06\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8\uFF09: %s",t instanceof Error?t.message:String(t)),t}}async markGroupRead(e,t){if(t.length===0)return new Set;this.ensureRegistered();const n=await this.httpClient.callTool("mark_group_read",{agentId:this.agentId,roomId:e,msgIds:t});return new Set(Array.isArray(n?.deliverableMsgIds)?n.deliverableMsgIds:[])}async markNotificationRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_notification_read",{agentId:this.agentId,msgIds:e})}catch{}}}async markMeetingRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_meeting_read",{agentId:this.agentId,msgIds:e})}catch{}}}async fetchBrowserListenerEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return i.info("[AgentClient] fetchBrowserListenerEvents \u8DF3\u8FC7: bridgeBaseUrl=%s, agentId=%s",e||"(\u7A7A)",t||"(\u7A7A)"),[];try{const n=`${e}/runtime/browser-listeners/${encodeURIComponent(t)}/events`,r=this.serverConfig.runtimeAccessToken||"";i.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6: url=%s, tokenLen=%d",n,r.length);const s=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!s.ok)return i.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",s.status,n),[];const a=await s.json();return!a.ok||!Array.isArray(a.events)?(i.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s, eventsType=%s",a.ok,Array.isArray(a.events)?"array":typeof a.events),[]):(i.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6",a.events.length),a.events)}catch(n){return i.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),[]}}async fetchPluginEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return{revision:0,events:[]};try{const n=`${e}/runtime/plugin-events/${encodeURIComponent(t)}/events`,r=this.serverConfig.runtimeAccessToken||"",s=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!s.ok)return i.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",s.status,n),{revision:0,events:[]};const a=await s.json();return!a.ok||!Array.isArray(a.events)?(i.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s",String(a.ok)),{revision:0,events:[]}):(i.debug("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6, revision=%s",a.events.length,String(a.revision??0)),{revision:a.revision??0,events:a.events})}catch(n){return i.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),{revision:0,events:[]}}}async notifyBridgeForceMessage(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!(!e||!t))try{const n=`${e}/runtime/sessions/${encodeURIComponent(t)}/notify-force-message`,r=this.serverConfig.runtimeAccessToken||"",s=await fetch(n,{method:"POST",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});s.ok||i.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5931\u8D25: HTTP %s, url=%s",s.status,n)}catch(n){i.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5F02\u5E38: %s",n instanceof Error?n.message:String(n))}}async fetchCurrentAction(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return null;try{const n=`${e}/runtime/sessions/${encodeURIComponent(t)}/current-action`,r=this.serverConfig.runtimeAccessToken||"",s=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!s.ok)return i.warn("[AgentClient] \u67E5\u8BE2 bridge \u5F53\u524D\u52A8\u4F5C\u5931\u8D25: HTTP %s, url=%s",s.status,n),null;const a=await s.json();return a?.ok?a:null}catch(n){return i.warn("[AgentClient] \u67E5\u8BE2 bridge \u5F53\u524D\u52A8\u4F5C\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),null}}async fetchDirectMessagesWithRecovery(e,t,n,r=!1){if(e==="poll_message"){i.info("[AgentClient] fetchDirectMessagesWithRecovery \u5165\u53E3: tool=poll_message, pollMessageTimeoutMs=%s, agentId=%s",String(n??"(\u9ED8\u8BA4)"),String(t?.agentId??""));try{const s=await this.httpClient.callToolOnce(e,t,n);return i.info("[AgentClient] fetchDirectMessagesWithRecovery poll_message \u6210\u529F\u8FD4\u56DE: %s \u6761",Array.isArray(s?.messages)?s.messages.length:0),s}catch(s){if(this.isRecoverableLongPollError(s)){if(r)throw new T(s instanceof Error?s.message:String(s));return i.warn("[AgentClient] poll_message \u5355\u6B21\u957F\u8F6E\u8BE2\u8D85\u65F6\uFF0C\u6309\u7A7A\u7ED3\u679C\u9000\u907F\u540E\u7EE7\u7EED\u7B49\u5F85:",s),{messages:[]}}throw s}}return await this.httpClient.callTool(e,t)}isRecoverableLongPollError(e){return e instanceof Error?/MCP tool poll_message call failed: 503(?:\s|$)/.test(e.message)||/MCP tool poll_message timed out after \d+ms/.test(e.message):!1}normalizeGroupMessages(e){return Array.isArray(e.messages)?e.messages.filter(t=>!!(t&&typeof t=="object"&&typeof t.msgId=="number"&&typeof t.senderId=="string"&&typeof t.content=="string"&&typeof t.timestamp=="string")):[]}collectRoomIds(e,t){const n=e.groups.filter(r=>r.projectId===t).map(r=>r.id);return Array.from(new Set(n))}async getProfile(){this.ensureRegistered();const e=this.agentId;if(!e)throw new Error("Agent is not registered");return{...await this.getProfileByAgentId(e),describe:this.agentConfig.describe}}async getProfileByAgentId(e){return await this.httpClient.callTool("get_profile",{agentId:e})}async getMyTasks(){return this.ensureRegistered(),await this.httpClient.callTool("my_task",{agentId:this.agentId})}async listTaskNodeIterations(e={}){return this.ensureRegistered(),await this.httpClient.callTool("list_task_node_iterations",{agentId:this.agentId,...e})}async createTaskInstanceComment(e){this.ensureRegistered();const t={agentId:this.agentId,...e};return await this.httpClient.callTool("create_task_instance_comment",t)}async submitTaskResult(e,t,n,r,s){this.ensureRegistered();const a={agentId:this.agentId,nodeId:e,outputPayload:t};return(Array.isArray(n)&&n.length>0||typeof n=="string"&&n.trim().length>0)&&(a.changeLog=n),typeof r=="string"&&r.trim().length>0&&(a.handoverNote=r),s&&Array.isArray(s)&&s.length>0&&(a.deliverables=s),await this.httpClient.callTool("submit_task_result",a)}async startTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("start_task_rollback",{agentId:this.agentId,...e})}async finishTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("finish_task_rollback",{agentId:this.agentId,...e})}async getDebugLogConfig(){return await this.httpClient.callTool("get_debug_log_config",{agentId:this.agentId})}async queryDebugLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("query_debug_logs",{...e})}async queryFileChangesHistory(e){return this.ensureRegistered(),await this.httpClient.callTool("query_file_changes_history",{...e})}async listColleagueEvents(e){return this.ensureRegistered(),await this.httpClient.callTool("list_colleague_events",{...e})}async getRuntimeFeatures(){return await this.httpClient.fetchRuntimeFeatures()}async listLaunchConfigs(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_list",{})}async createLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_create",{...e})}async updateLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_update",{...e})}async deleteLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_delete",{configId:e})}async startLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_start",e,t+6e4):await this.httpClient.callTool("launch_config_start",{...e})}async restartLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_restart",e,t+6e4):await this.httpClient.callTool("launch_config_restart",{...e})}async stopLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_stop",{configId:e})}async getLaunchLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_logs",{...e})}async listLaunchRuns(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_status",{})}async listAbilityMarket(e={}){return this.ensureRegistered(),await this.httpClient.callTool("list_ability_market",{...e})}async installAbilityMarketItem(e){return this.ensureRegistered(),await this.httpClient.callTool("install_ability_market_item",{...e})}async uninstallAbilityMarketItem(e){return this.ensureRegistered(),await this.httpClient.callTool("uninstall_ability_market_item",{...e})}async abilityDevIde(e){return this.ensureRegistered(),await this.httpClient.callTool("ability_dev_ide",{...e})}async formalAbility(e){return this.ensureRegistered(),await this.httpClient.callTool("formal_ability",{...e})}async listMyAbilities(e={}){return this.ensureRegistered(),await this.httpClient.callTool("list_my_abilities",{...e})}start(e,t){if(this.isRunning){i.warn("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u5DF2\u5728\u8FD0\u884C\u4E2D");return}this.isDegradedMode||this.ensureRegistered(),this.messageHandler=e,this.profileHandler=t?.profileHandler||null,this.configHandler=t?.configHandler||null,this.systemNotifyHandler=t?.systemNotifyHandler||null,this.isRunning=!0,i.info(`[AgentClient] start() \u88AB\u8C03\u7528\uFF0CcachedProfile: ${this.cachedProfile?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}, profileHandler: ${this.profileHandler?"\u5DF2\u8BBE\u7F6E":"\u672A\u8BBE\u7F6E"}, \u964D\u7EA7\u6A21\u5F0F: ${this.isDegradedMode?"\u662F":"\u5426"}`),this.cachedProfile&&this.profileHandler&&(i.info(`[AgentClient] \u5904\u7406\u7F13\u5B58\u7684 Profile \u4FE1\u606F: ${this.cachedProfile.displayName}`),this.profileHandler(this.cachedProfile),this.cachedProfile=null),t?.pollMode??!1?(i.warn("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08HTTP\u8F6E\u8BE2\u6A21\u5F0F - \u4E0D\u63A8\u8350\uFF09"),this.messageLoop()):i.info("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08WebSocket\u63A8\u9001\u6A21\u5F0F - \u63A8\u8350\uFF09")}stop(){this.isRunning=!1,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),this.stopRuntimeTokenRefresh(),i.info("[AgentClient] \u6D88\u606F\u4E3B\u5FAA\u73AF\u5DF2\u505C\u6B62")}async messageLoop(){for(;this.isRunning;)try{await this.delay(I)}catch(e){i.error("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u9519\u8BEF:",e),await this.delay(5e3)}}handleIncomingDm(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingGroup(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingMeeting(e){!e||e.senderId===this.agentId||this.processMessage(e)}handleProfileInfo(e){i.info(`[AgentClient] \u6536\u5230 Profile \u4FE1\u606F: ${e.displayName} (${e.roleName})`),e.projectId&&(this.projectId=e.projectId,i.info(`[AgentClient] \u66F4\u65B0\u6240\u5C5E\u9879\u76EE: ${this.projectId}`)),e.roleName&&e.roleName!==this.agentConfig.roleName&&(i.info(`[AgentClient] \u540C\u6B65\u89D2\u8272\u540D: "${this.agentConfig.roleName||"(\u7A7A)"}" -> "${e.roleName}"`),this.agentConfig.roleName=e.roleName),e.roleName&&u(e.roleName,e.instanceName||this.agentId||""),this.profileHandler?this.profileHandler(e):(i.info("[AgentClient] profileHandler \u672A\u8BBE\u7F6E\uFF0C\u7F13\u5B58 Profile \u4FE1\u606F"),this.cachedProfile=e)}async processMessage(e){if(!this.messageHandler)return;const t=typeof e.msgId=="string";i.info(`[AgentClient] \u6536\u5230${t?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F"}\u6765\u81EA ${e.senderName}: ${e.content.substring(0,50)}...`);try{const n=await this.messageHandler(e);if(t){const r=e;r.requireReply&&r.callId&&await this.replyToCall(r.callId,r.senderId,n||"\u5DF2\u6536\u5230\u6D88\u606F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D...")}}catch(n){const r=typeof e.msgId=="string";if(i.error("[AgentClient] \u5904\u7406\u6D88\u606F\u5931\u8D25: type=%s, senderId=%s, senderName=%s, msgId=%s, error=%s",r?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F",e.senderId,e.senderName,e.msgId,n instanceof Error?n.message:String(n)),r){const s=e;s.requireReply&&s.callId&&await this.replyToCall(s.callId,s.senderId,`\u5904\u7406\u5931\u8D25: ${n}`)}}}ensureRegistered(){if(!this.agentId)throw new Error("Agent is not registered")}delay(e){return new Promise(t=>{this.pollTimer=setTimeout(t,e)})}onNewCharacter(e){this.newCharacterHandler=e}getState(){return{agentId:this.agentId,displayName:this.displayName,projectId:this.projectId,isConnected:this.wsClient.isConnected(),isRunning:this.isRunning}}getAgentConfig(){return this.agentConfig}getServerConfig(){return this.serverConfig}reloadConfig(){h.loadConfig(),this.agentConfig=h.getAgentConfig(),i.info(`[AgentClient] \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D\uFF0C\u89D2\u8272: ${this.agentConfig.roleName}`)}enterDegradedMode(){this.isDegradedMode=!0,i.warn("[AgentClient] \u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F\uFF0C\u5C06\u5728\u540E\u53F0\u6301\u7EED\u5C1D\u8BD5\u91CD\u8FDE")}exitDegradedMode(){this.isDegradedMode=!1,i.info("[AgentClient] \u9000\u51FA\u964D\u7EA7\u6A21\u5F0F")}isInDegradedMode(){return this.isDegradedMode}async retryRegistrationInBackground(e,t){let n=0;(async()=>{for(;this.isDegradedMode;)try{i.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u5C1D\u8BD5\u91CD\u65B0\u6CE8\u518C (${n+1}/${t===-1?"\u65E0\u9650":t})`);const s=await this.register();i.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u6210\u529F - ${s.displayName} (${s.agentId})`),this.exitDegradedMode(),this.messageHandler&&this.start(this.messageHandler);return}catch(s){n++;const a=s instanceof Error?s.message:String(s);if(i.warn(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u5931\u8D25 (${n}/${t===-1?"\u65E0\u9650":t}): ${a}`),t>0&&n>=t){i.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u505C\u6B62\u91CD\u8FDE"),this.isDegradedMode=!1;return}await new Promise(c=>setTimeout(c,e))}})().catch(s=>{i.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\u540E\u53F0\u91CD\u8BD5\u5FAA\u73AF\u5F02\u5E38\u9000\u51FA: error=%s, stack=%s",s instanceof Error?s.message:String(s),s instanceof Error?s.stack:"(no stack)")})}initializeStatusReporter(){if(!this.agentId){i.warn("[AgentClient] \u65E0\u6CD5\u521D\u59CB\u5316\u72B6\u6001\u62A5\u544A\u5668\uFF1AagentId \u4E3A\u7A7A");return}this.statusReporter=new A({agentId:this.agentId,sendStatusUpdate:e=>{this.wsClient.send({type:"AGENT_STATUS",data:e,timestamp:new Date().toISOString()})}}),w(e=>this.reportMcpNodeLog(e)),this.startRuntimeTokenRefresh(),i.info("[AgentClient] \u72B6\u6001\u62A5\u544A\u5668\u5DF2\u521D\u59CB\u5316")}startRuntimeTokenRefresh(){this.stopRuntimeTokenRefresh();const e=this.serverConfig.runtimeTokenRefreshIntervalMs;if(!e||e<=0){i.warn("[AgentClient] runtimeTokenRefreshIntervalMs \u672A\u914D\u7F6E\u6216\u65E0\u6548\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}const t=this.agentId;if(!t){i.warn("[AgentClient] agentId \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}this.runtimeTokenRefreshTimer=setInterval(async()=>{try{await this.httpClient.refreshRuntimeAccessToken(t)&&i.info("[AgentClient] runtimeAccessToken \u5DF2\u4E3B\u52A8\u7EED\u671F")}catch(n){i.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F runtimeAccessToken \u5931\u8D25: %s",n instanceof Error?n.message:String(n)),n instanceof Error&&n.stack&&i.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F\u5F02\u5E38\u5806\u6808:",n.stack)}},e),this.runtimeTokenRefreshTimer.unref?.(),i.info(`[AgentClient] runtime token \u4E3B\u52A8\u7EED\u671F\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${e}ms`)}stopRuntimeTokenRefresh(){this.runtimeTokenRefreshTimer&&(clearInterval(this.runtimeTokenRefreshTimer),this.runtimeTokenRefreshTimer=null)}reportMcpNodeLog(e){const t=this.wsClient;!this.agentId||!this.wsClient.isConnected()||typeof t.sendMcpNodeLog!="function"||t.sendMcpNodeLog(e)}getStatusReporter(){return this.statusReporter}}export{N as AgentClient,T as PollLongPollTimeoutError};
1
+ import{configManager as c}from"./config.js";import{MESSAGE_POLL_INTERVAL_MS as I}from"./constants.js";import{HttpClient as f}from"./http-client.js";import{logger as i,setMcpNodeLogSink as w,updateStartupLogIdentity as u}from"./logger.js";import{claimRuntimeLaunchBindingDetailed as m}from"./runtime-launch-binding.js";import{StatusReporter as A}from"./status-reporter.js";import{WebSocketClient as p}from"./websocket-client.js";class T extends Error{constructor(e){super(e),this.name="PollLongPollTimeoutError"}}const C=27e4;class N{wsClient;httpClient;agentConfig;serverConfig;agentId=null;displayName=null;projectId=null;isRunning=!1;isDegradedMode=!1;messageHandler=null;profileHandler=null;configHandler=null;systemNotifyHandler=null;pollTimer=null;statusReporter=null;newCharacterHandler=null;runtimeTokenRefreshTimer=null;pendingLaunchBindingClaim=!1;cachedProfile=null;constructor(){c.loadConfig(),this.agentConfig=c.getAgentConfig(),this.serverConfig=c.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async initialize(){const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed"){this.applyLaunchBinding(e.binding);return}if(e.status==="unreachable"){this.pendingLaunchBindingClaim=!0,i.warn("[AgentClient] runtime-bridge \u672A\u5C31\u7EEA\uFF0C\u542F\u52A8\u7ED1\u5B9A\u8BA4\u9886\u5DF2\u6302\u8D77\uFF0C\u5C06\u5728\u6CE8\u518C\u91CD\u8BD5\u4E2D\u91CD\u65B0\u8BA4\u9886: %s",e.message);return}this.serverConfig.runtimeBridgeBaseUrl=void 0}applyLaunchBinding(e){c.applyRuntimeLaunchBinding(e),this.agentConfig=c.getAgentConfig(),this.serverConfig=c.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async retryPendingLaunchBindingClaim(){if(!this.pendingLaunchBindingClaim)return!0;const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed")return this.pendingLaunchBindingClaim=!1,i.info("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u6210\u529F\uFF0C\u7EE7\u7EED\u6CE8\u518C\u6D41\u7A0B"),this.applyLaunchBinding(e.binding),!0;if(e.status==="missing")return this.pendingLaunchBindingClaim=!1,this.serverConfig.runtimeBridgeBaseUrl=void 0,i.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u672A\u627E\u5230\u5F85\u8BA4\u9886\u8BB0\u5F55\uFF0C\u6309\u65E0\u7ED1\u5B9A\u6A21\u5F0F\u7EE7\u7EED\u6CE8\u518C"),!1;const t=e.status==="unreachable"?e.message:e.reason;return i.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u5931\u8D25\uFF0C\u4FDD\u7559\u6302\u8D77\u72B6\u6001\u7B49\u5F85\u4E0B\u6B21\u6CE8\u518C\u91CD\u8BD5: %s",t),!1}setupWebSocketListeners(){this.wsClient.on("directMessage",e=>{this.handleIncomingDm(e)}),this.wsClient.on("groupMessage",e=>{this.handleIncomingGroup(e)}),this.wsClient.on("meetingMessage",e=>{this.handleIncomingMeeting(e)}),this.wsClient.on("systemNotify",e=>{this.systemNotifyHandler?.(e)}),this.wsClient.on("profileInfo",e=>{i.info(`[AgentClient] WebSocket profileInfo \u4E8B\u4EF6\u89E6\u53D1\uFF0CdisplayName: ${e.displayName}`),this.handleProfileInfo(e)}),this.wsClient.on("agentConfig",e=>{i.info("[AgentClient] WebSocket agentConfig \u4E8B\u4EF6\u89E6\u53D1"),this.configHandler&&this.configHandler(e??{})}),this.wsClient.on("agentStatus",e=>{i.info(`[AgentClient] WebSocket agentStatus \u4E8B\u4EF6\u89E6\u53D1: ${e.status}`)}),this.wsClient.on("disconnected",(e,t)=>{const n=t?.toString()||"";i.warn("[AgentClient] WebSocket \u65AD\u5F00\u8FDE\u63A5: code=%s, reason=%s, agentId=%s, \u6B63\u5728\u81EA\u52A8\u91CD\u8FDE",e,n,this.agentId)}),this.wsClient.on("error",e=>{i.error("[AgentClient] WebSocket \u9519\u8BEF: %s, stack=%s",e.message,e.stack)}),this.wsClient.on("reconnectFailed",()=>{i.error("[AgentClient] \u91CD\u8FDE\u5931\u8D25\uFF08\u5DF2\u8FBE\u91CD\u8BD5\u4E0A\u9650\uFF09\uFF0C\u505C\u6B62\u6D88\u606F\u5FAA\u73AF, agentId=%s",this.agentId),this.stop()}),this.wsClient.on("tokenRejected",()=>{i.error("[AgentClient] runtime token \u88AB 1008 \u62D2\u7EDD\u4E14\u5237\u65B0\u65E0\u53D8\u5316\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85\u65B0 token \u7B7E\u53D1: agentId=%s",this.agentId)}),this.wsClient.on("tokenRefreshFailed",e=>{i.error("[AgentClient] runtime token \u5237\u65B0\u8FDE\u7EED\u5931\u8D25 %s \u6B21\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85 bridge \u6062\u590D: agentId=%s",e,this.agentId)})}async register(){return i.info("[AgentClient] \u6B63\u5728\u6CE8\u518C Agent..."),await this.retryPendingLaunchBindingClaim(),this.hasPresetAgentId()?await this.registerWithExistingAgentId():await this.registerAsNewAgent()}hasPresetAgentId(){return!!(this.agentConfig.agentId&&this.agentConfig.agentId.trim().length>0)}async registerWithExistingAgentId(){const e=this.agentConfig.agentId;if(!e)throw new Error("Preset agentId is missing");this.agentId=e.trim();let t;try{t=await this.getProfileByAgentId(this.agentId)}catch(r){throw i.error("[AgentClient] getProfileByAgentId \u5931\u8D25 (presetAgentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}this.displayName=t.displayName,this.projectId=t.projectId||null,i.info(`[AgentClient] \u4F7F\u7528\u9884\u8BBE AgentID \u7ED1\u5B9A\u5B9E\u4F8B: ${this.displayName} (${this.agentId})`),i.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`);try{await this.wsClient.connect(this.agentId)}catch(r){throw i.error("[AgentClient] WebSocket \u8FDE\u63A5\u5931\u8D25 (agentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}i.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter();const n=await this.getProfileByAgentId(this.agentId);return this.displayName=n.displayName,this.projectId=n.projectId||null,u(n.roleName||"unknown-role",n.instanceName||this.agentId),{agentId:this.agentId,displayName:this.displayName,status:n.isOnline?"online":"offline",projectId:n.projectId,workspacePath:n.workspacePath,runtimeStatus:n.runtimeStatus,runtimeSessionId:n.runtimeSessionId}}async registerAsNewAgent(){const e=await this.httpClient.callTool("register",{roleName:this.agentConfig.roleName,projectId:this.agentConfig.projectId,workspacePath:this.agentConfig.workspacePath,prompt:this.agentConfig.prompt,runtimeBridgeBaseUrl:this.serverConfig.runtimeBridgeBaseUrl}),t=e.agentId;if(!t)throw new Error("Registration failed: agentId was not returned");return this.agentId=t,this.displayName=e.displayName,this.projectId=e.projectId||null,u(this.agentConfig.roleName||"unknown-role",e.instanceName||t),i.info(`[AgentClient] \u6CE8\u518C\u6210\u529F: ${this.displayName} (${this.agentId})`),i.info(`[AgentClient] \u72B6\u6001: ${e.status}`),i.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`),await this.wsClient.connect(this.agentId),i.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter(),e.isExisting===!1&&this.newCharacterHandler&&this.newCharacterHandler(),e}async unregister(){i.info("[AgentClient] \u6B63\u5728\u6CE8\u9500 Agent..."),this.agentId&&await this.httpClient.callTool("unregister",{agentId:this.agentId}),this.stopRuntimeTokenRefresh(),this.wsClient.disconnect(),this.agentId=null,this.displayName=null,this.projectId=null,this.isRunning=!1,i.info("[AgentClient] \u5DF2\u6CE8\u9500")}async discoverColleagues(){return await this.httpClient.callTool("discover_colleague",{agentId:this.agentId})}async discoverGroupRooms(){return this.ensureRegistered(),await this.httpClient.callTool("discover_group_rooms",{agentId:this.agentId})}async listProjectMembers(){return this.ensureRegistered(),await this.httpClient.callTool("list_project_members",{agentId:this.agentId})}async hireColleague(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleague",{...e,agentId:this.agentId})}async callAgentScopedTool(e,t){this.ensureRegistered();const n={...t,agentId:this.agentId};if(e==="create_meeting"){const r=typeof t.waitTimeoutMs=="number"?t.waitTimeoutMs:Number.NaN,s=Number.isFinite(r)&&r>0?Math.min(r,C):C;return await this.httpClient.callToolOnce(e,{...n,waitTimeoutMs:s},0)}return await this.httpClient.callTool(e,n)}async reportMemoryStats(e){await this.callAgentScopedTool("report_memory_stats",{memoryStats:e})}async sendGroupMessage(e,t,n,r,s,a){this.ensureRegistered();const h=t||this.projectId||this.agentConfig.projectId,g={agentId:this.agentId,projectId:h,roomId:n,content:e,card:r,replyTo:s,...a?{voice:a}:{}};return a?await this.httpClient.callToolOnce("send_group_message",g,9e5):await this.httpClient.callTool("send_group_message",g)}async sendDirectMessage(e,t,n=!1,r,s,a,h,g,o){this.ensureRegistered();const l={agentId:this.agentId,targetId:e,content:t,requireReply:n,waitReply:n,replyToCallId:r,card:a,replyTo:h};if(typeof s=="number"&&s>0&&(l.timeoutMs=s),g?.priority&&g.priority!=="normal"&&(l.priority=g.priority,l.force=g.priority==="force",g.intent&&(l.intent=g.intent),g.ref&&(l.ref=g.ref),g.reason&&(l.reason=g.reason)),o&&(l.voice=o),n){const d=typeof s=="number"&&s>0?s+3e4:0;return await this.httpClient.callToolOnce("send_dm",l,d)}return o&&!o.async?await this.httpClient.callToolOnce("send_dm",l,9e5):await this.httpClient.callTool("send_dm",l)}async getDmSendStatus(e){return this.ensureRegistered(),await this.httpClient.callTool("get_dm_send_status",{agentId:this.agentId,ticket:e})}async sendCallAndWaitReply(e,t,n=6e4){const r=await this.sendDirectMessage(e,t,!0,void 0,n);if(r.reply)return r.reply;throw new Error("No reply received for call-style direct message before timeout")}async replyToCall(e,t,n){return await this.sendDirectMessage(t,n,!1,e)}async sendEmail(e){return await this.callAgentScopedTool("send_email",e)}async listEmails(e){return await this.callAgentScopedTool("list_emails",e)}async readEmail(e){return await this.callAgentScopedTool("read_email",{mailId:e})}async replyEmail(e){return await this.callAgentScopedTool("reply_email",e)}async ackEmail(e){return await this.callAgentScopedTool("ack_email",{mailId:e})}async getDmHistory(e,t=50,n){this.ensureRegistered();const r={agentId:this.agentId,targetUserId:e,limit:t};return n&&(r.since=n),await this.httpClient.callTool("get_dm_history",r)}async getGroupHistory(e=50,t,n){if(this.ensureRegistered(),t){const o={projectId:this.projectId||this.agentConfig.projectId,roomId:t,limit:e};return n&&(o.since=n),await this.httpClient.callTool("get_group_history",o)}const r=await this.discoverGroupRooms(),s=this.projectId||this.agentConfig.projectId,a=this.collectRoomIds(r,s);if(a.length===0)return{messages:[],count:0};const g=(await Promise.all(a.map(async o=>{const l={projectId:s,roomId:o,limit:e};return n&&(l.since=n),await this.httpClient.callTool("get_group_history",l)}))).flatMap(o=>o.messages).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime());return{messages:g,count:g.length}}async fetchUnreadMessages(e={}){this.ensureRegistered();const t=this.projectId||this.agentConfig.projectId,n={agentId:this.agentId,blockIfEmpty:e.blockIfEmpty??!1};e.since&&(n.since=e.since),e.blockTimeoutMs&&e.blockTimeoutMs>0&&(n.blockTimeoutMs=e.blockTimeoutMs),e.preemptiveJoinWaitMs!==void 0&&e.preemptiveJoinWaitMs!==null&&e.preemptiveJoinWaitMs>=0&&(n.preemptiveJoinWaitMs=e.preemptiveJoinWaitMs);const r=e.includePipelineTasks?"poll_message":"get_dm_messages";i.info("[AgentClient] fetchUnreadMessages \u5165\u53E3: tool=%s, blockIfEmpty=%s, blockTimeoutMs=%s, pollMessageTimeoutMs=%s, skipGroupMessages=%s, preemptiveJoinWaitMs=%s, agentId=%s",r,String(e.blockIfEmpty??!1),String(e.blockTimeoutMs??"-"),String(e.pollMessageTimeoutMs??"-"),String(e.skipGroupMessages??!1),String(e.preemptiveJoinWaitMs??"-"),this.agentId);const s=await this.fetchDirectMessagesWithRecovery(r,n,e.pollMessageTimeoutMs,e.propagatePollTimeout===!0);if(i.info("[AgentClient] fetchUnreadMessages \u79C1\u4FE1\u9636\u6BB5\u8FD4\u56DE: %s \u6761",Array.isArray(s.messages)?s.messages.length:0),e.skipGroupMessages)return i.info("[AgentClient] \u4F1A\u8BAE\u5FEB\u901F hydrate \u5DF2\u53D6\u5F97\u79C1\u4FE1\u54CD\u5E94\uFF0C\u8DF3\u8FC7\u7FA4\u804A\u53D1\u73B0\u5E76\u7ACB\u5373\u8FD4\u56DE: directMessages=%s",Array.isArray(s.messages)?s.messages.length:0),{directMessages:Array.isArray(s.messages)?s.messages:[],groupMessages:[]};let a;try{a=await this.discoverGroupRooms()}catch(o){i.warn("[AgentClient] \u53D1\u73B0\u7FA4\u623F\u95F4\u5931\u8D25\uFF0C\u672C\u6B21\u6309\u65E0\u7FA4\u6D88\u606F\u5904\u7406\uFF08\u5DF2\u53D6\u5230\u7684\u79C1\u4FE1\u4E0D\u53D7\u5F71\u54CD\uFF09: %s",o instanceof Error?o.message:String(o)),a={groups:[]}}const h=this.collectRoomIds(a,t),g=await Promise.all(h.map(async o=>{const l={agentId:this.agentId,projectId:t,roomId:o};e.since&&(l.since=e.since);try{return await this.httpClient.callTool("get_group_messages",l)}catch(d){return i.warn("[AgentClient] \u8DF3\u8FC7\u7FA4\u623F\u95F4\u672A\u8BFB\u8865\u62C9\u5931\u8D25: roomId=%s, error=%s",o,d instanceof Error?d.message:String(d)),{messages:[],currentReadPos:0,hasMore:!1}}}));return{directMessages:Array.isArray(s.messages)?s.messages:[],groupMessages:g.flatMap(o=>this.normalizeGroupMessages(o)).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime())}}async markDmRead(e){if(e.length===0)return new Set;this.ensureRegistered();try{const t=await this.httpClient.callTool("mark_dm_read",{agentId:this.agentId,msgIds:e}),n=new Set(Array.isArray(t?.deliverableMsgIds)?t.deliverableMsgIds:[]),r=e.filter(s=>!n.has(s));return r.length>0?i.warn("[AgentClient] mark_dm_read \u786E\u8BA4\u540E\u5C06\u6709 %d \u6761\u6D88\u606F\u88AB\u4E22\u5F03\u4E0D\u4EA4\u4ED8: \u8BF7\u6C42=%s, \u53EF\u4EA4\u4ED8=%s, \u88AB\u4E22\u5F03=%s",r.length,JSON.stringify(e),JSON.stringify([...n]),JSON.stringify(r)):i.info("[AgentClient] mark_dm_read \u786E\u8BA4\u5B8C\u6210: %d \u6761\u5168\u90E8\u53EF\u4EA4\u4ED8",e.length),n}catch(t){throw i.warn("[AgentClient] mark_dm_read \u8BF7\u6C42\u5931\u8D25\uFF08\u5C06\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8\uFF09: %s",t instanceof Error?t.message:String(t)),t}}async markForceInjected(e){if(e.length===0)return new Set;this.ensureRegistered();try{const t=await this.httpClient.callTool("mark_force_injected",{agentId:this.agentId,msgIds:e}),n=new Set(Array.isArray(t?.deliverableMsgIds)?t.deliverableMsgIds:[]),r=e.filter(s=>!n.has(s));return r.length>0?i.warn("[AgentClient] mark_force_injected \u786E\u8BA4\u540E\u5C06\u6709 %d \u6761\u5F3A\u5236\u6D88\u606F\u88AB\u4E22\u5F03\u4E0D\u4EA4\u4ED8: \u8BF7\u6C42=%s, \u53EF\u4EA4\u4ED8=%s",r.length,JSON.stringify(e),JSON.stringify([...n])):i.info("[AgentClient] mark_force_injected \u786E\u8BA4\u5B8C\u6210: %d \u6761\u5F3A\u5236\u6D88\u606F\u5DF2\u6CE8\u5165",e.length),n}catch(t){throw i.warn("[AgentClient] mark_force_injected \u8BF7\u6C42\u5931\u8D25\uFF08\u5C06\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8\uFF09: %s",t instanceof Error?t.message:String(t)),t}}async markGroupRead(e,t){if(t.length===0)return new Set;this.ensureRegistered();const n=await this.httpClient.callTool("mark_group_read",{agentId:this.agentId,roomId:e,msgIds:t});return new Set(Array.isArray(n?.deliverableMsgIds)?n.deliverableMsgIds:[])}async markNotificationRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_notification_read",{agentId:this.agentId,msgIds:e})}catch{}}}async markMeetingRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_meeting_read",{agentId:this.agentId,msgIds:e})}catch{}}}async fetchBrowserListenerEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return i.info("[AgentClient] fetchBrowserListenerEvents \u8DF3\u8FC7: bridgeBaseUrl=%s, agentId=%s",e||"(\u7A7A)",t||"(\u7A7A)"),[];try{const n=`${e}/runtime/browser-listeners/${encodeURIComponent(t)}/events`,r=this.serverConfig.runtimeAccessToken||"";i.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6: url=%s, tokenLen=%d",n,r.length);const s=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!s.ok)return i.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",s.status,n),[];const a=await s.json();return!a.ok||!Array.isArray(a.events)?(i.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s, eventsType=%s",a.ok,Array.isArray(a.events)?"array":typeof a.events),[]):(i.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6",a.events.length),a.events)}catch(n){return i.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),[]}}async fetchPluginEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return{revision:0,events:[]};try{const n=`${e}/runtime/plugin-events/${encodeURIComponent(t)}/events`,r=this.serverConfig.runtimeAccessToken||"",s=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!s.ok)return i.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",s.status,n),{revision:0,events:[]};const a=await s.json();return!a.ok||!Array.isArray(a.events)?(i.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s",String(a.ok)),{revision:0,events:[]}):(i.debug("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6, revision=%s",a.events.length,String(a.revision??0)),{revision:a.revision??0,events:a.events})}catch(n){return i.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),{revision:0,events:[]}}}async notifyBridgeForceMessage(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!(!e||!t))try{const n=`${e}/runtime/sessions/${encodeURIComponent(t)}/notify-force-message`,r=this.serverConfig.runtimeAccessToken||"",s=await fetch(n,{method:"POST",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});s.ok||i.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5931\u8D25: HTTP %s, url=%s",s.status,n)}catch(n){i.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5F02\u5E38: %s",n instanceof Error?n.message:String(n))}}async fetchCurrentAction(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return null;try{const n=`${e}/runtime/sessions/${encodeURIComponent(t)}/current-action`,r=this.serverConfig.runtimeAccessToken||"",s=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!s.ok)return i.warn("[AgentClient] \u67E5\u8BE2 bridge \u5F53\u524D\u52A8\u4F5C\u5931\u8D25: HTTP %s, url=%s",s.status,n),null;const a=await s.json();return a?.ok?a:null}catch(n){return i.warn("[AgentClient] \u67E5\u8BE2 bridge \u5F53\u524D\u52A8\u4F5C\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),null}}async fetchDirectMessagesWithRecovery(e,t,n,r=!1){if(e==="poll_message"){i.info("[AgentClient] fetchDirectMessagesWithRecovery \u5165\u53E3: tool=poll_message, pollMessageTimeoutMs=%s, agentId=%s",String(n??"(\u9ED8\u8BA4)"),String(t?.agentId??""));try{const s=await this.httpClient.callToolOnce(e,t,n);return i.info("[AgentClient] fetchDirectMessagesWithRecovery poll_message \u6210\u529F\u8FD4\u56DE: %s \u6761",Array.isArray(s?.messages)?s.messages.length:0),s}catch(s){if(this.isRecoverableLongPollError(s)){if(r)throw new T(s instanceof Error?s.message:String(s));return i.warn("[AgentClient] poll_message \u5355\u6B21\u957F\u8F6E\u8BE2\u8D85\u65F6\uFF0C\u6309\u7A7A\u7ED3\u679C\u9000\u907F\u540E\u7EE7\u7EED\u7B49\u5F85:",s),{messages:[]}}throw s}}return await this.httpClient.callTool(e,t)}isRecoverableLongPollError(e){return e instanceof Error?/MCP tool poll_message call failed: 503(?:\s|$)/.test(e.message)||/MCP tool poll_message timed out after \d+ms/.test(e.message):!1}normalizeGroupMessages(e){return Array.isArray(e.messages)?e.messages.filter(t=>!!(t&&typeof t=="object"&&typeof t.msgId=="number"&&typeof t.senderId=="string"&&typeof t.content=="string"&&typeof t.timestamp=="string")):[]}collectRoomIds(e,t){const n=e.groups.filter(r=>r.projectId===t).map(r=>r.id);return Array.from(new Set(n))}async getProfile(){this.ensureRegistered();const e=this.agentId;if(!e)throw new Error("Agent is not registered");return{...await this.getProfileByAgentId(e),describe:this.agentConfig.describe}}async getProfileByAgentId(e){return await this.httpClient.callTool("get_profile",{agentId:e})}async getMyTasks(){return this.ensureRegistered(),await this.httpClient.callTool("my_task",{agentId:this.agentId})}async listTaskNodeIterations(e={}){return this.ensureRegistered(),await this.httpClient.callTool("list_task_node_iterations",{agentId:this.agentId,...e})}async createTaskInstanceComment(e){this.ensureRegistered();const t={agentId:this.agentId,...e};return await this.httpClient.callTool("create_task_instance_comment",t)}async submitTaskResult(e,t,n,r,s){this.ensureRegistered();const a={agentId:this.agentId,nodeId:e,outputPayload:t};return(Array.isArray(n)&&n.length>0||typeof n=="string"&&n.trim().length>0)&&(a.changeLog=n),typeof r=="string"&&r.trim().length>0&&(a.handoverNote=r),s&&Array.isArray(s)&&s.length>0&&(a.deliverables=s),await this.httpClient.callTool("submit_task_result",a)}async startTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("start_task_rollback",{agentId:this.agentId,...e})}async finishTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("finish_task_rollback",{agentId:this.agentId,...e})}async getDebugLogConfig(){return await this.httpClient.callTool("get_debug_log_config",{agentId:this.agentId})}async queryDebugLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("query_debug_logs",{...e})}async queryFileChangesHistory(e){return this.ensureRegistered(),await this.httpClient.callTool("query_file_changes_history",{...e})}async listColleagueEvents(e){return this.ensureRegistered(),await this.httpClient.callTool("list_colleague_events",{...e})}async getRuntimeFeatures(){return await this.httpClient.fetchRuntimeFeatures()}async listLaunchConfigs(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_list",{})}async createLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_create",{...e})}async updateLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_update",{...e})}async deleteLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_delete",{configId:e})}async startLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_start",e,t+6e4):await this.httpClient.callTool("launch_config_start",{...e})}async restartLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_restart",e,t+6e4):await this.httpClient.callTool("launch_config_restart",{...e})}async stopLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_stop",{configId:e})}async getLaunchLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_logs",{...e})}async listLaunchRuns(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_status",{})}async listAbilityMarket(e={}){return this.ensureRegistered(),await this.httpClient.callTool("list_ability_market",{...e})}async installAbilityMarketItem(e){return this.ensureRegistered(),await this.httpClient.callTool("install_ability_market_item",{...e})}async uninstallAbilityMarketItem(e){return this.ensureRegistered(),await this.httpClient.callTool("uninstall_ability_market_item",{...e})}async abilityDevIde(e){return this.ensureRegistered(),await this.httpClient.callTool("ability_dev_ide",{...e})}async formalAbility(e){return this.ensureRegistered(),await this.httpClient.callTool("formal_ability",{...e})}async listMyAbilities(e={}){return this.ensureRegistered(),await this.httpClient.callTool("list_my_abilities",{...e})}start(e,t){if(this.isRunning){i.warn("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u5DF2\u5728\u8FD0\u884C\u4E2D");return}this.isDegradedMode||this.ensureRegistered(),this.messageHandler=e,this.profileHandler=t?.profileHandler||null,this.configHandler=t?.configHandler||null,this.systemNotifyHandler=t?.systemNotifyHandler||null,this.isRunning=!0,i.info(`[AgentClient] start() \u88AB\u8C03\u7528\uFF0CcachedProfile: ${this.cachedProfile?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}, profileHandler: ${this.profileHandler?"\u5DF2\u8BBE\u7F6E":"\u672A\u8BBE\u7F6E"}, \u964D\u7EA7\u6A21\u5F0F: ${this.isDegradedMode?"\u662F":"\u5426"}`),this.cachedProfile&&this.profileHandler&&(i.info(`[AgentClient] \u5904\u7406\u7F13\u5B58\u7684 Profile \u4FE1\u606F: ${this.cachedProfile.displayName}`),this.profileHandler(this.cachedProfile),this.cachedProfile=null),t?.pollMode??!1?(i.warn("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08HTTP\u8F6E\u8BE2\u6A21\u5F0F - \u4E0D\u63A8\u8350\uFF09"),this.messageLoop()):i.info("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08WebSocket\u63A8\u9001\u6A21\u5F0F - \u63A8\u8350\uFF09")}stop(){this.isRunning=!1,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),this.stopRuntimeTokenRefresh(),i.info("[AgentClient] \u6D88\u606F\u4E3B\u5FAA\u73AF\u5DF2\u505C\u6B62")}async messageLoop(){for(;this.isRunning;)try{await this.delay(I)}catch(e){i.error("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u9519\u8BEF:",e),await this.delay(5e3)}}handleIncomingDm(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingGroup(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingMeeting(e){!e||e.senderId===this.agentId||this.processMessage(e)}handleProfileInfo(e){i.info(`[AgentClient] \u6536\u5230 Profile \u4FE1\u606F: ${e.displayName} (${e.roleName})`),e.projectId&&(this.projectId=e.projectId,i.info(`[AgentClient] \u66F4\u65B0\u6240\u5C5E\u9879\u76EE: ${this.projectId}`)),e.roleName&&e.roleName!==this.agentConfig.roleName&&(i.info(`[AgentClient] \u540C\u6B65\u89D2\u8272\u540D: "${this.agentConfig.roleName||"(\u7A7A)"}" -> "${e.roleName}"`),this.agentConfig.roleName=e.roleName),e.roleName&&u(e.roleName,e.instanceName||this.agentId||""),this.profileHandler?this.profileHandler(e):(i.info("[AgentClient] profileHandler \u672A\u8BBE\u7F6E\uFF0C\u7F13\u5B58 Profile \u4FE1\u606F"),this.cachedProfile=e)}async processMessage(e){if(!this.messageHandler)return;const t=typeof e.msgId=="string";i.info(`[AgentClient] \u6536\u5230${t?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F"}\u6765\u81EA ${e.senderName}: ${e.content.substring(0,50)}...`);try{const n=await this.messageHandler(e);if(t){const r=e;r.requireReply&&r.callId&&await this.replyToCall(r.callId,r.senderId,n||"\u5DF2\u6536\u5230\u6D88\u606F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D...")}}catch(n){const r=typeof e.msgId=="string";if(i.error("[AgentClient] \u5904\u7406\u6D88\u606F\u5931\u8D25: type=%s, senderId=%s, senderName=%s, msgId=%s, error=%s",r?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F",e.senderId,e.senderName,e.msgId,n instanceof Error?n.message:String(n)),r){const s=e;s.requireReply&&s.callId&&await this.replyToCall(s.callId,s.senderId,`\u5904\u7406\u5931\u8D25: ${n}`)}}}ensureRegistered(){if(!this.agentId)throw new Error("Agent is not registered")}delay(e){return new Promise(t=>{this.pollTimer=setTimeout(t,e)})}onNewCharacter(e){this.newCharacterHandler=e}getState(){return{agentId:this.agentId,displayName:this.displayName,projectId:this.projectId,isConnected:this.wsClient.isConnected(),isRunning:this.isRunning}}getAgentConfig(){return this.agentConfig}getServerConfig(){return this.serverConfig}reloadConfig(){c.loadConfig(),this.agentConfig=c.getAgentConfig(),i.info(`[AgentClient] \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D\uFF0C\u89D2\u8272: ${this.agentConfig.roleName}`)}enterDegradedMode(){this.isDegradedMode=!0,i.warn("[AgentClient] \u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F\uFF0C\u5C06\u5728\u540E\u53F0\u6301\u7EED\u5C1D\u8BD5\u91CD\u8FDE")}exitDegradedMode(){this.isDegradedMode=!1,i.info("[AgentClient] \u9000\u51FA\u964D\u7EA7\u6A21\u5F0F")}isInDegradedMode(){return this.isDegradedMode}async retryRegistrationInBackground(e,t){let n=0;(async()=>{for(;this.isDegradedMode;)try{i.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u5C1D\u8BD5\u91CD\u65B0\u6CE8\u518C (${n+1}/${t===-1?"\u65E0\u9650":t})`);const s=await this.register();i.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u6210\u529F - ${s.displayName} (${s.agentId})`),this.exitDegradedMode(),this.messageHandler&&this.start(this.messageHandler);return}catch(s){n++;const a=s instanceof Error?s.message:String(s);if(i.warn(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u5931\u8D25 (${n}/${t===-1?"\u65E0\u9650":t}): ${a}`),t>0&&n>=t){i.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u505C\u6B62\u91CD\u8FDE"),this.isDegradedMode=!1;return}await new Promise(h=>setTimeout(h,e))}})().catch(s=>{i.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\u540E\u53F0\u91CD\u8BD5\u5FAA\u73AF\u5F02\u5E38\u9000\u51FA: error=%s, stack=%s",s instanceof Error?s.message:String(s),s instanceof Error?s.stack:"(no stack)")})}initializeStatusReporter(){if(!this.agentId){i.warn("[AgentClient] \u65E0\u6CD5\u521D\u59CB\u5316\u72B6\u6001\u62A5\u544A\u5668\uFF1AagentId \u4E3A\u7A7A");return}this.statusReporter=new A({agentId:this.agentId,sendStatusUpdate:e=>{this.wsClient.send({type:"AGENT_STATUS",data:e,timestamp:new Date().toISOString()})}}),w(e=>this.reportMcpNodeLog(e)),this.startRuntimeTokenRefresh(),i.info("[AgentClient] \u72B6\u6001\u62A5\u544A\u5668\u5DF2\u521D\u59CB\u5316")}startRuntimeTokenRefresh(){this.stopRuntimeTokenRefresh();const e=this.serverConfig.runtimeTokenRefreshIntervalMs;if(!e||e<=0){i.warn("[AgentClient] runtimeTokenRefreshIntervalMs \u672A\u914D\u7F6E\u6216\u65E0\u6548\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}const t=this.agentId;if(!t){i.warn("[AgentClient] agentId \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}this.runtimeTokenRefreshTimer=setInterval(async()=>{try{await this.httpClient.refreshRuntimeAccessToken(t)&&i.info("[AgentClient] runtimeAccessToken \u5DF2\u4E3B\u52A8\u7EED\u671F")}catch(n){i.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F runtimeAccessToken \u5931\u8D25: %s",n instanceof Error?n.message:String(n)),n instanceof Error&&n.stack&&i.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F\u5F02\u5E38\u5806\u6808:",n.stack)}},e),this.runtimeTokenRefreshTimer.unref?.(),i.info(`[AgentClient] runtime token \u4E3B\u52A8\u7EED\u671F\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${e}ms`)}stopRuntimeTokenRefresh(){this.runtimeTokenRefreshTimer&&(clearInterval(this.runtimeTokenRefreshTimer),this.runtimeTokenRefreshTimer=null)}reportMcpNodeLog(e){const t=this.wsClient;!this.agentId||!this.wsClient.isConnected()||typeof t.sendMcpNodeLog!="function"||t.sendMcpNodeLog(e)}getStatusReporter(){return this.statusReporter}}export{N as AgentClient,T as PollLongPollTimeoutError};
2
2
 
@@ -658,6 +658,8 @@ export declare class McpServer {
658
658
  private recordMessageTokenUsage;
659
659
  private handleHireColleague;
660
660
  private handleSendPrivate;
661
+
662
+ private handleGetDmSendStatus;
661
663
  private handleCreateTaskInstanceComment;
662
664
 
663
665