aws-runtime-bridge 1.9.186 → 1.9.189

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 (75) hide show
  1. package/CHANGELOG.md +1767 -1673
  2. package/README.md +256 -256
  3. package/dist/adapter/AcodeSdkAdapter.js +3 -3
  4. package/dist/browser/browser-pool.d.ts +2 -0
  5. package/dist/browser/browser-pool.js +1 -1
  6. package/dist/config.d.ts +12 -0
  7. package/dist/config.js +2 -2
  8. package/dist/index.js +1 -1
  9. package/dist/remote-desktop/win32-api.js +1 -1
  10. package/dist/routes/background-tasks.js +4 -4
  11. package/dist/routes/dashboard.js +17 -17
  12. package/dist/routes/terminal.js +19 -19
  13. package/dist/services/acode-bg-manager.js +1 -1
  14. package/dist/services/auto-register.js +1 -1
  15. package/dist/services/instance-features.d.ts +9 -0
  16. package/dist/services/instance-features.js +1 -1
  17. package/dist/services/panel-auth.d.ts +4 -0
  18. package/dist/services/panel-auth.js +1 -1
  19. package/dist/services/plugin-handler-adapter.js +2 -2
  20. package/dist/services/workspace-files.js +1 -1
  21. package/dist/utils/dynamic-import.d.ts +31 -0
  22. package/dist/utils/dynamic-import.js +2 -0
  23. package/dist/utils/sdk-package-loader.js +1 -1
  24. package/node_modules/playwright/cli.js +0 -0
  25. package/node_modules/playwright-core/bin/reinstall_chrome_beta_linux.sh +0 -0
  26. package/node_modules/playwright-core/bin/reinstall_chrome_beta_mac.sh +0 -0
  27. package/node_modules/playwright-core/bin/reinstall_chrome_stable_linux.sh +0 -0
  28. package/node_modules/playwright-core/bin/reinstall_chrome_stable_mac.sh +0 -0
  29. package/node_modules/playwright-core/bin/reinstall_msedge_beta_linux.sh +0 -0
  30. package/node_modules/playwright-core/bin/reinstall_msedge_beta_mac.sh +0 -0
  31. package/node_modules/playwright-core/bin/reinstall_msedge_dev_linux.sh +0 -0
  32. package/node_modules/playwright-core/bin/reinstall_msedge_dev_mac.sh +0 -0
  33. package/node_modules/playwright-core/bin/reinstall_msedge_stable_linux.sh +0 -0
  34. package/node_modules/playwright-core/bin/reinstall_msedge_stable_mac.sh +0 -0
  35. package/node_modules/playwright-core/cli.js +0 -0
  36. package/node_modules/playwright-core/lib/webp_codec.wasm +0 -0
  37. package/node_modules/playwright-core/lib/xdg-open +0 -0
  38. package/package/acode/dist/await-complete-tool.js +3 -3
  39. package/package/acode/dist/runtime.d.ts +9 -0
  40. package/package/acode/dist/runtime.js +20 -21
  41. package/package/acode/dist/sub-agent-manager.d.ts +33 -0
  42. package/package/acode/dist/sub-agent-manager.js +9 -1
  43. package/package/acode/dist/sub-agent-tools.d.ts +4 -0
  44. package/package/acode/dist/sub-agent-tools.js +27 -12
  45. package/package/acode/dist/subagent-handback.d.ts +16 -0
  46. package/package/acode/dist/subagent-handback.js +7 -0
  47. package/package/acode/dist/tool-allocation.js +1 -1
  48. package/package/acode/package.json +38 -38
  49. package/package/aws-client-agent-mcp/dist/agent-client.d.ts +10 -5
  50. package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
  51. package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +27 -0
  52. package/package/aws-client-agent-mcp/dist/mcp-server.js +16 -16
  53. package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +19 -0
  54. package/package/aws-client-agent-mcp/dist/mcp-tools.js +35 -19
  55. package/package/aws-client-agent-mcp/dist/message-buffer.d.ts +10 -0
  56. package/package/aws-client-agent-mcp/dist/message-buffer.js +1 -1
  57. package/package/aws-client-agent-mcp/dist/tool-groups.js +2 -2
  58. package/package/aws-client-agent-mcp/dist/types.d.ts +81 -3
  59. package/package/aws-client-agent-mcp/package.json +53 -53
  60. package/package.json +134 -132
  61. /package/package/acode/dist/grammars/{grammars/tree-sitter-bash.wasm → tree-sitter-bash.wasm} +0 -0
  62. /package/package/acode/dist/grammars/{grammars/tree-sitter-c-sharp.wasm → tree-sitter-c-sharp.wasm} +0 -0
  63. /package/package/acode/dist/grammars/{grammars/tree-sitter-c.wasm → tree-sitter-c.wasm} +0 -0
  64. /package/package/acode/dist/grammars/{grammars/tree-sitter-cpp.wasm → tree-sitter-cpp.wasm} +0 -0
  65. /package/package/acode/dist/grammars/{grammars/tree-sitter-go.wasm → tree-sitter-go.wasm} +0 -0
  66. /package/package/acode/dist/grammars/{grammars/tree-sitter-java.wasm → tree-sitter-java.wasm} +0 -0
  67. /package/package/acode/dist/grammars/{grammars/tree-sitter-javascript.wasm → tree-sitter-javascript.wasm} +0 -0
  68. /package/package/acode/dist/grammars/{grammars/tree-sitter-jsx.wasm → tree-sitter-jsx.wasm} +0 -0
  69. /package/package/acode/dist/grammars/{grammars/tree-sitter-lua.wasm → tree-sitter-lua.wasm} +0 -0
  70. /package/package/acode/dist/grammars/{grammars/tree-sitter-php.wasm → tree-sitter-php.wasm} +0 -0
  71. /package/package/acode/dist/grammars/{grammars/tree-sitter-python.wasm → tree-sitter-python.wasm} +0 -0
  72. /package/package/acode/dist/grammars/{grammars/tree-sitter-ruby.wasm → tree-sitter-ruby.wasm} +0 -0
  73. /package/package/acode/dist/grammars/{grammars/tree-sitter-rust.wasm → tree-sitter-rust.wasm} +0 -0
  74. /package/package/acode/dist/grammars/{grammars/tree-sitter-tsx.wasm → tree-sitter-tsx.wasm} +0 -0
  75. /package/package/acode/dist/grammars/{grammars/tree-sitter-typescript.wasm → tree-sitter-typescript.wasm} +0 -0
@@ -1,2 +1,2 @@
1
- import{getAgentOwner as P}from"./agent-ownership.js";import{getEffective as N,hasAnyDefault as D}from"./capability-config.js";const j=new Set(["disabled","collapsed","expanded"]);function v(e){if(e===!0)return"expanded";if(e===!1)return"disabled";if(typeof e=="string"&&j.has(e))return e}const b={},se="desktop",I="browser",S="agentSys.launchItem",x="agentSys.hire",O="agentSys.skillInstall",R="agentSys.abilityDev",z="pencil",G="draw",H="office",k="collaboration",h="collaboration.task",m="collaboration.meeting",L="collaboration.debug",U="collaboration.fileHistory",J="email",V=new Set,W=new Set([I,z,G,H,S,x,O,R,h,m,L,U,J]),X=[["agentSys","agentSys."],[k,"collaboration."]],q=new Map([["task",h],["meeting",m],["debug",L],["fileHistory",U],["launch",S],["hire",x],["abilityMarket",O],["abilityDev",R]]);function le(e){return q.get(e)??e}function w(e){for(const[t,n]of X)if(e.startsWith(n))return t}const Q=new Set,y=new Map,_=new Map,a=new Map,Z=["fileReadOutside","commandExecution","fileModification","fileModificationOutside"],$=new Set(["allow","ask","deny"]);function ee(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;const t=e,n={};let o=!1;for(const r of Z){const i=t[r];typeof i=="string"&&$.has(i)?(n[r]=i,o=!0):n[r]="allow"}return o?n:null}function K(e){if(e==null)return{...b};let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{t=null}if(typeof t!="object"||t===null||Array.isArray(t))return{...b};const n={};for(const[o,r]of Object.entries(t)){if(Q.has(o))continue;const i=v(r);i!==void 0&&(n[o]=i)}return n}function ue(e,t){if(!e)return;y.set(e,K(t));let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=null}if(typeof n=="object"&&n!==null&&!Array.isArray(n)){const o=ee(n.toolPermissions);o?a.set(e,o):a.delete(e)}else a.delete(e)}function te(e){return y.get(e)??{...b}}function ce(e,t){if(!e)return;if(t==null){_.delete(e);return}const n=K(t);if(Object.keys(n).length===0){_.delete(e);return}_.set(e,n)}function ne(e){return _.get(e)??{}}function oe(e,t){const n=te(e),o=ne(e),r=w(t);if(r&&(n[r]??o[r])==="disabled")return"disabled";const i=n[t]??o[t];return i!==void 0?i:V.has(t)?"expanded":W.has(t)?"collapsed":"disabled"}function fe(e,t){return oe(e,t)!=="disabled"}function ae(e){y.delete(e),a.delete(e),f.delete(e),T.delete(e)}function pe(e){return a.get(e)??null}function Ee(e){return a.get(e)??{fileReadOutside:"allow",commandExecution:"allow",fileModification:"allow",fileModificationOutside:"allow"}}const M=["skills","mcp","plugins"],f=new Map,T=new Map;function Y(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t={};for(const[n,o]of Object.entries(e))n.trim()&&typeof o=="boolean"&&(t[n.trim()]=o);return t}function Ae(e,t){if(!e)return;if(t==null){f.delete(e);return}let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=null}if(typeof n!="object"||n===null||Array.isArray(n)){f.delete(e);return}const o=n,r={};let i=!1;for(const A of M){const l=Y(o[A]);l&&(r[A]=l,i=!0)}i?f.set(e,r):f.delete(e);const s=o.plugins,u={};let E=!1;if(typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[A,l]of Object.entries(s)){const d=A.trim();if(d){if(typeof l=="boolean"){const c=r.plugins??{};c[d]=l,r.plugins=c,i=!0;continue}if(l!==null&&typeof l=="object"&&!Array.isArray(l)){const c=l,B=c.enabled!==!1,g=typeof c.url=="string"?c.url:void 0,C=typeof c.sha256=="string"?c.sha256:void 0,F=r.plugins??{};F[d]=B,r.plugins=F,i=!0,g&&(u[d]={url:g,sha256:C},E=!0)}}}E?T.set(e,u):T.delete(e)}function de(e){return f.get(e)??null}const p=new Map;function ye(e,t){if(!e)return;if(t==null){p.delete(e);return}let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=null}if(typeof n!="object"||n===null||Array.isArray(n)){p.delete(e);return}const o=n,r={};let i=!1;for(const s of M){const u=Y(o[s]);u&&(r[s]=u,i=!0)}i?p.set(e,r):p.delete(e)}function _e(e){return p.get(e)??null}function Te(e){return T.get(e)??null}function be(e,t,n){const o=P(e);if(D(o,t))return N(o,e,t,n);const i=p.get(e)?.[t]?.[n];if(i!==void 0)return i;const s=f.get(e);if(!s)return!0;const u=s[t];if(!u)return!0;const E=u[n];return E===void 0?!0:E}function ge(){return y.size}export{R as ABILITY_DEV_FEATURE_KEY,I as BROWSER_FEATURE_KEY,M as CAPABILITY_TYPES,L as COLLABORATION_DEBUG_FEATURE_KEY,k as COLLABORATION_FEATURE_KEY,U as COLLABORATION_FILE_HISTORY_FEATURE_KEY,m as COLLABORATION_MEETING_FEATURE_KEY,h as COLLABORATION_TASK_FEATURE_KEY,se as DESKTOP_FEATURE_KEY,G as DRAW_FEATURE_KEY,J as EMAIL_FEATURE_KEY,q as GROUP_KEY_TO_FEATURE,x as HIRE_FEATURE_KEY,S as LAUNCH_ITEM_FEATURE_KEY,H as OFFICE_FEATURE_KEY,z as PENCIL_FEATURE_KEY,O as SKILL_INSTALL_FEATURE_KEY,ae as clearAgentFeatures,de as getAgentCapabilities,_e as getAgentCapabilitiesInherited,te as getAgentFeatures,ne as getAgentInheritedFeatures,Te as getAgentPluginSources,pe as getAgentToolPermissions,oe as getFeatureState,ge as instanceFeaturesCacheSize,be as isCapabilityEnabled,fe as isFeatureEnabled,v as normalizeFeatureState,Ee as resolveAgentToolPermissions,le as resolveGroupFeatureKey,Ae as setAgentCapabilities,ye as setAgentCapabilitiesInherited,ue as setAgentFeatures,ce as setAgentInheritedFeatures};
1
+ import{getAgentOwner as P}from"./agent-ownership.js";import{getEffective as D,hasAnyDefault as v}from"./capability-config.js";const j=new Set(["disabled","collapsed","expanded"]);function I(e){if(e===!0)return"expanded";if(e===!1)return"disabled";if(typeof e=="string"&&j.has(e))return e}const b={},le="desktop",z="browser",F="agentSys.launchItem",x="agentSys.hire",S="agentSys.skillInstall",R="agentSys.abilityDev",G="pencil",H="draw",k="office",V="collaboration",L="collaboration.task",h="collaboration.meeting",m="collaboration.debug",U="collaboration.fileHistory",J="email",K="collaboration.voice",W=new Set,X=new Set([z,G,H,k,F,x,S,R,L,h,m,U,J,K]),q=[["agentSys","agentSys."],[V,"collaboration."]],w=new Map([["task",L],["meeting",h],["debug",m],["fileHistory",U],["voice",K],["launch",F],["hire",x],["abilityMarket",S],["abilityDev",R]]);function ue(e){return w.get(e)??e}function Q(e){for(const[t,n]of q)if(e.startsWith(n))return t}const Z=new Set,y=new Map,_=new Map,a=new Map,$=["fileReadOutside","commandExecution","fileModification","fileModificationOutside"],ee=new Set(["allow","ask","deny"]);function te(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;const t=e,n={};let o=!1;for(const r of $){const i=t[r];typeof i=="string"&&ee.has(i)?(n[r]=i,o=!0):n[r]="allow"}return o?n:null}function Y(e){if(e==null)return{...b};let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{t=null}if(typeof t!="object"||t===null||Array.isArray(t))return{...b};const n={};for(const[o,r]of Object.entries(t)){if(Z.has(o))continue;const i=I(r);i!==void 0&&(n[o]=i)}return n}function ce(e,t){if(!e)return;y.set(e,Y(t));let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=null}if(typeof n=="object"&&n!==null&&!Array.isArray(n)){const o=te(n.toolPermissions);o?a.set(e,o):a.delete(e)}else a.delete(e)}function ne(e){return y.get(e)??{...b}}function fe(e,t){if(!e)return;if(t==null){_.delete(e);return}const n=Y(t);if(Object.keys(n).length===0){_.delete(e);return}_.set(e,n)}function oe(e){return _.get(e)??{}}function re(e,t){const n=ne(e),o=oe(e),r=Q(t);if(r&&(n[r]??o[r])==="disabled")return"disabled";const i=n[t]??o[t];return i!==void 0?i:W.has(t)?"expanded":X.has(t)?"collapsed":"disabled"}function ae(e,t){return re(e,t)!=="disabled"}function pe(e){y.delete(e),a.delete(e),f.delete(e),T.delete(e)}function Ee(e){return a.get(e)??null}function Ae(e){return a.get(e)??{fileReadOutside:"allow",commandExecution:"allow",fileModification:"allow",fileModificationOutside:"allow"}}const C=["skills","mcp","plugins"],f=new Map,T=new Map;function M(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t={};for(const[n,o]of Object.entries(e))n.trim()&&typeof o=="boolean"&&(t[n.trim()]=o);return t}function de(e,t){if(!e)return;if(t==null){f.delete(e);return}let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=null}if(typeof n!="object"||n===null||Array.isArray(n)){f.delete(e);return}const o=n,r={};let i=!1;for(const A of C){const l=M(o[A]);l&&(r[A]=l,i=!0)}i?f.set(e,r):f.delete(e);const s=o.plugins,u={};let E=!1;if(typeof s=="object"&&s!==null&&!Array.isArray(s))for(const[A,l]of Object.entries(s)){const d=A.trim();if(d){if(typeof l=="boolean"){const c=r.plugins??{};c[d]=l,r.plugins=c,i=!0;continue}if(l!==null&&typeof l=="object"&&!Array.isArray(l)){const c=l,B=c.enabled!==!1,O=typeof c.url=="string"?c.url:void 0,N=typeof c.sha256=="string"?c.sha256:void 0,g=r.plugins??{};g[d]=B,r.plugins=g,i=!0,O&&(u[d]={url:O,sha256:N},E=!0)}}}E?T.set(e,u):T.delete(e)}function ye(e){return f.get(e)??null}const p=new Map;function _e(e,t){if(!e)return;if(t==null){p.delete(e);return}let n=t;if(typeof t=="string")try{n=JSON.parse(t)}catch{n=null}if(typeof n!="object"||n===null||Array.isArray(n)){p.delete(e);return}const o=n,r={};let i=!1;for(const s of C){const u=M(o[s]);u&&(r[s]=u,i=!0)}i?p.set(e,r):p.delete(e)}function Te(e){return p.get(e)??null}function be(e){return T.get(e)??null}function Oe(e,t,n){const o=P(e);if(v(o,t))return D(o,e,t,n);const i=p.get(e)?.[t]?.[n];if(i!==void 0)return i;const s=f.get(e);if(!s)return!0;const u=s[t];if(!u)return!0;const E=u[n];return E===void 0?!0:E}function ge(){return y.size}export{R as ABILITY_DEV_FEATURE_KEY,z as BROWSER_FEATURE_KEY,C as CAPABILITY_TYPES,m as COLLABORATION_DEBUG_FEATURE_KEY,V as COLLABORATION_FEATURE_KEY,U as COLLABORATION_FILE_HISTORY_FEATURE_KEY,h as COLLABORATION_MEETING_FEATURE_KEY,L as COLLABORATION_TASK_FEATURE_KEY,K as COLLABORATION_VOICE_FEATURE_KEY,le as DESKTOP_FEATURE_KEY,H as DRAW_FEATURE_KEY,J as EMAIL_FEATURE_KEY,w as GROUP_KEY_TO_FEATURE,x as HIRE_FEATURE_KEY,F as LAUNCH_ITEM_FEATURE_KEY,k as OFFICE_FEATURE_KEY,G as PENCIL_FEATURE_KEY,S as SKILL_INSTALL_FEATURE_KEY,pe as clearAgentFeatures,ye as getAgentCapabilities,Te as getAgentCapabilitiesInherited,ne as getAgentFeatures,oe as getAgentInheritedFeatures,be as getAgentPluginSources,Ee as getAgentToolPermissions,re as getFeatureState,ge as instanceFeaturesCacheSize,Oe as isCapabilityEnabled,ae as isFeatureEnabled,I as normalizeFeatureState,Ae as resolveAgentToolPermissions,ue as resolveGroupFeatureKey,de as setAgentCapabilities,_e as setAgentCapabilitiesInherited,ce as setAgentFeatures,fe as setAgentInheritedFeatures};
2
2
 
