@swifty.js/swifty 0.0.6 → 0.0.8

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.
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __swiftyCreateRequire } from "node:module";
3
3
  const require = __swiftyCreateRequire(import.meta.url);
4
- import{j as a}from"./chunk-IZ23BHLA.js";import"./chunk-DCI5RJC7.js";import"./chunk-FZPTNGTU.js";import"./chunk-4KVSJNS6.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{a as Agent};
4
+ import{j as a}from"./chunk-A6H62GTA.js";import"./chunk-OXEMDMZF.js";import"./chunk-FZPTNGTU.js";import"./chunk-ISXLT3QN.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{a as Agent};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __swiftyCreateRequire } from "node:module";
3
3
  const require = __swiftyCreateRequire(import.meta.url);
4
- import{l as C}from"./chunk-DCI5RJC7.js";import{g as w}from"./chunk-H7VXSMJR.js";import{e as D,g as F,h as R}from"./chunk-HU7ELU2V.js";import{b as B,c as U,d as M,e as $,f as K,g as W}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{H as P,J as v,K as O,L as I,M as k,N as j,e as S,l as N}from"./chunk-4KVSJNS6.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";var x=S({module:"llm"});var Y=3e3,q=P.object({max_input_tokens:P.coerce.number()});async function at(o){if(o.protocol!=="anthropic")return 0;let t=R(o),s=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,n=new AbortController,a=setTimeout(()=>{n.abort()},Y);try{let l=await fetch(s,{method:"GET",headers:{"anthropic-version":"2023-06-01",...t?{"x-api-key":t}:{}},signal:n.signal});if(!l.ok)return 0;let g=await l.json(),{success:h,error:d,data:f}=await N(q,g);if(!h)return console.error(d.message),0;let y=f.max_input_tokens;return Math.max(y,0)}catch(l){return console.error(l),0}finally{clearTimeout(a)}}function J(){return!0}function H(o){return(o??[]).map(t=>({type:"image",source:{type:"base64",media_type:t.mediaType,data:t.data}}))}function L(o){let t=[];return(o.content||!o.images?.length)&&t.push({type:"text",text:o.content}),t.push(...H(o.images)),t}function z(o){let t=[];for(let e of o)if(e.role==="assistant"){let s=[];if(e.thinkingBlocks)for(let n of e.thinkingBlocks)s.push({type:"thinking",thinking:n.thinking,signature:n.signature});if(e.content&&s.push({type:"text",text:e.content}),e.toolUses)for(let n of e.toolUses)s.push({type:"tool_use",id:n.toolUseId,name:n.toolName,input:n.arguments});s.length===0&&s.push({type:"text",text:""}),t.push({role:"assistant",content:s})}else if(e.toolResults&&e.toolResults.length>0){let s=[];for(let n of e.toolResults)s.push({type:"tool_result",tool_use_id:n.toolUseId,is_error:n.isError,content:n.images?.length?[{type:"text",text:n.content},...H(n.images)]:n.content});t.push({role:"user",content:s})}else{if(t.length===0){t.push({role:"user",content:L(e)});continue}let s=!1,n=t[t.length-1],a=n.content;n.role==="user"&&(typeof a=="string"||Array.isArray(a)&&a.length>0&&(a[0].type==="text"||a[0].type==="image"))&&(s=!0),s?(typeof a=="string"&&(a=n.content=a.trim().length>0?[{type:"text",text:a}]:[]),a.push(...L(e))):t.push({role:"user",content:L(e)})}return t}var G=class{client;model;thinking;systemPrompt;maxOutputTokens;contextWindow;constructor(t,e){let s=R(t);if(!s)throw new M("Anthropic API key not found, set ANTHROPIC_API_KEY in .swifty/config.y(a)ml, or via ANTHROPIC_API_KEY env variable.");this.client=new w({apiKey:s,baseURL:t.base_url}),this.model=t.model,this.thinking=t.thinking??!0,this.systemPrompt=e,this.maxOutputTokens=F(t),this.contextWindow=D(t)}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.maxOutputTokens=t}async*stream(t,e,s){let n=z(B(t.getMessages())),a=e.map(c=>{let p=c.input_schema;return{name:c.name,description:c.description,input_schema:{type:"object",properties:p.properties,required:p.required??[]}}});a.length>0&&(a[a.length-1].cache_control={type:"ephemeral"}),Q(n);let l={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:n,...a.length>0?{tools:a}:{}};this.thinking?J()&&(l.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)}):l.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)};let g=0,h=0,d=0,f=0,y="end_turn",b="",A="",T=!1,E=0;try{let c=this.client.messages.stream(l,{...s?{signal:s}:{}}),p="",_="",u="";for await(let i of c)switch(i.type){case"content_block_start":{let r=i.content_block;r.type==="thinking"?(T=!0,b="",A=""):r.type==="tool_use"&&(_=r.id,p=r.name,u="",yield{type:"tool_call_start",toolName:p,toolId:_});break}case"content_block_delta":{let r=i.delta;r.type==="thinking_delta"?(b+=r.thinking,yield{type:"thinking_delta",text:r.thinking}):r.type==="signature_delta"?(x.debug({signature:r.signature},"thinking signature received"),A=r.signature):r.type==="text_delta"?yield{type:"text_delta",text:r.text}:r.type==="input_json_delta"&&(u+=r.partial_json,yield{type:"tool_call_delta",text:r.partial_json});break}case"content_block_stop":{if(T&&(yield{type:"thinking_complete",thinking:b,signature:A},T=!1),p){let r={};if(u)try{let m=JSON.parse(u);r=O(m)?I(m):{[v]:u}}catch(m){x.error({err:m},"llm operation failed"),r={[v]:u}}yield{type:"tool_call_complete",toolId:_,toolName:p,arguments:r},p="",_="",u=""}break}case"message_delta":{i.delta.stop_reason&&(y=i.delta.stop_reason),i.usage.output_tokens&&(h=i.usage.output_tokens,i.usage.input_tokens&&(g=i.usage.input_tokens),i.usage.cache_read_input_tokens&&(d=i.usage.cache_read_input_tokens),i.usage.cache_creation_input_tokens&&(f=i.usage.cache_creation_input_tokens));break}case"message_start":{E=Date.now(),g=i.message.usage.input_tokens,h=i.message.usage.output_tokens,d=i.message.usage.cache_read_input_tokens??0,f=i.message.usage.cache_creation_input_tokens??0;break}case"message_stop":{let m=Date.now()-E;x.debug({elapsedMs:m},"message stream complete");break}}yield{type:"stream_end",stopReason:y,usage:{inputTokens:g,outputTokens:h,cacheReadInputTokens:d,cacheCreationInputTokens:f}}}catch(c){throw x.error({err:c},"llm operation failed"),V(c)}}};function Q(o){for(let t=o.length-1;t>=0;t--){if(o[t].role!=="user")continue;let e=o[t].content;if(typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0)return;typeof e=="string"&&(e=o[t].content=[{type:"text",text:e}]);let s=e[e.length-1];for(let n=e.length-1;n>=0;n--)if(e[n].type!=="image"){s=e[n];break}Reflect.set(s,"cache_control",{type:"ephemeral"})}}function V(o){if(o instanceof w.APIError){if(o.status===413||/prompts?\s+too\s+long/i.test(o.message))return new W(`Prompt too long: ${o.message}`);if(o.status===401)return new M(`Invalid API key: ${o.message}`);if(o.status===429){let t=I(o.headers)["retry-after"],e="Rate Limited";if(t){let s=Number.parseInt(k(t));Number.isNaN(s)&&(e+=", please wait."),e+=`, retry after ${k(s)}s.`}else e+=", please wait.";return new $(e,t?k(t):void 0)}return new U(`Anthropic API error (${k(o.status)}): ${o.message}`)}return new K(`Network error: ${j(o)}`)}export{G as AnthropicClient,z as buildAnthropicMessages,at as fetchModelContextWindow,Q as markLastUserTailForCache};
4
+ import{g as w}from"./chunk-H7VXSMJR.js";import{l as C}from"./chunk-OXEMDMZF.js";import{e as D,g as F,h as R}from"./chunk-LVLDD2BE.js";import{b as O,c as U,d as M,e as $,f as K,g as W}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{C as P,I as N,J as v,K as j,L as I,M as k,N as B,g as S}from"./chunk-ISXLT3QN.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";var x=N({module:"llm"});var Y=3e3,q=P.object({max_input_tokens:P.coerce.number()});async function at(o){if(o.protocol!=="anthropic")return 0;let t=R(o),s=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,n=new AbortController,a=setTimeout(()=>{n.abort()},Y);try{let l=await fetch(s,{method:"GET",headers:{"anthropic-version":"2023-06-01",...t?{"x-api-key":t}:{}},signal:n.signal});if(!l.ok)return 0;let g=await l.json(),{success:h,error:d,data:f}=await S(q,g);if(!h)return console.error(d.message),0;let y=f.max_input_tokens;return Math.max(y,0)}catch(l){return console.error(l),0}finally{clearTimeout(a)}}function J(){return!0}function H(o){return(o??[]).map(t=>({type:"image",source:{type:"base64",media_type:t.mediaType,data:t.data}}))}function L(o){let t=[];return(o.content||!o.images?.length)&&t.push({type:"text",text:o.content}),t.push(...H(o.images)),t}function z(o){let t=[];for(let e of o)if(e.role==="assistant"){let s=[];if(e.thinkingBlocks)for(let n of e.thinkingBlocks)s.push({type:"thinking",thinking:n.thinking,signature:n.signature});if(e.content&&s.push({type:"text",text:e.content}),e.toolUses)for(let n of e.toolUses)s.push({type:"tool_use",id:n.toolUseId,name:n.toolName,input:n.arguments});s.length===0&&s.push({type:"text",text:""}),t.push({role:"assistant",content:s})}else if(e.toolResults&&e.toolResults.length>0){let s=[];for(let n of e.toolResults)s.push({type:"tool_result",tool_use_id:n.toolUseId,is_error:n.isError,content:n.images?.length?[{type:"text",text:n.content},...H(n.images)]:n.content});t.push({role:"user",content:s})}else{if(t.length===0){t.push({role:"user",content:L(e)});continue}let s=!1,n=t[t.length-1],a=n.content;n.role==="user"&&(typeof a=="string"||Array.isArray(a)&&a.length>0&&(a[0].type==="text"||a[0].type==="image"))&&(s=!0),s?(typeof a=="string"&&(a=n.content=a.trim().length>0?[{type:"text",text:a}]:[]),a.push(...L(e))):t.push({role:"user",content:L(e)})}return t}var G=class{client;model;thinking;systemPrompt;maxOutputTokens;contextWindow;constructor(t,e){let s=R(t);if(!s)throw new M("Anthropic API key not found, set ANTHROPIC_API_KEY in .swifty/config.y(a)ml, or via ANTHROPIC_API_KEY env variable.");this.client=new w({apiKey:s,baseURL:t.base_url}),this.model=t.model,this.thinking=t.thinking??!0,this.systemPrompt=e,this.maxOutputTokens=F(t),this.contextWindow=D(t)}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.maxOutputTokens=t}async*stream(t,e,s){let n=z(O(t.getMessages())),a=e.map(c=>{let p=c.input_schema;return{name:c.name,description:c.description,input_schema:{type:"object",properties:p.properties,required:p.required??[]}}});a.length>0&&(a[a.length-1].cache_control={type:"ephemeral"}),Q(n);let l={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:n,...a.length>0?{tools:a}:{}};this.thinking?J()&&(l.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)}):l.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)};let g=0,h=0,d=0,f=0,y="end_turn",b="",A="",T=!1,E=0;try{let c=this.client.messages.stream(l,{...s?{signal:s}:{}}),p="",_="",u="";for await(let i of c)switch(i.type){case"content_block_start":{let r=i.content_block;r.type==="thinking"?(T=!0,b="",A=""):r.type==="tool_use"&&(_=r.id,p=r.name,u="",yield{type:"tool_call_start",toolName:p,toolId:_});break}case"content_block_delta":{let r=i.delta;r.type==="thinking_delta"?(b+=r.thinking,yield{type:"thinking_delta",text:r.thinking}):r.type==="signature_delta"?(x.debug({signature:r.signature},"thinking signature received"),A=r.signature):r.type==="text_delta"?yield{type:"text_delta",text:r.text}:r.type==="input_json_delta"&&(u+=r.partial_json,yield{type:"tool_call_delta",text:r.partial_json});break}case"content_block_stop":{if(T&&(yield{type:"thinking_complete",thinking:b,signature:A},T=!1),p){let r={};if(u)try{let m=JSON.parse(u);r=j(m)?I(m):{[v]:u}}catch(m){x.error({err:m},"llm operation failed"),r={[v]:u}}yield{type:"tool_call_complete",toolId:_,toolName:p,arguments:r},p="",_="",u=""}break}case"message_delta":{i.delta.stop_reason&&(y=i.delta.stop_reason),i.usage.output_tokens&&(h=i.usage.output_tokens,i.usage.input_tokens&&(g=i.usage.input_tokens),i.usage.cache_read_input_tokens&&(d=i.usage.cache_read_input_tokens),i.usage.cache_creation_input_tokens&&(f=i.usage.cache_creation_input_tokens));break}case"message_start":{E=Date.now(),g=i.message.usage.input_tokens,h=i.message.usage.output_tokens,d=i.message.usage.cache_read_input_tokens??0,f=i.message.usage.cache_creation_input_tokens??0;break}case"message_stop":{let m=Date.now()-E;x.debug({elapsedMs:m},"message stream complete");break}}yield{type:"stream_end",stopReason:y,usage:{inputTokens:g,outputTokens:h,cacheReadInputTokens:d,cacheCreationInputTokens:f}}}catch(c){throw x.error({err:c},"llm operation failed"),V(c)}}};function Q(o){for(let t=o.length-1;t>=0;t--){if(o[t].role!=="user")continue;let e=o[t].content;if(typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0)return;typeof e=="string"&&(e=o[t].content=[{type:"text",text:e}]);let s=e[e.length-1];for(let n=e.length-1;n>=0;n--)if(e[n].type!=="image"){s=e[n];break}Reflect.set(s,"cache_control",{type:"ephemeral"})}}function V(o){if(o instanceof w.APIError){if(o.status===413||/prompts?\s+too\s+long/i.test(o.message))return new W(`Prompt too long: ${o.message}`);if(o.status===401)return new M(`Invalid API key: ${o.message}`);if(o.status===429){let t=I(o.headers)["retry-after"],e="Rate Limited";if(t){let s=Number.parseInt(k(t));Number.isNaN(s)&&(e+=", please wait."),e+=`, retry after ${k(s)}s.`}else e+=", please wait.";return new $(e,t?k(t):void 0)}return new U(`Anthropic API error (${k(o.status)}): ${o.message}`)}return new K(`Network error: ${B(o)}`)}export{G as AnthropicClient,z as buildAnthropicMessages,at as fetchModelContextWindow,Q as markLastUserTailForCache};
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __swiftyCreateRequire } from "node:module";
3
3
  const require = __swiftyCreateRequire(import.meta.url);
