aws-runtime-bridge 1.9.131 → 1.9.135
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/AcodeSdkAdapter.d.ts +15 -0
- package/dist/adapter/AcodeSdkAdapter.js +5 -5
- package/dist/adapter/types.d.ts +9 -0
- package/dist/browser/built-in-browser-tools.js +1 -1
- package/dist/routes/system-metrics.js +1 -1
- package/dist/routes/terminal.js +19 -19
- package/dist/services/instance-features.d.ts +5 -0
- package/dist/services/instance-features.js +1 -1
- package/dist/services/process-detail.d.ts +77 -0
- package/dist/services/process-detail.js +32 -0
- package/dist/services/process-top.d.ts +53 -0
- package/dist/services/process-top.js +50 -0
- package/dist/services/session-output.d.ts +10 -0
- package/dist/services/session-output.js +3 -3
- package/package/acode/dist/built-in-file-tools.d.ts +25 -1
- package/package/acode/dist/built-in-file-tools.js +2 -2
- package/package/acode/dist/image-utils.d.ts +52 -0
- package/package/acode/dist/image-utils.js +2 -0
- package/package/acode/dist/index.d.ts +1 -0
- package/package/acode/dist/index.js +1 -1
- package/package/acode/dist/runtime.d.ts +15 -1
- package/package/acode/dist/runtime.js +26 -26
- package/package/acode/dist/types.d.ts +3 -1
- package/package/aws-client-agent-mcp/dist/http-client.d.ts +4 -0
- package/package/aws-client-agent-mcp/dist/http-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +8 -0
- package/package/aws-client-agent-mcp/dist/mcp-server.js +28 -25
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +6 -6
- package/package/aws-client-agent-mcp/dist/memory-store.d.ts +6 -0
- package/package/aws-client-agent-mcp/dist/memory-tools.js +2 -2
- package/package/aws-client-agent-mcp/dist/types.d.ts +4 -0
- package/package/aws-client-agent-mcp/package.json +1 -1
- package/package.json +1 -1
- package/package/aws-client-agent-mcp/dist/agent-client.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/agent-client.test.js +0 -1066
- package/package/aws-client-agent-mcp/dist/config.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/config.test.js +0 -259
- package/package/aws-client-agent-mcp/dist/context-manager.test.d.ts +0 -2
- package/package/aws-client-agent-mcp/dist/context-manager.test.js +0 -312
- package/package/aws-client-agent-mcp/dist/http-client.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/http-client.test.js +0 -808
- package/package/aws-client-agent-mcp/dist/launch-config-tools.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/launch-config-tools.test.js +0 -110
- package/package/aws-client-agent-mcp/dist/logger.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/logger.test.js +0 -27
- package/package/aws-client-agent-mcp/dist/mcp-server.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.test.js +0 -2798
- package/package/aws-client-agent-mcp/dist/mcp-tools.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/mcp-tools.test.js +0 -152
- package/package/aws-client-agent-mcp/dist/memory-store.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/memory-store.test.js +0 -664
- package/package/aws-client-agent-mcp/dist/message-buffer.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/message-buffer.test.js +0 -142
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.js +0 -81
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.js +0 -201
- package/package/aws-client-agent-mcp/dist/status-reporter.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/status-reporter.test.js +0 -157
- package/package/aws-client-agent-mcp/dist/watchdog.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/watchdog.test.js +0 -124
- package/package/aws-client-agent-mcp/dist/websocket-client.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/websocket-client.test.js +0 -725
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import h from"axios";import{resolveSchedulerBaseUrlFrom as M}from"../config.js";import{requestRuntimeAccessTokenRefreshForServer as C}from"../services/auto-register.js";import{logger as
|
|
2
|
-
${t.slice(-_)}`:t,
|
|
1
|
+
import h from"axios";import{resolveSchedulerBaseUrlFrom as M}from"../config.js";import{requestRuntimeAccessTokenRefreshForServer as C}from"../services/auto-register.js";import{logger as p}from"../utils/logger.js";import{agentEventStore as S}from"./agent-event-store.js";import{scheduleEventPush as $}from"./event-delta-pusher.js";import{RingBuffer as P}from"./ring-buffer.js";import{getRuntimeAccessToken as A}from"./runtime-binding.js";const B=new P(2e3);function m(e,t=y(e)){const c=e?.runtimeAccessToken||A(t)||A();return c?{"X-Runtime-Token":c}:void 0}function x(e){if(e)return{schedulerBaseUrl:e.schedulerBaseUrl}}function y(e){return M(e?.schedulerBaseUrl).url}const O=100;function w(e){if(typeof e!="object"||e===null)return;const t=e.response;if(typeof t!="object"||t===null)return;const c=t.status;return typeof c=="number"?c:void 0}let L=null;async function R(e){if(L)return L;L=(async()=>{try{const t=await C(e);return t.success&&t.runtimeAccessToken?(p.info("[session-output] Runtime token refreshed after 401"),!0):(p.warn("[session-output] Runtime token refresh failed",{error:t.error}),!1)}catch(t){return p.warn("[session-output] Runtime token refresh threw",{error:t}),!1}})();try{return await L}finally{L=null}}const _=8e3,g=64*1024,v=32*1024,E=15e3,U=new Map;async function J(e,t,c,n,r,o,u,s){const i={agentId:e,sessionId:t,status:c};u!==void 0&&(i.timestamp=u),n&&(n.actionType&&(i.actionType=n.actionType),n.actionLabel&&(i.actionLabel=n.actionLabel),n.actionDetail&&(i.actionDetail=n.actionDetail),n.actionInput&&(i.actionInput=n.actionInput),n.actionResult&&(i.actionResult=n.actionResult),n.actionId&&(i.actionId=n.actionId),n.parentId&&(i.parentId=n.parentId)),r&&(i.inputTokens=r.inputTokens,i.outputTokens=r.outputTokens,r.contextLimit&&(i.contextLimit=r.contextLimit),r.maxOutput&&(i.maxOutput=r.maxOutput),r.inputLimit&&(i.inputLimit=r.inputLimit),r.compactionThreshold&&(i.compactionThreshold=r.compactionThreshold),r.cacheHitTokens&&(i.cacheHitTokens=r.cacheHitTokens),r.cacheMissTokens&&(i.cacheMissTokens=r.cacheMissTokens)),s&&(i.sourceEventType=s),process.env.ACODE_TOKEN_DEBUG==="1"&&(i.inputTokens!==void 0||i.outputTokens!==void 0||i.cacheHitTokens!==void 0||i.cacheMissTokens!==void 0)&&console.log(`[TokenDebug][SendStatus] status=${c} inputTokens=${i.inputTokens??"(none)"} outputTokens=${i.outputTokens??"(none)"} cacheHitTokens=${i.cacheHitTokens??"(none)"} cacheMissTokens=${i.cacheMissTokens??"(none)"} contextLimit=${i.contextLimit??"(none)"} actionType=${i.actionType??"(none)"}`);const a=y(o),k=m(o,a);if(!k){p.warn("Skip runtime status callback because runtime token is missing",{agentId:e,sessionId:t,status:c,schedulerBaseUrl:a});return}const f=n?.actionType==="context_compaction";f&&p.info("[compaction-diag] sendStatus enter",{agentId:e,sessionId:t,status:c,actionId:n?.actionId,parentId:n?.parentId,actionLabel:n?.actionLabel});try{const l=await h.post(`${a}/api/runtime/callback/status`,i,{headers:k,timeout:15e3});if(f){const d=l?.data;p.info("[compaction-diag] sendStatus success",{agentId:e,actionId:n?.actionId,actionLabel:n?.actionLabel,httpStatus:l?.status,ignored:d?.ignored,responseBody:d})}return l}catch(l){if(w(l)===401&&await R(a)){const T=m(x(o),a);if(T)try{const b=await h.post(`${a}/api/runtime/callback/status`,i,{headers:T,timeout:15e3});if(f){const H=b?.data;p.info("[compaction-diag] sendStatus retry success",{agentId:e,actionId:n?.actionId,actionLabel:n?.actionLabel,httpStatus:b?.status,ignored:H?.ignored})}return b}catch(b){p.warn("Runtime status callback retry failed after token refresh",{agentId:e,sessionId:t,status:c,error:b});return}}p.warn("Runtime status callback failed",{agentId:e,sessionId:t,status:c,schedulerBaseUrl:a,error:l});return}finally{const l={category:"status",agentId:e,sessionId:t,status:c,actionType:n?.actionType,actionLabel:n?.actionLabel,actionDetail:n?.actionDetail,actionInput:n?.actionInput,actionResult:n?.actionResult,actionId:n?.actionId,parentId:n?.parentId,inputTokens:r?.inputTokens,outputTokens:r?.outputTokens,cacheHitTokens:r?.cacheHitTokens,cacheMissTokens:r?.cacheMissTokens,sourceEventType:s};B.append(l);const d=S.append(e,l);$(e,d,o)}}async function D(e,t,c,n,r,o,u){const s=y(o);try{const i=m(o,s);if(!i){p.warn("Skip runtime output callback because runtime token is missing",{agentId:e,sessionId:c,schedulerBaseUrl:s});return}const a={headers:i,timeout:E};u&&(a.signal=u),await h.post(`${s}/api/runtime/callback/output`,{agentId:e,output:t,sessionId:c,seq:n,...r},a)}catch(i){if(u?.aborted||i?.name==="AbortError"||i?.code==="ERR_CANCELED")throw i;if(w(i)===401&&await R(s)){const k=m(x(o),s);if(k)try{const f={headers:k,timeout:E};u&&(f.signal=u),await h.post(`${s}/api/runtime/callback/output`,{agentId:e,output:t,sessionId:c,seq:n,...r},f);return}catch{}}throw p.warn("Runtime output callback failed",{agentId:e,sessionId:c,error:i}),i}finally{const i=t.length>_?`...(truncated)
|
|
2
|
+
${t.slice(-_)}`:t,a={category:"output",agentId:e,sessionId:c,output:i,seq:n,sourceEventType:r?.sourceEventType,logLevel:r?.logLevel,logCategory:r?.logCategory};B.appendOrMerge(a,f=>{const l=f.data;if(l.category!=="output"||l.sessionId!==c||l.sourceEventType!==r?.sourceEventType||Date.now()-f.timestamp>1e4)return!1;const d=(l.output||"").length,T=(a.output||"").length;return d+T<=_},(f,l)=>{const d=f.output||"",T=l.output||"";return d.includes(T)?f:{...f,output:`${d}${T}`}});const k=S.appendOrMergeOutput(e,a);$(e,k,o)}}async function V(e,t,c,n,r){const o=y(n),u={agentId:e,sessionId:t,questions:c,...r?{toolCallId:r}:{}};try{const s=m(n,o);if(!s)return;await h.post(`${o}/api/runtime/callback/question`,u,{headers:s})}catch(s){if(w(s)===401&&await R(o)){const a=m(x(n),o);if(a)try{await h.post(`${o}/api/runtime/callback/question`,u,{headers:a});return}catch{}}}finally{const s={category:"question",agentId:e,sessionId:t,...r?{toolCallId:r}:{},questions:c};B.append(s);const i=S.append(e,s);$(e,i,n)}}async function Y(e,t,c,n){const r=y(n),o={agentId:e,sessionId:t,...c};try{const u=m(n,r);if(!u)return;await h.post(`${r}/api/runtime/callback/tool-auth`,o,{headers:u})}catch(u){if(w(u)===401&&await R(r)){const i=m(x(n),r);if(i)try{await h.post(`${r}/api/runtime/callback/tool-auth`,o,{headers:i});return}catch{}}}}async function Z(e){const t=y();try{const c=m(void 0,t);if(!c)return;await h.post(`${t}/api/runtime/callback/file-changed`,e,{headers:c})}catch(c){if(w(c)===401&&await R(t)){const r=m(void 0,t);if(r)try{await h.post(`${t}/api/runtime/callback/file-changed`,e,{headers:r});return}catch{}}}finally{const c={category:"file_changed",agentId:"",sessionId:null,workspacePath:e.workspacePath,filePath:e.filePath,eventType:e.eventType,size:e.size};B.append(c)}}function I(e,t){const c=U.get(e);if(!c||!t)return;const n=`${c.outputBuffer}${t}`;if(n.length<=g){c.outputBuffer=n;return}const o=`\r
|
|
3
3
|
[AgentsWorkStudio: omitted ${n.length-g} chars of old terminal output]\r
|
|
4
|
-
`,
|
|
4
|
+
`,u=Math.max(0,g-o.length);c.outputBuffer=`${o}${n.slice(-u)}`}function F(e){const t=U.get(e);t&&(t.flushTimer||(t.flushTimer=setTimeout(()=>{t.flushTimer=null,q(e).catch(()=>{})},O)))}async function q(e){const t=U.get(e);if(!t||t.flushInFlight||!t.outputBuffer)return;const c=t.outputBuffer.slice(0,v);t.outputBuffer=t.outputBuffer.slice(v);const n=(async()=>{const r=t.seq+1;t.seq=r,await D(t.agentId,c,e,r),U.get(e)?.outputBuffer&&F(e)})();t.flushInFlight=n;try{await n}finally{const r=U.get(e);r&&(r.flushInFlight=null)}}export{I as appendSessionOutput,B as bridgeEventBuffer,q as flushSessionOutput,F as scheduleOutputFlush,Z as sendFileChanged,D as sendOutput,V as sendQuestionRequest,J as sendStatus,Y as sendToolAuthRequest,U as sessions};
|
|
5
5
|
|
|
@@ -30,6 +30,30 @@ export interface ACodeBuiltInToolExecutionContext {
|
|
|
30
30
|
readonly settleSignal?: Promise<void>;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
export type ToolPermissionLevel = "allow" | "ask" | "deny";
|
|
34
|
+
|
|
35
|
+
export type ToolPermissionCapability = "fileReadOutside" | "commandExecution" | "fileModification";
|
|
36
|
+
export type ToolPermissionPolicy = Record<ToolPermissionCapability, ToolPermissionLevel>;
|
|
37
|
+
|
|
38
|
+
export declare const DEFAULT_TOOL_PERMISSION_POLICY: ToolPermissionPolicy;
|
|
39
|
+
|
|
40
|
+
export interface ToolPermissionRequestDetail {
|
|
41
|
+
|
|
42
|
+
path?: string;
|
|
43
|
+
|
|
44
|
+
command?: string;
|
|
45
|
+
|
|
46
|
+
cwd?: string;
|
|
47
|
+
|
|
48
|
+
operation?: "write" | "edit" | "delete";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface ToolPermissionController {
|
|
52
|
+
getLevel(capability: ToolPermissionCapability): ToolPermissionLevel;
|
|
53
|
+
|
|
54
|
+
requestPermission(capability: ToolPermissionCapability, detail: ToolPermissionRequestDetail): Promise<boolean>;
|
|
55
|
+
}
|
|
56
|
+
|
|
33
57
|
export interface AgentFileChangeRecord {
|
|
34
58
|
filePath: string;
|
|
35
59
|
operation: 'CREATE' | 'UPDATE' | 'DELETE';
|
|
@@ -47,4 +71,4 @@ export interface ResolvedWorkspaceTarget {
|
|
|
47
71
|
export declare function ensureInsideWorkspace(workspaceRoot: string, targetPath: string): string;
|
|
48
72
|
|
|
49
73
|
export declare function resolveWorkspaceTarget(workingDirectory: string, rawFilePath: string): Promise<ResolvedWorkspaceTarget>;
|
|
50
|
-
export declare function createBuiltInFileTools(workingDirectory: string, agentId?: string, onFileChange?: OnAgentFileChange, backgroundDeps?: BackgroundToolDeps): ACodeBuiltInTool[];
|
|
74
|
+
export declare function createBuiltInFileTools(workingDirectory: string, agentId?: string, onFileChange?: OnAgentFileChange, backgroundDeps?: BackgroundToolDeps, permissionController?: ToolPermissionController): ACodeBuiltInTool[];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomUUID as
|
|
1
|
+
import{randomUUID as nt}from"node:crypto";import{promises as m,createReadStream as G}from"node:fs";import it from"node:os";import d from"node:path";import X from"node:readline";import{runShellCommand as at}from"./builtins/shellCommandRunner.js";import{createOutputEventCollector as rt}from"./builtins/commandOutputEvents.js";import{symbolsTool as st}from"./built-in-symbols-tool.js";import{createListBackgroundCommandsTool as ct,createKillBackgroundCommandTool as lt,createReadBackgroundOutputTool as ut}from"./background-command-tools.js";import{detectImageFormatFromBuffer as dt,formatBytes as T,imageMediaType as Y,readImageDimensions as pt,tryResizeWithSharp as ht}from"./image-utils.js";const ft=2e3,O=2e3,mt=50*1024,H=4096,wt=.3,gt=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".tiff",".tif",".zip",".gz",".tar",".rar",".7z",".bz2",".xz",".lz",".exe",".dll",".so",".dylib",".bin",".o",".a",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".mp3",".mp4",".avi",".mov",".wav",".flv",".mkv",".ogg",".woff",".woff2",".ttf",".otf",".eot",".class",".jar",".war",".ear",".pyc",".pyo",".node",".sqlite",".db",".mdb",".wasm"]),_t=new Set(["png","jpg","jpeg","gif","webp"]),K=20*1024*1024,L=10*1024*1024,U=Math.floor(3.75*1024*1024),C=2e3,yt=15e3,bt=1e3,kt=1024*1024,Pt=256*1024,Et=1e3,vt=new Set([".git","node_modules","dist","build",".next",".nuxt",".cache",".turbo",".output","coverage",".nyc_output"]),te={fileReadOutside:"allow",commandExecution:"allow",fileModification:"allow"};async function F(n,o,e){if(!n)return;const t=n.getLevel(o);if(t==="deny")throw new Error(`Operation blocked by tool permission policy (${o} = deny). Explain this restriction to the user if needed.`);if(t==="ask"&&!await n.requestPermission(o,e))throw new Error(`Operation denied by the user (${o}). Do not retry the same operation without asking the user.`)}function v(n){return n.replace(/\\/g,"/")}async function V(n){try{return await m.access(n),!0}catch{return!1}}function xt(n,o){if(!o)return 0;let e=0,t=n.indexOf(o);for(;t>=0;)e+=1,t=n.indexOf(o,t+o.length);return e}function $(n,o,e){for(const t of o){const i=n[t];if(typeof i=="string")return i}throw new Error(`${e} is required`)}function I(n,o){for(const e of o){const t=n[e];if(typeof t=="string"&&t.trim())return t}}function B(n,o,e){for(const t of o){const i=n[t],s=typeof i=="number"?i:typeof i=="string"?Number(i):NaN;if(Number.isFinite(s)&&s>0)return Math.floor(s)}return e}async function Z(n){const o=d.extname(n).toLowerCase();if(gt.has(o))return!0;const e=await m.open(n,"r");try{const t=Buffer.alloc(H),{bytesRead:i}=await e.read(t,0,H,0);if(i===0)return!1;const s=t.subarray(0,i);if(s.includes(0))return!0;let r=0;for(let a=0;a<i;a++){const c=s[a];(c<9||c>13&&c<32)&&r++}return r/i>wt}finally{await e.close()}}function M(n,o){const e=d.resolve(o),t=d.relative(n,e);if(t.startsWith("..")||d.isAbsolute(t))throw new Error(`Target path is outside workspace: ${e}`);return e}function D(n){return n==="~"||n.startsWith("~/")?d.join(it.homedir(),n.slice(1)):n}async function Tt(n,o){const e=d.resolve(String(n||"").trim()),t=await m.realpath(e);if(!(await m.stat(t)).isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);if(!o?.trim())return{workspaceRoot:t,cwd:t};const s=D(o.trim()),r=d.isAbsolute(s)?d.resolve(s):d.resolve(e,s),a=d.relative(e,r);if(a.startsWith("..")||d.isAbsolute(a))throw new Error(`Command cwd is outside workspace: ${r}`);const c=M(t,await m.realpath(r));if(!(await m.stat(c)).isDirectory())throw new Error(`Command cwd is not a directory: ${c}`);return{workspaceRoot:t,cwd:c}}async function Rt(n,o){const e=await m.realpath(d.dirname(o));M(n,e);try{if((await m.lstat(o)).isSymbolicLink())throw new Error(`Refusing to write through symbolic link: ${o}`)}catch(t){if((typeof t=="object"&&t!==null?Reflect.get(t,"code"):void 0)!=="ENOENT")throw t}}async function A(n,o){const e=d.resolve(String(n||"").trim()),t=await m.realpath(e);if(!(await m.stat(t)).isDirectory())throw new Error(`Workspace path is not a directory: ${e}`);const s=D(o.trim());if(!s)throw new Error("file_path is required");const r=d.isAbsolute(s)?d.resolve(s):d.resolve(e,s),a=d.relative(e,r);if(a.startsWith("..")||d.isAbsolute(a))throw new Error(`Target path is outside workspace: ${r}`);return{workspaceRoot:t,requestedPath:r,targetPath:M(t,d.join(t,a))}}async function J(n,o,e){const t=d.resolve(String(n||"").trim()),i=await m.realpath(t);if(!(await m.stat(i)).isDirectory())throw new Error(`Workspace path is not a directory: ${t}`);const r=D(o.trim());if(!r)throw new Error("file_path is required");const a=d.isAbsolute(r)?d.resolve(r):d.resolve(t,r),c=d.relative(t,a),u=await m.realpath(a).catch(()=>a),l=d.relative(i,u);if(c.startsWith("..")||d.isAbsolute(c)||l.startsWith("..")||d.isAbsolute(l)){if(!e)throw new Error(`Target path is outside workspace: ${a}`);return await F(e,"fileReadOutside",{path:a}),{workspaceRoot:i,requestedPath:a,targetPath:u}}return{workspaceRoot:i,requestedPath:a,targetPath:M(i,u)}}async function Q(n,o,e){const t=await A(n,o),i=d.dirname(t.targetPath),s=!await V(i);await m.mkdir(i,{recursive:!0}),await Rt(t.workspaceRoot,t.targetPath);const r=d.join(i,`.${d.basename(t.targetPath)}.${process.pid}.${nt()}.tmp`);try{await m.writeFile(r,e,"utf-8"),await m.rename(r,t.targetPath)}catch(a){throw await m.rm(r,{force:!0}),a}return{workspaceRoot:t.workspaceRoot,targetPath:t.targetPath,bytes:Buffer.byteLength(e,"utf-8"),createdParentDirectory:s}}async function $t(n,o){const e=await A(n,o),t=M(e.workspaceRoot,await m.realpath(e.targetPath));if(!(await m.stat(t)).isFile())throw new Error(`Path is not a file: ${t}`);return{workspaceRoot:e.workspaceRoot,targetPath:t,content:await m.readFile(t,"utf-8")}}async function St(n,o,e,t,i){const s=await J(n,o,i),r=s.targetPath;if(!(await m.stat(r)).isFile())throw new Error(`Path is not a file: ${r}`);if(await Z(r))return{workspaceRoot:s.workspaceRoot,targetPath:r,content:"[Binary file, content skipped]",isBinary:!0,truncated:!1,totalLines:0,shownFromLine:0,shownToLine:0};const c=G(r,{encoding:"utf-8"}),u=X.createInterface({input:c,crlfDelay:1/0});try{const l=[];let w=0,h=0,g=0,p=!1,P=!1;const f=e-1;for await(const _ of u){if(h++,w<f){w++;continue}if(l.length>=t){p=!0,w++;continue}let R=_;R.length>O&&(R=R.slice(0,O)+`... (line truncated to ${O} chars)`);const S=`${w+1}: ${R}`,x=Buffer.byteLength(S,"utf-8")+1;if(g+x>mt){P=!0;break}l.push(S),g+=x,w++}if(h>0&&l.length===0&&!p&&!P&&f>=h)throw new Error(`offset ${e} exceeds total line count ${h} in file: ${r}`);const y=l.length>0?e:0,E=l.length>0?e+l.length-1:0;let b;P?b=`Output capped at 50 KB. Showing lines ${y}-${E}. Use offset=${E+1} to continue.`:p?b=`Showing lines ${y}-${E} of ${h}. Use offset=${E+1} to continue.`:b=`End of file - total ${h} lines`;const k=l.length>0?l.join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`+P:P;return{workspaceRoot:a.workspaceRoot,targetPath:i,content:E,isBinary:!1,truncated:y||u,totalLines:u?-1:m,shownFromLine:_,shownToLine:g}}finally{s.close(),r.destroy()}}function X(n){let o="",e=0;for(;e<n.length;){const t=n[e];if(t==="*")o+="[^/]*";else if(t==="?")o+="[^/]";else if(t==="{"){const a=n.indexOf("}",e);if(a>=0){const i=n.slice(e+1,a);o+=`(${i.split(",").join("|")})`,e=a}else o+="\\{"}else if(t==="["){const a=n.indexOf("]",e);a>=0?(o+=n.slice(e,a+1),e=a):o+="\\["}else"+^$.()|\\".includes(t)?o+="\\"+t:o+=t;e++}return new RegExp(`^${o}$`)}async function wt(n,o,e,t){const a=[];async function i(c){if(a.length>=t)return;const r=await d.readdir(c,{withFileTypes:!0});for(const s of r){if(a.length>=t)return;if(s.name.startsWith(".")&&s.isDirectory())continue;const l=p.join(c,s.name);if(s.isDirectory()){if(ut.has(s.name))continue;await i(l)}else if(s.isFile()){if(o&&!o.test(s.name)||e&&e.test(s.name))continue;a.push(l)}}}return await i(n),a}async function gt(n,o,e){if((await d.stat(n)).size>st)return{matches:[],count:0};if(await j(n))return{matches:[],count:0};const a=p.relative(o,n).replace(/\\/g,"/"),i=[];let c=0;const r=N(n,{encoding:"utf-8"}),s=U.createInterface({input:r,crlfDelay:1/0});try{let l=0;for await(const h of s)if(l++,e.regex.test(h)){if(c++,e.collectContent){let m=h;if(m.length>F&&(m=m.slice(0,F)+`... (line truncated to ${F} chars)`),i.push({file:a,line:l,content:m}),i.length>=e.maxResults)break}if(e.stopOnFirstMatch)break}}finally{s.close(),r.destroy()}return{matches:i,count:c}}const z=10*6e4,_t=z,yt=6e4,bt=10*6e4;function kt(n,o){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",description:"Create or overwrite a UTF-8 text file inside the current workspace. Parent directories are created automatically.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to write."},content:{type:"string",description:"Complete UTF-8 file content."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","content"],additionalProperties:!1},async execute(e){const t=T(e,["file_path","filePath"],"file_path"),a=T(e,["content"],"content"),i=O(e,["reason"]),c=await C(n,t),r=await W(c.targetPath),s=r?await d.readFile(c.targetPath,"utf-8").catch(()=>null):null,l=await G(n,t,a);if(o){const h=p.relative(l.workspaceRoot,l.targetPath).replace(/\\/g,"/");await o({filePath:h,operation:r?"UPDATE":"CREATE",beforeContent:s,afterContent:a,reason:i})}return{ok:!0,tool:"write_file",workspacePath:v(l.workspaceRoot),filePath:v(l.targetPath),bytes:l.bytes,createdParentDirectory:l.createdParentDirectory}}}}function Pt(n,o){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",description:"Replace exactly one occurrence of old_string with new_string in a UTF-8 workspace text file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to edit."},old_string:{type:"string",description:"Existing text to replace. Must occur exactly once."},new_string:{type:"string",description:"Replacement text."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","old_string","new_string"],additionalProperties:!1},async execute(e){const t=T(e,["file_path","filePath"],"file_path"),a=T(e,["old_string","oldString"],"old_string"),i=T(e,["new_string","newString"],"new_string"),c=O(e,["reason"]);if(!a)throw new Error("old_string must not be empty");const r=await ft(n,t),s=dt(r.content,a);if(s===0)throw new Error("old_string was not found in file");if(s>1)throw new Error(`old_string occurs ${s} times; provide a unique match`);const l=r.content.replace(a,i),h=await G(n,t,l);if(o){const m=p.relative(h.workspaceRoot,h.targetPath).replace(/\\/g,"/");await o({filePath:m,operation:"UPDATE",beforeContent:r.content,afterContent:l,reason:c})}return{ok:!0,tool:"edit_file",workspacePath:v(h.workspaceRoot),filePath:v(h.targetPath),replacements:1,bytes:h.bytes}}}}function xt(n,o){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",description:"Delete a file inside the current workspace. Returns an error if the file does not exist.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to delete."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path"],additionalProperties:!1},async execute(e){const t=T(e,["file_path","filePath"],"file_path"),a=O(e,["reason"]),i=await C(n,t),c=M(i.workspaceRoot,await d.realpath(i.targetPath).catch(()=>i.targetPath)),r=await d.stat(c).catch(()=>null);if(!r)throw new Error(`File does not exist: ${c}`);if(!r.isFile())throw new Error(`Path is not a file: ${c}`);const s=await d.readFile(c,"utf-8").catch(()=>null);if(await d.rm(c,{force:!0}),o){const l=p.relative(i.workspaceRoot,c).replace(/\\/g,"/");await o({filePath:l,operation:"DELETE",beforeContent:s,afterContent:null,reason:a})}return{ok:!0,tool:"delete_file",workspacePath:v(i.workspaceRoot),filePath:v(c),deleted:!0}}}}function vt(n){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",description:"Read a UTF-8 text file inside the current workspace. Returns content with line numbers in the format '<line>: <content>'. Supports offset (1-indexed line number to start from) and limit (max lines to return, default 2000). Output is capped at 2000 lines or 50 KB, whichever is reached first. Individual lines longer than 2000 characters are truncated. Avoid tiny repeated slices (e.g. 30-line chunks); read a larger window if more context is needed.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to read."},offset:{type:"number",description:"Line number to start reading from (1-indexed). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to return. Defaults to 2000."}},required:["file_path"],additionalProperties:!1},async execute(o){const e=T(o,["file_path","filePath"],"file_path"),t=I(o,["offset"],1),a=I(o,["limit"],ot),i=await ht(n,e,t,a);return{ok:!0,tool:"read_file",workspacePath:v(i.workspaceRoot),filePath:v(i.targetPath),content:i.content,isBinary:i.isBinary,truncated:i.truncated,totalLines:i.totalLines,shownFromLine:i.shownFromLine,shownToLine:i.shownToLine}}}}function Tt(n,o,e){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded timeout and returns stdout, stderr, exit code, and (if interrupted) partial output. By default (wait_seconds omitted or -1) the command runs in the FOREGROUND and streams output in real time; if the 5-minute adapter watchdog fires while it is still running, the command is interrupted and the partial output produced so far is returned (large output is spilled to a file via outputFilePath to avoid context overflow), with watchdogInterrupted=true. For long-running commands use wait_seconds=0 or n>0 to run in the BACKGROUND, then manage them via list_background_commands / read_background_output / kill_background_command / await_complete.",inputSchema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute."},cwd:{type:"string",description:"Optional workspace-relative working directory. Defaults to the workspace root."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds. Defaults to 600000 and is capped at 600000."},inactivity_timeout_ms:{type:"number",description:"Optional no-output timeout in milliseconds. Defaults to 60000 and is capped at 600000."},wait_seconds:{type:"number",description:"How to wait for the command to finish. Omitted values (or -1, the default): run in the FOREGROUND until completion; if the 5-minute adapter watchdog fires first, the command is interrupted and only the partial output already produced is returned (watchdogInterrupted=true; large output spills to outputFilePath). 0: spawn and immediately execute in the background, return task_id. n>0: wait up to n seconds; if still running, move to the background and return task_id. Background commands remain subject to timeout_ms (total upper bound); inactivity_timeout_ms is ignored once backgrounded.",minimum:-1},description:{type:"string",description:"Optional short reason for running the command."}},required:["command"],additionalProperties:!1},async execute(t,a){const i=T(t,["command"],"command").trim();if(!i)throw new Error("command must not be empty");const c=I(t,["timeout_ms","timeoutMs"],_t),r=Math.min(c,z),s=I(t,["inactivity_timeout_ms","inactivityTimeoutMs"],yt),l=Math.min(s,bt),h=O(t,["cwd"]),m=await pt(n,h),b=t.wait_seconds,u=typeof b=="number"&&Number.isFinite(b)?b:-1;if(u!==-1&&e)return await Rt({deps:e,command:i,agentId:o,workspaceRoot:m.workspaceRoot,cwd:m.cwd,timeoutMs:r,inactivityTimeoutMs:l,waitSeconds:u,onOutput:a?.onOutput,settleSignal:a?.settleSignal});const f=await V({commandText:i,agentId:o,workspaceRoot:m.workspaceRoot,cwd:m.cwd,timeoutMs:r,inactivityTimeoutMs:l,onOutput:a?.onOutput,watchdogSignal:a?.settleSignal}),_={ok:f.exitCode===0&&!f.timedOut,tool:"Bash",command:i,cwd:v(m.cwd),exitCode:f.exitCode,signal:f.signal,timedOut:f.timedOut,inactivityTimedOut:f.inactivityTimedOut,watchdogInterrupted:f.watchdogInterrupted,timeoutMs:r,inactivityTimeoutMs:l,durationMs:f.durationMs,outputSpilled:f.outputSpilled,outputFilePath:f.outputFilePath,outputLineCount:f.outputLineCount,commandFilePath:f.commandFilePath,commandLineCount:f.commandLineCount,stdout:f.stdout,stderr:f.stderr};return f.watchdogInterrupted?{..._,message:"Command was interrupted by the adapter watchdog after ~5 minutes of synchronous (foreground) execution. Only the partial output produced so far is returned above"+(f.outputFilePath?` (full output spilled to "${f.outputFilePath}"; read it if you need more)`:"")+". For long-running commands, re-run with wait_seconds=0 (or n>0) to execute in the background, then manage via await_complete / list_background_commands / read_background_output / kill_background_command."}:_}}}async function Rt(n){const{deps:o,command:e,agentId:t,workspaceRoot:a,cwd:i,timeoutMs:c,inactivityTimeoutMs:r,waitSeconds:s,onOutput:l,settleSignal:h}=n,m=l?Z({cwd:i,commandLineCount:0,onOutput:l}):void 0;let b=!!m;const y=()=>{b&&(b=!1,m?.close())};try{const{taskId:u,completion:f}=o.manager.startCommand({commandText:e,agentId:t,workspaceRoot:a,cwd:i,timeoutMs:c,inactivityTimeoutMs:r,onOutput:b?k=>{b&&m?.push(k.stream,k.text)}:void 0,onCompleted:o.emitCompleted});if(s===0)return o.manager.disableInactivityTimeout(t,u),y(),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:u,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use await_complete(bg_cmd_ids=["${u}"]) to block until it finishes, read_background_output(task_id="${u}", mode="tail") to read output, list_background_commands to view all, or kill_background_command(task_id="${u}") to stop.`};const _=s===-1?0:Math.max(0,Math.floor(s*1e3));let g,P;s===-1?P=Promise.resolve("__never__"):P=new Promise(k=>{g=setTimeout(()=>k("__timeout__"),_),g.unref?.()});const E=h?h.then(()=>"__settle__"):Promise.resolve("__never__");try{const k=await Promise.race([f,P,E]);if(k==="__settle__")return o.manager.disableInactivityTimeout(t,u),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:u,status:"backgrounded",reason:"watchdog_timeout",waitedMs:_,message:`Command still running after watchdog timeout; moved to background. Use await_complete(bg_cmd_ids=["${u}"]) to block until it finishes, read_background_output(task_id="${u}", mode="tail") to read output, or kill_background_command(task_id="${u}") to stop.`};if(k==="__timeout__")return o.manager.disableInactivityTimeout(t,u),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:u,status:"backgrounded",reason:"timeout",waitedMs:_,message:`Command still running after ${s}s; moved to background. Use await_complete(bg_cmd_ids=["${u}"]) to block until it finishes, or read_background_output(task_id="${u}", mode="tail") / kill_background_command(task_id="${u}") to inspect.`};const w=k;return{ok:w.exitCode===0&&!w.timedOut,tool:"Bash",command:e,backgrounded:!1,taskId:u,exitCode:w.exitCode,signal:w.signal,timedOut:w.timedOut,inactivityTimedOut:w.inactivityTimedOut,timeoutMs:w.timeoutMs,inactivityTimeoutMs:w.inactivityTimeoutMs,durationMs:w.durationMs,outputSpilled:w.outputSpilled,outputFilePath:w.outputFilePath,outputLineCount:w.outputLineCount,commandFilePath:w.commandFilePath,commandLineCount:w.commandLineCount,stdout:w.stdout,stderr:w.stderr}}finally{g&&clearTimeout(g),y()}}catch(u){if(u?.code==="too_many_tasks"||u?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:e,backgrounded:!1,status:"not_executed",error:u.code,message:`Command was NOT executed: ${u.message}. Wait for some background tasks to finish/cleanup (per-agent limit 16, global 256), or reduce concurrent background commands, then retry.`};throw u}}function Et(n){return{kind:"builtin",toolName:"grep",exposedName:"grep",description:"Search file contents using regular expressions within the workspace. Returns matched lines with file paths and line numbers. Supports include/exclude glob patterns, case-insensitive matching, and three output modes (content, files_with_matches, count). Searches recursively through directories, skipping binary files, hidden directories, and common build/dependency directories (node_modules, .git, dist, etc.).",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Regular expression pattern to search for in file contents."},path:{type:"string",description:"Workspace-relative file or directory path to search in. Defaults to the workspace root."},include:{type:"string",description:"Glob pattern to filter files by name (e.g. '*.ts', '*.{js,ts}'). Only matching files are searched."},exclude:{type:"string",description:"Glob pattern to exclude files by name (e.g. '*.test.ts'). Matching files are skipped."},case_insensitive:{type:"boolean",description:"Case-insensitive matching. Default false."},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output format: 'content' returns matched lines with line numbers (default), 'files_with_matches' returns only file paths with matches, 'count' returns match counts per file."},max_results:{type:"number",description:"Maximum number of matched lines to return (content mode). Default 1000."}},required:["pattern"],additionalProperties:!1},async execute(o){const e=T(o,["pattern"],"pattern"),t=O(o,["path"])||".",a=O(o,["include"]),i=O(o,["exclude"]),c=o.case_insensitive===!0,r=(()=>{const x=o.output_mode;return x==="files_with_matches"||x==="count"?x:"content"})(),s=I(o,["max_results"],lt),l=c?"i":"";let h;try{h=new RegExp(e,l)}catch(x){throw new Error(`Invalid regex pattern: ${x instanceof Error?x.message:String(x)}`)}const m=a?X(a):null,b=i?X(i):null,y=await C(n,t),u=M(y.workspaceRoot,await d.realpath(y.targetPath)),f=await d.stat(u);let _;if(f.isFile())_=[u];else if(f.isDirectory())_=await wt(u,m,b,rt);else throw new Error(`Path is neither a file nor a directory: ${u}`);const g=[],P=[],E=[];let k=0,w=0,R=!1;for(const x of _){if(r==="content"&&g.length>=s){R=!0;break}const Y={regex:h,maxResults:r==="content"?s-g.length:Number.MAX_SAFE_INTEGER,collectContent:r==="content",stopOnFirstMatch:r==="files_with_matches"},$=await gt(x,y.workspaceRoot,Y);if($.count>0){const L=p.relative(y.workspaceRoot,x).replace(/\\/g,"/");if(E.push(L),k+=$.count,r==="content"){for(const A of $.matches){const B=Buffer.byteLength(A.content,"utf-8")+64;if(w+B>ct){R=!0;break}w+=B,g.push(A)}if(R)break;if(g.length>=s){R=!0;break}}else r==="count"&&P.push({file:L,count:$.count})}}const S={ok:!0,tool:"grep",pattern:e,searchPath:v(y.targetPath),outputMode:r,filesSearched:_.length,filesMatched:E.length,totalMatches:k,truncated:R};return r==="content"?S.matches=g:r==="files_with_matches"?S.matches=E:S.matches=P,S}}}function Bt(n,o,e,t){const a=o||"unknown",i=[vt(n),kt(n,e),Pt(n,e),xt(n,e),Et(n),Tt(n,a,t),J(n)];return t&&i.push(Q(a,t),tt(a,t),et(a,t)),i}export{Bt as createBuiltInFileTools,M as ensureInsideWorkspace,C as resolveWorkspaceTarget};
|
|
3
|
+
`+b:b;return{workspaceRoot:s.workspaceRoot,targetPath:r,content:k,isBinary:!1,truncated:p||P,totalLines:P?-1:h,shownFromLine:y,shownToLine:E}}finally{u.close(),c.destroy()}}function W(n){return/^https?:\/\//i.test(n)}async function It(n){let o;try{o=new URL(n)}catch{throw new Error(`Invalid image URL: ${n}`)}if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error(`Unsupported image URL protocol: ${o.protocol} (only http/https)`);let e;try{e=await fetch(n,{signal:AbortSignal.timeout(yt)})}catch(u){const l=u instanceof Error?u.message:String(u);throw new Error(`Image URL fetch failed: ${n} (${l})`)}if(!e.ok)throw new Error(`Image URL fetch failed: ${n} (HTTP ${e.status})`);const t=(e.headers.get("content-type")||"").split(";")[0]?.trim().toLowerCase()||"";if(t&&!t.startsWith("image/"))throw new Error(`URL did not return an image (content-type: ${t}): ${n}`);const i=Number(e.headers.get("content-length")||"");if(Number.isFinite(i)&&i>L)throw new Error(`Image too large to fetch: ${n} (${T(i)} > ${T(L)})`);const s=e.body;if(!s){const u=await e.arrayBuffer();if(u.byteLength>L)throw new Error(`Image too large to fetch: ${n} (${T(u.byteLength)} > ${T(L)})`);return Buffer.from(u)}const r=s.getReader(),a=[];let c=0;for(;;){const{done:u,value:l}=await r.read();if(u)break;if(l){if(c+=l.byteLength,c>L)throw r.cancel().catch(()=>{}),new Error(`Image too large to fetch: ${n} (${T(c)} > ${T(L)})`);a.push(Buffer.from(l))}}return Buffer.concat(a,c)}async function Mt(n,o,e){let t,i,s;if(W(o))t=await It(o),i=o;else{const E=await J(n,o,e),b=E.targetPath,k=await m.stat(b);if(!k.isFile())throw new Error(`Path is not a file: ${b}`);if(k.size>K)throw new Error(`Image file too large to read: ${v(b)} (${T(k.size)} > ${T(K)}). Downscale it first.`);t=await m.readFile(b),i=v(b),s=v(E.workspaceRoot)}if(t.length===0)throw new Error(`Image file is empty: ${i}`);const r=dt(t);if(!r)throw new Error(`Unsupported or corrupt image (unrecognized format): ${i}`);const a=pt(t);let c=r,u=t,l=a?.width,w=a?.height,h=!1;const g=await ht(t,r,{maxWidth:C,maxHeight:C,maxBytes:U});if(g)u=g.buffer,c=g.mediaType,l=g.width,w=g.height,h=g.changed;else if(t.length>U)throw new Error(`Image too large to inline: ${i} (${T(t.length)} > ${T(U)}). Downscale it first, e.g. via Bash: magick "${o}" -resize ${C}x${C} "${o}". Installing sharp enables automatic downscaling.`);const p=l&&w?`${l}x${w}`:"unknown dimensions",P=h&&a&&a.width!==l?` (resized from ${a.width}x${a.height})`:h?" (resized)":"",f=`[Image: ${i}, ${p}${P}, ${T(u.length)}]`,y=W(o)?d.basename(new URL(o).pathname)||"image":d.basename(i);return{ok:!0,tool:"read_file",...s!==void 0?{workspacePath:s}:{},filePath:i,content:f,isBinary:!1,image:{mediaType:Y(c),width:l??null,height:w??null,originalWidth:a?.width??null,originalHeight:a?.height??null,resized:h,size:u.length},attachments:[{type:"image",name:y,mediaType:Y(c),base64Data:u.toString("base64")}]}}function tt(n){let o="",e=0;for(;e<n.length;){const t=n[e];if(t==="*")o+="[^/]*";else if(t==="?")o+="[^/]";else if(t==="{"){const i=n.indexOf("}",e);if(i>=0){const s=n.slice(e+1,i);o+=`(${s.split(",").join("|")})`,e=i}else o+="\\{"}else if(t==="["){const i=n.indexOf("]",e);i>=0?(o+=n.slice(e,i+1),e=i):o+="\\["}else"+^$.()|\\".includes(t)?o+="\\"+t:o+=t;e++}return new RegExp(`^${o}$`)}async function Ot(n,o,e,t){const i=[];async function s(r){if(i.length>=t)return;const a=await m.readdir(r,{withFileTypes:!0});for(const c of a){if(i.length>=t)return;if(c.name.startsWith(".")&&c.isDirectory())continue;const u=d.join(r,c.name);if(c.isDirectory()){if(vt.has(c.name))continue;await s(u)}else if(c.isFile()){if(o&&!o.test(c.name)||e&&e.test(c.name))continue;i.push(u)}}}return await s(n),i}async function Lt(n,o,e){if((await m.stat(n)).size>kt)return{matches:[],count:0};if(await Z(n))return{matches:[],count:0};const i=d.relative(o,n).replace(/\\/g,"/"),s=[];let r=0;const a=G(n,{encoding:"utf-8"}),c=X.createInterface({input:a,crlfDelay:1/0});try{let u=0;for await(const l of c)if(u++,e.regex.test(l)){if(r++,e.collectContent){let w=l;if(w.length>O&&(w=w.slice(0,O)+`... (line truncated to ${O} chars)`),s.push({file:i,line:u,content:w}),s.length>=e.maxResults)break}if(e.stopOnFirstMatch)break}}finally{c.close(),a.destroy()}return{matches:s,count:r}}const et=10*6e4,At=et,Ft=6e4,Bt=10*6e4;function Nt(n,o,e){return{kind:"builtin",toolName:"write_file",exposedName:"write_file",description:"Create or overwrite a UTF-8 text file inside the current workspace. Parent directories are created automatically.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to write."},content:{type:"string",description:"Complete UTF-8 file content."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","content"],additionalProperties:!1},async execute(t){const i=$(t,["file_path","filePath"],"file_path"),s=$(t,["content"],"content"),r=I(t,["reason"]),a=await A(n,i);await F(e,"fileModification",{operation:"write",path:a.targetPath});const c=await V(a.targetPath),u=c?await m.readFile(a.targetPath,"utf-8").catch(()=>null):null,l=await Q(n,i,s);if(o){const w=d.relative(l.workspaceRoot,l.targetPath).replace(/\\/g,"/");await o({filePath:w,operation:c?"UPDATE":"CREATE",beforeContent:u,afterContent:s,reason:r})}return{ok:!0,tool:"write_file",workspacePath:v(l.workspaceRoot),filePath:v(l.targetPath),bytes:l.bytes,createdParentDirectory:l.createdParentDirectory}}}}function Ct(n,o,e){return{kind:"builtin",toolName:"edit_file",exposedName:"edit_file",description:"Replace exactly one occurrence of old_string with new_string in a UTF-8 workspace text file.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to edit."},old_string:{type:"string",description:"Existing text to replace. Must occur exactly once."},new_string:{type:"string",description:"Replacement text."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path","old_string","new_string"],additionalProperties:!1},async execute(t){const i=$(t,["file_path","filePath"],"file_path"),s=$(t,["old_string","oldString"],"old_string"),r=$(t,["new_string","newString"],"new_string"),a=I(t,["reason"]);if(!s)throw new Error("old_string must not be empty");const c=await A(n,i);await F(e,"fileModification",{operation:"edit",path:c.targetPath});const u=await $t(n,i),l=xt(u.content,s);if(l===0)throw new Error("old_string was not found in file");if(l>1)throw new Error(`old_string occurs ${l} times; provide a unique match`);const w=u.content.replace(s,r),h=await Q(n,i,w);if(o){const g=d.relative(h.workspaceRoot,h.targetPath).replace(/\\/g,"/");await o({filePath:g,operation:"UPDATE",beforeContent:u.content,afterContent:w,reason:a})}return{ok:!0,tool:"edit_file",workspacePath:v(h.workspaceRoot),filePath:v(h.targetPath),replacements:1,bytes:h.bytes}}}}function Ut(n,o,e){return{kind:"builtin",toolName:"delete_file",exposedName:"delete_file",description:"Delete a file inside the current workspace. Returns an error if the file does not exist.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to delete."},reason:{type:"string",description:"Optional reason for this change, e.g. what bug is being fixed. Helps humans understand the change later."}},required:["file_path"],additionalProperties:!1},async execute(t){const i=$(t,["file_path","filePath"],"file_path"),s=I(t,["reason"]),r=await A(n,i);await F(e,"fileModification",{operation:"delete",path:r.targetPath});const a=M(r.workspaceRoot,await m.realpath(r.targetPath).catch(()=>r.targetPath)),c=await m.stat(a).catch(()=>null);if(!c)throw new Error(`File does not exist: ${a}`);if(!c.isFile())throw new Error(`Path is not a file: ${a}`);const u=await m.readFile(a,"utf-8").catch(()=>null);if(await m.rm(a,{force:!0}),o){const l=d.relative(r.workspaceRoot,a).replace(/\\/g,"/");await o({filePath:l,operation:"DELETE",beforeContent:u,afterContent:null,reason:s})}return{ok:!0,tool:"delete_file",workspacePath:v(r.workspaceRoot),filePath:v(a),deleted:!0}}}}function Dt(n,o){return{kind:"builtin",toolName:"read_file",exposedName:"read_file",description:"Read a UTF-8 text file inside the current workspace. Returns content with line numbers in the format '<line>: <content>'. Supports offset (1-indexed line number to start from) and limit (max lines to return, default 2000). Output is capped at 2000 lines or 50 KB, whichever is reached first. Individual lines longer than 2000 characters are truncated. Avoid tiny repeated slices (e.g. 30-line chunks); read a larger window if more context is needed. Images (.png/.jpg/.jpeg/.gif/.webp) and http(s) image URLs are also supported: the image is inlined into the conversation so you can see it (requires a model with image input). offset/limit are ignored for images; oversized images are automatically downscaled when sharp is available.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Workspace-relative file path to read. Also accepts an http(s) URL pointing to an image."},offset:{type:"number",description:"Line number to start reading from (1-indexed). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to return. Defaults to 2000."}},required:["file_path"],additionalProperties:!1},async execute(e){const t=$(e,["file_path","filePath"],"file_path"),i=d.extname(t).toLowerCase().slice(1);if(W(t)||_t.has(i))return await Mt(n,t,o);const s=B(e,["offset"],1),r=B(e,["limit"],ft),a=await St(n,t,s,r,o);return{ok:!0,tool:"read_file",workspacePath:v(a.workspaceRoot),filePath:v(a.targetPath),content:a.content,isBinary:a.isBinary,truncated:a.truncated,totalLines:a.totalLines,shownFromLine:a.shownFromLine,shownToLine:a.shownToLine}}}}function Wt(n,o,e,t){return{kind:"builtin",toolName:"Bash",exposedName:"Bash",description:"Execute a shell command in the current workspace. Use for local diagnostics, builds, tests, and OS commands. The command runs with a bounded timeout and returns stdout, stderr, exit code, and (if interrupted) partial output. By default (wait_seconds omitted or -1) the command runs in the FOREGROUND and streams output in real time; if the 5-minute adapter watchdog fires while it is still running, the command is interrupted and the partial output produced so far is returned (large output is spilled to a file via outputFilePath to avoid context overflow), with watchdogInterrupted=true. For long-running commands use wait_seconds=0 or n>0 to run in the BACKGROUND, then manage them via list_background_commands / read_background_output / kill_background_command / await_complete.",inputSchema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute."},cwd:{type:"string",description:"Optional workspace-relative working directory. Defaults to the workspace root."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds. Defaults to 600000 and is capped at 600000."},inactivity_timeout_ms:{type:"number",description:"Optional no-output timeout in milliseconds. Defaults to 60000 and is capped at 600000."},wait_seconds:{type:"number",description:"How to wait for the command to finish. Omitted values (or -1, the default): run in the FOREGROUND until completion; if the 5-minute adapter watchdog fires first, the command is interrupted and only the partial output already produced is returned (watchdogInterrupted=true; large output spills to outputFilePath). 0: spawn and immediately execute in the background, return task_id. n>0: wait up to n seconds; if still running, move to the background and return task_id. Background commands remain subject to timeout_ms (total upper bound); inactivity_timeout_ms is ignored once backgrounded.",minimum:-1},description:{type:"string",description:"Optional short reason for running the command."}},required:["command"],additionalProperties:!1},async execute(i,s){const r=$(i,["command"],"command").trim();if(!r)throw new Error("command must not be empty");const a=B(i,["timeout_ms","timeoutMs"],At),c=Math.min(a,et),u=B(i,["inactivity_timeout_ms","inactivityTimeoutMs"],Ft),l=Math.min(u,Bt),w=I(i,["cwd"]),h=await Tt(n,w);await F(t,"commandExecution",{command:r,cwd:v(h.cwd)});const g=i.wait_seconds,P=typeof g=="number"&&Number.isFinite(g)?g:-1;if(P!==-1&&e)return await qt({deps:e,command:r,agentId:o,workspaceRoot:h.workspaceRoot,cwd:h.cwd,timeoutMs:c,inactivityTimeoutMs:l,waitSeconds:P,onOutput:s?.onOutput,settleSignal:s?.settleSignal});const f=await at({commandText:r,agentId:o,workspaceRoot:h.workspaceRoot,cwd:h.cwd,timeoutMs:c,inactivityTimeoutMs:l,onOutput:s?.onOutput,watchdogSignal:s?.settleSignal}),y={ok:f.exitCode===0&&!f.timedOut,tool:"Bash",command:r,cwd:v(h.cwd),exitCode:f.exitCode,signal:f.signal,timedOut:f.timedOut,inactivityTimedOut:f.inactivityTimedOut,watchdogInterrupted:f.watchdogInterrupted,timeoutMs:c,inactivityTimeoutMs:l,durationMs:f.durationMs,outputSpilled:f.outputSpilled,outputFilePath:f.outputFilePath,outputLineCount:f.outputLineCount,commandFilePath:f.commandFilePath,commandLineCount:f.commandLineCount,stdout:f.stdout,stderr:f.stderr};return f.watchdogInterrupted?{...y,message:"Command was interrupted by the adapter watchdog after ~5 minutes of synchronous (foreground) execution. Only the partial output produced so far is returned above"+(f.outputFilePath?` (full output spilled to "${f.outputFilePath}"; read it if you need more)`:"")+". For long-running commands, re-run with wait_seconds=0 (or n>0) to execute in the background, then manage via await_complete / list_background_commands / read_background_output / kill_background_command."}:y}}}async function qt(n){const{deps:o,command:e,agentId:t,workspaceRoot:i,cwd:s,timeoutMs:r,inactivityTimeoutMs:a,waitSeconds:c,onOutput:u,settleSignal:l}=n,w=u?rt({cwd:s,commandLineCount:0,onOutput:u}):void 0;let h=!!w;const g=()=>{h&&(h=!1,w?.close())};try{const{taskId:p,completion:P}=o.manager.startCommand({commandText:e,agentId:t,workspaceRoot:i,cwd:s,timeoutMs:r,inactivityTimeoutMs:a,onOutput:h?k=>{h&&w?.push(k.stream,k.text)}:void 0,onCompleted:o.emitCompleted});if(c===0)return o.manager.disableInactivityTimeout(t,p),g(),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:p,status:"backgrounded",reason:"immediate",message:`Command moved to background. Use await_complete(bg_cmd_ids=["${p}"]) to block until it finishes, read_background_output(task_id="${p}", mode="tail") to read output, list_background_commands to view all, or kill_background_command(task_id="${p}") to stop.`};const f=c===-1?0:Math.max(0,Math.floor(c*1e3));let y,E;c===-1?E=Promise.resolve("__never__"):E=new Promise(k=>{y=setTimeout(()=>k("__timeout__"),f),y.unref?.()});const b=l?l.then(()=>"__settle__"):Promise.resolve("__never__");try{const k=await Promise.race([P,E,b]);if(k==="__settle__")return o.manager.disableInactivityTimeout(t,p),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:p,status:"backgrounded",reason:"watchdog_timeout",waitedMs:f,message:`Command still running after watchdog timeout; moved to background. Use await_complete(bg_cmd_ids=["${p}"]) to block until it finishes, read_background_output(task_id="${p}", mode="tail") to read output, or kill_background_command(task_id="${p}") to stop.`};if(k==="__timeout__")return o.manager.disableInactivityTimeout(t,p),{ok:!0,tool:"Bash",command:e,backgrounded:!0,taskId:p,status:"backgrounded",reason:"timeout",waitedMs:f,message:`Command still running after ${c}s; moved to background. Use await_complete(bg_cmd_ids=["${p}"]) to block until it finishes, or read_background_output(task_id="${p}", mode="tail") / kill_background_command(task_id="${p}") to inspect.`};const _=k;return{ok:_.exitCode===0&&!_.timedOut,tool:"Bash",command:e,backgrounded:!1,taskId:p,exitCode:_.exitCode,signal:_.signal,timedOut:_.timedOut,inactivityTimedOut:_.inactivityTimedOut,timeoutMs:_.timeoutMs,inactivityTimeoutMs:_.inactivityTimeoutMs,durationMs:_.durationMs,outputSpilled:_.outputSpilled,outputFilePath:_.outputFilePath,outputLineCount:_.outputLineCount,commandFilePath:_.commandFilePath,commandLineCount:_.commandLineCount,stdout:_.stdout,stderr:_.stderr}}finally{y&&clearTimeout(y),g()}}catch(p){if(p?.code==="too_many_tasks"||p?.code==="global_limit_reached")return{ok:!1,tool:"Bash",command:e,backgrounded:!1,status:"not_executed",error:p.code,message:`Command was NOT executed: ${p.message}. Wait for some background tasks to finish/cleanup (per-agent limit 16, global 256), or reduce concurrent background commands, then retry.`};throw p}}function jt(n){return{kind:"builtin",toolName:"grep",exposedName:"grep",description:"Search file contents using regular expressions within the workspace. Returns matched lines with file paths and line numbers. Supports include/exclude glob patterns, case-insensitive matching, and three output modes (content, files_with_matches, count). Searches recursively through directories, skipping binary files, hidden directories, and common build/dependency directories (node_modules, .git, dist, etc.).",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Regular expression pattern to search for in file contents."},path:{type:"string",description:"Workspace-relative file or directory path to search in. Defaults to the workspace root."},include:{type:"string",description:"Glob pattern to filter files by name (e.g. '*.ts', '*.{js,ts}'). Only matching files are searched."},exclude:{type:"string",description:"Glob pattern to exclude files by name (e.g. '*.test.ts'). Matching files are skipped."},case_insensitive:{type:"boolean",description:"Case-insensitive matching. Default false."},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output format: 'content' returns matched lines with line numbers (default), 'files_with_matches' returns only file paths with matches, 'count' returns match counts per file."},max_results:{type:"number",description:"Maximum number of matched lines to return (content mode). Default 1000."}},required:["pattern"],additionalProperties:!1},async execute(o){const e=$(o,["pattern"],"pattern"),t=I(o,["path"])||".",i=I(o,["include"]),s=I(o,["exclude"]),r=o.case_insensitive===!0,a=(()=>{const x=o.output_mode;return x==="files_with_matches"||x==="count"?x:"content"})(),c=B(o,["max_results"],Et),u=r?"i":"";let l;try{l=new RegExp(e,u)}catch(x){throw new Error(`Invalid regex pattern: ${x instanceof Error?x.message:String(x)}`)}const w=i?tt(i):null,h=s?tt(s):null,g=await A(n,t),p=M(g.workspaceRoot,await m.realpath(g.targetPath)),P=await m.stat(p);let f;if(P.isFile())f=[p];else if(P.isDirectory())f=await Ot(p,w,h,bt);else throw new Error(`Path is neither a file nor a directory: ${p}`);const y=[],E=[],b=[];let k=0,_=0,R=!1;for(const x of f){if(a==="content"&&y.length>=c){R=!0;break}const ot={regex:l,maxResults:a==="content"?c-y.length:Number.MAX_SAFE_INTEGER,collectContent:a==="content",stopOnFirstMatch:a==="files_with_matches"},N=await Lt(x,g.workspaceRoot,ot);if(N.count>0){const q=d.relative(g.workspaceRoot,x).replace(/\\/g,"/");if(b.push(q),k+=N.count,a==="content"){for(const j of N.matches){const z=Buffer.byteLength(j.content,"utf-8")+64;if(_+z>Pt){R=!0;break}_+=z,y.push(j)}if(R)break;if(y.length>=c){R=!0;break}}else a==="count"&&E.push({file:q,count:N.count})}}const S={ok:!0,tool:"grep",pattern:e,searchPath:v(g.targetPath),outputMode:a,filesSearched:f.length,filesMatched:b.length,totalMatches:k,truncated:R};return a==="content"?S.matches=y:a==="files_with_matches"?S.matches=b:S.matches=E,S}}}function ee(n,o,e,t,i){const s=o||"unknown",r=[Dt(n,i),Nt(n,e,i),Ct(n,e,i),Ut(n,e,i),jt(n),Wt(n,s,t,i),st(n)];return t&&r.push(ct(s,t),lt(s,t),ut(s,t)),r}export{te as DEFAULT_TOOL_PERMISSION_POLICY,ee as createBuiltInFileTools,M as ensureInsideWorkspace,A as resolveWorkspaceTarget};
|
|
4
4
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
|
|
2
|
+
export type ImageFormat = "png" | "jpeg" | "gif" | "webp";
|
|
3
|
+
export interface ImageDimensions {
|
|
4
|
+
width: number;
|
|
5
|
+
height: number;
|
|
6
|
+
}
|
|
7
|
+
export interface SharpResizeResult {
|
|
8
|
+
buffer: Buffer;
|
|
9
|
+
mediaType: ImageFormat;
|
|
10
|
+
width: number;
|
|
11
|
+
height: number;
|
|
12
|
+
|
|
13
|
+
changed: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface ResizeOptions {
|
|
16
|
+
maxWidth: number;
|
|
17
|
+
maxHeight: number;
|
|
18
|
+
maxBytes: number;
|
|
19
|
+
}
|
|
20
|
+
export declare function imageMediaType(format: ImageFormat): string;
|
|
21
|
+
export declare function formatBytes(bytes: number): string;
|
|
22
|
+
|
|
23
|
+
export declare function detectImageFormatFromBuffer(buffer: Buffer): ImageFormat | null;
|
|
24
|
+
|
|
25
|
+
export declare function readImageDimensions(buffer: Buffer): ImageDimensions | null;
|
|
26
|
+
interface SharpLike {
|
|
27
|
+
metadata(): Promise<{
|
|
28
|
+
width?: number;
|
|
29
|
+
height?: number;
|
|
30
|
+
format?: string;
|
|
31
|
+
}>;
|
|
32
|
+
resize(width: number, height: number, options?: {
|
|
33
|
+
fit?: string;
|
|
34
|
+
withoutEnlargement?: boolean;
|
|
35
|
+
}): SharpLike;
|
|
36
|
+
jpeg(options?: {
|
|
37
|
+
quality?: number;
|
|
38
|
+
}): SharpLike;
|
|
39
|
+
png(options?: {
|
|
40
|
+
compressionLevel?: number;
|
|
41
|
+
palette?: boolean;
|
|
42
|
+
}): SharpLike;
|
|
43
|
+
toBuffer(): Promise<Buffer>;
|
|
44
|
+
}
|
|
45
|
+
type SharpFactory = (input: Buffer) => SharpLike;
|
|
46
|
+
|
|
47
|
+
export declare function resetSharpCacheForTest(): void;
|
|
48
|
+
|
|
49
|
+
export declare function setSharpFactoryForTest(factory: SharpFactory | null): void;
|
|
50
|
+
|
|
51
|
+
export declare function tryResizeWithSharp(input: Buffer, format: ImageFormat, options: ResizeOptions): Promise<SharpResizeResult | null>;
|
|
52
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function S(t){return`image/${t}`}function U(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(2)} MB`:t>=1024?`${(t/1024).toFixed(1)} KB`:`${t} B`}function f(t){return t.length<12?null:t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"png":t[0]===255&&t[1]===216&&t[2]===255?"jpeg":t[0]===71&&t[1]===73&&t[2]===70?"gif":t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"webp":null}function w(t){if(!(t.length<24||t.toString("hex",0,8)!=="89504e470d0a1a0a"))return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}function y(t){if(!(t.length<10||t.toString("ascii",0,6)!=="GIF87a"&&t.toString("ascii",0,6)!=="GIF89a"))return{width:t.readUInt16LE(6),height:t.readUInt16LE(8)}}function B(t){if(t.length<4||t[0]!==255||t[1]!==216)return;let n=2;for(;n+9<t.length;){if(t[n]!==255){n+=1;continue}const e=t[n+1],i=t.readUInt16BE(n+2);if(i<2)return;if(e>=192&&e<=207&&![196,200,204].includes(e)&&n+8<t.length)return{height:t.readUInt16BE(n+5),width:t.readUInt16BE(n+7)};n+=2+i}}function I(t){if(t.length<30||t.toString("ascii",0,4)!=="RIFF"||t.toString("ascii",8,12)!=="WEBP")return;const n=t.toString("ascii",12,16);if(n==="VP8X")return{width:1+t.readUIntLE(24,3),height:1+t.readUIntLE(27,3)};if(n==="VP8 ")return{width:t.readUInt16LE(26)&16383,height:t.readUInt16LE(28)&16383};if(n==="VP8L"&&t.length>=25){const e=t.readUInt32LE(21);return{width:(e&16383)+1,height:(e>>14&16383)+1}}}function E(t){const n=f(t);if(!n)return null;const i=(n==="png"?w:n==="gif"?y:n==="jpeg"?B:I)(t);return!i||!i.width||!i.height?null:i}let g;async function F(){return g===void 0&&(g=import("sharp").then(n=>{const e=n,i=typeof e=="function"?e:e.default;return typeof i=="function"?i:null}).catch(()=>null)),g}function M(){g=void 0}function T(t){g=Promise.resolve(t)}async function W(t,n,e){const i=await F();if(!i)return null;try{const o=await i(t).metadata();let d=o.width??0,s=o.height??0;if(!d||!s){const h=E(t);d=h?.width??0,s=h?.height??0}const x=d>0&&s>0,u=x&&d<=e.maxWidth&&s<=e.maxHeight;if(u&&t.length<=e.maxBytes)return{buffer:t,mediaType:n,width:d,height:s,changed:!1};if(u){if(n==="png"){const h=await i(t).png({compressionLevel:9,palette:!0}).toBuffer();if(h.length<=e.maxBytes)return{buffer:h,mediaType:"png",width:d,height:s,changed:!0}}for(const h of[80,60,40,20]){const c=await i(t).jpeg({quality:h}).toBuffer();if(c.length<=e.maxBytes)return{buffer:c,mediaType:"jpeg",width:d,height:s,changed:!0}}}let r=x?d:e.maxWidth,a=x?s:e.maxHeight;r>e.maxWidth&&(a=Math.round(a*e.maxWidth/r),r=e.maxWidth),a>e.maxHeight&&(r=Math.round(r*e.maxHeight/a),a=e.maxHeight),r=Math.max(1,r),a=Math.max(1,a);const m={fit:"inside",withoutEnlargement:!0};if(n==="png"){const h=await i(t).resize(r,a,m).png({compressionLevel:9,palette:!0}).toBuffer();if(h.length<=e.maxBytes)return{buffer:h,mediaType:"png",width:r,height:a,changed:!0}}for(const h of[80,60,40,20]){const c=await i(t).resize(r,a,m).jpeg({quality:h}).toBuffer();if(c.length<=e.maxBytes)return{buffer:c,mediaType:"jpeg",width:r,height:a,changed:!0}}const l=Math.min(r,1e3),p=Math.max(1,Math.round(a*l/Math.max(r,1)));return{buffer:await i(t).resize(l,p,m).jpeg({quality:20}).toBuffer(),mediaType:"jpeg",width:l,height:p,changed:!0}}catch{return null}}export{f as detectImageFormatFromBuffer,U as formatBytes,S as imageMediaType,E as readImageDimensions,M as resetSharpCacheForTest,T as setSharpFactoryForTest,W as tryResizeWithSharp};
|
|
2
|
+
|
|
@@ -9,6 +9,7 @@ export * from './sub-agent-types.js';
|
|
|
9
9
|
export * from './sub-agent-store.js';
|
|
10
10
|
export * from './sub-agent-manager.js';
|
|
11
11
|
export * from './sub-agent-tools.js';
|
|
12
|
+
export * from './built-in-file-tools.js';
|
|
12
13
|
export * from './terminal-types.js';
|
|
13
14
|
export * from './parsers/types.js';
|
|
14
15
|
export * from './parsers/tree-sitter-loader.js';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export*from"./commands/commandRegistry.js";export*from"./commands/commandLoader.js";export*from"./commands/commandParser.js";export*from"./config.js";export*from"./hooks/hookBus.js";export*from"./runtime.js";export*from"./types.js";export*from"./sub-agent-types.js";export*from"./sub-agent-store.js";export*from"./sub-agent-manager.js";export*from"./sub-agent-tools.js";export*from"./terminal-types.js";export*from"./parsers/types.js";export*from"./parsers/tree-sitter-loader.js";export*from"./parsers/ast-cache.js";export*from"./parsers/language-detector.js";export*from"./parsers/language-queries.js";export*from"./parsers/symbol-extractor.js";export*from"./built-in-symbols-tool.js";
|
|
1
|
+
export*from"./commands/commandRegistry.js";export*from"./commands/commandLoader.js";export*from"./commands/commandParser.js";export*from"./config.js";export*from"./hooks/hookBus.js";export*from"./runtime.js";export*from"./types.js";export*from"./sub-agent-types.js";export*from"./sub-agent-store.js";export*from"./sub-agent-manager.js";export*from"./sub-agent-tools.js";export*from"./built-in-file-tools.js";export*from"./terminal-types.js";export*from"./parsers/types.js";export*from"./parsers/tree-sitter-loader.js";export*from"./parsers/ast-cache.js";export*from"./parsers/language-detector.js";export*from"./parsers/language-queries.js";export*from"./parsers/symbol-extractor.js";export*from"./built-in-symbols-tool.js";
|
|
2
2
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { EventEmitter } from "node:events";
|
|
2
2
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
3
|
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
4
|
-
import { type JsonObject } from "./built-in-file-tools.js";
|
|
4
|
+
import { type JsonObject, type ToolPermissionPolicy } from "./built-in-file-tools.js";
|
|
5
5
|
import type { ACodeRuntimeConfig } from "./types.js";
|
|
6
6
|
export interface ACodeMcpConnection {
|
|
7
7
|
serverName: string;
|
|
@@ -125,6 +125,18 @@ export declare class ACodeRuntime extends EventEmitter {
|
|
|
125
125
|
|
|
126
126
|
private rejectAllQuestionWaiters;
|
|
127
127
|
|
|
128
|
+
private readonly permissionWaiters;
|
|
129
|
+
|
|
130
|
+
private createToolPermissionController;
|
|
131
|
+
|
|
132
|
+
private requestToolPermission;
|
|
133
|
+
|
|
134
|
+
submitToolPermissionDecision(requestId: string, allowed: boolean): boolean;
|
|
135
|
+
|
|
136
|
+
private rejectAllPermissionWaiters;
|
|
137
|
+
|
|
138
|
+
setToolPermissionPolicy(policy: Partial<ToolPermissionPolicy>): void;
|
|
139
|
+
|
|
128
140
|
private cancelPendingAwaitedSubAgents;
|
|
129
141
|
|
|
130
142
|
private cancelPendingAwaitedBgTasks;
|
|
@@ -175,6 +187,8 @@ export declare class ACodeRuntime extends EventEmitter {
|
|
|
175
187
|
|
|
176
188
|
private notifyRuntimeStop;
|
|
177
189
|
private appendSyntheticMultimodalUserMessage;
|
|
190
|
+
|
|
191
|
+
private cleanToolMessageAttachments;
|
|
178
192
|
private appendToolFailureResult;
|
|
179
193
|
|
|
180
194
|
private filterSharedMcpConnectionsForSubAgent;
|