@vibetonomy/agent 1.5.34 → 1.5.36
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/bridge/dist/index.js +8 -8
- package/package.json +6 -6
package/bridge/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{createInterface as
|
|
1
|
+
import{createInterface as Ie}from"node:readline";import{readdir as te,readFile as oe,rm as _e,stat as he}from"node:fs/promises";import{join as R,basename as Ne,resolve as ee}from"node:path";import{homedir as ke}from"node:os";function V(t,e,s){if(e.session_id&&typeof e.session_id=="string"&&e.session_id!==t.cliSessionId&&(t.cliSessionId=e.session_id,s({type:"session_id",cliSessionId:t.cliSessionId,...t.relaySessionId?{relaySessionId:t.relaySessionId}:{},...t.sessionName?{sessionName:t.sessionName}:{}})),e.uuid&&typeof e.uuid=="string"&&(e.type==="user"&&!e.parent_tool_use_id?s({type:"message_uuid",uuid:e.uuid,messageType:"user"}):e.type==="assistant"&&s({type:"message_uuid",uuid:e.uuid,messageType:"assistant"})),e.type==="system"&&e.subtype==="init"){e.slash_commands&&Array.isArray(e.slash_commands)&&s({type:"slash_commands",commands:e.slash_commands}),e.model&&typeof e.model=="string"&&s({type:"model_info",model:e.model,models:[]}),e.fast_mode_state&&typeof e.fast_mode_state=="string"&&s({type:"fast_mode_state",state:e.fast_mode_state});return}if(e.type==="stream_event"&&e.event){me(t,e.event,s);return}if((e.type==="assistant"||e.type==="user")&&e.message&&typeof e.message=="object"){let r=e.message.content;if(e.parent_tool_use_id&&typeof e.parent_tool_use_id=="string"){fe(t,e,s);return}if(e.type==="assistant"&&!t.streamedText&&Array.isArray(r)){let a=r.filter(c=>c.type==="text").map(c=>c.text).join("");a&&s({type:"delta",text:a})}if(e.type==="user"){let a="";if(typeof r=="string"?a=r:Array.isArray(r)&&(a=r.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
2
2
|
`)),a.indexOf("local-command-stdout")!==-1){let c=a.match(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/);c&&s({type:"slash_command_result",text:c[1].trim()})}}if(Array.isArray(r)){for(let a of r)if(a.type==="tool_result"&&typeof a.tool_use_id=="string"&&!t.sentToolResults[a.tool_use_id]){t.activeTaskToolIds[a.tool_use_id]&&(s({type:"subagent_done",parentToolId:a.tool_use_id}),delete t.activeTaskToolIds[a.tool_use_id]);let c=t.teammateMap[a.tool_use_id];c&&(s({type:"teammate_status",parentToolId:a.tool_use_id,teammateName:c,status:a.is_error?"error":"idle"}),delete t.teammateMap[a.tool_use_id]);let d="";typeof a.content=="string"?d=a.content:Array.isArray(a.content)&&(d=a.content.filter(l=>l.type==="text").map(l=>l.text).join(`
|
|
3
|
-
`)),t.sentToolResults[a.tool_use_id]=!0,s({type:"tool_result",id:a.tool_use_id,content:d,is_error:a.is_error||!1})}}return}if(e.type==="result"){t.blocks={},t.sentToolResults={},t.activeTaskToolIds={},t.taskIdMap={},t.teammateMap={},t.isProcessing=!1,s({type:"result",cost:e.total_cost_usd??null,duration:e.duration_ms??null,usage:e.usage??null,modelUsage:e.modelUsage??null,sessionId:e.session_id}),e.fast_mode_state&&typeof e.fast_mode_state=="string"&&s({type:"fast_mode_state",state:e.fast_mode_state}),s({type:"done",code:0}),t.responsePreview="",t.streamedText=!1;return}if(e.type==="system"&&e.subtype==="status"){e.status==="compacting"?(s({type:"compacting",active:!0}),t.compacting=!0):t.compacting&&(s({type:"compacting",active:!1}),t.compacting=!1);return}if(e.type==="system"&&e.subtype==="task_started"){let n=e.tool_use_id;n&&(e.task_id&&(t.taskIdMap[n]=e.task_id),s({type:"task_started",parentToolId:n,taskId:e.task_id||"",description:e.description||""}));return}if(e.type==="system"&&e.subtype==="task_progress"){let n=e.tool_use_id||void 0,r=e.task_id,a=n||(r?Object.keys(t.taskIdMap).find(c=>t.taskIdMap[c]===r):void 0);if(a){s({type:"task_progress",parentToolId:a,taskId:r,usage:e.usage??null,lastToolName:e.last_tool_name||void 0,description:e.description||""});let c=t.teammateMap[a];if(c){let d=e.description||(e.last_tool_name?`Running ${e.last_tool_name}...`:void 0);s({type:"teammate_status",parentToolId:a,teammateName:c,status:"active",activityText:d})}}return}if(e.type==="tool_progress"){let n=e.parent_tool_use_id;if(n){s({type:"subagent_activity",parentToolId:n,text:e.content||""});let r=t.teammateMap[n];r&&s({type:"teammate_status",parentToolId:n,teammateName:r,status:"active",activityText:e.content||void 0})}return}if(e.type==="system"&&e.subtype==="task_notification"){let n=e.tool_use_id||void 0,r=e.task_id,a=n||(r?Object.keys(t.taskIdMap).find(c=>t.taskIdMap[c]===r):void 0);if(a){s({type:"subagent_done",parentToolId:a,status:e.status||"completed",summary:e.summary||"",usage:e.usage??null});let c=t.teammateMap[a];if(c){let d=e.status==="error"||e.status==="failed";s({type:"teammate_status",parentToolId:a,teammateName:c,status:d?"error":"idle",activityText:e.summary||void 0}),delete t.teammateMap[a]}}if(r){for(let c of Object.keys(t.taskIdMap))if(t.taskIdMap[c]===r){delete t.taskIdMap[c];break}}return}if(e.type==="rate_limit_event"&&e.rate_limit_info){let n=e.rate_limit_info;(n.status==="allowed_warning"||n.status==="rejected")&&s({type:"rate_limit",status:n.status,resetsAt:n.resetsAt?n.resetsAt*1e3:null,rateLimitType:n.rateLimitType||null,utilization:n.utilization||null});return}if(e.type==="prompt_suggestion"){s({type:"prompt_suggestion",suggestion:e.suggestion||""});return}}function
|
|
3
|
+
`)),t.sentToolResults[a.tool_use_id]=!0,s({type:"tool_result",id:a.tool_use_id,content:d,is_error:a.is_error||!1})}}return}if(e.type==="result"){t.blocks={},t.sentToolResults={},t.activeTaskToolIds={},t.taskIdMap={},t.teammateMap={},t.isProcessing=!1,s({type:"result",cost:e.total_cost_usd??null,duration:e.duration_ms??null,usage:e.usage??null,modelUsage:e.modelUsage??null,sessionId:e.session_id}),e.fast_mode_state&&typeof e.fast_mode_state=="string"&&s({type:"fast_mode_state",state:e.fast_mode_state}),s({type:"done",code:0}),t.responsePreview="",t.streamedText=!1;return}if(e.type==="system"&&e.subtype==="status"){e.status==="compacting"?(s({type:"compacting",active:!0}),t.compacting=!0):t.compacting&&(s({type:"compacting",active:!1}),t.compacting=!1);return}if(e.type==="system"&&e.subtype==="task_started"){let n=e.tool_use_id;n&&(e.task_id&&(t.taskIdMap[n]=e.task_id),s({type:"task_started",parentToolId:n,taskId:e.task_id||"",description:e.description||""}));return}if(e.type==="system"&&e.subtype==="task_progress"){let n=e.tool_use_id||void 0,r=e.task_id,a=n||(r?Object.keys(t.taskIdMap).find(c=>t.taskIdMap[c]===r):void 0);if(a){s({type:"task_progress",parentToolId:a,taskId:r,usage:e.usage??null,lastToolName:e.last_tool_name||void 0,description:e.description||""});let c=t.teammateMap[a];if(c){let d=e.description||(e.last_tool_name?`Running ${e.last_tool_name}...`:void 0);s({type:"teammate_status",parentToolId:a,teammateName:c,status:"active",activityText:d})}}return}if(e.type==="tool_progress"){let n=e.parent_tool_use_id;if(n){s({type:"subagent_activity",parentToolId:n,text:e.content||""});let r=t.teammateMap[n];r&&s({type:"teammate_status",parentToolId:n,teammateName:r,status:"active",activityText:e.content||void 0})}return}if(e.type==="system"&&e.subtype==="task_notification"){let n=e.tool_use_id||void 0,r=e.task_id,a=n||(r?Object.keys(t.taskIdMap).find(c=>t.taskIdMap[c]===r):void 0);if(a){s({type:"subagent_done",parentToolId:a,status:e.status||"completed",summary:e.summary||"",usage:e.usage??null});let c=t.teammateMap[a];if(c){let d=e.status==="error"||e.status==="failed";s({type:"teammate_status",parentToolId:a,teammateName:c,status:d?"error":"idle",activityText:e.summary||void 0}),delete t.teammateMap[a]}}if(r){for(let c of Object.keys(t.taskIdMap))if(t.taskIdMap[c]===r){delete t.taskIdMap[c];break}}return}if(e.type==="rate_limit_event"&&e.rate_limit_info){let n=e.rate_limit_info;(n.status==="allowed_warning"||n.status==="rejected")&&s({type:"rate_limit",status:n.status,resetsAt:n.resetsAt?n.resetsAt*1e3:null,rateLimitType:n.rateLimitType||null,utilization:n.utilization||null});return}if(e.type==="prompt_suggestion"){s({type:"prompt_suggestion",suggestion:e.suggestion||""});return}}function me(t,e,s){if(e.type==="content_block_start"){let n=e.content_block,r=e.index;n.type==="tool_use"?(t.blocks[r]={type:"tool_use",id:n.id,name:n.name,inputJson:""},s({type:"tool_start",id:n.id,name:n.name})):n.type==="thinking"?(t.blocks[r]={type:"thinking",thinkingText:"",startTime:Date.now()},s({type:"thinking_start"})):n.type==="text"&&(t.blocks[r]={type:"text"});return}if(e.type==="content_block_delta"&&e.delta){let n=e.index,r=e.delta;if(r.type==="text_delta"&&typeof r.text=="string"){if(t.streamedText=!0,t.responsePreview.length<200&&(t.responsePreview+=r.text),s({type:"delta",text:r.text}),t.teamActive){let a=r.text.matchAll(/teammate_id="([^"]+)"/g);for(let c of a){let d=c[1];(r.text.includes("idle_notification")||r.text.includes('"idleReason"'))&&s({type:"teammate_status",parentToolId:"",teammateName:d,status:"idle",activityText:"Idle"})}}}else r.type==="input_json_delta"&&t.blocks[n]?t.blocks[n].inputJson=(t.blocks[n].inputJson||"")+r.partial_json:r.type==="thinking_delta"&&t.blocks[n]&&(t.blocks[n].thinkingText=(t.blocks[n].thinkingText||"")+r.thinking,s({type:"thinking_delta",text:r.thinking}));return}if(e.type==="content_block_stop"){let n=e.index,r=t.blocks[n];if(r&&r.type==="tool_use"){let a={};try{a=JSON.parse(r.inputJson||"{}")}catch{}s({type:"tool_executing",id:r.id,name:r.name,input:a});let c=r.name;if((c==="Task"||c==="Agent"||c==="TeammateTool")&&(t.activeTaskToolIds[r.id]=!0,t.teamActive)){let d=a;if(d){let l=d.teammate_name||d.name||d.subagent_type,p=d.team_name||void 0;l&&(t.teammateMap[r.id]=l,s({type:"teammate_spawned",parentToolId:r.id,teammateName:l,teamName:p,description:d.description||d.prompt||""}))}}if(t.teamActive&&c==="SendMessage"){let d=a;if(d){let l=d.to;l&&l!=="*"&&s({type:"teammate_status",parentToolId:r.id,teammateName:l,status:"active",activityText:"Processing message\u2026"})}}}else if(r&&r.type==="thinking"){let a=r.startTime?(Date.now()-r.startTime)/1e3:0;s({type:"thinking_stop",duration:a})}delete t.blocks[n];return}}function fe(t,e,s){let n=e.parent_tool_use_id,a=e.message.content;if(Array.isArray(a)&&e.type==="assistant")for(let c of a)if(c.type==="tool_use"){let d=pe(c.name,c.input);s({type:"subagent_tool",parentToolId:n,toolName:c.name,toolId:c.id,text:d})}else c.type==="thinking"?s({type:"subagent_activity",parentToolId:n,text:"Thinking..."}):c.type==="text"&&c.text&&s({type:"subagent_activity",parentToolId:n,text:"Writing response..."})}function pe(t,e){return t==="Bash"&&e?.description?e.description:t==="Read"&&e?.file_path?"Reading "+e.file_path.split("/").pop():t==="Edit"&&e?.file_path?"Editing "+e.file_path.split("/").pop():t==="Write"&&e?.file_path?"Writing "+e.file_path.split("/").pop():t==="Grep"&&e?.pattern?"Searching for "+e.pattern:t==="Glob"&&e?.pattern?"Finding "+e.pattern:t==="WebSearch"&&e?.query?"Searching: "+e.query:t==="WebFetch"?"Fetching URL...":t==="Task"&&e?.description?e.description:"Running "+t+"..."}function j(){let t=[],e=null,s=!1;return{push(n){if(!s)if(e){let r=e;e=null,r({value:n,done:!1})}else t.push(n)},end(){if(s=!0,e){let n=e;e=null,n({value:void 0,done:!0})}},[Symbol.asyncIterator](){return{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):s?Promise.resolve({value:void 0,done:!0}):new Promise(n=>{e=n})}}}}}import{randomUUID as ye}from"node:crypto";function Z(t,e){let s={},n={},r={},a=l=>{let p=e?.();return p?{...l,relaySessionId:p}:l},c=(l,p)=>l(a(p)),d=l=>c(t,l);return{handleCanUseTool(l,p,h){return l==="AskUserQuestion"?new Promise(_=>{n[h.toolUseID]={resolve:_,input:p},h.signal&&h.signal.addEventListener("abort",()=>{delete n[h.toolUseID],d({type:"ask_user_answered",toolId:h.toolUseID}),_({behavior:"deny",message:"Cancelled"})})}):r[l]?Promise.resolve({behavior:"allow",updatedInput:p}):new Promise(_=>{let M=ye();s[M]={resolve:_,requestId:M,toolName:l,toolInput:p,toolUseId:h.toolUseID},d({type:"permission_request",requestId:M,toolName:l,toolInput:p,toolUseId:h.toolUseID,decisionReason:h.decisionReason||""}),h.signal&&h.signal.addEventListener("abort",()=>{delete s[M],d({type:"permission_cancel",requestId:M}),_({behavior:"deny",message:"Request cancelled"})})})},handlePermissionResponse(l,p,h){let _=s[l];if(!_&&l.startsWith("hydrated-")){let M=l.slice(9),b=Object.keys(s).find(C=>s[C].toolUseId===M);b&&(_=s[b])}_&&(delete s[_.requestId],d({type:"permission_resolved",requestId:_.requestId,decision:p}),l!==_.requestId&&d({type:"permission_resolved",requestId:l,decision:p}),p==="allow"?(h&&(r[_.toolName]=!0),_.resolve({behavior:"allow",updatedInput:_.toolInput})):_.resolve({behavior:"deny",message:"User denied"}))},handleAskUserResponse(l,p){let h=n[l];if(!h)return;delete n[l],d({type:"ask_user_answered",toolId:l});let _=Object.assign({},h.input,{answers:p});h.resolve({behavior:"allow",updatedInput:_})},clearPending(l){for(let p of Object.keys(n))c(l,{type:"ask_user_answered",toolId:p}),n[p].resolve({behavior:"deny",message:"Session ended"}),delete n[p];for(let p of Object.keys(s))c(l,{type:"permission_cancel",requestId:p}),s[p].resolve({behavior:"deny",message:"Session ended"}),delete s[p]}}}function F(){return{cliSessionId:null,resumeToken:null,relaySessionId:null,sessionName:null,blocks:{},sentToolResults:{},streamedText:!1,responsePreview:"",activeTaskToolIds:{},taskIdMap:{},teammateMap:{},teamActive:!1,isProcessing:!1,compacting:!1}}var ge=`## Sending a file to the user
|
|
4
4
|
|
|
5
5
|
When the user asks you to send, download, or give them a file, emit this marker
|
|
6
6
|
on a line of its own:
|
|
@@ -13,12 +13,12 @@ The agent replaces the marker with a downloadable chip in the chat. Rules:
|
|
|
13
13
|
anything outside the workspace are refused.
|
|
14
14
|
- Do NOT also paste the file's contents \u2014 the chip IS the delivery.
|
|
15
15
|
- Only emit it when the user asked for the file. Never on your own initiative.
|
|
16
|
-
- Files over 5 MB are refused; say so rather than emitting the marker.`,
|
|
16
|
+
- Files over 5 MB are refused; say so rather than emitting the marker.`,W=ge;var A={agents:[],teamName:null,leadSessionId:null,teamConfigDir:null};function se(t,e){let s=JSON.parse(t);if(!s.members||s.members.length===0)return A;let n=[];for(let r of s.members)r.agentType!=="team-lead"&&n.push({id:r.name.toLowerCase().replace(/\s+/g,"-"),name:r.name,description:r.prompt||`${r.agentType} agent`,systemPrompt:r.prompt||"",defaultModel:r.model,agentType:r.agentType,color:r.color});return{agents:n,teamName:s.name||null,leadSessionId:s.leadSessionId||null,teamConfigDir:e}}async function we(t){let e=R(ke(),".claude","teams"),s=ee(t);try{let n=await te(e);for(let r of n)try{let a=R(e,r),c=await oe(R(a,"config.json"),"utf-8");if(!JSON.parse(c).members?.some(p=>p.cwd&&ee(p.cwd)===s))continue;return se(c,a)}catch{}return A}catch{return A}}async function be(t){let e=R(t,".claude","teams");try{let s=await te(e);for(let n of s)try{let r=R(e,n),a=await oe(R(r,"config.json"),"utf-8");return se(a,r)}catch{}return A}catch{return A}}var B=3,J=[2e3,5e3,1e4],O="working directory no longer exists";function G(t){let e=t.toLowerCase();return e.includes("prompt is too long")||e.includes("context_length")||e.includes("maximum context length")||e.includes("no conversation found with session id")||e.includes(O)}async function z(t){if(!t)return!1;try{return!(await he(t)).isDirectory()}catch{return!0}}function re(t){let e=null,s=null,n=null,r=null,a=F(),c=null,d="",l=[],p="acceptEdits",h="medium",_="",M=0,b=A,C=!1,N=null,I=t;t=o=>{if(o.type==="model_info"&&(o.models&&o.models.length>0&&(l=o.models),o.models=l,o.model&&(d=o.model)),N){N(o);return}I(o)};async function K(){if(e)return e;try{return e=await import("@anthropic-ai/claude-agent-sdk"),e}catch(o){let i=o;throw new Error(`Failed to load Claude SDK: ${i.message}`)}}async function Q(o,i,f,u=B){let y;for(let m=0;m<u;m++){let g=J[m]??J[J.length-1];if(t({type:"info",text:`Reconnecting to Claude session (attempt ${m+1}/${u})...`}),await new Promise(T=>setTimeout(T,g)),i!==M)return console.error(`[sdk-runner] session generation changed during ${f}, aborting`),{ok:!1,reason:"generation-changed"};try{return o(m),console.error(`[sdk-runner] ${f} succeeded on attempt ${m+1}`),t({type:"info",text:"Reconnected to Claude session."}),{ok:!0}}catch(T){if(y=T,console.error(`[sdk-runner] ${f} attempt ${m+1} failed: ${y.message}`),G(y.message))return console.error(`[sdk-runner] non-retryable error during ${f}, giving up`),{ok:!1,reason:"non-retryable",error:y}}}return console.error(`[sdk-runner] ${f} all attempts exhausted`),{ok:!1,reason:"exhausted",error:y}}function ae(o,i){if(i.length===0||i.find(m=>m.value===o))return o;let u=o.toLowerCase(),y=i.find(m=>m.value.toLowerCase().split("-").some(g=>g===u));return y?y.value:o}function Y(o){return o.map(i=>({value:i.value,displayName:i.displayName,description:i.description,supportsEffort:i.supportsEffort,supportedEffortLevels:i.supportedEffortLevels}))}async function ie(o,i){let f={[Symbol.asyncIterator](){return{next:()=>Promise.resolve({value:void 0,done:!0})}}},u=null;try{u=o.query({prompt:f,options:{cwd:i}}),u[Symbol.asyncIterator]().next().catch(()=>{});let m=null,g=!!u.initializationResult,T=!!u.supportedModels;if(console.error(`[sdk-runner] probe: initializationResult=${g}, supportedModels=${T}`),u.initializationResult){let k=await Promise.race([u.initializationResult(),new Promise(w=>setTimeout(()=>w(null),8e3))]);if(k?.models?.length)m=k.models,console.error(`[sdk-runner] probe: initializationResult returned ${m.length} models`);else if(console.error("[sdk-runner] probe: initializationResult returned no models, trying supportedModels fallback"),u.supportedModels){let w=await Promise.race([u.supportedModels(),new Promise(E=>setTimeout(()=>E(null),8e3))]);w?.length?(m=w,console.error(`[sdk-runner] probe: supportedModels fallback returned ${m.length} models`)):console.error("[sdk-runner] probe: supportedModels fallback returned no models")}}else if(u.supportedModels){let k=await Promise.race([u.supportedModels(),new Promise(w=>setTimeout(()=>w(null),8e3))]);k?.length?(m=k,console.error(`[sdk-runner] probe: supportedModels returned ${m.length} models`)):console.error("[sdk-runner] probe: supportedModels returned no models")}else console.error("[sdk-runner] probe: neither initializationResult nor supportedModels available");m&&m.length>0?(l=Y(m),!d&&l.length>0&&(d=l[0].value),console.error(`[sdk-runner] probe: sending model_info with ${l.length} models`),t({type:"model_info",model:d,models:l})):console.error("[sdk-runner] probe: no models found from any method")}catch(y){console.error(`[sdk-runner] probe: error fetching models: ${y.message}`)}finally{u?.close&&u.close()}}async function H(){if(!n)return;let o=M;try{for await(let i of n)V(a,i,t)}catch(i){if(o!==M)return;let f=i,u=f.name==="AbortError"||r&&r.signal.aborted,y=f.message||String(f),m=G(y);if(!u&&!m&&a.resumeToken&&(console.error(`[sdk-runner] query stream crashed: ${f.message}, attempting recovery`),await ce(o)))return;let g=!u&&await z(_);a.isProcessing&&(a.isProcessing=!1,u?(t({type:"info",text:"Interrupted"}),t({type:"done",code:0})):g?(t({type:"error",text:`${O}: ${_}`}),t({type:"done",code:1})):m?(t({type:"error",text:"Conversation too long to continue."}),t({type:"done",code:1})):(t({type:"error",text:`Claude process error: ${f.message}`}),t({type:"done",code:1})))}finally{o===M&&(n=null,s=null,r=null,c&&c.clearPending(t))}}function le(o,i){let f={cwd:_,settingSources:["user","project","local"],systemPrompt:W,includePartialMessages:!0,enableFileCheckpointing:!0,enableAutoMode:!0,abortController:i,promptSuggestions:!0,resume:o,permissionMode:p,effort:h};return d&&(f.model=d),c&&(f.canUseTool=(u,y,m)=>c.handleCanUseTool(u,y,m)),b.teamName&&(f.env={...process.env,CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1",CLAUDE_CODE_TEAM_NAME:b.teamName.toLowerCase()}),f}async function ce(o){if(!e)return!1;let i=e,f=a.resumeToken;return f?await z(_)?(console.error(`[sdk-runner] skipping recovery \u2014 ${O}: ${_}`),!1):(await Q(()=>{s=j(),r=new AbortController;let y=le(f,r);n=i.query({prompt:s,options:y}),a.isProcessing=!0,M++,H().catch(m=>{console.error("[sdk-runner] recovered stream error:",m)})},o,"stream-crash-recovery")).ok:!1}let v="done",P="",D=0,U=0,q=null;function ue(){N=o=>{if(o.type==="delta"&&typeof o.text=="string"&&(P+=o.text),o.type==="delta"&&typeof o.text=="string"){let i=o.text,f=i.matchAll(/teammate_id="([^"]+)"/g);for(let u of f){let y=u[1];(i.includes("idle_notification")||i.includes("online"))&&I({type:"teammate_status",parentToolId:"",teammateName:y,status:"idle",activityText:"Online"})}}if(o.type==="done"||o.type==="result"){if(v==="broadcast_test"){let i=P.toUpperCase(),f=i.includes("TEAM_READY")||i.includes("BROADCAST")&&i.includes("SUCCESS")||i.includes("MESSAGE SENT"),u=i.includes("TEAM_NEEDS_REBUILD")||i.includes("NOT IN A TEAM")||i.includes("NO TEAM")||i.includes("ERROR");f&&!u?(v="done",N=null,I({type:"agent_mode_status",statusText:"Team is ready!"}),I({type:"agent_mode_ready",success:!0}),I(o)):(v="spawning",P="",I({type:"agent_mode_status",statusText:"Spawning teammates\u2026"}),de());return}if(v==="spawning"){C=!0,v="waiting_for_teammates",U=0,D=b.agents.filter(i=>i.agentType!=="team-lead").length,I({type:"agent_mode_status",statusText:`Waiting for ${D} teammates to come online\u2026`}),I(o),q=setTimeout(()=>{v==="waiting_for_teammates"&&(v="done",N=null,I({type:"agent_mode_status",statusText:"Team is ready!"}),I({type:"agent_mode_ready",success:!0}))},45e3);return}}if(v!=="done"){(o.type==="teammate_spawned"||o.type==="teammate_status"||o.type==="session_id")&&(I(o),v==="waiting_for_teammates"&&o.type==="teammate_spawned"&&(U++,I({type:"agent_mode_status",statusText:`Teammates online: ${U}/${D}\u2026`}),U>=D&&(q&&(clearTimeout(q),q=null),v="done",N=null,I({type:"agent_mode_status",statusText:"Team is ready!"}),I({type:"agent_mode_ready",success:!0}))));return}I(o)}}function de(){if(!s||!b.teamName){I({type:"agent_mode_ready",success:!1,error:"Cannot spawn team \u2014 no session or template"});return}(b.teamConfigDir?_e(b.teamConfigDir,{recursive:!0,force:!0}).catch(()=>{}):Promise.resolve()).then(()=>{let i=b.agents.map(u=>{let y=u.defaultModel?` (model: ${u.defaultModel})`:"";return`- **${u.name}** \u2014 ${u.agentType||"general-purpose"}${y}: ${u.description}`}).join(`
|
|
17
17
|
`),f=[`Create an agent team called "${b.teamName.toLowerCase()}" with the following teammates, all using in-process mode:`,"",i,"","Use teammate-mode in-process. Spawn all teammates now. After they are all running, confirm the team is ready.","Do NOT start any tasks yet \u2014 just set up the team."].join(`
|
|
18
|
-
`);s.push({type:"user",message:{role:"user",content:[{type:"text",text:f}]}})})}let
|
|
19
|
-
`);s.push({type:"user",message:{role:"user",content:[{type:"text",text:o}]}})},async requestHistory(o,i){let f=await
|
|
18
|
+
`);s.push({type:"user",message:{role:"user",content:[{type:"text",text:f}]}})})}let L={async startSession(o){if(await z(o.cwd)){let g=`${O}: ${o.cwd}`;console.error(`[sdk-runner] startSession: ${g}`),t({type:"error",text:g}),t({type:"done",code:1}),t({type:"session_ready",error:g});return}let i=await K();l.length===0?(console.error("[sdk-runner] startSession: no cached models, launching probe"),ie(i,o.cwd).catch(g=>{console.error(`[sdk-runner] startSession: probe failed: ${g.message}`)})):console.error(`[sdk-runner] startSession: ${l.length} models already cached, skipping probe`),C=!1;let f=A;try{f=await be(o.cwd)}catch{}let u=A;try{u=await we(o.cwd)}catch{}f.agents.length>0?b={agents:f.agents,teamName:f.teamName||u.teamName,leadSessionId:u.leadSessionId,teamConfigDir:u.teamConfigDir}:b={agents:[],teamName:u.teamName,leadSessionId:u.leadSessionId,teamConfigDir:u.teamConfigDir},t({type:"agent_team_loaded",agents:b.agents}),M++;let y=M;a=F(),a.isProcessing=!0,a.teamActive=b.agents.length>0,o.relaySessionId&&(a.relaySessionId=o.relaySessionId),o.sessionName&&(a.sessionName=o.sessionName),c=Z(t,()=>a.relaySessionId),s=j(),o.initialMessage&&s.push(o.initialMessage),r=new AbortController,_=o.cwd;let m={cwd:o.cwd,settingSources:["user","project","local"],systemPrompt:W,includePartialMessages:!0,enableFileCheckpointing:!0,enableAutoMode:!0,abortController:r,promptSuggestions:!0,canUseTool:(g,T,k)=>c.handleCanUseTool(g,T,k)};if(b.teamName&&(m.env={...process.env,CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:"1",CLAUDE_CODE_TEAM_NAME:b.teamName.toLowerCase()}),o.model&&(m.model=o.model,d=o.model),o.permissionMode?(m.permissionMode=o.permissionMode,p=o.permissionMode):m.permissionMode=p,m.effort=h,o.sessionName&&!o.resume&&(m.title=o.sessionName),o.resume){if(m.resume=o.resume,a.cliSessionId=o.resume,a.resumeToken=o.resume,i.getSessionMessages)try{let g=await i.getSessionMessages(o.resume);g&&g.length>0&&t({type:"session_history",messages:g,...a.relaySessionId?{relaySessionId:a.relaySessionId}:{}})}catch(g){t({type:"info",text:`Could not restore session history: ${g.message}`})}t({type:"config_state",model:d,mode:p,effort:h,betas:[]})}try{n=i.query({prompt:s,options:m})}catch(g){let T=g;if(console.error(`[sdk-runner] query start failed (attempt 1/${B+1}): ${T.message}`),G(T.message)){a.isProcessing=!1,n=null,s=null,r=null,t({type:"error",text:`Failed to start query: ${T.message}`}),t({type:"done",code:1}),t({type:"session_ready",error:T.message});return}let k=await Q(()=>{s=j(),r=new AbortController,m.abortController=r,n=i.query({prompt:s,options:m})},y,"query-start-retry");if(!k.ok){if(k.reason!=="generation-changed"){a.isProcessing=!1,n=null,s=null,r=null;let w=k.reason==="exhausted"?`Failed to start query after ${B+1} attempts: ${k.error?.message??T.message}`:`Failed to start query: ${k.error?.message??T.message}`;t({type:"error",text:w}),t({type:"done",code:1}),t({type:"session_ready",error:w})}return}}if(n?.supportedModels){let g=n;(async()=>{let k=[500,1500,3e3,5e3];for(let w=0;w<k.length;w++){if(l.length>0){console.error(`[sdk-runner] real query: models already populated (attempt ${w}), skipping`);return}try{console.error(`[sdk-runner] real query: calling supportedModels() attempt ${w}`);let E=await Promise.race([g.supportedModels(),new Promise(X=>setTimeout(()=>X(null),k[w]))]);if(E&&E.length>0){l=Y(E),!d&&l.length>0&&(d=l[0].value),console.error(`[sdk-runner] real query: supportedModels returned ${l.length} models on attempt ${w}`),t({type:"model_info",model:d,models:l});return}console.error(`[sdk-runner] real query: supportedModels returned empty on attempt ${w}`)}catch(E){console.error(`[sdk-runner] real query: supportedModels error on attempt ${w}: ${E.message}`)}w<k.length-1&&await new Promise(E=>setTimeout(E,k[w]))}console.error("[sdk-runner] real query: all supportedModels attempts exhausted")})().catch(()=>{})}else console.error("[sdk-runner] real query: supportedModels not available on query instance");H().catch(()=>{}),t({type:"session_ready"})},activateAgentMode(){if(!s){I({type:"agent_mode_ready",success:!1,error:"No active session"});return}if(b.agents.length===0||!b.teamName){I({type:"agent_mode_ready",success:!1,error:"No team template found"});return}if(v!=="done")return;I({type:"agent_mode_status",statusText:"Checking team status\u2026"}),v="broadcast_test",P="",ue();let o=['You are activating VibeAgent mode. First, try to broadcast a ping to the team using SendMessage with to="*".',"If the broadcast succeeds, respond with exactly: TEAM_READY",'If the broadcast fails (e.g. "Not in a team context" or no teammates found), respond with exactly: TEAM_NEEDS_REBUILD',"Do not explain anything else \u2014 just respond with one of those two phrases."].join(`
|
|
19
|
+
`);s.push({type:"user",message:{role:"user",content:[{type:"text",text:o}]}})},async requestHistory(o,i){let f=await K(),u=i||a.relaySessionId,y=o||a.cliSessionId;if(y&&f.getSessionMessages)try{let m=await f.getSessionMessages(y);if(m&&m.length>0)t({type:"session_history",messages:m,...u?{relaySessionId:u}:{}});else if(a.cliSessionId&&a.cliSessionId!==y){let g=await f.getSessionMessages(a.cliSessionId);g&&g.length>0&&(t({type:"session_history",messages:g,...u?{relaySessionId:u}:{}}),t({type:"session_id",cliSessionId:a.cliSessionId,...u?{relaySessionId:u}:{}}))}}catch(m){t({type:"info",text:`Could not restore session history: ${m.message}`})}l.length>0&&t({type:"model_info",model:d,models:l,...u?{relaySessionId:u}:{}}),t({type:"config_state",model:d,mode:p,effort:h,betas:[],...u?{relaySessionId:u}:{}})},pushUserMessage(o,i,f){if(f&&o&&(o=`Use SendMessage to send the following to teammate "${f}":
|
|
20
20
|
|
|
21
|
-
${o}`),o&&o.startsWith("/")){let y=o.split(/\s/)[0].toLowerCase();if(y==="/clear"){M++,r&&r.abort(),s&&s.end(),this.startSession({cwd:
|
|
22
|
-
`)});return}}if(!s){if(
|
|
21
|
+
${o}`),o&&o.startsWith("/")){let y=o.split(/\s/)[0].toLowerCase();if(y==="/clear"){M++,r&&r.abort(),s&&s.end(),this.startSession({cwd:_,model:d||void 0,permissionMode:p||void 0}).then(()=>{t({type:"slash_command_result",command:"clear",text:"Conversation cleared."})}).catch(m=>{t({type:"error",text:`Failed to clear session: ${m.message}`})});return}if(y==="/status"){let m=["**Bridge Status**","",`**Model:** ${d||"(not set)"}`,`**Available Models:** ${l.length>0?l.map(g=>`${g.displayName} (${g.value})`).join(", "):"(none discovered yet)"}`,`**Effort:** ${h}`,`**Permission Mode:** ${p}`,`**Session Active:** ${n?"yes":"no"}`,`**CLI Session:** ${a.cliSessionId||"(none)"}`,`**Working Directory:** ${_||"(not set)"}`,"","**Raw SDK Model Data:**","```json",JSON.stringify(l,null,2),"```"];t({type:"slash_command_result",command:"status",text:m.join(`
|
|
22
|
+
`)});return}}if(!s){if(_){console.error("[sdk-runner] pushUserMessage: no active stream, restarting bridge"),t({type:"info",text:"Reconnecting..."});let y=[];if(i&&i.length>0)for(let k of i)y.push({type:"image",source:{type:"base64",media_type:k.mediaType,data:k.data}});o&&y.push({type:"text",text:o});let m={type:"user",message:{role:"user",content:y}},g={cwd:_,model:d||void 0,permissionMode:p||void 0};(async()=>{try{await L.startSession({...g,...a.resumeToken?{resume:a.resumeToken}:{},initialMessage:m})}catch(k){console.error(`[sdk-runner] resume restart failed: ${k.message}, trying fresh`);try{await L.startSession({...g,initialMessage:m})}catch(w){t({type:"error",text:`Session restart failed: ${w.message}`}),t({type:"done",code:1})}}})();return}t({type:"error",text:"No active session"});return}let u=[];if(i&&i.length>0)for(let y of i)u.push({type:"image",source:{type:"base64",media_type:y.mediaType,data:y.data}});o&&u.push({type:"text",text:o}),o&&t({type:"user_message",text:o}),a.isProcessing=!0,a.streamedText=!1,a.responsePreview="",a.blocks={},a.sentToolResults={},s.push({type:"user",message:{role:"user",content:u}})},interrupt(){n?.interrupt?n.interrupt().catch(()=>{r&&r.abort()}):r&&r.abort()},async setModel(o){let i=ae(o,l);if(!n?.setModel){d=i,t({type:"model_info",model:i,models:l});return}try{await n.setModel(i),d=i,t({type:"model_info",model:i,models:[]}),t({type:"config_state",model:d,mode:p,effort:h,betas:[]})}catch(f){t({type:"error",text:`Failed to switch model: ${f.message}`})}},async setMode(o){if(!n?.setPermissionMode){p=o,t({type:"config_state",model:d,mode:p,effort:h,betas:[]});return}try{await n.setPermissionMode(o),p=o,t({type:"config_state",model:d,mode:p,effort:h,betas:[]})}catch(i){t({type:"error",text:`Failed to set permission mode: ${i.message}`})}},setEffort(o){["low","medium","high","xhigh","max"].includes(o)||(console.warn(`[sdk-runner] Unknown effort level "${o}", defaulting to medium`),o="medium"),h=o,t({type:"config_state",model:d,mode:p,effort:h,betas:[]})},handlePermissionResponse(o,i,f){c?.handlePermissionResponse(o,i,f)},handleAskUserResponse(o,i){c?.handleAskUserResponse(o,i)},shutdown(){n?.close?n.close():r&&r.abort(),s&&s.end()}};return L}function $(t){let e=JSON.stringify(t);process.stdout.write(e+`
|
|
23
23
|
`)}function S(t,e,s){let n={level:t,message:e,ts:new Date().toISOString(),...s};process.stderr.write(JSON.stringify(n)+`
|
|
24
|
-
`)}var x=
|
|
24
|
+
`)}var x=re($),ne=Ie({input:process.stdin,crlfDelay:1/0});ne.on("line",async t=>{if(!t.trim())return;let e;try{e=JSON.parse(t)}catch{S("error","Failed to parse inbound message",{raw:t.slice(0,200)});return}try{switch(e.type){case"start_session":S("info","Starting session",{cwd:e.cwd,model:e.model});try{await x.startSession({cwd:e.cwd,model:e.model,permissionMode:e.permissionMode,resume:e.resume,relaySessionId:e.relaySessionId,sessionName:e.sessionName}),$({type:"session_ready"})}catch(s){$({type:"session_ready",error:String(s)})}break;case"user_message":S("info","User message received",{textLength:e.text?.length??0,targetAgentId:e.targetAgentId}),x.pushUserMessage(e.text,e.images,e.targetAgentId);break;case"interrupt":S("info","Interrupt requested"),x.interrupt();break;case"permission_response":S("info","Permission response",{requestId:e.requestId,decision:e.decision}),x.handlePermissionResponse(e.requestId,e.decision,e.allowForSession);break;case"ask_user_response":S("info","Ask user response",{toolId:e.toolId}),x.handleAskUserResponse(e.toolId,e.answers);break;case"set_model":S("info","Set model",{model:e.model}),await x.setModel(e.model);break;case"set_mode":S("info","Set mode",{mode:e.mode}),await x.setMode(e.mode);break;case"set_effort":S("info","Set effort",{effort:e.effort}),x.setEffort(e.effort);break;case"activate_agent_mode":S("info","Activate agent mode requested"),x.activateAgentMode();break;case"request_history":S("info","History request",{resume:e.resume}),await x.requestHistory(e.resume,e.relaySessionId);break;case"ping":$({type:"pong"});break;case"shutdown":S("info","Shutdown requested"),x.shutdown(),setTimeout(()=>process.exit(0),500);break;default:S("warn","Unknown message type",{type:e.type})}}catch(s){let n=s;S("error",`Error handling message type=${e.type}`,{error:n.message}),$({type:"error",text:`Internal bridge error: ${n.message}`})}});ne.on("close",()=>{S("info","stdin closed, shutting down"),x.shutdown(),setTimeout(()=>process.exit(0),500)});process.on("uncaughtException",t=>{S("error","Uncaught exception",{error:t.message,stack:t.stack}),$({type:"error",text:`Bridge crash: ${t.message}`}),$({type:"done",code:1}),process.exit(1)});process.on("unhandledRejection",t=>{let e=t instanceof Error?t.message:String(t);S("error","Unhandled rejection",{error:e})});$({type:"ready"});S("info","SDK bridge ready");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibetonomy/agent",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.36",
|
|
4
4
|
"description": "Vibetonomy agent — managed Claude Code sessions via npx",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "module",
|
|
@@ -15,11 +15,11 @@
|
|
|
15
15
|
"@anthropic-ai/claude-agent-sdk": "0.3.248"
|
|
16
16
|
},
|
|
17
17
|
"optionalDependencies": {
|
|
18
|
-
"@vibetonomy/agent-linux-x64": "1.5.
|
|
19
|
-
"@vibetonomy/agent-linux-arm64": "1.5.
|
|
20
|
-
"@vibetonomy/agent-darwin-arm64": "1.5.
|
|
21
|
-
"@vibetonomy/agent-darwin-x64": "1.5.
|
|
22
|
-
"@vibetonomy/agent-win-x64": "1.5.
|
|
18
|
+
"@vibetonomy/agent-linux-x64": "1.5.36",
|
|
19
|
+
"@vibetonomy/agent-linux-arm64": "1.5.36",
|
|
20
|
+
"@vibetonomy/agent-darwin-arm64": "1.5.36",
|
|
21
|
+
"@vibetonomy/agent-darwin-x64": "1.5.36",
|
|
22
|
+
"@vibetonomy/agent-win-x64": "1.5.36"
|
|
23
23
|
},
|
|
24
24
|
"engines": {
|
|
25
25
|
"node": ">=18.0.0"
|