@@ -7,6 +7,10 @@
7
7
 
8
8
 
9
9
 
10
+
11
+
12
+ export declare const SESSION_COOKIE_MAX_AGE_SEC: number;
13
+
10
14
  export declare function createSession(): string;
11
15
 
12
16
  export declare function validateSession(token: string | undefined | null): boolean;
@@ -1,2 +1,2 @@
1
- import{randomUUID as _,randomBytes as $,scryptSync as S,timingSafeEqual as I}from"node:crypto";import{existsSync as f,mkdirSync as w,readFileSync as u,writeFileSync as y}from"node:fs";import{homedir as v}from"node:os";import g from"node:path";import{getAutoRegisterConfigFilePath as D}from"../config.js";import{runExclusiveConfigWrite as x}from"../utils/config-write-queue.js";import{logger as i}from"../utils/logger.js";const C=24*60*60*1e3,M=60*60*1e3,a=new Map;let p=null;function F(){p||(p=setInterval(()=>{const e=Date.now();let t=0;for(const[n,o]of a)e-o.lastUsedAt>C&&(a.delete(n),t++);t>0&&i.info(`[panel-auth] \u5DF2\u6E05\u7406 ${t} \u4E2A\u8FC7\u671F\u9762\u677F\u4F1A\u8BDD`)},M),p.unref())}function K(){F();const e=_(),t=Date.now();return a.set(e,{token:e,createdAt:t,lastUsedAt:t}),e}function ee(e){if(!e)return!1;const t=a.get(e);if(!t)return!1;const n=Date.now();return n-t.lastUsedAt>C?(a.delete(e),!1):(t.lastUsedAt=n,!0)}function te(e){a.delete(e)}function ne(){return Array.from(a.values())}function re(){return a.size}const P="scrypt$",A=64;function m(e){return e.startsWith(P)}function k(e){const t=$(16),n=S(e,t,A);return`${P}${t.toString("hex")}$${n.toString("hex")}`}function J(e,t){if(e.length!==t.length)return!1;try{return I(Buffer.from(e,"hex"),Buffer.from(t,"hex"))}catch{return!1}}function U(e,t){if(m(t)){const n=t.split("$");if(n.length!==3)return!1;const o=Buffer.from(n[1],"hex");if(o.length===0)return!1;const s=S(e,o,A).toString("hex");return J(s,n[2])}return e===t}const T=5,h=15*60*1e3,L=10*60*1e3,c=new Map;function R(){const e=Date.now();for(const[t,n]of c)n.lockedUntil<=e&&e-n.windowStart>h&&c.delete(t)}function oe(e){const t=Date.now(),n=c.get(e);return n?n.lockedUntil>t?{allowed:!1,retryAfterSec:Math.ceil((n.lockedUntil-t)/1e3)}:(t-n.windowStart>h&&c.delete(e),{allowed:!0,retryAfterSec:0}):{allowed:!0,retryAfterSec:0}}function se(e){const t=Date.now();R();const n=c.get(e);if(!n||t-n.windowStart>h){c.set(e,{failures:1,windowStart:t,lockedUntil:0});return}n.failures+=1,n.failures>=T&&(n.lockedUntil=t+L,i.warn(`[panel-auth] \u767B\u5F55\u5931\u8D25\u6B21\u6570\u8FC7\u591A\uFF0C\u5DF2\u4E34\u65F6\u9501\u5B9A\u6765\u6E90 ${e}\uFF08${L/6e4} \u5206\u949F\uFF09`))}function ae(e){c.delete(e)}let l=null;function d(){return D()}function B(){const e=d();if(!f(e))return null;try{const t=u(e,"utf-8"),n=JSON.parse(t),o=String(n.panelUsername||"").trim(),s=String(n.panelPassword||"").trim();if(o&&s)return{username:o,password:s}}catch{}return null}function N(){if(l)return l;const e=B();return e?(l=e,e):(q(),l={username:"root",password:"root"},l)}function ie(e,t){const n=N();return e!==n.username||!U(t,n.password)?!1:(!m(n.password)&&H()&&W(n.username,t).then(()=>{i.info("[panel-auth] \u5DF2\u5C06\u660E\u6587\u9762\u677F\u5BC6\u7801\u81EA\u52A8\u8FC1\u79FB\u4E3A scrypt \u54C8\u5E0C\u5B58\u50A8")}).catch(()=>{}),!0)}function O(){l=null}function H(){const e=d();if(!f(e))return!1;try{const t=u(e,"utf-8"),n=JSON.parse(t);return!!(n.panelUsername&&n.panelPassword)}catch{return!1}}function ce(){const e=N();return e.username==="root"&&U("root",e.password)}async function W(e,t){const n=d();O(),await x(n,()=>{const o=g.dirname(n);let s={};if(f(n))try{s=JSON.parse(u(n,"utf-8"))}catch{}s.panelUsername=e,s.panelPassword=m(t)?t:k(t);try{w(o,{recursive:!0})}catch{}y(n,JSON.stringify(s,null,2),"utf-8"),i.info("[panel-auth] \u9762\u677F\u51ED\u636E\u5DF2\u66F4\u65B0")})}let E=!1;function G(){return g.join(v(),".aws-bridge","config.json")}async function j(){const e=d(),t=G();if(t===e||!f(t))return!1;let n="",o="";try{const r=JSON.parse(u(t,"utf-8"));n=String(r.panelUsername??"").trim(),o=String(r.panelPassword??"").trim()}catch(r){return i.warn(`[panel-auth] \u65E7\u914D\u7F6E\u4E0D\u53EF\u89E3\u6790\uFF0C\u8DF3\u8FC7\u9762\u677F\u51ED\u636E\u8FC1\u79FB: ${r instanceof Error?r.message:String(r)}`),!1}if(!n||!o)return!1;let s=!1;return await x(e,()=>{let r={};if(f(e))try{r=JSON.parse(u(e,"utf-8"))}catch{r={}}if(!(String(r.panelUsername??"").trim()&&String(r.panelPassword??"").trim())){r.panelUsername=n,r.panelPassword=o;try{w(g.dirname(e),{recursive:!0})}catch{}y(e,JSON.stringify(r,null,2),"utf-8"),s=!0,i.info(`[panel-auth] \u5DF2\u4ECE ${t} \u8FC1\u79FB\u9762\u677F\u51ED\u636E`)}}),s}function q(){E||(E=!0,j().then(e=>{e&&O()}).catch(e=>{i.warn(`[panel-auth] \u65E7\u9762\u677F\u51ED\u636E\u8FC1\u79FB\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${e instanceof Error?e.message:String(e)}`)}))}export{oe as checkLoginAllowed,O as clearCredentialsCache,K as createSession,te as destroySession,re as getActiveSessionCount,ne as getAllSessions,N as getPanelCredentials,H as hasConfiguredCredentials,ce as isDefaultCredentials,j as migrateLegacyPanelCredentials,se as recordLoginFailure,ae as recordLoginSuccess,W as setPanelCredentials,ie as validateCredentials,ee as validateSession};
1
+ import{randomUUID as T,randomBytes as b,scryptSync as E,timingSafeEqual as j}from"node:crypto";import{existsSync as f,mkdirSync as h,readFileSync as l,writeFileSync as w}from"node:fs";import{homedir as H}from"node:os";import u from"node:path";import{getAutoRegisterConfigFilePath as O}from"../config.js";import{runExclusiveConfigWrite as L}from"../utils/config-write-queue.js";import{logger as a}from"../utils/logger.js";const y=30*24*60*60*1e3,fe=30*24*60*60,R=60*60*1e3,B=500,i=new Map;let A=null,p=null;function _(){return u.join(u.dirname(O()),"panel-sessions.json")}function G(){const e=_();if(f(e))try{const t=JSON.parse(l(e,"utf-8")),n=Date.now();let r=0;if(t.sessions&&typeof t.sessions=="object")for(const[o,s]of Object.entries(t.sessions)){const N=Number(s?.createdAt),m=Number(s?.lastUsedAt);typeof o!="string"||!Number.isFinite(N)||!Number.isFinite(m)||n-m>y||(i.set(o,{token:o,createdAt:N,lastUsedAt:m}),r++)}r>0&&a.info(`[panel-auth] \u5DF2\u4ECE\u78C1\u76D8\u6062\u590D ${r} \u4E2A\u9762\u677F\u4F1A\u8BDD`)}catch(t){a.warn(`[panel-auth] \u9762\u677F\u4F1A\u8BDD\u6587\u4EF6\u4E0D\u53EF\u8BFB\uFF08\u5FFD\u7565\uFF09: ${t instanceof Error?t.message:String(t)}`)}}let x=!1;function C(){x||(x=!0,G())}function F(){const e=_();try{h(u.dirname(e),{recursive:!0});const t={version:1,sessions:Object.fromEntries(Array.from(i.values()).map(n=>[n.token,{createdAt:n.createdAt,lastUsedAt:n.lastUsedAt}]))};w(e,JSON.stringify(t,null,2),{encoding:"utf-8",mode:384})}catch(t){a.warn(`[panel-auth] \u9762\u677F\u4F1A\u8BDD\u843D\u76D8\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${t instanceof Error?t.message:String(t)}`)}}function g(){p||(p=setTimeout(()=>{p=null,F()},B),p.unref())}function W(){A||(A=setInterval(()=>{const e=Date.now();let t=0;for(const[n,r]of i)e-r.lastUsedAt>y&&(i.delete(n),t++);t>0&&(a.info(`[panel-auth] \u5DF2\u6E05\u7406 ${t} \u4E2A\u8FC7\u671F\u9762\u677F\u4F1A\u8BDD`),g())},R),A.unref())}process.on("exit",()=>{x&&i.size>0&&F()});function le(){C(),W();const e=T(),t=Date.now();return i.set(e,{token:e,createdAt:t,lastUsedAt:t}),g(),e}function ue(e){if(!e)return!1;C();const t=i.get(e);if(!t)return!1;const n=Date.now();return n-t.lastUsedAt>y?(i.delete(e),g(),!1):(t.lastUsedAt=n,!0)}function de(e){C(),i.delete(e)&&g()}function pe(){return Array.from(i.values())}function ge(){return i.size}const $="scrypt$",I=64;function P(e){return e.startsWith($)}function X(e){const t=b(16),n=E(e,t,I);return`${$}${t.toString("hex")}$${n.toString("hex")}`}function Y(e,t){if(e.length!==t.length)return!1;try{return j(Buffer.from(e,"hex"),Buffer.from(t,"hex"))}catch{return!1}}function v(e,t){if(P(t)){const n=t.split("$");if(n.length!==3)return!1;const r=Buffer.from(n[1],"hex");if(r.length===0)return!1;const o=E(e,r,I).toString("hex");return Y(o,n[2])}return e===t}const q=5,U=15*60*1e3,D=10*60*1e3,c=new Map;function z(){const e=Date.now();for(const[t,n]of c)n.lockedUntil<=e&&e-n.windowStart>U&&c.delete(t)}function Se(e){const t=Date.now(),n=c.get(e);return n?n.lockedUntil>t?{allowed:!1,retryAfterSec:Math.ceil((n.lockedUntil-t)/1e3)}:(t-n.windowStart>U&&c.delete(e),{allowed:!0,retryAfterSec:0}):{allowed:!0,retryAfterSec:0}}function me(e){const t=Date.now();z();const n=c.get(e);if(!n||t-n.windowStart>U){c.set(e,{failures:1,windowStart:t,lockedUntil:0});return}n.failures+=1,n.failures>=q&&(n.lockedUntil=t+D,a.warn(`[panel-auth] \u767B\u5F55\u5931\u8D25\u6B21\u6570\u8FC7\u591A\uFF0C\u5DF2\u4E34\u65F6\u9501\u5B9A\u6765\u6E90 ${e}\uFF08${D/6e4} \u5206\u949F\uFF09`))}function he(e){c.delete(e)}let d=null;function S(){return O()}function V(){const e=S();if(!f(e))return null;try{const t=l(e,"utf-8"),n=JSON.parse(t),r=String(n.panelUsername||"").trim(),o=String(n.panelPassword||"").trim();if(r&&o)return{username:r,password:o}}catch{}return null}function M(){if(d)return d;const e=V();return e?(d=e,e):(te(),d={username:"root",password:"root"},d)}function we(e,t){const n=M();return e!==n.username||!v(t,n.password)?!1:(!P(n.password)&&K()&&Q(n.username,t).then(()=>{a.info("[panel-auth] \u5DF2\u5C06\u660E\u6587\u9762\u677F\u5BC6\u7801\u81EA\u52A8\u8FC1\u79FB\u4E3A scrypt \u54C8\u5E0C\u5B58\u50A8")}).catch(()=>{}),!0)}function k(){d=null}function K(){const e=S();if(!f(e))return!1;try{const t=l(e,"utf-8"),n=JSON.parse(t);return!!(n.panelUsername&&n.panelPassword)}catch{return!1}}function ye(){const e=M();return e.username==="root"&&v("root",e.password)}async function Q(e,t){const n=S();k(),await L(n,()=>{const r=u.dirname(n);let o={};if(f(n))try{o=JSON.parse(l(n,"utf-8"))}catch{}o.panelUsername=e,o.panelPassword=P(t)?t:X(t);try{h(r,{recursive:!0})}catch{}w(n,JSON.stringify(o,null,2),"utf-8"),a.info("[panel-auth] \u9762\u677F\u51ED\u636E\u5DF2\u66F4\u65B0")})}let J=!1;function Z(){return u.join(H(),".aws-bridge","config.json")}async function ee(){const e=S(),t=Z();if(t===e||!f(t))return!1;let n="",r="";try{const s=JSON.parse(l(t,"utf-8"));n=String(s.panelUsername??"").trim(),r=String(s.panelPassword??"").trim()}catch(s){return a.warn(`[panel-auth] \u65E7\u914D\u7F6E\u4E0D\u53EF\u89E3\u6790\uFF0C\u8DF3\u8FC7\u9762\u677F\u51ED\u636E\u8FC1\u79FB: ${s instanceof Error?s.message:String(s)}`),!1}if(!n||!r)return!1;let o=!1;return await L(e,()=>{let s={};if(f(e))try{s=JSON.parse(l(e,"utf-8"))}catch{s={}}if(!(String(s.panelUsername??"").trim()&&String(s.panelPassword??"").trim())){s.panelUsername=n,s.panelPassword=r;try{h(u.dirname(e),{recursive:!0})}catch{}w(e,JSON.stringify(s,null,2),"utf-8"),o=!0,a.info(`[panel-auth] \u5DF2\u4ECE ${t} \u8FC1\u79FB\u9762\u677F\u51ED\u636E`)}}),o}function te(){J||(J=!0,ee().then(e=>{e&&k()}).catch(e=>{a.warn(`[panel-auth] \u65E7\u9762\u677F\u51ED\u636E\u8FC1\u79FB\u5931\u8D25\uFF08\u5FFD\u7565\uFF09: ${e instanceof Error?e.message:String(e)}`)}))}export{fe as SESSION_COOKIE_MAX_AGE_SEC,Se as checkLoginAllowed,k as clearCredentialsCache,le as createSession,de as destroySession,ge as getActiveSessionCount,pe as getAllSessions,M as getPanelCredentials,K as hasConfiguredCredentials,ye as isDefaultCredentials,ee as migrateLegacyPanelCredentials,me as recordLoginFailure,he as recordLoginSuccess,Q as setPanelCredentials,we as validateCredentials,ue as validateSession};
2
2
 
