@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{j as a}from"./chunk-35WOW2VS.js";import"./chunk-UAHM3AAK.js";import"./chunk-FZPTNGTU.js";import"./chunk-4KVSJNS6.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{a as Agent};
@@ -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{l as C}from"./chunk-UAHM3AAK.js";import{g as w}from"./chunk-H7VXSMJR.js";import{f as D,h as F,i as R}from"./chunk-XOFTPYYD.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};
@@ -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{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};
@@ -0,0 +1,234 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __swiftyCreateRequire } from "node:module";
3
+ const require = __swiftyCreateRequire(import.meta.url);
4
+ import{b as F,c as N,d as M,e as L,g as O,m as U,n as D,o as W}from"./chunk-UAHM3AAK.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,r){this.pending.push({toolId:e,toolName:t,arguments:r})}async collectResults(){let e=[...this.pending];this.pending=[];let t=e.map(async r=>{let s=this.registry.get(r.toolName),n=Date.now();if(!s)return{toolId:r.toolId,toolName:r.toolName,result:{output:`Error: unknown tool '${r.toolName}'`,isError:!0},elapsed:0};try{let i=await s.execute(this.ctx,r.arguments);return{toolId:r.toolId,toolName:r.toolName,result:i,elapsed:(Date.now()-n)/1e3}}catch(i){return me.error({err:i},"agent operation failed"),{toolId:r.toolId,toolName:r.toolName,result:{output:`Error executing ${r.toolName}: ${I(i)}`,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((r,s)=>s.timestamp-r.timestamp).slice(0,e)}snapshotSkills(){return[...this.skills.values()].sort((e,t)=>t.timestamp-e.timestamp)}buildRecoveryAttachment(e){let t=[],r=this.snapshotFiles();if(r.length>0){t.push(`## Recently read files
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 r){let i=B(n.content,5e3),l=new Date(n.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${n.path} (read ${l})
8
+
9
+ \`\`\`
10
+ ${i}${i.endsWith(`
11
+ `)?"":`
12
+ `}\`\`\``)}}let s=this.snapshotSkills();if(s.length>0){let n=0,i=[];i.push(`## Active skills
13
+ `),i.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 s){let d=B(u.body,5e3),g=b(d)+b(u.name)+8;if(n+g>25e3)break;n+=g,i.push(`### ${u.name}
15
+
16
+ ${d}`),l=!0}l&&t.push(i.join(`
17
+
18
+ `))}return e.length>0&&t.push(`## Available tools
19
+
20
+ You still have access to the following tools \u2014 call them directly when the task needs one:
21
+
22
+ `+e.map(n=>`- ${n}`).join(`
23
+ `)),t.length===0?"":(t.push(`## Note
24
+
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
+
27
+ `))}};import{readFileSync as ge,writeFileSync as fe,mkdirSync as ye,existsSync as E}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&&E(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||!E(m)?null:ge(m,"utf-8")}function X(o){return!m||!E(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 r=`Plan file: ${o}`;return e?r+=`
73
+ A plan file already exists at ${o}. You can read it and make incremental edits using the EditFile tool.`:r+=`
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%",r):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.
75
+
76
+ ## 1. Your Role
77
+
78
+ You are a **coordinator**. Your job is to:
79
+ - Help the user achieve their goal
80
+ - Direct workers to research, implement and verify code changes
81
+ - Synthesize results and communicate with the user
82
+ - Answer questions directly when possible \u2014 don't delegate work you can handle without tools
83
+
84
+ 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.
85
+
86
+ ## 2. Your Tools
87
+
88
+ - **Agent** \u2014 Spawn a new worker
89
+ - **SendMessage** \u2014 Continue an existing worker (send a follow-up to its agent ID)
90
+ - **TaskStop** \u2014 Stop a running worker
91
+ - **SyntheticOutput** \u2014 Return structured output to the user
92
+ - **TeamDelete** \u2014 Tear down the team when the work is done
93
+
94
+ 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.
95
+
96
+ When calling Agent:
97
+ - Do not use one worker to check on another. Workers will notify you when they are done.
98
+ - Do not use workers to trivially report file contents or run commands. Give them higher-level tasks.
99
+ - Continue workers whose work is complete via SendMessage to take advantage of their loaded context.
100
+ - After launching agents, briefly tell the user what you launched and end your response. Never fabricate or predict agent results.
101
+
102
+ ### Worker Results
103
+
104
+ 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.
105
+
106
+ Format:
107
+
108
+ \`\`\`xml
109
+ <team-notification team="{team name}">
110
+ from={worker name}: {what the worker reported}
111
+ </team-notification>
112
+ \`\`\`
113
+
114
+ - One notification can carry several lines, one per worker that reported since your last turn.
115
+ - 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.
116
+ - Workers are addressed by name throughout. There is no separate numeric id to keep track of.
117
+
118
+ ## 3. Workers
119
+
120
+ When calling Agent, use subagent_type \`general-purpose\` or a specific agent definition. Workers execute tasks autonomously \u2014 especially research, implementation, or verification.
121
+
122
+ 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.
123
+
124
+ 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.
125
+
126
+ ## 4. Task Workflow
127
+
128
+ ### Phases
129
+
130
+ Most tasks break down into four phases:
131
+
132
+ | Phase | Who | Purpose |
133
+ |-------|-----|---------|
134
+ | Research | Workers (parallel) | Investigate codebase, find files, understand the problem |
135
+ | Synthesis | **You** (coordinator) | Read findings, understand the problem, craft implementation specs |
136
+ | Implementation | Workers | Make targeted changes per spec, commit |
137
+ | Verification | Workers | Test that changes work |
138
+
139
+ ### Concurrency
140
+
141
+ **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.**
142
+
143
+ - **Read-only tasks** (research) \u2014 run in parallel freely
144
+ - **Write-heavy tasks** (implementation) \u2014 one at a time per set of files
145
+ - **Verification** can sometimes run alongside implementation on different file areas
146
+
147
+ ### Verification MUST be a separate worker
148
+
149
+ **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.
150
+
151
+ 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.
152
+
153
+ ### Handling Worker Failures
154
+
155
+ 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.
156
+
157
+ ### Stopping Workers
158
+
159
+ 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.
160
+
161
+ ## 5. Writing Worker Prompts
162
+
163
+ **Workers can't see your conversation.** Every prompt must be self-contained.
164
+
165
+ ### Always synthesize \u2014 your most important job
166
+
167
+ 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.
168
+
169
+ 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.
170
+
171
+ \`\`\`
172
+ // Anti-pattern \u2014 lazy delegation
173
+ Agent(prompt="Based on your findings, fix the auth bug")
174
+
175
+ // Good \u2014 synthesized spec
176
+ 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.")
177
+ \`\`\`
178
+
179
+ ### Add a purpose statement
180
+
181
+ Include a brief purpose so workers can calibrate depth and emphasis:
182
+ - "This research will inform a PR description \u2014 focus on user-facing changes."
183
+ - "I need this to plan an implementation \u2014 report file paths, line numbers, and type signatures."
184
+ - "This is a quick check before we merge \u2014 just verify the happy path."
185
+
186
+ ### Choose continue vs. spawn by context overlap
187
+
188
+ | Situation | Mechanism | Why |
189
+ |-----------|-----------|-----|
190
+ | Research explored exactly the files that need editing | **Continue** (SendMessage) | Worker already has the files in context |
191
+ | Research was broad but implementation is narrow | **Spawn fresh** (Agent) | Avoid dragging along exploration noise |
192
+ | Correcting a failure or extending recent work | **Continue** | Worker has the error context |
193
+ | Verifying code a different worker just wrote | **Spawn fresh** | Verifier should see the code with fresh eyes |
194
+ | First attempt used the wrong approach entirely | **Spawn fresh** | Wrong-approach context pollutes the retry |
195
+
196
+ ### Prompt tips
197
+
198
+ - Include file paths, line numbers and error messages \u2014 workers start fresh and need complete context
199
+ - State what "done" looks like
200
+ - For implementation: "Run relevant tests, then commit and report the hash"
201
+ - For research: "Report findings \u2014 do not modify files"
202
+ - Be precise about git operations: name the branch, the commit hash, draft vs ready
203
+ - For verification: "Prove the code works, don't just confirm it exists"
204
+
205
+ ## 6. Example Session
206
+
207
+ User: "There's a null pointer in the auth module. Can you fix it?"
208
+
209
+ You:
210
+ Let me investigate first.
211
+
212
+ 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." })
213
+ 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." })
214
+
215
+ Investigating from two angles \u2014 I'll report back with findings.
216
+
217
+ User:
218
+ <team-notification team="auth-fix">
219
+ 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.
220
+ </team-notification>
221
+
222
+ You:
223
+ Found the bug \u2014 null pointer in validate.ts:42.
224
+
225
+ 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
+
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 Ee,mkdirSync as Se}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 re(o,e,t,r){let s=ne(o,e);Se(s,{recursive:!0});let n=oe(s,t+".txt");try{Ee(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){if(Te.error({err:i},"tool-result operation failed"),P(i)&&"code"in i&&i.code!=="EEXIST")throw i}return n}var S=2e3;function se(o,e){let t=Math.floor(o.length/1024),r=o.slice(0,S),s=o.length>S,n=`<persisted-output>
228
+ `;return n+=`Output too large (${String(t)}KB). Full content saved to:
229
+ ${e}
230
+
231
+ `,n+=`Preview (first 2KB):
232
+ ${r}`,s&&(n+=`
233
+ ...`),n+=`
234
+ </persisted-output>`,n}function ie(o,e,t,r){if(o!=="ReadFile"||!e)return!1;let s=e.file_path;return typeof s!="string"||!s?!1:ee(s).startsWith(ee(ne(t,r)))}function ae(o,e,t,r){let s=o.reduce((i,l)=>i+l.content.length,0);if(s<=te)return;let n=[...o].sort((i,l)=>l.content.length-i.content.length);for(let i of n){if(s<=te)break;if(r?.has(i.toolUseId)||i.images?.length||i.content.length<=S)continue;let l;try{l=re(e,t,i.toolUseId,i.content)}catch{continue}let u=se(i.content,l);s-=i.content.length-u.length,i.content=u}}function le(o,e,t,r){let s;try{s=re(o,e,t,r)}catch{return r}return se(r,s)}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 U;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?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.memoryRecallPromise=e.memoryRecallPromise}async*run(){let e=this.registry.getAllSchemas();this.toolFilter&&(e=e.filter(i=>this.toolFilter?.(i.name)));let t=this.registry.listTools().map(i=>i.name),r=!1,s=0,n=0;await this.fireLifecycle("session_start");try{let i=!0;for(;i;){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 h=z(this.workDir);this.checker.planFilePath=h,this.conversation.addSystemReminder(Q(h,X(this.workDir),n))}if(this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(Z(n)),this.hookEngine)for(let h of this.hookEngine.drainNotifications())this.conversation.addSystemReminder(h);if(this.notificationFn)for(let h of this.notificationFn())this.conversation.addSystemReminder(h);await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let k=await D(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 h=this.client.stream(this.conversation,e,this.abortSignal);for await(let a of h){if(this.abortSignal?.aborted){i=!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(h){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(h 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),yield{type:"compact",message:"Auto-compacted due to context length: "+a.message,boundary:a.boundary};continue}catch{yield{type:"error",error:h};return}if(h instanceof A){let a=Ae(x(T(h),"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:h instanceof Error?h:new Error(JSON.stringify(h))};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(r){if(s<ce){s++,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(s)}/${String(ce)}`,delay:0};continue}}else{this.client.setMaxOutputTokens?.(Pe),r=!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 s=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 h=await this.executeTools(d);for(let c of h)yield c;let a=new Set;for(let c of d)ie(c.toolName,c.arguments,this.workDir,this.sessionId)&&a.add(c.toolUseId);let R=[];for(let c of h)if(c.type==="tool_result"){c.images?.length&&a.add(c.toolId);let y=c.output;y.length>_e&&!a.has(c.toolId)&&(y=le(this.workDir,this.sessionId,c.toolId,c.output),a.add(c.toolId)),R.push({toolUseId:c.toolId,content:y,isError:c.isError,...c.images?.length?{images:c.images}:{}})}ae(R,this.workDir,this.sessionId,a);let ue=d.some(c=>c.toolName==="ExitPlanMode");if(this.conversation.addToolResultsMessage(R),this.persistLastMessage(),this.memoryRecallPromise&&!this.memoryRecallConsumed)try{let c=await Promise.race([this.memoryRecallPromise.then(y=>({done:!0,value:y})),Promise.resolve({done:!1,value:""})]);c.done&&(c.value&&this.conversation.addSystemReminder(c.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(i=!1,this.fileHistory){let h=l.length>60?l.slice(0,60)+"...":l;this.fileHistory.makeSnapshot(this.conversation.len(),h)}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 r=await this.hookEngine.fire(e,{event:e,message:t});for(let s of r)s.output&&this.hookEngine.recordNotification(s.output)}interruptibleSleep(e){return new Promise(t=>{if(this.abortSignal?.aborted){t(!0);return}let r=()=>{clearTimeout(s),t(!0)},s=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",r),t(!1)},e);this.abortSignal?.addEventListener("abort",r,{once:!0})})}async executeTools(e){let t=[],r=this.partitionToolCalls(e);for(let s of r){let n=await this.executeBatch(s.blocks,s.concurrent&&s.blocks.length>1);t.push(...n)}return t}partitionToolCalls(e){let t=[];for(let r of e){let n=(this.registry.get(r.toolName)?.category??"command")==="read";n&&t.length>0&&t[t.length-1].concurrent?t[t.length-1].blocks.push(r):t.push({concurrent:n,blocks:[r]})}return t}async executeBatch(e,t){let r=[],s=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){r.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"){r.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"){r.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(s.submit(n.toolUseId,n.toolName,n.arguments),!t){let d=await s.collectResults();for(let g of d)await this.processToolResult(g,e,r)}}if(t){let n=await s.collectResults();for(let i of n)await this.processToolResult(i,e,r)}return r}async processToolResult(e,t,r){if(!e.result.isError&&e.toolName==="ReadFile"){let s=t.find(i=>i.toolUseId===e.toolId),n=x(s?.arguments??{},"file_path");if(n&&!Y(n))try{this.recoveryState.recordFileRead(n,await Ie(n,"utf-8"))}catch{}}if(r.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 s=await this.hookEngine.fire("post_tool_use",{event:"post_tool_use",toolName:e.toolName,message:e.result.output});for(let n of s)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];O(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};