@swifty.js/swifty 0.0.32 → 0.0.35
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/README.md +64 -0
- package/dist/acp-A4KRKOHD.js +14 -0
- package/dist/agent-VDWIGFIV.js +4 -0
- package/dist/anthropic-AR2Y4FBR.js +4 -0
- package/dist/bwrap-4KOC7P3X.js +4 -0
- package/dist/chunk-2U4IWZ6E.js +4 -0
- package/dist/{chunk-2EV72T5X.js → chunk-325L2ILZ.js} +1 -1
- package/dist/chunk-35X3GW25.js +4 -0
- package/dist/chunk-44LPRRYU.js +60 -0
- package/dist/chunk-4B4SGVJH.js +164 -0
- package/dist/chunk-5W2TCASL.js +4 -0
- package/dist/chunk-6I3HEMIE.js +4 -0
- package/dist/{chunk-TKQ5T5VO.js → chunk-7JQHFZRD.js} +2 -2
- package/dist/chunk-F4FOFPKL.js +611 -0
- package/dist/chunk-FZORZF22.js +16 -0
- package/dist/chunk-G2TE2QZM.js +4 -0
- package/dist/{chunk-JMF2DWGY.js → chunk-H56UQALW.js} +1 -1
- package/dist/chunk-IOLGXPUQ.js +6 -0
- package/dist/chunk-IXCJZNBB.js +5 -0
- package/dist/chunk-IZ7QOBSB.js +4 -0
- package/dist/chunk-JC44NVST.js +4 -0
- package/dist/chunk-LC7ZWLIH.js +4 -0
- package/dist/chunk-M4D66APS.js +67 -0
- package/dist/chunk-NCZR3AGA.js +65 -0
- package/dist/chunk-NDPYUGE5.js +5 -0
- package/dist/chunk-PH643I2P.js +4 -0
- package/dist/{chunk-FPQ2LBL4.js → chunk-QQVDL4QT.js} +1 -1
- package/dist/{chunk-TCQ4EB4G.js → chunk-TNF3EHFY.js} +1 -1
- package/dist/{server-QMMIYNXW.js → chunk-TOM34LJB.js} +16 -16
- package/dist/{chunk-NERVCUWE.js → chunk-UJGMTIYO.js} +1 -1
- package/dist/chunk-XGUH7SGV.js +4 -0
- package/dist/chunk-YBS5ATGZ.js +4 -0
- package/dist/chunk-YKWIZE5D.js +4 -0
- package/dist/{devtools-OJ75EP3T.js → devtools-WJM4UVVT.js} +1 -1
- package/dist/esm-46WSO26W.js +4 -0
- package/dist/esm-6EDGM6QS.js +4 -0
- package/dist/esm-D6BB3FBR.js +4 -0
- package/dist/esm-P2KEXEEK.js +4 -0
- package/dist/esm-VBV56AO5.js +229 -0
- package/dist/esm-XYKZYVLV.js +4 -0
- package/dist/esm-YJVVI2QX.js +4 -0
- package/dist/getMachineId-bsd-NBOQ3GRQ.js +4 -0
- package/dist/getMachineId-darwin-6VBNSUFR.js +5 -0
- package/dist/getMachineId-linux-RQ33NIOO.js +4 -0
- package/dist/getMachineId-unsupported-IWOYPUHZ.js +4 -0
- package/dist/getMachineId-win-ITT3WXP6.js +4 -0
- package/dist/lib/agent-TC4HSVMS.js +16 -0
- package/dist/lib/{anthropic-B33M2AVN.js → anthropic-FKIGL7NL.js} +6 -5
- package/dist/lib/bwrap-2OL7VPSO.js +7 -0
- package/dist/lib/{chunk-FODSMOWP.js → chunk-6V7RW6HA.js} +34 -16
- package/dist/lib/{chunk-TJLAJGG4.js → chunk-ALQHMYOZ.js} +14 -3
- package/dist/lib/{chunk-XT67KGWE.js → chunk-BQFVUVLI.js} +12 -2
- package/dist/lib/chunk-FFM2LB4C.js +132 -0
- package/dist/lib/{chunk-VUD72RTY.js → chunk-FLKB4BK7.js} +16 -5
- package/dist/lib/{chunk-3OFLDUAW.js → chunk-HQSYRTER.js} +96 -49
- package/dist/lib/{chunk-4BPKIIQD.js → chunk-LRN4MOQ3.js} +31 -5
- package/dist/lib/chunk-MLKGABMK.js +9 -0
- package/dist/lib/chunk-OJTISIYU.js +462 -0
- package/dist/lib/{chunk-BCBD34D2.js → chunk-OLFXCZVH.js} +25 -7
- package/dist/lib/{chunk-SOOSTGHI.js → chunk-RUDYC7OS.js} +32 -48
- package/dist/lib/{chunk-UH5M7FDP.js → chunk-S5VWPTME.js} +1189 -126
- package/dist/lib/chunk-YIWNQ7OA.js +47 -0
- package/dist/lib/{chunk-3XCGUKGJ.js → chunk-ZPIF7IJN.js} +219 -6
- package/dist/lib/index.d.ts +3267 -1143
- package/dist/lib/index.js +13214 -12207
- package/dist/lib/{openai-C2PZFGJ2.js → openai-ZWIYIBLC.js} +4 -3
- package/dist/lib/{checker-QNMXPZ7C.js → permissions-BW4QPZXV.js} +4 -3
- package/dist/lib/providers-ROWSB6ND.js +9 -0
- package/dist/lib/sandbox-runtime-CCQ3X3SM.js +9 -0
- package/dist/lib/seatbelt-WO7YWKLR.js +7 -0
- package/dist/lib/{tool-filter-IMIU7CW2.js → tool-filter-QU4LOZII.js} +2 -1
- package/dist/main.js +231 -190
- package/dist/{node-GXMM4JG3.js → node-A6KBFKOV.js} +1 -1
- package/dist/{openai-M7B2TITO.js → openai-7LMX5HKW.js} +1 -1
- package/dist/permissions-74IHQW76.js +4 -0
- package/dist/providers-2J4JJYQD.js +4 -0
- package/dist/sandbox-runtime-RVW4BK3L.js +4 -0
- package/dist/seatbelt-GMQUP6SV.js +4 -0
- package/dist/server-ZYK4L22D.js +4 -0
- package/dist/src-3A5BCUSZ.js +4 -0
- package/dist/src-CRYFVH7Y.js +12 -0
- package/dist/src-Y77IB66J.js +4 -0
- package/dist/src-ZCW4GCG2.js +4 -0
- package/dist/{tool-filter-7LLVAHD5.js → tool-filter-U5SSL3LR.js} +1 -1
- package/dist/turndown.es-WNOSVZF6.js +83 -0
- package/package.json +34 -5
- package/dist/agent-2DUTUJFX.js +0 -4
- package/dist/anthropic-KR5MXB5I.js +0 -4
- package/dist/bwrap-TPE6G4BM.js +0 -4
- package/dist/checker-RKAWOOXC.js +0 -4
- package/dist/chunk-4YVJP2CO.js +0 -4
- package/dist/chunk-BWWNI2FK.js +0 -121
- package/dist/chunk-LTFPTWX4.js +0 -612
- package/dist/chunk-S35E7OYL.js +0 -5
- package/dist/chunk-TW7RHCDS.js +0 -150
- package/dist/chunk-X3UA5OZL.js +0 -4
- package/dist/lib/agent-3OEC4SOB.js +0 -10
- package/dist/lib/bwrap-QRGPUP4J.js +0 -6
- package/dist/lib/chunk-ORSYNBMM.js +0 -38
- package/dist/lib/seatbelt-FT5IY73W.js +0 -6
- package/dist/seatbelt-3GM2YGXV.js +0 -5
package/README.md
CHANGED
|
@@ -139,6 +139,70 @@ The thinking level controls reasoning depth. For `anthropic` it maps to a thinki
|
|
|
139
139
|
|
|
140
140
|
API keys are resolved in this order: explicit api_key field, then environment variables (ANTHROPIC_API_KEY for anthropic, OPENAI_API_KEY for openai and openai-compat).
|
|
141
141
|
|
|
142
|
+
### Telemetry
|
|
143
|
+
|
|
144
|
+
Telemetry is disabled by default and is configured only through environment variables. Swifty does not send prompts, model output, thinking content, tool arguments, tool results, file paths, API keys, or raw session IDs. Session identifiers included in traces are hashed.
|
|
145
|
+
|
|
146
|
+
#### OpenTelemetry
|
|
147
|
+
|
|
148
|
+
Set at least one exporter variable to enable OpenTelemetry:
|
|
149
|
+
|
|
150
|
+
| Variable | Values / purpose |
|
|
151
|
+
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
|
|
152
|
+
| `OTEL_SDK_DISABLED` | Set to `true` to disable OpenTelemetry and Langfuse tracing. |
|
|
153
|
+
| `OTEL_SERVICE_NAME` | Service name; defaults to `swifty`. |
|
|
154
|
+
| `OTEL_RESOURCE_ATTRIBUTES` | Comma-separated resource attributes, for example `deployment.environment.name=production`. |
|
|
155
|
+
| `OTEL_TRACES_EXPORTER` | Comma-separated `otlp`, `console`, or `none`. |
|
|
156
|
+
| `OTEL_LOGS_EXPORTER` | Comma-separated `otlp`, `console`, or `none`. |
|
|
157
|
+
| `OTEL_METRICS_EXPORTER` | Comma-separated `otlp`, `console`, `prometheus`, or `none`. |
|
|
158
|
+
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Default OTLP protocol: `grpc`, `http/json`, or `http/protobuf`. |
|
|
159
|
+
| `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` | Optional trace-specific protocol override. |
|
|
160
|
+
| `OTEL_EXPORTER_OTLP_LOGS_PROTOCOL` | Optional log-specific protocol override. |
|
|
161
|
+
| `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL` | Optional metric-specific protocol override. |
|
|
162
|
+
| `OTEL_EXPORTER_OTLP_ENDPOINT` | Shared OTLP collector endpoint. |
|
|
163
|
+
| `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` | Optional trace-specific endpoint. |
|
|
164
|
+
| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | Optional log-specific endpoint. |
|
|
165
|
+
| `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` | Optional metric-specific endpoint. |
|
|
166
|
+
| `OTEL_EXPORTER_OTLP_HEADERS` | Shared comma-separated OTLP headers. Signal-specific standard header variables are also supported by the exporters. |
|
|
167
|
+
| `OTEL_METRIC_EXPORT_INTERVAL` | Metric export interval in milliseconds; defaults to `60000`. |
|
|
168
|
+
|
|
169
|
+
Example:
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
export OTEL_TRACES_EXPORTER=otlp
|
|
173
|
+
export OTEL_METRICS_EXPORTER=otlp
|
|
174
|
+
export OTEL_LOGS_EXPORTER=otlp
|
|
175
|
+
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
|
176
|
+
export OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com
|
|
177
|
+
export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer token"
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
#### Langfuse
|
|
181
|
+
|
|
182
|
+
Langfuse tracing is enabled when both `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` are set. It shares Swifty's trace hierarchy with OpenTelemetry.
|
|
183
|
+
|
|
184
|
+
| Variable | Purpose |
|
|
185
|
+
| ------------------------------ | --------------------------------------------------- |
|
|
186
|
+
| `LANGFUSE_PUBLIC_KEY` | Langfuse project public key. |
|
|
187
|
+
| `LANGFUSE_SECRET_KEY` | Langfuse project secret key. |
|
|
188
|
+
| `LANGFUSE_BASE_URL` | Langfuse cloud or self-hosted endpoint. |
|
|
189
|
+
| `LANGFUSE_TRACING_ENVIRONMENT` | Environment attached to traces. |
|
|
190
|
+
| `LANGFUSE_RELEASE` | Release identifier; defaults to the Swifty version. |
|
|
191
|
+
| `LANGFUSE_FLUSH_AT` | Number of spans accumulated before export. |
|
|
192
|
+
| `LANGFUSE_FLUSH_INTERVAL` | Batch flush interval in seconds. |
|
|
193
|
+
| `LANGFUSE_TIMEOUT` | Export request timeout in seconds. |
|
|
194
|
+
|
|
195
|
+
#### Sentry
|
|
196
|
+
|
|
197
|
+
Sentry is enabled when `SENTRY_DSN` is set. It reports process-level errors only; performance tracing remains handled by OpenTelemetry.
|
|
198
|
+
|
|
199
|
+
| Variable | Purpose |
|
|
200
|
+
| -------------------- | --------------------------------------------------- |
|
|
201
|
+
| `SENTRY_DSN` | Sentry project DSN. |
|
|
202
|
+
| `SENTRY_ENVIRONMENT` | Deployment environment. |
|
|
203
|
+
| `SENTRY_RELEASE` | Release identifier; defaults to the Swifty version. |
|
|
204
|
+
| `SENTRY_DEBUG` | Set to `true` to enable Sentry SDK diagnostics. |
|
|
205
|
+
|
|
142
206
|
### Project-level MCP servers (.mcp.json)
|
|
143
207
|
|
|
144
208
|
In addition to `mcp_servers` in `config.yaml`, Swifty reads a project-level `.mcp.json` from the working directory, using the Claude Code-compatible format:
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{a as Ot,b as Dt}from"./chunk-TOM34LJB.js";import"./chunk-F4FOFPKL.js";import"./chunk-UJGMTIYO.js";import{p as kt,q as vt,s as Nt,t as At,u as It,v as Mt,w as jt}from"./chunk-4B4SGVJH.js";import{a as Ct}from"./chunk-IOLGXPUQ.js";import"./chunk-XGUH7SGV.js";import"./chunk-H56UQALW.js";import"./chunk-TNF3EHFY.js";import{v as Rt,w as yt,x as Tt}from"./chunk-NDPYUGE5.js";import"./chunk-5W2TCASL.js";import"./chunk-325L2ILZ.js";import{k as Be,s as $e}from"./chunk-44LPRRYU.js";import{D as K,g as s,h as xt,i as x,j as A,k as v,n as c,o as T,p as r,r as b,t as B,u as d,w as l}from"./chunk-NCZR3AGA.js";import{b as Et}from"./chunk-QQVDL4QT.js";import"./chunk-35X3GW25.js";import"./chunk-G2TE2QZM.js";import"./chunk-FZORZF22.js";import"./chunk-YKWIZE5D.js";import"./chunk-LC7ZWLIH.js";import{d as Se}from"./chunk-IZ7QOBSB.js";var Os={};Se(Os,{runAcpStdio:()=>zt});import{Readable as Oa,Writable as Da}from"stream";var h={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},_={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_connect:"mcp/connect",mcp_message:"mcp/message",mcp_disconnect:"mcp/disconnect",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},Je={cancel_request:"$/cancel_request"},Ve=1;var qt=Symbol("skippedItem");function o(t,e){return t.catch(e)}function O(t,e){let n=t.catch(e);return K.unknown().transform((i,a)=>i!==void 0?n.parse(i):(a.addIssue({code:"custom",message:"Required value is missing"}),K.NEVER))}function Ht(t,e){if(t===null||typeof t!="object"||Array.isArray(t))return;let n=t[e];return typeof n=="string"?n:void 0}function ae(t,e,n){return t.superRefine((i,a)=>{let u=Ht(i,e);u!==void 0&&n.includes(u)&&a.addIssue({code:"custom",path:[e],message:`${e} ${JSON.stringify(u)} is reserved by a known variant, but the value does not match that variant's schema`})})}function ce(t,e,n){return K.unknown().transform((i,a)=>{let u=t.safeParse(i);if(!u.success){for(let f of u.error.issues)a.addIssue({...f,input:i});return K.NEVER}let p=u.data,z=Ht(i,e);if(z!==void 0&&!n.includes(z)){let f=i;for(let[g,m]of Object.entries(f))g!=="__proto__"&&(Object.hasOwn(p,g)||(p[g]=m))}return p})}function S(t){return K.array(t.catch(qt)).transform(e=>e.filter(n=>n!==qt))}var $=b([x(),s()]).nullable(),E=s(),Qe=r({sessionId:E,path:s(),content:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Ye=r({sessionId:E,path:s(),line:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),limit:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ze=s(),Pt=b([l("read"),l("edit"),l("delete"),l("move"),l("search"),l("execute"),l("think"),l("fetch"),l("switch_mode"),l("other")]),Lt=b([l("pending"),l("in_progress"),l("completed"),l("failed")]),si=b([l("assistant"),l("user")]),de=r({audience:o(S(si).nullish(),()=>{}),lastModified:o(s().nullish(),()=>{}),priority:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),ii=r({annotations:o(de.nullish(),()=>{}),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),oi=r({annotations:o(de.nullish(),()=>{}),data:s(),mimeType:s(),uri:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),ri=r({annotations:o(de.nullish(),()=>{}),data:s(),mimeType:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),ai=r({annotations:o(de.nullish(),()=>{}),description:o(s().nullish(),()=>{}),mimeType:o(s().nullish(),()=>{}),name:s(),size:o(x().nullish(),()=>{}),title:o(s().nullish(),()=>{}),uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),ci=r({mimeType:o(s().nullish(),()=>{}),text:s(),uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),di=r({blob:s(),mimeType:o(s().nullish(),()=>{}),uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),ui=b([ci,di]),li=r({annotations:o(de.nullish(),()=>{}),resource:ui,_meta:o(d(s(),c()).nullish(),()=>{})}),ue=b([ii.and(r({type:l("text")})),oi.and(r({type:l("image")})),ri.and(r({type:l("audio")})),ai.and(r({type:l("resource_link")})),li.and(r({type:l("resource")}))]),hi=r({content:ue,_meta:o(d(s(),c()).nullish(),()=>{})}),pi=r({path:s(),oldText:o(s().nullish(),()=>{}),newText:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),X=s(),fi=r({terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),Gt=b([hi.and(r({type:l("content")})),pi.and(r({type:l("diff")})),fi.and(r({type:l("terminal")}))]),Ut=r({path:s(),line:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ft=r({toolCallId:Ze,kind:o(Pt.nullish(),()=>{}),status:o(Lt.nullish(),()=>{}),title:o(s().nullish(),()=>{}),name:o(s().nullish(),()=>{}),content:o(S(Gt).nullish(),()=>{}),locations:o(S(Ut).nullish(),()=>{}),rawInput:o(c().optional(),()=>{}),rawOutput:o(c().optional(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Wt=s(),zi=b([l("allow_once"),l("allow_always"),l("reject_once"),l("reject_always")]),mi=r({optionId:Wt,name:s(),kind:zi,_meta:o(d(s(),c()).nullish(),()=>{})}),Xe=r({sessionId:E,toolCall:Ft,options:T(mi),_meta:o(d(s(),c()).nullish(),()=>{})}),Bt=r({name:s(),value:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),en=r({sessionId:E,command:s(),args:o(S(s()).optional(),()=>[]),env:o(S(Bt).optional(),()=>[]),cwd:o(s().nullish(),()=>{}),outputByteLimit:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),nn=r({sessionId:E,terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),tn=r({sessionId:E,terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),sn=r({sessionId:E,terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),on=r({sessionId:E,terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),le=r({sessionId:E,toolCallId:o(Ze.nullish(),()=>{})}),he=r({requestId:$}),gi=l("object"),bi=b([l("email"),l("uri"),l("date"),l("date-time")]),$t=r({const:s(),title:s(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),rn=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),minLength:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:s().nullish(),format:bi.nullish(),default:o(s().nullish(),()=>{}),enum:T(s()).nullish(),oneOf:T($t).nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),an=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),minimum:x().nullish(),maximum:x().nullish(),default:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),cn=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),minimum:x().nullish(),maximum:x().nullish(),default:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),dn=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),default:o(v().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),un=r({enum:T(s()),_meta:o(d(s(),c()).nullish(),()=>{})}),Jt=r({anyOf:T($t),_meta:o(d(s(),c()).nullish(),()=>{})}),_i=ce(b([un.and(r({type:l("string")})),ae(r({type:s()}),"type",["string"]),Jt]),"type",["string"]),ln=r({title:o(s().nullish(),()=>{}),description:o(s().nullish(),()=>{}),minItems:x().nullish(),maxItems:x().nullish(),items:_i,default:o(S(s()).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),wi=ce(b([rn.and(r({type:l("string")})),an.and(r({type:l("number")})),cn.and(r({type:l("integer")})),dn.and(r({type:l("boolean")})),ln.and(r({type:l("array")})),ae(r({type:s()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),Si=r({type:o(gi.optional().default("object"),()=>"object"),title:o(s().nullish(),()=>{}),properties:d(s(),wi).optional().default({}),required:T(s()).nullish(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),hn=B(b([le,he]),r({requestedSchema:Si})),Vt=s(),pn=B(b([le,he]),r({elicitationId:Vt,url:xt()})),fn=ce(B(b([hn.and(r({mode:l("form")})),pn.and(r({mode:l("url")})),ae(B(b([le,he]),r({mode:s()})),"mode",["form","url"])]),r({message:s(),_meta:o(d(s(),c()).nullish(),()=>{})})),"mode",["form","url"]),Kt=s(),Ei=r({serverId:Kt,_meta:o(d(s(),c()).nullish(),()=>{})}),Ee=s(),Qt=r({connectionId:Ee,method:s(),params:d(s(),c()).nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),xi=r({connectionId:Ee,_meta:o(d(s(),c()).nullish(),()=>{})}),Yt=c(),mc=r({id:$,method:s(),params:b([Qe,Ye,Xe,en,nn,tn,sn,on,fn,Ei,Qt,xi,Yt]).nullish()}),Zt=A().gte(0).lte(65535),Ri=r({image:o(v().optional().default(!1),()=>!1),audio:o(v().optional().default(!1),()=>!1),embeddedContext:o(v().optional().default(!1),()=>!1),_meta:o(d(s(),c()).nullish(),()=>{})}),yi=r({http:o(v().optional().default(!1),()=>!1),sse:o(v().optional().default(!1),()=>!1),acp:o(v().optional().default(!1),()=>!1),_meta:o(d(s(),c()).nullish(),()=>{})}),Ti=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ci=r({_meta:o(d(s(),c()).nullish(),()=>{})}),ki=r({_meta:o(d(s(),c()).nullish(),()=>{})}),vi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ni=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ai=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ii=r({list:o(Ti.nullish(),()=>{}),delete:o(Ci.nullish(),()=>{}),additionalDirectories:o(ki.nullish(),()=>{}),fork:o(vi.nullish(),()=>{}),resume:o(Ni.nullish(),()=>{}),close:o(Ai.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Mi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),ji=r({logout:o(Mi.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Oi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Di=r({_meta:o(d(s(),c()).nullish(),()=>{})}),qi=b([l("full"),l("incremental")]),Hi=r({syncKind:qi,_meta:o(d(s(),c()).nullish(),()=>{})}),Pi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Li=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Gi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ui=r({didOpen:o(Di.nullish(),()=>{}),didChange:o(Hi.nullish(),()=>{}),didClose:o(Pi.nullish(),()=>{}),didSave:o(Li.nullish(),()=>{}),didFocus:o(Gi.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Fi=r({document:o(Ui.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Wi=r({maxCount:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Bi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),$i=r({maxCount:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ji=r({maxCount:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Vi=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Ki=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Qi=r({recentFiles:o(Wi.nullish(),()=>{}),relatedSnippets:o(Bi.nullish(),()=>{}),editHistory:o($i.nullish(),()=>{}),userActions:o(Ji.nullish(),()=>{}),openFiles:o(Vi.nullish(),()=>{}),diagnostics:o(Ki.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Yi=r({events:o(Fi.nullish(),()=>{}),context:o(Qi.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Xt=b([l("utf-16"),l("utf-32"),l("utf-8")]),Zi=r({loadSession:o(v().optional().default(!1),()=>!1),promptCapabilities:o(Ri.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:o(yi.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:o(Ii.optional().default({}),()=>({})),auth:o(ji.optional().default({}),()=>({})),providers:o(Oi.nullish(),()=>{}),nes:o(Yi.nullish(),()=>{}),positionEncoding:o(Xt.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),zn=s(),Xi=r({id:zn,name:s(),description:o(s().nullish(),()=>{}),args:o(S(s()).optional(),()=>[]),env:o(d(s(),s()).optional(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),eo=r({id:zn,name:s(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),no=b([Xi.and(r({type:l("terminal")})),eo]),es=r({name:s(),title:o(s().nullish(),()=>{}),version:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),to=r({protocolVersion:Zt,agentCapabilities:o(Zi.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:o(S(no).optional().default([]),()=>[]),agentInfo:o(es.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),so=r({_meta:o(d(s(),c()).nullish(),()=>{})}),mn=s(),gn=b([l("anthropic"),l("openai"),l("azure"),l("vertex"),l("bedrock"),s()]),io=r({apiType:gn,baseUrl:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),oo=r({providerId:mn,supported:O(S(gn),()=>[]),required:v(),current:io.nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),ro=r({providers:T(oo),_meta:o(d(s(),c()).nullish(),()=>{})}),ao=r({_meta:o(d(s(),c()).nullish(),()=>{})}),co=r({_meta:o(d(s(),c()).nullish(),()=>{})}),uo=r({_meta:o(d(s(),c()).nullish(),()=>{})}),xe=s(),lo=r({id:xe,name:s(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Re=r({currentModeId:xe,availableModes:O(S(lo),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),ns=s(),ho=b([l("mode"),l("model"),l("model_config"),l("thought_level"),s()]),bn=s(),ts=r({value:bn,name:s(),description:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),po=s(),fo=r({group:po,name:s(),options:O(S(ts),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),zo=b([T(ts),T(fo)]),mo=r({currentValue:bn,options:zo}),go=r({currentValue:v()}),ee=B(b([mo.and(r({type:l("select")})),go.and(r({type:l("boolean")}))]),r({id:ns,name:s(),description:o(s().nullish(),()=>{}),category:o(ho.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})})),bo=r({sessionId:E,modes:o(Re.nullish(),()=>{}),configOptions:o(S(ee).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),_o=r({modes:o(Re.nullish(),()=>{}),configOptions:o(S(ee).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),wo=r({sessionId:E,cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),title:o(s().nullish(),()=>{}),updatedAt:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),So=r({sessions:O(S(wo),()=>[]),nextCursor:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Eo=r({_meta:o(d(s(),c()).nullish(),()=>{})}),xo=r({sessionId:E,modes:o(Re.nullish(),()=>{}),configOptions:o(S(ee).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ro=r({modes:o(Re.nullish(),()=>{}),configOptions:o(S(ee).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),yo=r({_meta:o(d(s(),c()).nullish(),()=>{})}),To=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Co=r({configOptions:O(S(ee),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),ko=b([l("end_turn"),l("max_tokens"),l("max_turn_requests"),l("refusal"),l("cancelled")]),vo=r({totalTokens:x(),inputTokens:x(),outputTokens:x(),thoughtTokens:o(x().nullish(),()=>{}),cachedReadTokens:o(x().nullish(),()=>{}),cachedWriteTokens:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),No=r({stopReason:ko,usage:o(vo.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ao=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),ne=s(),J=r({line:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:o(d(s(),c()).nullish(),()=>{})}),te=r({start:J,end:J,_meta:o(d(s(),c()).nullish(),()=>{})}),Io=r({range:te,newText:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Mo=r({id:ne,uri:s(),edits:T(Io),cursorPosition:o(J.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),jo=r({id:ne,uri:s(),position:J,_meta:o(d(s(),c()).nullish(),()=>{})}),Oo=r({id:ne,uri:s(),position:J,newName:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Do=r({id:ne,uri:s(),search:s(),replace:s(),isRegex:v().nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),qo=b([Mo.and(r({kind:l("edit")})),jo.and(r({kind:l("jump")})),Oo.and(r({kind:l("rename")})),Do.and(r({kind:l("searchAndReplace")}))]),Ho=r({suggestions:T(qo),_meta:o(d(s(),c()).nullish(),()=>{})}),Po=r({_meta:o(d(s(),c()).nullish(),()=>{})}),ss=c(),is=c(),Lo=b([l(-32700),l(-32600),l(-32601),l(-32602),l(-32603),l(-32800),l(-32e3),l(-32002),A().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),os=r({code:Lo,message:s(),data:o(c().optional(),()=>{})}),gc=b([r({id:$,result:b([to,so,ro,ao,co,uo,bo,_o,So,Eo,xo,Ro,yo,To,Co,No,Ao,Ho,Po,ss,is])}),r({id:$,error:os})]),Go=s(),Ke=r({content:ue,messageId:o(Go.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Uo=r({toolCallId:Ze,title:s(),name:o(s().nullish(),()=>{}),kind:o(Pt.optional(),()=>{}),status:o(Lt.optional(),()=>{}),content:o(S(Gt).optional(),()=>[]),locations:o(S(Ut).optional(),()=>[]),rawInput:o(c().optional(),()=>{}),rawOutput:o(c().optional(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Fo=b([l("high"),l("medium"),l("low")]),Wo=b([l("pending"),l("in_progress"),l("completed")]),rs=r({content:s(),priority:Fo,status:Wo,_meta:o(d(s(),c()).nullish(),()=>{})}),Bo=r({entries:O(S(rs),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),ye=s(),$o=r({planId:ye,entries:O(S(rs),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),Jo=r({planId:ye,uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Vo=r({planId:ye,content:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Ko=b([$o.and(r({type:l("items")})),Jo.and(r({type:l("file")})),Vo.and(r({type:l("markdown")}))]),Qo=r({plan:Ko,_meta:o(d(s(),c()).nullish(),()=>{})}),Yo=r({planId:ye,_meta:o(d(s(),c()).nullish(),()=>{})}),Zo=r({hint:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Xo=Zo,er=r({name:s(),description:s(),input:o(Xo.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),nr=r({availableCommands:O(S(er),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),tr=r({currentModeId:xe,_meta:o(d(s(),c()).nullish(),()=>{})}),sr=r({configOptions:O(S(ee),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),ir=r({title:o(s().nullish(),()=>{}),updatedAt:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),or=r({amount:x(),currency:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),rr=r({used:x(),size:x(),cost:o(or.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),as=s(),ar=b([l("in_progress"),l("completed"),l("failed"),l("cancelled"),s()]),cr=r({compactionId:as,status:ar,summary:o(S(ue).nullish(),()=>{}),error:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),dr=r({compactionId:as,content:ue,_meta:o(d(s(),c()).nullish(),()=>{})}),ur=b([Ke.and(r({sessionUpdate:l("user_message_chunk")})),Ke.and(r({sessionUpdate:l("agent_message_chunk")})),Ke.and(r({sessionUpdate:l("agent_thought_chunk")})),Uo.and(r({sessionUpdate:l("tool_call")})),Ft.and(r({sessionUpdate:l("tool_call_update")})),Bo.and(r({sessionUpdate:l("plan")})),Qo.and(r({sessionUpdate:l("plan_update")})),Yo.and(r({sessionUpdate:l("plan_removed")})),nr.and(r({sessionUpdate:l("available_commands_update")})),tr.and(r({sessionUpdate:l("current_mode_update")})),sr.and(r({sessionUpdate:l("config_option_update")})),ir.and(r({sessionUpdate:l("session_info_update")})),rr.and(r({sessionUpdate:l("usage_update")})),cr.and(r({sessionUpdate:l("compaction_update")})),dr.and(r({sessionUpdate:l("compaction_summary_chunk")}))]),Te=r({sessionId:E,update:ur,_meta:o(d(s(),c()).nullish(),()=>{})}),_n=r({elicitationId:Vt,_meta:o(d(s(),c()).nullish(),()=>{})}),cs=r({connectionId:Ee,method:s(),params:o(d(s(),c()).nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),ds=c(),bc=r({method:s(),params:b([Te,_n,cs,ds]).nullish()}),lr=r({readTextFile:o(v().optional().default(!1),()=>!1),writeTextFile:o(v().optional().default(!1),()=>!1),_meta:o(d(s(),c()).nullish(),()=>{})}),hr=d(s(),c()),pr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),fr=r({boolean:o(pr.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),zr=r({compaction:o(hr.nullish(),()=>{}),configOptions:o(fr.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),mr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),gr=r({terminal:o(v().optional().default(!1),()=>!1),_meta:o(d(s(),c()).nullish(),()=>{})}),br=r({_meta:o(d(s(),c()).nullish(),()=>{})}),_r=r({_meta:o(d(s(),c()).nullish(),()=>{})}),wr=r({form:o(br.nullish(),()=>{}),url:o(_r.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Sr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Er=r({_meta:o(d(s(),c()).nullish(),()=>{})}),xr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Rr=r({jump:o(Sr.nullish(),()=>{}),rename:o(Er.nullish(),()=>{}),searchAndReplace:o(xr.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),yr=r({fs:o(lr.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:o(v().optional().default(!1),()=>!1),session:o(zr.nullish(),()=>{}),plan:o(mr.nullish(),()=>{}),auth:o(gr.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:o(wr.nullish(),()=>{}),nes:o(Rr.nullish(),()=>{}),positionEncodings:o(S(Xt).optional(),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),wn=r({protocolVersion:Zt,clientCapabilities:o(yr.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:o(es.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Sn=r({methodId:zn,_meta:o(d(s(),c()).nullish(),()=>{})}),En=r({_meta:o(d(s(),c()).nullish(),()=>{})}),xn=r({providerId:mn,apiType:gn,baseUrl:s(),headers:d(s(),s()).optional(),_meta:o(d(s(),c()).nullish(),()=>{})}),Rn=r({providerId:mn,_meta:o(d(s(),c()).nullish(),()=>{})}),yn=r({_meta:o(d(s(),c()).nullish(),()=>{})}),us=r({name:s(),value:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Tr=r({name:s(),url:s(),headers:T(us),_meta:o(d(s(),c()).nullish(),()=>{})}),Cr=r({name:s(),url:s(),headers:T(us),_meta:o(d(s(),c()).nullish(),()=>{})}),kr=r({name:s(),serverId:Kt,_meta:o(d(s(),c()).nullish(),()=>{})}),vr=r({name:s(),command:s(),args:T(s()),env:T(Bt),_meta:o(d(s(),c()).nullish(),()=>{})}),Ce=b([Tr.and(r({type:l("http")})),Cr.and(r({type:l("sse")})),kr.and(r({type:l("acp")})),vr]),Tn=r({cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),mcpServers:O(S(Ce),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),Cn=r({mcpServers:O(S(Ce),()=>[]),cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),kn=r({cwd:s().nullish(),cursor:s().nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),vn=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),Nn=r({sessionId:E,cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),mcpServers:o(S(Ce).optional(),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),An=r({sessionId:E,cwd:s(),additionalDirectories:o(S(s()).optional(),()=>[]),mcpServers:o(S(Ce).optional(),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),In=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),Mn=r({sessionId:E,modeId:xe,_meta:o(d(s(),c()).nullish(),()=>{})}),jn=B(b([r({value:v(),type:l("boolean")}),r({value:bn})]),r({sessionId:E,configId:ns,_meta:o(d(s(),c()).nullish(),()=>{})})),On=r({sessionId:E,prompt:T(ue),_meta:o(d(s(),c()).nullish(),()=>{})}),Nr=r({uri:s(),name:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Ar=r({name:s(),owner:s(),remoteUrl:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Dn=r({workspaceUri:o(s().nullish(),()=>{}),workspaceFolders:T(Nr).nullish(),repository:o(Ar.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Ir=b([l("automatic"),l("diagnostic"),l("manual")]),Mr=r({uri:s(),languageId:s(),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),jr=r({startLine:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Or=r({uri:s(),excerpts:T(jr),_meta:o(d(s(),c()).nullish(),()=>{})}),Dr=r({uri:s(),diff:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),qr=r({action:s(),uri:s(),position:J,timestampMs:x(),_meta:o(d(s(),c()).nullish(),()=>{})}),Hr=r({uri:s(),languageId:s(),visibleRange:o(te.nullish(),()=>{}),lastFocusedMs:o(x().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Pr=b([l("error"),l("warning"),l("information"),l("hint")]),Lr=r({uri:s(),range:te,severity:Pr,message:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Gr=r({recentFiles:T(Mr).nullish(),relatedSnippets:T(Or).nullish(),editHistory:T(Dr).nullish(),userActions:T(qr).nullish(),openFiles:T(Hr).nullish(),diagnostics:T(Lr).nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),qn=r({sessionId:E,uri:s(),version:x(),position:J,selection:te.nullish(),triggerKind:Ir,context:Gr.nullish(),_meta:o(d(s(),c()).nullish(),()=>{})}),Hn=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),_c=r({id:$,method:s(),params:b([wn,Sn,En,xn,Rn,yn,Tn,Cn,kn,vn,Nn,An,In,Mn,jn,On,Dn,qn,Hn,Qt,Yt]).nullish()}),Ur=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Fr=r({content:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Wr=r({optionId:Wt,_meta:o(d(s(),c()).nullish(),()=>{})}),Br=b([r({outcome:l("cancelled")}),Wr.and(r({outcome:l("selected")}))]),$r=r({outcome:Br,_meta:o(d(s(),c()).nullish(),()=>{})}),Jr=r({terminalId:X,_meta:o(d(s(),c()).nullish(),()=>{})}),Vr=r({exitCode:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Kr=r({output:s(),truncated:v(),exitStatus:o(Vr.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Qr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Yr=r({exitCode:o(A().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:o(s().nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Zr=r({_meta:o(d(s(),c()).nullish(),()=>{})}),Xr=b([s(),x(),x(),v(),T(s())]),Pn=r({content:d(s(),Xr).nullish()}),ea=ce(B(b([Pn.and(r({action:l("accept")})),r({action:l("decline")}),r({action:l("cancel")}),ae(r({action:s()}),"action",["accept","cancel","decline"])]),r({_meta:o(d(s(),c()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),na=r({connectionId:Ee,_meta:o(d(s(),c()).nullish(),()=>{})}),ta=r({_meta:o(d(s(),c()).nullish(),()=>{})}),wc=b([r({id:$,result:b([Ur,Fr,$r,Jr,Kr,Qr,Yr,Zr,ea,na,ta,is,ss])}),r({id:$,error:os})]),Ln=r({sessionId:E,_meta:o(d(s(),c()).nullish(),()=>{})}),Gn=r({sessionId:E,uri:s(),languageId:s(),version:x(),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),sa=r({range:te.nullish(),text:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Un=r({sessionId:E,uri:s(),version:x(),contentChanges:O(S(sa),()=>[]),_meta:o(d(s(),c()).nullish(),()=>{})}),Fn=r({sessionId:E,uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Wn=r({sessionId:E,uri:s(),_meta:o(d(s(),c()).nullish(),()=>{})}),Bn=r({sessionId:E,uri:s(),version:x(),position:J,visibleRange:te,_meta:o(d(s(),c()).nullish(),()=>{})}),$n=r({sessionId:E,id:ne,_meta:o(d(s(),c()).nullish(),()=>{})}),ia=b([l("rejected"),l("ignored"),l("replaced"),l("cancelled")]),Jn=r({sessionId:E,id:ne,reason:o(ia.nullish(),()=>{}),_meta:o(d(s(),c()).nullish(),()=>{})}),Sc=r({method:s(),params:b([Ln,Gn,Un,Fn,Wn,Bn,$n,Jn,cs,ds]).nullish()}),Ec=r({requestId:$,_meta:o(d(s(),c()).nullish(),()=>{})});var hs="$/cancel_request";function P(t){return Yn(t)&&"id"in t&&typeof t.method=="string"&&Zn(t.id)}function V(t){if(!Yn(t)||"method"in t||!("id"in t)||!Zn(t.id))return!1;let e=Object.hasOwn(t,"result"),n=Object.hasOwn(t,"error");return e===n?!1:!n||aa(t.error)}function F(t){return Yn(t)&&!("id"in t)&&typeof t.method=="string"}function I(t){return typeof t=="object"&&t!==null}function Yn(t){return I(t)&&t.jsonrpc==="2.0"}function Zn(t){return t===null||typeof t=="string"||typeof t=="number"&&Number.isFinite(t)}function pe(t){return I(t)&&!("method"in t)&&("id"in t||"result"in t||"error"in t)}function oa(t){let e=!1,n=!1,i=!1,a=!1;for(let u of t)e||=P(u)||F(u),n||=V(u),I(u)&&(i||="method"in u,a||="result"in u||"error"in u);return e?!1:n?!0:a&&!i}function ra(t){if(!(!I(t)||!Zn(t.requestId)))return t.requestId}function aa(t){return I(t)&&typeof t.code=="number"&&Number.isInteger(t.code)&&typeof t.message=="string"}var D={yes(){return{handled:!0}},no(t,e=!1){return{handled:!1,message:t,retry:e}}};function Q(t){let e=Promise.reject(t);return e.catch(()=>{}),e}function ca(t){if(t instanceof Error||typeof t=="object"&&t!=null&&"message"in t&&typeof t.message=="string")return t.message}function da(t){return typeof t=="object"&&t!==null&&"name"in t&&t.name==="ZodError"&&"issues"in t&&Array.isArray(t.issues)&&"format"in t&&typeof t.format=="function"}function ps(t){if(t instanceof w)return t.toResult();if(da(t))return w.invalidParams(t.format()).toResult();let e=ca(t);try{return w.internalError(e?JSON.parse(e):{}).toResult()}catch{return w.internalError({details:e}).toResult()}}function ua(t){return t instanceof w&&t.code===-32800?t:w.requestCancelled(t)}function la(t,e){let n=ha(t,e);return n?n.toResult():ps(t)}function ha(t,e){if(!(!e.aborted||!pa(t)))return ua(e.reason)}function pa(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.name==="AbortError"||e.code==="ABORT_ERR"}var Vn=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,n,i=new AbortController().signal,a){this.id=e,this.sendResult=n,this.signal=i,this.finishRequest=a}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let n=e instanceof w?e.toErrorResponse():e;return this.respondWithResult({error:n})}respondWithResult(e){return this.didRespond?Q(new Error("JSON-RPC request already responded")):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},fa=new WeakMap;var se=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Kn=class{connection;constructor(e){this.connection=e}sendRequest(e,n,i,a){return this.connection.sendRequest(e,n,i,a)}sendNotification(e,n){return this.connection.sendNotification(e,n)}sendBatch(e){return this.connection.sendBatch(e)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ie=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Kn(this);receiveReader;allowBatches=!0;constructor(e,n,i,a){if(typeof e=="function"){let f=e,g=n,m=i;this.initialize(m,[...a?.handlers??[],this.legacyHandler(f,g)],a);return}let u=e,p=n,z=i;this.initialize(u,[...z?.handlers??[],...p],z)}static builder(){return new Qn}runUntil(e){let n=!1,i=Promise.resolve().then(()=>e(this.context)).finally(()=>{n=!0}),a=this.closed.then(()=>{if(n)return new Promise(()=>{});throw this.closedReason()});return Promise.race([i,a]).finally(()=>{n=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let n of this.retryQueue.splice(0))this.processIncomingMessage(n).catch(i=>this.close(i));return new se(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,n,i,a={}){if(this.abortController.signal.aborted)return Q(this.closedReason());let u=this.prepareRequest(e,n,i,a);return this.sendWireMessage(u.message).catch(()=>{}),a.cancellationSignal?.aborted&&u.cancel(),u.response}sendBatch(e){if(this.abortController.signal.aborted)return Q(this.closedReason());if(!this.allowBatches)return Q(new TypeError("JSON-RPC batches are not supported on this connection"));if(e.length===0)return Q(new TypeError("JSON-RPC batch must contain at least one entry"));let n=[],i=[],a=[];for(let f of e){if(f.kind==="notification"){n.push({jsonrpc:"2.0",method:f.method,params:f.params}),a.push(Promise.resolve(void 0));continue}let g=this.prepareRequest(f.method,f.params,f.mapResponse,f.options);n.push(g.message),a.push(g.response),i.push({signal:f.options?.cancellationSignal,cancel:g.cancel})}let u=n,p=this.sendWireMessage(u);for(let f of i)f.signal?.aborted&&f.cancel();let z=Promise.all([p,...a]).then(([,...f])=>f);return z.catch(()=>{}),z}sendCancelRequest(e){return this.sendNotification(hs,{requestId:e})}sendNotification(e,n){return this.abortController.signal.aborted?Q(this.closedReason()):this.sendWireMessage({jsonrpc:"2.0",method:e,params:n})}prepareRequest(e,n,i,a={}){let u=this.nextRequestId++,p=()=>{},z=new Promise((f,g)=>{let m={resolve:y=>{try{f(i?i(y):y)}catch(C){g(C)}},reject:g};p=()=>{m.cancellationSent||(m.cancellationSent=!0,m.cleanup?.(),this.sendCancelRequest(u).catch(()=>{}))},a.cancellationSignal?.addEventListener("abort",p,{once:!0}),m.cleanup=()=>{a.cancellationSignal?.removeEventListener("abort",p)},this.pendingResponses.set(u,m)});return z.catch(()=>{}),{message:{jsonrpc:"2.0",id:u,method:e,params:n},response:z,cancel:()=>p()}}close(e){if(this.abortController.signal.aborted)return;let n=e??new Error("ACP connection closed");this.abortController.abort(n);for(let i of this.pendingResponses.values())i.cleanup?.(),i.reject(n);this.pendingResponses.clear();for(let i of this.incomingRequests.values())i.abort(n);this.incomingRequests.clear(),this.receiveReader?.cancel(n).catch(()=>{})}initialize(e,n,i){this.stream=e,this.staticHandlers=n,this.allowBatches=i?.allowBatches??!0,this.closedPromise=new Promise(a=>{this.abortController.signal.addEventListener("abort",()=>a())}),this.receive()}legacyHandler(e,n){return{handleMessage:async(i,a)=>{if(i.kind==="request"){let u=await e(i.method,i.params,a);await i.responder.respond(u)}else await n(i.method,i.params,a);return D.yes()}}}async receive(){let e;try{let n=this.stream.readable.getReader();this.receiveReader=n;try{for(;!this.abortController.signal.aborted;){let{value:i,done:a}=await n.read();if(this.abortController.signal.aborted||a)break;this.receiveWireMessage(i)}}finally{this.receiveReader===n&&(this.receiveReader=void 0),n.releaseLock()}}catch(n){e=n}finally{this.close(e)}}receiveWireMessage(e){if(Array.isArray(e)){if(!this.allowBatches){this.close(new TypeError("JSON-RPC batches are not supported on this connection"));return}this.receiveBatch(e);return}if(!P(e)&&!F(e)&&!pe(e)){this.sendWireMessage(L(w.invalidRequest(e))).catch(()=>{});return}this.receiveMessage(e)}receiveBatch(e){if(e.length===0){this.sendWireMessage(L(w.invalidRequest(e))).catch(()=>{});return}let n=oa(e),a=n?0:e.reduce((m,y)=>m+(F(y)?0:1),0),u=e.reduce((m,y)=>m+(F(y)?1:0),0),p=!1,z=[],f=async()=>{p||a!==0||u!==0||z.length===0||(p=!0,await this.sendWireMessage(z))},g=async m=>{z.push(m),a-=1,await f()};for(let m of e){if(n){pe(m)&&this.receiveMessage(m);continue}if(!P(m)&&!F(m)){g(L(w.invalidRequest(m))).catch(()=>{});continue}let y=this.receiveMessage(m,P(m)?g:void 0,e.length);F(m)&&y.finally(()=>{u-=1,f().catch(C=>this.close(C))})}}receiveMessage(e,n,i){return this.abortController.signal.aborted?Promise.resolve():I(e)?"method"in e?("id"in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e,n,i)).catch(a=>this.close(a))):("id"in e?this.handleResponse(e):console.error("Invalid message",{message:e}),Promise.resolve()):(console.error("Invalid message",{message:e}),Promise.resolve())}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let n=e,i=!1;try{for(let a of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let u=await a.handleMessage(n,this.context)??{handled:!0};if(u.handled)return;n=u.message??n,i=i||!!u.retry}i?this.retryQueue.push(n):n.kind==="request"&&await n.responder.respondWithError(w.methodNotFound(n.method))}catch(a){if(this.abortController.signal.aborted)return;if(n.kind==="request"&&!n.responder.responded)await n.responder.respondWithResult(la(a,n.responder.signal));else{let u=ps(a);"error"in u&&console.error("Error handling notification",e.raw,u.error)}}}toIncomingMessage(e,n,i){if("id"in e){let a=new AbortController;this.incomingRequests.set(e.id,a);let u=()=>{this.incomingRequests.get(e.id)===a&&this.incomingRequests.delete(e.id)},p=new Vn(e.id,z=>{let f={jsonrpc:"2.0",id:e.id,...z};return n?n(f):this.sendWireMessage(f)},a.signal,u);return i!==void 0&&fa.set(p,i),{kind:"request",method:e.method,params:e.params,raw:e,signal:a.signal,responder:p}}return{kind:"notification",method:e.method,params:e.params,raw:e}}handleResponse(e){let n=this.pendingResponses.get(e.id);if(n)if(this.pendingResponses.delete(e.id),n.cleanup?.(),!V(e))n.reject(w.invalidRequest(e));else if("result"in e)n.resolve(e.result);else{let{code:i,message:a,data:u}=e.error;n.reject(new w(i,a,u))}else console.error("Got response to unknown request",e.id)}handleProtocolNotification(e){if(e.method!==hs)return;let n=ra(e.params);if(n===void 0)return;let i=this.incomingRequests.get(n);!i||i.signal.aborted||i.abort(w.requestCancelled({requestId:n}))}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendWireMessage(e){return this.abortController.signal.aborted?Q(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let n=this.stream.writable.getWriter();try{await n.write(e)}finally{n.releaseLock()}}).catch(n=>{throw this.close(n),n}),this.writeQueue)}},Qn=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(n,i)=>await e(n,i)??D.no(n),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(e,n,i){return this.withHandler({handleMessage:async(a,u)=>{if(a.kind!=="request"||a.method!==e)return D.no(a);let p=n(a.params);return await i(p,a.responder,u)??D.yes()},describe:()=>`${this.connectionName??"request"}:${e}`})}onReceiveNotification(e,n,i){return this.withHandler({handleMessage:async(a,u)=>{if(a.kind!=="notification"||a.method!==e)return D.no(a);let p=n(a.params);return await i(p,u)??D.yes()},describe:()=>`${this.connectionName??"notification"}:${e}`})}connect(e,n){return new ie(e,this.handlers,n)}connectWith(e,n,i){return this.connect(e,i).runUntil(n)}},w=class t extends Error{code;data;constructor(e,n,i){super(n),this.code=e,this.name="RequestError",this.data=i}static parseError(e,n){return new t(-32700,`Parse error${n?`: ${n}`:""}`,e)}static invalidRequest(e,n){return new t(-32600,`Invalid request${n?`: ${n}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,n){return new t(-32602,`Invalid params${n?`: ${n}`:""}`,e)}static internalError(e,n){return new t(-32603,`Internal error${n?`: ${n}`:""}`,e)}static requestCancelled(e,n){return new t(-32800,`Request cancelled${n?`: ${n}`:""}`,e)}static authRequired(e,n){return new t(-32e3,`Authentication required${n?`: ${n}`:""}`,e)}static resourceNotFound(e){return new t(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};function L(t){return{jsonrpc:"2.0",id:null,error:t.toErrorResponse()}}var fe=class{#e=[];push(e){let n=[],i=0,a=e.indexOf(10,i);for(;a!==-1;)n.push(this.#n(e.subarray(i,a))),i=a+1,a=e.indexOf(10,i);return i<e.byteLength&&this.#e.push(i===0?e:new Uint8Array(e.subarray(i))),n}flush(){if(this.#e.length!==0)return this.#n(new Uint8Array(0))}#n(e){if(this.#e.length===0)return e;let n=e.byteLength;for(let u of this.#e)n+=u.byteLength;let i=new Uint8Array(n),a=0;for(let u of this.#e)i.set(u,a),a+=u.byteLength;return i.set(e,a),this.#e=[],i}};function fs(t,e){let n=new TextEncoder,i=new TextDecoder,a=!1,u,p=Promise.resolve(),z=m=>{let y=JSON.stringify(m)+`
|
|
5
|
+
`,C=p.then(async()=>{let k=t.getWriter();try{await k.write(n.encode(y))}finally{k.releaseLock()}});return p=C.catch(()=>{}),C},f=new ReadableStream({async start(m){let y=new fe,C=async M=>{let U=i.decode(M).trim();if(!U)return;let H;try{H=JSON.parse(U)}catch{await z(L(w.parseError()));return}I(H)||Array.isArray(H)?m.enqueue(H):await z(L(w.invalidRequest(H)))},k=e.getReader();u=k;try{for(;;){let{value:U,done:H}=await k.read();if(a)return;if(H)break;if(U){for(let We of y.push(U))if(await C(We),a)return}}if(a)return;let M=y.flush();M&&await C(M)}catch(M){if(a)return;m.error(M);return}finally{u===k&&(u=void 0),k.releaseLock()}a||m.close()},cancel(m){return a=!0,u?.cancel(m)}}),g=new WritableStream({write(m){return z(m)}});return{readable:f,writable:g}}var kc=hn.and(r({mode:l("form")})).and(r({message:s()})),vc=pn.and(r({mode:l("url")})).and(r({message:s()})),Nc=b([le,he]).and(r({message:s()})),Ac=rn.and(r({type:l("string")})),Ic=an.and(r({type:l("number")})),Mc=cn.and(r({type:l("integer")})),jc=dn.and(r({type:l("boolean")})),Oc=ln.and(r({type:l("array")})),Dc=un.and(r({type:l("string")}));var qc=Pn.and(r({action:l("accept")})),Hc=r({action:l("decline")}),Pc=r({action:l("cancel")});function bs(t,e){return fs(t,e)}function j(t){return t??{}}function _s(t){return typeof t=="object"&&t!==null&&"readable"in t&&"writable"in t}function ws(){let t=new TransformStream,e=new TransformStream;return[{readable:e.readable,writable:t.writable},{readable:t.readable,writable:e.writable}]}var q={agent:{initialize:h.initialize,authenticate:h.authenticate,logout:h.logout,providers:{list:h.providers_list,set:h.providers_set,disable:h.providers_disable},session:{new:h.session_new,load:h.session_load,list:h.session_list,delete:h.session_delete,fork:h.session_fork,resume:h.session_resume,close:h.session_close,setMode:h.session_set_mode,setConfigOption:h.session_set_config_option,prompt:h.session_prompt,cancel:h.session_cancel},nes:{start:h.nes_start,suggest:h.nes_suggest,accept:h.nes_accept,reject:h.nes_reject,close:h.nes_close},document:{didOpen:h.document_did_open,didChange:h.document_did_change,didClose:h.document_did_close,didSave:h.document_did_save,didFocus:h.document_did_focus}},client:{session:{requestPermission:_.session_request_permission,update:_.session_update},fs:{writeTextFile:_.fs_write_text_file,readTextFile:_.fs_read_text_file},terminal:{create:_.terminal_create,output:_.terminal_output,release:_.terminal_release,waitForExit:_.terminal_wait_for_exit,kill:_.terminal_kill},elicitation:{create:_.elicitation_create,complete:_.elicitation_complete}},protocol:{cancelRequest:Je.cancel_request}},Ss=Symbol("startActiveSession"),Ne=class{cx;currentRequestId;constructor(e,n){this.cx=e,this.currentRequestId=n}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,n,i,a){return this.cx.sendRequest(e,n,i,a)}sendNotification(e,n){return this.cx.sendNotification(e,n)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},ze=class t extends Ne{constructor(e,n){super(e,n)}static create(e,n){return new t(e,n)}request(e,n,i){let a=rt[e];return this.sendRequest(e,n,a?.mapResponse,i)}notify(e,n){return this.sendNotification(e,n)}},me=class t extends Ne{constructor(e,n){super(e,n)}static create(e,n){return new t(e,n)}[Ss](e,n){return this.sendRequest(h.session_new,e,i=>this.attachSession(i),n)}buildSession(e){return typeof e=="string"?Ie.create(this,{cwd:e,mcpServers:[]}):Ie.create(this,e)}attachSession(e){let n=new nt,i=this.connectionContext.signal,a=()=>{n.fail(i.reason??new Error("ACP connection closed"))};i.aborted?a():i.addEventListener("abort",a);let u=ks(this.connectionContext).attach(e,n),p=new se(()=>{i.removeEventListener("abort",a)});return tt.create(this,e,n,[u,p])}request(e,n,i){let a=Cs[e];return this.sendRequest(e,n,a?.mapResponse,i)}notify(e,n){return this.sendNotification(e,n)}},Ae=class{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}},Xn=class extends Ae{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,n=[]){super(e),this.connectHandlers=n,this.client=ze.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Oe(this,this.connectHandlers))}},et=class extends Ae{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,n=[]){super(e),this.connectHandlers=n,this.agent=me.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Oe(this,this.connectHandlers))}};function Es(t,e=[]){return new Xn(t,e)}function xs(t,e=[]){return new et(t,e)}var nt=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let n=this.waiters.shift();n?n.resolve(e):this.values.push({kind:"value",value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(let n of this.waiters.splice(0))n.reject(e);return}this.values.push({kind:"error",error:e})}}clearErrors(){this.values=this.values.filter(e=>e.kind==="value")}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(let n of this.waiters.splice(0))n.reject(e)}}next(){if(this.values.length>0){let e=this.values.shift();return e.kind==="error"?Promise.reject(e.error):Promise.resolve(e.value)}return this.failed?Promise.reject(this.failure):new Promise((e,n)=>{this.waiters.push({resolve:e,reject:n})})}};function zs(t){return{...t,additionalDirectories:t.additionalDirectories?[...t.additionalDirectories]:void 0,mcpServers:[...t.mcpServers]}}var Ie=class t{cx;request;constructor(e,n){this.cx=e,this.request=zs(n)}static create(e,n){return new t(e,n)}toRequest(){return zs(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[Ss](this.toRequest(),e)}async withSession(e){let n=await this.start();try{return await e(n)}finally{n.dispose()}}},tt=class t{cx;sessionResponse;updates;registrations;constructor(e,n,i,a){this.cx=e,this.sessionResponse=n,this.updates=i,this.registrations=a}static create(e,n,i,a){return new t(e,n,i,a)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,n){this.updates.clearErrors();let i=this.cx.request(h.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},n);return i.then(a=>{this.updates.enqueue({kind:"stop",response:a,stopReason:a.stopReason})},a=>{this.updates.reject(a)}),i}nextUpdate(){return this.updates.next()}async readText(){let e="";for(;;){let n=await this.nextUpdate();if(n.kind==="stop")return e;let{update:i}=n;i.sessionUpdate==="agent_message_chunk"&&i.content.type==="text"&&(e+=i.content.text)}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:[e]}};function Rs(t,e){return t?typeof t=="function"?t(e):t.parse(e):e}function R(t,e,n){return{method:t,params:e,mapResponse:n}}function G(t,e){return{method:t,params:e}}function ys(t,e,n,i){t.onReceiveRequest(e.method,a=>Rs(e.params,a),async(a,u,p)=>{let z=await i(n(a,p,u.signal,u.id));await u.respond(e.mapResponse?e.mapResponse(z):z)})}function Ts(t,e,n,i){t.onReceiveNotification(e.method,a=>Rs(e.params,a),(a,u)=>i(n(a,u,u.signal)))}function je(t){let e={};for(let n of Object.values(t))e[n.method]=n;return e}var za={initialize:R(h.initialize,wn),newSession:R(h.session_new,Tn),loadSession:R(h.session_load,Cn,j),unstable_forkSession:R(h.session_fork,Nn),listSessions:R(h.session_list,kn),deleteSession:R(h.session_delete,vn,j),resumeSession:R(h.session_resume,An),closeSession:R(h.session_close,In,j),setSessionMode:R(h.session_set_mode,Mn,j),setSessionConfigOption:R(h.session_set_config_option,jn),authenticate:R(h.authenticate,Sn,j),unstable_listProviders:R(h.providers_list,En),unstable_setProvider:R(h.providers_set,xn,j),unstable_disableProvider:R(h.providers_disable,Rn,j),logout:R(h.logout,yn,j),prompt:R(h.session_prompt,On),unstable_startNes:R(h.nes_start,Dn),unstable_suggestNes:R(h.nes_suggest,qn),unstable_closeNes:R(h.nes_close,Hn,j)},ma={cancel:G(h.session_cancel,Ln),unstable_didOpenDocument:G(h.document_did_open,Gn),unstable_didChangeDocument:G(h.document_did_change,Un),unstable_didCloseDocument:G(h.document_did_close,Fn),unstable_didSaveDocument:G(h.document_did_save,Wn),unstable_didFocusDocument:G(h.document_did_focus,Bn),unstable_acceptNes:G(h.nes_accept,$n),unstable_rejectNes:G(h.nes_reject,Jn)},ga={requestPermission:R(_.session_request_permission,Xe),writeTextFile:R(_.fs_write_text_file,Qe,j),readTextFile:R(_.fs_read_text_file,Ye),createTerminal:R(_.terminal_create,en),terminalOutput:R(_.terminal_output,nn),releaseTerminal:R(_.terminal_release,tn,j),waitForTerminalExit:R(_.terminal_wait_for_exit,sn),killTerminal:R(_.terminal_kill,on,j),createElicitation:R(_.elicitation_create,fn)},ba={sessionUpdate:G(_.session_update,Te),completeElicitation:G(_.elicitation_complete,_n)},Cs=je(za),_a=je(ma),rt=je(ga),wa=je(ba);function Sa(t,e,n,i){return{params:t,requestId:i,signal:n,client:e}}function Ea(t,e,n){return{params:t,signal:n,client:e}}function xa(t,e,n,i){return{params:t,requestId:i,signal:n,agent:e}}function Ra(t,e,n){return{params:t,signal:n,agent:e}}var st=class{activeSessions=new Map;handleMessage(e){if(e.kind!=="notification"||e.method!==_.session_update)return D.no(e);let n=Te.parse(e.params),i={kind:"session_update",notification:n,update:n.update},a=this.activeSessions.get(n.sessionId);if(a&&a.size>0)for(let u of a)u.enqueue(i);return D.no(e)}attach(e,n){let i=this.activeSessions.get(e.sessionId)??new Set;return i.add(n),this.activeSessions.set(e.sessionId,i),new se(()=>{i.delete(n),i.size===0&&this.activeSessions.delete(e.sessionId)})}},ms=new WeakMap;function ks(t){let e=ms.get(t);return e||(e=new st,ms.set(t,e)),e}function Oe(t,e){for(let n of e){let i;try{i=n(t)}catch(a){throw t.close(a),a}Promise.resolve(i).catch(a=>{t.close(a)})}}var Y=Symbol("appBuilder"),ke=Symbol("runAgentConnectHandlers"),ve=Symbol("runClientConnectHandlers"),ge={allowBatches:!1};function at(t){return new it(t)}var it=class{builder=ie.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name)}[Y](){return this.builder}[ke](e){Oe(e,this.connectHandlers)}connect(e,n={}){return this.connectConnection(e,n).connection}connectWith(e,n){let{rawConnection:i,connection:a}=this.connectConnection(e);return i.runUntil(()=>n(a.client))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,n,i){if(i)return this.request({method:e,params:n},i);let a=Cs[e];if(!a)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(a,n)}onNotification(e,n,i){if(i)return this.notification({method:e,params:n},i);let a=_a[e];if(!a)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(a,n)}request(e,n){return ys(this.builder,e,(i,a,u,p)=>Sa(i,ze.create(a,p),u,p),n),this}notification(e,n){return Ts(this.builder,e,(i,a,u)=>Ea(i,ze.create(a),u),n),this}connectConnection(e,n={}){if(_s(e)){let f=this.openStreamConnection(e);return n.deferConnectHandlers||this[ke](f.connection),f}let[i,a]=ws(),u=e[Y]().connect(a,ge),p=xs(u),z=this.openStreamConnection(i);z.rawConnection.closed.then(()=>p.close()),u.closed.then(()=>z.connection.close());try{e[ve](p),this[ke](z.connection)}catch(f){throw p.close(f),z.connection.close(f),f}return z}openStreamConnection(e){let n=this.builder.connect(e,ge);return{rawConnection:n,connection:Es(n,this.connectHandlers)}}};var gs=class{builder=ie.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(n,i)=>ks(i).handleMessage(n),describe:()=>"client-session-update-router"})}[Y](){return this.builder}[ve](e){Oe(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,n){let{rawConnection:i,connection:a}=this.connectConnection(e);return i.runUntil(()=>n(a.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,n,i){if(i)return this.request({method:e,params:n},i);let a=rt[e];if(!a)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(a,n)}onNotification(e,n,i){if(i)return this.notification({method:e,params:n},i);let a=wa[e];if(!a)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(a,n)}request(e,n){return ys(this.builder,e,(i,a,u,p)=>xa(i,me.create(a,p),u,p),n),this}notification(e,n){return Ts(this.builder,e,(i,a,u)=>Ra(i,me.create(a),u),n),this}connectConnection(e){if(_s(e)){let z=this.openStreamConnection(e);return this[ve](z.connection),z}let[n,i]=ws(),a=e[Y]().connect(i,ge),u=Es(a),p=this.openStreamConnection(n);p.rawConnection.closed.then(()=>u.close()),a.closed.then(()=>p.connection.close());try{e[ke](u),this[ve](p.connection)}catch(z){throw u.close(z),p.connection.close(z),z}return p}openStreamConnection(e){let n=this.builder.connect(e,ge);return{rawConnection:n,connection:xs(n,this.connectHandlers)}}},ya=new Set([h.initialize,h.authenticate,h.providers_list,h.providers_set,h.providers_disable,h.session_new,h.session_load,h.session_set_mode,h.session_set_config_option,h.session_prompt,h.session_list,h.session_delete,h.session_fork,h.session_resume,h.session_close,h.logout,h.nes_start,h.nes_suggest,h.nes_close]),Ta=new Set([h.session_cancel,h.nes_accept,h.nes_reject,h.document_did_open,h.document_did_change,h.document_did_close,h.document_did_save,h.document_did_focus]),Jc=new Set([_.session_request_permission,_.fs_write_text_file,_.fs_read_text_file,_.terminal_create,_.terminal_output,_.terminal_release,_.terminal_wait_for_exit,_.terminal_kill,_.elicitation_create]),Vc=new Set([_.session_update,_.elicitation_complete]);function Ca(t){let e=at().onRequest(h.initialize,n=>t.initialize(n.params)).onRequest(h.session_new,n=>t.newSession(n.params)).onRequest(h.authenticate,async n=>await t.authenticate(n.params)??{}).onRequest(h.session_prompt,n=>t.prompt(n.params)).onNotification(h.session_cancel,n=>t.cancel(n.params));return t.loadSession&&e.onRequest(h.session_load,n=>t.loadSession(n.params)),t.listSessions&&e.onRequest(h.session_list,n=>t.listSessions(n.params)),t.deleteSession&&e.onRequest(h.session_delete,async n=>await t.deleteSession(n.params)??{}),t.unstable_forkSession&&e.onRequest(h.session_fork,n=>t.unstable_forkSession(n.params)),t.resumeSession&&e.onRequest(h.session_resume,n=>t.resumeSession(n.params)),t.closeSession&&e.onRequest(h.session_close,async n=>await t.closeSession(n.params)??{}),t.setSessionMode&&e.onRequest(h.session_set_mode,async n=>await t.setSessionMode(n.params)??{}),t.setSessionConfigOption&&e.onRequest(h.session_set_config_option,n=>t.setSessionConfigOption(n.params)),t.unstable_listProviders&&e.onRequest(h.providers_list,n=>t.unstable_listProviders(n.params)),t.unstable_setProvider&&e.onRequest(h.providers_set,async n=>await t.unstable_setProvider(n.params)??{}),t.unstable_disableProvider&&e.onRequest(h.providers_disable,async n=>await t.unstable_disableProvider(n.params)??{}),t.logout&&e.onRequest(h.logout,async n=>await t.logout(n.params)??{}),t.unstable_startNes&&e.onRequest(h.nes_start,n=>t.unstable_startNes(n.params)),t.unstable_suggestNes&&e.onRequest(h.nes_suggest,n=>t.unstable_suggestNes(n.params)),t.unstable_closeNes&&e.onRequest(h.nes_close,async n=>await t.unstable_closeNes(n.params)??{}),t.unstable_didOpenDocument&&e.onNotification(h.document_did_open,n=>t.unstable_didOpenDocument(n.params)),t.unstable_didChangeDocument&&e.onNotification(h.document_did_change,n=>t.unstable_didChangeDocument(n.params)),t.unstable_didCloseDocument&&e.onNotification(h.document_did_close,n=>t.unstable_didCloseDocument(n.params)),t.unstable_didSaveDocument&&e.onNotification(h.document_did_save,n=>t.unstable_didSaveDocument(n.params)),t.unstable_didFocusDocument&&e.onNotification(h.document_did_focus,n=>t.unstable_didFocusDocument(n.params)),t.unstable_acceptNes&&e.onNotification(h.nes_accept,n=>t.unstable_acceptNes(n.params)),t.unstable_rejectNes&&e.onNotification(h.nes_reject,n=>t.unstable_rejectNes(n.params)),t.extMethod&&e[Y]().withHandler({handleMessage:async n=>n.kind!=="request"||ya.has(n.method)?D.no(n):(await n.responder.respond(await t.extMethod(n.method,n.params)),D.yes()),describe:()=>"legacy-agent-extension-request"}),t.extNotification&&e[Y]().withHandler({handleMessage:async n=>n.kind!=="notification"||Ta.has(n.method)?D.no(n):(await t.extNotification(n.method,n.params),D.yes()),describe:()=>"legacy-agent-extension-notification"}),e}var Me=class{connection;constructor(e,n){this.connection=Ca(e(this))[Y]().connect(n,ge)}sessionUpdate(e){return this.connection.sendNotification(_.session_update,e)}requestPermission(e){return this.connection.sendRequest(_.session_request_permission,e)}readTextFile(e){return this.connection.sendRequest(_.fs_read_text_file,e)}writeTextFile(e){return this.connection.sendRequest(_.fs_write_text_file,e,j)}createTerminal(e){return this.connection.sendRequest(_.terminal_create,e,n=>ot.create(n.terminalId,e.sessionId,this.connection))}createElicitation(e){return this.connection.sendRequest(_.elicitation_create,e)}completeElicitation(e){return this.connection.sendNotification(_.elicitation_complete,e)}request(e,n,i){let a=rt[e];return this.connection.sendRequest(e,n,a?.mapResponse,i)}notify(e,n){return this.connection.sendNotification(e,n)}extMethod(e,n){return this.request(e,n)}extNotification(e,n){return this.notify(e,n)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ot=class t{id;sessionId;connection;constructor(e,n,i){this.id=e,this.sessionId=n,this.connection=i}static create(e,n,i){return new t(e,n,i)}currentOutput(){return this.connection.sendRequest(_.terminal_output,{sessionId:this.sessionId,terminalId:this.id})}waitForExit(){return this.connection.sendRequest(_.terminal_wait_for_exit,{sessionId:this.sessionId,terminalId:this.id})}kill(){return this.connection.sendRequest(_.terminal_kill,{sessionId:this.sessionId,terminalId:this.id},j)}release(){return this.connection.sendRequest(_.terminal_release,{sessionId:this.sessionId,terminalId:this.id},j)}async[Symbol.asyncDispose](){await this.release()}};var js={};Se(js,{SwiftyAcpAgent:()=>He,createSwiftyAcpApp:()=>be});import{existsSync as Aa}from"fs";import{isAbsolute as Ia}from"path";var As={};Se(As,{addUsage:()=>ut,agentEventToUpdate:()=>dt,emptyUsage:()=>lt,historyNotifications:()=>pt,promptToText:()=>ct,stopReason:()=>ht,toolKind:()=>De,toolLocations:()=>qe});import{isAbsolute as va,resolve as Na}from"path";function ct(t){let e=[];for(let i of t)switch(i.type){case"text":i.text.trim()&&e.push(i.text);break;case"resource_link":e.push(`Resource: ${i.name} (${i.uri})`);break;case"resource":if("text"in i.resource){e.push(`Resource: ${i.resource.uri}
|
|
6
|
+
${i.resource.text}`);break}throw w.invalidParams(void 0,"Binary resources are not supported.");case"image":throw w.invalidParams(void 0,"Image prompts are not supported.");case"audio":throw w.invalidParams(void 0,"Audio prompts are not supported.")}let n=e.join(`
|
|
7
|
+
|
|
8
|
+
`).trim();if(!n)throw w.invalidParams(void 0,"Prompt must contain text or a resource link.");return n}function De(t){return/^(ReadFile)$/u.test(t)?"read":/^(WriteFile|EditFile)$/u.test(t)?"edit":/^(Glob|Grep|ToolSearch)$/u.test(t)?"search":/^(Bash|PowerShell|ComputerUse)$/u.test(t)?"execute":/^(Agent|TaskCreate|TaskGet|TaskList|TaskUpdate|TaskStop)$/u.test(t)?"think":t==="ExitPlanMode"?"switch_mode":"other"}function qe(t,e){let n=$e(t,"file_path")||$e(t,"path");if(n)return[{path:va(n)?n:Na(e,n)}]}function vs(t,e,n,i){return{sessionUpdate:"tool_call",toolCallId:e,title:t,kind:De(t),status:"pending",rawInput:n,locations:qe(n,i)}}function Ns(t,e,n,i){return{sessionUpdate:"tool_call_update",toolCallId:t,status:n?"failed":"completed",content:e?[{type:"content",content:{type:"text",text:e}}]:void 0,rawOutput:{output:e,isError:n,...i===void 0?{}:{elapsed:i}}}}function dt(t,e,n){switch(t.type){case"stream_text":return{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t.text}};case"thinking_text":return{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t.text}};case"tool_use":return vs(t.toolName,t.toolId,t.args,e);case"tool_result":return Ns(t.toolId,t.output,t.isError,t.elapsed);case"usage":return{sessionUpdate:"usage_update",used:t.usage.inputTokens+t.usage.cacheReadInputTokens+t.usage.cacheCreationInputTokens,size:n};default:return null}}function ut(t,e){let n=t.inputTokens+e.usage.inputTokens,i=t.outputTokens+e.usage.outputTokens,a=(t.cachedReadTokens??0)+e.usage.cacheReadInputTokens,u=(t.cachedWriteTokens??0)+e.usage.cacheCreationInputTokens;return{inputTokens:n,outputTokens:i,cachedReadTokens:a,cachedWriteTokens:u,totalTokens:n+i+a+u}}function lt(){return{totalTokens:0,inputTokens:0,outputTokens:0,cachedReadTokens:0,cachedWriteTokens:0}}function ht(t){switch(t){case"max_tokens":return"max_tokens";case"max_turn_requests":return"max_turn_requests";case"refusal":return"refusal";case"cancelled":case"interrupted":return"cancelled";default:return"end_turn"}}function*pt(t,e,n){for(let i of e){if(i.type===kt||i.role!=="user"&&i.role!=="assistant")continue;let a=Be(i.content);a&&(yield{sessionId:t,update:{sessionUpdate:i.role==="assistant"?"agent_message_chunk":"user_message_chunk",content:{type:"text",text:a}}});for(let u of i.tool_uses??[])yield{sessionId:t,update:vs(u.tool_name,u.tool_use_id,u.arguments??{},n)};for(let u of i.tool_results??[]){let p=Be(u.content);yield{sessionId:t,update:Ns(u.tool_use_id,p,u.is_error??!1)}}}}var Ma=/^[a-z0-9]+-[a-f0-9]{8}$/u;async function ja(t,e){let n=yt(Tt(),t),i=n.providers[0];if(!i)throw w.internalError(void 0,"No provider configured.");let a=await Dt({provider:i,workDir:t,hooks:n.hooks,mcpServers:n.mcp_servers,enableCoordinatorMode:n.enable_coordinator_mode??!1,forkDisabled:!Rt(n),sessionId:e});return{sessionId:a.sessionId,workDir:a.workDir,contextWindow:a.contextWindow,conv:a.conv,run:a.run.bind(a),abort:()=>{a.abort()},dispose:async()=>{a.abort(),await Promise.all([a.backgroundTaskManager.stopAll(),a.teamManager.stopAll(),a.mcpManager?.disconnectAll()??Promise.resolve()])}}}function Ms(t){if(!Ia(t))throw w.invalidParams(void 0,"Session cwd must be absolute.")}function ft(t){if(!Ma.test(t))throw w.invalidParams(void 0,"Invalid session ID.")}function Is(t){if(Ms(t.cwd),(t.mcpServers?.length??0)>0)throw w.invalidParams(void 0,"Client-provided MCP servers are not supported.");if((t.additionalDirectories?.length??0)>0)throw w.invalidParams(void 0,"Additional workspace directories are not supported.")}var He=class{constructor(e=ja){this.runtimeFactory=e}runtimeFactory;sessions=new Map;initialize(e){return{protocolVersion:Ve,authMethods:[],agentInfo:{name:"swifty",title:"Swifty",version:Ct},agentCapabilities:{loadSession:!0,promptCapabilities:{embeddedContext:!0},sessionCapabilities:{list:{},resume:{},close:{}}}}}authenticate(){return{}}addSession(e){let n={runtime:e,generation:0,tail:Promise.resolve(),turnAbort:null,closed:!1,usage:lt()};return this.sessions.set(e.sessionId,n),n}async newSession(e){Is(e);let n=await this.runtimeFactory(e.cwd);return this.addSession(n),{sessionId:n.sessionId}}async loadSession(e,n,i){Is(e),ft(e.sessionId);let a=this.sessions.get(e.sessionId);if(a&&a.runtime.workDir!==e.cwd)throw w.invalidParams(void 0,"Session cwd does not match.");if(a&&!i)return{};let u=It(e.cwd,e.sessionId);if(!a&&!Aa(vt(e.cwd,e.sessionId)))throw w.resourceNotFound(e.sessionId);if(!a){let p=await this.runtimeFactory(e.cwd,e.sessionId);p.conv.reset(),p.conv.appendMessages(Mt(u)),a=this.addSession(p)}if(i)for(let p of pt(e.sessionId,u,e.cwd))await n.notify(q.client.session.update,p);return{}}listSessions(e){if(e.cursor)throw w.invalidParams(void 0,"Session pagination is not supported.");let n=e.cwd??process.cwd();return Ms(n),{sessions:jt(n).map(i=>({sessionId:i.id,cwd:n,title:i.firstMessage||void 0,updatedAt:i.modTime.toISOString()}))}}prompt(e,n){let i=this.requireSession(e.sessionId),a=ct(e.prompt),u=i.generation,p=i.tail.catch(()=>{}).then(async()=>{if(i.closed||u!==i.generation||n.signal.aborted)return{stopReason:"cancelled"};let z=new AbortController;i.turnAbort=z;let f=AbortSignal.any([n.signal,z.signal]),g=()=>{i.runtime.abort()};f.aborted?g():f.addEventListener("abort",g,{once:!0});try{return await this.runPrompt(i,e.sessionId,a,n,f)}finally{f.removeEventListener("abort",g),i.turnAbort===z&&(i.turnAbort=null)}});return i.tail=p.then(()=>{},()=>{}),p}cancel(e){let n=this.sessions.get(e.sessionId);n&&(n.generation+=1,n.turnAbort?.abort(),n.runtime.abort())}async closeSession(e){ft(e.sessionId);let n=this.sessions.get(e.sessionId);return n?(n.closed=!0,n.generation+=1,n.turnAbort?.abort(),n.runtime.abort(),await n.tail.catch(()=>{}),await n.runtime.dispose(),this.sessions.delete(e.sessionId),{}):{}}async dispose(){let e=[...this.sessions.values()];this.sessions.clear();for(let n of e)n.closed=!0,n.generation+=1,n.turnAbort?.abort(),n.runtime.abort();await Promise.all(e.map(async n=>{await n.tail.catch(()=>{}),await n.runtime.dispose()}))}requireSession(e){ft(e);let n=this.sessions.get(e);if(!n||n.closed)throw w.resourceNotFound(e);return n}async runPrompt(e,n,i,a,u){Nt(e.runtime.workDir,n,{role:"user",content:i,timestamp:Math.floor(Date.now()/1e3)});let p="end_turn",z=!1;for await(let f of e.runtime.run(i,{onPermissionRequest:async(g,m,y,C)=>{let k=a.client.request(q.client.session.requestPermission,{sessionId:n,toolCall:{toolCallId:C,title:`${g}: ${y.reason}`,kind:De(g),status:"pending",rawInput:m,locations:qe(m,e.runtime.workDir)},options:[{optionId:"allow",name:"Allow once",kind:"allow_once"},{optionId:"allowAlways",name:"Always allow",kind:"allow_always"},{optionId:"deny",name:"Reject",kind:"reject_once"}]}),M=()=>{},U=new Promise(We=>{M=()=>{We(null)},u.aborted?M():u.addEventListener("abort",M,{once:!0})}),H=await Promise.race([k,U]);return u.removeEventListener("abort",M),!H||H.outcome.outcome==="cancelled"?(e.runtime.abort(),"deny"):H.outcome.optionId==="allowAlways"?"allowAlways":H.outcome.optionId==="allow"?"allow":"deny"}})){if(f.type==="compact"&&f.boundary&&At(e.runtime.workDir,n,f.boundary),f.type==="error")throw w.internalError(void 0,f.error.message);f.type==="loop_complete"&&(p=ht(f.stopReason)),f.type==="usage"&&(e.usage=ut(e.usage,f),z=!0);let g=dt(f,e.runtime.workDir,e.runtime.contextWindow);if(g){let m={sessionId:n,update:g};await a.client.notify(q.client.session.update,m)}}return{stopReason:p,...z?{usage:e.usage}:{}}}};function be(t){let e=new He(t);return{app:at({name:"swifty"}).onRequest(q.agent.initialize,i=>e.initialize(i.params)).onRequest(q.agent.authenticate,()=>e.authenticate()).onRequest(q.agent.session.new,i=>e.newSession(i.params)).onRequest(q.agent.session.prompt,i=>e.prompt(i.params,i)).onRequest(q.agent.session.list,i=>e.listSessions(i.params)).onRequest(q.agent.session.load,i=>e.loadSession(i.params,i.client,!0)).onRequest(q.agent.session.resume,i=>e.loadSession(i.params,i.client,!1)).onRequest(q.agent.session.close,i=>e.closeSession(i.params)).onNotification(q.agent.session.cancel,i=>{e.cancel(i.params)}).onConnect(i=>{i.signal.addEventListener("abort",()=>{e.dispose()},{once:!0})}),dispose:()=>e.dispose()}}function qa(){let t=(...e)=>{process.stderr.write(`${e.map(String).join(" ")}
|
|
9
|
+
`)};console.log=t,console.info=t,console.warn=t,console.debug=t}async function zt(){qa();let t=be(),e=bs(Da.toWeb(process.stdout),Oa.toWeb(process.stdin)),n=t.app.connect(e);process.stdin.resume();try{await n.closed}finally{await t.dispose()}}var ei={};Se(ei,{parseAcpWebSocketAddress:()=>Zs,runAcpWebSocket:()=>St,startAcpWebSocketServer:()=>Xs});import{createServer as ac}from"http";var Z="Acp-Connection-Id",Pe="Acp-Session-Id",mt="text/event-stream",gt="application/json",Ha=new Set([h.session_cancel,h.session_close,h.session_delete,h.session_fork,h.session_load,h.session_prompt,h.session_resume,h.session_set_config_option,h.session_set_mode,"session/set_model",h.nes_suggest,h.nes_accept,h.nes_reject,h.nes_close,h.document_did_open,h.document_did_change,h.document_did_close,h.document_did_save,h.document_did_focus]);function Ds(t){return Ha.has(t)}function _e(t){if(!I(t))return;let e=t.sessionId;return typeof e=="string"?e:void 0}function qs(t){return"method"in t?_e(t.params):void 0}function Hs(t){if(!V(t)||!("result"in t)||!I(t.result))return;let e=t.result.sessionId;return typeof e=="string"?e:void 0}function oe(t){return t.jsonrpc==="2.0"&&"id"in t&&"method"in t&&t.method===h.initialize}function W(t){if(typeof t=="string")return`string:${t}`;if(typeof t=="number")return`number:${t}`;if(t===null)return"null"}var md=16*1024*1024;function Ps(t,e){return(n,i,a)=>{let u,p=!1,z=()=>{e.off("headers",f),i.off("close",g),i.off("error",g)},f=(m,y)=>{y!==n||!u||m.push(`${Z}: ${u.connectionId}`)},g=()=>{p||(z(),u?.reject())};try{u=t.prepareWebSocketUpgrade(),e.on("headers",f),i.once("close",g),i.once("error",g),e.handleUpgrade(n,i,a,m=>{p=!0,z(),u?.accept(m)})}catch(m){z(),u?.reject(),Pa(i,m)}}}function Pa(t,e){t.destroy(e instanceof Error?e:void 0)}var we=class{enabled;queue=[];activeLease;isFinished=!1;isAborted=!1;constructor(e=!0){this.enabled=e}push(e){!this.enabled||this.isFinished||(this.queue.push(e),this.activeLease?.wake())}tryAcquire(){if(!this.enabled||this.isAborted||this.activeLease)return;let e=new bt(this);return this.activeLease=e,e}finish(){this.isFinished||(this.isFinished=!0,this.activeLease?.wake())}abort(){this.isAborted||(this.isAborted=!0,this.isFinished=!0,this.queue.length=0,this.activeLease?.wake())}async receive(e){for(;;){if(this.isAborted||e.released||this.activeLease!==e)return{done:!0,value:void 0};if(this.queue.length>0)return{done:!1,value:this.queue.shift()};if(this.isFinished)return{done:!0,value:void 0};await e.wait()}}release(e){this.activeLease===e&&(this.activeLease=void 0,e.markReleased())}},Le=class{transport;connectionId;inboundTx;outboundRx;connectionStream;allOutbound;sessionStreams=new Map;pendingRoutes=new Map;clientResponseRoutes=new Map;closed;agentConnection;supportsBatches=!1;hasStartedRouter=!1;inboundWriteChain=Promise.resolve();initialReader;outboundReader;routerPromise;shutdownPromise;hasResolvedClosed=!1;finishAgentOutbound=()=>{};resolveClosed=()=>{};constructor(e,n="http"){this.transport=n,this.connectionId=globalThis.crypto.randomUUID(),this.connectionStream=new we(n==="http"),this.allOutbound=new we(n==="websocket"),this.closed=new Promise(p=>{this.resolveClosed=p});let i=new TransformStream,a=La(p=>{if(!this.supportsBatches&&Array.isArray(p))throw new TypeError("AcpServer transports do not support outbound JSON-RPC batch messages")});this.inboundTx=i.writable,this.outboundRx=a.readable,this.finishAgentOutbound=a.finish;let u={readable:i.readable,writable:a.writable};this.agentConnection=e.connect(u,{deferConnectHandlers:!0}),this.observeAgentConnection()}async recvInitial(e){let n=this.outboundRx.getReader();this.initialReader=n;try{let i=await n.read();if(i.done||!i.value||!Ga(i.value,e))throw this.shutdownPromise||await this.shutdown(),new Error("Expected initialize response from agent");return i.value}finally{this.initialReader===n&&(this.initialReader=void 0),n.releaseLock()}}async writeInbound(e){if(!this.supportsBatches&&Array.isArray(e))throw new TypeError("AcpServer transports do not support inbound JSON-RPC batch messages");let n=this.inboundWriteChain.then(()=>this.writeInboundMessage(e));this.inboundWriteChain=n.catch(()=>{}),await n}startRouter(){this.hasStartedRouter||(this.hasStartedRouter=!0,this.routerPromise=this.runRouter())}startConnectHandlers(){typeof this.agentConnection=="object"&&this.agentConnection!==null&&"startConnectHandlers"in this.agentConnection&&typeof this.agentConnection.startConnectHandlers=="function"&&this.agentConnection.startConnectHandlers()}enableBatches(){this.supportsBatches=!0}get batchesEnabled(){return this.supportsBatches}ensureSession(e){let n=this.sessionStreams.get(e);if(n)return n;let i=new we(this.transport==="http");return this.sessionStreams.set(e,i),i}async shutdown(){return this.shutdownPromise||(this.shutdownPromise=this.runShutdown()),this.shutdownPromise}async runShutdown(){try{this.connectionStream.abort(),this.allOutbound.abort();for(let e of this.sessionStreams.values())e.abort();this.sessionStreams.clear(),this.pendingRoutes.clear(),this.clientResponseRoutes.clear(),await Promise.allSettled([this.inboundTx.close(),this.cancelOutboundReader()])}finally{this.resolveClosedOnce()}}observeAgentConnection(){typeof this.agentConnection!="object"||this.agentConnection===null||!("closed"in this.agentConnection)||!this.agentConnection.closed||Promise.resolve(this.agentConnection.closed).finally(async()=>{if(!this.hasStartedRouter){await this.shutdown();return}this.finishAgentOutbound(),await this.routerPromise})}cancelOutboundReader(){let e=this.initialReader??this.outboundReader;return e?e.cancel():this.outboundRx.cancel()}async writeInboundMessage(e){let n=this.inboundTx.getWriter();try{await n.write(e)}finally{n.releaseLock()}}async runRouter(){let e=this.outboundRx.getReader();this.outboundReader=e;try{for(;;){let n=await e.read();if(n.done)return;this.routeOutbound(n.value)}}catch(n){console.error("ACP connection router stopped unexpectedly:",n)}finally{this.outboundReader===e&&(this.outboundReader=void 0),e.releaseLock(),this.connectionStream.finish(),this.allOutbound.finish();for(let n of this.sessionStreams.values())n.finish();this.resolveClosedOnce()}}resolveClosedOnce(){this.hasResolvedClosed||(this.hasResolvedClosed=!0,this.resolveClosed())}routeOutbound(e){if(this.allOutbound.push(e),Array.isArray(e)){for(let n of e)this.routeOutboundMessage(n);return}this.routeOutboundMessage(e)}routeOutboundMessage(e){if(V(e)){this.routeOutboundResponse(e);return}this.routeOutboundRequestOrNotification(e)}routeOutboundResponse(e){let n=W(e.id),i=n?this.pendingRoutes.get(n):void 0,a=Hs(e);a&&this.ensureSession(a),n&&this.pendingRoutes.delete(n),this.pushToRoute(i??"connection",e)}routeOutboundRequestOrNotification(e){let n=qs(e);if(n){this.trackClientResponseRoute(e,{session:n}),this.ensureSession(n).push(e);return}this.trackClientResponseRoute(e,"connection"),this.connectionStream.push(e)}trackClientResponseRoute(e,n){if(!("id"in e)||!("method"in e))return;let i=W(e.id);i&&this.clientResponseRoutes.set(i,n)}pushToRoute(e,n){if(e==="connection"){this.connectionStream.push(n);return}this.ensureSession(e.session).push(n)}},Ge=class{connections=new Map;pendingConnections=new Map;createConnection(e,n="http"){let i=new Le(e,n);return this.connections.set(i.connectionId,i),this.trackConnectionClose(i),i}createPendingConnection(e,n="websocket"){let i=new Le(e,n);return this.pendingConnections.set(i.connectionId,i),this.trackConnectionClose(i),i}register(e){this.pendingConnections.delete(e.connectionId),this.connections.set(e.connectionId,e)}get(e){return this.connections.get(e)}remove(e){let n=this.get(e);if(n)return this.connections.delete(e),n.shutdown(),n}discard(e){let n=this.connections.get(e)??this.pendingConnections.get(e);if(n)return this.connections.delete(e),this.pendingConnections.delete(e),n.shutdown(),n}async closeAll(){let e=new Set([...this.connections.values(),...this.pendingConnections.values()]);this.connections.clear(),this.pendingConnections.clear(),await Promise.all(Array.from(e,n=>n.shutdown()))}trackConnectionClose(e){e.closed.then(()=>{this.connections.get(e.connectionId)===e&&this.connections.delete(e.connectionId),this.pendingConnections.get(e.connectionId)===e&&this.pendingConnections.delete(e.connectionId)})}},bt=class{mailbox;released=!1;receiving=!1;wakePromise;resolveWake;constructor(e){this.mailbox=e}async receive(){if(this.receiving)throw new Error("ACP outbound mailbox lease already has a pending receive");this.receiving=!0;try{return await this.mailbox.receive(this)}finally{this.receiving=!1}}release(){this.mailbox.release(this)}wake(){this.resolveWake?.(),this.wakePromise=void 0,this.resolveWake=void 0}wait(){return this.wakePromise||(this.wakePromise=new Promise(e=>{this.resolveWake=e})),this.wakePromise}markReleased(){this.released=!0,this.wake()}};function La(t){let e,n=!1,i=()=>{if(!n){n=!0;try{e?.close()}catch{}}},a=u=>{if(!n){n=!0;try{e?.error(u)}catch{}}};return{readable:new ReadableStream({start(u){e=u},cancel(){n=!0}}),writable:new WritableStream({write(u){if(n)throw new Error("ACP outbound channel is closed");try{t(u),e?.enqueue(u)}catch(p){throw a(p),p}},close:i,abort:a}),finish:i}}function Ga(t,e){return!Array.isArray(t)&&"id"in t&&!("method"in t)&&t.id===e}function Ls(t){return`data: ${JSON.stringify(t)}
|
|
10
|
+
|
|
11
|
+
`}function Gs(){return`:
|
|
12
|
+
|
|
13
|
+
`}function Us(t){return new ReadableStream(Ua(t))}function Ua(t){let e=new TextEncoder,n,i=!1,a=!1,u=()=>{n&&(clearInterval(n),n=void 0)},p=(g,m)=>{try{return g.enqueue(e.encode(m)),!0}catch{return!1}},z=g=>g.desiredSize!==null&&g.desiredSize>0,f=g=>{if(!a){a=!0,u(),t.release();try{g.close()}catch{}}};return{start(g){n=setInterval(()=>{a||!z(g)||p(g,Gs())||f(g)},15e3)},async pull(g){if(!(a||i||!z(g))){i=!0;try{let m=await t.receive();if(a)return;if(m.done){f(g);return}p(g,Ls(m.value))||f(g)}catch(m){a||(a=!0,u(),g.error(m))}finally{i=!1}}},cancel(){a=!0,u(),t.release()}}}function Ue(t,e,n){if(t.on){let i=(...a)=>{n(...Fa(e,a))};return t.on(e,i),()=>{if(t.off){t.off(e,i);return}t.removeListener?.(e,i)}}if(t.addEventListener){let i=a=>n(a);return t.addEventListener(e,i),()=>{t.removeEventListener?.(e,i)}}throw new Error("WebSocket object does not support event listeners")}function Fs(t){let e=Ba(t);if(typeof e=="string")return e}function Fa(t,e){return t!=="message"||typeof e[1]!="boolean"?e:e[1]?[void 0]:[Wa(e[0])]}function Wa(t){if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return new TextDecoder().decode(t);if(ArrayBuffer.isView(t))return new TextDecoder().decode(t);if(Ja(t))return Va(t)}function Ba(t){let[e]=t;return $a(e)?e.data:e}function $a(t){return typeof t=="object"&&t!==null&&"data"in t}function Ja(t){return Array.isArray(t)&&t.every(ArrayBuffer.isView)}function Va(t){let e=t.reduce((a,u)=>a+u.byteLength,0),n=new Uint8Array(e),i=0;for(let a of t)n.set(new Uint8Array(a.buffer,a.byteOffset,a.byteLength),i),i+=a.byteLength;return new TextDecoder().decode(n)}function $s(t,e){let n=new _t(t,e);return n.start(),n}var _t=class{socket;options;connection;preparedConnection;outboundLease;inboundWriteChain=Promise.resolve();messageChain=Promise.resolve();isClosed=!1;closedPromise;resolveClosed=()=>{};detachListeners=[];constructor(e,n){this.socket=e,this.options=n,this.preparedConnection=n.connection,this.closedPromise=new Promise(i=>{this.resolveClosed=i})}get closed(){return this.closedPromise}start(){this.detachListeners.push(Ue(this.socket,"message",(...e)=>{this.enqueueSocketMessage(e)})),this.detachListeners.push(Ue(this.socket,"close",()=>{this.closeSession()})),this.detachListeners.push(Ue(this.socket,"error",()=>{this.shutdown(1011,"WebSocket error")}))}close(e=1001,n="Server shutting down"){return this.shutdown(e,n)}enqueueSocketMessage(e){let n=this.messageChain.then(()=>this.handleSocketMessage(e));this.messageChain=n.catch(i=>{this.isClosed||(console.error("ACP WebSocket message handling failed:",i),this.shutdown(1011,"Message handling failed"))})}async handleSocketMessage(e){if(this.isClosed)return;let n=Fs(e);if(n===void 0){console.warn("Ignoring non-text ACP WebSocket frame");return}let i;try{i=JSON.parse(n)}catch{this.send(L(w.parseError()));return}if(!Array.isArray(i)&&!I(i)){this.send(L(w.invalidRequest(i)));return}if(!this.connection&&Array.isArray(i)){if(i.length===1&&P(i[0])){await this.handleInitialize(i[0],!0);return}console.warn("First ACP WebSocket message must be initialize or a single-entry initialize batch"),await this.shutdown(1002,"First message must be initialize");return}let a=i;if(!this.connection){if(pe(a))return;if(!P(a)&&!F(a)){this.send(L(w.invalidRequest(a)));return}await this.handleInitialize(a,!1);return}let u=await this.forwardMessage(a);u.ok||console.warn("Ignoring ACP WebSocket message:",u.message)}async handleInitialize(e,n){if(!oe(e)){console.warn("First ACP WebSocket message must be initialize"),await this.shutdown(1002,"First message must be initialize");return}if(!("id"in e)||e.id===null){console.warn("ACP WebSocket initialize request must include an ID"),await this.shutdown(1002,"Initialize request must include an ID");return}let i=this.preparedConnection??this.options.registry.createPendingConnection(this.options.agent);this.preparedConnection=i;try{await Ws(i,e);let a=await i.recvInitial(e.id);if(this.isClosed){this.options.registry.discard(i.connectionId);return}this.preparedConnection=void 0,Qa(a)===2&&i.enableBatches(),this.connection=i,this.options.registry.register(i),i.startRouter(),i.startConnectHandlers(),this.send(n?[a]:a),this.startOutboundPump(i)}catch(a){this.preparedConnection=void 0,this.options.registry.discard(i.connectionId);let u={jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:a instanceof Error?a.message:void 0}};this.send(n?[u]:u),await this.shutdown(1011,"Initialize failed")}}async forwardMessage(e){let n=this.connection;if(!n)return{ok:!1,message:"ACP WebSocket connection is not initialized"};if(Array.isArray(e)){if(!n.batchesEnabled)return await this.shutdown(1002,"JSON-RPC batches require ACP v2"),{ok:!1,message:"JSON-RPC batches require ACP v2"};if(e.some(Ka))return await this.shutdown(1002,"Initialize not allowed on existing connection"),{ok:!1,message:"Initialize not allowed on existing connection"};for(let i of e)this.trackInboundRoutes(i);return await this.writeInbound(e),{ok:!0}}return P(e)&&oe(e)?(this.send({jsonrpc:"2.0",id:e.id,error:{code:-32600,message:"Initialize not allowed on existing connection"}}),{ok:!1,message:"Initialize not allowed on existing connection"}):(this.trackInboundRoutes(e),await this.writeInbound(e),{ok:!0})}trackInboundRoutes(e){let n=this.connection;if(n){if(P(e)){let i=Bs(e);i!=="connection"&&n.ensureSession(i.session);let a=W(e.id);a&&n.pendingRoutes.set(a,e.method===h.session_load?"connection":i);return}if(F(e)){let i=Bs(e);i!=="connection"&&n.ensureSession(i.session);return}if(pe(e)){let i=e.id,a=i===null||typeof i=="string"||typeof i=="number"&&Number.isFinite(i)?W(i):void 0;a&&n.clientResponseRoutes.delete(a)}}}async writeInbound(e){let n=this.connection;if(!n)throw new Error("ACP WebSocket connection is not initialized");let i=this.inboundWriteChain.then(()=>Ws(n,e));this.inboundWriteChain=i.catch(()=>{}),await i}startOutboundPump(e){let n=e.allOutbound.tryAcquire();if(!n){this.shutdown(1011,"Outbound stream already has an active receiver");return}this.outboundLease=n,(async()=>{try{for(;!this.isClosed;){let i=await n.receive();if(i.done||!this.send(i.value))return}}catch(i){this.isClosed||console.error("ACP WebSocket outbound pump failed:",i)}finally{this.outboundLease===n&&(this.outboundLease=void 0),n.release(),this.isClosed||this.shutdown()}})()}send(e){if(this.isClosed)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch(n){return console.warn("Failed to send ACP WebSocket message:",n),this.shutdown(1011,"Failed to send message"),!1}}async shutdownIfUninitialized(e,n){this.connection||await this.shutdown(e,n)}async shutdown(e,n){this.closeSocket(e,n),await this.closeSession()}closeSocket(e,n){try{this.socket.close(e,n)}catch(i){console.warn("Failed to close ACP WebSocket:",i)}}async closeSession(){if(!this.isClosed){this.isClosed=!0;try{for(let n of this.detachListeners.splice(0))n();let e=this.outboundLease;this.outboundLease=void 0,e?.release(),this.connection&&(this.options.registry.discard(this.connection.connectionId),this.connection=void 0),this.preparedConnection&&(this.options.registry.discard(this.preparedConnection.connectionId),this.preparedConnection=void 0)}finally{this.resolveClosed()}}}};async function Ws(t,e){await t.writeInbound(e)}function Bs(t){let e=_e(t.params);return e?{session:e}:"connection"}function Ka(t){return P(t)&&oe(t)}function Qa(t){if(!("result"in t)||!I(t.result))return;let e=t.result.protocolVersion;return typeof e=="number"?e:void 0}var Fe=class{agent;registry=new Ge;webSocketSessions=new Set;constructor(e){this.agent=Qs(e)}async handleRequest(e,n={}){return e.method==="POST"?await this.handlePost(e,n):e.method==="GET"?this.handleGet(e):e.method==="DELETE"?this.handleDelete(e):N("Method Not Allowed",405)}prepareWebSocketUpgrade(e={}){let n=Js(e,this.agent),i=this.registry.createPendingConnection(n),a=!1;return{connectionId:i.connectionId,accept:u=>{if(a)throw new Error("ACP WebSocket upgrade has already been settled");a=!0;let p=$s(u,{registry:this.registry,agent:n,connection:i});this.webSocketSessions.add(p),p.closed.finally(()=>{this.webSocketSessions.delete(p)})},reject:()=>{a||(a=!0,this.registry.discard(i.connectionId))}}}async close(){let e=this.registry.closeAll(),n=Promise.all(Array.from(this.webSocketSessions,i=>i.close()));await Promise.all([e,n])}async handlePost(e,n){let i=e.headers.get("Content-Type");if(!oc(i))return N("Unsupported Media Type",415);let a=await Za(e);if(!a.ok)return N("Invalid JSON",400);if(Array.isArray(a.value))return N("Batch JSON-RPC requests are not implemented",501);if(!I(a.value))return N("Invalid JSON-RPC message",400);let u=a.value,p=e.headers.get(Z);if(oe(u))return p?N("Initialize not allowed on existing connection",400):await this.handleInitialize(u,e.signal,n);if(!p)return N("Missing Acp-Connection-Id",400);let z=this.registry.get(p);if(!z)return N("Unknown Acp-Connection-Id",404);let f=await this.forwardConnectedMessage(z,u,e.headers);return f.ok?Ks(202):N(f.message,f.status)}handleGet(e){if(e.headers.get("Upgrade")?.toLowerCase()==="websocket")return N("WebSocket upgrade is not implemented",426);if(!e.headers.get("Accept")?.toLowerCase()?.includes(mt))return N("Not Acceptable",406);let i=e.headers.get(Z);if(!i)return N("Missing Acp-Connection-Id",400);let a=this.registry.get(i);if(!a)return N("Unknown Acp-Connection-Id",404);let u=e.headers.get(Pe),z=(u?a.ensureSession(u):a.connectionStream).tryAcquire();return z?rc(z):N("Outbound stream already has an active receiver",409)}handleDelete(e){let n=e.headers.get(Z);return n?this.registry.remove(n)?Ks(202):N("Unknown Acp-Connection-Id",404):N("Missing Acp-Connection-Id",400)}async handleInitialize(e,n,i){if(!("id"in e)||e.id===null)return N("Initialize request must include an ID",400);if(n.aborted)return N("Request aborted",499);let a;try{a=this.registry.createConnection(Js(i,this.agent));let u=Xa(a,e);u.catch(()=>{});let p=await ec(u,n);if(n.aborted)throw new re;return a.startRouter(),a.startConnectHandlers(),Vs(p,200,{[Z]:a.connectionId})}catch(u){return a&&this.registry.remove(a.connectionId),u instanceof re?N("Request aborted",499):Vs({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:u instanceof Error?u.message:void 0}},500)}}async forwardConnectedMessage(e,n,i){return V(n)?await tc(e,n,i):await nc(e,n,i)}};function Js(t,e){return Ya(t)?Qs(t):e}function Ya(t){return!!(t.agent||t.createAgent||t.createLegacyAgent)}function Qs(t){if((t.agent?1:0)+(t.createAgent?1:0)+(t.createLegacyAgent?1:0)!==1)throw new Error("AcpServer requires exactly one of agent, createAgent, or createLegacyAgent");return t.agent?t.agent:t.createAgent?{connect:(n,i)=>t.createAgent().connect(n,i??{})}:{connect:n=>{new Me(t.createLegacyAgent,n)}}}var re=class extends Error{constructor(){super("Request aborted"),this.name="RequestAbortedError"}};async function Za(t){try{return{ok:!0,value:await t.json()}}catch{return{ok:!1}}}async function wt(t,e){await t.writeInbound(e)}async function Xa(t,e){if(await wt(t,e),!("id"in e)||e.id===null)throw new Error("Initialize request must include an ID");return await t.recvInitial(e.id)}async function ec(t,e){if(e.aborted)throw new re;let n=()=>{},i=new Promise((a,u)=>{let p=()=>{u(new re)};e.addEventListener("abort",p,{once:!0}),n=()=>{e.removeEventListener("abort",p)}});try{return await Promise.race([t,i])}finally{n()}}async function nc(t,e,n){let i=ic(e,n);if(!i.ok)return i;i.value!=="connection"&&t.ensureSession(i.value.session);let a="id"in e?W(e.id):void 0;return a&&t.pendingRoutes.set(a,sc(e,i.value)),await wt(t,e),{ok:!0}}async function tc(t,e,n){let i=W(e.id),a=i?t.clientResponseRoutes.get(i):void 0,u=n.get(Pe);return a&&a!=="connection"&&!u?{ok:!1,status:400,message:"Missing Acp-Session-Id"}:a&&a!=="connection"&&u!==a.session?{ok:!1,status:400,message:"Mismatched Acp-Session-Id"}:(i&&t.clientResponseRoutes.delete(i),await wt(t,e),{ok:!0})}function sc(t,e){return t.method===h.session_load?"connection":e}function ic(t,e){let n=e.get(Pe),i=_e(t.params);return(Ds(t.method)||i!==void 0)&&!n?{ok:!1,status:400,message:"Missing Acp-Session-Id"}:n!==null&&i!==void 0&&n!==i?{ok:!1,status:400,message:"Mismatched Acp-Session-Id"}:n?{ok:!0,value:{session:n}}:i?{ok:!0,value:{session:i}}:{ok:!0,value:"connection"}}function oc(t){return t?.split(";",1)[0]?.trim().toLowerCase()===gt}function rc(t){return new Response(Us(t),{status:200,headers:{"Content-Type":mt,"Cache-Control":"no-cache",Connection:"keep-alive"}})}function Vs(t,e,n){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":gt,...n}})}function N(t,e){return new Response(t,{status:e,headers:{"Content-Type":"text/plain"}})}function Ks(t){return new Response(null,{status:t})}var Ys="/acp",cc="127.0.0.1:18889",dc=new Set(["127.0.0.1","::1","localhost"]);function Zs(t){let e=Ot(t??cc);if(!dc.has(e.host))throw new Error("ACP WebSocket must listen on a loopback address.");return e}async function Xs(t){let{host:e,port:n}=Zs(t),i=new Fe({createAgent:()=>be().app}),a=new Et.default({noServer:!0}),u=Ps(i,a),p=ac((y,C)=>{C.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),C.end("Not Found")});p.on("upgrade",(y,C,k)=>{if(new URL(y.url??"/","http://localhost").pathname!==Ys){C.destroy();return}u(y,C,k)}),await new Promise((y,C)=>{let k=U=>{p.off("listening",M),C(U)},M=()=>{p.off("error",k),y()};p.once("error",k),p.once("listening",M),p.listen(n,e)});let z=p.address();if(!z||typeof z=="string")throw new Error("ACP WebSocket server did not bind to a TCP address.");let f=z,g=f.family==="IPv6"?`[${f.address}]`:f.address,m=!1;return{url:`ws://${g}:${String(f.port)}${Ys}`,async close(){m||(m=!0,await i.close(),await new Promise((y,C)=>{a.close(k=>{k?C(k):y()})}),await new Promise((y,C)=>{p.close(k=>{k?C(k):y()})}))}}}async function St(t){let e=await Xs(t);process.stderr.write(`ACP WebSocket listening at ${e.url}
|
|
14
|
+
`),await new Promise(n=>{let i=()=>{process.off("SIGINT",i),process.off("SIGTERM",i),e.close().finally(n)};process.once("SIGINT",i),process.once("SIGTERM",i)})}function uc(t){let e=t.indexOf("--acp"),n=t.indexOf("--acp-ws");if(e===-1&&n===-1)return null;if(e!==-1&&n!==-1)throw new Error("Use either --acp or --acp-ws, not both.");if(e!==-1){if(t.length!==1)throw new Error("--acp cannot be combined with other CLI options.");return{transport:"stdio"}}let i=t[n+1],a=i&&!i.startsWith("-")?2:1;if(t.length!==a)throw new Error("--acp-ws accepts only an optional host:port address.");return{transport:"websocket",...a===2?{address:i}:{}}}async function Vd(t){let e=uc(t);if(!e)throw new Error("ACP mode was not selected.");if(e.transport==="stdio"){await zt();return}await St(e.address)}export{js as Agent,As as Conversion,Os as Stdio,ei as Websocket,uc as parseAcpMode,Vd as runAcp};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{H as b,I as c,g as a}from"./chunk-4B4SGVJH.js";import"./chunk-IOLGXPUQ.js";import"./chunk-XGUH7SGV.js";import"./chunk-TNF3EHFY.js";import"./chunk-NDPYUGE5.js";import"./chunk-325L2ILZ.js";import"./chunk-44LPRRYU.js";import"./chunk-NCZR3AGA.js";import"./chunk-35X3GW25.js";import"./chunk-G2TE2QZM.js";import"./chunk-FZORZF22.js";import"./chunk-YKWIZE5D.js";import"./chunk-LC7ZWLIH.js";import"./chunk-IZ7QOBSB.js";export{c as Agent,b as Events,a as StreamingExecutor};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{g as M}from"./chunk-7JQHFZRD.js";import{a as Z}from"./chunk-H56UQALW.js";import{a as X}from"./chunk-TNF3EHFY.js";import{A as J,B as I,C as V,D as q,E as Q,k as B,m as O,n as U,o as j,p as $,q as K,r as F,t as C,u as E,z as D}from"./chunk-NDPYUGE5.js";import"./chunk-325L2ILZ.js";import{f as N,k as H,l as z,m as G,n as d,o as W,s as Y}from"./chunk-44LPRRYU.js";import{D as w,f as R}from"./chunk-NCZR3AGA.js";import"./chunk-IZ7QOBSB.js";function oe(o){for(let t=o.length-1;t>=0;t--){let e=o[t];if(e.defer_loading!==!0){e.cache_control={type:"ephemeral"};return}}}function ne(o){return o.some(t=>"defer_loading"in t&&t.defer_loading===!0)}var re="computer-use-2025-11-24";function se(o){if("type"in o&&o.type==="computer_20251124")return{...o};if("input_schema"in o){let t=o,{cache_control:e,...n}=t;return{...n,type:"custom",...t.defer_loading!==!0&&e?{cache_control:e}:{}}}throw new Error("Anthropic received a tool schema serialized for another protocol.")}var T=N({module:"llm"});var ie=3e3,ae=w.object({max_input_tokens:w.coerce.number()});async function Te(o){if(o.protocol!=="anthropic")return 0;let t=E(o),n=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,r=new AbortController,s=setTimeout(()=>{r.abort()},ie);try{let c=await fetch(n,{method:"GET",headers:{"anthropic-version":"2023-06-01",...t?{"x-api-key":t}:{}},signal:r.signal});if(!c.ok)return 0;let v=await c.json(),{success:p,error:u,data:h}=await R(ae,v);if(!p)return T.warn({message:u.message},"model context window schema validation failed"),0;let m=h.max_input_tokens;return Math.max(m,0)}catch(c){return T.error({err:c},"failed to fetch model context window"),0}finally{clearTimeout(s)}}function y(o){return typeof o=="string"?[{type:"text",text:o}]:o.map(t=>{let e=X(t);if(!e||e.type==="tool_reference")throw new Error(`Unsupported user content block: ${Y(t,"type","unknown")}`);return e})}function le(o){let t=[];for(let e of o)if(e.role==="assistant"){let n=[];if(e.thinkingBlocks)for(let s of e.thinkingBlocks)n.push({type:"thinking",thinking:s.thinking,signature:s.signature});let r=typeof e.content=="string"?e.content:H(e.content);if(r&&n.push({type:"text",text:r}),e.toolUses)for(let s of e.toolUses)n.push({type:"tool_use",id:s.toolUseId,name:s.toolName==="ComputerUse"?"computer":s.toolName,input:s.arguments});n.length===0&&n.push({type:"text",text:""}),t.push({role:"assistant",content:n})}else if(e.toolResults&&e.toolResults.length>0){let n=[];for(let r of e.toolResults)n.push({type:"tool_result",tool_use_id:r.toolUseId,is_error:r.isError,content:r.contentBlocks?.length?r.contentBlocks:r.content});e.content.length>0&&n.push(...y(e.content)),t.push({role:"user",content:n})}else{if(t.length===0){t.push({role:"user",content:y(e.content)});continue}let n=!1,r=t[t.length-1],s=r.content;r.role==="user"&&(typeof s=="string"||Array.isArray(s)&&s.length>0&&(s[0].type==="text"||s[0].type==="image"))&&(n=!0),n?(typeof s=="string"&&(s=r.content=s.trim().length>0?[{type:"text",text:s}]:[]),s.push(...y(e.content))):t.push({role:"user",content:y(e.content)})}return t}var ee=class{protocol="anthropic";client;model;thinkingLevel;systemPrompt;maxOutputTokens;config;constructor(t,e){let n=E(t);if(!n)throw new I("Anthropic API key not found, set ANTHROPIC_API_KEY in ~/.swifty/config.yaml, or via ANTHROPIC_API_KEY env variable.");this.client=new M({apiKey:n,baseURL:t.base_url}),this.model=t.model,this.config={...t},this.thinkingLevel=O(t),this.systemPrompt=e,this.maxOutputTokens=C(t)}setSystemPrompt(t){this.systemPrompt=t}setMaxOutputTokens(t){this.config={...this.config,max_output_tokens:t},this.maxOutputTokens=C(this.config),this.setThinkingLevel(this.thinkingLevel)}setThinkingLevel(t){return this.thinkingLevel=F(this.config,t),this.thinkingLevel}getThinkingLevel(){return this.thinkingLevel}getSupportedThinkingLevels(){return K(this.config)}async*stream(t,e,n){let r=le(D(t.getMessages())),s=ne(e),c=e.map(se),v=c.some(l=>"type"in l&&l.type==="computer_20251124");oe(c),ce(r);let p={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:r,...c.length>0?{tools:c}:{}},u=this.getThinkingLevel();if(this.config.reasoning!==!1)if(u==="off")p.thinking={type:"disabled"};else if(this.config.thinking_mode==="adaptive"){let l=$(u,this.config);l!==null&&(p.thinking={type:"adaptive"},p.output_config={effort:l})}else{let l=j(u,this.config);l!==null&&l!=="none"&&(p.thinking={type:"enabled",budget_tokens:Math.min(U(l),this.maxOutputTokens-B)})}let h=0,m=0,x=0,A=0,S="end_turn",b="",L="",P=!1;try{let l=[...s?[Z]:[],...v?[re]:[]],te=this.client.messages.stream(p,{...n?{signal:n}:{},...l.length>0?{headers:{"anthropic-beta":l.join(",")}}:{}}),g="",k="",f="";for await(let a of te)switch(a.type){case"content_block_start":{let i=a.content_block;i.type==="thinking"?(P=!0,b="",L=""):i.type==="tool_use"&&(k=i.id,g=i.name==="computer"?"ComputerUse":i.name,f="",yield{type:"tool_call_start",toolName:g,toolId:k});break}case"content_block_delta":{let i=a.delta;i.type==="thinking_delta"?(b+=i.thinking,yield{type:"thinking_delta",text:i.thinking}):i.type==="signature_delta"?L+=i.signature:i.type==="text_delta"?yield{type:"text_delta",text:i.text}:i.type==="input_json_delta"&&(f+=i.partial_json,yield{type:"tool_call_delta",text:i.partial_json});break}case"content_block_stop":{if(P&&(yield{type:"thinking_complete",thinking:b,signature:L},P=!1),g){let i={};if(f)try{let _=JSON.parse(f);i=z(_)?G(_):{}}catch(_){T.error({err:_},"llm operation failed"),i={}}yield{type:"tool_call_complete",toolId:k,toolName:g,arguments:i},g="",k="",f=""}break}case"message_delta":{a.delta.stop_reason&&(S=a.delta.stop_reason),a.usage.output_tokens&&(m=a.usage.output_tokens,a.usage.input_tokens&&(h=a.usage.input_tokens),a.usage.cache_read_input_tokens&&(x=a.usage.cache_read_input_tokens),a.usage.cache_creation_input_tokens&&(A=a.usage.cache_creation_input_tokens));break}case"message_start":{h=a.message.usage.input_tokens,m=a.message.usage.output_tokens,x=a.message.usage.cache_read_input_tokens??0,A=a.message.usage.cache_creation_input_tokens??0;break}}yield{type:"stream_end",stopReason:S,usage:{inputTokens:h,outputTokens:m,cacheReadInputTokens:x,cacheCreationInputTokens:A}}}catch(l){throw T.error({err:l},"llm operation failed"),pe(l)}}};function ce(o){for(let t=o.length-1;t>=0;t--){if(o[t].role!=="user")continue;let e=o[t].content;if(typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0)return;typeof e=="string"&&(e=o[t].content=[{type:"text",text:e}]);let n=e[e.length-1];for(let r=e.length-1;r>=0;r--)if(e[r].type!=="image"){n=e[r];break}Reflect.set(n,"cache_control",{type:"ephemeral"});return}}function pe(o){if(o instanceof M.APIError){if(o.status===413||/prompts?\s+too\s+long/i.test(o.message))return new Q(`Prompt too long: ${o.message}`);if(o.status===401)return new I(`Invalid API key: ${o.message}`);if(o.status===429){let t=o.headers,e=t instanceof Headers?t.get("retry-after"):void 0,n="Rate Limited";if(e){let r=Number.parseInt(d(e));Number.isNaN(r)?n+=", please wait.":n+=`, retry after ${d(r)}s.`}else n+=", please wait.";return new V(n,e?d(e):void 0)}return new J(`Anthropic API error (${d(o.status)}): ${o.message}`)}return new q(`Network error: ${W(o)}`)}export{ee as AnthropicClient,le as buildAnthropicMessages,Te as fetchModelContextWindow,ce as markLastUserTailForCache,oe as markToolsForCache,ne as needsToolSearchBeta};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{a as R,c as B,d as n,n as g,q as h,r as A,s as U,t as S,v}from"./chunk-G2TE2QZM.js";import{a as i,b as t,d as M,i as D}from"./chunk-FZORZF22.js";import{M as I,i as L}from"./chunk-YKWIZE5D.js";import{p as u,u as N}from"./chunk-LC7ZWLIH.js";import{b as o,d as y}from"./chunk-IZ7QOBSB.js";var E,p=o(()=>{"use strict";(function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE",e[e.LOWMEMORY=2]="LOWMEMORY"})(E||(E={}))});function G(){let e=(L("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE")??"cumulative").toLowerCase();return e==="cumulative"?c:e==="delta"?s:e==="lowmemory"?l:(u.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),c)}function V(e){return e!=null?e===E.DELTA?s:e===E.LOWMEMORY?l:c:G()}function w(e){return e?.aggregationPreference??(()=>d)}var c,s,l,d,a,O=o(()=>{"use strict";I();D();p();B();N();c=()=>i.CUMULATIVE,s=e=>{switch(e){case t.COUNTER:case t.OBSERVABLE_COUNTER:case t.GAUGE:case t.HISTOGRAM:case t.OBSERVABLE_GAUGE:return i.DELTA;case t.UP_DOWN_COUNTER:case t.OBSERVABLE_UP_DOWN_COUNTER:return i.CUMULATIVE}},l=e=>{switch(e){case t.COUNTER:case t.HISTOGRAM:return i.DELTA;case t.GAUGE:case t.UP_DOWN_COUNTER:case t.OBSERVABLE_UP_DOWN_COUNTER:case t.OBSERVABLE_COUNTER:case t.OBSERVABLE_GAUGE:return i.CUMULATIVE}};d=Object.freeze({type:M.DEFAULT});a=class extends R{_aggregationTemporalitySelector;_aggregationSelector;constructor(r,m){super(r),this._aggregationSelector=w(m),this._aggregationTemporalitySelector=V(m?.temporalityPreference)}selectAggregation(r){return this._aggregationSelector(r)}selectAggregationTemporality(r){return this._aggregationTemporalitySelector(r)}}});var _,C=o(()=>{"use strict";_="otlp_http_metric_exporter"});var T,P=o(()=>{"use strict";O();h();v();C();T=class extends a{_url;constructor(r){super(U(S(r??{},"METRICS","v1/metrics",{"Content-Type":"application/json"}),g,_,n,r?.selfObsMeterProvider),r),this._url=r?.url}setSelfObsMeterProvider(r){this.setMetrics(A(_,n,this._url,r))}}});var f=o(()=>{"use strict";P()});var x=o(()=>{"use strict";f()});var H={};y(H,{AggregationTemporalityPreference:()=>E,CumulativeTemporalitySelector:()=>c,DeltaTemporalitySelector:()=>s,LowMemoryTemporalitySelector:()=>l,OTLPMetricExporter:()=>T,OTLPMetricExporterBase:()=>a});var W=o(()=>{x();p();O()});export{E as a,c as b,s as c,l as d,a as e,T as f,H as g,W as h};
|
|
@@ -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{
|
|
4
|
+
import{f as d,m as f,o as y,s as l}from"./chunk-44LPRRYU.js";var S=d({module:"mcp"}),u="mcp__",p="__";function a(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}function M(e){return u+a(e)+p}function g(e,t){return M(e)+a(t)}var T=class{name;description;category="command";deferred=!0;mcpServerName;client;originalName;inputSchema;constructor(t,r,n){this.name=g(r,n.name),this.description=n.description,this.originalName=n.name,this.client=t,this.inputSchema=n.inputSchema,this.mcpServerName=r}mcpInputSchema(){return this.inputSchema??{}}setDeferLoading(t){this.deferred=t}schema(){return{name:this.name,description:this.description,input_schema:this.inputSchema}}async execute(t,r){try{return await this.client.callTool(this.originalName,r,t.abortSignal)}catch(n){return S.error({err:n},"mcp operation failed"),{output:`MCP tool error: ${y(n)}`,isError:!0}}}};function P(e,t){if(t==="string"&&typeof e=="number"&&Number.isFinite(e))return String(e);if((t==="integer"||t==="number")&&typeof e=="string"){let r=e.trim();if(r===""||!(t==="integer"?/^[+-]?\d+$/:/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/).test(r))return e;let s=t==="integer"?Number.parseInt(r,10):Number.parseFloat(r);return Number.isFinite(s)?s:e}if(t==="boolean"&&typeof e=="string"){let r=e.trim().toLowerCase();if(r==="true")return!0;if(r==="false")return!1}return e}function h(e,t){if(typeof t!="object"||t===null)return e;let r=f(t),n=l(r,"type","");if(n==="object"&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let s=f(r.properties??{}),o={};for(let[i,c]of Object.entries(e))o[i]=i in s?h(c,s[i]):c;return o}if(n==="array"){let s=r.items??{},o=e;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Object.values(o);i.length===1&&Array.isArray(i[0])&&(o=i[0])}else typeof o=="string"&&(o=o.split(",").map(i=>i.trim()).filter(i=>i!==""));return Array.isArray(o)?o.map(i=>h(i,s)):o}return n!==""?P(e,n):e}function A(e,t){if(t.startsWith(u)){let r=t.slice(u.length),n=r.indexOf(p);if(n>=0)return a(r.slice(0,n))+p+a(r.slice(n+p.length))}return a(e)+p+a(t)}function b(e){return"mcpInputSchema"in e&&typeof e.mcpInputSchema=="function"}var C=class{constructor(t){this.registry=t}registry;name="McpCall";description="Invoke a tool on a connected MCP server. Call ToolSearch first to load the tool's schema, then pass its arguments here exactly as that schema requires, using the same JSON types.";category="command";deferred=!1;schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{server:{type:"string",description:"MCP server name, e.g. 'linear'."},tool:{type:"string",description:"Full tool name as returned by ToolSearch, e.g. 'mcp__linear__create_issue'."},arguments:{type:"object",description:"The target tool's arguments. Must match that tool's input_schema exactly, including JSON types: bare numbers for integer fields, bare true/false for boolean fields, quoted strings for string fields, and plain JSON arrays for array fields."}},required:["server","tool","arguments"]}}}resolveTarget(t){let r=l(t,"server"),n=l(t,"tool");if(!r||!n)return;let s=n.startsWith(u)?n:g(r,n),o=this.registry.get(s);return o&&b(o)&&a(o.mcpServerName)===a(r)?o:void 0}availableNames(){return this.registry.listTools().filter(t=>t.name.startsWith(u)).map(t=>t.name).sort()}async execute(t,r){let n=l(r,"server",""),s=l(r,"tool","");if(s==="")return{output:"McpCall requires a 'tool' name",isError:!0};let o=this.resolveTarget(r);if(!o){let c=this.availableNames(),m=c.length>0?c.join(", "):"(none connected)";return{output:`Unknown MCP tool '${s}' on server '${n}'. Available tools: ${m}`,isError:!0}}if(typeof r.arguments!="object"||r.arguments===null||Array.isArray(r.arguments))return{output:"McpCall requires an 'arguments' object matching the target schema",isError:!0};let i=f(r.arguments);if(b(o)){let c=o.mcpInputSchema();if(Object.keys(c).length>0){let m=h(i,c);typeof m=="object"&&m!==null&&!Array.isArray(m)&&(i=f(m))}}return t.abortSignal?.throwIfAborted(),o.execute(t,i)}};export{u as a,T as b,A as c,b as d,C as e};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{a as t,c as O,e as o,o as p,q as P,s as T,t as E,v as s}from"./chunk-G2TE2QZM.js";O();P();s();var _="otlp_http_span_exporter";var r=class extends t{constructor(e={}){super(T(E(e,"TRACES","v1/traces",{"Content-Type":"application/json"}),p,_,o,e.selfObsMeterProvider))}};export{r as a};
|