aws-runtime-bridge 1.9.186 → 1.9.192

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 (108) hide show
  1. package/CHANGELOG.md +1878 -1673
  2. package/README.md +256 -256
  3. package/dist/adapter/AcodeSdkAdapter.d.ts +13 -0
  4. package/dist/adapter/AcodeSdkAdapter.js +3 -3
  5. package/dist/browser/browser-pool.d.ts +2 -0
  6. package/dist/browser/browser-pool.js +1 -1
  7. package/dist/config.d.ts +12 -31
  8. package/dist/config.js +2 -2
  9. package/dist/index.js +1 -1
  10. package/dist/remote-desktop/win32-api.js +1 -1
  11. package/dist/routes/background-tasks.js +4 -4
  12. package/dist/routes/dashboard.js +17 -17
  13. package/dist/routes/media-files.d.ts +19 -0
  14. package/dist/routes/media-files.js +2 -0
  15. package/dist/routes/plugin-ui.d.ts +17 -0
  16. package/dist/routes/plugin-ui.js +2 -0
  17. package/dist/routes/plugins.d.ts +3 -0
  18. package/dist/routes/plugins.js +1 -1
  19. package/dist/routes/terminal.d.ts +83 -0
  20. package/dist/routes/terminal.js +23 -23
  21. package/dist/scripts/migrate-user-scopes.js +1 -1
  22. package/dist/services/acode-bg-manager.js +1 -1
  23. package/dist/services/agent-capability-sync.js +1 -1
  24. package/dist/services/auto-register.js +1 -1
  25. package/dist/services/capability-config.d.ts +0 -1
  26. package/dist/services/capability-config.js +2 -2
  27. package/dist/services/instance-ai-config-service.js +1 -1
  28. package/dist/services/instance-features.d.ts +9 -0
  29. package/dist/services/instance-features.js +1 -1
  30. package/dist/services/panel-auth.d.ts +4 -0
  31. package/dist/services/panel-auth.js +1 -1
  32. package/dist/services/plugin-deployment.d.ts +2 -30
  33. package/dist/services/plugin-deployment.js +2 -2
  34. package/dist/services/plugin-handler-adapter.d.ts +10 -1
  35. package/dist/services/plugin-handler-adapter.js +2 -2
  36. package/dist/services/plugin-listener-runner.js +4 -4
  37. package/dist/services/plugin-loader.d.ts +7 -1
  38. package/dist/services/plugin-loader.js +1 -1
  39. package/dist/services/plugin-manager.d.ts +32 -12
  40. package/dist/services/plugin-manager.js +4 -4
  41. package/dist/services/plugin-manifest.d.ts +53 -3
  42. package/dist/services/plugin-manifest.js +1 -1
  43. package/dist/services/plugin-runtime.d.ts +8 -9
  44. package/dist/services/plugin-ui-status-runtime.d.ts +8 -0
  45. package/dist/services/plugin-ui-status-runtime.js +2 -0
  46. package/dist/services/plugin-ui-status.d.ts +96 -0
  47. package/dist/services/plugin-ui-status.js +2 -0
  48. package/dist/services/plugin-wecom-callback.d.ts +61 -0
  49. package/dist/services/plugin-wecom-callback.js +3 -0
  50. package/dist/services/user-scope.d.ts +1 -9
  51. package/dist/services/user-scope.js +1 -1
  52. package/dist/services/workspace-files.js +1 -1
  53. package/dist/utils/dynamic-import.d.ts +31 -0
  54. package/dist/utils/dynamic-import.js +2 -0
  55. package/dist/utils/sdk-package-loader.js +1 -1
  56. package/node_modules/playwright/cli.js +0 -0
  57. package/node_modules/playwright-core/bin/reinstall_chrome_beta_linux.sh +0 -0
  58. package/node_modules/playwright-core/bin/reinstall_chrome_beta_mac.sh +0 -0
  59. package/node_modules/playwright-core/bin/reinstall_chrome_stable_linux.sh +0 -0
  60. package/node_modules/playwright-core/bin/reinstall_chrome_stable_mac.sh +0 -0
  61. package/node_modules/playwright-core/bin/reinstall_msedge_beta_linux.sh +0 -0
  62. package/node_modules/playwright-core/bin/reinstall_msedge_beta_mac.sh +0 -0
  63. package/node_modules/playwright-core/bin/reinstall_msedge_dev_linux.sh +0 -0
  64. package/node_modules/playwright-core/bin/reinstall_msedge_dev_mac.sh +0 -0
  65. package/node_modules/playwright-core/bin/reinstall_msedge_stable_linux.sh +0 -0
  66. package/node_modules/playwright-core/bin/reinstall_msedge_stable_mac.sh +0 -0
  67. package/node_modules/playwright-core/cli.js +0 -0
  68. package/node_modules/playwright-core/lib/webp_codec.wasm +0 -0
  69. package/node_modules/playwright-core/lib/xdg-open +0 -0
  70. package/package/acode/dist/await-complete-tool.js +3 -3
  71. package/package/acode/dist/plugin-types.d.ts +41 -1
  72. package/package/acode/dist/runtime.d.ts +26 -0
  73. package/package/acode/dist/runtime.js +21 -22
  74. package/package/acode/dist/sub-agent-manager.d.ts +33 -0
  75. package/package/acode/dist/sub-agent-manager.js +9 -1
  76. package/package/acode/dist/sub-agent-tools.d.ts +4 -0
  77. package/package/acode/dist/sub-agent-tools.js +27 -12
  78. package/package/acode/dist/subagent-handback.d.ts +16 -0
  79. package/package/acode/dist/subagent-handback.js +7 -0
  80. package/package/acode/dist/tool-allocation.js +1 -1
  81. package/package/acode/package.json +38 -38
  82. package/package/aws-client-agent-mcp/dist/agent-client.d.ts +10 -5
  83. package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
  84. package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +27 -0
  85. package/package/aws-client-agent-mcp/dist/mcp-server.js +16 -16
  86. package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +34 -0
  87. package/package/aws-client-agent-mcp/dist/mcp-tools.js +65 -19
  88. package/package/aws-client-agent-mcp/dist/message-buffer.d.ts +10 -0
  89. package/package/aws-client-agent-mcp/dist/message-buffer.js +1 -1
  90. package/package/aws-client-agent-mcp/dist/tool-groups.js +2 -2
  91. package/package/aws-client-agent-mcp/dist/types.d.ts +81 -3
  92. package/package/aws-client-agent-mcp/package.json +53 -53
  93. package/package.json +134 -132
  94. /package/package/acode/dist/grammars/{grammars/tree-sitter-bash.wasm → tree-sitter-bash.wasm} +0 -0
  95. /package/package/acode/dist/grammars/{grammars/tree-sitter-c-sharp.wasm → tree-sitter-c-sharp.wasm} +0 -0
  96. /package/package/acode/dist/grammars/{grammars/tree-sitter-c.wasm → tree-sitter-c.wasm} +0 -0
  97. /package/package/acode/dist/grammars/{grammars/tree-sitter-cpp.wasm → tree-sitter-cpp.wasm} +0 -0
  98. /package/package/acode/dist/grammars/{grammars/tree-sitter-go.wasm → tree-sitter-go.wasm} +0 -0
  99. /package/package/acode/dist/grammars/{grammars/tree-sitter-java.wasm → tree-sitter-java.wasm} +0 -0
  100. /package/package/acode/dist/grammars/{grammars/tree-sitter-javascript.wasm → tree-sitter-javascript.wasm} +0 -0
  101. /package/package/acode/dist/grammars/{grammars/tree-sitter-jsx.wasm → tree-sitter-jsx.wasm} +0 -0
  102. /package/package/acode/dist/grammars/{grammars/tree-sitter-lua.wasm → tree-sitter-lua.wasm} +0 -0
  103. /package/package/acode/dist/grammars/{grammars/tree-sitter-php.wasm → tree-sitter-php.wasm} +0 -0
  104. /package/package/acode/dist/grammars/{grammars/tree-sitter-python.wasm → tree-sitter-python.wasm} +0 -0
  105. /package/package/acode/dist/grammars/{grammars/tree-sitter-ruby.wasm → tree-sitter-ruby.wasm} +0 -0
  106. /package/package/acode/dist/grammars/{grammars/tree-sitter-rust.wasm → tree-sitter-rust.wasm} +0 -0
  107. /package/package/acode/dist/grammars/{grammars/tree-sitter-tsx.wasm → tree-sitter-tsx.wasm} +0 -0
  108. /package/package/acode/dist/grammars/{grammars/tree-sitter-typescript.wasm → tree-sitter-typescript.wasm} +0 -0
