@swifty.js/swifty 0.0.2 → 0.0.3

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.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g}from"./chunk-UBV5T4TV.js";import"./chunk-X3UA5OZL.js";export{a as ALL_AGENT_DISALLOWED_TOOLS,d as ASYNC_AGENT_ALLOWED_TOOLS,c as CUSTOM_AGENT_DISALLOWED_TOOLS,f as FORK_QUERY_SOURCE,b as TEAMMATE_DISALLOWED_TOOLS,g as cloneRegistryForFork,e as filterToolsForAgent};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swifty.js/swifty",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "Swifty — CLI coding agent",
5
5
  "keywords": [
6
6
  "ai",
@@ -36,12 +36,11 @@
36
36
  "scripts": {
37
37
  "fe:dev": "cd src/remote/fe && tsup --watch",
38
38
  "fe:build": "cd src/remote/fe && tsup",
39
- "fe:preview": "npx -y serve src/remote/fe/dist",
40
- "prebuild": "pnpm --filter @swifty.js/glob-addon build && pnpm --filter @swifty.js/glob-wasm asbuild:release",
39
+ "fe:preview": "pnpm dlx serve src/remote/fe/dist",
41
40
  "dev": "tsx ./src/main.tsx",
42
41
  "build": "tsup",
43
- "lint": "eslint ./src",
44
- "lint:fix": "eslint --fix ./src",
42
+ "lint": "eslint ./src ./tests",
43
+ "lint:fix": "eslint --fix ./src ./tests",
45
44
  "test": "vitest run",
46
45
  "test:watch": "vitest",
47
46
  "typecheck": "tsc --noEmit -p tsconfig.json",
@@ -72,6 +71,7 @@
72
71
  "pino": "^10.3.1",
73
72
  "react": "19.2.7",
74
73
  "react-dom": "19.2.7",
74
+ "sharp": "^0.35.3",
75
75
  "ws": "^8.21.0",
76
76
  "zod": "^4.4.3"
77
77
  },
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __swiftyCreateRequire } from "node:module";
3
- const require = __swiftyCreateRequire(import.meta.url);
4
- import{q as a}from"./chunk-F6HLYUZ4.js";import"./chunk-FZPTNGTU.js";import"./chunk-4KVSJNS6.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{a as Agent};
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __swiftyCreateRequire } from "node:module";
3
- const require = __swiftyCreateRequire(import.meta.url);
4
- import{g as P}from"./chunk-H7VXSMJR.js";import{f as B,h as W,i as R}from"./chunk-RD3MICOU.js";import{b as O,c as j,d as M,e as U,f as $,g as K}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{H as w,J as v,K as S,L as I,M as k,N,e as L,l as E}from"./chunk-4KVSJNS6.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";var x=L({module:"llm"});var H=3e3,Y=w.object({max_input_tokens:w.coerce.number()});async function ot(n){if(n.protocol!=="anthropic")return 0;let t=R(n),o=`${n.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(n.model)}`,r=new AbortController,a=setTimeout(()=>{r.abort()},H);try{let l=await fetch(o,{method:"GET",headers:{"anthropic-version":"2023-06-01",...t?{"x-api-key":t}:{}},signal:r.signal});if(!l.ok)return 0;let g=await l.json(),{success:h,error:f,data:d}=await E(Y,g);if(!h)return console.error(f.message),0;let y=d.max_input_tokens;return Math.max(y,0)}catch(l){return console.error(l),0}finally{clearTimeout(a)}}function q(){return!0}function D(n){let t=[];for(let e of n)if(e.role==="assistant"){let o=[];if(e.thinkingBlocks)for(let r of e.thinkingBlocks)o.push({type:"thinking",thinking:r.thinking,signature:r.signature});if(e.content&&o.push({type:"text",text:e.content}),e.toolUses)for(let r of e.toolUses)o.push({type:"tool_use",id:r.toolUseId,name:r.toolName,input:r.arguments});o.length===0&&o.push({type:"text",text:""}),t.push({role:"assistant",content:o})}else if(e.toolResults&&e.toolResults.length>0){let o=[];for(let r of e.toolResults)o.push({type:"tool_result",tool_use_id:r.toolUseId,is_error:r.isError,content:r.content});t.push({role:"user",content:o})}else{if(t.length===0){t.push({role:"user",content:[{type:"text",text:e.content}]});continue}let o=!1,r=t[t.length-1],a=r.content;r.role==="user"&&(typeof a=="string"||Array.isArray(a)&&a.length>0&&a[0].type==="text")&&(o=!0),o?(typeof a=="string"&&(a=r.content=a.trim().length>0?[{type:"text",text:a}]:[]),a.push({type:"text",text:e.content})):t.push({role:"user",content:[{type:"text",text:e.content}]})}return t}var G=class{client;model;thinking;systemPrompt;maxOutputTokens;contextWindow;constructor(t,e){let o=R(t);if(!o)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 P({apiKey:o,baseURL:t.base_url}),this.model=t.model,this.thinking=t.thinking??!0,this.systemPrompt=e,this.maxOutputTokens=W(t),this.contextWindow=B(t)}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.maxOutputTokens=t}async*stream(t,e,o){let r=D(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"}),F(r);let l={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:r,...a.length>0?{tools:a}:{}};this.thinking?q()&&(l.thinking={type:"enabled",budget_tokens:this.maxOutputTokens-1}):l.thinking={type:"enabled",budget_tokens:this.maxOutputTokens-1};let g=0,h=0,f=0,d=0,y="end_turn",b="",T="",A=!1,C=0;try{let c=this.client.messages.stream(l,{...o?{signal:o}:{}}),p="",_="",u="";for await(let i of c)switch(i.type){case"content_block_start":{let s=i.content_block;s.type==="thinking"?(A=!0,b="",T=""):s.type==="tool_use"&&(_=s.id,p=s.name,u="",yield{type:"tool_call_start",toolName:p,toolId:_});break}case"content_block_delta":{let s=i.delta;s.type==="thinking_delta"?(b+=s.thinking,yield{type:"thinking_delta",text:s.thinking}):s.type==="signature_delta"?(x.debug({signature:s.signature},"thinking signature received"),T=s.signature):s.type==="text_delta"?yield{type:"text_delta",text:s.text}:s.type==="input_json_delta"&&(u+=s.partial_json,yield{type:"tool_call_delta",text:s.partial_json});break}case"content_block_stop":{if(A&&(yield{type:"thinking_complete",thinking:b,signature:T},A=!1),p){let s={};if(u)try{let m=JSON.parse(u);s=S(m)?I(m):{[v]:u}}catch(m){x.error({err:m},"llm operation failed"),s={[v]:u}}yield{type:"tool_call_complete",toolId:_,toolName:p,arguments:s},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&&(f=i.usage.cache_read_input_tokens),i.usage.cache_creation_input_tokens&&(d=i.usage.cache_creation_input_tokens));break}case"message_start":{C=performance.now(),g=i.message.usage.input_tokens,h=i.message.usage.output_tokens,f=i.message.usage.cache_read_input_tokens??0,d=i.message.usage.cache_creation_input_tokens??0;break}case"message_stop":{let m=performance.now()-C;x.debug({elapsedMs:m},"message stream complete");break}}yield{type:"stream_end",stopReason:y,usage:{inputTokens:g,outputTokens:h,cacheReadInputTokens:f,cacheCreationInputTokens:d}}}catch(c){throw x.error({err:c},"llm operation failed"),J(c)}}};function F(n){for(let t=n.length-1;t>=0;t--){if(n[t].role!=="user")continue;let e=n[t].content;if(typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0)return;typeof e=="string"&&(e=n[t].content=[{type:"text",text:e}]);let o=e[e.length-1];Reflect.set(o,"cache_control",{type:"ephemeral"})}}function J(n){if(n instanceof P.APIError){if(n.status===413||/prompts?\s+too\s+long/i.test(n.message))return new K(`Prompt too long: ${n.message}`);if(n.status===401)return new M(`Invalid API key: ${n.message}`);if(n.status===429){let t=I(n.headers)["retry-after"],e="Rate Limited";if(t){let o=Number.parseInt(k(t));Number.isNaN(o)&&(e+=", please wait."),e+=`, retry after ${k(o)}s.`}else e+=", please wait.";return new U(e,t?k(t):void 0)}return new j(`Anthropic API error (${k(n.status)}): ${n.message}`)}return new $(`Network error: ${N(n)}`)}export{G as AnthropicClient,D as buildAnthropicMessages,ot as fetchModelContextWindow};
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __swiftyCreateRequire } from "node:module";
3
- const require = __swiftyCreateRequire(import.meta.url);
4
- import{a,b,c,d}from"./chunk-6ARDOHBL.js";import"./chunk-7MHXMDYC.js";import"./chunk-4KVSJNS6.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{b as PathSandbox,d as PermissionChecker,c as RuleEngine,a as extractContent};
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __swiftyCreateRequire } from "node:module";
3
- const require = __swiftyCreateRequire(import.meta.url);
4
- import{a as w}from"./chunk-7MHXMDYC.js";import{I as d,R as u,e as P,j as R}from"./chunk-4KVSJNS6.js";import{readFileSync as S,writeFileSync as $,mkdirSync as F,statSync as A}from"fs";import{join as p,resolve as l,dirname as x}from"path";import{homedir as W,tmpdir as j}from"os";var y=P({module:"permissions"}),_=[{re:/rm\s+(-rf?|--recursive)\s+[/~]/,reason:"recursive force delete root"},{re:/rm\s+-rf?\s+\*/,reason:"recursive force delete wildcard"},{re:/mkfs\./,reason:"format disk"},{re:/dd\s+if=/,reason:"direct write to disk device"},{re:/>\s*\/dev\/sd/,reason:"overwrite disk device"},{re:/chmod\s+-R?\s*777\s+\//,reason:"recursive chmod root"},{re:/:\(\)\{\s*:\|\s*:\s*&\s*\}\s*;/,reason:"fork bomb"},{re:/curl\s+.*\|\s*(ba)?sh/,reason:"pipe remote script"},{re:/wget\s+.*\|\s*(ba)?sh/,reason:"pipe remote script"},{re:/git\s+push\s+.*--force/,reason:"force push"},{re:/git\s+reset\s+--hard/,reason:"hard reset"},{re:/git\s+clean\s+-f/,reason:"force clean untracked files"},{re:/git\s+checkout\s+\./,reason:"discard all changes"},{re:/git\s+branch\s+-D/,reason:"force delete branch"}],T=["ls","pwd","echo","cat","head","tail","wc","date","whoami","uname","hostname","which","type","file","git status","git log","git diff","git branch","git show","git rev-parse","git remote","bun test","bun run","npm test","npm run","go test","go build","go vet","python -c","node -e"],L={Bash:"command",ReadFile:"file_path",WriteFile:"file_path",EditFile:"file_path",Glob:"pattern",Grep:"pattern"},M=[".swifty/config.yaml",".swifty/permissions.local.yaml",".swifty/skills/"];function h(o,e){let t=L[o];if(!t)return"";let r=e[t];return typeof r=="string"?r:""}var E=class{allowedRoots;denyWritePaths;projectDir;constructor(e){this.projectDir=l(e),this.allowedRoots=[this.projectDir,j()],this.denyWritePaths=M.map(t=>p(this.projectDir,t))}addRoot(e){this.allowedRoots.push(l(e))}addDenyWrite(e){this.denyWritePaths.push(l(e))}checkDenyWrite(e){let t=l(e);for(let r of this.denyWritePaths)if(t.startsWith(r))return{effect:"deny",reason:`Path ${e} is in deny-write list`};return null}check(e){let t=l(e);for(let r of this.allowedRoots)if(t.startsWith(r))return null;return{effect:"deny",reason:`Path ${e} is outside allowed directories`}}};function O(o,e){let t="^"+o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".")+"$";try{return new RegExp(t).test(e)}catch(r){return y.error({err:r},"permissions operation failed"),!1}}var Y=/^(\w+)\((.+)\)$/;function k(o){let e;try{e=S(o,"utf-8")}catch(s){return s.code!=="ENOENT"&&y.error({err:s},"permissions operation failed"),[]}let t=d.object({rule:d.string().optional(),effect:d.string().optional()}),r;try{let s=w.load(e);r=R(d.array(t),s)}catch(s){return y.error({err:s},"permissions operation failed"),[]}let i=[];for(let s of r){if(s.effect!=="allow"&&s.effect!=="deny"&&s.effect!=="ask")continue;let n=Y.exec((s.rule??"").trim());n&&i.push({tool:n[1],pattern:n[2],effect:s.effect})}return i}var b=class{userPath;projectPath;localPath;constructor(e){this.userPath=p(W(),".swifty","permissions.yaml"),this.projectPath=p(e,".swifty","permissions.yaml"),this.localPath=p(e,".swifty","permissions.local.yaml")}evaluate(e,t){for(let r of[this.userPath,this.projectPath,this.localPath]){let i=k(r);for(let s=i.length-1;s>=0;s--){let n=i[s];if(!(n.tool!==e&&n.tool!=="*")&&O(n.pattern,t))return n.effect}}return null}appendLocalRule(e){F(x(this.localPath),{recursive:!0});let t=k(this.localPath);if(t.some(s=>s.tool===e.tool&&s.pattern===e.pattern&&s.effect===e.effect))return;t.push(e);let i=t.map(s=>({rule:`${s.tool}(${s.pattern})`,effect:s.effect}));$(this.localPath,w.dump(i),"utf-8")}};function C(o){for(let e of _)if(e.re.test(o))return e.reason;return""}function G(o){let e=o.trim();return e.includes(">")||e.includes("|")||e.includes(";")||e.includes("&&")||e.includes("$(")||e.includes("`")?!1:T.some(t=>e===t||e.startsWith(t+" ")||e.startsWith(t+" "))}function I(o,e){switch(o){case"bypassPermissions":return"allow";case"plan":return e==="read"?"allow":"ask";case"acceptEdits":return e==="command"?"ask":"allow";default:return e==="read"?"allow":"ask"}}var D=class{mode;planFilePath="";sandboxEnabled=!1;sandboxAutoAllow=!1;sandbox;ruleEngine;sessionAllowed=new Set;constructor(e,t="default"){this.mode=t,this.sandbox=new E(e),this.ruleEngine=new b(e)}check(e,t,r){let i=h(e,r);if(this.mode==="plan"&&(e==="WriteFile"||e==="EditFile")&&u(r,"file_path","").includes(".swifty/plans/"))return{effect:"allow",reason:"Plan file write allowed in plan mode"};if(t==="command"&&G(i))return{effect:"allow",reason:"Safe read-only command"};let s=t==="command"?C(i):"";if(s)return{effect:"deny",reason:`Dangerous command blocked: ${s}`};if(this.sandboxEnabled&&this.sandboxAutoAllow&&t==="command"){let f=u(r,"command").split(/\s*(?:&&|\|\||[;|])\s*/).map(g=>g.trim()).filter(Boolean),c=!1;for(let g of f){let v=this.ruleEngine.evaluate(e,g);if(v==="deny")return{effect:"deny",reason:"Permission rule: deny"};v==="ask"&&(c=!0)}return c?{effect:"ask",reason:"Permission rule: ask (sandbox does not override)"}:{effect:"allow",reason:"Sandbox auto-allow: OS sandbox active"}}let n=u(r,"file_path",u(r,"path",""));if((t==="read"||t==="write")&&n){if(t==="write"){let c=this.sandbox.checkDenyWrite(n);if(c)return c}let f=this.sandbox.check(n);if(f&&this.mode!=="bypassPermissions"){let c=this.ruleEngine.evaluate(e,i);return c?{effect:c,reason:`Permission rule: ${c}`}:{effect:"ask",reason:f.reason}}}let a=`${e}:${i}`;if(this.sessionAllowed.has(a))return{effect:"allow",reason:"Session allow: previously approved"};let m=this.ruleEngine.evaluate(e,i);return m?{effect:m,reason:`Permission rule: ${m}`}:{effect:I(this.mode,t),reason:`Mode: ${this.mode}`}}allowForSession(e,t){let r=h(e,t);this.sessionAllowed.add(`${e}:${r}`)}allowAlways(e,t){let r=h(e,t),i=e==="ReadFile"||e==="WriteFile"||e==="EditFile",s;if(i&&r){let n=l(r),a=!1;try{a=A(n).isDirectory()}catch{}s=p(a?n:x(n),"*")}else s=r.trim().split(/\s+/).slice(0,2).join(" ")+"*";this.ruleEngine.appendLocalRule({tool:e,pattern:s,effect:"allow"})}describeToolAction(e,t){let r=h(e,t);if(r)return r;let i=[];for(let[s,n]of Object.entries(t)){let a=String(n);a.length>80&&(a=a.slice(0,80)+"..."),i.push(`${s}: ${a}`)}return i.join(", ")}};export{h as a,E as b,b as c,D as d};
@@ -1,355 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __swiftyCreateRequire } from "node:module";
3
- const require = __swiftyCreateRequire(import.meta.url);
4
- import{a as q,e as H,g as K}from"./chunk-FZPTNGTU.js";import{I as p,L as Y,N as R,O as $,R as N,e as w,j as A,k as W}from"./chunk-4KVSJNS6.js";import{readFileSync as z,writeFileSync as Pe,readdirSync as Ae,mkdirSync as Ne,statSync as Ue,existsSync as G,unlinkSync as Tt,rmSync as St}from"fs";import{join as b}from"path";import{randomBytes as Fe}from"crypto";var U="compact_boundary";var X=p.object({tool_use_id:p.string(),tool_name:p.string(),arguments:p.record(p.string(),p.unknown()).optional()}),J=p.object({tool_use_id:p.string(),content:p.string(),is_error:p.boolean().optional()}),Q=p.object({role:p.string(),content:p.string().default(""),timestamp:p.number(),type:p.string().optional(),tool_uses:p.array(X).optional(),tool_results:p.array(J).optional()}),Le=p.object({role:p.string(),content:p.string(),tool_uses:p.array(X).optional(),tool_results:p.array(J).optional()});function S(s){return(s??[]).map(e=>({tool_use_id:e.toolUseId,tool_name:e.toolName,...e.arguments&&Object.keys(e.arguments).length?{arguments:e.arguments}:{}}))}function x(s){return(s??[]).map(e=>({tool_use_id:e.toolUseId,content:e.content,...e.isError?{is_error:!0}:{}}))}var Oe=p.object({summary:p.string(),keep:p.array(Le)}),T=w({module:"session"});function E(s){return b(s,".swifty","sessions")}function Z(s,e){return b(E(s),e+".jsonl")}function Mt(){let s=Date.now().toString(36),e=Fe(4).toString("hex");return`${s}-${e}`}function F(s,e,t){let o=E(s);Ne(o,{recursive:!0});let n=b(o,`${e}.jsonl`),r=JSON.stringify(t)+`
5
- `;Pe(n,r,{flag:"a",encoding:"utf-8"})}function It(s,e,t){F(s,e,{role:"system",content:JSON.stringify(t),timestamp:Math.floor(Date.now()/1e3),type:U})}function Pt(s,e){let t=b(E(s),`${e}.jsonl`);if(!G(t))return[];let o=[];for(let n of z(t,"utf-8").split(`
6
- `))if(n.trim())try{let r=JSON.parse(n),{success:i,data:a,error:l}=W(Q,r);i?!a.content&&!(a.tool_uses?.length??0)&&!(a.tool_results?.length??0)||o.push(a):T.error({err:l},"session operation failed")}catch(r){T.error({err:r},"session operation failed")}return o}function ee(s){return s?.map(e=>({toolUseId:e.tool_use_id,toolName:e.tool_name,arguments:e.arguments}))}function te(s){return s?.map(e=>({toolUseId:e.tool_use_id,content:e.content,isError:e.is_error}))}function At(s){let e=-1;for(let o=s.length-1;o>=0;o--)if(s[o].type===U){e=o;break}let t=[];if(e>=0){let o=null;try{let n=JSON.parse(s[e].content);o=A(Oe,n)}catch{o=null}if(o){let n=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
7
-
8
- `+o.summary;o.keep.length>0&&(n+=`
9
-
10
- Recent messages have been preserved verbatim.`),t.push({role:"user",content:n});for(let r of o.keep)r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)||t.push({role:r.role,content:r.content,toolUses:ee(r.tool_uses),toolResults:te(r.tool_results)})}for(let n=e+1;n<s.length;n++){let r=s[n];if(r.type===U)continue;let i=V(r);i&&t.push(i)}return t}for(let o of s){let n=V(o);n&&t.push(n)}return t}function V(s){return s.role!=="user"&&s.role!=="assistant"||!s.content&&!s.tool_uses?.length&&!s.tool_results?.length?null:{role:s.role,content:s.content,toolUses:ee(s.tool_uses),toolResults:te(s.tool_results)}}function Nt(s){let e=E(s);if(!G(e))return[];let t=Ae(e).filter(n=>n.endsWith(".jsonl")),o=[];for(let n of t){let r=b(e,n),i=Ue(r),a=n.replace(".jsonl",""),l="",c=0;try{for(let h of z(r,"utf-8").split(`
11
- `)){if(!h.trim())continue;let f;try{let d=JSON.parse(h);f=A(Q,d)}catch(d){T.error({err:d},"session operation failed");continue}c++,!l&&f.role==="user"&&f.content&&(l=f.content.slice(0,100))}}catch(h){T.error({err:h},"session operation failed");continue}o.push({id:a,firstMessage:l,messageCount:c,size:i.size,modTime:i.mtime})}return o.sort((n,r)=>r.modTime.getTime()-n.modTime.getTime()),o}var De=w({module:"agent"}),_=class{pending=[];registry;ctx;constructor(e,t){this.registry=e,this.ctx=t}submit(e,t,o){this.pending.push({toolId:e,toolName:t,arguments:o})}async collectResults(){let e=[...this.pending];this.pending=[];let t=e.map(async o=>{let n=this.registry.get(o.toolName),r=Date.now();if(!n)return{toolId:o.toolId,toolName:o.toolName,result:{output:`Error: unknown tool '${o.toolName}'`,isError:!0},elapsed:0};try{let i=await n.execute(this.ctx,o.arguments);return{toolId:o.toolId,toolName:o.toolName,result:i,elapsed:(Date.now()-r)/1e3}}catch(i){return De.error({err:i},"agent operation failed"),{toolId:o.toolId,toolName:o.toolName,result:{output:`Error executing ${o.toolName}: ${R(i)}`,isError:!0},elapsed:(Date.now()-r)/1e3}}});return Promise.all(t)}hasPending(){return this.pending.length>0}};var C=class{history=[];longTermMemoryInjected=!1;baselineTokens=0;_anchorCount=0;addUserMessage(e){this.history.push({role:"user",content:e})}addAssistantMessage(e){this.history.push({role:"assistant",content:e})}addToolUseMessage(e,t,o,n){this.history.push({role:"assistant",content:e,toolUses:[{toolUseId:t,toolName:o,arguments:n}]})}addAssistantMessageWithTools(e,t){this.history.push({role:"assistant",content:e,toolUses:t})}addAssistantFull(e,t,o){this.history.push({role:"assistant",content:e,thinkingBlocks:t.length>0?t:void 0,toolUses:o.length>0?o:void 0})}addToolResultMessage(e,t,o){this.history.push({role:"user",content:"",toolResults:[{toolUseId:e,content:t,isError:o}]})}addToolResultsMessage(e){this.history.push({role:"user",content:"",toolResults:e})}addSystemReminder(e){this.history.push({role:"user",content:`<system-reminder>
12
- ${e}
13
- </system-reminder>`})}injectLongTermMemory(e,t){if(this.longTermMemoryInjected)return;let o=[];if(e&&o.push(`# SWIFTY.md
14
- Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.
15
-
16
- `+e),t&&o.push(`# Auto Memory
17
- `+t),o.length===0)return;let n=new Date().toISOString().split("T")[0];o.push(`# Current Date
18
- Today's date is `+n+".");let i=`
19
- <system-reminder>
20
- As you answer the user's questions, you can use the following context:
21
-
22
- ${o.join(`
23
-
24
- `)}
25
-
26
- IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.
27
- </system-reminder>`;this.history.unshift({role:"user",content:i}),this.longTermMemoryInjected=!0}len(){return this.history.length}truncateTo(e){e<0&&(e=0),!(e>this.history.length)&&(this.history=this.history.slice(0,e))}getMessages(){return[...this.history]}replaceWithCompacted(e,t){this.history=[{role:"user",content:e},...t],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(e,t,o,n){let r=e+o+n+t;r<=0||(this.baselineTokens=r,this._anchorCount=this.history.length)}clearUsageAnchor(){this.baselineTokens=0,this._anchorCount=0}usageAnchorState(){return this.baselineTokens<=0?null:{baselineTokens:this.baselineTokens,anchorCount:this._anchorCount}}};var oe=3,Be=3,je="[earlier conversation truncated for compaction retry]",We=3.5,Ye=1e4,$e=5,qe=4e4,He=2,Ke=2e4,Ve=13e3,ze=3e3;function se(s,e,t=!1){return s-Math.min(e,Ke)-(t?ze:Ve)}var M=class{consecutiveFailures=0};function L(s){let e=0;for(let t of s){if(e+=t.content.length,t.toolUses&&(e+=JSON.stringify(t.toolUses).length),t.toolResults)for(let o of t.toolResults)e+=o.content.length;if(t.thinkingBlocks)for(let o of t.thinkingBlocks)e+=o.thinking.length}return Math.ceil(e/We)}function Ge(s){return L(s.getMessages())}function O(s){return L([s])}function Xe(s){return s.role==="user"&&!!s.toolResults&&s.toolResults.length>0}function Je(s){let e=0,t=0,o=s.length;for(let n=s.length-1;n>=0;n--){let r=O(s[n]);if(t>0&&e+r>qe||(o=n,e+=r,t++,e>=Ye||t>=$e))break}return o=Qe(s,o),o}function Qe(s,e){if(e<=0||e>=s.length||!Xe(s[e]))return e;let t=new Set((s[e].toolResults??[]).map(o=>o.toolUseId));for(let o=e-1;o>=0;o--){let n=s[o];if(n.role==="assistant"&&n.toolUses?.some(r=>t.has(r.toolUseId)))return o}return e}function Ze(s,e){let t=e??s.usageAnchorState();if(!t)return Ge(s);let o=s.getMessages(),n=Math.min(t.anchorCount,o.length);return t.baselineTokens+L(o.slice(n))}async function ne(s,e,t,o,n,r,i,a,l=""){let c=Ze(s),h=se(t,o),f=se(t,o,!0);if(c<h)return{compacted:!1,message:""};if(!(c>=f)&&n.consecutiveFailures>=oe)return{compacted:!1,message:`Auto-compact circuit breaker: ${String(oe)} consecutive failures`};try{let k=await ie(s,e,r,i,a,l);return n.consecutiveFailures=0,k}catch(k){return n.consecutiveFailures++,{compacted:!1,message:`Auto-compact failed: ${R(k)}`}}}async function re(s,e,t,o,n,r=""){return ie(s,e,t,o,n,r)}var et=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
28
- This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
29
-
30
- Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
31
-
32
- 1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
33
- - The user's explicit requests and intents
34
- - Your approach to addressing the user's requests
35
- - Key decisions, technical concepts and code patterns
36
- - Specific details like:
37
- - file names
38
- - full code snippets
39
- - function signatures
40
- - file edits
41
- - Errors that you ran into and how you fixed them
42
- - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
43
- 2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
44
-
45
- After your analysis, output your final summary wrapped in <summary> tags. Your summary should include the following sections:
46
-
47
- 1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
48
- 2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
49
- 3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
50
- 4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
51
- 5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
52
- 6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
53
- 7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
54
- 8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
55
- 9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
56
- If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
57
-
58
- Here's an example of how your output should be structured:
59
-
60
- <example>
61
- <analysis>
62
- [Your thought process, ensuring all points are covered thoroughly and accurately]
63
- </analysis>
64
-
65
- <summary>
66
- 1. Primary Request and Intent:
67
- [Detailed description]
68
-
69
- 2. Key Technical Concepts:
70
- - [Concept 1]
71
- - [Concept 2]
72
- - [...]
73
-
74
- 3. Files and Code Sections:
75
- - [File Name 1]
76
- - [Summary of why this file is important]
77
- - [Summary of the changes made to this file, if any]
78
- - [Important Code Snippet]
79
- - [File Name 2]
80
- - [Important Code Snippet]
81
- - [...]
82
-
83
- 4. Errors and fixes:
84
- - [Detailed description of error 1]:
85
- - [How you fixed the error]
86
- - [User feedback on the error if any]
87
- - [...]
88
-
89
- 5. Problem Solving:
90
- [Description of solved problems and ongoing troubleshooting]
91
-
92
- 6. All user messages:
93
- - [Detailed non tool use user message]
94
- - [...]
95
-
96
- 7. Pending Tasks:
97
- - [Task 1]
98
- - [Task 2]
99
- - [...]
100
-
101
- 8. Current Work:
102
- [Precise description of current work]
103
-
104
- 9. Optional Next Step:
105
- [Optional Next step to take]
106
-
107
- </summary>
108
- </example>
109
-
110
- Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.`;function tt(s){return et+`
111
-
112
- `+s}function ot(s){let e=[],t=[],o=!1;for(let n of s)n.role==="assistant"&&o&&t.length>0&&(e.push(t),t=[]),t.push(n),o=!!(n.toolResults&&n.toolResults.length>0);return t.length>0&&e.push(t),e}function st(s,e){let t=ot(s);if(t.length<2)return null;let o;if(e>0){let r=0;o=0;for(let i of t)if(r+=i.reduce((a,l)=>a+O(l),0),o++,r>=e)break}else o=Math.max(1,Math.floor(t.length/5));if(o=Math.min(o,t.length-1),o<1)return null;let n=t.slice(o).flat();return n.length>0&&n[0].role!=="user"&&n.unshift({role:"user",content:je}),n}function nt(s){return s.map(e=>{let t=`[${e.role}]: ${e.content}`;return e.toolUses&&(t+=`
113
- [tools: ${e.toolUses.map(o=>o.toolName).join(", ")}]`),t}).join(`
114
-
115
- `)}async function rt(s,e,t){let o=e;for(let n=0;;n++){let r=nt(o),i=new C;i.addUserMessage(tt(r));try{let a="",l=s.stream(i,t);for await(let h of l)h.type==="text_delta"&&(a+=h.text);let c=/<summary>([\s\S]*?)<\/summary>/.exec(a);return c?c[1].trim():a}catch(a){let l=a instanceof Error?a.message.toLowerCase():"";if(!(l.includes("prompt")&&l.includes("long")||l.includes("too many")||l.includes("context_length"))||n>=Be)throw a;let h=o.reduce((d,k)=>d+O(k),0)/5,f=st(o,h);if(!f)throw a;o=f}}}async function ie(s,e,t,o,n,r=""){let i=s.getMessages(),a=Je(i);if(a<=0||a<He)return{compacted:!1,message:`Compaction skipped: only ${String(a)} message(s) to summarize, kept verbatim`};let l=i.slice(0,a),c=i.slice(a),h=await rt(e,l,n),f=t?t.buildRecoveryAttachment(o):"",d=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
116
-
117
- `+h;c.length>0&&(d+=`
118
-
119
- Recent messages have been preserved verbatim.`),r&&(d+=`
120
-
121
- If you need specific details from before compaction (code snippets, error messages, etc.), use ReadFile to read the full session transcript: ${r}`),f&&(d+=`
122
-
123
- ---
124
-
125
- ${f}`),s.replaceWithCompacted(d,c);let k=c.filter(u=>(u.role==="user"||u.role==="assistant")&&(u.content||(u.toolUses?.length??0)||(u.toolResults?.length??0))).map(u=>({role:u.role,content:u.content,...u.toolUses?.length?{tool_uses:S(u.toolUses)}:{},...u.toolResults?.length?{tool_results:x(u.toolResults)}:{}}));return{compacted:!0,message:`Compacted ${String(l.length)} messages into summary (${String(h.length)} chars), kept ${String(c.length)} recent messages verbatim`,boundary:{summary:h,keep:k}}}function D(s){return s?Math.floor(s.length/3.5):0}function ae(s,e){if(e<=0||!s||D(s)<=e)return s;let t=Math.floor(e*3.5);return t<=0||t>=s.length?s:s.slice(0,t)+`
126
- \u2026 (content truncated)`}var I=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((o,n)=>n.timestamp-o.timestamp).slice(0,e)}snapshotSkills(){return[...this.skills.values()].sort((e,t)=>t.timestamp-e.timestamp)}buildRecoveryAttachment(e){let t=[],o=this.snapshotFiles();if(o.length>0){t.push(`## Recently read files
127
- `),t.push(`These snapshots are what the file-reading tool last returned. Re-open with the tool if you need the current bytes.
128
- `);for(let r of o){let i=ae(r.content,5e3),a=new Date(r.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${r.path} (read ${a})
129
-
130
- \`\`\`
131
- ${i}${i.endsWith(`
132
- `)?"":`
133
- `}\`\`\``)}}let n=this.snapshotSkills();if(n.length>0){let r=0,i=[];i.push(`## Active skills
134
- `),i.push(`These skills were invoked earlier in the session. Continue to follow each SOP when its triggering condition applies.
135
- `);let a=!1;for(let l of n){let c=ae(l.body,5e3),h=D(c)+D(l.name)+8;if(r+h>25e3)break;r+=h,i.push(`### ${l.name}
136
-
137
- ${c}`),a=!0}a&&t.push(i.join(`
138
-
139
- `))}return e.length>0&&t.push(`## Available tools
140
-
141
- You still have access to the following tools \u2014 call them directly when the task needs one:
142
-
143
- `+e.map(r=>`- ${r}`).join(`
144
- `)),t.length===0?"":(t.push(`## Note
145
-
146
- 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(`
147
-
148
- `))}};import{readFileSync as it,writeFileSync as at,mkdirSync as lt,existsSync as B}from"fs";import{join as le,resolve as ce}from"path";var de=w({module:"plan-file"}),ue=["brave","calm","dark","eager","fair","gentle","happy","kind","lively","mighty","noble","proud","quiet","swift","warm","wise"],he=["crystal","dragon","eagle","falcon","flame","forest","frost","mountain","ocean","phoenix","river","shadow","thunder","tiger"];function ct(){let s=ue[Math.floor(Math.random()*ue.length)],e=he[Math.floor(Math.random()*he.length)],t=Date.now().toString(36).slice(-4);return`${s}-${e}-${t}`}var y=null;function me(s,e){let t=ce(e,".swifty","plans");return ce(s).startsWith(t+"/")}function pe(s){if(y&&B(y))if(!me(y,s))de.warn({planPath:y,workDir:s},"current plan path is not under work dir");else return y;let e=le(s,".swifty","plans");lt(e,{recursive:!0});let t=ct();return y=le(e,`${t}.md`),at(y,"","utf-8"),y}function Vt(){return!y||!B(y)?null:it(y,"utf-8")}function ge(s){return!y||!B(y)?!1:me(y,s)?!0:(de.warn({planPath:y,workDir:s},"current plan path is not under work dir"),!1)}function zt(){y=null}var fe=`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.
149
-
150
- ## Plan File Info:
151
-
152
- %PLAN_FILE_INFO%
153
- 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.
154
-
155
- ## Plan Workflow
156
-
157
- ### Phase 1: Initial Understanding
158
-
159
- 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".
160
-
161
- 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.
162
-
163
- 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.
164
-
165
- ### Phase 2: Design
166
-
167
- Goal: Design an implementation approach.
168
-
169
- 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.
170
-
171
- ### Phase 3: Review
172
-
173
- Goal: Review the plan(s) from Phase 2 and ensure alignment with the user's intentions.
174
-
175
- 1. Read the critical files identified by agents to deepen your understanding
176
- 2. Ensure that the plans align with the user's original request
177
- 3. Use AskUserQuestion to clarify any remaining questions with the user.
178
-
179
- ### Phase 4: Final Plan
180
-
181
- Goal: Write your final plan to the plan file (the only file you can edit).
182
-
183
- - Begin with a **Context** section
184
- - Include only your recommended approach
185
- - Include the paths of critical files to be modified
186
- - Include a verification section
187
-
188
- ### Phase 5: Call ExitPlanMode
189
-
190
- 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.
191
- `,ut="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.",ht=`## Exited Plan Mode
192
-
193
- You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`,dt="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 ye(s,e,t){let o=`Plan file: ${s}`;return e?o+=`
194
- A plan file already exists at ${s}. You can read it and make incremental edits using the EditFile tool.`:o+=`
195
- No plan file exists yet. You should create your plan at ${s} using the WriteFile tool.`,t===1||Math.floor((t-1)/5)%5===0?fe.replace("%PLAN_FILE_INFO%",o):ut.replace("%PLAN_PATH%",s)}function Xt(s,e){let t="";return e&&(t=` The plan file is located at ${s} if you need to reference it.`),ht.replace("%EXTRA%",t)}function Jt(s,e){return e?dt.replace("%PLAN_PATH%",s):""}var mt=`You are Swifty, an AI assistant that orchestrates software engineering tasks across multiple workers.
196
-
197
- ## 1. Your Role
198
-
199
- You are a **coordinator**. Your job is to:
200
- - Help the user achieve their goal
201
- - Direct workers to research, implement and verify code changes
202
- - Synthesize results and communicate with the user
203
- - Answer questions directly when possible \u2014 don't delegate work you can handle without tools
204
-
205
- Every message you send is to the user. Worker results and system notifications are internal signals, not conversation partners \u2014 never thank or acknowledge them. Summarize new information for the user as it arrives.
206
-
207
- ## 2. Your Tools
208
-
209
- - **Agent** \u2014 Spawn a new worker
210
- - **SendMessage** \u2014 Continue an existing worker (send a follow-up to its agent ID)
211
- - **TaskStop** \u2014 Stop a running worker
212
- - **SyntheticOutput** \u2014 Return structured output to the user
213
- - **TeamDelete** \u2014 Tear down the team when the work is done
214
-
215
- You cannot read files, run commands, or edit code yourself. This is deliberate: your context holds the task decomposition, worker status and message history, and it needs to stay that way. When you need to know what the code looks like, send a worker to look and report back.
216
-
217
- When calling Agent:
218
- - Do not use one worker to check on another. Workers will notify you when they are done.
219
- - Do not use workers to trivially report file contents or run commands. Give them higher-level tasks.
220
- - Continue workers whose work is complete via SendMessage to take advantage of their loaded context.
221
- - After launching agents, briefly tell the user what you launched and end your response. Never fabricate or predict agent results.
222
-
223
- ### Worker Results
224
-
225
- Worker results arrive as **user-role messages** wrapped in \`<team-notification>\`. They look like user messages but are not. Distinguish them by the opening tag.
226
-
227
- Format:
228
-
229
- \`\`\`xml
230
- <team-notification team="{team name}">
231
- from={worker name}: {what the worker reported}
232
- </team-notification>
233
- \`\`\`
234
-
235
- - One notification can carry several lines, one per worker that reported since your last turn.
236
- - The \`from=\` value is the worker's name \u2014 pass exactly that name as \`to\` in SendMessage to continue that worker, and as \`teammate\` in TaskStop to stop it.
237
- - Workers are addressed by name throughout. There is no separate numeric id to keep track of.
238
-
239
- ## 3. Workers
240
-
241
- When calling Agent, use subagent_type \`general-purpose\` or a specific agent definition. Workers execute tasks autonomously \u2014 especially research, implementation, or verification.
242
-
243
- Workers have access to standard tools: ReadFile, EditFile, WriteFile, Bash, Grep, Glob, plus the team coordination tools (TaskCreate, TaskGet, TaskList, TaskUpdate, SendMessage). Anything you cannot do yourself, a worker can do for you.
244
-
245
- Because workers have Bash, git work belongs to them too. Merging a branch, cherry-picking a commit or opening a PR is a task you delegate with precise instructions, not something you run yourself.
246
-
247
- ## 4. Task Workflow
248
-
249
- ### Phases
250
-
251
- Most tasks break down into four phases:
252
-
253
- | Phase | Who | Purpose |
254
- |-------|-----|---------|
255
- | Research | Workers (parallel) | Investigate codebase, find files, understand the problem |
256
- | Synthesis | **You** (coordinator) | Read findings, understand the problem, craft implementation specs |
257
- | Implementation | Workers | Make targeted changes per spec, commit |
258
- | Verification | Workers | Test that changes work |
259
-
260
- ### Concurrency
261
-
262
- **Parallelism is your superpower. Workers are async. Launch independent workers concurrently whenever possible. To launch workers in parallel, make multiple tool calls in a single message.**
263
-
264
- - **Read-only tasks** (research) \u2014 run in parallel freely
265
- - **Write-heavy tasks** (implementation) \u2014 one at a time per set of files
266
- - **Verification** can sometimes run alongside implementation on different file areas
267
-
268
- ### Verification MUST be a separate worker
269
-
270
- **Never let the implementation worker verify its own work.** Spawn a fresh worker after implementation completes. The implementation worker is anchored on its own approach and will rubber-stamp its own code; a fresh verifier sees the code with no assumptions.
271
-
272
- Real verification means running tests with the feature enabled, investigating typecheck errors instead of dismissing them as unrelated, and proving the change works rather than confirming it exists.
273
-
274
- ### Handling Worker Failures
275
-
276
- When a worker reports failure, continue that same worker with SendMessage \u2014 it has the full error context. If a correction attempt fails, try a different approach or report to the user.
277
-
278
- ### Stopping Workers
279
-
280
- Use TaskStop on a worker you sent in the wrong direction, for example when the user changes requirements after you launched it. Stopped workers can be continued later with SendMessage.
281
-
282
- ## 5. Writing Worker Prompts
283
-
284
- **Workers can't see your conversation.** Every prompt must be self-contained.
285
-
286
- ### Always synthesize \u2014 your most important job
287
-
288
- When workers report research findings, you must understand them before directing follow-up work. Read the findings, identify the approach, then write a prompt that proves you understood it by naming specific file paths, line numbers, and exactly what to change.
289
-
290
- Never write "based on your findings" or "based on the research". These phrases hand your understanding off to a worker, which is the one thing you must not delegate.
291
-
292
- \`\`\`
293
- // Anti-pattern \u2014 lazy delegation
294
- Agent(prompt="Based on your findings, fix the auth bug")
295
-
296
- // Good \u2014 synthesized spec
297
- Agent(prompt="Fix the null pointer in src/auth/validate.ts:42. The user field on Session is undefined when the session expires but the token is still cached. Add a null check before accessing user.id \u2014 if null, return 401 with 'Session expired'. Commit and report the hash.")
298
- \`\`\`
299
-
300
- ### Add a purpose statement
301
-
302
- Include a brief purpose so workers can calibrate depth and emphasis:
303
- - "This research will inform a PR description \u2014 focus on user-facing changes."
304
- - "I need this to plan an implementation \u2014 report file paths, line numbers, and type signatures."
305
- - "This is a quick check before we merge \u2014 just verify the happy path."
306
-
307
- ### Choose continue vs. spawn by context overlap
308
-
309
- | Situation | Mechanism | Why |
310
- |-----------|-----------|-----|
311
- | Research explored exactly the files that need editing | **Continue** (SendMessage) | Worker already has the files in context |
312
- | Research was broad but implementation is narrow | **Spawn fresh** (Agent) | Avoid dragging along exploration noise |
313
- | Correcting a failure or extending recent work | **Continue** | Worker has the error context |
314
- | Verifying code a different worker just wrote | **Spawn fresh** | Verifier should see the code with fresh eyes |
315
- | First attempt used the wrong approach entirely | **Spawn fresh** | Wrong-approach context pollutes the retry |
316
-
317
- ### Prompt tips
318
-
319
- - Include file paths, line numbers and error messages \u2014 workers start fresh and need complete context
320
- - State what "done" looks like
321
- - For implementation: "Run relevant tests, then commit and report the hash"
322
- - For research: "Report findings \u2014 do not modify files"
323
- - Be precise about git operations: name the branch, the commit hash, draft vs ready
324
- - For verification: "Prove the code works, don't just confirm it exists"
325
-
326
- ## 6. Example Session
327
-
328
- User: "There's a null pointer in the auth module. Can you fix it?"
329
-
330
- You:
331
- Let me investigate first.
332
-
333
- Agent({ description: "Investigate auth bug", subagent_type: "general-purpose", prompt: "Investigate the auth module in src/auth/. Find where null pointer errors could occur around session handling and token validation. Report specific file paths, line numbers, and types involved. Do not modify files." })
334
- Agent({ description: "Research auth tests", subagent_type: "general-purpose", prompt: "Find all test files related to src/auth/. Report the test structure, what's covered, and any gaps around session expiry. Do not modify files." })
335
-
336
- Investigating from two angles \u2014 I'll report back with findings.
337
-
338
- User:
339
- <team-notification team="auth-fix">
340
- from=investigator: Found null pointer in src/auth/validate.ts:42. The user field on Session is undefined when the session expires but the token is still cached.
341
- </team-notification>
342
-
343
- You:
344
- Found the bug \u2014 null pointer in validate.ts:42.
345
-
346
- 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." })
347
-
348
- Fix is in progress.`,pt="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 ke(s=1){return s<=1||(s-1)%5===0?mt:pt}import{writeFileSync as gt,mkdirSync as ft}from"fs";import{join as be,resolve as we}from"path";var yt=w({module:"tool-result"}),ve=2e5;function Re(s,e){return be(s,".swifty","sessions",e||"default","tool-results")}function Te(s,e,t,o){let n=Re(s,e);ft(n,{recursive:!0});let r=be(n,t+".txt");try{gt(r,o,{encoding:"utf-8",flag:"wx"})}catch(i){if(yt.error({err:i},"tool-result operation failed"),$(i)&&"code"in i&&i.code!=="EEXIST")throw i}return r}var j=2e3;function Se(s,e){let t=Math.floor(s.length/1024),o=s.slice(0,j),n=s.length>j,r=`<persisted-output>
349
- `;return r+=`Output too large (${String(t)}KB). Full content saved to:
350
- ${e}
351
-
352
- `,r+=`Preview (first 2KB):
353
- ${o}`,n&&(r+=`
354
- ...`),r+=`
355
- </persisted-output>`,r}function xe(s,e,t,o){if(s!=="ReadFile"||!e)return!1;let n=e.file_path;return typeof n!="string"||!n?!1:we(n).startsWith(we(Re(t,o)))}function Ee(s,e,t,o){let n=s.reduce((i,a)=>i+a.content.length,0);if(n<=ve)return;let r=[...s].sort((i,a)=>a.content.length-i.content.length);for(let i of r){if(n<=ve)break;if(o?.has(i.toolUseId)||i.content.length<=j)continue;let a;try{a=Te(e,t,i.toolUseId,i.content)}catch{continue}let l=Se(i.content,a);n-=i.content.length-l.length,i.content=l}}function _e(s,e,t,o){let n;try{n=Te(s,e,t,o)}catch{return o}return Se(o,n)}import{readFile as kt}from"fs/promises";var wt=64e3,Ce=3,vt=5e4,Me=class{client;registry;checker;conversation;workDir;sessionId;sessionFilePath;hookEngine;fileHistory;fileStateCache;abortSignal;contextWindow;maxOutput;recoveryState;maxIterations;notificationFn;onLoopComplete;compactTracking=new M;onPermissionRequest;toolFilter;coordinatorActiveFn;activeSkills;instructions;memoryContent;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?Z(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 I,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.memoryRecallPromise=e.memoryRecallPromise}async*run(){let e=this.registry.getAllSchemas();this.toolFilter&&(e=e.filter(a=>this.toolFilter?.(a.name)));let t=this.registry.listTools().map(a=>a.name),o=!1,n=0,r=0,i=0;await this.fireLifecycle("session_start");try{let a=!0;for(;a;){if(i++,this.maxIterations>0&&i>this.maxIterations){yield{type:"error",error:new Error(`Agent reached maximum iterations (${String(this.maxIterations)})`)};return}let l="",c=[],h=[],f="end_turn",d=null;if(this.checker.mode==="plan"){let u=pe(this.workDir);this.checker.planFilePath=u,this.conversation.addSystemReminder(ye(u,ge(this.workDir),i))}if(this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(ke(i)),this.hookEngine)for(let u of this.hookEngine.drainNotifications())this.conversation.addSystemReminder(u);if(this.notificationFn)for(let u of this.notificationFn())this.conversation.addSystemReminder(u);await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let k=await ne(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);try{let u=this.client.stream(this.conversation,e,this.abortSignal);for await(let m of u){if(this.abortSignal?.aborted){a=!1;break}switch(m.type){case"text_delta":l+=m.text,yield{type:"stream_text",text:m.text};break;case"thinking_delta":yield{type:"thinking_text",text:m.text};break;case"thinking_complete":c.push({thinking:m.thinking,signature:m.signature}),yield{type:"thinking_complete",thinking:m.thinking,signature:m.signature};break;case"tool_call_start":break;case"tool_call_complete":h.push({toolUseId:m.toolId,toolName:m.toolName,arguments:m.arguments}),yield{type:"tool_use",toolName:m.toolName,toolId:m.toolId,args:m.arguments};break;case"stream_end":f=m.stopReason,d=m.usage,yield{type:"usage",usage:m.usage};break}}}catch(u){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(u instanceof K)try{let m=await re(this.conversation,this.client,this.recoveryState,t,e,this.sessionFilePath);this.conversation.clearUsageAnchor(),this.conversation.injectLongTermMemory(this.instructions,this.memoryContent),yield{type:"compact",message:"Auto-compacted due to context length: "+m.message,boundary:m.boundary};continue}catch{yield{type:"error",error:u};return}if(u instanceof H){let m=bt(N(Y(u),"retryAfter"));if(yield{type:"retry",reason:"rate limited",delay:m},await this.interruptibleSleep(m)){yield{type:"loop_complete",stopReason:"interrupted"};return}continue}yield{type:"error",error:u};return}if(this.abortSignal?.aborted){l&&(this.conversation.addAssistantFull(l,c,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",l),f==="max_tokens")if(o){if(n<Ce){n++,this.conversation.addAssistantFull(l,c,[]),this.persistLastMessage(),d&&this.conversation.recordUsageAnchor(d.inputTokens,d.outputTokens,d.cacheReadInputTokens,d.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(n)}/${String(Ce)}`,delay:0};continue}}else{this.client.setMaxOutputTokens?.(wt),o=!0,l&&(this.conversation.addAssistantFull(l,c,[]),this.persistLastMessage(),d&&this.conversation.recordUsageAnchor(d.inputTokens,d.outputTokens,d.cacheReadInputTokens,d.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 n=0;if(this.conversation.addAssistantFull(l,c,h),this.persistLastMessage(),d&&this.conversation.recordUsageAnchor(d.inputTokens,d.outputTokens,d.cacheReadInputTokens,d.cacheCreationInputTokens),h.length>0){let u=await this.executeTools(h);for(let g of u)yield g;for(let g of h)this.registry.get(g.toolName)?r=0:r++;if(r>=3){yield{type:"error",error:new Error("Too many consecutive unknown tool calls")};return}let m=new Set;for(let g of h)xe(g.toolName,g.arguments,this.workDir,this.sessionId)&&m.add(g.toolUseId);let P=[];for(let g of u)if(g.type==="tool_result"){let v=g.output;v.length>vt&&!m.has(g.toolId)&&(v=_e(this.workDir,this.sessionId,g.toolId,g.output),m.add(g.toolId)),P.push({toolUseId:g.toolId,content:v,isError:g.isError})}Ee(P,this.workDir,this.sessionId,m);let Ie=h.some(g=>g.toolName==="ExitPlanMode");if(this.conversation.addToolResultsMessage(P),this.persistLastMessage(),this.memoryRecallPromise&&!this.memoryRecallConsumed)try{let g=await Promise.race([this.memoryRecallPromise.then(v=>({done:!0,value:v})),Promise.resolve({done:!1,value:""})]);g.done&&(g.value&&this.conversation.addSystemReminder(g.value),this.memoryRecallConsumed=!0)}catch{this.memoryRecallConsumed=!0}if(Ie){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"end_turn"};return}yield{type:"turn_complete"},await this.fireLifecycle("turn_end")}else{if(a=!1,this.fileHistory){let u=l.length>60?l.slice(0,60)+"...":l;this.fileHistory.makeSnapshot(this.conversation.len(),u)}if(yield{type:"loop_complete",stopReason:f},this.onLoopComplete)try{this.onLoopComplete(this.conversation)}catch{}}}}finally{await this.fireLifecycle("session_end")}}async fireLifecycle(e,t){if(!this.hookEngine)return;let o=await this.hookEngine.fire(e,{event:e,message:t});for(let n of o)n.output&&this.hookEngine.recordNotification(n.output)}interruptibleSleep(e){return new Promise(t=>{if(this.abortSignal?.aborted){t(!0);return}let o=()=>{clearTimeout(n),t(!0)},n=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",o),t(!1)},e);this.abortSignal?.addEventListener("abort",o,{once:!0})})}async executeTools(e){let t=[],o=this.partitionToolCalls(e);for(let n of o){let r=await this.executeBatch(n.blocks,n.concurrent&&n.blocks.length>1);t.push(...r)}return t}partitionToolCalls(e){let t=[];for(let o of e){let r=(this.registry.get(o.toolName)?.category??"command")==="read";r&&t.length>0&&t[t.length-1].concurrent?t[t.length-1].blocks.push(o):t.push({concurrent:r,blocks:[o]})}return t}async executeBatch(e,t){let o=[],n=new _(this.registry,{workDir:this.workDir,fileHistory:this.fileHistory,fileStateCache:this.fileStateCache});for(let r of e){if(this.hookEngine){let c=await this.hookEngine.firePreToolHooks(r.toolName,r.arguments);if(c.rejected){o.push({type:"tool_result",toolName:r.toolName,toolId:r.toolUseId,output:`Rejected by hook: ${c.reason}`,isError:!0,elapsed:0});continue}}let a=this.registry.get(r.toolName)?.category??"command",l=this.checker.check(r.toolName,a,r.arguments);if(l.effect==="deny"){o.push({type:"tool_result",toolName:r.toolName,toolId:r.toolUseId,output:`Permission denied: ${l.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(l.effect==="ask"&&this.onPermissionRequest){let c=await this.onPermissionRequest(r.toolName,r.arguments,l);if(c==="deny"){o.push({type:"tool_result",toolName:r.toolName,toolId:r.toolUseId,output:q,isError:!0,elapsed:0});continue}c==="allowAlways"&&this.checker.allowAlways(r.toolName,r.arguments)}if(n.submit(r.toolUseId,r.toolName,r.arguments),!t){let c=await n.collectResults();for(let h of c)await this.processToolResult(h,e,o)}}if(t){let r=await n.collectResults();for(let i of r)await this.processToolResult(i,e,o)}return o}async processToolResult(e,t,o){if(!e.result.isError&&e.toolName==="ReadFile"){let n=t.find(i=>i.toolUseId===e.toolId),r=N(n?.arguments??{},"file_path");if(r)try{this.recoveryState.recordFileRead(r,await kt(r,"utf-8"))}catch{}}if(o.push({type:"tool_result",toolName:e.toolName,toolId:e.toolId,output:e.result.output,isError:e.result.isError,elapsed:e.elapsed}),this.hookEngine){let n=await this.hookEngine.fire("post_tool_use",{event:"post_tool_use",toolName:e.toolName,message:e.result.output});for(let r of n)r.output&&this.hookEngine.recordNotification(r.output)}}persistLastMessage(){if(!this.workDir||!this.sessionId)return;let e=this.conversation.getMessages();if(e.length===0)return;let t=e[e.length-1];F(this.workDir,this.sessionId,{role:t.role,content:t.content,timestamp:Math.floor(Date.now()/1e3),...t.toolUses?.length?{tool_uses:S(t.toolUses)}:{},...t.toolResults?.length?{tool_results:x(t.toolResults)}:{}})}};function bt(s){if(!s)return 5e3;let e=parseInt(s,10);return Number.isNaN(e)?5e3:e*1e3}export{C as a,Z as b,Mt as c,F as d,It as e,Pt as f,At as g,Nt as h,re as i,I as j,pe as k,Vt as l,ge as m,zt as n,Xt as o,Jt as p,Me as q};
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- import { createRequire as __swiftyCreateRequire } from "node:module";
3
- const require = __swiftyCreateRequire(import.meta.url);
4
- import{b as a,c as b,d as c,e as d,f as e,g as f}from"./chunk-GW6RG76F.js";import"./chunk-X3UA5OZL.js";export{a as ALL_AGENT_DISALLOWED_TOOLS,c as ASYNC_AGENT_ALLOWED_TOOLS,b as CUSTOM_AGENT_DISALLOWED_TOOLS,e as FORK_QUERY_SOURCE,f as cloneRegistryForFork,d as filterToolsForAgent};