@@ -1,3 +1,3 @@
1
- import{spawn as T}from"node:child_process";import{join as _}from"node:path";import{pathToFileURL as O}from"node:url";import{BLOCKED_ENV_KEYS as P}from"../utils/env-safety.js";import{createLogger as A}from"../utils/logger.js";import{renderCommandArgv as v,truncate as C}from"./plugin-manifest.js";const N=A("plugin-manager"),g=256*1024,h=6e4,S=/^[A-Za-z_][A-Za-z0-9_]*$/;async function G(t,e,s,a,o){const n=Date.now(),r=s.handler??{type:"process"};try{return r.type==="mcp"?{ok:!1,error:"handler.type=mcp \u5C06\u5728\u540E\u7EED\u7248\u672C\u652F\u6301\uFF0C\u8BF7\u6539\u7528 process/module handler"}:r.type==="module"?{ok:!0,result:await b(e,r,a,t,o),durationMs:Date.now()-n}:!r.command||!r.command.trim()?{ok:!1,error:`\u5DE5\u5177 ${s.name} \u7684 process handler \u7F3A\u5C11 command`}:{ok:!0,result:await $(e,r,a,t,o),durationMs:Date.now()-n}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i),durationMs:Date.now()-n}}}async function $(t,e,s,a,o){const n=e.command??"";if(e.shell===!0&&/\{\{.+?\}\}/.test(n))throw new Error('shell:true \u7684 handler \u4E0D\u652F\u6301 {{params.*}} \u63D2\u503C\uFF08\u547D\u4EE4\u6CE8\u5165\u98CE\u9669\uFF09\uFF1B\u8BF7\u6539\u7528 shell:false \u7684 argv \u6A21\u5F0F\u6216 stdin:"params"');const r=v(n,{params:s});if(r.length===0)throw new Error("process handler command \u4E3A\u7A7A");const i=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:h,u=new AbortController,d=()=>u.abort();o?.signal?.addEventListener("abort",d,{once:!0});const E=setTimeout(()=>u.abort(),i);try{return await new Promise((l,w)=>{N.info("[plugin:%s] spawn: %s",t.name,r.join(" "));const c=T(r[0],r.slice(1),{cwd:t.dir,env:k(t,a),shell:e.shell===!0,windowsHide:!0,signal:u.signal});let f="",y="";c.stdin?.on("error",()=>{}),c.stdout?.on("data",m=>{f.length<g&&(f+=m.toString("utf8"))}),c.stderr?.on("data",m=>{y.length<g&&(y+=m.toString("utf8"))}),c.on("error",m=>{w(new Error(`\u63D2\u4EF6\u8FDB\u7A0B\u542F\u52A8\u5931\u8D25: ${m.message}`))}),c.on("close",m=>{const p=f.trim();if(m!==0){const M=C(y.trim()||p||"(\u65E0\u8F93\u51FA)",600);w(new Error(u.signal.aborted?`\u63D2\u4EF6\u8FDB\u7A0B\u8D85\u65F6(${i}ms)\u6216\u88AB\u4E2D\u6B62`:`\u63D2\u4EF6\u8FDB\u7A0B\u9000\u51FA\u7801 ${m}: ${M}`));return}if(!p){l({ok:!0});return}try{l(JSON.parse(p))}catch{l(p)}});try{e.stdin==="params"?c.stdin?.end(`${JSON.stringify(s)}
2
- `):c.stdin?.end()}catch{}})}finally{clearTimeout(E),o?.signal?.removeEventListener("abort",d)}}async function b(t,e,s,a,o){if(!e.module)throw new Error("module handler \u7F3A\u5C11 module \u8DEF\u5F84");const n=_(t.dir,e.module);let r=t.moduleCache.get(n);r||(r=await import(`${O(n).href}?acode_nonce=${t.importNonce}`),t.moduleCache.set(n,r));const i=e.export||"default",d=r[i];if(typeof d!="function")throw new Error(`\u6A21\u5757 ${e.module} \u672A\u5BFC\u51FA\u51FD\u6570 ${i}`);const E=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:h;let l;const w=Promise.resolve().then(()=>d(s,{agentId:a,signal:o?.signal,pluginRoot:t.dir}));try{return await Promise.race([w,new Promise((c,f)=>{l=setTimeout(()=>f(new Error(`\u63D2\u4EF6\u6A21\u5757\u6267\u884C\u8D85\u65F6(${E}ms)`)),E)})])}finally{clearTimeout(l)}}function k(t,e){const s={};for(const o of["PATH","HOME","USERPROFILE","SystemRoot","COMSPEC","TEMP","TMP","LANG","TZ"]){const n=process.env[o];n!==void 0&&(s[o]=n)}s.ACODE_PLUGIN_ROOT=t.dir,s.ACODE_AGENT_ID=e,s.ACODE_PLUGIN_NAME=t.name;const a=new Set((t.userConfig??[]).map(o=>o.key));for(const[o,n]of Object.entries(t.configValues))a.has(o)&&(!S.test(o)||P.has(o.toUpperCase())||(s[o]=n));return s}export{k as buildPluginEnv,G as executeHandler};
1
+ import{spawn as T}from"node:child_process";import{join as _}from"node:path";import{pathToFileURL as O}from"node:url";import{loadDynamicModule as P}from"../utils/dynamic-import.js";import{BLOCKED_ENV_KEYS as A}from"../utils/env-safety.js";import{createLogger as v}from"../utils/logger.js";import{renderCommandArgv as C,truncate as N}from"./plugin-manifest.js";const S=v("plugin-manager"),g=256*1024,h=6e4,b=/^[A-Za-z_][A-Za-z0-9_]*$/;async function K(t,e,s,a,o){const n=Date.now(),r=s.handler??{type:"process"};try{return r.type==="mcp"?{ok:!1,error:"handler.type=mcp \u5C06\u5728\u540E\u7EED\u7248\u672C\u652F\u6301\uFF0C\u8BF7\u6539\u7528 process/module handler"}:r.type==="module"?{ok:!0,result:await D(e,r,a,t,o),durationMs:Date.now()-n}:!r.command||!r.command.trim()?{ok:!1,error:`\u5DE5\u5177 ${s.name} \u7684 process handler \u7F3A\u5C11 command`}:{ok:!0,result:await k(e,r,a,t,o),durationMs:Date.now()-n}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i),durationMs:Date.now()-n}}}async function k(t,e,s,a,o){const n=e.command??"";if(e.shell===!0&&/\{\{.+?\}\}/.test(n))throw new Error('shell:true \u7684 handler \u4E0D\u652F\u6301 {{params.*}} \u63D2\u503C\uFF08\u547D\u4EE4\u6CE8\u5165\u98CE\u9669\uFF09\uFF1B\u8BF7\u6539\u7528 shell:false \u7684 argv \u6A21\u5F0F\u6216 stdin:"params"');const r=C(n,{params:s});if(r.length===0)throw new Error("process handler command \u4E3A\u7A7A");const i=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:h,u=new AbortController,d=()=>u.abort();o?.signal?.addEventListener("abort",d,{once:!0});const E=setTimeout(()=>u.abort(),i);try{return await new Promise((l,w)=>{S.info("[plugin:%s] spawn: %s",t.name,r.join(" "));const c=T(r[0],r.slice(1),{cwd:t.dir,env:L(t,a),shell:e.shell===!0,windowsHide:!0,signal:u.signal});let f="",y="";c.stdin?.on("error",()=>{}),c.stdout?.on("data",m=>{f.length<g&&(f+=m.toString("utf8"))}),c.stderr?.on("data",m=>{y.length<g&&(y+=m.toString("utf8"))}),c.on("error",m=>{w(new Error(`\u63D2\u4EF6\u8FDB\u7A0B\u542F\u52A8\u5931\u8D25: ${m.message}`))}),c.on("close",m=>{const p=f.trim();if(m!==0){const M=N(y.trim()||p||"(\u65E0\u8F93\u51FA)",600);w(new Error(u.signal.aborted?`\u63D2\u4EF6\u8FDB\u7A0B\u8D85\u65F6(${i}ms)\u6216\u88AB\u4E2D\u6B62`:`\u63D2\u4EF6\u8FDB\u7A0B\u9000\u51FA\u7801 ${m}: ${M}`));return}if(!p){l({ok:!0});return}try{l(JSON.parse(p))}catch{l(p)}});try{e.stdin==="params"?c.stdin?.end(`${JSON.stringify(s)}
2
+ `):c.stdin?.end()}catch{}})}finally{clearTimeout(E),o?.signal?.removeEventListener("abort",d)}}async function D(t,e,s,a,o){if(!e.module)throw new Error("module handler \u7F3A\u5C11 module \u8DEF\u5F84");const n=_(t.dir,e.module);let r=t.moduleCache.get(n);r||(r=await P(O(n).href,{freshInstanceQuery:`acode_nonce=${t.importNonce}`}),t.moduleCache.set(n,r));const i=e.export||"default",d=r[i];if(typeof d!="function")throw new Error(`\u6A21\u5757 ${e.module} \u672A\u5BFC\u51FA\u51FD\u6570 ${i}`);const E=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:h;let l;const w=Promise.resolve().then(()=>d(s,{agentId:a,signal:o?.signal,pluginRoot:t.dir}));try{return await Promise.race([w,new Promise((c,f)=>{l=setTimeout(()=>f(new Error(`\u63D2\u4EF6\u6A21\u5757\u6267\u884C\u8D85\u65F6(${E}ms)`)),E)})])}finally{clearTimeout(l)}}function L(t,e){const s={};for(const o of["PATH","HOME","USERPROFILE","SystemRoot","COMSPEC","TEMP","TMP","LANG","TZ"]){const n=process.env[o];n!==void 0&&(s[o]=n)}s.ACODE_PLUGIN_ROOT=t.dir,s.ACODE_AGENT_ID=e,s.ACODE_PLUGIN_NAME=t.name;const a=new Set((t.userConfig??[]).map(o=>o.key));for(const[o,n]of Object.entries(t.configValues))a.has(o)&&(!b.test(o)||A.has(o.toUpperCase())||(s[o]=n));return s}export{L as buildPluginEnv,K as executeHandler};
3
3
 