@@ -21,6 +21,7 @@
21
21
 
22
22
 
23
23
 
24
+
24
25
 
25
26
 
26
27
  import type { NextFunction, Request, Response } from "express";
@@ -30,8 +31,6 @@ export interface UserScope {
30
31
  }
31
32
  export declare const SCOPE_ID_PATTERN: RegExp;
32
33
 
33
- export declare const LEGACY_SCOPE: Readonly<UserScope>;
34
-
35
34
  export declare const TENANT_HEADER = "x-tenant-id";
36
35
  export declare const USER_HEADER = "x-user-id";
37
36
  declare module "express-serve-static-core" {
@@ -62,13 +61,6 @@ export declare function scopeEquals(a: UserScope | null, b: UserScope | null): b
62
61
 
63
62
  export declare function isLegacyScope(scope: UserScope | null): boolean;
64
63
 
65
-
66
-
67
-
68
- export declare function isLegacyScopeAllowed(): boolean;
69
-
70
- export declare function isLegacyFallbackDisabled(): boolean;
71
-
72
64
  export declare function getUserScopeRoot(scope: UserScope): string;
73
65
 
74
66
  export declare function getUserAiConfigFile(scope: UserScope): string;
@@ -1,2 +1,2 @@
1
- import o from"node:path";import{getBridgeDataHome as x}from"../config.js";import{loadRuntimeBinding as m}from"./runtime-binding.js";const y=/^[a-zA-Z0-9_.-]+$/,p=Object.freeze({tenantId:"_legacy",userId:"_legacy"}),U="x-tenant-id",D="x-user-id";function i(e){const r=String(e??"").replace(/[^a-zA-Z0-9_.-]/g,"_");return/^\.+$/.test(r)?"_":r.replace(/^\.+/g,"")}function b(e){return typeof e=="string"&&e.length>0&&y.test(e)}function a(e,r){const t=String(e??"").trim(),n=String(r??"").trim();return!t||!n?null:{tenantId:t,userId:n}}function _(e,r){return!e||!r?!1:i(e.tenantId)===i(r.tenantId)&&i(e.userId)===i(r.userId)}function L(e){return _(e,p)}function f(){return String(process.env.AWS_BRIDGE_LEGACY_SCOPE||"").trim().toLowerCase()==="1"}function O(){return String(process.env.AWS_BRIDGE_DISABLE_LEGACY_FALLBACK||"").trim().toLowerCase()==="1"}function j(e){return[i(e.tenantId),i(e.userId)]}function s(e){return o.join(x(),"users",...j(e))}function R(e){return o.join(s(e),"ai","acode.json")}function A(e){return o.join(s(e),"skills")}function P(e){return o.join(A(e),"deployed")}function d(e){return o.join(s(e),"mcp")}function B(e){return o.join(d(e),"deployed")}function F(e){return o.join(d(e),"packages")}function E(e){return o.join(s(e),"plugins")}function H(e){return o.join(E(e),"deployed")}function g(e,r){return o.join(s(e),"capability",r)}function T(e,r){return o.join(g(e,r),"config.json")}function z(e,r,t){return o.join(g(e,r),"agents",`${i(t)}.json`)}function h(...e){for(const r of e){const t=String(r??"").trim();if(t)return t}return""}function u(e){const r=a(e.header(U),e.header(D));if(r)return r;const t=e.body??{};return a(t.tenantId,h(t.ownerUserId,t.userId))}function S(){try{const e=m();return e?.userId?a("_local",e.userId):null}catch{return null}}function G(e,r,t){const n=u(e)??S();n?e.userScope=n:f()&&(e.userScope={...p}),t()}function v(e,r,t){if(e.userScope){t();return}const n=u(e)??S();if(n){e.userScope=n,t();return}if(f()){e.userScope={...p},t();return}r.status(400).json({ok:!1,error:"user-scope-required",message:"\u8BF7\u6C42\u7F3A\u5C11 X-Tenant-Id / X-User-Id\uFF08\u6216\u4F53 tenantId + ownerUserId\uFF09\u8EAB\u4EFD"})}function M(e){const r=e.userScope??u(e);if(!r)throw new Error("user-scope-required: \u8BF7\u6C42\u7F3A\u5C11 (tenantId, userId) \u8EAB\u4EFD");return r}let l=null,I=null;function N(e){l=e}function Y(e){I=e}function $(e,r,t){const n=String(e.params?.agentId??e.body?.agentId??"").trim();if(!n){t();return}const c=e.userScope??u(e);if(!c){r.status(400).json({ok:!1,error:"user-scope-required",message:"agent \u7EA7\u64CD\u4F5C\u7F3A\u5C11 (tenantId, userId) \u8EAB\u4EFD"});return}if(l&&!l(n,c)){if(I?.(n,c)){t();return}r.status(403).json({ok:!1,error:"agent-ownership-mismatch",message:"\u8BE5\u5B9E\u4F8B\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237"});return}t()}export{p as LEGACY_SCOPE,y as SCOPE_ID_PATTERN,U as TENANT_HEADER,D as USER_HEADER,u as extractUserScope,R as getUserAiConfigFile,z as getUserCapabilityAgentFile,T as getUserCapabilityDefaultsFile,g as getUserCapabilityDir,B as getUserMcpDeployedDir,d as getUserMcpDir,F as getUserMcpPackagesDir,H as getUserPluginsDeployedDir,E as getUserPluginsDir,M as getUserScopeOrThrow,s as getUserScopeRoot,P as getUserSkillsDeployedDir,A as getUserSkillsDir,O as isLegacyFallbackDisabled,L as isLegacyScope,f as isLegacyScopeAllowed,b as isValidScopeId,a as normalizeUserScope,$ as requireAgentOwnership,v as requireUserScope,G as resolveUserScope,i as sanitizeScopeId,_ as scopeEquals,N as setAgentOwnershipChecker,Y as setMachineOwnershipSelfHeal};
1
+ import o from"node:path";import{getBridgeDataHome as I}from"../config.js";import{loadRuntimeBinding as x}from"./runtime-binding.js";const S=/^[a-zA-Z0-9_.-]+$/,m="x-tenant-id",U="x-user-id";function i(e){const r=String(e??"").replace(/[^a-zA-Z0-9_.-]/g,"_");return/^\.+$/.test(r)?"_":r.replace(/^\.+/g,"")}function E(e){return typeof e=="string"&&e.length>0&&S.test(e)}function p(e,r){const t=String(e??"").trim(),n=String(r??"").trim();return!t||!n?null:{tenantId:t,userId:n}}function A(e,r){return!e||!r?!1:i(e.tenantId)===i(r.tenantId)&&i(e.userId)===i(r.userId)}function b(e){return i(e?.tenantId??"")==="_legacy"&&i(e?.userId??"")==="_legacy"}function y(e){return[i(e.tenantId),i(e.userId)]}function s(e){return o.join(I(),"users",...y(e))}function C(e){return o.join(s(e),"ai","acode.json")}function h(e){return o.join(s(e),"skills")}function H(e){return o.join(h(e),"deployed")}function f(e){return o.join(s(e),"mcp")}function O(e){return o.join(f(e),"deployed")}function R(e){return o.join(f(e),"packages")}function j(e){return o.join(s(e),"plugins")}function T(e){return o.join(j(e),"deployed")}function l(e,r){return o.join(s(e),"capability",r)}function P(e,r){return o.join(l(e,r),"config.json")}function z(e,r,t){return o.join(l(e,r),"agents",`${i(t)}.json`)}function D(...e){for(const r of e){const t=String(r??"").trim();if(t)return t}return""}function u(e){const r=p(e.header(m),e.header(U));if(r)return r;const t=e.body??{};return p(t.tenantId,D(t.ownerUserId,t.userId))}function d(){try{const e=x();return e?.userId?p("_local",e.userId):null}catch{return null}}function F(e,r,t){const n=u(e)??d();n&&(e.userScope=n),t()}function M(e,r,t){if(e.userScope){t();return}const n=u(e)??d();if(n){e.userScope=n,t();return}r.status(400).json({ok:!1,error:"user-scope-required",message:"\u8BF7\u6C42\u7F3A\u5C11 X-Tenant-Id / X-User-Id\uFF08\u6216\u4F53 tenantId + ownerUserId\uFF09\u8EAB\u4EFD"})}function N(e){const r=e.userScope??u(e);if(!r)throw new Error("user-scope-required: \u8BF7\u6C42\u7F3A\u5C11 (tenantId, userId) \u8EAB\u4EFD");return r}let a=null,g=null;function $(e){a=e}function v(e){g=e}function B(e,r,t){const n=String(e.params?.agentId??e.body?.agentId??"").trim();if(!n){t();return}const c=e.userScope??u(e);if(!c){r.status(400).json({ok:!1,error:"user-scope-required",message:"agent \u7EA7\u64CD\u4F5C\u7F3A\u5C11 (tenantId, userId) \u8EAB\u4EFD"});return}if(a&&!a(n,c)){if(g?.(n,c)){t();return}r.status(403).json({ok:!1,error:"agent-ownership-mismatch",message:"\u8BE5\u5B9E\u4F8B\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237"});return}t()}export{S as SCOPE_ID_PATTERN,m as TENANT_HEADER,U as USER_HEADER,u as extractUserScope,C as getUserAiConfigFile,z as getUserCapabilityAgentFile,P as getUserCapabilityDefaultsFile,l as getUserCapabilityDir,O as getUserMcpDeployedDir,f as getUserMcpDir,R as getUserMcpPackagesDir,T as getUserPluginsDeployedDir,j as getUserPluginsDir,N as getUserScopeOrThrow,s as getUserScopeRoot,H as getUserSkillsDeployedDir,h as getUserSkillsDir,b as isLegacyScope,E as isValidScopeId,p as normalizeUserScope,B as requireAgentOwnership,M as requireUserScope,F as resolveUserScope,i as sanitizeScopeId,A as scopeEquals,$ as setAgentOwnershipChecker,v as setMachineOwnershipSelfHeal};
2
2
 
@@ -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
 
@@ -27,11 +27,35 @@ export declare function splitQualifiedToolName(qualifiedName: string): {
27
27
 
28
28
  export type PluginStatus = "enabled" | "disabled" | "error";
29
29
 
30
+
31
+
32
+
33
+ export interface PluginUiSummary {
34
+
35
+ icon?: string;
36
+ status?: {
37
+ tool: string;
38
+ persistent: boolean;
39
+
40
+ hideWhenZero?: boolean;
41
+ pollIntervalMs: number;
42
+ title?: string;
43
+ };
44
+ view?: {
45
+
46
+ entry: string;
47
+ title: string;
48
+
49
+ invoke: string[];
50
+ defaultRoute?: string;
51
+ };
52
+ }
53
+
30
54
  export type PluginListenerState = "pending" | "running" | "stopped";
31
55
 
32
56
  export interface PluginListenerSummary {
33
57
  event: string;
34
- delivery: "poll" | "force" | "wake";
58
+ delivery: "poll";
35
59
  running: boolean;
36
60
 
37
61
 
@@ -68,6 +92,22 @@ export interface PluginSummary {
68
92
  listenerState?: PluginListenerState;
69
93
 
70
94
  error?: string;
95
+
96
+ frontend?: PluginUiSummary;
97
+
98
+
99
+
100
+
101
+ userConfig?: Array<{
102
+ key: string;
103
+ description?: string;
104
+ required?: boolean;
105
+ sensitive?: boolean;
106
+
107
+ source: "json" | "env" | "default";
108
+
109
+ value?: string;
110
+ }>;
71
111
  }
72
112
 
73
113
  export type PluginManageAction = "install" | "uninstall" | "reload" | "enable" | "disable" | "list";
@@ -256,6 +256,12 @@ export declare class ACodeRuntime extends EventEmitter {
256
256
  private instructionsDirty;
257
257
 
258
258
  private turnPromptPushed;
259
+
260
+
261
+
262
+
263
+
264
+ private resumeContextNoticeAppended;
259
265
  private abortRequested;
260
266
 
261
267
 
@@ -523,6 +529,7 @@ export declare class ACodeRuntime extends EventEmitter {
523
529
 
524
530
 
525
531
 
532
+
526
533
  exportConversation(): ChatMessage[];
527
534
 
528
535
 
@@ -542,6 +549,8 @@ export declare class ACodeRuntime extends EventEmitter {
542
549
 
543
550
 
544
551
 
552
+
553
+
545
554
 
546
555
 
547
556
  importTranscript(transcript: ChatMessage[]): Promise<number>;
@@ -552,6 +561,14 @@ export declare class ACodeRuntime extends EventEmitter {
552
561
 
553
562
 
554
563
 
564
+ appendResumeContextNotice(): void;
565
+
566
+
567
+
568
+
569
+
570
+
571
+
555
572
  addBuiltInTools(tools: unknown[]): number;
556
573
 
557
574
 
@@ -963,6 +980,15 @@ export declare class ACodeRuntime extends EventEmitter {
963
980
 
964
981
 
965
982
 
983
+
984
+
985
+
986
+
987
+ private static buildSubAgentCompletionMessage;
988
+
989
+
990
+
991
+
966
992
  private static formatSubAgentCompletionAsPollResult;
967
993
 
968
994