4
- import{a,b,c,d,e}from"./chunk-S2DPVNBA.js";import"./chunk-7MHXMDYC.js";import"./chunk-4KVSJNS6.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{b as PathSandbox,e as PermissionChecker,d as RuleEngine,c as evaluateRules,a as extractContent};
4
+ import{a,b,c,d,e}from"./chunk-ZSJ2I5WM.js";import"./chunk-7MHXMDYC.js";import"./chunk-ISXLT3QN.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{b as PathSandbox,e as PermissionChecker,d as RuleEngine,c as evaluateRules,a as extractContent};
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __swiftyCreateRequire } from "node:module";
3
3
  const require = __swiftyCreateRequire(import.meta.url);
4
- import{b as F,c as N,d as M,e as L,g as D,m as O,n as U,o as W}from"./chunk-DCI5RJC7.js";import{a as _,e as A,g as C}from"./chunk-FZPTNGTU.js";import{L as T,N as I,O as P,R as x,e as f}from"./chunk-4KVSJNS6.js";import{extname as de}from"path";var j={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Fe=new Set(Object.keys(j));function pe(o){return j[de(o).toLowerCase()]??null}function Y(o){return pe(o)!==null}function Ne(o){return o.length>=8&&o[0]===137&&o[1]===80&&o[2]===78&&o[3]===71?"image/png":o.length>=3&&o[0]===255&&o[1]===216&&o[2]===255?"image/jpeg":o.length>=6&&o[0]===71&&o[1]===73&&o[2]===70?"image/gif":o.length>=12&&o[0]===82&&o[1]===73&&o[2]===70&&o[3]===70&&o[8]===87&&o[9]===69&&o[10]===66&&o[11]===80?"image/webp":null}var me=f({module:"agent"}),w=class{pending=[];registry;ctx;constructor(e,t){this.registry=e,this.ctx=t}submit(e,t,s){this.pending.push({toolId:e,toolName:t,arguments:s})}async collectResults(){let e=[...this.pending];this.pending=[];let t=e.map(async s=>{let i=this.registry.get(s.toolName),n=Date.now();if(!i)return{toolId:s.toolId,toolName:s.toolName,result:{output:`Error: unknown tool '${s.toolName}'`,isError:!0},elapsed:0};try{let r=await i.execute(this.ctx,s.arguments);return{toolId:s.toolId,toolName:s.toolName,result:r,elapsed:(Date.now()-n)/1e3}}catch(r){return me.error({err:r},"agent operation failed"),{toolId:s.toolId,toolName:s.toolName,result:{output:`Error executing ${s.toolName}: ${I(r)}`,isError:!0},elapsed:(Date.now()-n)/1e3}}});return Promise.all(t)}hasPending(){return this.pending.length>0}};function b(o){return o?Math.floor(o.length/3.5):0}function B(o,e){if(e<=0||!o||b(o)<=e)return o;let t=Math.floor(e*3.5);return t<=0||t>=o.length?o:o.slice(0,t)+`
5
- \u2026 (content truncated)`}var v=class{files=new Map;skills=new Map;recordFileRead(e,t){this.files.set(e,{path:e,content:t,timestamp:Date.now()})}recordSkillInvocation(e,t){this.skills.set(e,{name:e,body:t,timestamp:Date.now()})}snapshotFiles(e=5){return[...this.files.values()].sort((s,i)=>i.timestamp-s.timestamp).slice(0,e)}snapshotSkills(){return[...this.skills.values()].sort((e,t)=>t.timestamp-e.timestamp)}buildRecoveryAttachment(e){let t=[],s=this.snapshotFiles();if(s.length>0){t.push(`## Recently read files
4
+ import{b as F,c as N,d as M,e as L,g as D,m as O,n as U,o as W}from"./chunk-OXEMDMZF.js";import{a as T,e as A,g as C}from"./chunk-FZPTNGTU.js";import{I as f,L as I,N as P,O as _,R as x}from"./chunk-ISXLT3QN.js";import{readFile as Ie}from"fs/promises";function b(o){return o?Math.floor(o.length/3.5):0}function j(o,e){if(e<=0||!o||b(o)<=e)return o;let t=Math.floor(e*3.5);return t<=0||t>=o.length?o:o.slice(0,t)+`
5
+ \u2026 (content truncated)`}var w=class{files=new Map;skills=new Map;recordFileRead(e,t){this.files.set(e,{path:e,content:t,timestamp:Date.now()})}recordSkillInvocation(e,t){this.skills.set(e,{name:e,body:t,timestamp:Date.now()})}snapshotFiles(e=5){return[...this.files.values()].sort((s,i)=>i.timestamp-s.timestamp).slice(0,e)}snapshotSkills(){return[...this.skills.values()].sort((e,t)=>t.timestamp-e.timestamp)}buildRecoveryAttachment(e){let t=[],s=this.snapshotFiles();if(s.length>0){t.push(`## Recently read files
6
6
  `),t.push(`These snapshots are what the file-reading tool last returned. Re-open with the tool if you need the current bytes.
7
- `);for(let n of s){let r=B(n.content,5e3),l=new Date(n.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${n.path} (read ${l})
7
+ `);for(let n of s){let r=j(n.content,5e3),l=new Date(n.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${n.path} (read ${l})
8
8
 
9
9
  \`\`\`
10
10
  ${r}${r.endsWith(`
11
11
  `)?"":`
12
12
  `}\`\`\``)}}let i=this.snapshotSkills();if(i.length>0){let n=0,r=[];r.push(`## Active skills
13
13
  `),r.push(`These skills were invoked earlier in the session. Continue to follow each SOP when its triggering condition applies.
14
- `);let l=!1;for(let u of i){let d=B(u.body,5e3),g=b(d)+b(u.name)+8;if(n+g>25e3)break;n+=g,r.push(`### ${u.name}
14
+ `);let l=!1;for(let u of i){let d=j(u.body,5e3),g=b(d)+b(u.name)+8;if(n+g>25e3)break;n+=g,r.push(`### ${u.name}
15
15
 
16
16
  ${d}`),l=!0}l&&t.push(r.join(`
17
17
 
@@ -24,54 +24,7 @@ You still have access to the following tools \u2014 call them directly when the
24
24
 
25
25
  Everything above the divider is reconstructed context. For exact code, error strings, or user-typed text, re-read the source rather than guess from the summary.`),t.join(`
26
26
 
27
- `))}};import{readFileSync as ge,writeFileSync as fe,mkdirSync as ye,existsSync as S}from"fs";import{join as $,resolve as H}from"path";var q=f({module:"plan-file"}),V=["brave","calm","dark","eager","fair","gentle","happy","kind","lively","mighty","noble","proud","quiet","swift","warm","wise"],G=["crystal","dragon","eagle","falcon","flame","forest","frost","mountain","ocean","phoenix","river","shadow","thunder","tiger"];function ke(){let o=V[Math.floor(Math.random()*V.length)],e=G[Math.floor(Math.random()*G.length)],t=Date.now().toString(36).slice(-4);return`${o}-${e}-${t}`}var m=null;function K(o,e){let t=H(e,".swifty","plans");return H(o).startsWith(t+"/")}function z(o){if(m&&S(m))if(!K(m,o))q.warn({planPath:m,workDir:o},"current plan path is not under work dir");else return m;let e=$(o,".swifty","plans");ye(e,{recursive:!0});let t=ke();return m=$(e,`${t}.md`),fe(m,"","utf-8"),m}function Be(){return!m||!S(m)?null:ge(m,"utf-8")}function X(o){return!m||!S(m)?!1:K(m,o)?!0:(q.warn({planPath:m,workDir:o},"current plan path is not under work dir"),!1)}function $e(){m=null}var J=`Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
28
-
29
- ## Plan File Info:
30
-
31
- %PLAN_FILE_INFO%
32
- You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
33
-
34
- ## Plan Workflow
35
-
36
- ### Phase 1: Initial Understanding
37
-
38
- Goal: Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should use the Agent tool with subagent_type="explore".
39
-
40
- 1. Focus on understanding the user's request and the code associated with their request. Actively search for existing functions, utilities, and patterns that can be reused \u2014 avoid proposing new code when suitable implementations already exist.
41
-
42
- 2. **Call the Agent tool with subagent_type="explore" to explore the codebase.** You can launch up to 3 explore agents IN PARALLEL by making multiple Agent tool calls in a single response.
43
-
44
- ### Phase 2: Design
45
-
46
- Goal: Design an implementation approach.
47
-
48
- Call the Agent tool with subagent_type="plan" to design the implementation based on the user's intent and your exploration results from Phase 1.
49
-
50
- ### Phase 3: Review
51
-
52
- Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
53
-
54
- 1. Read the critical files identified by agents to deepen your understanding
55
- 2. Ensure that the plans align with the user's original request
56
- 3. Use AskUserQuestion to clarify any remaining questions with the user.
57
-
58
- ### Phase 4: Final Plan
59
-
60
- Goal: Write your final plan to the plan file (the only file you can edit).
61
-
62
- - Begin with a **Context** section
63
- - Include only your recommended approach
64
- - Include the paths of critical files to be modified
65
- - Include a verification section
66
-
67
- ### Phase 5: Call ExitPlanMode
68
-
69
- At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call ExitPlanMode.
70
- `,we="Plan mode still active (see full instructions earlier in conversation). Read-only except plan file (%PLAN_PATH%). Follow 5-phase workflow. End turns with AskUserQuestion (for clarifications) or ExitPlanMode (for plan approval). Never ask about plan approval via text or AskUserQuestion.",ve=`## Exited Plan Mode
71
-
72
- You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`,Re="You have re-entered plan mode. Your previous plan file is at %PLAN_PATH%. Review it and continue from where you left off. You can update, refine, or restart the plan as needed. Follow the same 5-phase workflow as before.";function Q(o,e,t){let s=`Plan file: ${o}`;return e?s+=`
73
- A plan file already exists at ${o}. You can read it and make incremental edits using the EditFile tool.`:s+=`
74
- No plan file exists yet. You should create your plan at ${o} using the WriteFile tool.`,t===1||Math.floor((t-1)/5)%5===0?J.replace("%PLAN_FILE_INFO%",s):we.replace("%PLAN_PATH%",o)}function Ve(o,e){let t="";return e&&(t=` The plan file is located at ${o} if you need to reference it.`),ve.replace("%EXTRA%",t)}function Ge(o,e){return e?Re.replace("%PLAN_PATH%",o):""}var xe=`You are Swifty, an AI assistant that orchestrates software engineering tasks across multiple workers.
27
+ `))}};import{extname as de}from"path";var Y={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Ne=new Set(Object.keys(Y));function pe(o){return Y[de(o).toLowerCase()]??null}function B(o){return pe(o)!==null}function Me(o){return o.length>=8&&o[0]===137&&o[1]===80&&o[2]===78&&o[3]===71?"image/png":o.length>=3&&o[0]===255&&o[1]===216&&o[2]===255?"image/jpeg":o.length>=6&&o[0]===71&&o[1]===73&&o[2]===70?"image/gif":o.length>=12&&o[0]===82&&o[1]===73&&o[2]===70&&o[3]===70&&o[8]===87&&o[9]===69&&o[10]===66&&o[11]===80?"image/webp":null}import{readFileSync as me,writeFileSync as ge,mkdirSync as fe,existsSync as S}from"fs";import{join as $,resolve as H}from"path";var q=f({module:"plan-file"}),V=["brave","calm","dark","eager","fair","gentle","happy","kind","lively","mighty","noble","proud","quiet","swift","warm","wise"],G=["crystal","dragon","eagle","falcon","flame","forest","frost","mountain","ocean","phoenix","river","shadow","thunder","tiger"];function ye(){let o=V[Math.floor(Math.random()*V.length)],e=G[Math.floor(Math.random()*G.length)],t=Date.now().toString(36).slice(-4);return`${o}-${e}-${t}`}var m=null;function K(o,e){let t=H(e,".swifty","plans");return H(o).startsWith(t+"/")}function z(o){if(m&&S(m))if(!K(m,o))q.warn({planPath:m,workDir:o},"current plan path is not under work dir");else return m;let e=$(o,".swifty","plans");fe(e,{recursive:!0});let t=ye();return m=$(e,`${t}.md`),ge(m,"","utf-8"),m}function We(){return!m||!S(m)?null:me(m,"utf-8")}function X(o){return!m||!S(m)?!1:K(m,o)?!0:(q.warn({planPath:m,workDir:o},"current plan path is not under work dir"),!1)}function je(){m=null}var ke=`You are Swifty, an AI assistant that orchestrates software engineering tasks across multiple workers.
75
28
 
76
29
  ## 1. Your Role
77
30
 
@@ -224,12 +177,59 @@ You:
224
177
 
225
178
  SendMessage({ to: "investigator", message: "Fix the null pointer in src/auth/validate.ts:42. Add a null check before accessing user.id \u2014 if null, return 401. Commit and report the hash." })
226
179
 
227
- Fix is in progress.`,be="Coordinator mode still active (see full instructions earlier in conversation). You cannot read files, run commands, or edit code \u2014 send a worker instead. Tools: Agent, SendMessage, TaskStop, SyntheticOutput, TeamDelete. Address workers by the name in the from= field of a team-notification. Synthesize worker findings yourself before directing follow-up work.";function Z(o=1){return o<=1||(o-1)%5===0?xe:be}import{writeFileSync as Se,mkdirSync as Ee}from"fs";import{join as oe,resolve as ee}from"path";var Te=f({module:"tool-result"}),te=2e5;function ne(o,e){return oe(o,".swifty","sessions",e||"default","tool-results")}function se(o,e,t,s){let i=ne(o,e);Ee(i,{recursive:!0});let n=oe(i,t+".txt");try{Se(n,s,{encoding:"utf-8",flag:"wx"})}catch(r){if(Te.error({err:r},"tool-result operation failed"),P(r)&&"code"in r&&r.code!=="EEXIST")throw r}return n}var E=2e3;function ie(o,e){let t=Math.floor(o.length/1024),s=o.slice(0,E),i=o.length>E,n=`<persisted-output>
180
+ Fix is in progress.`,we="Coordinator mode still active (see full instructions earlier in conversation). You cannot read files, run commands, or edit code \u2014 send a worker instead. Tools: Agent, SendMessage, TaskStop, SyntheticOutput, TeamDelete. Address workers by the name in the from= field of a team-notification. Synthesize worker findings yourself before directing follow-up work.";function J(o=1){return o<=1||(o-1)%5===0?ke:we}var Q=`Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
181
+
182
+ ## Plan File Info:
183
+
184
+ %PLAN_FILE_INFO%
185
+ You should build your plan incrementally by writing to or editing this file. NOTE that this is the only file you are allowed to edit - other than this you are only allowed to take READ-ONLY actions.
186
+
187
+ ## Plan Workflow
188
+
189
+ ### Phase 1: Initial Understanding
190
+
191
+ Goal: Gain a comprehensive understanding of the user's request by reading through code and asking them questions. Critical: In this phase you should use the Agent tool with subagent_type="explore".
192
+
193
+ 1. Focus on understanding the user's request and the code associated with their request. Actively search for existing functions, utilities, and patterns that can be reused \u2014 avoid proposing new code when suitable implementations already exist.
194
+
195
+ 2. **Call the Agent tool with subagent_type="explore" to explore the codebase.** You can launch up to 3 explore agents IN PARALLEL by making multiple Agent tool calls in a single response.
196
+
197
+ ### Phase 2: Design
198
+
199
+ Goal: Design an implementation approach.
200
+
201
+ Call the Agent tool with subagent_type="plan" to design the implementation based on the user's intent and your exploration results from Phase 1.
202
+
203
+ ### Phase 3: Review
204
+
205
+ Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
206
+
207
+ 1. Read the critical files identified by agents to deepen your understanding
208
+ 2. Ensure that the plans align with the user's original request
209
+ 3. Use AskUserQuestion to clarify any remaining questions with the user.
210
+
211
+ ### Phase 4: Final Plan
212
+
213
+ Goal: Write your final plan to the plan file (the only file you can edit).
214
+
215
+ - Begin with a **Context** section
216
+ - Include only your recommended approach
217
+ - Include the paths of critical files to be modified
218
+ - Include a verification section
219
+
220
+ ### Phase 5: Call ExitPlanMode
221
+
222
+ At the very end of your turn, once you have asked the user questions and are happy with your final plan file - you should always call ExitPlanMode.
223
+ `,ve="Plan mode still active (see full instructions earlier in conversation). Read-only except plan file (%PLAN_PATH%). Follow 5-phase workflow. End turns with AskUserQuestion (for clarifications) or ExitPlanMode (for plan approval). Never ask about plan approval via text or AskUserQuestion.",Re=`## Exited Plan Mode
224
+
225
+ You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`,xe="You have re-entered plan mode. Your previous plan file is at %PLAN_PATH%. Review it and continue from where you left off. You can update, refine, or restart the plan as needed. Follow the same 5-phase workflow as before.";function Z(o,e,t){let s=`Plan file: ${o}`;return e?s+=`
226
+ A plan file already exists at ${o}. You can read it and make incremental edits using the EditFile tool.`:s+=`
227
+ No plan file exists yet. You should create your plan at ${o} using the WriteFile tool.`,t===1||Math.floor((t-1)/5)%5===0?Q.replace("%PLAN_FILE_INFO%",s):ve.replace("%PLAN_PATH%",o)}function $e(o,e){let t="";return e&&(t=` The plan file is located at ${o} if you need to reference it.`),Re.replace("%EXTRA%",t)}function He(o,e){return e?xe.replace("%PLAN_PATH%",o):""}import{writeFileSync as be,mkdirSync as Se}from"fs";import{join as oe,resolve as ee}from"path";var Ee=f({module:"tool-result"}),te=2e5;function ne(o,e){return oe(o,".swifty","sessions",e||"default","tool-results")}function se(o,e,t,s){let i=ne(o,e);Se(i,{recursive:!0});let n=oe(i,t+".txt");try{be(n,s,{encoding:"utf-8",flag:"wx"})}catch(r){if(Ee.error({err:r},"tool-result operation failed"),_(r)&&"code"in r&&r.code!=="EEXIST")throw r}return n}var E=2e3;function ie(o,e){let t=Math.floor(o.length/1024),s=o.slice(0,E),i=o.length>E,n=`<persisted-output>
228
228
  `;return n+=`Output too large (${String(t)}KB). Full content saved to:
229
229
  ${e}
230
230
 
231
231
  `,n+=`Preview (first 2KB):
232
232
  ${s}`,i&&(n+=`
233
233
  ...`),n+=`
234
- </persisted-output>`,n}function re(o,e,t,s){if(o!=="ReadFile"||!e)return!1;let i=e.file_path;return typeof i!="string"||!i?!1:ee(i).startsWith(ee(ne(t,s)))}function ae(o,e,t,s){let i=o.reduce((r,l)=>r+l.content.length,0);if(i<=te)return;let n=[...o].sort((r,l)=>l.content.length-r.content.length);for(let r of n){if(i<=te)break;if(s?.has(r.toolUseId)||r.images?.length||r.content.length<=E)continue;let l;try{l=se(e,t,r.toolUseId,r.content)}catch{continue}let u=ie(r.content,l);i-=r.content.length-u.length,r.content=u}}function le(o,e,t,s){let i;try{i=se(o,e,t,s)}catch{return s}return ie(s,i)}import{readFile as Ie}from"fs/promises";var Pe=64e3,ce=3,_e=5e4,he=class{client;registry;checker;conversation;workDir;sessionId;sessionFilePath;hookEngine;fileHistory;fileStateCache;abortSignal;contextWindow;maxOutput;recoveryState;maxIterations;notificationFn;onLoopComplete;compactTracking=new O;onPermissionRequest;toolFilter;coordinatorActiveFn;activeSkills;instructions;memoryContent;skillSection;skillDeltaFn;memoryRecallPromise;memoryRecallConsumed=!1;constructor(e){this.client=e.client,this.registry=e.registry,this.checker=e.checker,this.conversation=e.conversation,this.workDir=e.workDir,this.sessionId=e.sessionId??"",this.sessionFilePath=e.sessionId?L(e.workDir,e.sessionId):"",this.hookEngine=e.hookEngine,this.fileHistory=e.fileHistory,this.fileStateCache=e.fileStateCache,this.abortSignal=e.abortSignal,this.contextWindow=e.contextWindow??2e5,this.maxOutput=e.maxOutput??8192,this.recoveryState=e.recoveryState??new v,this.maxIterations=e.maxIterations??0,this.notificationFn=e.notificationFn,this.onLoopComplete=e.onLoopComplete,this.onPermissionRequest=e.onPermissionRequest,this.activeSkills=e.activeSkills??new Map,this.toolFilter=e.toolFilter,this.coordinatorActiveFn=e.coordinatorActiveFn,this.instructions=e.instructions??"",this.memoryContent=e.memoryContent??"",this.skillSection=e.skillSection??"",this.skillDeltaFn=e.skillDeltaFn,this.memoryRecallPromise=e.memoryRecallPromise}async*run(){let e=this.registry.getAllSchemas();this.toolFilter&&(e=e.filter(r=>this.toolFilter?.(r.name)));let t=this.registry.listTools().map(r=>r.name),s=!1,i=0,n=0;await this.fireLifecycle("session_start");try{let r=!0;for(;r;){if(n++,this.maxIterations>0&&n>this.maxIterations){yield{type:"error",error:new Error(`Agent reached maximum iterations (${String(this.maxIterations)})`)};return}let l="",u=[],d=[],g="end_turn",p=null;if(this.checker.mode==="plan"){let c=z(this.workDir);this.checker.planFilePath=c,this.conversation.addSystemReminder(Q(c,X(this.workDir),n))}if(this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(Z(n)),this.hookEngine)for(let c of this.hookEngine.drainNotifications())this.conversation.addSystemReminder(c);if(this.notificationFn)for(let c of this.notificationFn())this.conversation.addSystemReminder(c);if(this.skillDeltaFn){let c=this.skillDeltaFn();c&&this.conversation.addSystemReminder(`The following skills became available:
235
- `+c)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let k=await U(this.conversation,this.client,this.contextWindow,this.maxOutput,this.compactTracking,this.recoveryState,t,e,this.sessionFilePath);k.message&&(yield{type:"compact",message:k.message,boundary:k.boundary}),k.compacted&&this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection);try{let c=this.client.stream(this.conversation,e,this.abortSignal);for await(let a of c){if(this.abortSignal?.aborted){r=!1;break}switch(a.type){case"text_delta":l+=a.text,yield{type:"stream_text",text:a.text};break;case"thinking_delta":yield{type:"thinking_text",text:a.text};break;case"thinking_complete":u.push({thinking:a.thinking,signature:a.signature}),yield{type:"thinking_complete",thinking:a.thinking,signature:a.signature};break;case"tool_call_start":break;case"tool_call_complete":d.push({toolUseId:a.toolId,toolName:a.toolName,arguments:a.arguments}),yield{type:"tool_use",toolName:a.toolName,toolId:a.toolId,args:a.arguments};break;case"stream_end":g=a.stopReason,p=a.usage,yield{type:"usage",usage:a.usage};break}}}catch(c){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(c instanceof C)try{let a=await W(this.conversation,this.client,this.recoveryState,t,e,this.sessionFilePath);this.conversation.clearUsageAnchor(),this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection),yield{type:"compact",message:"Auto-compacted due to context length: "+a.message,boundary:a.boundary};continue}catch{yield{type:"error",error:c};return}if(c instanceof A){let a=Ae(x(T(c),"retryAfter"));if(yield{type:"retry",reason:"rate limited",delay:a},await this.interruptibleSleep(a)){yield{type:"loop_complete",stopReason:"interrupted"};return}continue}yield{type:"error",error:c instanceof Error?c:new Error(JSON.stringify(c))};return}if(this.abortSignal?.aborted){l&&(this.conversation.addAssistantFull(l,u,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",l),g==="max_tokens")if(s){if(i<ce){i++,this.conversation.addAssistantFull(l,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Break remaining work into smaller pieces."),yield{type:"retry",reason:`max_tokens recovery ${String(i)}/${String(ce)}`,delay:0};continue}}else{this.client.setMaxOutputTokens?.(Pe),s=!0,l&&(this.conversation.addAssistantFull(l,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Do not apologize or repeat previous content. Pick up mid-thought if needed.")),yield{type:"retry",reason:"max_tokens escalation",delay:0};continue}else i=0;if(this.conversation.addAssistantFull(l,u,d),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),d.length>0){let c=await this.executeTools(d);for(let h of c)yield h;let a=new Set;for(let h of d)re(h.toolName,h.arguments,this.workDir,this.sessionId)&&a.add(h.toolUseId);let R=[];for(let h of c)if(h.type==="tool_result"){h.images?.length&&a.add(h.toolId);let y=h.output;y.length>_e&&!a.has(h.toolId)&&(y=le(this.workDir,this.sessionId,h.toolId,h.output),a.add(h.toolId)),R.push({toolUseId:h.toolId,content:y,isError:h.isError,...h.images?.length?{images:h.images}:{}})}ae(R,this.workDir,this.sessionId,a);let ue=d.some(h=>h.toolName==="ExitPlanMode");if(this.conversation.addToolResultsMessage(R),this.persistLastMessage(),this.memoryRecallPromise&&!this.memoryRecallConsumed)try{let h=await Promise.race([this.memoryRecallPromise.then(y=>({done:!0,value:y})),Promise.resolve({done:!1,value:""})]);h.done&&(h.value&&this.conversation.addSystemReminder(h.value),this.memoryRecallConsumed=!0)}catch{this.memoryRecallConsumed=!0}if(ue){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"end_turn"};return}yield{type:"turn_complete"},await this.fireLifecycle("turn_end")}else{if(r=!1,this.fileHistory){let c=l.length>60?l.slice(0,60)+"...":l;this.fileHistory.makeSnapshot(this.conversation.len(),c)}if(yield{type:"loop_complete",stopReason:g},this.onLoopComplete)try{this.onLoopComplete(this.conversation)}catch{}}}}finally{await this.fireLifecycle("session_end")}}async fireLifecycle(e,t){if(!this.hookEngine)return;let s=await this.hookEngine.fire(e,{event:e,message:t});for(let i of s)i.output&&this.hookEngine.recordNotification(i.output)}interruptibleSleep(e){return new Promise(t=>{if(this.abortSignal?.aborted){t(!0);return}let s=()=>{clearTimeout(i),t(!0)},i=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",s),t(!1)},e);this.abortSignal?.addEventListener("abort",s,{once:!0})})}async executeTools(e){let t=[],s=this.partitionToolCalls(e);for(let i of s){let n=await this.executeBatch(i.blocks,i.concurrent&&i.blocks.length>1);t.push(...n)}return t}partitionToolCalls(e){let t=[];for(let s of e){let n=(this.registry.get(s.toolName)?.category??"command")==="read";n&&t.length>0&&t[t.length-1].concurrent?t[t.length-1].blocks.push(s):t.push({concurrent:n,blocks:[s]})}return t}async executeBatch(e,t){let s=[],i=new w(this.registry,{workDir:this.workDir,fileHistory:this.fileHistory,fileStateCache:this.fileStateCache});for(let n of e){if(this.hookEngine){let d=await this.hookEngine.firePreToolHooks(n.toolName,n.arguments);if(d.rejected){s.push({type:"tool_result",toolName:n.toolName,toolId:n.toolUseId,output:`Rejected by hook: ${d.reason}`,isError:!0,elapsed:0});continue}}let l=this.registry.get(n.toolName)?.category??"command",u=this.checker.check(n.toolName,l,n.arguments);if(u.effect==="deny"){s.push({type:"tool_result",toolName:n.toolName,toolId:n.toolUseId,output:`Permission denied: ${u.reason}. This operation has been blocked by the security policy. Inform the user that the command was denied; do not describe what the command would do.`,isError:!0,elapsed:0});continue}if(u.effect==="ask"&&this.onPermissionRequest){let d=await this.onPermissionRequest(n.toolName,n.arguments,u);if(d==="deny"){s.push({type:"tool_result",toolName:n.toolName,toolId:n.toolUseId,output:_,isError:!0,elapsed:0});continue}d==="allowAlways"&&this.checker.allowAlways(n.toolName,n.arguments)}if(i.submit(n.toolUseId,n.toolName,n.arguments),!t){let d=await i.collectResults();for(let g of d)await this.processToolResult(g,e,s)}}if(t){let n=await i.collectResults();for(let r of n)await this.processToolResult(r,e,s)}return s}async processToolResult(e,t,s){if(!e.result.isError&&e.toolName==="ReadFile"){let i=t.find(r=>r.toolUseId===e.toolId),n=x(i?.arguments??{},"file_path");if(n&&!Y(n))try{this.recoveryState.recordFileRead(n,await Ie(n,"utf-8"))}catch{}}if(s.push({type:"tool_result",toolName:e.toolName,toolId:e.toolId,output:e.result.output,isError:e.result.isError,elapsed:e.elapsed,...e.result.images?.length?{images:e.result.images}:{}}),this.hookEngine){let i=await this.hookEngine.fire("post_tool_use",{event:"post_tool_use",toolName:e.toolName,message:e.result.output});for(let n of i)n.output&&this.hookEngine.recordNotification(n.output)}}persistLastMessage(){if(!this.workDir||!this.sessionId)return;let e=this.conversation.getMessages();if(e.length===0)return;let t=e[e.length-1];D(this.workDir,this.sessionId,{role:t.role,content:t.content,timestamp:Math.floor(Date.now()/1e3),...t.toolUses?.length?{tool_uses:N(t.toolUses)}:{},...t.toolResults?.length?{tool_results:M(t.toolResults,{workDir:this.workDir,sessionId:this.sessionId})}:{},...t.images?.length?{images:F(this.workDir,this.sessionId,t.images)}:{}})}};function Ae(o){if(!o)return 5e3;let e=parseInt(o,10);return Number.isNaN(e)?5e3:e*1e3}export{Y as a,Ne as b,v as c,z as d,Be as e,X as f,$e as g,Ve as h,Ge as i,he as j};
234
+ </persisted-output>`,n}function re(o,e,t,s){if(o!=="ReadFile"||!e)return!1;let i=e.file_path;return typeof i!="string"||!i?!1:ee(i).startsWith(ee(ne(t,s)))}function ae(o,e,t,s){let i=o.reduce((r,l)=>r+l.content.length,0);if(i<=te)return;let n=[...o].sort((r,l)=>l.content.length-r.content.length);for(let r of n){if(i<=te)break;if(s?.has(r.toolUseId)||r.images?.length||r.content.length<=E)continue;let l;try{l=se(e,t,r.toolUseId,r.content)}catch{continue}let u=ie(r.content,l);i-=r.content.length-u.length,r.content=u}}function le(o,e,t,s){let i;try{i=se(o,e,t,s)}catch{return s}return ie(s,i)}var Te=f({module:"agent"}),v=class{pending=[];registry;ctx;constructor(e,t){this.registry=e,this.ctx=t}submit(e,t,s){this.pending.push({toolId:e,toolName:t,arguments:s})}async collectResults(){let e=[...this.pending];this.pending=[];let t=e.map(async s=>{let i=this.registry.get(s.toolName),n=Date.now();if(!i)return{toolId:s.toolId,toolName:s.toolName,result:{output:`Error: unknown tool '${s.toolName}'`,isError:!0},elapsed:0};try{let r=await i.execute(this.ctx,s.arguments);return{toolId:s.toolId,toolName:s.toolName,result:r,elapsed:(Date.now()-n)/1e3}}catch(r){return Te.error({err:r},"agent operation failed"),{toolId:s.toolId,toolName:s.toolName,result:{output:`Error executing ${s.toolName}: ${P(r)}`,isError:!0},elapsed:(Date.now()-n)/1e3}}});return Promise.all(t)}hasPending(){return this.pending.length>0}};var Pe=64e3,ce=3,_e=5e4,he=class{client;registry;checker;conversation;workDir;sessionId;sessionFilePath;hookEngine;fileHistory;fileStateCache;abortSignal;contextWindow;maxOutput;recoveryState;maxIterations;notificationFn;onLoopComplete;compactTracking=new O;onPermissionRequest;toolFilter;coordinatorActiveFn;activeSkills;instructions;memoryContent;skillSection;skillDeltaFn;memoryRecallPromise;memoryRecallConsumed=!1;constructor(e){this.client=e.client,this.registry=e.registry,this.checker=e.checker,this.conversation=e.conversation,this.workDir=e.workDir,this.sessionId=e.sessionId??"",this.sessionFilePath=e.sessionId?L(e.workDir,e.sessionId):"",this.hookEngine=e.hookEngine,this.fileHistory=e.fileHistory,this.fileStateCache=e.fileStateCache,this.abortSignal=e.abortSignal,this.contextWindow=e.contextWindow??2e5,this.maxOutput=e.maxOutput??8192,this.recoveryState=e.recoveryState??new w,this.maxIterations=e.maxIterations??0,this.notificationFn=e.notificationFn,this.onLoopComplete=e.onLoopComplete,this.onPermissionRequest=e.onPermissionRequest,this.activeSkills=e.activeSkills??new Map,this.toolFilter=e.toolFilter,this.coordinatorActiveFn=e.coordinatorActiveFn,this.instructions=e.instructions??"",this.memoryContent=e.memoryContent??"",this.skillSection=e.skillSection??"",this.skillDeltaFn=e.skillDeltaFn,this.memoryRecallPromise=e.memoryRecallPromise}async*run(){let e=this.registry.getAllSchemas();this.toolFilter&&(e=e.filter(r=>this.toolFilter?.(r.name)));let t=this.registry.listTools().map(r=>r.name),s=!1,i=0,n=0;await this.fireLifecycle("session_start");try{let r=!0;for(;r;){if(n++,this.maxIterations>0&&n>this.maxIterations){yield{type:"error",error:new Error(`Agent reached maximum iterations (${String(this.maxIterations)})`)};return}let l="",u=[],d=[],g="end_turn",p=null;if(this.checker.mode==="plan"){let c=z(this.workDir);this.checker.planFilePath=c,this.conversation.addSystemReminder(Z(c,X(this.workDir),n))}if(this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(J(n)),this.hookEngine)for(let c of this.hookEngine.drainNotifications())this.conversation.addSystemReminder(c);if(this.notificationFn)for(let c of this.notificationFn())this.conversation.addSystemReminder(c);if(this.skillDeltaFn){let c=this.skillDeltaFn();c&&this.conversation.addSystemReminder(`The following skills became available:
235
+ `+c)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let k=await U(this.conversation,this.client,this.contextWindow,this.maxOutput,this.compactTracking,this.recoveryState,t,e,this.sessionFilePath);k.message&&(yield{type:"compact",message:k.message,boundary:k.boundary}),k.compacted&&this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection);try{let c=this.client.stream(this.conversation,e,this.abortSignal);for await(let a of c){if(this.abortSignal?.aborted){r=!1;break}switch(a.type){case"text_delta":l+=a.text,yield{type:"stream_text",text:a.text};break;case"thinking_delta":yield{type:"thinking_text",text:a.text};break;case"thinking_complete":u.push({thinking:a.thinking,signature:a.signature}),yield{type:"thinking_complete",thinking:a.thinking,signature:a.signature};break;case"tool_call_start":break;case"tool_call_complete":d.push({toolUseId:a.toolId,toolName:a.toolName,arguments:a.arguments}),yield{type:"tool_use",toolName:a.toolName,toolId:a.toolId,args:a.arguments};break;case"stream_end":g=a.stopReason,p=a.usage,yield{type:"usage",usage:a.usage};break}}}catch(c){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(c instanceof C)try{let a=await W(this.conversation,this.client,this.recoveryState,t,e,this.sessionFilePath);this.conversation.clearUsageAnchor(),this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection),yield{type:"compact",message:"Auto-compacted due to context length: "+a.message,boundary:a.boundary};continue}catch{yield{type:"error",error:c};return}if(c instanceof A){let a=Ae(x(I(c),"retryAfter"));if(yield{type:"retry",reason:"rate limited",delay:a},await this.interruptibleSleep(a)){yield{type:"loop_complete",stopReason:"interrupted"};return}continue}yield{type:"error",error:c instanceof Error?c:new Error(JSON.stringify(c))};return}if(this.abortSignal?.aborted){l&&(this.conversation.addAssistantFull(l,u,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",l),g==="max_tokens")if(s){if(i<ce){i++,this.conversation.addAssistantFull(l,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Break remaining work into smaller pieces."),yield{type:"retry",reason:`max_tokens recovery ${String(i)}/${String(ce)}`,delay:0};continue}}else{this.client.setMaxOutputTokens?.(Pe),s=!0,l&&(this.conversation.addAssistantFull(l,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Do not apologize or repeat previous content. Pick up mid-thought if needed.")),yield{type:"retry",reason:"max_tokens escalation",delay:0};continue}else i=0;if(this.conversation.addAssistantFull(l,u,d),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),d.length>0){let c=await this.executeTools(d);for(let h of c)yield h;let a=new Set;for(let h of d)re(h.toolName,h.arguments,this.workDir,this.sessionId)&&a.add(h.toolUseId);let R=[];for(let h of c)if(h.type==="tool_result"){h.images?.length&&a.add(h.toolId);let y=h.output;y.length>_e&&!a.has(h.toolId)&&(y=le(this.workDir,this.sessionId,h.toolId,h.output),a.add(h.toolId)),R.push({toolUseId:h.toolId,content:y,isError:h.isError,...h.images?.length?{images:h.images}:{}})}ae(R,this.workDir,this.sessionId,a);let ue=d.some(h=>h.toolName==="ExitPlanMode");if(this.conversation.addToolResultsMessage(R),this.persistLastMessage(),this.memoryRecallPromise&&!this.memoryRecallConsumed)try{let h=await Promise.race([this.memoryRecallPromise.then(y=>({done:!0,value:y})),Promise.resolve({done:!1,value:""})]);h.done&&(h.value&&this.conversation.addSystemReminder(h.value),this.memoryRecallConsumed=!0)}catch{this.memoryRecallConsumed=!0}if(ue){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"end_turn"};return}yield{type:"turn_complete"},await this.fireLifecycle("turn_end")}else{if(r=!1,this.fileHistory){let c=l.length>60?l.slice(0,60)+"...":l;this.fileHistory.makeSnapshot(this.conversation.len(),c)}if(yield{type:"loop_complete",stopReason:g},this.onLoopComplete)try{this.onLoopComplete(this.conversation)}catch{}}}}finally{await this.fireLifecycle("session_end")}}async fireLifecycle(e,t){if(!this.hookEngine)return;let s=await this.hookEngine.fire(e,{event:e,message:t});for(let i of s)i.output&&this.hookEngine.recordNotification(i.output)}interruptibleSleep(e){return new Promise(t=>{if(this.abortSignal?.aborted){t(!0);return}let s=()=>{clearTimeout(i),t(!0)},i=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",s),t(!1)},e);this.abortSignal?.addEventListener("abort",s,{once:!0})})}async executeTools(e){let t=[],s=this.partitionToolCalls(e);for(let i of s){let n=await this.executeBatch(i.blocks,i.concurrent&&i.blocks.length>1);t.push(...n)}return t}partitionToolCalls(e){let t=[];for(let s of e){let n=(this.registry.get(s.toolName)?.category??"command")==="read";n&&t.length>0&&t[t.length-1].concurrent?t[t.length-1].blocks.push(s):t.push({concurrent:n,blocks:[s]})}return t}async executeBatch(e,t){let s=[],i=new v(this.registry,{workDir:this.workDir,fileHistory:this.fileHistory,fileStateCache:this.fileStateCache});for(let n of e){if(this.hookEngine){let d=await this.hookEngine.firePreToolHooks(n.toolName,n.arguments);if(d.rejected){s.push({type:"tool_result",toolName:n.toolName,toolId:n.toolUseId,output:`Rejected by hook: ${d.reason}`,isError:!0,elapsed:0});continue}}let l=this.registry.get(n.toolName)?.category??"command",u=this.checker.check(n.toolName,l,n.arguments);if(u.effect==="deny"){s.push({type:"tool_result",toolName:n.toolName,toolId:n.toolUseId,output:`Permission denied: ${u.reason}. This operation has been blocked by the security policy. Inform the user that the command was denied; do not describe what the command would do.`,isError:!0,elapsed:0});continue}if(u.effect==="ask"&&this.onPermissionRequest){let d=await this.onPermissionRequest(n.toolName,n.arguments,u);if(d==="deny"){s.push({type:"tool_result",toolName:n.toolName,toolId:n.toolUseId,output:T,isError:!0,elapsed:0});continue}d==="allowAlways"&&this.checker.allowAlways(n.toolName,n.arguments)}if(i.submit(n.toolUseId,n.toolName,n.arguments),!t){let d=await i.collectResults();for(let g of d)await this.processToolResult(g,e,s)}}if(t){let n=await i.collectResults();for(let r of n)await this.processToolResult(r,e,s)}return s}async processToolResult(e,t,s){if(!e.result.isError&&e.toolName==="ReadFile"){let i=t.find(r=>r.toolUseId===e.toolId),n=x(i?.arguments??{},"file_path");if(n&&!B(n))try{this.recoveryState.recordFileRead(n,await Ie(n,"utf-8"))}catch{}}if(s.push({type:"tool_result",toolName:e.toolName,toolId:e.toolId,output:e.result.output,isError:e.result.isError,elapsed:e.elapsed,...e.result.images?.length?{images:e.result.images}:{}}),this.hookEngine){let i=await this.hookEngine.fire("post_tool_use",{event:"post_tool_use",toolName:e.toolName,message:e.result.output});for(let n of i)n.output&&this.hookEngine.recordNotification(n.output)}}persistLastMessage(){if(!this.workDir||!this.sessionId)return;let e=this.conversation.getMessages();if(e.length===0)return;let t=e[e.length-1];D(this.workDir,this.sessionId,{role:t.role,content:t.content,timestamp:Math.floor(Date.now()/1e3),...t.toolUses?.length?{tool_uses:N(t.toolUses)}:{},...t.toolResults?.length?{tool_results:M(t.toolResults,{workDir:this.workDir,sessionId:this.sessionId})}:{},...t.images?.length?{images:F(this.workDir,this.sessionId,t.images)}:{}})}};function Ae(o){if(!o)return 5e3;let e=parseInt(o,10);return Number.isNaN(e)?5e3:e*1e3}export{w as a,B as b,Me as c,z as d,We as e,X as f,je as g,$e as h,He as i,he as j};