@swifty.js/swifty 0.0.3 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-5YZWK2BD.js → agent-MPIDW5VX.js} +1 -1
- package/dist/{anthropic-PWUGDLNY.js → anthropic-25O6Y2EC.js} +1 -1
- package/dist/{chunk-IE47RFDE.js → chunk-647XF5VP.js} +81 -72
- package/dist/{chunk-UAHM3AAK.js → chunk-DCI5RJC7.js} +12 -11
- package/dist/{chunk-XOFTPYYD.js → chunk-HU7ELU2V.js} +1 -1
- package/dist/{chunk-35WOW2VS.js → chunk-IZ23BHLA.js} +16 -15
- package/dist/chunk-XBHVVB5A.js +10 -0
- package/dist/{devtools-CUVBHY35.js → devtools-3OAJUZGE.js} +1 -1
- package/dist/glob_addon.node +0 -0
- package/dist/main.js +246 -245
- package/dist/openai-2MX6GD45.js +34 -0
- package/dist/server-JD4YMWIW.js +244 -0
- package/package.json +15 -15
- package/dist/chunk-2PFMEUGN.js +0 -10
- package/dist/openai-S5NEHZTE.js +0 -26
- package/dist/server-BHJVCZVP.js +0 -245
|
@@ -3,29 +3,30 @@ import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
4
|
import{I as i,N as U,e as y,j as M,k as A}from"./chunk-4KVSJNS6.js";var T=class{history=[];longTermMemoryInjected=!1;baselineTokens=0;_anchorCount=0;addUserMessage(e,s){this.history.push({role:"user",content:e,...s?.length?{images:s}:{}})}addAssistantMessage(e){this.history.push({role:"assistant",content:e})}addToolUseMessage(e,s,o,n){this.history.push({role:"assistant",content:e,toolUses:[{toolUseId:s,toolName:o,arguments:n}]})}addAssistantMessageWithTools(e,s){this.history.push({role:"assistant",content:e,toolUses:s})}addAssistantFull(e,s,o){this.history.push({role:"assistant",content:e,thinkingBlocks:s.length>0?s:void 0,toolUses:o.length>0?o:void 0})}addToolResultMessage(e,s,o){this.history.push({role:"user",content:"",toolResults:[{toolUseId:e,content:s,isError:o}]})}addToolResultsMessage(e){this.history.push({role:"user",content:"",toolResults:e})}addSystemReminder(e){this.history.push({role:"user",content:`<system-reminder>
|
|
5
5
|
${e}
|
|
6
|
-
</system-reminder>`})}injectLongTermMemory(e,s){if(this.longTermMemoryInjected)return;let
|
|
6
|
+
</system-reminder>`})}injectLongTermMemory(e,s,o=""){if(this.longTermMemoryInjected)return;let n=[];if(e&&n.push(`# SWIFTY.md
|
|
7
7
|
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.
|
|
8
8
|
|
|
9
|
-
`+e),s&&
|
|
10
|
-
`+s),o
|
|
11
|
-
|
|
9
|
+
`+e),s&&n.push(`# Auto Memory
|
|
10
|
+
`+s),o&&n.push(`# availableSkills
|
|
11
|
+
`+o),n.length===0)return;let r=new Date().toISOString().split("T")[0];n.push(`# Current Date
|
|
12
|
+
Today's date is `+r+".");let a=`
|
|
12
13
|
<system-reminder>
|
|
13
14
|
As you answer the user's questions, you can use the following context:
|
|
14
15
|
|
|
15
|
-
${
|
|
16
|
+
${n.join(`
|
|
16
17
|
|
|
17
18
|
`)}
|
|
18
19
|
|
|
19
20
|
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.
|
|
20
|
-
</system-reminder>`;this.history.unshift({role:"user",content:a}),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,s){this.history=[{role:"user",content:e},...s],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(e,s,o,n){let r=e+o+n+s;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}}};import{createHash as Z}from"crypto";import{existsSync as ee,mkdirSync as te,readFileSync as se,writeFileSync as oe}from"fs";import{join as E}from"path";function P(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var j=y({module:"images"}),ne={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"};function re(t,e){return E(t,".swifty","sessions",e||"default","images")}function b(t,e,s){let o=re(t,e),n=[];for(let r of s)try{let
|
|
21
|
+
</system-reminder>`;this.history.unshift({role:"user",content:a}),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,s){this.history=[{role:"user",content:e},...s],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(e,s,o,n){let r=e+o+n+s;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}}};import{createHash as Z}from"crypto";import{existsSync as ee,mkdirSync as te,readFileSync as se,writeFileSync as oe}from"fs";import{join as E}from"path";function P(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var j=y({module:"images"}),ne={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"};function re(t,e){return E(t,".swifty","sessions",e||"default","images")}function b(t,e,s){let o=re(t,e),n=[];for(let r of s)try{let l=Buffer.from(r.data,"base64"),a=Z("sha256").update(l).digest("hex").slice(0,16),c=ne[r.mediaType]??"png",u=E(o,`${a}.${c}`);ee(u)||(te(o,{recursive:!0}),oe(u,l)),n.push({path:u,media_type:r.mediaType,...r.sourcePath?{source_path:r.sourcePath}:{}})}catch(l){j.error({err:l},"failed to persist session image")}return n}function N(t){try{let e=se(t.path);return{mediaType:P(t.media_type),data:e.toString("base64"),sourcePath:t.source_path,byteLength:e.length}}catch(e){return j.warn({err:e,path:t.path},"failed to restore session image"),null}}import{readFileSync as L,writeFileSync as ie,readdirSync as ae,mkdirSync as le,statSync as ce,existsSync as O,unlinkSync as ze,rmSync as Ke}from"fs";import{basename as k,dirname as I,join as f}from"path";import{randomBytes as ue}from"crypto";var x="compact_boundary";var D=i.object({tool_use_id:i.string(),tool_name:i.string(),arguments:i.record(i.string(),i.unknown()).optional()}),w=i.object({path:i.string(),media_type:i.string(),source_path:i.string().optional()}),F=i.object({tool_use_id:i.string(),content:i.string(),is_error:i.boolean().optional(),images:i.array(w).optional()}),$=i.object({role:i.string(),content:i.string().default(""),timestamp:i.number(),type:i.string().optional(),tool_uses:i.array(D).optional(),tool_results:i.array(F).optional(),images:i.array(w).optional()}),me=i.object({role:i.string(),content:i.string(),tool_uses:i.array(D).optional(),tool_results:i.array(F).optional(),images:i.array(w).optional()});function Y(t){return(t??[]).map(e=>({tool_use_id:e.toolUseId,tool_name:e.toolName,...e.arguments&&Object.keys(e.arguments).length?{arguments:e.arguments}:{}}))}function q(t,e){return(t??[]).map(s=>({tool_use_id:s.toolUseId,content:s.content,...s.isError?{is_error:!0}:{},...e&&s.images?.length?{images:b(e.workDir,e.sessionId,s.images)}:{}}))}function _(t){if(!t?.length)return{images:[],note:""};let e=[];for(let o of t){let n=N(o);n&&e.push(n)}let s=t.length-e.length;return{images:e,note:s>0?`
|
|
21
22
|
[note: ${String(s)} image(s) from this message could not be restored]`:""}}var ge=i.object({summary:i.string(),keep:i.array(me)}),R=y({module:"session"});function S(t){return f(t,".swifty","sessions")}function Ve(t,e){return f(S(t),e+".jsonl")}function z(t){let e=k(t);if(!e.endsWith(".jsonl"))return null;let s=I(t),o=I(s);return k(s)!=="sessions"||k(o)!==".swifty"?null:{workDir:I(o),sessionId:e.slice(0,-6)}}function Qe(){let t=Date.now().toString(36),e=ue(4).toString("hex");return`${t}-${e}`}function de(t,e,s){let o=S(t);le(o,{recursive:!0});let n=f(o,`${e}.jsonl`),r=JSON.stringify(s)+`
|
|
22
23
|
`;ie(n,r,{flag:"a",encoding:"utf-8"})}function Ze(t,e,s){de(t,e,{role:"system",content:JSON.stringify(s),timestamp:Math.floor(Date.now()/1e3),type:x})}function et(t,e){let s=f(S(t),`${e}.jsonl`);if(!O(s))return[];let o=[];for(let n of L(s,"utf-8").split(`
|
|
23
|
-
`))if(n.trim())try{let r=JSON.parse(n),{success:
|
|
24
|
+
`))if(n.trim())try{let r=JSON.parse(n),{success:l,data:a,error:c}=A($,r);l?!a.content&&!(a.tool_uses?.length??0)&&!(a.tool_results?.length??0)&&!(a.images?.length??0)||o.push(a):R.error({err:c},"session operation failed")}catch(r){R.error({err:r},"session operation failed")}return o}function K(t){return t?.map(e=>({toolUseId:e.tool_use_id,toolName:e.tool_name,arguments:e.arguments}))}function H(t){return t?.map(e=>{let s=_(e.images);return{toolUseId:e.tool_use_id,content:e.content+s.note,isError:e.is_error,...s.images.length?{images:s.images}:{}}})}function tt(t){let e=-1;for(let o=t.length-1;o>=0;o--)if(t[o].type===x){e=o;break}let s=[];if(e>=0){let o=null;try{let n=JSON.parse(t[e].content);o=M(ge,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:
|
|
24
25
|
|
|
25
26
|
`+o.summary;o.keep.length>0&&(n+=`
|
|
26
27
|
|
|
27
|
-
Recent messages have been preserved verbatim.`),s.push({role:"user",content:n});for(let r of o.keep){if(r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)&&!(r.images?.length??0))continue;let
|
|
28
|
-
`)){if(!g.trim())continue;let d;try{let h=JSON.parse(g);d=M($,h)}catch(h){R.error({err:h},"session operation failed");continue}u++,!c&&d.role==="user"&&d.content&&(c=d.content.slice(0,100))}}catch(g){R.error({err:g},"session operation failed");continue}o.push({id:
|
|
28
|
+
Recent messages have been preserved verbatim.`),s.push({role:"user",content:n});for(let r of o.keep){if(r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)&&!(r.images?.length??0))continue;let l=_(r.images);s.push({role:r.role,content:r.content+l.note,toolUses:K(r.tool_uses),toolResults:H(r.tool_results),...l.images.length?{images:l.images}:{}})}}for(let n=e+1;n<t.length;n++){let r=t[n];if(r.type===x)continue;let l=B(r);l&&s.push(l)}return s}for(let o of t){let n=B(o);n&&s.push(n)}return s}function B(t){if(t.role!=="user"&&t.role!=="assistant"||!t.content&&!(t.tool_uses?.length??0)&&!(t.tool_results?.length??0)&&!(t.images?.length??0))return null;let e=_(t.images);return{role:t.role,content:t.content+e.note,toolUses:K(t.tool_uses),toolResults:H(t.tool_results),...e.images.length?{images:e.images}:{}}}function st(t){let e=S(t);if(!O(e))return[];let s=ae(e).filter(n=>n.endsWith(".jsonl")),o=[];for(let n of s){let r=f(e,n),l=ce(r),a=n.replace(".jsonl",""),c="",u=0;try{for(let g of L(r,"utf-8").split(`
|
|
29
|
+
`)){if(!g.trim())continue;let d;try{let h=JSON.parse(g);d=M($,h)}catch(h){R.error({err:h},"session operation failed");continue}u++,!c&&d.role==="user"&&d.content&&(c=d.content.slice(0,100))}}catch(g){R.error({err:g},"session operation failed");continue}o.push({id:a,firstMessage:c,messageCount:u,size:l.size,modTime:l.mtime})}return o.sort((n,r)=>r.modTime.getTime()-n.modTime.getTime()),o}var W=3,he=3,pe="[earlier conversation truncated for compaction retry]",fe=3.5,ye=1e4,Te=5,be=4e4,Re=2,Se=2e4,Me=13e3,ke=3e3;function J(t,e,s=!1){return t-Math.min(e,Se)-(s?ke:Me)}var X=class{consecutiveFailures=0},G=7e3;function C(t){let e=0;for(let s of t){if(e+=s.content.length,s.images&&(e+=s.images.length*G),s.toolUses&&(e+=JSON.stringify(s.toolUses).length),s.toolResults)for(let o of s.toolResults)e+=o.content.length,e+=(o.images?.length??0)*G;if(s.thinkingBlocks)for(let o of s.thinkingBlocks)e+=o.thinking.length}return Math.ceil(e/fe)}function Ie(t){return C(t.getMessages())}function v(t){return C([t])}function xe(t){return t.role==="user"&&!!t.toolResults&&t.toolResults.length>0}function we(t){let e=0,s=0,o=t.length;for(let n=t.length-1;n>=0;n--){let r=v(t[n]);if(s>0&&e+r>be||(o=n,e+=r,s++,e>=ye||s>=Te))break}return o=_e(t,o),o}function _e(t,e){if(e<=0||e>=t.length||!xe(t[e]))return e;let s=new Set((t[e].toolResults??[]).map(o=>o.toolUseId));for(let o=e-1;o>=0;o--){let n=t[o];if(n.role==="assistant"&&n.toolUses?.some(r=>s.has(r.toolUseId)))return o}return e}function Ce(t,e){let s=e??t.usageAnchorState();if(!s)return Ie(t);let o=t.getMessages(),n=Math.min(s.anchorCount,o.length);return s.baselineTokens+C(o.slice(n))}async function lt(t,e,s,o,n,r,l,a,c=""){let u=Ce(t),g=J(s,o),d=J(s,o,!0);if(u<g)return{compacted:!1,message:""};if(!(u>=d)&&n.consecutiveFailures>=W)return{compacted:!1,message:`Auto-compact circuit breaker: ${String(W)} consecutive failures`};try{let p=await V(t,e,r,l,a,c);return n.consecutiveFailures=0,p}catch(p){return n.consecutiveFailures++,{compacted:!1,message:`Auto-compact failed: ${U(p)}`}}}async function ct(t,e,s,o,n,r=""){return V(t,e,s,o,n,r)}var ve=`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.
|
|
29
30
|
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.
|
|
30
31
|
|
|
31
32
|
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:
|
|
@@ -110,11 +111,11 @@ Here's an example of how your output should be structured:
|
|
|
110
111
|
|
|
111
112
|
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.`;function Ae(t){return ve+`
|
|
112
113
|
|
|
113
|
-
`+t}function Ue(t){let e=[],s=[],o=!1;for(let n of t)n.role==="assistant"&&o&&s.length>0&&(e.push(s),s=[]),s.push(n),o=!!(n.toolResults&&n.toolResults.length>0);return s.length>0&&e.push(s),e}function Pe(t,e){let s=Ue(t);if(s.length<2)return null;let o;if(e>0){let r=0;o=0;for(let
|
|
114
|
+
`+t}function Ue(t){let e=[],s=[],o=!1;for(let n of t)n.role==="assistant"&&o&&s.length>0&&(e.push(s),s=[]),s.push(n),o=!!(n.toolResults&&n.toolResults.length>0);return s.length>0&&e.push(s),e}function Pe(t,e){let s=Ue(t);if(s.length<2)return null;let o;if(e>0){let r=0;o=0;for(let l of s)if(r+=l.reduce((a,c)=>a+v(c),0),o++,r>=e)break}else o=Math.max(1,Math.floor(s.length/5));if(o=Math.min(o,s.length-1),o<1)return null;let n=s.slice(o).flat();return n.length>0&&n[0].role!=="user"&&n.unshift({role:"user",content:pe}),n}function Ee(t){return t.map(e=>{let s=`[${e.role}]: ${e.content}`;return e.images?.length&&(s+=`
|
|
114
115
|
[attached images: ${e.images.map(o=>o.sourcePath??"image").join(", ")}]`),e.toolUses&&(s+=`
|
|
115
116
|
[tools: ${e.toolUses.map(o=>o.toolName).join(", ")}]`),s}).join(`
|
|
116
117
|
|
|
117
|
-
`)}async function je(t,e,s){let o=e;for(let n=0;;n++){let r=Ee(o),
|
|
118
|
+
`)}async function je(t,e,s){let o=e;for(let n=0;;n++){let r=Ee(o),l=new T;l.addUserMessage(Ae(r));try{let a="",c=t.stream(l,s);for await(let g of c)g.type==="text_delta"&&(a+=g.text);let u=/<summary>([\s\S]*?)<\/summary>/.exec(a);return u?u[1].trim():a}catch(a){let c=a instanceof Error?a.message.toLowerCase():"";if(!(c.includes("prompt")&&c.includes("long")||c.includes("too many")||c.includes("context_length"))||n>=he)throw a;let g=o.reduce((h,p)=>h+v(p),0)/5,d=Pe(o,g);if(!d)throw a;o=d}}}async function V(t,e,s,o,n,r=""){let l=t.getMessages(),a=we(l);if(a<=0||a<Re)return{compacted:!1,message:`Compaction skipped: only ${String(a)} message(s) to summarize, kept verbatim`};let c=l.slice(0,a),u=l.slice(a),g=await je(e,c,n),d=s?s.buildRecoveryAttachment(o):"",h=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
|
|
118
119
|
|
|
119
120
|
`+g;u.length>0&&(h+=`
|
|
120
121
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{a as S}from"./chunk-7MHXMDYC.js";import{H as o,e as x,g as u,h as m}from"./chunk-4KVSJNS6.js";import{existsSync as E,readFileSync as
|
|
4
|
+
import{a as S}from"./chunk-7MHXMDYC.js";import{H as o,e as x,g as u,h as m}from"./chunk-4KVSJNS6.js";import{existsSync as E,readFileSync as $}from"fs";import{homedir as I}from"os";import{join as d}from"path";function p(e){return!!e._zod}function c(e,n){return p(e)?u(e,n):e.safeParse(n)}async function ee(e,n){return p(e)?await m(e,n):await e.safeParseAsync(n)}function oe(e){if(!e)return;let n;if(p(e)?n=e._zod?.def?.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function ne(e){if(p(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let r=e.value;if(r!==void 0)return r}var g=x({module:"config"}),A={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY","openai-compat":"OPENAI_API_KEY"};function N(e){return _.has(e)}var _=new Set(Object.keys(A)),l=class extends Error{constructor(n){super(n),this.name="ConfigError"}},P=o.object({name:o.string(),protocol:o.enum(["anthropic","openai","openai-compat"]),base_url:o.string(),model:o.string(),api_key:o.string().optional(),thinking:o.boolean().optional(),context_window:o.coerce.number().optional(),max_output_tokens:o.coerce.number().optional()}),V=[["1m",1e6],["gpt-4.1",1e6],["gpt-4o",128e3],["gpt-4-turbo",128e3],["o1",2e5],["o3",2e5],["o4",2e5],["gpt-3.5",16385],["claude",2e5]];function j(e){let n=e.toLowerCase();for(let[t,r]of V)if(n.includes(t))return r;return n.includes("claude")?2e5:128e3}function le(e){return e.context_window&&e.context_window>0?e.context_window:j(e.model)}var w=new Map;async function pe(e,n){if(e.context_window&&e.context_window>0)return e.context_window;if(e.protocol==="anthropic"){let t=`${e.name}-${e.model}`,r=w.get(t);if(r===void 0){try{r=await(n??(await import("./anthropic-25O6Y2EC.js")).fetchModelContextWindow)(e)}catch(i){g.error({err:i},"config operation failed"),r=0}w.set(t,r)}if(r&&r>0)return r}return j(e.model)}function ue(e){return e.max_output_tokens&&e.max_output_tokens>0?e.max_output_tokens:e.thinking?64e3:8192}function me(e){if(e.api_key)return e.api_key;let n=N(e.protocol)?A[e.protocol]:"";return n?process.env[n]??"":""}var z=o.object({name:o.string(),command:o.string().optional(),args:o.array(o.string()).optional(),url:o.string().optional(),transport:o.string().optional(),headers:o.record(o.string(),o.string()).optional(),env:o.record(o.string(),o.string()).optional()}),O=o.object({id:o.string().optional(),event:o.string(),condition:o.string().optional(),action:o.object({type:o.string(),command:o.string().optional(),url:o.string().optional(),method:o.string().optional(),prompt:o.string().optional()}),reject:o.boolean().optional(),once:o.boolean().optional(),async:o.boolean().optional(),on_error:o.string().optional()}),M=o.object({enabled:o.boolean().optional(),auto_allow:o.boolean().optional(),network_enabled:o.boolean().optional()}),T=o.object({providers:o.array(P),permission_mode:o.string().optional(),mcp_servers:o.array(z).default([]),hooks:o.array(O).default([]),sandbox:M.optional(),enable_coordinator_mode:o.boolean().optional(),enable_fork:o.boolean().optional()});function ge(e){return e.enable_fork!==!1}function Y(e){return typeof e=="object"&&e!==null}function C(e){let n=$(e,"utf-8"),t=S.load(n);if(!Y(t))return g.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=c(T,t);if(r.success){let a=r.data;return{providers:a.providers,permission_mode:a.permission_mode,mcp_servers:a.mcp_servers,hooks:a.hooks}}g.error({error:r.error},"config error");let i=[],s,f=[],y=[],v,b=!1,h=!0;if("providers"in t){let a=c(o.array(P),t.providers);a.success&&(i=a.data)}if("permission_mode"in t&&typeof t.permission_mode=="string"&&(s=t.permission_mode),"mcp_servers"in t){let a=c(o.array(z),t.mcp_servers);a.success&&(f=a.data)}if("hooks"in t){let a=c(o.array(O),t.hooks);a.success&&(y=a.data)}if("sandbox"in t){let a=c(M,t.sandbox);a.success&&(v=a.data)}return"enable_coordinator_mode"in t&&(b=!!t.enable_coordinator_mode),"enable_fork"in t&&(h=!!t.enable_fork),{providers:i,permission_mode:s,mcp_servers:f,hooks:y,sandbox:v,enable_coordinator_mode:b,enable_fork:h}}function K(e,n){if(n.providers.length>0&&(e.providers=n.providers),n.permission_mode&&(e.permission_mode=n.permission_mode),n.mcp_servers.length>0){let t=new Map;for(let r=0;r<e.mcp_servers.length;r++){let i=e.mcp_servers[r];t.set(i.name,r)}for(let r of n.mcp_servers){let i=t.get(r.name);i!==void 0?e.mcp_servers[i]=r:(e.mcp_servers.push(r),t.set(r.name,e.mcp_servers.length-1))}}return e.hooks=[...e.hooks,...n.hooks],n.sandbox&&(e.sandbox={...e.sandbox,...n.sandbox}),n.enable_coordinator_mode&&(e.enable_coordinator_mode=!0),n.enable_fork!==void 0&&(e.enable_fork=n.enable_fork),e}function k(e){if(e.providers.length===0)throw new l("At least one provider MUST be configured.");let n=["name","protocol","base_url","model"];for(let t=0;t<e.providers.length;t++){let r=e.providers[t],i={name:r.name,protocol:r.protocol,base_url:r.base_url,model:r.model},s=n.filter(f=>!(f in i));if(s.length>0)throw new l(`Provider #${String(t+1)}: missing fields: ${s.join(", ")}`);if(!_.has(r.protocol))throw new l(`Provider #${String(t+1)}: invalid protocol '${r.protocol}', MUST be one of: ${Array.from(_).join(", ")}`)}}function _e(e){if(e){let s=C(e);return k(s),s}let n=process.cwd(),t=I(),r=[d(t,".swifty","config.yml"),d(t,".swifty","config.yaml"),d(n,".swifty","config.yml"),d(n,".swifty","config.yaml"),d(n,".swifty","config.local.yml"),d(n,".swifty","config.local.yaml")],i=null;for(let s of r){if(!E(s))continue;let f=C(s);i?i=K(i,f):i=f}if(!i)throw new l("No config file found, expected .swifty/config.y(a)ml under project or $HOME/.swifty/config.y(a)ml.");return k(i),i}export{c as a,ee as b,oe as c,ne as d,le as e,pe as f,ue as g,me as h,ge as i,_e as j};
|
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{b as F,c as N,d as M,e as L,g as
|
|
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((
|
|
4
|
+
import{b as F,c as N,d as M,e as L,g as D,m as O,n as U,o as W}from"./chunk-DCI5RJC7.js";import{a as _,e as A,g as C}from"./chunk-FZPTNGTU.js";import{L as T,N as I,O as P,R as x,e as f}from"./chunk-4KVSJNS6.js";import{extname as de}from"path";var j={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},Fe=new Set(Object.keys(j));function pe(o){return j[de(o).toLowerCase()]??null}function Y(o){return pe(o)!==null}function Ne(o){return o.length>=8&&o[0]===137&&o[1]===80&&o[2]===78&&o[3]===71?"image/png":o.length>=3&&o[0]===255&&o[1]===216&&o[2]===255?"image/jpeg":o.length>=6&&o[0]===71&&o[1]===73&&o[2]===70?"image/gif":o.length>=12&&o[0]===82&&o[1]===73&&o[2]===70&&o[3]===70&&o[8]===87&&o[9]===69&&o[10]===66&&o[11]===80?"image/webp":null}var me=f({module:"agent"}),w=class{pending=[];registry;ctx;constructor(e,t){this.registry=e,this.ctx=t}submit(e,t,s){this.pending.push({toolId:e,toolName:t,arguments:s})}async collectResults(){let e=[...this.pending];this.pending=[];let t=e.map(async s=>{let i=this.registry.get(s.toolName),n=Date.now();if(!i)return{toolId:s.toolId,toolName:s.toolName,result:{output:`Error: unknown tool '${s.toolName}'`,isError:!0},elapsed:0};try{let r=await i.execute(this.ctx,s.arguments);return{toolId:s.toolId,toolName:s.toolName,result:r,elapsed:(Date.now()-n)/1e3}}catch(r){return me.error({err:r},"agent operation failed"),{toolId:s.toolId,toolName:s.toolName,result:{output:`Error executing ${s.toolName}: ${I(r)}`,isError:!0},elapsed:(Date.now()-n)/1e3}}});return Promise.all(t)}hasPending(){return this.pending.length>0}};function b(o){return o?Math.floor(o.length/3.5):0}function B(o,e){if(e<=0||!o||b(o)<=e)return o;let t=Math.floor(e*3.5);return t<=0||t>=o.length?o:o.slice(0,t)+`
|
|
5
|
+
\u2026 (content truncated)`}var v=class{files=new Map;skills=new Map;recordFileRead(e,t){this.files.set(e,{path:e,content:t,timestamp:Date.now()})}recordSkillInvocation(e,t){this.skills.set(e,{name:e,body:t,timestamp:Date.now()})}snapshotFiles(e=5){return[...this.files.values()].sort((s,i)=>i.timestamp-s.timestamp).slice(0,e)}snapshotSkills(){return[...this.skills.values()].sort((e,t)=>t.timestamp-e.timestamp)}buildRecoveryAttachment(e){let t=[],s=this.snapshotFiles();if(s.length>0){t.push(`## Recently read files
|
|
6
6
|
`),t.push(`These snapshots are what the file-reading tool last returned. Re-open with the tool if you need the current bytes.
|
|
7
|
-
`);for(let n of
|
|
7
|
+
`);for(let n of s){let r=B(n.content,5e3),l=new Date(n.timestamp).toISOString().replace(/\.\d{3}Z$/,"Z");t.push(`### ${n.path} (read ${l})
|
|
8
8
|
|
|
9
9
|
\`\`\`
|
|
10
|
-
${
|
|
10
|
+
${r}${r.endsWith(`
|
|
11
11
|
`)?"":`
|
|
12
|
-
`}\`\`\``)}}let
|
|
13
|
-
`),
|
|
14
|
-
`);let l=!1;for(let u of
|
|
12
|
+
`}\`\`\``)}}let i=this.snapshotSkills();if(i.length>0){let n=0,r=[];r.push(`## Active skills
|
|
13
|
+
`),r.push(`These skills were invoked earlier in the session. Continue to follow each SOP when its triggering condition applies.
|
|
14
|
+
`);let l=!1;for(let u of i){let d=B(u.body,5e3),g=b(d)+b(u.name)+8;if(n+g>25e3)break;n+=g,r.push(`### ${u.name}
|
|
15
15
|
|
|
16
|
-
${d}`),l=!0}l&&t.push(
|
|
16
|
+
${d}`),l=!0}l&&t.push(r.join(`
|
|
17
17
|
|
|
18
18
|
`))}return e.length>0&&t.push(`## Available tools
|
|
19
19
|
|
|
@@ -24,7 +24,7 @@ You still have access to the following tools \u2014 call them directly when the
|
|
|
24
24
|
|
|
25
25
|
Everything above the divider is reconstructed context. For exact code, error strings, or user-typed text, re-read the source rather than guess from the summary.`),t.join(`
|
|
26
26
|
|
|
27
|
-
`))}};import{readFileSync as ge,writeFileSync as fe,mkdirSync as ye,existsSync as
|
|
27
|
+
`))}};import{readFileSync as ge,writeFileSync as fe,mkdirSync as ye,existsSync as S}from"fs";import{join as $,resolve as H}from"path";var q=f({module:"plan-file"}),V=["brave","calm","dark","eager","fair","gentle","happy","kind","lively","mighty","noble","proud","quiet","swift","warm","wise"],G=["crystal","dragon","eagle","falcon","flame","forest","frost","mountain","ocean","phoenix","river","shadow","thunder","tiger"];function ke(){let o=V[Math.floor(Math.random()*V.length)],e=G[Math.floor(Math.random()*G.length)],t=Date.now().toString(36).slice(-4);return`${o}-${e}-${t}`}var m=null;function K(o,e){let t=H(e,".swifty","plans");return H(o).startsWith(t+"/")}function z(o){if(m&&S(m))if(!K(m,o))q.warn({planPath:m,workDir:o},"current plan path is not under work dir");else return m;let e=$(o,".swifty","plans");ye(e,{recursive:!0});let t=ke();return m=$(e,`${t}.md`),fe(m,"","utf-8"),m}function Be(){return!m||!S(m)?null:ge(m,"utf-8")}function X(o){return!m||!S(m)?!1:K(m,o)?!0:(q.warn({planPath:m,workDir:o},"current plan path is not under work dir"),!1)}function $e(){m=null}var J=`Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits (with the exception of the plan file mentioned below), run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.
|
|
28
28
|
|
|
29
29
|
## Plan File Info:
|
|
30
30
|
|
|
@@ -69,9 +69,9 @@ Goal: Write your final plan to the plan file (the only file you can edit).
|
|
|
69
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
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
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
|
|
73
|
-
A plan file already exists at ${o}. You can read it and make incremental edits using the EditFile tool.`:
|
|
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%",
|
|
72
|
+
You have exited plan mode. You can now make edits, run tools, and take actions.%EXTRA%`,Re="You have re-entered plan mode. Your previous plan file is at %PLAN_PATH%. Review it and continue from where you left off. You can update, refine, or restart the plan as needed. Follow the same 5-phase workflow as before.";function Q(o,e,t){let s=`Plan file: ${o}`;return e?s+=`
|
|
73
|
+
A plan file already exists at ${o}. You can read it and make incremental edits using the EditFile tool.`:s+=`
|
|
74
|
+
No plan file exists yet. You should create your plan at ${o} using the WriteFile tool.`,t===1||Math.floor((t-1)/5)%5===0?J.replace("%PLAN_FILE_INFO%",s):we.replace("%PLAN_PATH%",o)}function Ve(o,e){let t="";return e&&(t=` The plan file is located at ${o} if you need to reference it.`),ve.replace("%EXTRA%",t)}function Ge(o,e){return e?Re.replace("%PLAN_PATH%",o):""}var xe=`You are Swifty, an AI assistant that orchestrates software engineering tasks across multiple workers.
|
|
75
75
|
|
|
76
76
|
## 1. Your Role
|
|
77
77
|
|
|
@@ -224,11 +224,12 @@ You:
|
|
|
224
224
|
|
|
225
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
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
|
|
227
|
+
Fix is in progress.`,be="Coordinator mode still active (see full instructions earlier in conversation). You cannot read files, run commands, or edit code \u2014 send a worker instead. Tools: Agent, SendMessage, TaskStop, SyntheticOutput, TeamDelete. Address workers by the name in the from= field of a team-notification. Synthesize worker findings yourself before directing follow-up work.";function Z(o=1){return o<=1||(o-1)%5===0?xe:be}import{writeFileSync as Se,mkdirSync as Ee}from"fs";import{join as oe,resolve as ee}from"path";var Te=f({module:"tool-result"}),te=2e5;function ne(o,e){return oe(o,".swifty","sessions",e||"default","tool-results")}function se(o,e,t,s){let i=ne(o,e);Ee(i,{recursive:!0});let n=oe(i,t+".txt");try{Se(n,s,{encoding:"utf-8",flag:"wx"})}catch(r){if(Te.error({err:r},"tool-result operation failed"),P(r)&&"code"in r&&r.code!=="EEXIST")throw r}return n}var E=2e3;function ie(o,e){let t=Math.floor(o.length/1024),s=o.slice(0,E),i=o.length>E,n=`<persisted-output>
|
|
228
228
|
`;return n+=`Output too large (${String(t)}KB). Full content saved to:
|
|
229
229
|
${e}
|
|
230
230
|
|
|
231
231
|
`,n+=`Preview (first 2KB):
|
|
232
|
-
${
|
|
232
|
+
${s}`,i&&(n+=`
|
|
233
233
|
...`),n+=`
|
|
234
|
-
</persisted-output>`,n}function 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};
|
|
234
|
+
</persisted-output>`,n}function re(o,e,t,s){if(o!=="ReadFile"||!e)return!1;let i=e.file_path;return typeof i!="string"||!i?!1:ee(i).startsWith(ee(ne(t,s)))}function ae(o,e,t,s){let i=o.reduce((r,l)=>r+l.content.length,0);if(i<=te)return;let n=[...o].sort((r,l)=>l.content.length-r.content.length);for(let r of n){if(i<=te)break;if(s?.has(r.toolUseId)||r.images?.length||r.content.length<=E)continue;let l;try{l=se(e,t,r.toolUseId,r.content)}catch{continue}let u=ie(r.content,l);i-=r.content.length-u.length,r.content=u}}function le(o,e,t,s){let i;try{i=se(o,e,t,s)}catch{return s}return ie(s,i)}import{readFile as Ie}from"fs/promises";var Pe=64e3,ce=3,_e=5e4,he=class{client;registry;checker;conversation;workDir;sessionId;sessionFilePath;hookEngine;fileHistory;fileStateCache;abortSignal;contextWindow;maxOutput;recoveryState;maxIterations;notificationFn;onLoopComplete;compactTracking=new O;onPermissionRequest;toolFilter;coordinatorActiveFn;activeSkills;instructions;memoryContent;skillSection;skillDeltaFn;memoryRecallPromise;memoryRecallConsumed=!1;constructor(e){this.client=e.client,this.registry=e.registry,this.checker=e.checker,this.conversation=e.conversation,this.workDir=e.workDir,this.sessionId=e.sessionId??"",this.sessionFilePath=e.sessionId?L(e.workDir,e.sessionId):"",this.hookEngine=e.hookEngine,this.fileHistory=e.fileHistory,this.fileStateCache=e.fileStateCache,this.abortSignal=e.abortSignal,this.contextWindow=e.contextWindow??2e5,this.maxOutput=e.maxOutput??8192,this.recoveryState=e.recoveryState??new v,this.maxIterations=e.maxIterations??0,this.notificationFn=e.notificationFn,this.onLoopComplete=e.onLoopComplete,this.onPermissionRequest=e.onPermissionRequest,this.activeSkills=e.activeSkills??new Map,this.toolFilter=e.toolFilter,this.coordinatorActiveFn=e.coordinatorActiveFn,this.instructions=e.instructions??"",this.memoryContent=e.memoryContent??"",this.skillSection=e.skillSection??"",this.skillDeltaFn=e.skillDeltaFn,this.memoryRecallPromise=e.memoryRecallPromise}async*run(){let e=this.registry.getAllSchemas();this.toolFilter&&(e=e.filter(r=>this.toolFilter?.(r.name)));let t=this.registry.listTools().map(r=>r.name),s=!1,i=0,n=0;await this.fireLifecycle("session_start");try{let r=!0;for(;r;){if(n++,this.maxIterations>0&&n>this.maxIterations){yield{type:"error",error:new Error(`Agent reached maximum iterations (${String(this.maxIterations)})`)};return}let l="",u=[],d=[],g="end_turn",p=null;if(this.checker.mode==="plan"){let c=z(this.workDir);this.checker.planFilePath=c,this.conversation.addSystemReminder(Q(c,X(this.workDir),n))}if(this.coordinatorActiveFn?.()&&this.conversation.addSystemReminder(Z(n)),this.hookEngine)for(let c of this.hookEngine.drainNotifications())this.conversation.addSystemReminder(c);if(this.notificationFn)for(let c of this.notificationFn())this.conversation.addSystemReminder(c);if(this.skillDeltaFn){let c=this.skillDeltaFn();c&&this.conversation.addSystemReminder(`The following skills became available:
|
|
235
|
+
`+c)}await this.fireLifecycle("turn_start"),await this.fireLifecycle("pre_send");let k=await U(this.conversation,this.client,this.contextWindow,this.maxOutput,this.compactTracking,this.recoveryState,t,e,this.sessionFilePath);k.message&&(yield{type:"compact",message:k.message,boundary:k.boundary}),k.compacted&&this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection);try{let c=this.client.stream(this.conversation,e,this.abortSignal);for await(let a of c){if(this.abortSignal?.aborted){r=!1;break}switch(a.type){case"text_delta":l+=a.text,yield{type:"stream_text",text:a.text};break;case"thinking_delta":yield{type:"thinking_text",text:a.text};break;case"thinking_complete":u.push({thinking:a.thinking,signature:a.signature}),yield{type:"thinking_complete",thinking:a.thinking,signature:a.signature};break;case"tool_call_start":break;case"tool_call_complete":d.push({toolUseId:a.toolId,toolName:a.toolName,arguments:a.arguments}),yield{type:"tool_use",toolName:a.toolName,toolId:a.toolId,args:a.arguments};break;case"stream_end":g=a.stopReason,p=a.usage,yield{type:"usage",usage:a.usage};break}}}catch(c){if(this.abortSignal?.aborted){yield{type:"loop_complete",stopReason:"interrupted"};return}if(c instanceof C)try{let a=await W(this.conversation,this.client,this.recoveryState,t,e,this.sessionFilePath);this.conversation.clearUsageAnchor(),this.conversation.injectLongTermMemory(this.instructions,this.memoryContent,this.skillSection),yield{type:"compact",message:"Auto-compacted due to context length: "+a.message,boundary:a.boundary};continue}catch{yield{type:"error",error:c};return}if(c instanceof A){let a=Ae(x(T(c),"retryAfter"));if(yield{type:"retry",reason:"rate limited",delay:a},await this.interruptibleSleep(a)){yield{type:"loop_complete",stopReason:"interrupted"};return}continue}yield{type:"error",error:c instanceof Error?c:new Error(JSON.stringify(c))};return}if(this.abortSignal?.aborted){l&&(this.conversation.addAssistantFull(l,u,[]),this.persistLastMessage()),yield{type:"loop_complete",stopReason:"interrupted"};return}if(await this.fireLifecycle("post_receive",l),g==="max_tokens")if(s){if(i<ce){i++,this.conversation.addAssistantFull(l,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Break remaining work into smaller pieces."),yield{type:"retry",reason:`max_tokens recovery ${String(i)}/${String(ce)}`,delay:0};continue}}else{this.client.setMaxOutputTokens?.(Pe),s=!0,l&&(this.conversation.addAssistantFull(l,u,[]),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),this.conversation.addUserMessage("Output token limit hit. Resume directly from where you stopped. Do not apologize or repeat previous content. Pick up mid-thought if needed.")),yield{type:"retry",reason:"max_tokens escalation",delay:0};continue}else i=0;if(this.conversation.addAssistantFull(l,u,d),this.persistLastMessage(),p&&this.conversation.recordUsageAnchor(p.inputTokens,p.outputTokens,p.cacheReadInputTokens,p.cacheCreationInputTokens),d.length>0){let c=await this.executeTools(d);for(let h of c)yield h;let a=new Set;for(let h of d)re(h.toolName,h.arguments,this.workDir,this.sessionId)&&a.add(h.toolUseId);let R=[];for(let h of c)if(h.type==="tool_result"){h.images?.length&&a.add(h.toolId);let y=h.output;y.length>_e&&!a.has(h.toolId)&&(y=le(this.workDir,this.sessionId,h.toolId,h.output),a.add(h.toolId)),R.push({toolUseId:h.toolId,content:y,isError:h.isError,...h.images?.length?{images:h.images}:{}})}ae(R,this.workDir,this.sessionId,a);let ue=d.some(h=>h.toolName==="ExitPlanMode");if(this.conversation.addToolResultsMessage(R),this.persistLastMessage(),this.memoryRecallPromise&&!this.memoryRecallConsumed)try{let h=await Promise.race([this.memoryRecallPromise.then(y=>({done:!0,value:y})),Promise.resolve({done:!1,value:""})]);h.done&&(h.value&&this.conversation.addSystemReminder(h.value),this.memoryRecallConsumed=!0)}catch{this.memoryRecallConsumed=!0}if(ue){yield{type:"turn_complete"},yield{type:"loop_complete",stopReason:"end_turn"};return}yield{type:"turn_complete"},await this.fireLifecycle("turn_end")}else{if(r=!1,this.fileHistory){let c=l.length>60?l.slice(0,60)+"...":l;this.fileHistory.makeSnapshot(this.conversation.len(),c)}if(yield{type:"loop_complete",stopReason:g},this.onLoopComplete)try{this.onLoopComplete(this.conversation)}catch{}}}}finally{await this.fireLifecycle("session_end")}}async fireLifecycle(e,t){if(!this.hookEngine)return;let s=await this.hookEngine.fire(e,{event:e,message:t});for(let i of s)i.output&&this.hookEngine.recordNotification(i.output)}interruptibleSleep(e){return new Promise(t=>{if(this.abortSignal?.aborted){t(!0);return}let s=()=>{clearTimeout(i),t(!0)},i=setTimeout(()=>{this.abortSignal?.removeEventListener("abort",s),t(!1)},e);this.abortSignal?.addEventListener("abort",s,{once:!0})})}async executeTools(e){let t=[],s=this.partitionToolCalls(e);for(let i of s){let n=await this.executeBatch(i.blocks,i.concurrent&&i.blocks.length>1);t.push(...n)}return t}partitionToolCalls(e){let t=[];for(let s of e){let n=(this.registry.get(s.toolName)?.category??"command")==="read";n&&t.length>0&&t[t.length-1].concurrent?t[t.length-1].blocks.push(s):t.push({concurrent:n,blocks:[s]})}return t}async executeBatch(e,t){let s=[],i=new w(this.registry,{workDir:this.workDir,fileHistory:this.fileHistory,fileStateCache:this.fileStateCache});for(let n of e){if(this.hookEngine){let d=await this.hookEngine.firePreToolHooks(n.toolName,n.arguments);if(d.rejected){s.push({type:"tool_result",toolName:n.toolName,toolId:n.toolUseId,output:`Rejected by hook: ${d.reason}`,isError:!0,elapsed:0});continue}}let l=this.registry.get(n.toolName)?.category??"command",u=this.checker.check(n.toolName,l,n.arguments);if(u.effect==="deny"){s.push({type:"tool_result",toolName:n.toolName,toolId:n.toolUseId,output:`Permission denied: ${u.reason}. This operation has been blocked by the security policy. Inform the user that the command was denied; do not describe what the command would do.`,isError:!0,elapsed:0});continue}if(u.effect==="ask"&&this.onPermissionRequest){let d=await this.onPermissionRequest(n.toolName,n.arguments,u);if(d==="deny"){s.push({type:"tool_result",toolName:n.toolName,toolId:n.toolUseId,output:_,isError:!0,elapsed:0});continue}d==="allowAlways"&&this.checker.allowAlways(n.toolName,n.arguments)}if(i.submit(n.toolUseId,n.toolName,n.arguments),!t){let d=await i.collectResults();for(let g of d)await this.processToolResult(g,e,s)}}if(t){let n=await i.collectResults();for(let r of n)await this.processToolResult(r,e,s)}return s}async processToolResult(e,t,s){if(!e.result.isError&&e.toolName==="ReadFile"){let i=t.find(r=>r.toolUseId===e.toolId),n=x(i?.arguments??{},"file_path");if(n&&!Y(n))try{this.recoveryState.recordFileRead(n,await Ie(n,"utf-8"))}catch{}}if(s.push({type:"tool_result",toolName:e.toolName,toolId:e.toolId,output:e.result.output,isError:e.result.isError,elapsed:e.elapsed,...e.result.images?.length?{images:e.result.images}:{}}),this.hookEngine){let i=await this.hookEngine.fire("post_tool_use",{event:"post_tool_use",toolName:e.toolName,message:e.result.output});for(let n of i)n.output&&this.hookEngine.recordNotification(n.output)}}persistLastMessage(){if(!this.workDir||!this.sessionId)return;let e=this.conversation.getMessages();if(e.length===0)return;let t=e[e.length-1];D(this.workDir,this.sessionId,{role:t.role,content:t.content,timestamp:Math.floor(Date.now()/1e3),...t.toolUses?.length?{tool_uses:N(t.toolUses)}:{},...t.toolResults?.length?{tool_results:M(t.toolResults,{workDir:this.workDir,sessionId:this.sessionId})}:{},...t.images?.length?{images:F(this.workDir,this.sessionId,t.images)}:{}})}};function Ae(o){if(!o)return 5e3;let e=parseInt(o,10);return Number.isNaN(e)?5e3:e*1e3}export{Y as a,Ne as b,v as c,z as d,Be as e,X as f,$e as g,Ve as h,Ge as i,he as j};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{a as p,b as S,d as N}from"./chunk-X3UA5OZL.js";var T=S((Er,Ve)=>{"use strict";var $e=["nodebuffer","arraybuffer","fragments"],je=typeof Blob<"u";je&&$e.push("blob");Ve.exports={BINARY_TYPES:$e,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:je,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var X=S((vr,re)=>{"use strict";var{EMPTY_BUFFER:Yt}=T(),xe=Buffer[Symbol.species];function Kt(t,e){if(t.length===0)return Yt;if(t.length===1)return t[0];let s=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let n=t[i];s.set(n,r),r+=n.length}return r<e?new xe(s.buffer,s.byteOffset,r):s}function ze(t,e,s,r,i){for(let n=0;n<i;n++)s[r+n]=t[n]^e[n&3]}function He(t,e){for(let s=0;s<t.length;s++)t[s]^=e[s&3]}function Xt(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Se(t){if(Se.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new xe(t):ArrayBuffer.isView(t)?e=new xe(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Se.readOnly=!1),e}re.exports={concat:Kt,mask:ze,toArrayBuffer:Xt,toBuffer:Se,unmask:He};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=p("bufferutil");re.exports.mask=function(e,s,r,i,n){n<48?ze(e,s,r,i,n):t.mask(e,s,r,i,n)},re.exports.unmask=function(e,s){e.length<32?He(e,s):t.unmask(e,s)}}catch{}});var Xe=S((br,Ke)=>{"use strict";var Ye=Symbol("kDone"),Ee=Symbol("kRun"),ve=class{constructor(e){this[Ye]=()=>{this.pending--,this[Ee]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ee]()}[Ee](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ye])}}};Ke.exports=ve});var G=S((wr,et)=>{"use strict";var Z=p("zlib"),Ze=X(),Zt=Xe(),{kStatusCode:Qe}=T(),Qt=Buffer[Symbol.species],Jt=Buffer.from([0,0,255,255]),ne=Symbol("permessage-deflate"),k=Symbol("total-length"),W=Symbol("callback"),P=Symbol("buffers"),q=Symbol("error"),ie,be=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ie){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ie=new Zt(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[W];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let s=this._options,r=e.find(i=>!(s.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(s.serverMaxWindowBits===!1||typeof s.serverMaxWindowBits=="number"&&s.serverMaxWindowBits>i.server_max_window_bits)||typeof s.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return s.serverNoContextTakeover&&(r.server_no_context_takeover=!0),s.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof s.serverMaxWindowBits=="number"&&(r.server_max_window_bits=s.serverMaxWindowBits),typeof s.clientMaxWindowBits=="number"?r.client_max_window_bits=s.clientMaxWindowBits:(r.client_max_window_bits===!0||s.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let s=e[0];if(this._options.clientNoContextTakeover===!1&&s.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!s.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(s.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&s.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return s}normalizeParams(e){return e.forEach(s=>{Object.keys(s).forEach(r=>{let i=s[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);s[r]=i})}),e}decompress(e,s,r){ie.add(i=>{this._decompress(e,s,(n,o)=>{i(),r(n,o)})})}compress(e,s,r){ie.add(i=>{this._compress(e,s,(n,o)=>{i(),r(n,o)})})}_decompress(e,s,r){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?Z.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=Z.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ne]=this,this._inflate[k]=0,this._inflate[P]=[],this._inflate.on("error",ts),this._inflate.on("data",Je)}this._inflate[W]=r,this._inflate.write(e),s&&this._inflate.write(Jt),this._inflate.flush(()=>{let n=this._inflate[q];if(n){this._inflate.close(),this._inflate=null,r(n);return}let o=Ze.concat(this._inflate[P],this._inflate[k]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[k]=0,this._inflate[P]=[],s&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,s,r){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?Z.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=Z.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[k]=0,this._deflate[P]=[],this._deflate.on("data",es)}this._deflate[W]=r,this._deflate.write(e),this._deflate.flush(Z.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=Ze.concat(this._deflate[P],this._deflate[k]);s&&(n=new Qt(n.buffer,n.byteOffset,n.length-4)),this._deflate[W]=null,this._deflate[k]=0,this._deflate[P]=[],s&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,n)})}};et.exports=be;function es(t){this[P].push(t),this[k]+=t.length}function Je(t){if(this[k]+=t.length,this[ne]._maxPayload<1||this[k]<=this[ne]._maxPayload){this[P].push(t);return}this[q]=new RangeError("Max payload size exceeded"),this[q].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[q][Qe]=1009,this.removeListener("data",Je),this.reset()}function ts(t){if(this[ne]._inflate=null,this[q]){this[W](this[q]);return}t[Qe]=1007,this[W](t)}});var $=S((Or,oe)=>{"use strict";var{isUtf8:tt}=p("buffer"),{hasBlob:ss}=T(),rs=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function is(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function we(t){let e=t.length,s=0;for(;s<e;)if((t[s]&128)===0)s++;else if((t[s]&224)===192){if(s+1===e||(t[s+1]&192)!==128||(t[s]&254)===192)return!1;s+=2}else if((t[s]&240)===224){if(s+2>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||t[s]===224&&(t[s+1]&224)===128||t[s]===237&&(t[s+1]&224)===160)return!1;s+=3}else if((t[s]&248)===240){if(s+3>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||(t[s+3]&192)!==128||t[s]===240&&(t[s+1]&240)===128||t[s]===244&&t[s+1]>143||t[s]>244)return!1;s+=4}else return!1;return!0}function ns(t){return ss&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}oe.exports={isBlob:ns,isValidStatusCode:is,isValidUTF8:we,tokenChars:rs};if(tt)oe.exports.isValidUTF8=function(t){return t.length<24?we(t):tt(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=p("utf-8-validate");oe.exports.isValidUTF8=function(e){return e.length<32?we(e):t(e)}}catch{}});var Le=S((Tr,ft)=>{"use strict";var{Writable:os}=p("stream"),st=G(),{BINARY_TYPES:as,EMPTY_BUFFER:rt,kStatusCode:fs,kWebSocket:ls}=T(),{concat:Oe,toArrayBuffer:hs,unmask:cs}=X(),{isValidStatusCode:us,isValidUTF8:it}=$(),ae=Buffer[Symbol.species],v=0,nt=1,ot=2,at=3,Te=4,ke=5,fe=6,Ce=class extends os{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||as[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ls]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=v}_write(e,s,r){if(this._opcode===8&&this._state==v)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new ae(r.buffer,r.byteOffset+e,r.length-e),new ae(r.buffer,r.byteOffset,e)}let s=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=s.length-e;e>=r.length?s.set(this._buffers.shift(),i):(s.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new ae(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return s}startLoop(e){this._loop=!0;do switch(this._state){case v:this.getInfo(e);break;case nt:this.getPayloadLength16(e);break;case ot:this.getPayloadLength64(e);break;case at:this.getMask();break;case Te:this.getData(e);break;case ke:case fe:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let s=this.consume(2);if((s[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(s[0]&64)===64;if(r&&!this._extensions[st.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(s[0]&128)===128,this._opcode=s[0]&15,this._payloadLength=s[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(s[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=nt:this._payloadLength===127?this._state=ot:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let s=this.consume(8),r=s.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+s.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(s);return}this._masked?this._state=at:this._state=Te}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Te}getData(e){let s=rt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}s=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&cs(s,this._mask)}if(this._opcode>7){this.controlMessage(s,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=ke,this.decompress(s,e);return}s.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(s)),this.dataMessage(e)}decompress(e,s){this._extensions[st.extensionName].decompress(e,this._fin,(i,n)=>{if(i)return s(i);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");s(o);return}this._fragments.push(n)}this.dataMessage(s),this._state===v&&this.startLoop(s)})}dataMessage(e){if(!this._fin){this._state=v;return}let s=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Oe(r,s):this._binaryType==="arraybuffer"?i=hs(Oe(r,s)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=v):(this._state=fe,setImmediate(()=>{this.emit("message",i,!0),this._state=v,this.startLoop(e)}))}else{let i=Oe(r,s);if(!this._skipUTF8Validation&&!it(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===ke||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=v):(this._state=fe,setImmediate(()=>{this.emit("message",i,!1),this._state=v,this.startLoop(e)}))}}controlMessage(e,s){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,rt),this.end();else{let r=e.readUInt16BE(0);if(!us(r)){let n=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");s(n);return}let i=new ae(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!it(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");s(n);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=v;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=v):(this._state=fe,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=v,this.startLoop(s)}))}createError(e,s,r,i,n){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${s}`:s);return Error.captureStackTrace(o,this.createError),o.code=n,o[fs]=i,o}};ft.exports=Ce});var Be=S((Cr,ct)=>{"use strict";var{Duplex:kr}=p("stream"),{randomFillSync:ds}=p("crypto"),{types:{isUint8Array:_s}}=p("util"),lt=G(),{EMPTY_BUFFER:ms,kWebSocket:ps,NOOP:gs}=T(),{isBlob:j,isValidStatusCode:ys}=$(),{mask:ht,toBuffer:R}=X(),b=Symbol("kByteLength"),xs=Buffer.alloc(4),le=8*1024,U,V=le,w=0,Ss=1,Es=2,Ne=class t{constructor(e,s,r){this._extensions=s||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=w,this.onerror=gs,this[ps]=void 0}static frame(e,s){let r,i=!1,n=2,o=!1;s.mask&&(r=s.maskBuffer||xs,s.generateMask?s.generateMask(r):(V===le&&(U===void 0&&(U=Buffer.alloc(le)),ds(U,0,le),V=0),r[0]=U[V++],r[1]=U[V++],r[2]=U[V++],r[3]=U[V++]),o=(r[0]|r[1]|r[2]|r[3])===0,n=6);let f;typeof e=="string"?(!s.mask||o)&&s[b]!==void 0?f=s[b]:(e=Buffer.from(e),f=e.length):(f=e.length,i=s.mask&&s.readOnly&&!o);let l=f;f>=65536?(n+=8,l=127):f>125&&(n+=2,l=126);let a=Buffer.allocUnsafe(i?f+n:n);return a[0]=s.fin?s.opcode|128:s.opcode,s.rsv1&&(a[0]|=64),a[1]=l,l===126?a.writeUInt16BE(f,2):l===127&&(a[2]=a[3]=0,a.writeUIntBE(f,4,6)),s.mask?(a[1]|=128,a[n-4]=r[0],a[n-3]=r[1],a[n-2]=r[2],a[n-1]=r[3],o?[a,e]:i?(ht(e,r,a,n,f),[a]):(ht(e,r,e,0,f),[a,e])):[a,e]}close(e,s,r,i){let n;if(e===void 0)n=ms;else{if(typeof e!="number"||!ys(e))throw new TypeError("First argument must be a valid error code number");if(s===void 0||!s.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let f=Buffer.byteLength(s);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");if(n=Buffer.allocUnsafe(2+f),n.writeUInt16BE(e,0),typeof s=="string")n.write(s,2);else if(_s(s))n.set(s,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[b]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==w?this.enqueue([this.dispatch,n,!1,o,i]):this.sendFrame(t.frame(n,o),i)}ping(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):j(e)?(i=e.size,n=!1):(e=R(e),i=e.length,n=R.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[b]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};j(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==w?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):j(e)?(i=e.size,n=!1):(e=R(e),i=e.length,n=R.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[b]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};j(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==w?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,s,r){let i=this._extensions[lt.extensionName],n=s.binary?2:1,o=s.compress,f,l;typeof e=="string"?(f=Buffer.byteLength(e),l=!1):j(e)?(f=e.size,l=!1):(e=R(e),f=e.length,l=R.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=f>=i._threshold),this._compress=o):(o=!1,n=0),s.fin&&(this._firstFragment=!0);let a={[b]:f,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:l,rsv1:o};j(e)?this._state!==w?this.enqueue([this.getBlobData,e,this._compress,a,r]):this.getBlobData(e,this._compress,a,r):this._state!==w?this.enqueue([this.dispatch,e,this._compress,a,r]):this.dispatch(e,this._compress,a,r)}getBlobData(e,s,r,i){this._bufferedBytes+=r[b],this._state=Es,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(Pe,this,f,i);return}this._bufferedBytes-=r[b];let o=R(n);s?this.dispatch(o,s,r,i):(this._state=w,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(n=>{process.nextTick(vs,this,n,i)})}dispatch(e,s,r,i){if(!s){this.sendFrame(t.frame(e,r),i);return}let n=this._extensions[lt.extensionName];this._bufferedBytes+=r[b],this._state=Ss,n.compress(e,r.fin,(o,f)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Pe(this,l,i);return}this._bufferedBytes-=r[b],this._state=w,r.readOnly=!1,this.sendFrame(t.frame(f,r),i),this.dequeue()})}dequeue(){for(;this._state===w&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][b],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][b],this._queue.push(e)}sendFrame(e,s){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],s),this._socket.uncork()):this._socket.write(e[0],s)}};ct.exports=Ne;function Pe(t,e,s){typeof s=="function"&&s(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],n=i[i.length-1];typeof n=="function"&&n(e)}}function vs(t,e,s){Pe(t,e,s),t.onerror(e)}});var St=S((Lr,xt)=>{"use strict";var{kForOnEventAttribute:Q,kListener:Re}=T(),ut=Symbol("kCode"),dt=Symbol("kData"),_t=Symbol("kError"),mt=Symbol("kMessage"),pt=Symbol("kReason"),z=Symbol("kTarget"),gt=Symbol("kType"),yt=Symbol("kWasClean"),C=class{constructor(e){this[z]=null,this[gt]=e}get target(){return this[z]}get type(){return this[gt]}};Object.defineProperty(C.prototype,"target",{enumerable:!0});Object.defineProperty(C.prototype,"type",{enumerable:!0});var I=class extends C{constructor(e,s={}){super(e),this[ut]=s.code===void 0?0:s.code,this[pt]=s.reason===void 0?"":s.reason,this[yt]=s.wasClean===void 0?!1:s.wasClean}get code(){return this[ut]}get reason(){return this[pt]}get wasClean(){return this[yt]}};Object.defineProperty(I.prototype,"code",{enumerable:!0});Object.defineProperty(I.prototype,"reason",{enumerable:!0});Object.defineProperty(I.prototype,"wasClean",{enumerable:!0});var H=class extends C{constructor(e,s={}){super(e),this[_t]=s.error===void 0?null:s.error,this[mt]=s.message===void 0?"":s.message}get error(){return this[_t]}get message(){return this[mt]}};Object.defineProperty(H.prototype,"error",{enumerable:!0});Object.defineProperty(H.prototype,"message",{enumerable:!0});var J=class extends C{constructor(e,s={}){super(e),this[dt]=s.data===void 0?null:s.data}get data(){return this[dt]}};Object.defineProperty(J.prototype,"data",{enumerable:!0});var bs={addEventListener(t,e,s={}){for(let i of this.listeners(t))if(!s[Q]&&i[Re]===e&&!i[Q])return;let r;if(t==="message")r=function(n,o){let f=new J("message",{data:o?n:n.toString()});f[z]=this,he(e,this,f)};else if(t==="close")r=function(n,o){let f=new I("close",{code:n,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[z]=this,he(e,this,f)};else if(t==="error")r=function(n){let o=new H("error",{error:n,message:n.message});o[z]=this,he(e,this,o)};else if(t==="open")r=function(){let n=new C("open");n[z]=this,he(e,this,n)};else return;r[Q]=!!s[Q],r[Re]=e,s.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let s of this.listeners(t))if(s[Re]===e&&!s[Q]){this.removeListener(t,s);break}}};xt.exports={CloseEvent:I,ErrorEvent:H,Event:C,EventTarget:bs,MessageEvent:J};function he(t,e,s){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,s):t.call(e,s)}});var ce=S((Nr,Et)=>{"use strict";var{tokenChars:ee}=$();function O(t,e,s){t[e]===void 0?t[e]=[s]:t[e].push(s)}function ws(t){let e=Object.create(null),s=Object.create(null),r=!1,i=!1,n=!1,o,f,l=-1,a=-1,h=-1,c=0;for(;c<t.length;c++)if(a=t.charCodeAt(c),o===void 0)if(h===-1&&ee[a]===1)l===-1&&(l=c);else if(c!==0&&(a===32||a===9))h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);a===44?(O(e,g,s),s=Object.create(null)):o=g,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);else if(f===void 0)if(h===-1&&ee[a]===1)l===-1&&(l=c);else if(a===32||a===9)h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c),O(s,t.slice(l,h),!0),a===44&&(O(e,o,s),s=Object.create(null),o=void 0),l=h=-1}else if(a===61&&l!==-1&&h===-1)f=t.slice(l,c),l=h=-1;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(i){if(ee[a]!==1)throw new SyntaxError(`Unexpected character at index ${c}`);l===-1?l=c:r||(r=!0),i=!1}else if(n)if(ee[a]===1)l===-1&&(l=c);else if(a===34&&l!==-1)n=!1,h=c;else if(a===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(a===34&&t.charCodeAt(c-1)===61)n=!0;else if(h===-1&&ee[a]===1)l===-1&&(l=c);else if(l!==-1&&(a===32||a===9))h===-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);r&&(g=g.replace(/\\/g,""),r=!1),O(s,f,g),a===44&&(O(e,o,s),s=Object.create(null),o=void 0),f=void 0,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);if(l===-1||n||a===32||a===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=c);let _=t.slice(l,h);return o===void 0?O(e,_,s):(f===void 0?O(s,_,!0):r?O(s,f,_.replace(/\\/g,"")):O(s,f,_),O(e,o,s)),e}function Os(t){return Object.keys(t).map(e=>{let s=t[e];return Array.isArray(s)||(s=[s]),s.map(r=>[e].concat(Object.keys(r).map(i=>{let n=r[i];return Array.isArray(n)||(n=[n]),n.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Et.exports={format:Os,parse:ws}});var me=S((Rr,Rt)=>{"use strict";var Ts=p("events"),ks=p("https"),Cs=p("http"),wt=p("net"),Ls=p("tls"),{randomBytes:Ns,createHash:Ps}=p("crypto"),{Duplex:Pr,Readable:Br}=p("stream"),{URL:Ue}=p("url"),B=G(),Bs=Le(),Rs=Be(),{isBlob:Us}=$(),{BINARY_TYPES:vt,CLOSE_TIMEOUT:Is,EMPTY_BUFFER:ue,GUID:Ds,kForOnEventAttribute:Ie,kListener:Ms,kStatusCode:Fs,kWebSocket:y,NOOP:Ot}=T(),{EventTarget:{addEventListener:As,removeEventListener:Ws}}=St(),{format:qs,parse:Gs}=ce(),{toBuffer:$s}=X(),Tt=Symbol("kAborted"),De=[8,13],L=["CONNECTING","OPEN","CLOSING","CLOSED"],js=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,d=class t extends Ts{constructor(e,s,r){super(),this._binaryType=vt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ue,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?s=[]:Array.isArray(s)||(typeof s=="object"&&s!==null?(r=s,s=[]):s=[s]),kt(this,e,s,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){vt.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,s,r){let i=new Bs({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),n=new Rs(e,this._extensions,r.generateMask);this._receiver=i,this._sender=n,this._socket=e,i[y]=this,n[y]=this,e[y]=this,i.on("conclude",Hs),i.on("drain",Ys),i.on("error",Ks),i.on("message",Xs),i.on("ping",Zs),i.on("pong",Qs),n.onerror=Js,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),s.length>0&&e.unshift(s),e.on("close",Nt),e.on("data",_e),e.on("end",Pt),e.on("error",Bt),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[B.extensionName]&&this._extensions[B.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,s){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,s,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Lt(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Me(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.ping(e||ue,s,r)}pong(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Me(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.pong(e||ue,s,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof s=="function"&&(r=s,s={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Me(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[B.extensionName]||(i.compress=!1),this._sender.send(e||ue,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(d,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(d.prototype,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(d,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(d.prototype,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(d,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(d.prototype,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(d,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});Object.defineProperty(d.prototype,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(d.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(d.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ie])return e[Ms];return null},set(e){for(let s of this.listeners(t))if(s[Ie]){this.removeListener(t,s);break}typeof e=="function"&&this.addEventListener(t,e,{[Ie]:!0})}})});d.prototype.addEventListener=As;d.prototype.removeEventListener=Ws;Rt.exports=d;function kt(t,e,s,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Is,protocolVersion:De[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!De.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${De.join(", ")})`);let n;if(e instanceof Ue)n=e;else try{n=new Ue(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),t._url=n.href;let o=n.protocol==="wss:",f=n.protocol==="ws+unix:",l;if(n.protocol!=="ws:"&&!o&&!f?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!n.pathname?l="The URL's pathname is empty":n.hash&&(l="The URL contains a fragment identifier"),l){let u=new SyntaxError(l);if(t._redirects===0)throw u;de(t,u);return}let a=o?443:80,h=Ns(16).toString("base64"),c=o?ks.request:Cs.request,_=new Set,g;if(i.createConnection=i.createConnection||(o?zs:Vs),i.defaultPort=i.defaultPort||a,i.port=n.port||a,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new B({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=qs({[B.extensionName]:g.offer()})),s.length){for(let u of s){if(typeof u!="string"||!js.test(u)||_.has(u))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(u)}i.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),f){let u=i.path.split(":");i.socketPath=u[0],i.path=u[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=f,t._originalSecure=o,t._originalHostOrSocketPath=f?i.socketPath:n.host;let u=r&&r.headers;if(r={...r,headers:{}},u)for(let[x,F]of Object.entries(u))r.headers[x.toLowerCase()]=F}else if(t.listenerCount("redirect")===0){let u=f?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:n.host===t._originalHostOrSocketPath;(!u||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,u||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=c(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=c(i);i.timeout&&m.on("timeout",()=>{E(t,m,"Opening handshake has timed out")}),m.on("error",u=>{m===null||m[Tt]||(m=t._req=null,de(t,u))}),m.on("response",u=>{let x=u.headers.location,F=u.statusCode;if(x&&i.followRedirects&&F>=300&&F<400){if(++t._redirects>i.maxRedirects){E(t,m,"Maximum redirects exceeded");return}m.abort();let Y;try{Y=new Ue(x,e)}catch{let A=new SyntaxError(`Invalid URL: ${x}`);de(t,A);return}kt(t,Y,s,r)}else t.emit("unexpected-response",m,u)||E(t,m,`Unexpected server response: ${u.statusCode}`)}),m.on("upgrade",(u,x,F)=>{if(t.emit("upgrade",u),t.readyState!==d.CONNECTING)return;m=t._req=null;let Y=u.headers.upgrade;if(Y===void 0||Y.toLowerCase()!=="websocket"){E(t,x,"Invalid Upgrade header");return}let We=Ps("sha1").update(h+Ds).digest("base64");if(u.headers["sec-websocket-accept"]!==We){E(t,x,"Invalid Sec-WebSocket-Accept header");return}let A=u.headers["sec-websocket-protocol"],K;if(A!==void 0?_.size?_.has(A)||(K="Server sent an invalid subprotocol"):K="Server sent a subprotocol but none was requested":_.size&&(K="Server sent no subprotocol"),K){E(t,x,K);return}A&&(t._protocol=A);let qe=u.headers["sec-websocket-extensions"];if(qe!==void 0){if(!g){E(t,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ge;try{ge=Gs(qe)}catch{E(t,x,"Invalid Sec-WebSocket-Extensions header");return}let Ge=Object.keys(ge);if(Ge.length!==1||Ge[0]!==B.extensionName){E(t,x,"Server indicated an extension that was not requested");return}try{g.accept(ge[B.extensionName])}catch{E(t,x,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[B.extensionName]=g}t.setSocket(x,F,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function de(t,e){t._readyState=d.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Vs(t){return t.path=t.socketPath,wt.connect(t)}function zs(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=wt.isIP(t.host)?"":t.host),Ls.connect(t)}function E(t,e,s){t._readyState=d.CLOSING;let r=new Error(s);Error.captureStackTrace(r,E),e.setHeader?(e[Tt]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(de,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Me(t,e,s){if(e){let r=Us(e)?e.size:$s(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(s){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${L[t.readyState]})`);process.nextTick(s,r)}}function Hs(t,e){let s=this[y];s._closeFrameReceived=!0,s._closeMessage=e,s._closeCode=t,s._socket[y]!==void 0&&(s._socket.removeListener("data",_e),process.nextTick(Ct,s._socket),t===1005?s.close():s.close(t,e))}function Ys(){let t=this[y];t.isPaused||t._socket.resume()}function Ks(t){let e=this[y];e._socket[y]!==void 0&&(e._socket.removeListener("data",_e),process.nextTick(Ct,e._socket),e.close(t[Fs])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function bt(){this[y].emitClose()}function Xs(t,e){this[y].emit("message",t,e)}function Zs(t){let e=this[y];e._autoPong&&e.pong(t,!this._isServer,Ot),e.emit("ping",t)}function Qs(t){this[y].emit("pong",t)}function Ct(t){t.resume()}function Js(t){let e=this[y];e.readyState!==d.CLOSED&&(e.readyState===d.OPEN&&(e._readyState=d.CLOSING,Lt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Lt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Nt(){let t=this[y];if(this.removeListener("close",Nt),this.removeListener("data",_e),this.removeListener("end",Pt),t._readyState=d.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[y]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",bt),t._receiver.on("finish",bt))}function _e(t){this[y]._receiver.write(t)||this.pause()}function Pt(){let t=this[y];t._readyState=d.CLOSING,t._receiver.end(),this.end()}function Bt(){let t=this[y];this.removeListener("error",Bt),this.on("error",Ot),t&&(t._readyState=d.CLOSING,this.destroy())}});var Mt=S((Ir,Dt)=>{"use strict";var Ur=me(),{Duplex:er}=p("stream");function Ut(t){t.emit("close")}function tr(){!this.destroyed&&this._writableState.finished&&this.destroy()}function It(t){this.removeListener("error",It),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function sr(t,e){let s=!0,r=new er({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(n,o){let f=!o&&r._readableState.objectMode?n.toString():n;r.push(f)||t.pause()}),t.once("error",function(n){r.destroyed||(s=!1,r.destroy(n))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,n){if(t.readyState===t.CLOSED){n(i),process.nextTick(Ut,r);return}let o=!1;t.once("error",function(l){o=!0,n(l)}),t.once("close",function(){o||n(i),process.nextTick(Ut,r)}),s&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,n,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,n,o)});return}t.send(i,o)},r.on("end",tr),r.on("error",It),r}Dt.exports=sr});var Fe=S((Dr,Ft)=>{"use strict";var{tokenChars:rr}=$();function ir(t){let e=new Set,s=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&rr[o]===1)s===-1&&(s=i);else if(i!==0&&(o===32||o===9))r===-1&&s!==-1&&(r=i);else if(o===44){if(s===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let f=t.slice(s,r);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),s=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(s===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let n=t.slice(s,i);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}Ft.exports={parse:ir}});var Vt=S((Fr,jt)=>{"use strict";var nr=p("events"),pe=p("http"),{Duplex:Mr}=p("stream"),{createHash:or}=p("crypto"),At=ce(),D=G(),ar=Fe(),fr=me(),{CLOSE_TIMEOUT:lr,GUID:hr,kWebSocket:cr}=T(),ur=/^[+/0-9A-Za-z]{22}==$/,Wt=0,qt=1,$t=2,Ae=class extends nr{constructor(e,s){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:lr,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:fr,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=pe.createServer((r,i)=>{let n=pe.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n)}),this._server.listen(e.port,e.host,e.backlog,s)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=dr(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,o)=>{this.handleUpgrade(i,n,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Wt}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===$t){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(te,this);return}if(e&&this.once("close",e),this._state!==qt)if(this._state=qt,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(te,this):process.nextTick(te,this);else{let s=this._server;this._removeListeners(),this._removeListeners=this._server=null,s.close(()=>{te(this)})}}shouldHandle(e){if(this.options.path){let s=e.url.indexOf("?");if((s!==-1?e.url.slice(0,s):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,s,r,i){s.on("error",Gt);let n=e.headers["sec-websocket-key"],o=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){M(this,e,s,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){M(this,e,s,400,"Invalid Upgrade header");return}if(n===void 0||!ur.test(n)){M(this,e,s,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){M(this,e,s,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){se(s,400);return}let l=e.headers["sec-websocket-protocol"],a=new Set;if(l!==void 0)try{a=ar.parse(l)}catch{M(this,e,s,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],c={};if(this.options.perMessageDeflate&&h!==void 0){let _=new D({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=At.parse(h);g[D.extensionName]&&(_.accept(g[D.extensionName]),c[D.extensionName]=_)}catch{M(this,e,s,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(g,m,u,x)=>{if(!g)return se(s,m||401,u,x);this.completeUpgrade(c,n,a,e,s,r,i)});return}if(!this.options.verifyClient(_))return se(s,401)}this.completeUpgrade(c,n,a,e,s,r,i)}completeUpgrade(e,s,r,i,n,o,f){if(!n.readable||!n.writable)return n.destroy();if(n[cr])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Wt)return se(n,503);let a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${or("sha1").update(s+hr).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(r.size){let c=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;c&&(a.push(`Sec-WebSocket-Protocol: ${c}`),h._protocol=c)}if(e[D.extensionName]){let c=e[D.extensionName].params,_=At.format({[D.extensionName]:[c]});a.push(`Sec-WebSocket-Extensions: ${_}`),h._extensions=e}this.emit("headers",a,i),n.write(a.concat(`\r
|
|
5
|
+
`).join(`\r
|
|
6
|
+
`)),n.removeListener("error",Gt),h.setSocket(n,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(te,this)})),f(h,i)}};jt.exports=Ae;function dr(t,e){for(let s of Object.keys(e))t.on(s,e[s]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function te(t){t._state=$t,t.emit("close")}function Gt(){this.destroy()}function se(t,e,s,r){s=s||pe.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${pe.STATUS_CODES[e]}\r
|
|
7
|
+
`+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
|
|
8
|
+
`)+`\r
|
|
9
|
+
\r
|
|
10
|
+
`+s)}function M(t,e,s,r,i,n){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,M),t.emit("wsClientError",o,s,e)}else se(s,r,i,n)}});var _r=N(Mt(),1),mr=N(ce(),1),pr=N(G(),1),gr=N(Le(),1),yr=N(Be(),1),xr=N(Fe(),1),zt=N(me(),1),Sr=N(Vt(),1);var Ar=zt.default;export{zt as a,Sr as b,Ar as c};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{c as t}from"./chunk-
|
|
4
|
+
import{c as t}from"./chunk-XBHVVB5A.js";import"./chunk-X3UA5OZL.js";var n=globalThis;n.WebSocket||=t;n.window||=globalThis;n.self||=globalThis;n.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__=[{type:1,value:7,isEnabled:!0},{type:2,value:"InternalApp",isEnabled:!0,isValid:!0},{type:2,value:"InternalAppContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalStdoutContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalStderrContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalStdinContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalFocusContext",isEnabled:!0,isValid:!0}];import a from"react-devtools-core";var l=async()=>new Promise(o=>{let e=new t("ws://localhost:8097"),i=setTimeout(()=>{e.terminate(),o(!1)},2e3);i.unref(),e.on("open",()=>{clearTimeout(i),e.terminate(),o(!0)}),e.on("error",()=>{clearTimeout(i),e.terminate(),o(!1)})});await l()?(a.initialize(),a.connectToDevTools()):console.warn(`DEV is set to true, but the React DevTools server is not running. Start it with:
|
|
5
5
|
|
|
6
6
|
$ npx react-devtools
|
|
7
7
|
`);
|
package/dist/glob_addon.node
CHANGED
|
Binary file
|