@stdiobus/workers-registry 1.4.11 → 1.4.12
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/launch/index.js +1 -1
- package/launch/index.js.map +2 -2
- package/out/dist/workers-registry/acp-registry/index.js +2 -2
- package/out/dist/workers-registry/acp-registry/index.js.map +3 -3
- package/out/dist/workers-registry/acp-worker/index.js +1 -1
- package/out/dist/workers-registry/acp-worker/index.js.map +2 -2
- package/out/dist/workers-registry/index.d.ts +1 -0
- package/out/dist/workers-registry/index.js +6 -0
- package/out/dist/workers-registry/openai-agent/index.js +4 -0
- package/out/dist/workers-registry/openai-agent/index.js.map +7 -0
- package/out/tsc/workers-registry/acp-worker/src/registry-launcher/config/types.d.ts +2 -0
- package/out/tsc/workers-registry/acp-worker/src/registry-launcher/registry/index.d.ts +45 -0
- package/out/tsc/workers-registry/openai-agent/src/agent.d.ts +26 -0
- package/out/tsc/workers-registry/openai-agent/src/client.d.ts +7 -0
- package/out/tsc/workers-registry/openai-agent/src/config.d.ts +2 -0
- package/out/tsc/workers-registry/openai-agent/src/index.d.ts +11 -0
- package/out/tsc/workers-registry/openai-agent/src/session-id-router.d.ts +21 -0
- package/out/tsc/workers-registry/openai-agent/src/session-manager.d.ts +7 -0
- package/out/tsc/workers-registry/openai-agent/src/session.d.ts +18 -0
- package/out/tsc/workers-registry/openai-agent/src/sse-parser.d.ts +2 -0
- package/out/tsc/workers-registry/openai-agent/src/types.d.ts +43 -0
- package/out/tsc/workers-registry/openai-agent/tests/agent.property.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/agent.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/client.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/config.property.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/config.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/conversion.property.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/error-handling.property.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/session.property.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/session.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/sse-parser.property.test.d.ts +1 -0
- package/out/tsc/workers-registry/openai-agent/tests/sse-parser.test.d.ts +1 -0
- package/package.json +5 -1
|
@@ -3,5 +3,5 @@ import{Readable,Writable,Transform}from"node:stream";import{AgentSideConnection,
|
|
|
3
3
|
${content.text}`}}})}else if("blob"in content){await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resource: ${resourceLink.name}] (binary data, ${content.blob.length} bytes)`}}})}}}catch{await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resource link: ${resourceLink.name} (${resourceLink.uri})]`}}})}}else if(block.type==="resource"){const resource=block;if(resource.resource.text!==void 0){await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Embedded resource: ${resource.resource.uri}]
|
|
4
4
|
${resource.resource.text}`}}})}else if(resource.resource.blob!==void 0){await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Embedded resource: ${resource.resource.uri}] (binary data)`}}})}}else if(block.type==="image"){const image=block;await this._connection.sessionUpdate({sessionId:params.sessionId,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Image: ${image.mimeType}]`}}})}}if(session.isCancelled()){return{stopReason:"cancelled"}}return{stopReason:"end_turn"}}async cancel(params){this._sessionManager.cancelSession(params.sessionId)}};var SessionIdRouter=class{requestSessionIdMap=new Map;acpSessionIdMap=new Map;processIncomingLine(line){if(!line.trim()){return line}try{const msg=JSON.parse(line);const routingSessionId=this.readSessionId(msg.sessionId);const hasId=msg.id!==void 0&&msg.id!==null;if(hasId&&routingSessionId){this.requestSessionIdMap.set(msg.id,routingSessionId);console.error(`[worker] Saved sessionId="${routingSessionId}" for request id=${msg.id}`)}const paramsSessionId=this.readSessionId(msg.params?.sessionId);if(routingSessionId&¶msSessionId){this.setAcpSessionMapping(paramsSessionId,routingSessionId,"request")}if(hasId&&routingSessionId){const{sessionId,...msgWithoutSession}=msg;return JSON.stringify(msgWithoutSession)}return line}catch{return line}}processOutgoingLine(line){if(!line.trim()){return line}try{const msg=JSON.parse(line);const hasId=msg.id!==void 0&&msg.id!==null;if(hasId&&this.requestSessionIdMap.has(msg.id)){const routingSessionId=this.requestSessionIdMap.get(msg.id);this.requestSessionIdMap.delete(msg.id);if(routingSessionId){const resultSessionId=this.readSessionId(msg.result?.sessionId);if(resultSessionId){this.setAcpSessionMapping(resultSessionId,routingSessionId,"response")}const msgWithSession={...msg,sessionId:routingSessionId};console.error(`[worker] Restored sessionId="${routingSessionId}" for response id=${msg.id}`);return JSON.stringify(msgWithSession)}}if(!hasId&&!this.readSessionId(msg.sessionId)){const paramsSessionId=this.readSessionId(msg.params?.sessionId);if(paramsSessionId){const routingSessionId=this.acpSessionIdMap.get(paramsSessionId);if(routingSessionId){const msgWithSession={...msg,sessionId:routingSessionId};return JSON.stringify(msgWithSession)}}}return line}catch{return line}}readSessionId(value){return typeof value==="string"&&value.length>0?value:null}setAcpSessionMapping(acpSessionId,routingSessionId,source){const existing=this.acpSessionIdMap.get(acpSessionId);if(existing===routingSessionId){return}this.acpSessionIdMap.set(acpSessionId,routingSessionId);console.error(`[worker] Mapped ACP sessionId="${acpSessionId}" to routing sessionId="${routingSessionId}" (${source})`)}};var PlatformNotSupportedError=class extends Error{constructor(agentId,platform){super(`Platform not supported: ${platform} for agent ${agentId}`);this.agentId=agentId;this.platform=platform;this.name="PlatformNotSupportedError"}};var NoDistributionError=class extends Error{constructor(agentId){super(`No supported distribution type for agent ${agentId}`);this.agentId=agentId;this.name="NoDistributionError"}};function getCurrentPlatform(){const platform=process.platform;const arch=process.arch;if(platform==="darwin"&&arch==="arm64")return"darwin-aarch64";if(platform==="darwin"&&arch==="x64")return"darwin-x86_64";if(platform==="linux"&&arch==="arm64")return"linux-aarch64";if(platform==="linux"&&arch==="x64")return"linux-x86_64";if(platform==="win32"&&arch==="arm64")return"windows-aarch64";if(platform==="win32"&&arch==="x64")return"windows-x86_64";return"linux-x86_64"}function resolveBinary(distribution,agentId){const currentPlatform=getCurrentPlatform();const target=distribution[currentPlatform];if(!target){throw new PlatformNotSupportedError(agentId,currentPlatform)}return{command:target.cmd,args:target.args??[],env:target.env}}function resolveNpx(distribution){return{command:"npx",args:[distribution.package,...distribution.args??[]],env:distribution.env}}function resolveUvx(distribution){return{command:"uvx",args:[distribution.package,...distribution.args??[]],env:distribution.env}}function resolve(distribution,agentId){if(distribution.npx){return resolveNpx(distribution.npx)}if(distribution.uvx){return resolveUvx(distribution.uvx)}if(distribution.binary){return resolveBinary(distribution.binary,agentId)}throw new NoDistributionError(agentId)}import{spawn}from"child_process";var DEFAULT_TERMINATE_TIMEOUT_MS=5e3;var AgentRuntimeImpl=class _AgentRuntimeImpl{agentId;state;process;onExitCallback;constructor(agentId,process2,onExit){this.agentId=agentId;this.process=process2;this.state="starting";this.onExitCallback=onExit;this.setupProcessHandlers()}static spawn(agentId,spawnCommand,onExit){const childProcess=spawn(spawnCommand.command,spawnCommand.args,{stdio:["pipe","pipe","pipe"],env:{...process.env,...spawnCommand.env},detached:false});if(childProcess.stdout){childProcess.stdout.setEncoding("utf8")}if(childProcess.stderr){childProcess.stderr.setEncoding("utf8")}return new _AgentRuntimeImpl(agentId,childProcess,onExit)}setupProcessHandlers(){this.process.on("spawn",()=>{if(this.state==="starting"){this.state="running"}});this.process.on("error",error=>{this.state="stopped";process.stderr.write(`[${new Date().toISOString()}] ERROR: Agent ${this.agentId} process error: ${error.message}
|
|
5
5
|
`)});this.process.on("exit",(code,signal)=>{this.state="stopped";if(this.onExitCallback){this.onExitCallback(code,signal)}});if(this.process.stdin){this.process.stdin.on("error",error=>{process.stderr.write(`[${new Date().toISOString()}] WARN: Agent ${this.agentId} stdin error: ${error.message}
|
|
6
|
-
`)})}}write(message){if(this.state!=="running"&&this.state!=="starting"){return false}if(!this.process.stdin||this.process.stdin.destroyed){return false}try{const ndjsonLine=JSON.stringify(message)+"\n";return this.process.stdin.write(ndjsonLine)}catch{return false}}async terminate(timeout=DEFAULT_TERMINATE_TIMEOUT_MS){if(this.state==="stopped"){return}if(this.state==="stopping"){return this.waitForExit()}this.state="stopping";if(this.process.stdin&&!this.process.stdin.destroyed){this.process.stdin.end()}this.process.kill("SIGTERM");const exitPromise=this.waitForExit();const timeoutPromise=new Promise(resolve2=>{setTimeout(()=>resolve2("timeout"),timeout)});const result=await Promise.race([exitPromise,timeoutPromise]);if(result==="timeout"&&!this.process.killed&&this.process.exitCode===null){this.process.kill("SIGKILL");await this.waitForExit()}}waitForExit(){if(this.state==="stopped"){return Promise.resolve()}return new Promise(resolve2=>{this.process.once("exit",()=>{resolve2()})})}};var DEFAULT_SHUTDOWN_TIMEOUT_MS=5e3;var AgentRuntimeManager=class{runtimes=new Map;exitCallbacks=[];async getOrSpawn(agentId,spawnCommand){const existing=this.runtimes.get(agentId);if(existing&&existing.state!=="stopped"){return existing}const runtime=AgentRuntimeImpl.spawn(agentId,spawnCommand,(code,_signal)=>{this.handleAgentExit(agentId,code)});this.runtimes.set(agentId,runtime);return runtime}get(agentId){return this.runtimes.get(agentId)}async terminate(agentId,timeout=DEFAULT_SHUTDOWN_TIMEOUT_MS){const runtime=this.runtimes.get(agentId);if(!runtime){return}await runtime.terminate(timeout);this.runtimes.delete(agentId)}async terminateAll(timeout=DEFAULT_SHUTDOWN_TIMEOUT_MS){const terminatePromises=[];for(const[agentId,runtime]of this.runtimes){if(runtime.state!=="stopped"){terminatePromises.push(runtime.terminate(timeout).then(()=>{this.runtimes.delete(agentId)}))}}await Promise.all(terminatePromises)}onAgentExit(callback){this.exitCallbacks.push(callback)}handleAgentExit(agentId,code){this.runtimes.delete(agentId);for(const callback of this.exitCallbacks){try{callback(agentId,code)}catch{}}}get size(){return this.runtimes.size}has(agentId){return this.runtimes.has(agentId)}};function logError(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [ERROR] [ndjson] ${message}`)}var NDJSONHandler=class{buffer="";output;messageCallback=null;errorCallback=null;constructor(output){this.output=output}onMessage(callback){this.messageCallback=callback}onError(callback){this.errorCallback=callback}write(message){if(!this.output.writable){return false}try{const json=JSON.stringify(message);this.output.write(json+"\n");return true}catch{return false}}processChunk(chunk){this.buffer+=chunk.toString("utf-8");this.processBuffer()}processBuffer(){let newlineIndex;while((newlineIndex=this.buffer.indexOf("\n"))!==-1){const line=this.buffer.slice(0,newlineIndex);this.buffer=this.buffer.slice(newlineIndex+1);if(line.trim().length===0){continue}this.parseLine(line)}}parseLine(line){try{const message=JSON.parse(line);if(message===null||typeof message!=="object"){const error=new Error("Parsed JSON is not an object");logError(`Malformed NDJSON line (not an object): ${this.truncateLine(line)}`);this.errorCallback?.(error,line);return}this.messageCallback?.(message)}catch(error){logError(`Failed to parse NDJSON line: ${this.truncateLine(line)}`);this.errorCallback?.(error,line)}}truncateLine(line,maxLength=100){if(line.length<=maxLength){return line}return line.slice(0,maxLength)+"..."}};var AgentNotFoundError=class extends Error{constructor(agentId){super(`Agent not found: ${agentId}`);this.agentId=agentId;this.name="AgentNotFoundError"}};function getAgentApiKey(apiKeys,agentId){const keys=apiKeys[agentId];if(!keys||!keys.apiKey||keys.apiKey.length===0){return void 0}return keys.apiKey}var RoutingErrorCodes={MISSING_AGENT_ID:-32600,AGENT_NOT_FOUND:-32001,PLATFORM_NOT_SUPPORTED:-32002,SPAWN_FAILED:-32003};function logError2(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [ERROR] [router] ${message}`)}function logInfo(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [INFO] [router] ${message}`)}function createErrorResponse(id,code,message,data){const response={jsonrpc:"2.0",id,error:{code,message}};if(data!==void 0){response.error.data=data}return response}function extractAgentId(message){const msg=message;const agentId=msg.agentId;if(typeof agentId==="string"&&agentId.length>0){return agentId}return void 0}function extractId(message){const msg=message;const id=msg.id;if(typeof id==="string"||typeof id==="number"){return id}return null}function transformMessage(message){const{agentId:_,...rest}=message;return rest}var MessageRouter=class{registry;runtimeManager;writeCallback;apiKeys;pendingRequests=new Map;authState=new Map;sessionIdMap=new Map;constructor(registry,runtimeManager,writeCallback,apiKeys={}){this.registry=registry;this.runtimeManager=runtimeManager;this.writeCallback=writeCallback;this.apiKeys=apiKeys}async route(message){const id=extractId(message);const agentId=extractAgentId(message);if(agentId===void 0){logError2("Missing agentId in request");return createErrorResponse(id,RoutingErrorCodes.MISSING_AGENT_ID,"Missing agentId")}let spawnCommand;try{spawnCommand=this.registry.resolve(agentId)}catch(error){if(error instanceof AgentNotFoundError){logError2(`Agent not found: ${agentId}`);return createErrorResponse(id,RoutingErrorCodes.AGENT_NOT_FOUND,"Agent not found",{agentId})}if(error instanceof PlatformNotSupportedError){logError2(`Platform not supported for agent: ${agentId}`);return createErrorResponse(id,RoutingErrorCodes.PLATFORM_NOT_SUPPORTED,"Platform not supported",{agentId,platform:error.platform})}throw error}let runtime;try{runtime=await this.runtimeManager.getOrSpawn(agentId,spawnCommand)}catch(error){logError2(`Failed to spawn agent ${agentId}: ${error.message}`);return createErrorResponse(id,RoutingErrorCodes.SPAWN_FAILED,"Agent spawn failed",{agentId,error:error.message})}if(id!==null){const msg=message;const clientSessionId=typeof msg.sessionId==="string"?msg.sessionId:void 0;this.pendingRequests.set(id,{id,agentId,timestamp:Date.now(),clientSessionId})}const transformedMessage=transformMessage(message);const success=runtime.write(transformedMessage);if(!success){logError2(`Failed to write to agent ${agentId}`);if(id!==null){this.pendingRequests.delete(id)}}else{logInfo(`Routed message to agent ${agentId}`)}return void 0}handleAgentResponse(agentId,response){const id=extractId(response);const msg=response;const method=typeof msg.method==="string"?msg.method:void 0;if(id!==null&&method){this.handleAgentRequest(agentId,id,method,msg);return}if(id!==null){const pending=this.pendingRequests.get(id);if(pending&&pending.agentId===agentId){const result=msg.result;if(result&&Array.isArray(result.authMethods)&&result.authMethods.length>0){logInfo(`Agent ${agentId} requires authentication, attempting auto-auth`);this.authState.set(agentId,"pending");void this.attemptAuthentication(agentId,result.authMethods)}if(result&&typeof result.sessionId==="string"){const agentSessionId=result.sessionId;const clientSessionId=pending.clientSessionId;if(clientSessionId){this.sessionIdMap.set(agentSessionId,clientSessionId);logInfo(`Mapped agent sessionId ${agentSessionId} to client sessionId ${clientSessionId}`)}}this.pendingRequests.delete(id)}}if(id===null&&method){logInfo(`Received notification: ${method}`);const params=msg.params;if(params&&typeof params.sessionId==="string"){const agentSessionId=params.sessionId;const clientSessionId=this.sessionIdMap.get(agentSessionId);if(clientSessionId){const enriched={...msg,sessionId:clientSessionId,params:{...params,sessionId:agentSessionId}};logInfo(`Forwarding notification with mapped sessionId: ${clientSessionId}`);this.writeCallback(enriched);return}else{logError2(`Notification with unmapped agentSessionId: ${agentSessionId}, using default sessionId`);const enriched={...msg,sessionId:"global-notifications",params:{...params,sessionId:agentSessionId}};this.writeCallback(enriched);return}}else{const topLevelSessionId=msg.sessionId;if(topLevelSessionId){this.writeCallback(response);return}else{logError2(`Notification without sessionId: ${method}, adding default sessionId for routing`);const enriched={...msg,sessionId:"global-notifications"};this.writeCallback(enriched);return}}}this.writeCallback(response)}handleAgentRequest(agentId,id,method,msg){logInfo(`Agent ${agentId} sent request: ${method} (id=${id}), auto-responding`);let result;if(method==="session/request_permission"){result=this.buildPermissionResponse(msg)}else{logInfo(`Unknown agent request method: ${method}, sending generic success`);result={}}const response={jsonrpc:"2.0",id,result};this.sendToAgent(agentId,response)}buildPermissionResponse(msg){const params=msg.params;const options=params?.options;if(!options||options.length===0){return{optionId:"approved"}}const allowAlways=options.find(o=>o.kind==="allow_always");if(allowAlways&&typeof allowAlways.optionId==="string"){logInfo(`Auto-approving permission with option: ${allowAlways.optionId} (allow_always)`);return{optionId:allowAlways.optionId}}const allowOnce=options.find(o=>o.kind==="allow_once");if(allowOnce&&typeof allowOnce.optionId==="string"){logInfo(`Auto-approving permission with option: ${allowOnce.optionId} (allow_once)`);return{optionId:allowOnce.optionId}}const firstOption=options[0];const optionId=typeof firstOption.optionId==="string"?firstOption.optionId:"approved";logInfo(`Auto-approving permission with fallback option: ${optionId}`);return{optionId}}sendToAgent(agentId,message){let runtime;try{runtime=this.runtimeManager.get(agentId)}catch{logError2(`Failed to get runtime for agent ${agentId} to send response`);return}if(!runtime){logError2(`No runtime found for agent ${agentId}, cannot send response`);return}const success=runtime.write(message);if(!success){logError2(`Failed to write response to agent ${agentId}`)}else{logInfo(`Sent auto-response to agent ${agentId}`)}}async attemptAuthentication(agentId,authMethods){const apiKey=getAgentApiKey(this.apiKeys,agentId);if(!apiKey){logError2(`No API key found for agent ${agentId}, authentication will fail`);this.authState.set(agentId,"none");return}let selectedMethod=authMethods.find(m=>m.id==="openai-api-key");if(!selectedMethod){selectedMethod=authMethods.find(m=>m.id.includes("api-key")||m.id.includes("apikey"))}if(!selectedMethod){selectedMethod=authMethods[0]}logInfo(`Authenticating agent ${agentId} with method: ${selectedMethod.id}`);let runtime;try{const spawnCommand=this.registry.resolve(agentId);runtime=await this.runtimeManager.getOrSpawn(agentId,spawnCommand)}catch(error){logError2(`Failed to get runtime for authentication: ${error.message}`);this.authState.set(agentId,"none");return}const authRequest={jsonrpc:"2.0",id:`auth-${agentId}-${Date.now()}`,method:"authenticate",params:{methodId:selectedMethod.id,credentials:{apiKey}}};const transformed=transformMessage(authRequest);const serialized=JSON.stringify(transformed)+"\n";if(runtime.process.stdin){runtime.process.stdin.write(serialized,error=>{if(error){logError2(`Failed to send authenticate request to ${agentId}: ${error.message}`);this.authState.set(agentId,"none")}else{logInfo(`Sent authenticate request to agent ${agentId}`);this.authState.set(agentId,"authenticated")}})}}get pendingCount(){return this.pendingRequests.size}isPending(id){return this.pendingRequests.has(id)}clearPending(){this.pendingRequests.clear()}};import{readFileSync}from"node:fs";var DEFAULT_CONFIG={registryUrl:"https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",apiKeysPath:"./api-keys.json",shutdownTimeoutSec:5};var ENV_REGISTRY_URL="ACP_REGISTRY_URL";var ENV_API_KEYS_PATH="ACP_API_KEYS_PATH";function logWarning(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [WARN] [config] ${message}`)}function isNonEmptyString(value){return typeof value==="string"&&value.length>0}function isPositiveNumber(value){return typeof value==="number"&&value>0&&Number.isFinite(value)}function parseConfigObject(obj){const config={...DEFAULT_CONFIG};if(obj===null||typeof obj!=="object"){logWarning("Config file does not contain a valid object, using defaults");return config}const rawConfig=obj;if("registryUrl"in rawConfig){if(isNonEmptyString(rawConfig.registryUrl)){config.registryUrl=rawConfig.registryUrl}else{logWarning('Config field "registryUrl" is not a valid string, using default')}}if("apiKeysPath"in rawConfig){if(isNonEmptyString(rawConfig.apiKeysPath)){config.apiKeysPath=rawConfig.apiKeysPath}else{logWarning('Config field "apiKeysPath" is not a valid string, using default')}}if("shutdownTimeoutSec"in rawConfig){if(isPositiveNumber(rawConfig.shutdownTimeoutSec)){config.shutdownTimeoutSec=rawConfig.shutdownTimeoutSec}else{logWarning('Config field "shutdownTimeoutSec" is not a valid positive number, using default')}}return config}function applyEnvironmentOverrides(config){const envRegistryUrl=process.env[ENV_REGISTRY_URL];const envApiKeysPath=process.env[ENV_API_KEYS_PATH];const overrides={};if(isNonEmptyString(envRegistryUrl)){overrides.registryUrl=envRegistryUrl}if(isNonEmptyString(envApiKeysPath)){overrides.apiKeysPath=envApiKeysPath}return{...config,...overrides}}function loadConfig(configPath){let config={...DEFAULT_CONFIG};if(configPath){try{const fileContent=readFileSync(configPath,"utf-8");const parsed=JSON.parse(fileContent);config=parseConfigObject(parsed)}catch(error){if(error instanceof SyntaxError){logWarning(`Config file "${configPath}" contains malformed JSON, using defaults`)}else if(error.code==="ENOENT"){logWarning(`Config file "${configPath}" not found, using defaults`)}else if(error.code==="EACCES"){logWarning(`Config file "${configPath}" is not readable, using defaults`)}else{logWarning(`Failed to read config file "${configPath}": ${error.message}, using defaults`)}}}config=applyEnvironmentOverrides(config);return config}function canReadFile(capabilities){return capabilities?.fs?.readTextFile===true}function canWriteFile(capabilities){return capabilities?.fs?.writeTextFile===true}function canUseTerminal(capabilities){return capabilities?.terminal===true}async function readFile(connection2,sessionId,path,options){try{const response=await connection2.readTextFile({sessionId,path,line:options?.line,limit:options?.limit});return{content:response.content,success:true}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to read file "${path}":`,error);return{content:"",success:false,error:errorMessage}}}async function writeFile(connection2,sessionId,path,content){try{await connection2.writeTextFile({sessionId,path,content});return{success:true}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to write file "${path}":`,error);return{success:false,error:errorMessage}}}async function executeCommand(connection2,sessionId,command,options){let terminal=null;try{terminal=await connection2.createTerminal({sessionId,command,args:options?.args,cwd:options?.cwd,env:options?.env,outputByteLimit:options?.outputByteLimit});let timeoutId=null;let timedOut=false;if(options?.timeout&&options.timeout>0){timeoutId=setTimeout(async()=>{timedOut=true;if(terminal){try{await terminal.kill()}catch{}}},options.timeout)}try{const exitResult=await terminal.waitForExit();if(timeoutId){clearTimeout(timeoutId)}const outputResult=await terminal.currentOutput();return{output:outputResult.output,exitCode:timedOut?null:exitResult.exitCode??null,signal:timedOut?"SIGTERM":exitResult.signal??null,truncated:outputResult.truncated,success:!timedOut&&exitResult.exitCode===0,error:timedOut?"Command timed out":void 0}}finally{if(timeoutId){clearTimeout(timeoutId)}}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to execute command "${command}":`,error);return{output:"",exitCode:null,signal:null,truncated:false,success:false,error:errorMessage}}finally{if(terminal){try{await terminal.release()}catch{}}}}async function startCommand(connection2,sessionId,command,options){return connection2.createTerminal({sessionId,command,args:options?.args,cwd:options?.cwd,env:options?.env,outputByteLimit:options?.outputByteLimit})}function mapMCPContentToACPContentBlock(mcpContent){switch(mcpContent.type){case"text":return mapTextContent(mcpContent);case"image":return mapImageContent(mcpContent);case"resource":return mapEmbeddedResource(mcpContent);default:return{type:"text",text:JSON.stringify(mcpContent)}}}function mapTextContent(mcpText){const result={type:"text",text:mcpText.text};return result}function mapImageContent(mcpImage){const result={type:"image",data:mcpImage.data,mimeType:mcpImage.mimeType};return result}function mapEmbeddedResource(mcpResource){const{resource}=mcpResource;if(resource.text!==void 0){const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,text:resource.text}};return result}else if(resource.blob!==void 0){const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,blob:resource.blob}};return result}else{const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,text:""}};return result}}function mapMCPResultToACPToolCallContent(mcpContents){return mcpContents.map(mcpContent=>{const contentBlock=mapMCPContentToACPContentBlock(mcpContent);return{type:"content",content:contentBlock}})}function createErrorToolCallContent(errorMessage){return[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}]}function mapToolResultToACPContent(content,isError=false){if(isError&&content.length>0){const errorText=content.filter(c=>c.type==="text").map(c=>c.text).join("\n");if(errorText){return createErrorToolCallContent(errorText)}}return mapMCPResultToACPToolCallContent(content)}function isResourceLink(block){return block.type==="resource_link"&&"uri"in block}function mapMCPResourceContentsToACPContentBlock(contents){if("text"in contents){const result2={type:"resource",resource:{uri:contents.uri,mimeType:contents.mimeType,text:contents.text}};return result2}const result={type:"resource",resource:{uri:contents.uri,mimeType:contents.mimeType,blob:contents.blob}};return result}function extractResourceLinkUri(block){if(isResourceLink(block)){return block.uri}return null}var toolCallCounter=0;function generateToolCallId(){toolCallCounter++;return`tool-${Date.now()}-${toolCallCounter}`}function determineToolKind(toolName,description){const name=toolName.toLowerCase();const desc=(description||"").toLowerCase();if(desc.includes("external")||desc.includes("api")||desc.includes("http")){return"fetch"}if(name.includes("read")||name.includes("get")||name.includes("list")||name.includes("fetch")){return"read"}if(name.includes("write")||name.includes("edit")||name.includes("update")||name.includes("modify")){return"edit"}if(name.includes("delete")||name.includes("remove")){return"delete"}if(name.includes("move")||name.includes("rename")){return"move"}if(name.includes("search")||name.includes("find")||name.includes("query")){return"search"}if(name.includes("exec")||name.includes("run")||name.includes("shell")||name.includes("command")){return"execute"}if(name.includes("http")||name.includes("api")||name.includes("request")){return"fetch"}return"other"}async function sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind="other",status="pending"){await connection2.sessionUpdate({sessionId,update:{sessionUpdate:"tool_call",toolCallId,title,kind,status}})}async function sendToolCallUpdate(connection2,sessionId,toolCallId,status,content,title){await connection2.sessionUpdate({sessionId,update:{sessionUpdate:"tool_call_update",toolCallId,status,content,title}})}async function requestToolPermission(connection2,sessionId,toolCallId,title,kind="other",options){const permissionOptions=options??[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Allow always",kind:"allow_always"},{optionId:"reject_once",name:"Reject",kind:"reject_once"}];const toolCall={toolCallId,title,kind,status:"pending"};try{const response=await connection2.requestPermission({sessionId,toolCall,options:permissionOptions});if(response.outcome.outcome==="cancelled"){return{granted:false,cancelled:true}}if(response.outcome.outcome==="selected"){const selectedOption=response.outcome.optionId;const isAllowed=selectedOption.startsWith("allow");return{granted:isAllowed,optionId:selectedOption,cancelled:false}}return{granted:false,cancelled:false}}catch(error){console.error("[ACP] Permission request failed:",error);return{granted:false,cancelled:true}}}async function executeToolCall(connection2,sessionId,mcpManager,toolName,args,description){const toolCallId=generateToolCallId();const kind=determineToolKind(toolName,description);const title=`Executing: ${toolName}`;try{await sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind,"pending");await sendToolCallUpdate(connection2,sessionId,toolCallId,"in_progress");const result=await mcpManager.callTool(toolName,args);const content=mapToolResultToACPContent(result.content,result.isError);const finalStatus=result.isError?"failed":"completed";await sendToolCallUpdate(connection2,sessionId,toolCallId,finalStatus,content);return content}catch(error){const errorMessage=error instanceof Error?error.message:String(error);const errorContent=[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,"failed",errorContent);return errorContent}}async function executeToolCallWithPermission(connection2,sessionId,mcpManager,toolName,args,description,requirePermission=true){const toolCallId=generateToolCallId();const kind=determineToolKind(toolName,description);const title=`Executing: ${toolName}`;try{await sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind,"pending");if(requirePermission){const permissionResult=await requestToolPermission(connection2,sessionId,toolCallId,title,kind);if(!permissionResult.granted){const status=permissionResult.cancelled?"failed":"failed";const message=permissionResult.cancelled?"Permission request cancelled":"Permission denied";const errorContent=[{type:"content",content:{type:"text",text:message}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,status,errorContent);return{content:errorContent,permissionResult}}}await sendToolCallUpdate(connection2,sessionId,toolCallId,"in_progress");const result=await mcpManager.callTool(toolName,args);const content=mapToolResultToACPContent(result.content,result.isError);const finalStatus=result.isError?"failed":"completed";await sendToolCallUpdate(connection2,sessionId,toolCallId,finalStatus,content);return{content}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);const errorContent=[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,"failed",errorContent);return{content:errorContent}}}console.error("[worker] Starting ACP/MCP Protocol Worker...");var sessionIdRouter=new SessionIdRouter;var stdinTransform=new Transform({objectMode:false,transform(chunk,_encoding,callback){const lines=chunk.toString().split("\n");const processedLines=[];for(const line of lines){processedLines.push(sessionIdRouter.processIncomingLine(line))}callback(null,Buffer.from(processedLines.join("\n")))}});var stdoutTransform=new Transform({objectMode:false,transform(chunk,_encoding,callback){const lines=chunk.toString().split("\n");const processedLines=[];for(const line of lines){processedLines.push(sessionIdRouter.processOutgoingLine(line))}callback(null,Buffer.from(processedLines.join("\n")))}});process.stdin.pipe(stdinTransform);var inputStream=Readable.toWeb(stdinTransform);var outputStream=Writable.toWeb(stdoutTransform);stdoutTransform.pipe(process.stdout);var stream=ndJsonStream(outputStream,inputStream);var connection=new AgentSideConnection(conn=>new ACPAgent(conn),stream);console.error("[worker] AgentSideConnection established, ready for messages");process.on("SIGTERM",async()=>{console.error("[worker] Received SIGTERM, shutting down...");await connection.closed;process.exit(0)});process.on("SIGINT",async()=>{console.error("[worker] Received SIGINT, shutting down...");await connection.closed;process.exit(0)});process.on("uncaughtException",error=>{console.error("[worker] Uncaught exception:",error);process.exit(1)});process.on("unhandledRejection",(reason,promise)=>{console.error("[worker] Unhandled rejection at:",promise,"reason:",reason)});connection.closed.then(()=>{console.error("[worker] Connection closed");process.exit(0)}).catch(error=>{console.error("[worker] Connection error:",error);process.exit(1)});export{ACPAgent,AgentRuntimeImpl,AgentRuntimeManager,MCPManager,MessageRouter,NDJSONHandler,NoDistributionError,PlatformNotSupportedError,RoutingErrorCodes,canReadFile,canUseTerminal,canWriteFile,createErrorResponse,createErrorToolCallContent,determineToolKind,executeCommand,executeToolCall,executeToolCallWithPermission,extractAgentId,extractId,extractResourceLinkUri,generateToolCallId,getCurrentPlatform,isResourceLink,loadConfig,mapMCPContentToACPContentBlock,mapMCPResourceContentsToACPContentBlock,mapMCPResultToACPToolCallContent,mapToolResultToACPContent,readFile,requestToolPermission,resolve,resolveBinary,resolveNpx,resolveUvx,sendToolCallInitiation,sendToolCallUpdate,startCommand,transformMessage,writeFile};
|
|
6
|
+
`)})}}write(message){if(this.state!=="running"&&this.state!=="starting"){return false}if(!this.process.stdin||this.process.stdin.destroyed){return false}try{const ndjsonLine=JSON.stringify(message)+"\n";return this.process.stdin.write(ndjsonLine)}catch{return false}}async terminate(timeout=DEFAULT_TERMINATE_TIMEOUT_MS){if(this.state==="stopped"){return}if(this.state==="stopping"){return this.waitForExit()}this.state="stopping";if(this.process.stdin&&!this.process.stdin.destroyed){this.process.stdin.end()}this.process.kill("SIGTERM");const exitPromise=this.waitForExit();const timeoutPromise=new Promise(resolve2=>{setTimeout(()=>resolve2("timeout"),timeout)});const result=await Promise.race([exitPromise,timeoutPromise]);if(result==="timeout"&&!this.process.killed&&this.process.exitCode===null){this.process.kill("SIGKILL");await this.waitForExit()}}waitForExit(){if(this.state==="stopped"){return Promise.resolve()}return new Promise(resolve2=>{this.process.once("exit",()=>{resolve2()})})}};var DEFAULT_SHUTDOWN_TIMEOUT_MS=5e3;var AgentRuntimeManager=class{runtimes=new Map;exitCallbacks=[];async getOrSpawn(agentId,spawnCommand){const existing=this.runtimes.get(agentId);if(existing&&existing.state!=="stopped"){return existing}const runtime=AgentRuntimeImpl.spawn(agentId,spawnCommand,(code,_signal)=>{this.handleAgentExit(agentId,code)});this.runtimes.set(agentId,runtime);return runtime}get(agentId){return this.runtimes.get(agentId)}async terminate(agentId,timeout=DEFAULT_SHUTDOWN_TIMEOUT_MS){const runtime=this.runtimes.get(agentId);if(!runtime){return}await runtime.terminate(timeout);this.runtimes.delete(agentId)}async terminateAll(timeout=DEFAULT_SHUTDOWN_TIMEOUT_MS){const terminatePromises=[];for(const[agentId,runtime]of this.runtimes){if(runtime.state!=="stopped"){terminatePromises.push(runtime.terminate(timeout).then(()=>{this.runtimes.delete(agentId)}))}}await Promise.all(terminatePromises)}onAgentExit(callback){this.exitCallbacks.push(callback)}handleAgentExit(agentId,code){this.runtimes.delete(agentId);for(const callback of this.exitCallbacks){try{callback(agentId,code)}catch{}}}get size(){return this.runtimes.size}has(agentId){return this.runtimes.has(agentId)}};function logError(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [ERROR] [ndjson] ${message}`)}var NDJSONHandler=class{buffer="";output;messageCallback=null;errorCallback=null;constructor(output){this.output=output}onMessage(callback){this.messageCallback=callback}onError(callback){this.errorCallback=callback}write(message){if(!this.output.writable){return false}try{const json=JSON.stringify(message);this.output.write(json+"\n");return true}catch{return false}}processChunk(chunk){this.buffer+=chunk.toString("utf-8");this.processBuffer()}processBuffer(){let newlineIndex;while((newlineIndex=this.buffer.indexOf("\n"))!==-1){const line=this.buffer.slice(0,newlineIndex);this.buffer=this.buffer.slice(newlineIndex+1);if(line.trim().length===0){continue}this.parseLine(line)}}parseLine(line){try{const message=JSON.parse(line);if(message===null||typeof message!=="object"){const error=new Error("Parsed JSON is not an object");logError(`Malformed NDJSON line (not an object): ${this.truncateLine(line)}`);this.errorCallback?.(error,line);return}this.messageCallback?.(message)}catch(error){logError(`Failed to parse NDJSON line: ${this.truncateLine(line)}`);this.errorCallback?.(error,line)}}truncateLine(line,maxLength=100){if(line.length<=maxLength){return line}return line.slice(0,maxLength)+"..."}};var AgentNotFoundError=class extends Error{constructor(agentId){super(`Agent not found: ${agentId}`);this.agentId=agentId;this.name="AgentNotFoundError"}};function getAgentApiKey(apiKeys,agentId){const keys=apiKeys[agentId];if(!keys||!keys.apiKey||keys.apiKey.length===0){return void 0}return keys.apiKey}var RoutingErrorCodes={MISSING_AGENT_ID:-32600,AGENT_NOT_FOUND:-32001,PLATFORM_NOT_SUPPORTED:-32002,SPAWN_FAILED:-32003};function logError2(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [ERROR] [router] ${message}`)}function logInfo(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [INFO] [router] ${message}`)}function createErrorResponse(id,code,message,data){const response={jsonrpc:"2.0",id,error:{code,message}};if(data!==void 0){response.error.data=data}return response}function extractAgentId(message){const msg=message;const agentId=msg.agentId;if(typeof agentId==="string"&&agentId.length>0){return agentId}return void 0}function extractId(message){const msg=message;const id=msg.id;if(typeof id==="string"||typeof id==="number"){return id}return null}function transformMessage(message){const{agentId:_,...rest}=message;return rest}var MessageRouter=class{registry;runtimeManager;writeCallback;apiKeys;pendingRequests=new Map;authState=new Map;sessionIdMap=new Map;constructor(registry,runtimeManager,writeCallback,apiKeys={}){this.registry=registry;this.runtimeManager=runtimeManager;this.writeCallback=writeCallback;this.apiKeys=apiKeys}async route(message){const id=extractId(message);const agentId=extractAgentId(message);if(agentId===void 0){logError2("Missing agentId in request");return createErrorResponse(id,RoutingErrorCodes.MISSING_AGENT_ID,"Missing agentId")}let spawnCommand;try{spawnCommand=this.registry.resolve(agentId)}catch(error){if(error instanceof AgentNotFoundError){logError2(`Agent not found: ${agentId}`);return createErrorResponse(id,RoutingErrorCodes.AGENT_NOT_FOUND,"Agent not found",{agentId})}if(error instanceof PlatformNotSupportedError){logError2(`Platform not supported for agent: ${agentId}`);return createErrorResponse(id,RoutingErrorCodes.PLATFORM_NOT_SUPPORTED,"Platform not supported",{agentId,platform:error.platform})}throw error}let runtime;try{runtime=await this.runtimeManager.getOrSpawn(agentId,spawnCommand)}catch(error){logError2(`Failed to spawn agent ${agentId}: ${error.message}`);return createErrorResponse(id,RoutingErrorCodes.SPAWN_FAILED,"Agent spawn failed",{agentId,error:error.message})}if(id!==null){const msg=message;const clientSessionId=typeof msg.sessionId==="string"?msg.sessionId:void 0;this.pendingRequests.set(id,{id,agentId,timestamp:Date.now(),clientSessionId})}const transformedMessage=transformMessage(message);const success=runtime.write(transformedMessage);if(!success){logError2(`Failed to write to agent ${agentId}`);if(id!==null){this.pendingRequests.delete(id)}}else{logInfo(`Routed message to agent ${agentId}`)}return void 0}handleAgentResponse(agentId,response){const id=extractId(response);const msg=response;const method=typeof msg.method==="string"?msg.method:void 0;if(id!==null&&method){this.handleAgentRequest(agentId,id,method,msg);return}if(id!==null){const pending=this.pendingRequests.get(id);if(pending&&pending.agentId===agentId){const result=msg.result;if(result&&Array.isArray(result.authMethods)&&result.authMethods.length>0){logInfo(`Agent ${agentId} requires authentication, attempting auto-auth`);this.authState.set(agentId,"pending");void this.attemptAuthentication(agentId,result.authMethods)}if(result&&typeof result.sessionId==="string"){const agentSessionId=result.sessionId;const clientSessionId=pending.clientSessionId;if(clientSessionId){this.sessionIdMap.set(agentSessionId,clientSessionId);logInfo(`Mapped agent sessionId ${agentSessionId} to client sessionId ${clientSessionId}`)}}this.pendingRequests.delete(id)}}if(id===null&&method){logInfo(`Received notification: ${method}`);const params=msg.params;if(params&&typeof params.sessionId==="string"){const agentSessionId=params.sessionId;const clientSessionId=this.sessionIdMap.get(agentSessionId);if(clientSessionId){const enriched={...msg,sessionId:clientSessionId,params:{...params,sessionId:agentSessionId}};logInfo(`Forwarding notification with mapped sessionId: ${clientSessionId}`);this.writeCallback(enriched);return}else{logError2(`Notification with unmapped agentSessionId: ${agentSessionId}, using default sessionId`);const enriched={...msg,sessionId:"global-notifications",params:{...params,sessionId:agentSessionId}};this.writeCallback(enriched);return}}else{const topLevelSessionId=msg.sessionId;if(topLevelSessionId){this.writeCallback(response);return}else{logError2(`Notification without sessionId: ${method}, adding default sessionId for routing`);const enriched={...msg,sessionId:"global-notifications"};this.writeCallback(enriched);return}}}this.writeCallback(response)}handleAgentRequest(agentId,id,method,msg){logInfo(`Agent ${agentId} sent request: ${method} (id=${id}), auto-responding`);let result;if(method==="session/request_permission"){result=this.buildPermissionResponse(msg)}else{logInfo(`Unknown agent request method: ${method}, sending generic success`);result={}}const response={jsonrpc:"2.0",id,result};this.sendToAgent(agentId,response)}buildPermissionResponse(msg){const params=msg.params;const options=params?.options;if(!options||options.length===0){return{optionId:"approved"}}const allowAlways=options.find(o=>o.kind==="allow_always");if(allowAlways&&typeof allowAlways.optionId==="string"){logInfo(`Auto-approving permission with option: ${allowAlways.optionId} (allow_always)`);return{optionId:allowAlways.optionId}}const allowOnce=options.find(o=>o.kind==="allow_once");if(allowOnce&&typeof allowOnce.optionId==="string"){logInfo(`Auto-approving permission with option: ${allowOnce.optionId} (allow_once)`);return{optionId:allowOnce.optionId}}const firstOption=options[0];const optionId=typeof firstOption.optionId==="string"?firstOption.optionId:"approved";logInfo(`Auto-approving permission with fallback option: ${optionId}`);return{optionId}}sendToAgent(agentId,message){let runtime;try{runtime=this.runtimeManager.get(agentId)}catch{logError2(`Failed to get runtime for agent ${agentId} to send response`);return}if(!runtime){logError2(`No runtime found for agent ${agentId}, cannot send response`);return}const success=runtime.write(message);if(!success){logError2(`Failed to write response to agent ${agentId}`)}else{logInfo(`Sent auto-response to agent ${agentId}`)}}async attemptAuthentication(agentId,authMethods){const apiKey=getAgentApiKey(this.apiKeys,agentId);if(!apiKey){logError2(`No API key found for agent ${agentId}, authentication will fail`);this.authState.set(agentId,"none");return}let selectedMethod=authMethods.find(m=>m.id==="openai-api-key");if(!selectedMethod){selectedMethod=authMethods.find(m=>m.id.includes("api-key")||m.id.includes("apikey"))}if(!selectedMethod){selectedMethod=authMethods[0]}logInfo(`Authenticating agent ${agentId} with method: ${selectedMethod.id}`);let runtime;try{const spawnCommand=this.registry.resolve(agentId);runtime=await this.runtimeManager.getOrSpawn(agentId,spawnCommand)}catch(error){logError2(`Failed to get runtime for authentication: ${error.message}`);this.authState.set(agentId,"none");return}const authRequest={jsonrpc:"2.0",id:`auth-${agentId}-${Date.now()}`,method:"authenticate",params:{methodId:selectedMethod.id,credentials:{apiKey}}};const transformed=transformMessage(authRequest);const serialized=JSON.stringify(transformed)+"\n";if(runtime.process.stdin){runtime.process.stdin.write(serialized,error=>{if(error){logError2(`Failed to send authenticate request to ${agentId}: ${error.message}`);this.authState.set(agentId,"none")}else{logInfo(`Sent authenticate request to agent ${agentId}`);this.authState.set(agentId,"authenticated")}})}}get pendingCount(){return this.pendingRequests.size}isPending(id){return this.pendingRequests.has(id)}clearPending(){this.pendingRequests.clear()}};import{readFileSync}from"node:fs";var DEFAULT_CONFIG={registryUrl:"https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",apiKeysPath:"./api-keys.json",shutdownTimeoutSec:5};var ENV_REGISTRY_URL="ACP_REGISTRY_URL";var ENV_API_KEYS_PATH="ACP_API_KEYS_PATH";var ENV_CUSTOM_AGENTS_PATH="ACP_CUSTOM_AGENTS_PATH";function logWarning(message){const timestamp=new Date().toISOString();console.error(`[${timestamp}] [WARN] [config] ${message}`)}function isNonEmptyString(value){return typeof value==="string"&&value.length>0}function isPositiveNumber(value){return typeof value==="number"&&value>0&&Number.isFinite(value)}function parseConfigObject(obj){const config={...DEFAULT_CONFIG};if(obj===null||typeof obj!=="object"){logWarning("Config file does not contain a valid object, using defaults");return config}const rawConfig=obj;if("registryUrl"in rawConfig){if(isNonEmptyString(rawConfig.registryUrl)){config.registryUrl=rawConfig.registryUrl}else{logWarning('Config field "registryUrl" is not a valid string, using default')}}if("apiKeysPath"in rawConfig){if(isNonEmptyString(rawConfig.apiKeysPath)){config.apiKeysPath=rawConfig.apiKeysPath}else{logWarning('Config field "apiKeysPath" is not a valid string, using default')}}if("shutdownTimeoutSec"in rawConfig){if(isPositiveNumber(rawConfig.shutdownTimeoutSec)){config.shutdownTimeoutSec=rawConfig.shutdownTimeoutSec}else{logWarning('Config field "shutdownTimeoutSec" is not a valid positive number, using default')}}if("customAgentsPath"in rawConfig){if(isNonEmptyString(rawConfig.customAgentsPath)){config.customAgentsPath=rawConfig.customAgentsPath}else{logWarning('Config field "customAgentsPath" is not a valid string, ignoring')}}return config}function applyEnvironmentOverrides(config){const envRegistryUrl=process.env[ENV_REGISTRY_URL];const envApiKeysPath=process.env[ENV_API_KEYS_PATH];const envCustomAgentsPath=process.env[ENV_CUSTOM_AGENTS_PATH];const overrides={};if(isNonEmptyString(envRegistryUrl)){overrides.registryUrl=envRegistryUrl}if(isNonEmptyString(envApiKeysPath)){overrides.apiKeysPath=envApiKeysPath}if(isNonEmptyString(envCustomAgentsPath)){overrides.customAgentsPath=envCustomAgentsPath}return{...config,...overrides}}function loadConfig(configPath){let config={...DEFAULT_CONFIG};if(configPath){try{const fileContent=readFileSync(configPath,"utf-8");const parsed=JSON.parse(fileContent);config=parseConfigObject(parsed)}catch(error){if(error instanceof SyntaxError){logWarning(`Config file "${configPath}" contains malformed JSON, using defaults`)}else if(error.code==="ENOENT"){logWarning(`Config file "${configPath}" not found, using defaults`)}else if(error.code==="EACCES"){logWarning(`Config file "${configPath}" is not readable, using defaults`)}else{logWarning(`Failed to read config file "${configPath}": ${error.message}, using defaults`)}}}config=applyEnvironmentOverrides(config);return config}function canReadFile(capabilities){return capabilities?.fs?.readTextFile===true}function canWriteFile(capabilities){return capabilities?.fs?.writeTextFile===true}function canUseTerminal(capabilities){return capabilities?.terminal===true}async function readFile(connection2,sessionId,path,options){try{const response=await connection2.readTextFile({sessionId,path,line:options?.line,limit:options?.limit});return{content:response.content,success:true}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to read file "${path}":`,error);return{content:"",success:false,error:errorMessage}}}async function writeFile(connection2,sessionId,path,content){try{await connection2.writeTextFile({sessionId,path,content});return{success:true}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to write file "${path}":`,error);return{success:false,error:errorMessage}}}async function executeCommand(connection2,sessionId,command,options){let terminal=null;try{terminal=await connection2.createTerminal({sessionId,command,args:options?.args,cwd:options?.cwd,env:options?.env,outputByteLimit:options?.outputByteLimit});let timeoutId=null;let timedOut=false;if(options?.timeout&&options.timeout>0){timeoutId=setTimeout(async()=>{timedOut=true;if(terminal){try{await terminal.kill()}catch{}}},options.timeout)}try{const exitResult=await terminal.waitForExit();if(timeoutId){clearTimeout(timeoutId)}const outputResult=await terminal.currentOutput();return{output:outputResult.output,exitCode:timedOut?null:exitResult.exitCode??null,signal:timedOut?"SIGTERM":exitResult.signal??null,truncated:outputResult.truncated,success:!timedOut&&exitResult.exitCode===0,error:timedOut?"Command timed out":void 0}}finally{if(timeoutId){clearTimeout(timeoutId)}}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);console.error(`[ACP] Failed to execute command "${command}":`,error);return{output:"",exitCode:null,signal:null,truncated:false,success:false,error:errorMessage}}finally{if(terminal){try{await terminal.release()}catch{}}}}async function startCommand(connection2,sessionId,command,options){return connection2.createTerminal({sessionId,command,args:options?.args,cwd:options?.cwd,env:options?.env,outputByteLimit:options?.outputByteLimit})}function mapMCPContentToACPContentBlock(mcpContent){switch(mcpContent.type){case"text":return mapTextContent(mcpContent);case"image":return mapImageContent(mcpContent);case"resource":return mapEmbeddedResource(mcpContent);default:return{type:"text",text:JSON.stringify(mcpContent)}}}function mapTextContent(mcpText){const result={type:"text",text:mcpText.text};return result}function mapImageContent(mcpImage){const result={type:"image",data:mcpImage.data,mimeType:mcpImage.mimeType};return result}function mapEmbeddedResource(mcpResource){const{resource}=mcpResource;if(resource.text!==void 0){const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,text:resource.text}};return result}else if(resource.blob!==void 0){const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,blob:resource.blob}};return result}else{const result={type:"resource",resource:{uri:resource.uri,mimeType:resource.mimeType,text:""}};return result}}function mapMCPResultToACPToolCallContent(mcpContents){return mcpContents.map(mcpContent=>{const contentBlock=mapMCPContentToACPContentBlock(mcpContent);return{type:"content",content:contentBlock}})}function createErrorToolCallContent(errorMessage){return[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}]}function mapToolResultToACPContent(content,isError=false){if(isError&&content.length>0){const errorText=content.filter(c=>c.type==="text").map(c=>c.text).join("\n");if(errorText){return createErrorToolCallContent(errorText)}}return mapMCPResultToACPToolCallContent(content)}function isResourceLink(block){return block.type==="resource_link"&&"uri"in block}function mapMCPResourceContentsToACPContentBlock(contents){if("text"in contents){const result2={type:"resource",resource:{uri:contents.uri,mimeType:contents.mimeType,text:contents.text}};return result2}const result={type:"resource",resource:{uri:contents.uri,mimeType:contents.mimeType,blob:contents.blob}};return result}function extractResourceLinkUri(block){if(isResourceLink(block)){return block.uri}return null}var toolCallCounter=0;function generateToolCallId(){toolCallCounter++;return`tool-${Date.now()}-${toolCallCounter}`}function determineToolKind(toolName,description){const name=toolName.toLowerCase();const desc=(description||"").toLowerCase();if(desc.includes("external")||desc.includes("api")||desc.includes("http")){return"fetch"}if(name.includes("read")||name.includes("get")||name.includes("list")||name.includes("fetch")){return"read"}if(name.includes("write")||name.includes("edit")||name.includes("update")||name.includes("modify")){return"edit"}if(name.includes("delete")||name.includes("remove")){return"delete"}if(name.includes("move")||name.includes("rename")){return"move"}if(name.includes("search")||name.includes("find")||name.includes("query")){return"search"}if(name.includes("exec")||name.includes("run")||name.includes("shell")||name.includes("command")){return"execute"}if(name.includes("http")||name.includes("api")||name.includes("request")){return"fetch"}return"other"}async function sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind="other",status="pending"){await connection2.sessionUpdate({sessionId,update:{sessionUpdate:"tool_call",toolCallId,title,kind,status}})}async function sendToolCallUpdate(connection2,sessionId,toolCallId,status,content,title){await connection2.sessionUpdate({sessionId,update:{sessionUpdate:"tool_call_update",toolCallId,status,content,title}})}async function requestToolPermission(connection2,sessionId,toolCallId,title,kind="other",options){const permissionOptions=options??[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Allow always",kind:"allow_always"},{optionId:"reject_once",name:"Reject",kind:"reject_once"}];const toolCall={toolCallId,title,kind,status:"pending"};try{const response=await connection2.requestPermission({sessionId,toolCall,options:permissionOptions});if(response.outcome.outcome==="cancelled"){return{granted:false,cancelled:true}}if(response.outcome.outcome==="selected"){const selectedOption=response.outcome.optionId;const isAllowed=selectedOption.startsWith("allow");return{granted:isAllowed,optionId:selectedOption,cancelled:false}}return{granted:false,cancelled:false}}catch(error){console.error("[ACP] Permission request failed:",error);return{granted:false,cancelled:true}}}async function executeToolCall(connection2,sessionId,mcpManager,toolName,args,description){const toolCallId=generateToolCallId();const kind=determineToolKind(toolName,description);const title=`Executing: ${toolName}`;try{await sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind,"pending");await sendToolCallUpdate(connection2,sessionId,toolCallId,"in_progress");const result=await mcpManager.callTool(toolName,args);const content=mapToolResultToACPContent(result.content,result.isError);const finalStatus=result.isError?"failed":"completed";await sendToolCallUpdate(connection2,sessionId,toolCallId,finalStatus,content);return content}catch(error){const errorMessage=error instanceof Error?error.message:String(error);const errorContent=[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,"failed",errorContent);return errorContent}}async function executeToolCallWithPermission(connection2,sessionId,mcpManager,toolName,args,description,requirePermission=true){const toolCallId=generateToolCallId();const kind=determineToolKind(toolName,description);const title=`Executing: ${toolName}`;try{await sendToolCallInitiation(connection2,sessionId,toolCallId,title,kind,"pending");if(requirePermission){const permissionResult=await requestToolPermission(connection2,sessionId,toolCallId,title,kind);if(!permissionResult.granted){const status=permissionResult.cancelled?"failed":"failed";const message=permissionResult.cancelled?"Permission request cancelled":"Permission denied";const errorContent=[{type:"content",content:{type:"text",text:message}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,status,errorContent);return{content:errorContent,permissionResult}}}await sendToolCallUpdate(connection2,sessionId,toolCallId,"in_progress");const result=await mcpManager.callTool(toolName,args);const content=mapToolResultToACPContent(result.content,result.isError);const finalStatus=result.isError?"failed":"completed";await sendToolCallUpdate(connection2,sessionId,toolCallId,finalStatus,content);return{content}}catch(error){const errorMessage=error instanceof Error?error.message:String(error);const errorContent=[{type:"content",content:{type:"text",text:`Error: ${errorMessage}`}}];await sendToolCallUpdate(connection2,sessionId,toolCallId,"failed",errorContent);return{content:errorContent}}}console.error("[worker] Starting ACP/MCP Protocol Worker...");var sessionIdRouter=new SessionIdRouter;var stdinTransform=new Transform({objectMode:false,transform(chunk,_encoding,callback){const lines=chunk.toString().split("\n");const processedLines=[];for(const line of lines){processedLines.push(sessionIdRouter.processIncomingLine(line))}callback(null,Buffer.from(processedLines.join("\n")))}});var stdoutTransform=new Transform({objectMode:false,transform(chunk,_encoding,callback){const lines=chunk.toString().split("\n");const processedLines=[];for(const line of lines){processedLines.push(sessionIdRouter.processOutgoingLine(line))}callback(null,Buffer.from(processedLines.join("\n")))}});process.stdin.pipe(stdinTransform);var inputStream=Readable.toWeb(stdinTransform);var outputStream=Writable.toWeb(stdoutTransform);stdoutTransform.pipe(process.stdout);var stream=ndJsonStream(outputStream,inputStream);var connection=new AgentSideConnection(conn=>new ACPAgent(conn),stream);console.error("[worker] AgentSideConnection established, ready for messages");process.on("SIGTERM",async()=>{console.error("[worker] Received SIGTERM, shutting down...");await connection.closed;process.exit(0)});process.on("SIGINT",async()=>{console.error("[worker] Received SIGINT, shutting down...");await connection.closed;process.exit(0)});process.on("uncaughtException",error=>{console.error("[worker] Uncaught exception:",error);process.exit(1)});process.on("unhandledRejection",(reason,promise)=>{console.error("[worker] Unhandled rejection at:",promise,"reason:",reason)});connection.closed.then(()=>{console.error("[worker] Connection closed");process.exit(0)}).catch(error=>{console.error("[worker] Connection error:",error);process.exit(1)});export{ACPAgent,AgentRuntimeImpl,AgentRuntimeManager,MCPManager,MessageRouter,NDJSONHandler,NoDistributionError,PlatformNotSupportedError,RoutingErrorCodes,canReadFile,canUseTerminal,canWriteFile,createErrorResponse,createErrorToolCallContent,determineToolKind,executeCommand,executeToolCall,executeToolCallWithPermission,extractAgentId,extractId,extractResourceLinkUri,generateToolCallId,getCurrentPlatform,isResourceLink,loadConfig,mapMCPContentToACPContentBlock,mapMCPResourceContentsToACPContentBlock,mapMCPResultToACPToolCallContent,mapToolResultToACPContent,readFile,requestToolPermission,resolve,resolveBinary,resolveNpx,resolveUvx,sendToolCallInitiation,sendToolCallUpdate,startCommand,transformMessage,writeFile};
|
|
7
7
|
//# sourceMappingURL=index.js.map
|