@@ -1,2 +1,2 @@
1
- import{createReadStream as O,createWriteStream as _,promises as s}from"node:fs";import ut from"node:os";import w from"node:path";import{Readable as wt}from"node:stream";import{pipeline as dt}from"node:stream/promises";import{TextDecoder as ft}from"node:util";import{createGunzip as pt}from"node:zlib";import*as mt from"tar";import yt from"unzipper";const{ZipArchive:Z}=await import("archiver"),x={maxEntries:1e4,maxFileBytes:512*1024*1024,maxTotalBytes:2*1024*1024*1024,maxPathDepth:64,maxPathLength:4096},gt=new ft("gbk");function u(t){return String(t||"").replace(/\\/g,"/")}function G(t){const e=w.resolve(String(t||"").trim());if(!e)throw new Error("workspacePath is required");return e}async function Pt(t){const e=G(t),r=await s.realpath(e);if(!(await s.stat(r)).isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);return r}async function v(t){return{requestedRoot:G(t),workspaceRoot:await Pt(t)}}function C(t,e){const r=w.resolve(e),i=w.relative(t,r);if(i.startsWith("..")||w.isAbsolute(i))throw new Error(`Target path is outside workspace: ${r}`);return r}async function R(t){return s.realpath(t)}async function D(t){await s.realpath(w.dirname(t));try{if((await s.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}}function $(t,e,r){const i=w.resolve(t,r),o=w.relative(t,i);return o.startsWith("..")||w.isAbsolute(o)?i:C(e,w.join(e,o))}async function B({workspacePath:t,targetPath:e=""}){const{requestedRoot:r,workspaceRoot:i}=await v(t),o=String(e||"").trim(),a=o?$(r,i,o):i,c=await R(a);return{workspaceRoot:i,resolvedTargetPath:c}}function L(t){const e=String(t||"").trim();if(!e)throw new Error("entryName is required");if(e==="."||e==="..")throw new Error("entryName is invalid");if(e.includes("/")||e.includes("\\")||w.basename(e)!==e)throw new Error(`entryName must be a plain file or directory name: ${e}`);return e}function H(t){const e=String(t||"");if(!/[\u00c0-\u00ff]/.test(e))return e;const r=Buffer.from(e,"latin1").toString("utf8");return!r||r.includes("\uFFFD")?e:r}function I(t){const e=H(t);return L(w.basename(e.replace(/\\/g,"/")))}function kt(t,e){if(!t)return I(e);const i=H(String(t||e||"")).replace(/\\/g,"/").split("/").filter(Boolean).map(o=>L(o));return i.length===0?I(e):w.join(...i)}function K(t){return(t&4095).toString(8).padStart(4,"0")}function xt(t){const e=String(t||"").trim();if(!/^[0-7]{3,4}$/.test(e))throw new Error("mode must be a 3 or 4 digit octal string");return Number.parseInt(e,8)}function M(t,e,r,i,o,a,c){const n=t&e?"r":"-",l=t&r?"w":"-",h=(t&i)!==0,f=(t&o)!==0?h?a:c:h?"x":"-";return`${n}${l}${f}`}function vt(t){return[M(t,256,128,64,2048,"s","S"),M(t,32,16,8,1024,"s","S"),M(t,4,2,1,512,"t","T")].join("")}function Et(t){if(!(t.length<24||t.toString("hex",0,8)!=="89504e470d0a1a0a"))return{format:"png",width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}function St(t){if(!(t.length<10||t.toString("ascii",0,6)!=="GIF87a"&&t.toString("ascii",0,6)!=="GIF89a"))return{format:"gif",width:t.readUInt16LE(6),height:t.readUInt16LE(8)}}function Rt(t){if(t.length<4||t[0]!==255||t[1]!==216)return;let e=2;for(;e+9<t.length;){if(t[e]!==255){e+=1;continue}const r=t[e+1],i=t.readUInt16BE(e+2);if(i<2)return;if(r>=192&&r<=207&&![196,200,204].includes(r)&&e+8<t.length)return{format:"jpeg",height:t.readUInt16BE(e+5),width:t.readUInt16BE(e+7)};e+=2+i}}function Dt(t){if(t.length<30||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WEBP")return;const e=t.toString("ascii",12,16);if(e==="VP8X"&&t.length>=30)return{format:"webp",width:1+t.readUIntLE(24,3),height:1+t.readUIntLE(27,3)};if(e==="VP8 "&&t.length>=30)return{format:"webp",width:t.readUInt16LE(26)&16383,height:t.readUInt16LE(28)&16383};if(e==="VP8L"&&t.length>=25){const r=t.readUInt32LE(21);return{format:"webp",width:(r&16383)+1,height:(r>>14&16383)+1}}}async function X(t,e){if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to change permissions on symbolic link: ${t}`);const i=await s.stat(t);if(!e||!i.isDirectory())return[t];const o=await s.readdir(t),a=await Promise.all(o.map(c=>{const n=w.join(t,c);return X(n,!0)}));return[t,...a.flat()]}async function Ft(t){if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to change permissions on symbolic link: ${t}`);await R(t)}async function Tt(t){const e=await s.open(t,"r");try{const r=Buffer.alloc(512),{bytesRead:i}=await e.read(r,0,r.length,0),o=r.subarray(0,i);return Et(o)||St(o)||Rt(o)||Dt(o)}finally{await e.close()}}async function F({workspacePath:t,targetPath:e},r={}){const{requestedRoot:i,workspaceRoot:o}=await v(t),a=String(e||"").trim();if(!a)throw new Error("targetPath is required");const c=$(i,o,a),n=await R(c);if(!r.allowWorkspaceRoot&&n===o)throw new Error("Workspace root cannot be modified");return{workspaceRoot:o,resolvedTargetPath:n}}async function V(t){const{requestedRoot:e,workspaceRoot:r}=await v(t.workspacePath),i=String(t.targetPath||"").trim();if(!i)return{workspaceRoot:r,resolvedTargetPath:r};const o=$(e,r,i);return await rt(o)?{workspaceRoot:r,resolvedTargetPath:await s.realpath(o)}:(await s.realpath(w.dirname(o)),{workspaceRoot:r,resolvedTargetPath:o})}function Y(t){const e=t.toLowerCase();return e.endsWith(".zip")?"zip":e.endsWith(".tar.gz")||e.endsWith(".tgz")?"tgz":e.endsWith(".tar")?"tar":e.endsWith(".gz")?"gz":null}function J(t){return t.replace(/\.tar\.gz$/i,"").replace(/\.tgz$/i,"").replace(/\.zip$/i,"").replace(/\.tar$/i,"").replace(/\.gz$/i,"")}function zt(t,e){const r=L(J(e)||"extracted");return w.join(t,r)}function N(t,e){const r=String(e||"").replace(/\\/g,"/"),i=r.split("/").filter(Boolean);if(!r||r.startsWith("/")||/^[A-Za-z]:/.test(r))throw new Error(`Archive entry path is invalid: ${e}`);if(r.length>x.maxPathLength||i.length>x.maxPathDepth)throw new Error(`Archive entry path is too deep or too long: ${e}`);return C(t,w.join(t,r))}function $t(t){const e=t.props?.pathBuffer;if(!e||t.props?.flags?.isUnicode)return t.path;const r=gt.decode(e);return!r||r.includes("\uFFFD")?t.path:r}async function Q(t){const e=t.autodrain?.();e&&await new Promise((r,i)=>{e.on("close",r),e.on("end",r),e.on("finish",r),e.on("error",i)})}function j(t){if(t.entries+=1,t.entries>x.maxEntries)throw new Error(`Archive contains too many entries. Limit: ${x.maxEntries}`)}function tt(t,e){if(t.totalBytes+=e,e>x.maxFileBytes)throw new Error(`Archive entry exceeds max size. Limit: ${x.maxFileBytes} bytes`);if(t.totalBytes>x.maxTotalBytes)throw new Error(`Archive extraction exceeds total size. Limit: ${x.maxTotalBytes} bytes`)}async function et(t,e,r){let i=0;t.on("data",o=>{const a=Buffer.isBuffer(o)?o.length:Buffer.byteLength(o);i+=a,(i>x.maxFileBytes||r.totalBytes+i>x.maxTotalBytes)&&t instanceof wt&&t.destroy(new Error("Archive extraction size limit exceeded"))}),await dt(t,_(e)),tt(r,i)}async function rt(t){try{return await s.access(t),!0}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)==="ENOENT")return!1;throw e}}async function W({workspacePath:t,filePath:e}){const{requestedRoot:r,workspaceRoot:i}=await v(t),o=String(e||"").trim();if(!o)throw new Error("filePath is required");return{workspaceRoot:i,resolvedFilePath:$(r,i,o)}}async function Kt(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.targetPath||"").trim();if(!r){const{resolvedTargetPath:l}=await B(t);return it(e,l)}const i=w.resolve(r);let o;try{o=await s.realpath(i)}catch{throw new Error(`Path not found: ${i}`)}if(!(await s.stat(o)).isDirectory())throw new Error(`Path is not a directory: ${i}`);const c=w.relative(e,o),n=c===""||!c.startsWith("..")&&!w.isAbsolute(c);return it(e,n?o:i)}async function it(t,e){if(!(await s.stat(e)).isDirectory())throw new Error(`Path is not a directory: ${e}`);const i=await s.readdir(e,{withFileTypes:!0}),o=await Promise.all(i.map(async a=>{const c=w.join(e,a.name);let n;if(a.isFile())try{n=(await s.stat(c)).size}catch{n=void 0}return{name:a.name,path:u(c),isDirectory:a.isDirectory(),size:n}}));return{currentPath:u(e),workspacePath:u(t),items:o}}async function Xt(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t),i=await R(r),o=await s.stat(i);if(!o.isFile())throw new Error(`Path is not a file: ${i}`);const a=await s.readFile(i,"utf-8");return{workspacePath:u(e),filePath:u(i),content:a,mtimeMs:o.mtimeMs}}const ot={maxEntries:1e5,maxDepth:32};async function Lt(t){let e=0,r=0;async function i(o,a){if(a>=ot.maxDepth)return;let c;try{c=await s.readdir(o,{withFileTypes:!0})}catch{return}for(const n of c){if(r+=1,r>ot.maxEntries)return;if(n.isSymbolicLink())continue;const l=w.join(o,n.name);try{if(n.isDirectory())await i(l,a+1);else if(n.isFile()){const h=await s.stat(l);e+=h.size}}catch{}}}return await i(t,0),e}async function Vt(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t,{allowWorkspaceRoot:!0}),[i,o]=await Promise.all([s.stat(r),s.lstat(r)]),a=i.isDirectory(),c=i.isFile()?await Tt(r):void 0,n=a?await Lt(r):i.size;return{workspacePath:u(e),targetPath:u(r),name:w.basename(r),isDirectory:i.isDirectory(),isFile:i.isFile(),isSymbolicLink:o.isSymbolicLink(),size:n,mode:i.mode,modeOctal:K(i.mode),permissions:vt(i.mode),uid:i.uid,gid:i.gid,atimeMs:i.atimeMs,mtimeMs:i.mtimeMs,ctimeMs:i.ctimeMs,birthtimeMs:i.birthtimeMs,...c?{image:c}:{}}}async function Yt(t){const e=xt(t.mode),r=!!t.recursive,{workspaceRoot:i,resolvedTargetPath:o}=await F(t),a=await X(o,r);for(const c of a)await Ft(c),await s.chmod(c,e);return{ok:!0,workspacePath:u(i),targetPath:u(o),mode:e,modeOctal:K(e),recursive:r,changedCount:a.length}}async function Jt(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t),i=await R(r),o=await s.stat(i);if(!o.isFile())throw new Error(`Path is not a file: ${i}`);const a=w.extname(i).toLowerCase();if(a===".doc"||a===".xls"||a===".ppt")return{workspacePath:u(e),filePath:u(i),kind:"unsupported",content:"",message:`\u65E7\u7248 ${a} \u683C\u5F0F\u5C06\u7531\u670D\u52A1\u7AEF\u8F6C\u6362\u4E3A\u73B0\u4EE3\u683C\u5F0F\u540E\u6253\u5F00\uFF08\u539F\u6587\u4EF6\u4E0D\u53D8\uFF09\u3002`,size:o.size,mtimeMs:o.mtimeMs};if(!/\.(docx|docm|xlsx|xlsm|pptx|pptm)$/.test(a))throw new Error("Document preview only supports docx/xlsx/pptx files");return{workspacePath:u(e),filePath:u(i),kind:"html",content:"",size:o.size,mtimeMs:o.mtimeMs}}async function Qt(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t);await s.mkdir(w.dirname(r),{recursive:!0}),await D(r),await s.writeFile(r,String(t.content??""),"utf-8");const i=await s.stat(r);return{ok:!0,workspacePath:u(e),filePath:u(r),mtimeMs:i.mtimeMs}}async function te(t){const{workspaceRoot:e,resolvedTargetPath:r}=await B(t),i=L(t.entryName),o=w.join(r,i);if(!(await s.stat(r)).isDirectory())throw new Error(`Path is not a directory: ${r}`);try{throw await s.access(o),new Error(`Path already exists: ${o}`)}catch(c){if((typeof c=="object"&&c!==null?Reflect.get(c,"code"):void 0)!=="ENOENT")throw c}return t.isDirectory?await s.mkdir(o,{recursive:!1}):(await s.mkdir(w.dirname(o),{recursive:!0}),await D(o),await s.writeFile(o,"","utf-8")),{ok:!0,workspacePath:u(e),targetPath:u(o),isDirectory:t.isDirectory}}async function ee(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t),i=L(t.newName),o=w.join(w.dirname(r),i);if(o===r)return{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(o)};await s.stat(r);try{throw await s.access(o),new Error(`Path already exists: ${o}`)}catch(a){if((typeof a=="object"&&a!==null?Reflect.get(a,"code"):void 0)!=="ENOENT")throw a}return await s.rename(r,o),{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(o)}}async function re(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t),i=await B({workspacePath:t.workspacePath,targetPath:t.destinationPath});if(!(await s.stat(i.resolvedTargetPath)).isDirectory())throw new Error(`Destination is not a directory: ${i.resolvedTargetPath}`);if((await s.stat(r)).isDirectory()){const n=w.relative(r,i.resolvedTargetPath);if(n===""||!n.startsWith("..")&&!w.isAbsolute(n))throw new Error("Cannot move a directory into itself or its descendant")}const c=w.join(i.resolvedTargetPath,w.basename(r));if(c===r)return{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(c),destinationPath:u(i.resolvedTargetPath)};try{throw await s.access(c),new Error(`Path already exists: ${c}`)}catch(n){if((typeof n=="object"&&n!==null?Reflect.get(n,"code"):void 0)!=="ENOENT")throw n}return await s.rename(r,c),{ok:!0,workspacePath:u(e),sourcePath:u(r),targetPath:u(c),destinationPath:u(i.resolvedTargetPath)}}async function ie(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t),i=await s.stat(r),o=w.parse(r).root;if(r===o)throw new Error("Filesystem root cannot be deleted");return i.isDirectory()?await s.rm(r,{recursive:!0,force:!1}):await s.unlink(r),{ok:!0,workspacePath:u(e),targetPath:u(r)}}async function oe(t){if(!Array.isArray(t.files)||t.files.length===0)throw new Error("files are required");const{workspaceRoot:e,resolvedTargetPath:r}=await V(t);if(!(await s.stat(r)).isDirectory())throw new Error(`Path is not a directory: ${r}`);const o=[];for(const a of t.files){const c=I(a.originalname),n=kt(a.relativePath,a.originalname),l=w.join(r,n);await s.mkdir(w.dirname(l),{recursive:!0}),await D(l),await s.copyFile(a.path,l);let h;t.extractArchives&&Y(l)&&(h=await Bt({workspacePath:e,archivePath:l,outputPath:zt(r,c)})),o.push({fileName:c,targetPath:u(l),size:a.size,extracted:h})}return{ok:!0,workspacePath:u(e),targetPath:u(r),files:o}}async function ae(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t),i=await s.stat(r),o=w.basename(r);return{workspacePath:u(e),targetPath:u(r),resolvedTargetPath:r,fileName:i.isDirectory()?`${o||"workspace"}.zip`:o,contentType:i.isDirectory()?"application/zip":At(r),isDirectory:i.isDirectory(),size:i.isDirectory()?void 0:i.size}}function At(t){const e=w.extname(t).toLowerCase();return{".svg":"image/svg+xml",".svgz":"image/svg+xml",".ico":"image/x-icon",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".avif":"image/avif",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".xml":"application/xml; charset=utf-8",".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".md":"text/markdown; charset=utf-8",".csv":"text/csv; charset=utf-8",".pdf":"application/pdf",".zip":"application/zip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm"}[e]||"application/octet-stream"}async function ne(t,e){const r=new Z({zlib:{level:9}}),i=new Promise((o,a)=>{e.on("close",o),e.on("finish",o),r.on("error",a),e.on("error",a)});r.pipe(e),r.directory(t,!1),await r.finalize(),await i}async function se(t,e,r,i){const o=w.join(ut.tmpdir(),"agentswork-bridge-downloads");await s.mkdir(o,{recursive:!0});const a=(e||"workspace.zip").replace(/[^\w.-]/g,"_").replace(/\.zip$/i,"")||"workspace",c=w.join(o,`${a}-${Date.now()}-${Math.random().toString(36).slice(2,8)}.zip`),n=new Z({zlib:{level:9}}),l=()=>n.pointer(),h=()=>n.abort(),d=_(c),f=new Promise((p,g)=>{d.on("close",p),d.on("finish",p),n.on("error",g),d.on("error",g)});f.catch(()=>{}),n.pipe(d);const m=setInterval(()=>{try{if(i?.()){h();return}r?.(l())}catch{}},200);try{return n.on("progress",()=>{i?.()&&h()}),n.directory(t,!1),i?.()&&h(),await n.finalize(),await f,r?.(l()),c}catch(p){throw await s.rm(c,{force:!0}).catch(()=>{}),p}finally{clearInterval(m)}}async function Ct(t,e,r){let i=0,o;const a=O(t),c=a.pipe(yt.Parse({forceStream:!0}));try{for await(const n of c){if(o){await Q(n);continue}const l=$t(n);try{const h=N(e,l);if(j(r),n.type==="Directory"){await s.mkdir(h,{recursive:!0});continue}if(n.type!=="File")throw new Error(`Unsupported archive entry type: ${l}`);await s.mkdir(w.dirname(h),{recursive:!0}),await D(h),await et(n,h,r),i+=1}catch(h){o=h,await Q(n)}}}finally{a.destroy(),c.destroy()}if(o)throw o;return i}async function Wt(t,e,r,i){let o=0,a;const c=(n,l)=>{if(a)return!1;try{N(e,n),j(i);const h=String(l.type||"").toLowerCase();if(h==="symboliclink"||h==="link")throw new Error(`Archive links are not supported: ${n}`);if(h!=="file"&&h!=="oldfile"&&h!=="contiguousfile"&&h!=="directory")throw new Error(`Unsupported archive entry type: ${n}`);return typeof l.size=="number"&&tt(i,l.size),h!=="directory"&&(o+=1),!0}catch(h){return a=h,!1}};if(await mt.x({file:t,cwd:e,gzip:r,strict:!0,filter:(n,l)=>c(n,l)}),a)throw a;return o}async function bt(t,e,r){const i=J(w.basename(t)),o=N(e,i||"decompressed");return j(r),await s.mkdir(w.dirname(o),{recursive:!0}),await D(o),await et(O(t).pipe(pt()),o,r),1}async function Bt(t){const{requestedRoot:e,workspaceRoot:r}=await v(t.workspacePath),{resolvedTargetPath:i}=await V({workspacePath:t.workspacePath,targetPath:t.outputPath||""}),o=$(e,r,String(t.archivePath||"").trim()),a=await R(o);if(!(await s.stat(a)).isFile())throw new Error(`Archive path is not a file: ${a}`);if(await rt(i)||await s.mkdir(i,{recursive:!0}),!(await s.stat(i)).isDirectory())throw new Error(`Output path is not a directory: ${i}`);const l=Y(a);if(!l)throw new Error("Unsupported archive type. Supported: .zip, .tar, .tar.gz, .tgz, .gz");let h=0;const d={entries:0,totalBytes:0};return l==="zip"?h=await Ct(a,i,d):l==="tar"||l==="tgz"?h=await Wt(a,i,l==="tgz",d):h=await bt(a,i,d),{ok:!0,workspacePath:u(r),archivePath:u(a),targetPath:u(i),extractedEntries:h}}function at(t){const e=t.match(/^(.*?)\{([^}]+)\}(.*)$/);if(!e)return[t];const[,r,i,o]=e;return i.split(",").flatMap(a=>at(r+a.trim()+o))}function nt(t,e){const r=String(e||"").trim();if(!r||r==="*"||r==="*.*")return!0;const i=t.toLowerCase();return at(r.toLowerCase()).some(a=>{if(a==="*")return!0;const c=a.replace(/\./g,"\\.").replace(/\*\*/g,"<<GLOBSTAR>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<GLOBSTAR>>/g,".*");return new RegExp(`^${c}$`).test(i)})}function U(t){return t===".git"||t==="node_modules"||t===".svn"||t===".hg"}const st=10*1024*1024,It=1e3;async function ct(t,e){const{workspaceRoot:r}=await v(t),i=String(e||"").trim();if(!i)return{workspaceRoot:r,searchRoot:r};const o=w.resolve(/^[A-Za-z]:$/.test(i)?`${i}/`:i);let a;try{a=await s.realpath(o)}catch{throw new Error(`Path not found: ${o}`)}if(!(await s.stat(a)).isDirectory())throw new Error(`Path is not a directory: ${o}`);return{workspaceRoot:r,searchRoot:a}}async function ce(t){const{workspaceRoot:e,searchRoot:r}=await ct(t.workspacePath,t.rootPath),i=String(t.keyword||"").trim();if(!i)throw new Error("keyword is required");const o=!!t.ignoreCase,a=String(t.fileMask||"").trim(),c=typeof t.maxResults=="number"&&t.maxResults>0?t.maxResults:It,n=o?i.toLowerCase():i,h=(t.mode==="filename"?"filename":"content")==="filename",d=[];let f=0,m=!1;async function p(g){if(m)return;let k;try{k=await s.readdir(g,{withFileTypes:!0})}catch{return}for(const y of k){if(m)return;const P=C(r,w.join(g,y.name));if(y.isSymbolicLink())continue;if(y.isDirectory()){if(U(y.name))continue;await p(P);continue}if(!y.isFile()||a&&!nt(y.name,a))continue;f+=1;let S;try{S=await s.stat(P)}catch{continue}if(S.size>st)continue;if(h){const E=(o?y.name.toLowerCase():y.name).indexOf(n);if(E!==-1&&(d.push({filePath:u(P),lineNumber:0,lineContent:y.name,matchStart:E,matchEnd:E+i.length}),d.length>=c)){m=!0;return}continue}let T;try{T=await s.readFile(P,"utf-8")}catch{continue}const b=T.split(/\r?\n/);for(let z=0;z<b.length;z+=1){const E=b[z],ht=o?E.toLowerCase():E;let q=0;for(;;){const A=ht.indexOf(n,q);if(A===-1)break;if(d.push({filePath:u(P),lineNumber:z+1,lineContent:E,matchStart:A,matchEnd:A+i.length}),d.length>=c){m=!0;return}q=A+1}}}}return await p(r),{workspacePath:u(e),keyword:i,totalFiles:f,totalMatches:d.length,matches:d,truncated:m}}const Mt=100,Nt=120;async function le(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.keyword||"").trim();if(!r)throw new Error("keyword is required");const i=!!t.ignoreCase,o=i?r.toLowerCase():r,a=typeof t.maxResults=="number"&&t.maxResults>0?t.maxResults:Mt,c=typeof t.maxDirectories=="number"&&t.maxDirectories>0?t.maxDirectories:Nt,n=String(t.rootPath||"").trim(),l=n?w.resolve(/^[A-Za-z]:$/.test(n)?`${n}/`:n):e;let h;try{h=await s.realpath(l)}catch{throw new Error(`Path not found: ${l}`)}if(!(await s.stat(h)).isDirectory())throw new Error(`Path is not a directory: ${l}`);const f=[],m=[h];let p=0,g=!1;for(;m.length>0&&f.length<a&&p<c;){const k=m.shift();p+=1;let y;try{y=await s.readdir(k,{withFileTypes:!0})}catch{continue}for(const P of y){if(f.length>=a){g=!0;break}if(P.isSymbolicLink())continue;const S=w.join(k,P.name);if(P.isDirectory()&&U(P.name))continue;const T=w.relative(h,S).replace(/\\/g,"/");(i?T.toLowerCase():T).includes(o)&&f.push({name:P.name,path:u(S),isDirectory:P.isDirectory()}),P.isDirectory()&&p<c&&m.push(S)}}return(p>=c||f.length>=a)&&(g=!0),f.sort((k,y)=>k.isDirectory===y.isDirectory?k.name.localeCompare(y.name):k.isDirectory?-1:1),{workspacePath:u(e),rootPath:u(h),keyword:r,items:f,truncated:g}}async function lt(t,e,r,i){let o;try{o=await s.readFile(t,"utf-8")}catch{return{changed:!1,count:0}}const a=o;let c=0;if(i){const n=e.toLowerCase();let l=0;for(;;){const d=o.toLowerCase().indexOf(n,l);if(d===-1)break;o=o.slice(0,d)+r+o.slice(d+e.length),c+=1;const f=r.length||1;l=d+f}}else{let n=0;for(;;){const l=o.indexOf(e,n);if(l===-1)break;o=o.slice(0,l)+r+o.slice(l+e.length),c+=1;const h=r.length||1;n=l+h}}return o===a?{changed:!1,count:0}:(await D(t),await s.writeFile(t,o,"utf-8"),{changed:!0,count:c})}async function he(t){const{workspaceRoot:e,searchRoot:r}=await ct(t.workspacePath,t.rootPath),i=String(t.keyword||"").trim();if(!i)throw new Error("keyword is required");const o=String(t.replacement??""),a=!!t.ignoreCase,c=String(t.fileMask||"").trim(),n=String(t.filePath||"").trim();let l=0,h=0;if(n){const{resolvedFilePath:f}=await W({workspacePath:t.workspacePath,filePath:n}),m=await lt(f,i,o,a);return m.changed&&(l=1,h=m.count),{workspacePath:u(e),keyword:i,replacement:o,changedFiles:l,changedMatches:h}}async function d(f){let m;try{m=await s.readdir(f,{withFileTypes:!0})}catch{return}for(const p of m){const g=C(r,w.join(f,p.name));if(p.isSymbolicLink())continue;if(p.isDirectory()){if(U(p.name))continue;await d(g);continue}if(!p.isFile()||c&&!nt(p.name,c))continue;try{if((await s.stat(g)).size>st)continue}catch{continue}const k=await lt(g,i,o,a);k.changed&&(l+=1,h+=k.count)}}return await d(r),{workspacePath:u(e),keyword:i,replacement:o,changedFiles:l,changedMatches:h}}export{Yt as chmodWorkspaceEntry,te as createWorkspaceEntry,ie as deleteWorkspaceEntry,Bt as extractWorkspaceArchive,Vt as getWorkspaceEntryProperties,Kt as listWorkspaceDirectory,re as moveWorkspaceEntry,Jt as previewWorkspaceDocument,Xt as readWorkspaceFile,ee as renameWorkspaceEntry,he as replaceWorkspaceFiles,ae as resolveWorkspaceDownloadTarget,ce as searchWorkspaceFiles,le as searchWorkspacePaths,ne as streamWorkspaceDirectoryZip,oe as uploadWorkspaceFiles,Qt as writeWorkspaceFile,se as zipWorkspaceDirectoryToTemp};
1
+ import{createReadStream as _,createWriteStream as Z,promises as s}from"node:fs";import wt from"node:os";import w from"node:path";import{Readable as dt}from"node:stream";import{pipeline as ft}from"node:stream/promises";import{TextDecoder as pt}from"node:util";import{createGunzip as mt}from"node:zlib";import*as yt from"tar";import gt from"unzipper";let B;async function G(){return B||(B=await import("archiver")),B}const x={maxEntries:1e4,maxFileBytes:512*1024*1024,maxTotalBytes:2*1024*1024*1024,maxPathDepth:64,maxPathLength:4096},Pt=new pt("gbk");function h(t){return String(t||"").replace(/\\/g,"/")}function H(t){const e=w.resolve(String(t||"").trim());if(!e)throw new Error("workspacePath is required");return e}async function kt(t){const e=H(t),r=await s.realpath(e);if(!(await s.stat(r)).isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);return r}async function v(t){return{requestedRoot:H(t),workspaceRoot:await kt(t)}}function C(t,e){const r=w.resolve(e),i=w.relative(t,r);if(i.startsWith("..")||w.isAbsolute(i))throw new Error(`Target path is outside workspace: ${r}`);return r}async function R(t){return s.realpath(t)}async function D(t){await s.realpath(w.dirname(t));try{if((await s.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}}function $(t,e,r){const i=w.resolve(t,r),o=w.relative(t,i);return o.startsWith("..")||w.isAbsolute(o)?i:C(e,w.join(e,o))}async function I({workspacePath:t,targetPath:e=""}){const{requestedRoot:r,workspaceRoot:i}=await v(t),o=String(e||"").trim(),a=o?$(r,i,o):i,n=await R(a);return{workspaceRoot:i,resolvedTargetPath:n}}function L(t){const e=String(t||"").trim();if(!e)throw new Error("entryName is required");if(e==="."||e==="..")throw new Error("entryName is invalid");if(e.includes("/")||e.includes("\\")||w.basename(e)!==e)throw new Error(`entryName must be a plain file or directory name: ${e}`);return e}function K(t){const e=String(t||"");if(!/[\u00c0-\u00ff]/.test(e))return e;const r=Buffer.from(e,"latin1").toString("utf8");return!r||r.includes("\uFFFD")?e:r}function M(t){const e=K(t);return L(w.basename(e.replace(/\\/g,"/")))}function xt(t,e){if(!t)return M(e);const i=K(String(t||e||"")).replace(/\\/g,"/").split("/").filter(Boolean).map(o=>L(o));return i.length===0?M(e):w.join(...i)}function X(t){return(t&4095).toString(8).padStart(4,"0")}function vt(t){const e=String(t||"").trim();if(!/^[0-7]{3,4}$/.test(e))throw new Error("mode must be a 3 or 4 digit octal string");return Number.parseInt(e,8)}function N(t,e,r,i,o,a,n){const c=t&e?"r":"-",l=t&r?"w":"-",u=(t&i)!==0,f=(t&o)!==0?u?a:n:u?"x":"-";return`${c}${l}${f}`}function Et(t){return[N(t,256,128,64,2048,"s","S"),N(t,32,16,8,1024,"s","S"),N(t,4,2,1,512,"t","T")].join("")}function St(t){if(!(t.length<24||t.toString("hex",0,8)!=="89504e470d0a1a0a"))return{format:"png",width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}function Rt(t){if(!(t.length<10||t.toString("ascii",0,6)!=="GIF87a"&&t.toString("ascii",0,6)!=="GIF89a"))return{format:"gif",width:t.readUInt16LE(6),height:t.readUInt16LE(8)}}function Dt(t){if(t.length<4||t[0]!==255||t[1]!==216)return;let e=2;for(;e+9<t.length;){if(t[e]!==255){e+=1;continue}const r=t[e+1],i=t.readUInt16BE(e+2);if(i<2)return;if(r>=192&&r<=207&&![196,200,204].includes(r)&&e+8<t.length)return{format:"jpeg",height:t.readUInt16BE(e+5),width:t.readUInt16BE(e+7)};e+=2+i}}function Ft(t){if(t.length<30||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WEBP")return;const e=t.toString("ascii",12,16);if(e==="VP8X"&&t.length>=30)return{format:"webp",width:1+t.readUIntLE(24,3),height:1+t.readUIntLE(27,3)};if(e==="VP8 "&&t.length>=30)return{format:"webp",width:t.readUInt16LE(26)&16383,height:t.readUInt16LE(28)&16383};if(e==="VP8L"&&t.length>=25){const r=t.readUInt32LE(21);return{format:"webp",width:(r&16383)+1,height:(r>>14&16383)+1}}}async function V(t,e){if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to change permissions on symbolic link: ${t}`);const i=await s.stat(t);if(!e||!i.isDirectory())return[t];const o=await s.readdir(t),a=await Promise.all(o.map(n=>{const c=w.join(t,n);return V(c,!0)}));return[t,...a.flat()]}async function zt(t){if((await s.lstat(t)).isSymbolicLink())throw new Error(`Refusing to change permissions on symbolic link: ${t}`);await R(t)}async function Tt(t){const e=await s.open(t,"r");try{const r=Buffer.alloc(512),{bytesRead:i}=await e.read(r,0,r.length,0),o=r.subarray(0,i);return St(o)||Rt(o)||Dt(o)||Ft(o)}finally{await e.close()}}async function F({workspacePath:t,targetPath:e},r={}){const{requestedRoot:i,workspaceRoot:o}=await v(t),a=String(e||"").trim();if(!a)throw new Error("targetPath is required");const n=$(i,o,a),c=await R(n);if(!r.allowWorkspaceRoot&&c===o)throw new Error("Workspace root cannot be modified");return{workspaceRoot:o,resolvedTargetPath:c}}async function Y(t){const{requestedRoot:e,workspaceRoot:r}=await v(t.workspacePath),i=String(t.targetPath||"").trim();if(!i)return{workspaceRoot:r,resolvedTargetPath:r};const o=$(e,r,i);return await it(o)?{workspaceRoot:r,resolvedTargetPath:await s.realpath(o)}:(await s.realpath(w.dirname(o)),{workspaceRoot:r,resolvedTargetPath:o})}function J(t){const e=t.toLowerCase();return e.endsWith(".zip")?"zip":e.endsWith(".tar.gz")||e.endsWith(".tgz")?"tgz":e.endsWith(".tar")?"tar":e.endsWith(".gz")?"gz":null}function Q(t){return t.replace(/\.tar\.gz$/i,"").replace(/\.tgz$/i,"").replace(/\.zip$/i,"").replace(/\.tar$/i,"").replace(/\.gz$/i,"")}function $t(t,e){const r=L(Q(e)||"extracted");return w.join(t,r)}function j(t,e){const r=String(e||"").replace(/\\/g,"/"),i=r.split("/").filter(Boolean);if(!r||r.startsWith("/")||/^[A-Za-z]:/.test(r))throw new Error(`Archive entry path is invalid: ${e}`);if(r.length>x.maxPathLength||i.length>x.maxPathDepth)throw new Error(`Archive entry path is too deep or too long: ${e}`);return C(t,w.join(t,r))}function Lt(t){const e=t.props?.pathBuffer;if(!e||t.props?.flags?.isUnicode)return t.path;const r=Pt.decode(e);return!r||r.includes("\uFFFD")?t.path:r}async function tt(t){const e=t.autodrain?.();e&&await new Promise((r,i)=>{e.on("close",r),e.on("end",r),e.on("finish",r),e.on("error",i)})}function U(t){if(t.entries+=1,t.entries>x.maxEntries)throw new Error(`Archive contains too many entries. Limit: ${x.maxEntries}`)}function et(t,e){if(t.totalBytes+=e,e>x.maxFileBytes)throw new Error(`Archive entry exceeds max size. Limit: ${x.maxFileBytes} bytes`);if(t.totalBytes>x.maxTotalBytes)throw new Error(`Archive extraction exceeds total size. Limit: ${x.maxTotalBytes} bytes`)}async function rt(t,e,r){let i=0;t.on("data",o=>{const a=Buffer.isBuffer(o)?o.length:Buffer.byteLength(o);i+=a,(i>x.maxFileBytes||r.totalBytes+i>x.maxTotalBytes)&&t instanceof dt&&t.destroy(new Error("Archive extraction size limit exceeded"))}),await ft(t,Z(e)),et(r,i)}async function it(t){try{return await s.access(t),!0}catch(e){if((typeof e=="object"&&e!==null?Reflect.get(e,"code"):void 0)==="ENOENT")return!1;throw e}}async function W({workspacePath:t,filePath:e}){const{requestedRoot:r,workspaceRoot:i}=await v(t),o=String(e||"").trim();if(!o)throw new Error("filePath is required");return{workspaceRoot:i,resolvedFilePath:$(r,i,o)}}async function Xt(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.targetPath||"").trim();if(!r){const{resolvedTargetPath:l}=await I(t);return ot(e,l)}const i=w.resolve(r);let o;try{o=await s.realpath(i)}catch{throw new Error(`Path not found: ${i}`)}if(!(await s.stat(o)).isDirectory())throw new Error(`Path is not a directory: ${i}`);const n=w.relative(e,o),c=n===""||!n.startsWith("..")&&!w.isAbsolute(n);return ot(e,c?o:i)}async function ot(t,e){if(!(await s.stat(e)).isDirectory())throw new Error(`Path is not a directory: ${e}`);const i=await s.readdir(e,{withFileTypes:!0}),o=await Promise.all(i.map(async a=>{const n=w.join(e,a.name);let c;if(a.isFile())try{c=(await s.stat(n)).size}catch{c=void 0}return{name:a.name,path:h(n),isDirectory:a.isDirectory(),size:c}}));return{currentPath:h(e),workspacePath:h(t),items:o}}async function Vt(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t),i=await R(r),o=await s.stat(i);if(!o.isFile())throw new Error(`Path is not a file: ${i}`);const a=await s.readFile(i,"utf-8");return{workspacePath:h(e),filePath:h(i),content:a,mtimeMs:o.mtimeMs}}const at={maxEntries:1e5,maxDepth:32};async function At(t){let e=0,r=0;async function i(o,a){if(a>=at.maxDepth)return;let n;try{n=await s.readdir(o,{withFileTypes:!0})}catch{return}for(const c of n){if(r+=1,r>at.maxEntries)return;if(c.isSymbolicLink())continue;const l=w.join(o,c.name);try{if(c.isDirectory())await i(l,a+1);else if(c.isFile()){const u=await s.stat(l);e+=u.size}}catch{}}}return await i(t,0),e}async function Yt(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t,{allowWorkspaceRoot:!0}),[i,o]=await Promise.all([s.stat(r),s.lstat(r)]),a=i.isDirectory(),n=i.isFile()?await Tt(r):void 0,c=a?await At(r):i.size;return{workspacePath:h(e),targetPath:h(r),name:w.basename(r),isDirectory:i.isDirectory(),isFile:i.isFile(),isSymbolicLink:o.isSymbolicLink(),size:c,mode:i.mode,modeOctal:X(i.mode),permissions:Et(i.mode),uid:i.uid,gid:i.gid,atimeMs:i.atimeMs,mtimeMs:i.mtimeMs,ctimeMs:i.ctimeMs,birthtimeMs:i.birthtimeMs,...n?{image:n}:{}}}async function Jt(t){const e=vt(t.mode),r=!!t.recursive,{workspaceRoot:i,resolvedTargetPath:o}=await F(t),a=await V(o,r);for(const n of a)await zt(n),await s.chmod(n,e);return{ok:!0,workspacePath:h(i),targetPath:h(o),mode:e,modeOctal:X(e),recursive:r,changedCount:a.length}}async function Qt(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t),i=await R(r),o=await s.stat(i);if(!o.isFile())throw new Error(`Path is not a file: ${i}`);const a=w.extname(i).toLowerCase();if(a===".doc"||a===".xls"||a===".ppt")return{workspacePath:h(e),filePath:h(i),kind:"unsupported",content:"",message:`\u65E7\u7248 ${a} \u683C\u5F0F\u5C06\u7531\u670D\u52A1\u7AEF\u8F6C\u6362\u4E3A\u73B0\u4EE3\u683C\u5F0F\u540E\u6253\u5F00\uFF08\u539F\u6587\u4EF6\u4E0D\u53D8\uFF09\u3002`,size:o.size,mtimeMs:o.mtimeMs};if(!/\.(docx|docm|xlsx|xlsm|pptx|pptm)$/.test(a))throw new Error("Document preview only supports docx/xlsx/pptx files");return{workspacePath:h(e),filePath:h(i),kind:"html",content:"",size:o.size,mtimeMs:o.mtimeMs}}async function te(t){const{workspaceRoot:e,resolvedFilePath:r}=await W(t);await s.mkdir(w.dirname(r),{recursive:!0}),await D(r),await s.writeFile(r,String(t.content??""),"utf-8");const i=await s.stat(r);return{ok:!0,workspacePath:h(e),filePath:h(r),mtimeMs:i.mtimeMs}}async function ee(t){const{workspaceRoot:e,resolvedTargetPath:r}=await I(t),i=L(t.entryName),o=w.join(r,i);if(!(await s.stat(r)).isDirectory())throw new Error(`Path is not a directory: ${r}`);try{throw await s.access(o),new Error(`Path already exists: ${o}`)}catch(n){if((typeof n=="object"&&n!==null?Reflect.get(n,"code"):void 0)!=="ENOENT")throw n}return t.isDirectory?await s.mkdir(o,{recursive:!1}):(await s.mkdir(w.dirname(o),{recursive:!0}),await D(o),await s.writeFile(o,"","utf-8")),{ok:!0,workspacePath:h(e),targetPath:h(o),isDirectory:t.isDirectory}}async function re(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t),i=L(t.newName),o=w.join(w.dirname(r),i);if(o===r)return{ok:!0,workspacePath:h(e),sourcePath:h(r),targetPath:h(o)};await s.stat(r);try{throw await s.access(o),new Error(`Path already exists: ${o}`)}catch(a){if((typeof a=="object"&&a!==null?Reflect.get(a,"code"):void 0)!=="ENOENT")throw a}return await s.rename(r,o),{ok:!0,workspacePath:h(e),sourcePath:h(r),targetPath:h(o)}}async function ie(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t),i=await I({workspacePath:t.workspacePath,targetPath:t.destinationPath});if(!(await s.stat(i.resolvedTargetPath)).isDirectory())throw new Error(`Destination is not a directory: ${i.resolvedTargetPath}`);if((await s.stat(r)).isDirectory()){const c=w.relative(r,i.resolvedTargetPath);if(c===""||!c.startsWith("..")&&!w.isAbsolute(c))throw new Error("Cannot move a directory into itself or its descendant")}const n=w.join(i.resolvedTargetPath,w.basename(r));if(n===r)return{ok:!0,workspacePath:h(e),sourcePath:h(r),targetPath:h(n),destinationPath:h(i.resolvedTargetPath)};try{throw await s.access(n),new Error(`Path already exists: ${n}`)}catch(c){if((typeof c=="object"&&c!==null?Reflect.get(c,"code"):void 0)!=="ENOENT")throw c}return await s.rename(r,n),{ok:!0,workspacePath:h(e),sourcePath:h(r),targetPath:h(n),destinationPath:h(i.resolvedTargetPath)}}async function oe(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t),i=await s.stat(r),o=w.parse(r).root;if(r===o)throw new Error("Filesystem root cannot be deleted");return i.isDirectory()?await s.rm(r,{recursive:!0,force:!1}):await s.unlink(r),{ok:!0,workspacePath:h(e),targetPath:h(r)}}async function ae(t){if(!Array.isArray(t.files)||t.files.length===0)throw new Error("files are required");const{workspaceRoot:e,resolvedTargetPath:r}=await Y(t);if(!(await s.stat(r)).isDirectory())throw new Error(`Path is not a directory: ${r}`);const o=[];for(const a of t.files){const n=M(a.originalname),c=xt(a.relativePath,a.originalname),l=w.join(r,c);await s.mkdir(w.dirname(l),{recursive:!0}),await D(l),await s.copyFile(a.path,l);let u;t.extractArchives&&J(l)&&(u=await It({workspacePath:e,archivePath:l,outputPath:$t(r,n)})),o.push({fileName:n,targetPath:h(l),size:a.size,extracted:u})}return{ok:!0,workspacePath:h(e),targetPath:h(r),files:o}}async function ne(t){const{workspaceRoot:e,resolvedTargetPath:r}=await F(t),i=await s.stat(r),o=w.basename(r);return{workspacePath:h(e),targetPath:h(r),resolvedTargetPath:r,fileName:i.isDirectory()?`${o||"workspace"}.zip`:o,contentType:i.isDirectory()?"application/zip":Ct(r),isDirectory:i.isDirectory(),size:i.isDirectory()?void 0:i.size}}function Ct(t){const e=w.extname(t).toLowerCase();return{".svg":"image/svg+xml",".svgz":"image/svg+xml",".ico":"image/x-icon",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".avif":"image/avif",".txt":"text/plain; charset=utf-8",".json":"application/json; charset=utf-8",".xml":"application/xml; charset=utf-8",".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".md":"text/markdown; charset=utf-8",".csv":"text/csv; charset=utf-8",".pdf":"application/pdf",".zip":"application/zip",".mp3":"audio/mpeg",".wav":"audio/wav",".mp4":"video/mp4",".webm":"video/webm"}[e]||"application/octet-stream"}async function se(t,e){const{ZipArchive:r}=await G(),i=new r({zlib:{level:9}}),o=new Promise((a,n)=>{e.on("close",a),e.on("finish",a),i.on("error",n),e.on("error",n)});i.pipe(e),i.directory(t,!1),await i.finalize(),await o}async function ce(t,e,r,i){const o=w.join(wt.tmpdir(),"agentswork-bridge-downloads");await s.mkdir(o,{recursive:!0});const a=(e||"workspace.zip").replace(/[^\w.-]/g,"_").replace(/\.zip$/i,"")||"workspace",n=w.join(o,`${a}-${Date.now()}-${Math.random().toString(36).slice(2,8)}.zip`),{ZipArchive:c}=await G(),l=new c({zlib:{level:9}}),u=()=>l.pointer(),d=()=>l.abort(),f=Z(n),p=new Promise((g,P)=>{f.on("close",g),f.on("finish",g),l.on("error",P),f.on("error",P)});p.catch(()=>{}),l.pipe(f);const m=setInterval(()=>{try{if(i?.()){d();return}r?.(u())}catch{}},200);try{return l.on("progress",()=>{i?.()&&d()}),l.directory(t,!1),i?.()&&d(),await l.finalize(),await p,r?.(u()),n}catch(g){throw await s.rm(n,{force:!0}).catch(()=>{}),g}finally{clearInterval(m)}}async function Wt(t,e,r){let i=0,o;const a=_(t),n=a.pipe(gt.Parse({forceStream:!0}));try{for await(const c of n){if(o){await tt(c);continue}const l=Lt(c);try{const u=j(e,l);if(U(r),c.type==="Directory"){await s.mkdir(u,{recursive:!0});continue}if(c.type!=="File")throw new Error(`Unsupported archive entry type: ${l}`);await s.mkdir(w.dirname(u),{recursive:!0}),await D(u),await rt(c,u,r),i+=1}catch(u){o=u,await tt(c)}}}finally{a.destroy(),n.destroy()}if(o)throw o;return i}async function bt(t,e,r,i){let o=0,a;const n=(c,l)=>{if(a)return!1;try{j(e,c),U(i);const u=String(l.type||"").toLowerCase();if(u==="symboliclink"||u==="link")throw new Error(`Archive links are not supported: ${c}`);if(u!=="file"&&u!=="oldfile"&&u!=="contiguousfile"&&u!=="directory")throw new Error(`Unsupported archive entry type: ${c}`);return typeof l.size=="number"&&et(i,l.size),u!=="directory"&&(o+=1),!0}catch(u){return a=u,!1}};if(await yt.x({file:t,cwd:e,gzip:r,strict:!0,filter:(c,l)=>n(c,l)}),a)throw a;return o}async function Bt(t,e,r){const i=Q(w.basename(t)),o=j(e,i||"decompressed");return U(r),await s.mkdir(w.dirname(o),{recursive:!0}),await D(o),await rt(_(t).pipe(mt()),o,r),1}async function It(t){const{requestedRoot:e,workspaceRoot:r}=await v(t.workspacePath),{resolvedTargetPath:i}=await Y({workspacePath:t.workspacePath,targetPath:t.outputPath||""}),o=$(e,r,String(t.archivePath||"").trim()),a=await R(o);if(!(await s.stat(a)).isFile())throw new Error(`Archive path is not a file: ${a}`);if(await it(i)||await s.mkdir(i,{recursive:!0}),!(await s.stat(i)).isDirectory())throw new Error(`Output path is not a directory: ${i}`);const l=J(a);if(!l)throw new Error("Unsupported archive type. Supported: .zip, .tar, .tar.gz, .tgz, .gz");let u=0;const d={entries:0,totalBytes:0};return l==="zip"?u=await Wt(a,i,d):l==="tar"||l==="tgz"?u=await bt(a,i,l==="tgz",d):u=await Bt(a,i,d),{ok:!0,workspacePath:h(r),archivePath:h(a),targetPath:h(i),extractedEntries:u}}function nt(t){const e=t.match(/^(.*?)\{([^}]+)\}(.*)$/);if(!e)return[t];const[,r,i,o]=e;return i.split(",").flatMap(a=>nt(r+a.trim()+o))}function st(t,e){const r=String(e||"").trim();if(!r||r==="*"||r==="*.*")return!0;const i=t.toLowerCase();return nt(r.toLowerCase()).some(a=>{if(a==="*")return!0;const n=a.replace(/\./g,"\\.").replace(/\*\*/g,"<<GLOBSTAR>>").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/<<GLOBSTAR>>/g,".*");return new RegExp(`^${n}$`).test(i)})}function q(t){return t===".git"||t==="node_modules"||t===".svn"||t===".hg"}const ct=10*1024*1024,Mt=1e3;async function lt(t,e){const{workspaceRoot:r}=await v(t),i=String(e||"").trim();if(!i)return{workspaceRoot:r,searchRoot:r};const o=w.resolve(/^[A-Za-z]:$/.test(i)?`${i}/`:i);let a;try{a=await s.realpath(o)}catch{throw new Error(`Path not found: ${o}`)}if(!(await s.stat(a)).isDirectory())throw new Error(`Path is not a directory: ${o}`);return{workspaceRoot:r,searchRoot:a}}async function le(t){const{workspaceRoot:e,searchRoot:r}=await lt(t.workspacePath,t.rootPath),i=String(t.keyword||"").trim();if(!i)throw new Error("keyword is required");const o=!!t.ignoreCase,a=String(t.fileMask||"").trim(),n=typeof t.maxResults=="number"&&t.maxResults>0?t.maxResults:Mt,c=o?i.toLowerCase():i,u=(t.mode==="filename"?"filename":"content")==="filename",d=[];let f=0,p=!1;async function m(g){if(p)return;let P;try{P=await s.readdir(g,{withFileTypes:!0})}catch{return}for(const y of P){if(p)return;const k=C(r,w.join(g,y.name));if(y.isSymbolicLink())continue;if(y.isDirectory()){if(q(y.name))continue;await m(k);continue}if(!y.isFile()||a&&!st(y.name,a))continue;f+=1;let S;try{S=await s.stat(k)}catch{continue}if(S.size>ct)continue;if(u){const E=(o?y.name.toLowerCase():y.name).indexOf(c);if(E!==-1&&(d.push({filePath:h(k),lineNumber:0,lineContent:y.name,matchStart:E,matchEnd:E+i.length}),d.length>=n)){p=!0;return}continue}let z;try{z=await s.readFile(k,"utf-8")}catch{continue}const b=z.split(/\r?\n/);for(let T=0;T<b.length;T+=1){const E=b[T],ut=o?E.toLowerCase():E;let O=0;for(;;){const A=ut.indexOf(c,O);if(A===-1)break;if(d.push({filePath:h(k),lineNumber:T+1,lineContent:E,matchStart:A,matchEnd:A+i.length}),d.length>=n){p=!0;return}O=A+1}}}}return await m(r),{workspacePath:h(e),keyword:i,totalFiles:f,totalMatches:d.length,matches:d,truncated:p}}const Nt=100,jt=120;async function he(t){const{workspaceRoot:e}=await v(t.workspacePath),r=String(t.keyword||"").trim();if(!r)throw new Error("keyword is required");const i=!!t.ignoreCase,o=i?r.toLowerCase():r,a=typeof t.maxResults=="number"&&t.maxResults>0?t.maxResults:Nt,n=typeof t.maxDirectories=="number"&&t.maxDirectories>0?t.maxDirectories:jt,c=String(t.rootPath||"").trim(),l=c?w.resolve(/^[A-Za-z]:$/.test(c)?`${c}/`:c):e;let u;try{u=await s.realpath(l)}catch{throw new Error(`Path not found: ${l}`)}if(!(await s.stat(u)).isDirectory())throw new Error(`Path is not a directory: ${l}`);const f=[],p=[u];let m=0,g=!1;for(;p.length>0&&f.length<a&&m<n;){const P=p.shift();m+=1;let y;try{y=await s.readdir(P,{withFileTypes:!0})}catch{continue}for(const k of y){if(f.length>=a){g=!0;break}if(k.isSymbolicLink())continue;const S=w.join(P,k.name);if(k.isDirectory()&&q(k.name))continue;const z=w.relative(u,S).replace(/\\/g,"/");(i?z.toLowerCase():z).includes(o)&&f.push({name:k.name,path:h(S),isDirectory:k.isDirectory()}),k.isDirectory()&&m<n&&p.push(S)}}return(m>=n||f.length>=a)&&(g=!0),f.sort((P,y)=>P.isDirectory===y.isDirectory?P.name.localeCompare(y.name):P.isDirectory?-1:1),{workspacePath:h(e),rootPath:h(u),keyword:r,items:f,truncated:g}}async function ht(t,e,r,i){let o;try{o=await s.readFile(t,"utf-8")}catch{return{changed:!1,count:0}}const a=o;let n=0;if(i){const c=e.toLowerCase();let l=0;for(;;){const d=o.toLowerCase().indexOf(c,l);if(d===-1)break;o=o.slice(0,d)+r+o.slice(d+e.length),n+=1;const f=r.length||1;l=d+f}}else{let c=0;for(;;){const l=o.indexOf(e,c);if(l===-1)break;o=o.slice(0,l)+r+o.slice(l+e.length),n+=1;const u=r.length||1;c=l+u}}return o===a?{changed:!1,count:0}:(await D(t),await s.writeFile(t,o,"utf-8"),{changed:!0,count:n})}async function ue(t){const{workspaceRoot:e,searchRoot:r}=await lt(t.workspacePath,t.rootPath),i=String(t.keyword||"").trim();if(!i)throw new Error("keyword is required");const o=String(t.replacement??""),a=!!t.ignoreCase,n=String(t.fileMask||"").trim(),c=String(t.filePath||"").trim();let l=0,u=0;if(c){const{resolvedFilePath:f}=await W({workspacePath:t.workspacePath,filePath:c}),p=await ht(f,i,o,a);return p.changed&&(l=1,u=p.count),{workspacePath:h(e),keyword:i,replacement:o,changedFiles:l,changedMatches:u}}async function d(f){let p;try{p=await s.readdir(f,{withFileTypes:!0})}catch{return}for(const m of p){const g=C(r,w.join(f,m.name));if(m.isSymbolicLink())continue;if(m.isDirectory()){if(q(m.name))continue;await d(g);continue}if(!m.isFile()||n&&!st(m.name,n))continue;try{if((await s.stat(g)).size>ct)continue}catch{continue}const P=await ht(g,i,o,a);P.changed&&(l+=1,u+=P.count)}}return await d(r),{workspacePath:h(e),keyword:i,replacement:o,changedFiles:l,changedMatches:u}}export{Jt as chmodWorkspaceEntry,ee as createWorkspaceEntry,oe as deleteWorkspaceEntry,It as extractWorkspaceArchive,Yt as getWorkspaceEntryProperties,Xt as listWorkspaceDirectory,ie as moveWorkspaceEntry,Qt as previewWorkspaceDocument,Vt as readWorkspaceFile,re as renameWorkspaceEntry,ue as replaceWorkspaceFiles,ne as resolveWorkspaceDownloadTarget,le as searchWorkspaceFiles,he as searchWorkspacePaths,se as streamWorkspaceDirectoryZip,ae as uploadWorkspaceFiles,te as writeWorkspaceFile,ce as zipWorkspaceDirectoryToTemp};
2
2
 
@@ -0,0 +1,31 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+ export interface LoadDynamicModuleOptions {
28
+
29
+ freshInstanceQuery?: string;
30
+ }
31
+ export declare function loadDynamicModule<T = unknown>(specifier: string, options?: LoadDynamicModuleOptions): Promise<T>;
@@ -0,0 +1,2 @@
1
+ import{copyFileSync as u,rmSync as s}from"node:fs";import{fileURLToPath as l}from"node:url";async function i(e,t){if(typeof require=="function"&&typeof require.cache=="object"&&require.cache!==null){const o=require,r=e.startsWith("file://")?l(e):e;if(t?.freshInstanceQuery){if(/\.m[jt]s$/i.test(r)){const c=t.freshInstanceQuery.replace(/[^A-Za-z0-9._-]/g,"_"),n=r.match(/\.[^.]+$/)?.[0]??".mjs",a=`${r}.acode-fresh-${c}${n}`;try{return u(r,a),o(a)}finally{try{s(a,{force:!0})}catch{}}}try{const c=o.resolve(r),n=require.cache;n&&c&&delete n[c]}catch{}}return o(r)}return import(t?.freshInstanceQuery?`${e}${e.includes("?")?"&":"?"}${t.freshInstanceQuery}`:e)}export{i as loadDynamicModule};
2
+
@@ -1,2 +1,2 @@
1
- import{access as p,readFile as m}from"node:fs/promises";import o from"node:path";import{fileURLToPath as l,pathToFileURL as y}from"node:url";const d=(()=>{const r=String(process.env.AWS_BRIDGE_PACKAGE_ROOT||"").trim();return r?o.resolve(r):o.resolve(o.dirname(l(import.meta.url)),"..","..")})();function c(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function E(r,t){return o.join(t,"node_modules",...r.split("/"))}function e(r){if(typeof r=="string")return r;if(!c(r))return null;for(const t of["import","module","default","node"]){const n=e(r[t]);if(n)return n}return null}function g(r){return typeof r=="string"?r:c(r)?e(r["."])??e(r):null}function P(r){const t=g(r.exports);return t||(typeof r.module=="string"?r.module:typeof r.main=="string"?r.main:"index.js")}async function h(r,t=d){const n=E(r,t),a=o.join(n,"package.json"),s=await m(a,"utf8"),f=JSON.parse(s),u=P(f),i=o.resolve(n,u);return await p(i),i}async function A(r){try{const t=await h(r);return await import(y(t).href)}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return await import(r);throw t}}export{d as BRIDGE_PACKAGE_ROOT,A as importBridgeSdkPackage,h as resolveBridgePackageEntryPath};
1
+ import{access as l,readFile as m}from"node:fs/promises";import o from"node:path";import{fileURLToPath as y,pathToFileURL as d}from"node:url";import{loadDynamicModule as c}from"./dynamic-import.js";const E=(()=>{const r=String(process.env.AWS_BRIDGE_PACKAGE_ROOT||"").trim();return r?o.resolve(r):o.resolve(o.dirname(y(import.meta.url)),"..","..")})();function a(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function g(r,t){return o.join(t,"node_modules",...r.split("/"))}function e(r){if(typeof r=="string")return r;if(!a(r))return null;for(const t of["import","module","default","node"]){const n=e(r[t]);if(n)return n}return null}function P(r){return typeof r=="string"?r:a(r)?e(r["."])??e(r):null}function h(r){const t=P(r.exports);return t||(typeof r.module=="string"?r.module:typeof r.main=="string"?r.main:"index.js")}async function R(r,t=E){const n=g(r,t),s=o.join(n,"package.json"),f=await m(s,"utf8"),u=JSON.parse(f),p=h(u),i=o.resolve(n,p);return await l(i),i}async function O(r){try{const t=await R(r);return await c(d(t).href)}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return await c(r);throw t}}export{E as BRIDGE_PACKAGE_ROOT,O as importBridgeSdkPackage,R as resolveBridgePackageEntryPath};
2
2
 
File without changes
File without changes
File without changes
File without changes
@@ -1,4 +1,4 @@
1
- const _=6e5,g=`Block and wait for one or more sub-agents AND/OR background commands to complete.
1
+ import{formatSubagentHandback as h,formatSubagentPartialHandback as _}from"./subagent-handback.js";const b=10*6e4,f=`Block and wait for one or more sub-agents AND/OR background commands to complete.
2
2
 
3
3
  This is the unified replacement for the old await_sub_agents: it can wait for BOTH
4
4
  sub-agents (spawned via sub_agent) and background commands (started via Bash with
@@ -16,6 +16,6 @@ Guidelines:
16
16
  - Pass sub-agent IDs in 'sub_agent_ids' and/or background command task_ids in 'bg_cmd_ids'
17
17
  - At least one of the two arrays must be non-empty
18
18
  - Use timeout_ms to bound the wait (default 600000 = 10 minutes; 0 = wait forever)
19
- - After this returns, call poll_message to receive any pending messages`;function h(o){return{kind:"builtin",toolName:"await_complete",exposedName:"await_complete",concurrencyMode:"blocking",description:g,inputSchema:{type:"object",properties:{sub_agent_ids:{type:"array",items:{type:"string"},description:"Array of sub-agent IDs to wait for (from sub_agent). Empty if none."},bg_cmd_ids:{type:"array",items:{type:"string"},description:"Array of background command task_ids to wait for (from Bash wait_seconds or list_background_commands). Empty if none."},timeout_ms:{type:"number",description:"Maximum time to wait in milliseconds, applied to the whole JOIN. 0 = no timeout (wait forever). Default: 600000 (10 minutes)."}},additionalProperties:!1},async execute(n){const l=typeof n.timeout_ms=="number"?n.timeout_ms:6e5,m=n.sub_agent_ids,c=n.bg_cmd_ids,i=Array.isArray(m)?m.filter(t=>typeof t=="string"&&t.trim().length>0):[],u=Array.isArray(c)?c.filter(t=>typeof t=="string"&&t.trim().length>0):[];if(i.length===0&&u.length===0)return{title:"await_complete validation error",output:"Invalid input: provide at least one of 'sub_agent_ids' or 'bg_cmd_ids'.",metadata:{error:!0}};if(i.length>0&&!o.awaitSubAgents)return{title:"await_complete error",output:"sub_agent_ids provided but sub-agent manager is not enabled for this agent.",metadata:{error:!0}};try{let t=[];i.length>0&&o.awaitSubAgents&&(t=await o.awaitSubAgents(i,l)??[]);let a=[];u.length>0&&(a=await o.awaitBgCommands(u,l));const s=[],p=[],d=[];if(t.length>0){s.push(`=== ${t.length} sub-agent(s) ===`);for(const e of t)s.push(`[${e.status}] ${e.subId}`),e.error?(s.push("<task_error>"),s.push(e.error),s.push("</task_error>")):(s.push("<task_result>"),s.push(e.output||"(empty output)"),s.push("</task_result>")),s.push(""),p.push(e)}if(a.length>0){s.push(`=== ${a.length} background command(s) ===`);for(const e of a){if(!e){s.push("[not_found] (unknown task_id)"),s.push(""),d.push(null);continue}const r=[];e.timedOut&&r.push("timed_out"),e.aborted&&r.push("aborted"),s.push(`[${e.status}] ${e.taskId} exit=${e.exitCode??"?"}`+(r.length?` (${r.join(",")})`:"")+(e.outputFilePath?` output=${e.outputFilePath}`:"")),s.push(""),d.push(e)}}return{title:`awaited ${t.length+a.length} item(s)`,output:s.join(`
20
- `),metadata:{total:t.length+a.length,sub_agents:p,bg_cmds:d}}}catch(t){return{title:"await_complete error",output:`Failed to await: ${t instanceof Error?t.message:String(t)}`,metadata:{error:!0}}}}}}export{h as createAwaitCompleteTool};
19
+ - After this returns, call poll_message to receive any pending messages`;function k(n){return{kind:"builtin",toolName:"await_complete",exposedName:"await_complete",concurrencyMode:"blocking",description:f,inputSchema:{type:"object",properties:{sub_agent_ids:{type:"array",items:{type:"string"},description:"Array of sub-agent IDs to wait for (from sub_agent). Empty if none."},bg_cmd_ids:{type:"array",items:{type:"string"},description:"Array of background command task_ids to wait for (from Bash wait_seconds or list_background_commands). Empty if none."},timeout_ms:{type:"number",description:"Maximum time to wait in milliseconds, applied to the whole JOIN. 0 = no timeout (wait forever). Default: 600000 (10 minutes)."}},additionalProperties:!1},async execute(i){const u=typeof i.timeout_ms=="number"?i.timeout_ms:b,c=i.sub_agent_ids,p=i.bg_cmd_ids,d=Array.isArray(c)?c.filter(a=>typeof a=="string"&&a.trim().length>0):[],l=Array.isArray(p)?p.filter(a=>typeof a=="string"&&a.trim().length>0):[];if(d.length===0&&l.length===0)return{title:"await_complete validation error",output:"Invalid input: provide at least one of 'sub_agent_ids' or 'bg_cmd_ids'.",metadata:{error:!0}};if(d.length>0&&!n.awaitSubAgents)return{title:"await_complete error",output:"sub_agent_ids provided but sub-agent manager is not enabled for this agent.",metadata:{error:!0}};try{const a=Date.now()+u;let s=[];d.length>0&&n.awaitSubAgents&&(s=await n.awaitSubAgents(d,u)??[]);let r=[];l.length>0&&(r=await n.awaitBgCommands(l,u>0?Math.max(0,a-Date.now()):u));const e=[],g=[],m=[];if(s.length>0){e.push(`=== ${s.length} sub-agent(s) ===`);for(const t of s){if(e.push(`[${t.status}] ${t.subId}`),t.error&&(e.push("<task_error>"),e.push(t.error),e.push("</task_error>")),t.output){const o=t.error?"task_partial_output":"task_result";e.push(`<${o}>`),e.push(t.error?_(t.output):h(t.output)),e.push(`</${o}>`)}else t.error||(e.push("<task_result>"),e.push("(empty output)"),e.push("</task_result>"));e.push(""),g.push(t)}}if(r.length>0){e.push(`=== ${r.length} background command(s) ===`);for(const t of r){if(!t){e.push("[not_found] (unknown task_id)"),e.push(""),m.push(null);continue}const o=[];t.timedOut&&o.push("timed_out"),t.aborted&&o.push("aborted"),e.push(`[${t.status}] ${t.taskId} exit=${t.exitCode??"?"}`+(o.length?` (${o.join(",")})`:"")+(t.outputFilePath?` output=${t.outputFilePath}`:"")),e.push(""),m.push(t)}}return{title:`awaited ${s.length+r.length} item(s)`,output:e.join(`
20
+ `),metadata:{total:s.length+r.length,sub_agents:g,bg_cmds:m}}}catch(a){return{title:"await_complete error",output:`Failed to await: ${a instanceof Error?a.message:String(a)}`,metadata:{error:!0}}}}}}export{k as createAwaitCompleteTool};
21
21
 
@@ -963,6 +963,15 @@ export declare class ACodeRuntime extends EventEmitter {
963
963
 
964
964
 
965
965
 
966
+
967
+
968
+
969
+
970
+ private static buildSubAgentCompletionMessage;
971
+
972
+
973
+
974
+
966
975
  private static formatSubAgentCompletionAsPollResult;
967
976
 
968
977