beeos-claw 0.5.25 → 0.5.27
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/a2a/tools.js +1 -1
- package/dist/a2a/tools.test.js +1 -1
- package/dist/acp-gateway/beeos-file-resolver.js +1 -1
- package/dist/acp-gateway/bridge-core-agent-create.test.js +1 -1
- package/dist/acp-gateway/bridge-core-apply-template.test.js +1 -1
- package/dist/acp-gateway/bridge-core.js +1 -1
- package/dist/acp-gateway/file-artifact-presenter.js +1 -0
- package/dist/acp-gateway/file-artifact-presenter.test.js +1 -0
- package/dist/acp-gateway/gateway-events.js +1 -1
- package/dist/acp-gateway/session-state.js +1 -1
- package/dist/acp-gateway/tool-result-payload-strategies.js +1 -1
- package/dist/acp-gateway/tool-result-payload-strategies.test.js +1 -0
- package/dist/acp-server.js +1 -1
- package/dist/canvas/tools.js +1 -1
- package/dist/files/beeos-file-uri.js +1 -0
- package/dist/files/beeos-file-uri.test.js +1 -0
- package/dist/files/fetch-tool.js +1 -1
- package/dist/files/fetch-tool.test.js +1 -0
- package/dist/index.js +1 -1
- package/dist/upload/tool.js +1 -1
- package/dist/upload/tool.test.js +1 -0
- package/package.json +1 -1
package/dist/a2a/tools.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{agentFetch}from"../agent-auth.js";import{resolveAgentIdFromMentions}from"../delegation/mention-resolver.js";async function a2aFetch(t,e,a){const n=`${t.agentGatewayUrl}${e}`;return t.agentKeys?agentFetch(n,t.agentKeys,a):fetch(n,a)}export{a2aFetch};function normalizeState(t){if(!t)return"";const e=t.toLowerCase();return{task_state_submitted:"submitted",task_state_delivered:"submitted",task_state_working:"working",task_state_completed:"completed",task_state_failed:"failed",task_state_timeout:"timeout",task_state_canceled:"canceled",task_state_rejected:"rejected",task_state_input_required:"input-required",task_state_auth_required:"auth-required"}[e]??e}function unwrapTask(t){if(!t||"object"!=typeof t)return;const e=t,a=e.task;return a&&"object"==typeof a?a:e}function extractArtifactText(t){const e=t?.artifacts;if(!e)return;return e.flatMap(t=>t.parts??[]).filter(t=>"string"==typeof t.text&&(void 0===t.kind||"text"===t.kind)).map(t=>t.text).join("\n")||void 0}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function stringValue(t){return"string"==typeof t&&""!==t?t:void 0}function normalizeArtifactFilePart(t){const e=stringValue(t.kind),a=isRecord(t.file)?t.file:void 0;let n=stringValue(t.url),r=stringValue(t.filename),s=stringValue(t.mediaType);if(a&&(n=stringValue(a.uri)??stringValue(a.url)??n,r=stringValue(a.name)??stringValue(a.filename)??r,s=stringValue(a.mimeType)??stringValue(a.mediaType)??s),n&&(!e||"file"===e))return{uri:n,...r?{name:r}:{},...s?{mimeType:s}:{}}}function extractArtifactFiles(t){const e=t?.artifacts;if(!e)return;const a=[];for(const t of e){const e=t.parts;if(Array.isArray(e))for(const t of e){if(!isRecord(t))continue;const e=normalizeArtifactFilePart(t);e&&a.push(e)}}return a.length>0?a:void 0}function extractStatusText(t){const e=t?.status,a=e?.message?.parts,n=a?.[0]?.text;return"string"==typeof n?n:void 0}function taskState(t){return normalizeState(t?.status?.state)}const TERMINAL_FAILURE_STATES=new Set(["failed","timeout","canceled","rejected"]);function taskContextId(t){const e=t?.contextId;return"string"==typeof e&&""!==e?e:void 0}function buildTaskPayload(t,e,a){const n=taskState(t),r=extractArtifactText(t),s=extractArtifactFiles(t),i=extractStatusText(t),o=taskContextId(t),c={status:n,is_terminal:"completed"===n||TERMINAL_FAILURE_STATES.has(n)};return e&&(c.task_id=e),a&&(c.agent_id=a),o&&(c.context_id=o),r?c.result=r:i&&(c.error=i),s&&(c.files=s),c}export{unwrapTask,extractArtifactText,extractArtifactFiles,extractStatusText,taskState,taskContextId,normalizeState,buildTaskPayload};export class TaskHandleRegistry{seq=0;handles=new Map;taskIdToHandle=new Map;create(t,e,a,n){const r="bth_"+ ++this.seq;return this.handles.set(r,{taskId:t,agentId:e,contextId:a,sessionKey:n}),this.taskIdToHandle.set(t,r),r}resolveTaskId(t){const e=this.handles.get(t);return e?e.taskId:t}resolveAgentId(t){const e=this.handles.get(t);if(e)return e.agentId;const a=this.taskIdToHandle.get(t);return a?this.handles.get(a)?.agentId:void 0}}const defaultRegistry=new TaskHandleRegistry;export function registerA2ATools(t,e,a=defaultRegistry,n,r,s,i){t.registerTool({name:"beeos_discover_agents",description:"List agents available for A2A collaboration. When called without a query, returns all visible agents (your own agents + public agents). When called with a query, filters by name, description, or skill. Results include an `isSelf` flag marking the agent that represents the current instance (do not call yourself). Each result includes `instanceName` (human-readable device/instance label) when available.",parameters:{type:"object",properties:{query:{type:"string",description:"Optional keyword to filter agents by name, description, or skill. Omit to list all agents."}},required:[]},async execute(t,a,n){const{query:r}=a??{};try{const t=new URLSearchParams({limit:"50"});r&&t.set("query",r);const a=await a2aFetch(e,`/api/v1/a2a/discover?${t}`,{signal:n});if(!a.ok)return{content:JSON.stringify({error:`discover failed: ${a.status}`})};const s=await a.json(),o=i?.();if(o&&Array.isArray(s?.data))for(const t of s.data)t.isSelf=t.instance_id===o;return{content:JSON.stringify(s,null,2)}}catch(t){if(n?.aborted)throw t;return{content:JSON.stringify({error:t instanceof Error?t.message:String(t)})}}}}),t.registerTool({name:"beeos_call_agent",description:"Ask another agent to perform a task. This creates the task ASYNCHRONOUSLY and returns immediately with a handle ({ task_id, agent_id, context_id, status }) — it does NOT wait for the result. To fetch the agent's reply, call beeos_get_task with the returned task_id (and agent_id). Do NOT call beeos_call_agent again to poll an existing task — that creates a brand-new task.",parameters:{type:"object",properties:{agentId:{type:"string",description:"The target agent UUID (e.g. d04080d1-...) or display name. Prefer the UUID from discover results or @mention metadata when available."},message:{type:"string",description:"The task description or message to send to the agent"},taskId:{type:"string",description:"Optional existing task ID to continue a multi-turn conversation. When provided, the message is appended to the existing task instead of creating a new one."},files:{type:"array",items:{type:"string"},description:"Optional file URLs to include with the request"},contextId:{type:"string",description:"Optional context ID for multi-turn conversations with the same agent"},timeoutMs:{type:"number",description:"Server-side task timeout in milliseconds (how long the target agent may run before the task is timed out). Defaults to 600000 (10 minutes). This is NOT a client wait time — beeos_call_agent returns immediately regardless."}},required:["agentId","message"]},async execute(t,i,o){let{agentId:c,message:d,files:l,contextId:u,timeoutMs:g,taskId:f}=i;const h=n?.(t),p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!p.test(c)){const a=r?.(t);if(a?.length){const t=resolveAgentIdFromMentions(a,c);t&&(e.logger.info?.(`beeos_call_agent: resolved "${c}" → ${t} via mention context`),c=t)}if(!p.test(c))try{const t=await a2aFetch(e,`/api/v1/a2a/discover?query=${encodeURIComponent(c)}&limit=10`,{signal:o});if(t.ok){const a=await t.json(),n=a?.data??[],r=c.toLowerCase(),s=n.find(t=>t.name.toLowerCase()===r)??n.find(t=>t.name.toLowerCase().includes(r));if(!s)return{content:JSON.stringify({error:`Could not resolve agent name "${c}". Available agents: ${n.map(t=>`${t.name} (${t.id})`).join(", ")||"none"}`})};e.logger.info?.(`beeos_call_agent: resolved "${c}" → ${s.id} (${s.name}) via discover`),c=s.id}}catch{}}const m=u||(h?`session:${h}`:""),k=g||6e5;try{const t={jsonrpc:"2.0",id:`claw-${Date.now()}`,method:"SendMessage",params:{message:{role:"user",parts:[{text:d}],...m?{contextId:m}:{},...f?{taskId:f}:{}},configuration:{timeoutMs:k}}},n=`/api/v1/a2a/${encodeURIComponent(c)}`,r=AbortSignal.timeout(3e4),i=o?AbortSignal.any([o,r]):r,l=await a2aFetch(e,n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:i}),g=await l.text();let p;try{p=JSON.parse(g)}catch{p={}}if(!l.ok||p.error){if(401===l.status||403===l.status){const t=p.error??{};-32600===t.code&&s&&s("_beeos/auth_required",{type:"auth_required",target_agent_id:c,target_agent_name:c,title:"Authentication Required",content:`Agent **${c}** requires authentication.`})}const t=p.error?JSON.stringify(p.error):g;return{content:JSON.stringify({error:`send task failed: ${l.status} ${t}`,agent_id:c})}}const y=unwrapTask(p.result),_=y?.id;return _?(a.create(_,c,u,h),{content:JSON.stringify({status:taskState(y)||"working",task_id:_,agent_id:c,context_id:taskContextId(y)??m??void 0,message:`Task created. Call beeos_get_task with task_id "${_}" (and agent_id "${c}") to fetch status and result.`})}):{content:JSON.stringify({error:"task created but server returned no task_id",agent_id:c})}}catch(t){if(o?.aborted)throw t;return t instanceof DOMException&&"TimeoutError"===t.name?{content:JSON.stringify({error:"create task request timed out after 30000ms",agent_id:c})}:{content:JSON.stringify({error:t instanceof Error?t.message:String(t),agent_id:c})}}}}),t.registerTool({name:"beeos_get_task",description:'Fetch the current state AND data of an existing A2A task by its task_id. Use this to check on a task that beeos_call_agent created (it returns status "working" with a task_id), or to re-read a finished task. Always returns a JSON object { status, task_id, agent_id, context_id, is_terminal, result?, error? }: `result` holds the produced output (present whenever the device produced output, EVEN for timeout/canceled/failed tasks that still produced content); `error` holds the failure reason when there is no produced output; `is_terminal` indicates whether the task has reached a final state. Do NOT call beeos_call_agent again to re-query an existing task — that creates a brand-new task.',parameters:{type:"object",properties:{taskId:{type:"string",description:"The task ID returned by a previous beeos_call_agent call."},agentId:{type:"string",description:"The target agent UUID that owns the task (the same agentId passed to beeos_call_agent). Optional when the task was created earlier in this session — it is resolved automatically."}},required:["taskId"]},async execute(t,n,r){const{taskId:s,agentId:i}=n??{};if(!s)return{content:JSON.stringify({error:"taskId is required"})};const o=i||a.resolveAgentId(s);if(!o)return{content:JSON.stringify({error:`agentId is required to query task "${s}" (it was not created in this session, so the target agent is unknown). Pass the agentId you originally called.`,task_id:s})};try{const t=`/api/v1/a2a/${encodeURIComponent(o)}`,a=await a2aFetch(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:`claw-get-${Date.now()}`,method:"GetTask",params:{id:s}}),signal:r}),n=await a.text();let i;try{i=JSON.parse(n)}catch{i={}}if(!a.ok||i.error){const t=i.error?JSON.stringify(i.error):n;return{content:JSON.stringify({error:`get task failed: ${a.status} ${t}`,task_id:s,agent_id:o})}}const c=unwrapTask(i.result);return{content:JSON.stringify(buildTaskPayload(c,s,o))}}catch(t){if(r?.aborted)throw t;return{content:JSON.stringify({error:t instanceof Error?t.message:String(t),task_id:s,agent_id:o})}}}})}
|
|
1
|
+
import{agentFetch}from"../agent-auth.js";import{resolveAgentIdFromMentions}from"../delegation/mention-resolver.js";async function a2aFetch(t,e,a){const n=`${t.agentGatewayUrl}${e}`;return t.agentKeys?agentFetch(n,t.agentKeys,a):fetch(n,a)}export{a2aFetch};function normalizeState(t){if(!t)return"";const e=t.toLowerCase();return{task_state_submitted:"submitted",task_state_delivered:"submitted",task_state_working:"working",task_state_completed:"completed",task_state_failed:"failed",task_state_timeout:"timeout",task_state_canceled:"canceled",task_state_rejected:"rejected",task_state_input_required:"input-required",task_state_auth_required:"auth-required"}[e]??e}function unwrapTask(t){if(!t||"object"!=typeof t)return;const e=t,a=e.task;return a&&"object"==typeof a?a:e}function extractArtifactText(t){const e=t?.artifacts;if(!e)return;return e.flatMap(t=>t.parts??[]).filter(t=>"string"==typeof t.text&&(void 0===t.kind||"text"===t.kind)).map(t=>t.text).join("\n")||void 0}function isRecord(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function stringValue(t){return"string"==typeof t&&""!==t?t:void 0}function normalizeArtifactFilePart(t){const e=stringValue(t.kind),a=isRecord(t.file)?t.file:void 0;let n=stringValue(t.url),s=stringValue(t.filename),r=stringValue(t.mediaType);if(a&&(n=stringValue(a.uri)??stringValue(a.url)??n,s=stringValue(a.name)??stringValue(a.filename)??s,r=stringValue(a.mimeType)??stringValue(a.mediaType)??r),n&&(!e||"file"===e))return{uri:n,...s?{name:s}:{},...r?{mimeType:r}:{}}}function extractArtifactFiles(t){const e=t?.artifacts;if(!e)return;const a=[];for(const t of e){const e=t.parts;if(Array.isArray(e))for(const t of e){if(!isRecord(t))continue;const e=normalizeArtifactFilePart(t);e&&a.push(e)}}return a.length>0?a:void 0}function extractStatusText(t){const e=t?.status,a=e?.message?.parts,n=a?.[0]?.text;return"string"==typeof n?n:void 0}function taskState(t){return normalizeState(t?.status?.state)}const TERMINAL_FAILURE_STATES=new Set(["failed","timeout","canceled","rejected"]);function taskContextId(t){const e=t?.contextId;return"string"==typeof e&&""!==e?e:void 0}function buildTaskPayload(t,e,a){const n=taskState(t),s=extractArtifactText(t),r=extractArtifactFiles(t),i=extractStatusText(t),o=taskContextId(t),c={status:n,is_terminal:"completed"===n||TERMINAL_FAILURE_STATES.has(n)};return e&&(c.task_id=e),a&&(c.agent_id=a),o&&(c.context_id=o),s?c.result=s:i&&(c.error=i),r&&(c.files=r),c}export{unwrapTask,extractArtifactText,extractArtifactFiles,extractStatusText,taskState,taskContextId,normalizeState,buildTaskPayload};export class TaskHandleRegistry{seq=0;handles=new Map;taskIdToHandle=new Map;create(t,e,a,n){const s="bth_"+ ++this.seq;return this.handles.set(s,{taskId:t,agentId:e,contextId:a,sessionKey:n}),this.taskIdToHandle.set(t,s),s}resolveTaskId(t){const e=this.handles.get(t);return e?e.taskId:t}resolveAgentId(t){const e=this.handles.get(t);if(e)return e.agentId;const a=this.taskIdToHandle.get(t);return a?this.handles.get(a)?.agentId:void 0}}const defaultRegistry=new TaskHandleRegistry;export function registerA2ATools(t,e,a=defaultRegistry,n,s,r,i){t.registerTool({name:"beeos_discover_agents",description:"List agents available for A2A collaboration. When called without a query, returns all visible agents (your own agents + public agents). When called with a query, filters by name, description, or skill. Results include an `isSelf` flag marking the agent that represents the current instance (do not call yourself). Each result includes `instanceName` (human-readable device/instance label) when available.",parameters:{type:"object",properties:{query:{type:"string",description:"Optional keyword to filter agents by name, description, or skill. Omit to list all agents."}},required:[]},async execute(t,a,n){const{query:s}=a??{};try{const t=new URLSearchParams({limit:"50"});s&&t.set("query",s);const a=await a2aFetch(e,`/api/v1/a2a/discover?${t}`,{signal:n});if(!a.ok)return{content:JSON.stringify({error:`discover failed: ${a.status}`})};const r=await a.json(),o=i?.();if(o&&Array.isArray(r?.data))for(const t of r.data)t.isSelf=t.instance_id===o;return{content:JSON.stringify(r,null,2)}}catch(t){if(n?.aborted)throw t;return{content:JSON.stringify({error:t instanceof Error?t.message:String(t)})}}}}),t.registerTool({name:"beeos_call_agent",description:"Ask another agent to perform a task. This creates the task ASYNCHRONOUSLY and returns immediately with a handle ({ task_id, agent_id, context_id, status }) — it does NOT wait for the result. To fetch the agent's reply, call beeos_get_task with the returned task_id (and agent_id). Do NOT call beeos_call_agent again to poll an existing task — that creates a brand-new task.",parameters:{type:"object",properties:{agentId:{type:"string",description:"The target agent UUID (e.g. d04080d1-...) or display name. Prefer the UUID from discover results or @mention metadata when available."},message:{type:"string",description:"The task description or message to send to the agent"},taskId:{type:"string",description:"Optional existing task ID to continue a multi-turn conversation. When provided, the message is appended to the existing task instead of creating a new one."},files:{type:"array",items:{type:"string"},description:"Optional file URLs to include with the request"},contextId:{type:"string",description:"Optional context ID for multi-turn conversations with the same agent"},timeoutMs:{type:"number",description:"Server-side task timeout in milliseconds (how long the target agent may run before the task is timed out). Defaults to 600000 (10 minutes). This is NOT a client wait time — beeos_call_agent returns immediately regardless."}},required:["agentId","message"]},async execute(t,i,o){let{agentId:c,message:d,files:l,contextId:u,timeoutMs:g,taskId:f}=i;const h=n?.(t),p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!p.test(c)){const a=s?.(t);if(a?.length){const t=resolveAgentIdFromMentions(a,c);t&&(e.logger.info?.(`beeos_call_agent: resolved "${c}" → ${t} via mention context`),c=t)}if(!p.test(c))try{const t=await a2aFetch(e,`/api/v1/a2a/discover?query=${encodeURIComponent(c)}&limit=10`,{signal:o});if(t.ok){const a=await t.json(),n=a?.data??[],s=c.toLowerCase(),r=n.find(t=>t.name.toLowerCase()===s)??n.find(t=>t.name.toLowerCase().includes(s));if(!r)return{content:JSON.stringify({error:`Could not resolve agent name "${c}". Available agents: ${n.map(t=>`${t.name} (${t.id})`).join(", ")||"none"}`})};e.logger.info?.(`beeos_call_agent: resolved "${c}" → ${r.id} (${r.name}) via discover`),c=r.id}}catch{}}const m=u||(h?`session:${h}`:""),y=g||6e5;try{const t={jsonrpc:"2.0",id:`claw-${Date.now()}`,method:"SendMessage",params:{message:{role:"user",parts:[{text:d}],...m?{contextId:m}:{},...f?{taskId:f}:{}},configuration:{timeoutMs:y}}},n=`/api/v1/a2a/${encodeURIComponent(c)}`,s=AbortSignal.timeout(3e4),i=o?AbortSignal.any([o,s]):s,l=await a2aFetch(e,n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:i}),g=await l.text();let p;try{p=JSON.parse(g)}catch{p={}}if(!l.ok||p.error){if(401===l.status||403===l.status){const t=p.error??{};-32600===t.code&&r&&r("_beeos/auth_required",{type:"auth_required",target_agent_id:c,target_agent_name:c,title:"Authentication Required",content:`Agent **${c}** requires authentication.`})}const t=p.error?JSON.stringify(p.error):g;return{content:JSON.stringify({error:`send task failed: ${l.status} ${t}`,agent_id:c})}}const k=unwrapTask(p.result),_=k?.id;return _?(a.create(_,c,u,h),{content:JSON.stringify({status:taskState(k)||"working",task_id:_,agent_id:c,context_id:taskContextId(k)??m??void 0,message:`Task created. Call beeos_get_task with task_id "${_}" (and agent_id "${c}") to fetch status and result.`})}):{content:JSON.stringify({error:"task created but server returned no task_id",agent_id:c})}}catch(t){if(o?.aborted)throw t;return t instanceof DOMException&&"TimeoutError"===t.name?{content:JSON.stringify({error:"create task request timed out after 30000ms",agent_id:c})}:{content:JSON.stringify({error:t instanceof Error?t.message:String(t),agent_id:c})}}}}),t.registerTool({name:"beeos_get_task",description:'Fetch the current state AND data of an existing A2A task by its task_id. Use this to check on a task that beeos_call_agent created (it returns status "working" with a task_id), or to re-read a finished task. Always returns a JSON object { status, task_id, agent_id, context_id, is_terminal, result?, files?, error? }: `result` holds the produced output (present whenever the device produced output, EVEN for timeout/canceled/failed tasks that still produced content); `files` contains structured file artifacts ({uri,name,mimeType}). The runtime displays image files in Canvas when Canvas is active, otherwise as chat attachments. Do not output MEDIA:, and do not upload/fetch/browser/shell files[].uri for display. Use beeos_fetch_file only for local byte analysis. `error` holds the failure reason when there is no produced output; `is_terminal` indicates whether the task has reached a final state. Do NOT call beeos_call_agent again to re-query an existing task — that creates a brand-new task.',parameters:{type:"object",properties:{taskId:{type:"string",description:"The task ID returned by a previous beeos_call_agent call."},agentId:{type:"string",description:"The target agent UUID that owns the task (the same agentId passed to beeos_call_agent). Optional when the task was created earlier in this session — it is resolved automatically."}},required:["taskId"]},async execute(t,n,s){const{taskId:r,agentId:i}=n??{};if(!r)return{content:JSON.stringify({error:"taskId is required"})};const o=i||a.resolveAgentId(r);if(!o)return{content:JSON.stringify({error:`agentId is required to query task "${r}" (it was not created in this session, so the target agent is unknown). Pass the agentId you originally called.`,task_id:r})};try{const t=`/api/v1/a2a/${encodeURIComponent(o)}`,a=await a2aFetch(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:`claw-get-${Date.now()}`,method:"GetTask",params:{id:r}}),signal:s}),n=await a.text();let i;try{i=JSON.parse(n)}catch{i={}}if(!a.ok||i.error){const t=i.error?JSON.stringify(i.error):n;return{content:JSON.stringify({error:`get task failed: ${a.status} ${t}`,task_id:r,agent_id:o})}}const c=unwrapTask(i.result);return{content:JSON.stringify(buildTaskPayload(c,r,o))}}catch(t){if(s?.aborted)throw t;return{content:JSON.stringify({error:t instanceof Error?t.message:String(t),task_id:r,agent_id:o})}}}})}
|
package/dist/a2a/tools.test.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,vi,afterEach}from"vitest";import{registerA2ATools,TaskHandleRegistry,unwrapTask,extractArtifactText,extractArtifactFiles,extractStatusText,taskState,buildTaskPayload}from"./tools.js";const AGENT_ID="d04080d1-1111-2222-3333-444455556666";function makeCfg(){return{agentGatewayUrl:"https://gw.test",agentKeys:null,logger:{info:vi.fn(),warn:vi.fn(),error:vi.fn(),debug:vi.fn()}}}function registerTools(t,e=new TaskHandleRegistry){const a=new Map;return registerA2ATools({registerTool:t=>a.set(t.name,t)},t,e),a}function jsonResponse(t,e=!0,a=200){const s=JSON.stringify(t);return{ok:e,status:a,text:async()=>s,json:async()=>JSON.parse(s)}}describe("unwrapTask",()=>{it("unwraps the v1.0 SendMessage { task } envelope",()=>{const t=unwrapTask({task:{id:"t1",status:{state:"TASK_STATE_WORKING"}}});expect(t?.id).toBe("t1")}),it("returns the bare task for v0.3 / GetTask results",()=>{const t=unwrapTask({id:"t2",status:{state:"working"}});expect(t?.id).toBe("t2")}),it("returns undefined for non-object input",()=>{expect(unwrapTask(void 0)).toBeUndefined(),expect(unwrapTask("nope")).toBeUndefined()})}),describe("extractArtifactText",()=>{it("reads v1.0 text parts ({ text } without kind)",()=>{expect(extractArtifactText({artifacts:[{parts:[{text:"hello"},{text:"world"}]}]})).toBe("hello\nworld")}),it("reads v0.3 text parts ({ kind: 'text', text })",()=>{expect(extractArtifactText({artifacts:[{parts:[{kind:"text",text:"hi"}]}]})).toBe("hi")}),it("skips non-text parts (e.g. file/data)",()=>{expect(extractArtifactText({artifacts:[{parts:[{kind:"file",url:"u"},{text:"kept"}]}]})).toBe("kept")}),it("returns undefined when there are no artifacts",()=>{expect(extractArtifactText({status:{state:"working"}})).toBeUndefined(),expect(extractArtifactText(void 0)).toBeUndefined()})}),describe("extractArtifactFiles",()=>{it("reads v1.0 flat file parts",()=>{expect(extractArtifactFiles({artifacts:[{parts:[{url:"beeos-file://file-1",filename:"screenshot.jpeg",mediaType:"image/jpeg"}]}]})).toEqual([{uri:"beeos-file://file-1",name:"screenshot.jpeg",mimeType:"image/jpeg"}])}),it("reads v0.3 nested file parts",()=>{expect(extractArtifactFiles({artifacts:[{parts:[{kind:"file",file:{uri:"beeos-file://file-2",name:"capture.png",mimeType:"image/png"}}]}]})).toEqual([{uri:"beeos-file://file-2",name:"capture.png",mimeType:"image/png"}])}),it("does not infer files from text-only beeos-file URI artifacts",()=>{expect(extractArtifactFiles({artifacts:[{parts:[{text:"beeos-file://file-3"}]}]})).toBeUndefined()})}),describe("extractStatusText",()=>{it("reads the agent status message text",()=>{expect(extractStatusText({status:{message:{parts:[{text:"boom"}]}}})).toBe("boom")}),it("returns undefined when no status message",()=>{expect(extractStatusText({status:{}})).toBeUndefined()})}),describe("taskState",()=>{it("normalizes v1.0 SCREAMING_SNAKE states",()=>{expect(taskState({status:{state:"TASK_STATE_COMPLETED"}})).toBe("completed"),expect(taskState({status:{state:"TASK_STATE_WORKING"}})).toBe("working")}),it("passes through v0.3 lowercase states",()=>{expect(taskState({status:{state:"failed"}})).toBe("failed")})}),describe("buildTaskPayload",()=>{it("surfaces produced content with the terminal state (canceled with artifact)",()=>{expect(buildTaskPayload({contextId:"ctx-1",status:{state:"TASK_STATE_CANCELED"},artifacts:[{parts:[{text:"partial work"}]}]},"t1","agent-1")).toEqual({status:"canceled",task_id:"t1",agent_id:"agent-1",context_id:"ctx-1",is_terminal:!0,result:"partial work"})}),it("reports status-message text as error when there is no artifact",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_FAILED",message:{parts:[{text:"boom"}]}}},"t2","agent-2")).toEqual({status:"failed",task_id:"t2",agent_id:"agent-2",is_terminal:!0,error:"boom"})}),it("marks a working task as non-terminal with neither result nor error",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_WORKING"}},"t3","agent-3")).toEqual({status:"working",task_id:"t3",agent_id:"agent-3",is_terminal:!1})}),it("includes result for a completed task",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"the answer"}]}]},"t4","agent-4")).toEqual({status:"completed",task_id:"t4",agent_id:"agent-4",is_terminal:!0,result:"the answer"})}),it("returns result text and structured files together",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"beeos-file://file-1"},{url:"beeos-file://file-1",filename:"screenshot.jpeg",mediaType:"image/jpeg"}]}]},"t5","agent-5")).toEqual({status:"completed",task_id:"t5",agent_id:"agent-5",is_terminal:!0,result:"beeos-file://file-1",files:[{uri:"beeos-file://file-1",name:"screenshot.jpeg",mimeType:"image/jpeg"}]})}),it("does not turn text-only beeos-file URI results into files",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"beeos-file://file-only-text"}]}]},"t6","agent-6")).toEqual({status:"completed",task_id:"t6",agent_id:"agent-6",is_terminal:!0,result:"beeos-file://file-only-text"})})}),describe("beeos_call_agent async create",()=>{afterEach(()=>{vi.unstubAllGlobals()}),it("creates the task and returns the handle (task_id, agent_id, context_id) without polling or task data",async()=>{const t=[],e=vi.fn(async(e,a)=>{const s=a?.body?JSON.parse(a.body):{};if(t.push({url:e,method:a?.method,rpcMethod:s.method}),"SendMessage"===s.method)return jsonResponse({jsonrpc:"2.0",id:s.id,result:{task:{id:"task-async-1",contextId:"c1",status:{state:"TASK_STATE_WORKING"}}}});throw new Error(`unexpected request method: ${s.method}`)});vi.stubGlobal("fetch",e);const a=registerTools(makeCfg()).get("beeos_call_agent"),s=await a.execute("tc-1",{agentId:AGENT_ID,message:"do it"}),r=JSON.parse(s.content);expect(r.status).toBe("working"),expect(r.task_id).toBe("task-async-1"),expect(r.agent_id).toBe(AGENT_ID),expect(r.context_id).toBe("c1"),expect(r.result).toBeUndefined(),expect(t).toHaveLength(1),expect(t[0].rpcMethod).toBe("SendMessage"),expect(t[0].url).toBe(`https://gw.test/api/v1/a2a/${AGENT_ID}`)}),it("registers the task so beeos_get_task can resolve the agent id",async()=>{const t=vi.fn(async(t,e)=>{const a=e?.body?JSON.parse(e.body):{};return"SendMessage"===a.method?jsonResponse({jsonrpc:"2.0",id:a.id,result:{task:{id:"task-reg-1",status:{state:"TASK_STATE_WORKING"}}}}):jsonResponse({jsonrpc:"2.0",id:a.id,result:{id:"task-reg-1",status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"done"}]}]}})});vi.stubGlobal("fetch",t);const e=new TaskHandleRegistry,a=registerTools(makeCfg(),e);await a.get("beeos_call_agent").execute("tc",{agentId:AGENT_ID,message:"do it"});const s=await a.get("beeos_get_task").execute("tc",{taskId:"task-reg-1"}),r=JSON.parse(s.content);expect(r.status).toBe("completed"),expect(r.result).toBe("done"),expect(r.agent_id).toBe(AGENT_ID)}),it("returns an error handle (with agent_id, no task_id) when create fails",async()=>{const t=vi.fn(async(t,e)=>jsonResponse({jsonrpc:"2.0",id:(e?.body?JSON.parse(e.body):{}).id,error:{code:-32e3,message:"boom"}},!1,500));vi.stubGlobal("fetch",t);const e=registerTools(makeCfg()).get("beeos_call_agent"),a=await e.execute("tc",{agentId:AGENT_ID,message:"do it"}),s=JSON.parse(a.content);expect(s.error).toContain("send task failed"),expect(s.agent_id).toBe(AGENT_ID),expect(s.task_id).toBeUndefined()})}),describe("beeos_get_task",()=>{function t(t){const e=[],a=vi.fn(async(a,s)=>{const r=s?.body?JSON.parse(s.body):{};if(e.push({url:a,method:s?.method,rpcMethod:r.method,params:r.params}),"GetTask"!==r.method)throw new Error(`unexpected method: ${r.method}`);return jsonResponse({jsonrpc:"2.0",id:r.id,result:t})});return vi.stubGlobal("fetch",a),e}afterEach(()=>{vi.unstubAllGlobals()}),it("returns the data of a completed task and queries the right endpoint",async()=>{const e=t({id:"task-1",contextId:"ctx-1",status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"the answer"}]}]}),a=registerTools(makeCfg()).get("beeos_get_task"),s=await a.execute("tc",{taskId:"task-1",agentId:AGENT_ID}),r=JSON.parse(s.content);expect(r.status).toBe("completed"),expect(r.task_id).toBe("task-1"),expect(r.agent_id).toBe(AGENT_ID),expect(r.context_id).toBe("ctx-1"),expect(r.is_terminal).toBe(!0),expect(r.result).toBe("the answer"),expect(e).toHaveLength(1),expect(e[0].method).toBe("POST"),expect(e[0].url).toBe(`https://gw.test/api/v1/a2a/${AGENT_ID}`),expect(e[0].params.id).toBe("task-1")}),it("surfaces partial output AND the terminal state for a canceled task that still produced an artifact",async()=>{t({id:"task-cx",status:{state:"TASK_STATE_CANCELED"},artifacts:[{parts:[{text:"partial plan"}]}]});const e=registerTools(makeCfg()).get("beeos_get_task"),a=await e.execute("tc",{taskId:"task-cx",agentId:AGENT_ID}),s=JSON.parse(a.content);expect(s.status).toBe("canceled"),expect(s.task_id).toBe("task-cx"),expect(s.result).toBe("partial plan")}),it("returns an error for a terminal task with no produced content",async()=>{t({id:"task-to",status:{state:"TASK_STATE_FAILED",message:{parts:[{text:"boom"}]}}});const e=registerTools(makeCfg()).get("beeos_get_task"),a=await e.execute("tc",{taskId:"task-to",agentId:AGENT_ID}),s=JSON.parse(a.content);expect(s.error).toBe("boom"),expect(s.task_id).toBe("task-to")}),it("reports a still-running task as working",async()=>{t({id:"task-w",status:{state:"TASK_STATE_WORKING"}});const e=registerTools(makeCfg()).get("beeos_get_task"),a=await e.execute("tc",{taskId:"task-w",agentId:AGENT_ID}),s=JSON.parse(a.content);expect(s.status).toBe("working"),expect(s.task_id).toBe("task-w")}),it("resolves agentId from the session registry when omitted",async()=>{const e=new TaskHandleRegistry;e.create("task-reg",AGENT_ID);const a=t({id:"task-reg",status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"ok"}]}]}),s=registerTools(makeCfg(),e).get("beeos_get_task"),r=await s.execute("tc",{taskId:"task-reg"}),o=JSON.parse(r.content);expect(o.status).toBe("completed"),expect(o.result).toBe("ok"),expect(o.agent_id).toBe(AGENT_ID),expect(a[0].url).toBe(`https://gw.test/api/v1/a2a/${AGENT_ID}`)}),it("errors when agentId is neither passed nor resolvable",async()=>{const t=vi.fn();vi.stubGlobal("fetch",t);const e=registerTools(makeCfg()).get("beeos_get_task"),a=await e.execute("tc",{taskId:"unknown-task"}),s=JSON.parse(a.content);expect(s.error).toContain("agentId is required"),expect(t).not.toHaveBeenCalled()})});
|
|
1
|
+
import{describe,it,expect,vi,afterEach}from"vitest";import{registerA2ATools,TaskHandleRegistry,unwrapTask,extractArtifactText,extractArtifactFiles,extractStatusText,taskState,buildTaskPayload}from"./tools.js";const AGENT_ID="d04080d1-1111-2222-3333-444455556666";function makeCfg(){return{agentGatewayUrl:"https://gw.test",agentKeys:null,logger:{info:vi.fn(),warn:vi.fn(),error:vi.fn(),debug:vi.fn()}}}function registerTools(t,e=new TaskHandleRegistry){const s=new Map;return registerA2ATools({registerTool:t=>s.set(t.name,t)},t,e),s}function jsonResponse(t,e=!0,s=200){const a=JSON.stringify(t);return{ok:e,status:s,text:async()=>a,json:async()=>JSON.parse(a)}}describe("unwrapTask",()=>{it("unwraps the v1.0 SendMessage { task } envelope",()=>{const t=unwrapTask({task:{id:"t1",status:{state:"TASK_STATE_WORKING"}}});expect(t?.id).toBe("t1")}),it("returns the bare task for v0.3 / GetTask results",()=>{const t=unwrapTask({id:"t2",status:{state:"working"}});expect(t?.id).toBe("t2")}),it("returns undefined for non-object input",()=>{expect(unwrapTask(void 0)).toBeUndefined(),expect(unwrapTask("nope")).toBeUndefined()})}),describe("extractArtifactText",()=>{it("reads v1.0 text parts ({ text } without kind)",()=>{expect(extractArtifactText({artifacts:[{parts:[{text:"hello"},{text:"world"}]}]})).toBe("hello\nworld")}),it("reads v0.3 text parts ({ kind: 'text', text })",()=>{expect(extractArtifactText({artifacts:[{parts:[{kind:"text",text:"hi"}]}]})).toBe("hi")}),it("skips non-text parts (e.g. file/data)",()=>{expect(extractArtifactText({artifacts:[{parts:[{kind:"file",url:"u"},{text:"kept"}]}]})).toBe("kept")}),it("returns undefined when there are no artifacts",()=>{expect(extractArtifactText({status:{state:"working"}})).toBeUndefined(),expect(extractArtifactText(void 0)).toBeUndefined()})}),describe("extractArtifactFiles",()=>{it("reads v1.0 flat file parts",()=>{expect(extractArtifactFiles({artifacts:[{parts:[{url:"beeos-file://file-1",filename:"screenshot.jpeg",mediaType:"image/jpeg"}]}]})).toEqual([{uri:"beeos-file://file-1",name:"screenshot.jpeg",mimeType:"image/jpeg"}])}),it("reads v0.3 nested file parts",()=>{expect(extractArtifactFiles({artifacts:[{parts:[{kind:"file",file:{uri:"beeos-file://file-2",name:"capture.png",mimeType:"image/png"}}]}]})).toEqual([{uri:"beeos-file://file-2",name:"capture.png",mimeType:"image/png"}])}),it("does not infer files from text-only beeos-file URI artifacts",()=>{expect(extractArtifactFiles({artifacts:[{parts:[{text:"beeos-file://file-3"}]}]})).toBeUndefined()})}),describe("extractStatusText",()=>{it("reads the agent status message text",()=>{expect(extractStatusText({status:{message:{parts:[{text:"boom"}]}}})).toBe("boom")}),it("returns undefined when no status message",()=>{expect(extractStatusText({status:{}})).toBeUndefined()})}),describe("taskState",()=>{it("normalizes v1.0 SCREAMING_SNAKE states",()=>{expect(taskState({status:{state:"TASK_STATE_COMPLETED"}})).toBe("completed"),expect(taskState({status:{state:"TASK_STATE_WORKING"}})).toBe("working")}),it("passes through v0.3 lowercase states",()=>{expect(taskState({status:{state:"failed"}})).toBe("failed")})}),describe("buildTaskPayload",()=>{it("surfaces produced content with the terminal state (canceled with artifact)",()=>{expect(buildTaskPayload({contextId:"ctx-1",status:{state:"TASK_STATE_CANCELED"},artifacts:[{parts:[{text:"partial work"}]}]},"t1","agent-1")).toEqual({status:"canceled",task_id:"t1",agent_id:"agent-1",context_id:"ctx-1",is_terminal:!0,result:"partial work"})}),it("reports status-message text as error when there is no artifact",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_FAILED",message:{parts:[{text:"boom"}]}}},"t2","agent-2")).toEqual({status:"failed",task_id:"t2",agent_id:"agent-2",is_terminal:!0,error:"boom"})}),it("marks a working task as non-terminal with neither result nor error",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_WORKING"}},"t3","agent-3")).toEqual({status:"working",task_id:"t3",agent_id:"agent-3",is_terminal:!1})}),it("includes result for a completed task",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"the answer"}]}]},"t4","agent-4")).toEqual({status:"completed",task_id:"t4",agent_id:"agent-4",is_terminal:!0,result:"the answer"})}),it("returns result text and structured files together",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"beeos-file://file-1"},{url:"beeos-file://file-1",filename:"screenshot.jpeg",mediaType:"image/jpeg"}]}]},"t5","agent-5")).toEqual({status:"completed",task_id:"t5",agent_id:"agent-5",is_terminal:!0,result:"beeos-file://file-1",files:[{uri:"beeos-file://file-1",name:"screenshot.jpeg",mimeType:"image/jpeg"}]})}),it("does not turn text-only beeos-file URI results into files",()=>{expect(buildTaskPayload({status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"beeos-file://file-only-text"}]}]},"t6","agent-6")).toEqual({status:"completed",task_id:"t6",agent_id:"agent-6",is_terminal:!0,result:"beeos-file://file-only-text"})})}),describe("beeos_call_agent async create",()=>{afterEach(()=>{vi.unstubAllGlobals()}),it("creates the task and returns the handle (task_id, agent_id, context_id) without polling or task data",async()=>{const t=[],e=vi.fn(async(e,s)=>{const a=s?.body?JSON.parse(s.body):{};if(t.push({url:e,method:s?.method,rpcMethod:a.method}),"SendMessage"===a.method)return jsonResponse({jsonrpc:"2.0",id:a.id,result:{task:{id:"task-async-1",contextId:"c1",status:{state:"TASK_STATE_WORKING"}}}});throw new Error(`unexpected request method: ${a.method}`)});vi.stubGlobal("fetch",e);const s=registerTools(makeCfg()).get("beeos_call_agent"),a=await s.execute("tc-1",{agentId:AGENT_ID,message:"do it"}),o=JSON.parse(a.content);expect(o.status).toBe("working"),expect(o.task_id).toBe("task-async-1"),expect(o.agent_id).toBe(AGENT_ID),expect(o.context_id).toBe("c1"),expect(o.result).toBeUndefined(),expect(t).toHaveLength(1),expect(t[0].rpcMethod).toBe("SendMessage"),expect(t[0].url).toBe(`https://gw.test/api/v1/a2a/${AGENT_ID}`)}),it("registers the task so beeos_get_task can resolve the agent id",async()=>{const t=vi.fn(async(t,e)=>{const s=e?.body?JSON.parse(e.body):{};return"SendMessage"===s.method?jsonResponse({jsonrpc:"2.0",id:s.id,result:{task:{id:"task-reg-1",status:{state:"TASK_STATE_WORKING"}}}}):jsonResponse({jsonrpc:"2.0",id:s.id,result:{id:"task-reg-1",status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"done"}]}]}})});vi.stubGlobal("fetch",t);const e=new TaskHandleRegistry,s=registerTools(makeCfg(),e);await s.get("beeos_call_agent").execute("tc",{agentId:AGENT_ID,message:"do it"});const a=await s.get("beeos_get_task").execute("tc",{taskId:"task-reg-1"}),o=JSON.parse(a.content);expect(o.status).toBe("completed"),expect(o.result).toBe("done"),expect(o.agent_id).toBe(AGENT_ID)}),it("returns an error handle (with agent_id, no task_id) when create fails",async()=>{const t=vi.fn(async(t,e)=>jsonResponse({jsonrpc:"2.0",id:(e?.body?JSON.parse(e.body):{}).id,error:{code:-32e3,message:"boom"}},!1,500));vi.stubGlobal("fetch",t);const e=registerTools(makeCfg()).get("beeos_call_agent"),s=await e.execute("tc",{agentId:AGENT_ID,message:"do it"}),a=JSON.parse(s.content);expect(a.error).toContain("send task failed"),expect(a.agent_id).toBe(AGENT_ID),expect(a.task_id).toBeUndefined()})}),describe("beeos_get_task",()=>{function t(t){const e=[],s=vi.fn(async(s,a)=>{const o=a?.body?JSON.parse(a.body):{};if(e.push({url:s,method:a?.method,rpcMethod:o.method,params:o.params}),"GetTask"!==o.method)throw new Error(`unexpected method: ${o.method}`);return jsonResponse({jsonrpc:"2.0",id:o.id,result:t})});return vi.stubGlobal("fetch",s),e}afterEach(()=>{vi.unstubAllGlobals()}),it("describes structured files as runtime-presented artifacts, not Markdown or MEDIA",()=>{const t=registerTools(makeCfg()).get("beeos_get_task").description??"";expect(t).toContain("runtime displays image files"),expect(t).toContain("chat attachments"),expect(t).toContain("Do not output MEDIA:"),expect(t).not.toContain("![")}),it("returns the data of a completed task and queries the right endpoint",async()=>{const e=t({id:"task-1",contextId:"ctx-1",status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"the answer"}]}]}),s=registerTools(makeCfg()).get("beeos_get_task"),a=await s.execute("tc",{taskId:"task-1",agentId:AGENT_ID}),o=JSON.parse(a.content);expect(o.status).toBe("completed"),expect(o.task_id).toBe("task-1"),expect(o.agent_id).toBe(AGENT_ID),expect(o.context_id).toBe("ctx-1"),expect(o.is_terminal).toBe(!0),expect(o.result).toBe("the answer"),expect(e).toHaveLength(1),expect(e[0].method).toBe("POST"),expect(e[0].url).toBe(`https://gw.test/api/v1/a2a/${AGENT_ID}`),expect(e[0].params.id).toBe("task-1")}),it("surfaces partial output AND the terminal state for a canceled task that still produced an artifact",async()=>{t({id:"task-cx",status:{state:"TASK_STATE_CANCELED"},artifacts:[{parts:[{text:"partial plan"}]}]});const e=registerTools(makeCfg()).get("beeos_get_task"),s=await e.execute("tc",{taskId:"task-cx",agentId:AGENT_ID}),a=JSON.parse(s.content);expect(a.status).toBe("canceled"),expect(a.task_id).toBe("task-cx"),expect(a.result).toBe("partial plan")}),it("returns an error for a terminal task with no produced content",async()=>{t({id:"task-to",status:{state:"TASK_STATE_FAILED",message:{parts:[{text:"boom"}]}}});const e=registerTools(makeCfg()).get("beeos_get_task"),s=await e.execute("tc",{taskId:"task-to",agentId:AGENT_ID}),a=JSON.parse(s.content);expect(a.error).toBe("boom"),expect(a.task_id).toBe("task-to")}),it("reports a still-running task as working",async()=>{t({id:"task-w",status:{state:"TASK_STATE_WORKING"}});const e=registerTools(makeCfg()).get("beeos_get_task"),s=await e.execute("tc",{taskId:"task-w",agentId:AGENT_ID}),a=JSON.parse(s.content);expect(a.status).toBe("working"),expect(a.task_id).toBe("task-w")}),it("resolves agentId from the session registry when omitted",async()=>{const e=new TaskHandleRegistry;e.create("task-reg",AGENT_ID);const s=t({id:"task-reg",status:{state:"TASK_STATE_COMPLETED"},artifacts:[{parts:[{text:"ok"}]}]}),a=registerTools(makeCfg(),e).get("beeos_get_task"),o=await a.execute("tc",{taskId:"task-reg"}),r=JSON.parse(o.content);expect(r.status).toBe("completed"),expect(r.result).toBe("ok"),expect(r.agent_id).toBe(AGENT_ID),expect(s[0].url).toBe(`https://gw.test/api/v1/a2a/${AGENT_ID}`)}),it("errors when agentId is neither passed nor resolvable",async()=>{const t=vi.fn();vi.stubGlobal("fetch",t);const e=registerTools(makeCfg()).get("beeos_get_task"),s=await e.execute("tc",{taskId:"unknown-task"}),a=JSON.parse(s.content);expect(a.error).toContain("agentId is required"),expect(t).not.toHaveBeenCalled()})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,mkdirSync,readdirSync,statSync,writeFileSync}from"node:fs";import{join,basename}from"node:path";
|
|
1
|
+
import{existsSync,mkdirSync,readdirSync,statSync,writeFileSync}from"node:fs";import{join,basename}from"node:path";import{parseBeeosFileUri}from"../files/beeos-file-uri.js";const MAX_FILE_NAME_LENGTH=120,DOWNLOAD_TIMEOUT_MS=12e4,MAX_CONCURRENT_RESOLVES=3,OPENCLAW_HOME=process.env.OPENCLAW_HOME||join(process.env.HOME||"/home/node",".openclaw"),UPLOAD_DIR=join(OPENCLAW_HOME,"workspace","uploads"),RESOURCE_CACHE_DIR=join(OPENCLAW_HOME,"workspace","resource_cache");export{parseBeeosFileUri}from"../files/beeos-file-uri.js";export class BeeosFileResolver{agentGatewayUrl;agentFetch;writeObs;constructor(e){this.agentGatewayUrl=e.agentGatewayUrl,this.agentFetch=e.agentFetch,this.writeObs=e.writeObs}buildResolutionPlan(e){const t=[],a=new Map;for(let i=0;i<e.length;i++){const o=e[i];if("resource_link"!==o.type||!o.uri)continue;const r=parseBeeosFileUri(o.uri);r.fileId&&(t.push({blockIndex:i,uri:o.uri,fileId:r.fileId,name:o.title??o.name}),a.set(o.uri,r.fileId))}return{refs:t,fileIds:[...new Set(a.values())],fileIdByUri:a}}async resolveMetadataForPrompt(e){if(0===e.fileIds.length)return new Map;const t=new Map,a=e.fileIds.map(e=>async()=>{const a=await this.resolveOneFile(e);t.set(e,a)});await runWithConcurrency(a,3);const i=new Map;for(const[a,o]of e.fileIdByUri.entries()){const e=t.get(o);e&&i.set(a,e)}return i}async resolveOneFile(e){const t=Date.now(),a=this.findCachedFile(e);if(a)return this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"cache_hit",severity:"debug",payload:{fileId:e,localPath:a.localPath}}),{status:"resolved",fileId:e,name:a.localFileName,mimeType:"application/octet-stream",localPath:a.localPath,localFileName:a.localFileName,localSizeBytes:a.localSizeBytes,localCacheHit:!0,downloadUrl:""};const i=`${this.agentGatewayUrl}/api/v1/agent/files/${encodeURIComponent(e)}/resolve`;this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"metadata_request",severity:"info",payload:{fileId:e,url:i}});const o=new AbortController,r=setTimeout(()=>o.abort(),12e4);"object"==typeof r&&"unref"in r&&r.unref();try{const a=await this.agentFetch(i,{method:"GET",signal:o.signal});if(!a.ok){const i=a.status>=500?"http_5xx":"http_4xx",o=a.status>=500||429===a.status;return this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"metadata_failed",severity:"warn",payload:{fileId:e,httpStatus:a.status,code:i,durationMs:Date.now()-t}}),{status:"resolve_failed",fileId:e,code:i,message:`resolve request failed with status ${a.status}`,retriable:o,httpStatus:a.status}}let r;try{r=await a.json()}catch{return this.makeFailure(e,"invalid_response","resolve response is not valid json",!1)}const l=asString(r.fileName),s=asString(r.mimeType),n=asString(r.downloadUrl),c="number"==typeof r.size?r.size:void 0;if(!n)return this.makeFailure(e,"missing_download_url","resolve response missing downloadUrl",!1,l);this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"metadata_ok",severity:"debug",payload:{fileId:e,fileName:l,mimeType:s,size:c,durationMs:Date.now()-t}});const d=await this.ensureFileDownloaded({fileId:e,name:l||e,downloadUrl:n});return"resolve_failed"===d.status?d:{status:"resolved",fileId:e,name:l||d.localFileName,mimeType:s||"application/octet-stream",size:c,downloadUrl:n,localPath:d.localPath,localFileName:d.localFileName,localSizeBytes:d.localSizeBytes,localCacheHit:!1}}catch(t){const a=t instanceof Error&&"AbortError"===t.name,i=a?"timeout":"network_error",o=a?"resolve request timed out after 120000ms":`resolve request failed: ${t instanceof Error?t.message:String(t)}`;return this.makeFailure(e,i,o,!0)}finally{clearTimeout(r)}}findCachedFile(e){for(const t of[UPLOAD_DIR,RESOURCE_CACHE_DIR]){const a=this.findFileByPrefix(t,e);if(a)return a}}findFileByPrefix(e,t){if(!existsSync(e))return;const a=`${t}_`;let i;try{i=readdirSync(e).sort()}catch{return}for(const t of i){if(!t.startsWith(a))continue;const i=join(e,t);try{const e=statSync(i);if(e.isFile()&&e.size>0)return{localPath:i,localFileName:t,localSizeBytes:e.size}}catch{continue}}}async ensureFileDownloaded(e){const t=sanitizeFileName(e.name),a=`${e.fileId}_${t}`,i=join(RESOURCE_CACHE_DIR,a);try{mkdirSync(RESOURCE_CACHE_DIR,{recursive:!0})}catch(t){return this.makeFailure(e.fileId,"fs_error",`failed to create cache dir: ${String(t)}`,!1,e.name)}const o=this.findFileByPrefix(RESOURCE_CACHE_DIR,e.fileId);if(o)return{status:"resolved",fileId:e.fileId,name:e.name,mimeType:"application/octet-stream",downloadUrl:e.downloadUrl,localPath:o.localPath,localFileName:o.localFileName,localSizeBytes:o.localSizeBytes,localCacheHit:!0};const r=new AbortController,l=setTimeout(()=>r.abort(),12e4);"object"==typeof l&&"unref"in l&&l.unref();try{const t=await this.agentFetch(e.downloadUrl,{method:"GET",signal:r.signal});if(!t.ok){const a=t.status>=500?"http_5xx":"http_4xx";return this.makeFailure(e.fileId,a,`file download failed with status ${t.status}`,t.status>=500||429===t.status,e.name,t.status)}let o;try{o=Buffer.from(await t.arrayBuffer())}catch{return this.makeFailure(e.fileId,"network_error","failed to read download response body",!0,e.name)}if(0===o.byteLength)return this.makeFailure(e.fileId,"invalid_response","downloaded file is empty",!1,e.name);try{writeFileSync(i,o)}catch(t){return this.makeFailure(e.fileId,"fs_error",`failed to write file: ${String(t)}`,!1,e.name)}let l=o.byteLength;try{const e=statSync(i);e.isFile()&&e.size>0&&(l=e.size)}catch{}return this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"download_ok",severity:"info",payload:{fileId:e.fileId,localPath:i,localSizeBytes:l}}),{status:"resolved",fileId:e.fileId,name:e.name,mimeType:"application/octet-stream",downloadUrl:e.downloadUrl,localPath:i,localFileName:a,localSizeBytes:l,localCacheHit:!1}}catch(t){const a=t instanceof Error&&"AbortError"===t.name,i=a?"timeout":"network_error",o=a?"file download timed out after 120000ms":`file download failed: ${t instanceof Error?t.message:String(t)}`;return this.makeFailure(e.fileId,i,o,!0,e.name)}finally{clearTimeout(l)}}makeFailure(e,t,a,i,o,r){return this.writeObs?.({component:"beeos-file-resolver",domain:"file",name:"resolve_failed",severity:"warn",payload:{fileId:e,code:t,message:a,retriable:i,...void 0!==r?{httpStatus:r}:{}}}),{status:"resolve_failed",fileId:e,...o?{name:o}:{},code:t,message:a,retriable:i,...void 0!==r?{httpStatus:r}:{}}}}function sanitizeFileName(e){return basename(e).trim().replace(/[\u0000-\u001f\u007f]/g,"").replace(/[\\/]+/g,"_").replace(/[^\p{L}\p{N}._-]+/gu,"_").replace(/_+/g,"_").replace(/^\.+/,"").replace(/^_+|_+$/g,"").slice(0,120)||"file"}function asString(e){if("string"==typeof e&&e.trim())return e.trim()}async function runWithConcurrency(e,t){let a=0;async function i(){for(;a<e.length;){const t=a++;await e[t]()}}const o=[];for(let a=0;a<Math.min(t,e.length);a++)o.push(i());await Promise.all(o)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpGatewayBridgeCore,normalizeAgentId}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";function makeBridge(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},t=new AcpGatewaySessionState(e),a={sendResult:vi.fn(),sendAcpError:vi.fn(),sendSessionUpdate:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},n={isConnected:!0,request:vi.fn(async(e,t)=>"agents.create"===e?{ok:!0,agentId:t.name,name:t.name,workspace:t.workspace}:"agents.update"===e?{ok:!0,agentId:t.agentId}:"agents.files.set"===e?{ok:!0,agentId:t.agentId,workspace:"/ws",file:{name:t.name}}:{})},
|
|
1
|
+
import{describe,it,expect,beforeEach,vi}from"vitest";import{AcpGatewayBridgeCore,normalizeAgentId}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";function makeBridge(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},t=new AcpGatewaySessionState(e),a={sendResult:vi.fn(),sendAcpError:vi.fn(),sendSessionUpdate:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},n={isConnected:!0,request:vi.fn(async(e,t)=>"agents.create"===e?{ok:!0,agentId:t.name,name:t.name,workspace:t.workspace}:"agents.update"===e?{ok:!0,agentId:t.agentId}:"agents.files.set"===e?{ok:!0,agentId:t.agentId,workspace:"/ws",file:{name:t.name}}:{})},s=vi.fn(async()=>{const e=n.request.mock.calls.find(e=>"agents.create"===e[0]),t=e?e[1].name:void 0;t&&r.setAgentMapping(new Map([[t,{id:`agent_platform_${t}`}]]))}),r=new AcpGatewayBridgeCore({state:t,transport:a,config:{gateway:{agentId:"main"}},logger:e,writeObs:vi.fn(),getGateway:()=>n,instanceId:"test-instance",thirdPartyChannels:new Set,triggerAgentSync:s});return{bridge:r,state:t,transport:a,gateway:n,logger:e,triggerAgentSync:s}}async function callAgentCreate(e,t){const a={jsonrpc:"2.0",id:1,method:"agent/create",params:t};await e.bridge.handleAgentCreate(a),await Promise.resolve();const n=e.transport.sendResult.mock.calls[0]?.[1];if(!n)throw new Error("agent/create did not call sendResult");return n}describe("handleAgentCreate",()=>{let e;beforeEach(()=>{e=makeBridge()}),it("rejects an empty name with InvalidParams",async()=>{await e.bridge.handleAgentCreate({jsonrpc:"2.0",id:1,method:"agent/create",params:{name:" "}}),expect(e.transport.sendAcpError).toHaveBeenCalledTimes(1),expect(e.transport.sendResult).not.toHaveBeenCalled()}),it("synthesizes a random id and re-applies the display name for an ASCII name",async()=>{const t=await callAgentCreate(e,{name:"coder"});expect(t.agentId).toMatch(/^agent-[0-9a-f]{12}$/),expect(t.agentId).not.toBe("coder");const a=e.gateway.request.mock.calls.find(e=>"agents.create"===e[0]);expect((a?.[1]).name).toBe(t.agentId),expect((a?.[1]).workspace).toContain(`workspace-${t.agentId}`);const n=e.gateway.request.mock.calls.find(e=>"agents.update"===e[0]);expect(n?.[1]).toMatchObject({agentId:t.agentId,name:"coder"}),expect(t.platformAgentId).toBe(`agent_platform_${t.agentId}`)}),it("synthesizes a random id and re-applies the display name for a pure-Chinese name",async()=>{expect(normalizeAgentId("助手")).toBe("main");const t=await callAgentCreate(e,{name:"助手"});expect(t.agentId).not.toBe("main"),expect(t.agentId).toMatch(/^agent-[0-9a-f]{12}$/);const a=e.gateway.request.mock.calls.find(e=>"agents.create"===e[0]);expect((a?.[1]).name).toBe(t.agentId);const n=e.gateway.request.mock.calls.find(e=>"agents.update"===e[0]);expect(n?.[1]).toMatchObject({agentId:t.agentId,name:"助手"})}),it("seeds bootstrap files but refuses IDENTITY.md",async()=>{await callAgentCreate(e,{name:"writer",files:{"SOUL.md":"you are a writer","IDENTITY.md":"should be ignored"}});const t=e.gateway.request.mock.calls.filter(e=>"agents.files.set"===e[0]).map(e=>e[1].name);expect(t).toContain("SOUL.md"),expect(t).not.toContain("IDENTITY.md")}),it("passes model and identity emoji/avatar through to agents.create",async()=>{await callAgentCreate(e,{name:"coder",model:"deepseek-chat",identity:{emoji:"🤖",avatar:"https://x/y.png"}});const t=e.gateway.request.mock.calls.find(e=>"agents.create"===e[0]);expect(t?.[1]).toMatchObject({model:"deepseek-chat",emoji:"🤖",avatar:"https://x/y.png"})})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import AdmZip from"adm-zip";import{existsSync,mkdirSync,mkdtempSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";import{afterEach,beforeEach,describe,expect,it,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";function buildPackage(e){const
|
|
1
|
+
import AdmZip from"adm-zip";import{existsSync,mkdirSync,mkdtempSync,readFileSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";import{afterEach,beforeEach,describe,expect,it,vi}from"vitest";import{AcpGatewayBridgeCore}from"./bridge-core.js";import{AcpGatewaySessionState}from"./session-state.js";function buildPackage(e){const t=new AdmZip,a={schema_version:1,slug:e.slug,display_name:e.displayName,version:"1.0.0",vibe:e.vibe??"",skills:(e.skills??[]).map(e=>({slug:e,version:"1.0.0"}))};t.addFile("manifest.json",Buffer.from(JSON.stringify(a))),t.addFile("workspace/SOUL.md",Buffer.from(`# SOUL of ${e.slug}\n`)),t.addFile("workspace/AGENTS.md",Buffer.from(`# AGENTS of ${e.slug}\n`));for(const a of e.skills??[])t.addFile(`workspace/skills/${a}/SKILL.md`,Buffer.from(`# skill ${a} for ${e.slug}\n`));return t.toBuffer()}function stubFetch(e){vi.stubGlobal("fetch",vi.fn(async()=>{if(Buffer.isBuffer(e)){const t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return{ok:!0,status:200,arrayBuffer:async()=>t}}return{ok:!1,status:e.status,arrayBuffer:async()=>new ArrayBuffer(0)}}))}function createHarness(){const e={info:vi.fn(),warn:vi.fn(),debug:vi.fn(),error:vi.fn()},t=new AcpGatewaySessionState(e),a=[],s=new Map,n=e=>{const t=s.get(e);if(!t)return;const a=["# IDENTITY.md","",`- Name: ${t.name}`];t.emoji&&a.push(`- Emoji: ${t.emoji}`),writeFileSync(join(t.workspace,"IDENTITY.md"),a.join("\n")+"\n")},r={isConnected:!0,request:vi.fn(async(e,t)=>{if(a.push({method:e,params:t}),"agents.create"===e){const e=t.workspace;mkdirSync(e,{recursive:!0});const a=String(t.name);return s.set(a,{workspace:e,name:a,emoji:t.emoji?String(t.emoji):void 0}),n(a),{ok:!0,agentId:a,workspace:e}}if("agents.update"===e){const e=String(t.agentId),a=s.get(e);return a&&(t.name&&(a.name=String(t.name)),t.emoji&&(a.emoji=String(t.emoji)),n(e)),{ok:!0}}return"agents.list"===e?{agents:[]}:{ok:!0}})},i={sendResult:vi.fn(),sendAcpError:vi.fn(),sendSessionUpdate:vi.fn(),sendNotification:vi.fn(),resetSessionUpdateCount:vi.fn(),setSessionUpdateObserver:vi.fn(),isReady:()=>!0,get forwardControl(){return{forwardThinking:!0,forwardToolCalls:!0}}},o=vi.fn(async()=>{});return{bridge:new AcpGatewayBridgeCore({state:t,transport:i,config:{gateway:{agentId:"main"}},logger:e,writeObs:vi.fn(),getGateway:()=>r,instanceId:"test-instance",thirdPartyChannels:new Set,triggerAgentSync:o}),gateway:r,transport:i,calls:a}}function applyMsg(e,t){return{jsonrpc:"2.0",id:e,method:"agent/applyTemplate",params:t}}let home;beforeEach(()=>{home=mkdtempSync(join(tmpdir(),"applytpl-home-")),process.env.OPENCLAW_HOME=home}),afterEach(()=>{vi.unstubAllGlobals(),delete process.env.OPENCLAW_HOME,rmSync(home,{recursive:!0,force:!0})}),describe("agent/applyTemplate — live download → unzip → merge into isolated workspace",()=>{it("materializes bootstrap + skills into a unique workspace-<agentId> folder",async()=>{stubFetch(buildPackage({slug:"litigation-advisor",displayName:"诉讼纠纷顾问",vibe:"法条不瞎背",skills:["legal-research","case-analysis"]}));const{bridge:e,transport:t}=createHarness();await e.handleRequest(applyMsg(1,{name:"诉讼纠纷顾问",packageUrl:"https://example.com/p.zip",identity:{emoji:"⚖️"}})),expect(t.sendAcpError).not.toHaveBeenCalled();const a=t.sendResult.mock.calls[0][1];expect(a.agentId).toMatch(/^agent-[0-9a-f]{12}$/),expect(a.workspace).toBe(join(home,`workspace-${a.agentId}`)),expect(readFileSync(join(a.workspace,"SOUL.md"),"utf8")).toContain("SOUL of litigation-advisor"),expect(existsSync(join(a.workspace,"AGENTS.md"))).toBe(!0),expect(existsSync(join(a.workspace,"skills/legal-research/SKILL.md"))).toBe(!0),expect(existsSync(join(a.workspace,"skills/case-analysis/SKILL.md"))).toBe(!0);const s=readFileSync(join(a.workspace,"IDENTITY.md"),"utf8");expect(s).toContain("诉讼纠纷顾问"),expect(s).toContain("⚖️")}),it("keeps multiple agents in separate folders with no cross-contamination",async()=>{const{bridge:e,transport:t}=createHarness();stubFetch(buildPackage({slug:"litigation-advisor",displayName:"诉讼纠纷顾问",skills:["legal-research"]})),await e.handleRequest(applyMsg(1,{name:"诉讼纠纷顾问",packageUrl:"https://x/a.zip"}));const a=t.sendResult.mock.calls[0][1];stubFetch(buildPackage({slug:"tax-advisor",displayName:"财税顾问",skills:["tax-filing"]})),await e.handleRequest(applyMsg(2,{name:"财税顾问",packageUrl:"https://x/b.zip"}));const s=t.sendResult.mock.calls[1][1];expect(a.workspace).not.toBe(s.workspace),expect(existsSync(join(a.workspace,"skills/legal-research/SKILL.md"))).toBe(!0),expect(existsSync(join(a.workspace,"skills/tax-filing/SKILL.md"))).toBe(!1),expect(existsSync(join(s.workspace,"skills/tax-filing/SKILL.md"))).toBe(!0),expect(existsSync(join(s.workspace,"skills/legal-research/SKILL.md"))).toBe(!1)}),it("allows duplicate names: same name yields distinct random ids and folders",async()=>{const{bridge:e,transport:t}=createHarness();stubFetch(buildPackage({slug:"researcher",displayName:"Researcher",skills:["search"]})),await e.handleRequest(applyMsg(1,{name:"researcher",packageUrl:"https://x/a.zip"}));const a=t.sendResult.mock.calls[0][1];stubFetch(buildPackage({slug:"researcher",displayName:"Researcher",skills:["search"]})),await e.handleRequest(applyMsg(2,{name:"researcher",packageUrl:"https://x/b.zip"}));const s=t.sendResult.mock.calls[1][1];expect(a.agentId).toMatch(/^agent-[0-9a-f]{12}$/),expect(s.agentId).toMatch(/^agent-[0-9a-f]{12}$/),expect(a.agentId).not.toBe(s.agentId),expect(a.workspace).not.toBe(s.workspace)}),it("rejects a malformed package without creating an agent (fail-fast)",async()=>{stubFetch(Buffer.from("this is not a zip"));const{bridge:e,transport:t,calls:a}=createHarness();await e.handleRequest(applyMsg(1,{name:"诉讼纠纷顾问",packageUrl:"https://x/bad.zip"})),expect(t.sendResult).not.toHaveBeenCalled(),expect(t.sendAcpError).toHaveBeenCalled(),expect(a.find(e=>"agents.create"===e.method)).toBeUndefined()}),it("surfaces a download failure as an error",async()=>{stubFetch({ok:!1,status:403});const{bridge:e,transport:t}=createHarness();await e.handleRequest(applyMsg(1,{name:"诉讼纠纷顾问",packageUrl:"https://x/denied.zip"})),expect(t.sendResult).not.toHaveBeenCalled(),expect(t.sendAcpError).toHaveBeenCalled()})});
|