@soba-so/worker 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form, made
34
+ available under the License, as indicated by a copyright notice that is included
35
+ in or attached to the work (an example is provided in the Appendix below).
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work
47
+ by the copyright owner or by an individual or Legal Entity authorized to submit
48
+ on behalf of the copyright owner. For the purposes of this definition,
49
+ "submitted" means any form of electronic, verbal, or written communication sent
50
+ to the Licensor or its representatives, including but not limited to
51
+ communication on electronic mailing lists, source code control systems, and
52
+ issue tracking systems that are managed by, or on behalf of, the Licensor for
53
+ the purpose of discussing and improving the Work, but excluding communication
54
+ that is conspicuously marked or otherwise designated in writing by the copyright
55
+ owner as "Not a Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License.
62
+
63
+ Subject to the terms and conditions of this License, each Contributor hereby
64
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
65
+ irrevocable copyright license to reproduce, prepare Derivative Works of,
66
+ publicly display, publicly perform, sublicense, and distribute the Work and such
67
+ Derivative Works in Source or Object form.
68
+
69
+ 3. Grant of Patent License.
70
+
71
+ Subject to the terms and conditions of this License, each Contributor hereby
72
+ grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
73
+ irrevocable (except as stated in this section) patent license to make, have
74
+ made, use, offer to sell, sell, import, and otherwise transfer the Work, where
75
+ such license applies only to those patent claims licensable by such Contributor
76
+ that are necessarily infringed by their Contribution(s) alone or by combination
77
+ of their Contribution(s) with the Work to which such Contribution(s) was
78
+ submitted. If You institute patent litigation against any entity (including a
79
+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a
80
+ Contribution incorporated within the Work constitutes direct or contributory
81
+ patent infringement, then any patent licenses granted to You under this License
82
+ for that Work shall terminate as of the date such litigation is filed.
83
+
84
+ 4. Redistribution.
85
+
86
+ You may reproduce and distribute copies of the Work or Derivative Works thereof
87
+ in any medium, with or without modifications, and in Source or Object form,
88
+ provided that You meet the following conditions:
89
+
90
+ You must give any other recipients of the Work or Derivative Works a copy of
91
+ this License; and
92
+ You must cause any modified files to carry prominent notices stating that You
93
+ changed the files; and
94
+ You must retain, in the Source form of any Derivative Works that You distribute,
95
+ all copyright, patent, trademark, and attribution notices from the Source form
96
+ of the Work, excluding those notices that do not pertain to any part of the
97
+ Derivative Works; and
98
+ If the Work includes a "NOTICE" text file as part of its distribution, then any
99
+ Derivative Works that You distribute must include a readable copy of the
100
+ attribution notices contained within such NOTICE file, excluding those notices
101
+ that do not pertain to any part of the Derivative Works, in at least one of the
102
+ following places: within a NOTICE text file distributed as part of the
103
+ Derivative Works; within the Source form or documentation, if provided along
104
+ with the Derivative Works; or, within a display generated by the Derivative
105
+ Works, if and wherever such third-party notices normally appear. The contents of
106
+ the NOTICE file are for informational purposes only and do not modify the
107
+ License. You may add Your own attribution notices within Derivative Works that
108
+ You distribute, alongside or as an addendum to the NOTICE text from the Work,
109
+ provided that such additional attribution notices cannot be construed as
110
+ modifying the License.
111
+ You may add Your own copyright statement to Your modifications and may provide
112
+ additional or different license terms and conditions for use, reproduction, or
113
+ distribution of Your modifications, or for any such Derivative Works as a whole,
114
+ provided Your use, reproduction, and distribution of the Work otherwise complies
115
+ with the conditions stated in this License.
116
+
117
+ 5. Submission of Contributions.
118
+
119
+ Unless You explicitly state otherwise, any Contribution intentionally submitted
120
+ for inclusion in the Work by You to the Licensor shall be under the terms and
121
+ conditions of this License, without any additional terms or conditions.
122
+ Notwithstanding the above, nothing herein shall supersede or modify the terms of
123
+ any separate license agreement you may have executed with Licensor regarding
124
+ such Contributions.
125
+
126
+ 6. Trademarks.
127
+
128
+ This License does not grant permission to use the trade names, trademarks,
129
+ service marks, or product names of the Licensor, except as required for
130
+ reasonable and customary use in describing the origin of the Work and
131
+ reproducing the content of the NOTICE file.
132
+
133
+ 7. Disclaimer of Warranty.
134
+
135
+ Unless required by applicable law or agreed to in writing, Licensor provides the
136
+ Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
137
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
138
+ including, without limitation, any warranties or conditions of TITLE,
139
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
140
+ solely responsible for determining the appropriateness of using or
141
+ redistributing the Work and assume any risks associated with Your exercise of
142
+ permissions under this License.
143
+
144
+ 8. Limitation of Liability.
145
+
146
+ In no event and under no legal theory, whether in tort (including negligence),
147
+ contract, or otherwise, unless required by applicable law (such as deliberate
148
+ and grossly negligent acts) or agreed to in writing, shall any Contributor be
149
+ liable to You for damages, including any direct, indirect, special, incidental,
150
+ or consequential damages of any character arising as a result of this License or
151
+ out of the use or inability to use the Work (including but not limited to
152
+ damages for loss of goodwill, work stoppage, computer failure or malfunction, or
153
+ any and all other commercial damages or losses), even if such Contributor has
154
+ been advised of the possibility of such damages.
155
+
156
+ 9. Accepting Warranty or Additional Liability.
157
+
158
+ While redistributing the Work or Derivative Works thereof, You may choose to
159
+ offer, and charge a fee for, acceptance of support, warranty, indemnity, or
160
+ other liability obligations and/or rights consistent with this License. However,
161
+ in accepting such obligations, You may act only on Your own behalf and on Your
162
+ sole responsibility, not on behalf of any other Contributor, and only if You
163
+ agree to indemnify, defend, and hold each Contributor harmless for any liability
164
+ incurred by, or claims asserted against, such Contributor by reason of your
165
+ accepting any such warranty or additional liability.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ APPENDIX: How to apply the Apache License to your work
170
+
171
+ To apply the Apache License to your work, attach the following boilerplate
172
+ notice, with the fields enclosed by brackets "[]" replaced with your own
173
+ identifying information. (Don't include the brackets!) The text should be
174
+ enclosed in the appropriate comment syntax for the file format. We also
175
+ recommend that a file or class name and description of purpose be included on
176
+ the same "printed page" as the copyright notice for easier identification within
177
+ third-party archives.
178
+
179
+ Copyright [yyyy] [name of copyright owner]
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # @soba-so/worker
2
+
3
+ Run agent jobs on your own machine, on the AI subscription you already pay for.
4
+
5
+ This is the half of [Soba](https://soba.so) that runs where you are. An app asks
6
+ for a run; your machine answers it with Claude Code, Codex or a local model,
7
+ signed in as you, under your own agreement with that provider. The app gets the
8
+ answer and never the account that produced it.
9
+
10
+ ```sh
11
+ npx @soba-so/worker login --broker https://soba.so/c/pk_soba_<your app's connect key>
12
+ ```
13
+
14
+ ```text
15
+ Your code: ACDE-F234
16
+ Approve at: https://soba.so/link
17
+
18
+ Press Enter to open that in your browser (or n to skip)…
19
+ [soba] waiting for you to approve…
20
+ [soba] paired. The token is in ~/.soba/worker.json (0600) — it was never shown or pasted.
21
+ [soba] starting. Run `soba-worker install` to keep it running after you close this.
22
+ ```
23
+
24
+ That is the device authorization grant (RFC 8628), the shape `gh auth login`
25
+ uses. The credential is never displayed and never pasted, and you approve in a
26
+ browser where you are already signed in to the app you are connecting — which
27
+ is also the only place you can judge what you are approving.
28
+
29
+ ## What it will and will not do
30
+
31
+ Everything a run may touch on this machine is bounded by a file you write, and
32
+ we never write it: `~/.soba/policy.json`. The rule is one line:
33
+
34
+ ```
35
+ resolved = machine grant ∩ broker request
36
+ ```
37
+
38
+ An app can ask for less than you granted. It can never ask for more. Refusing to
39
+ start on a policy file it cannot parse is deliberate — a machine grant that
40
+ silently falls back to a default is not a grant.
41
+
42
+ `permissionMode: "ask"` sends anything outside `allowTools` to an approver, and
43
+ every failure path denies: no terminal, no approver, a timeout, a malformed
44
+ answer. An approval channel that opens on failure is worse than none, because it
45
+ reads as protection while granting everything.
46
+
47
+ ## Keeping it running
48
+
49
+ ```sh
50
+ soba-worker install # launchd on macOS, systemd on Linux
51
+ soba-worker service-status
52
+ soba-worker --status # runtimes and the service, in one report
53
+ ```
54
+
55
+ Windows has no service path here. Use [Soba Connect](https://soba.so/soba-connect),
56
+ which carries this worker inside it and runs as a login item.
57
+
58
+ ## What it needs
59
+
60
+ Node 22 or newer, and whichever agent CLI you want it to use, installed and
61
+ signed in. Nothing else: this package has no dependencies, because everything it
62
+ uses is bundled into one file.
63
+
64
+ Full documentation: [soba.so/docs](https://soba.so/docs). What ships today, and
65
+ what does not: [soba.so/changelog](https://soba.so/changelog).
66
+
67
+ ---
68
+
69
+ Claude Code, Codex, Gemini CLI and Ollama are the products of their respective
70
+ owners. Soba is an independent tool, not affiliated with or endorsed by any of
71
+ them, and each run stays on a machine dedicated to one user, signed in with that
72
+ user's own account and under that provider's terms.
73
+
74
+ © 2026 Soba. All rights reserved.
@@ -0,0 +1,384 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __sobaCreateRequire } from 'node:module';
3
+ import { fileURLToPath as __sobaFileURLToPath } from 'node:url';
4
+ import { dirname as __sobaDirname } from 'node:path';
5
+ const require = __sobaCreateRequire(import.meta.url);
6
+ const __filename = __sobaFileURLToPath(import.meta.url);
7
+ const __dirname = __sobaDirname(__filename);
8
+ var _s=Object.create;var Xt=Object.defineProperty;var ws=Object.getOwnPropertyDescriptor;var vs=Object.getOwnPropertyNames;var bs=Object.getPrototypeOf,ks=Object.prototype.hasOwnProperty;var w=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var x=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var xs=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of vs(e))!ks.call(t,s)&&s!==r&&Xt(t,s,{get:()=>e[s],enumerable:!(n=ws(e,s))||n.enumerable});return t};var U=(t,e,r)=>(r=t!=null?_s(bs(t)):{},xs(e||!t||!t.__esModule?Xt(r,"default",{value:t,enumerable:!0}):r,t));var L=x((Vl,Vr)=>{"use strict";var qr=["nodebuffer","arraybuffer","fragments"],Hr=typeof Blob<"u";Hr&&qr.push("blob");Vr.exports={BINARY_TYPES:qr,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Hr,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ge=x((Kl,De)=>{"use strict";var{EMPTY_BUFFER:$o}=L(),bt=Buffer[Symbol.species];function Bo(t,e){if(t.length===0)return $o;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let s=0;s<t.length;s++){let o=t[s];r.set(o,n),n+=o.length}return n<e?new bt(r.buffer,r.byteOffset,n):r}function Kr(t,e,r,n,s){for(let o=0;o<s;o++)r[n+o]=t[o]^e[o&3]}function zr(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function Do(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function kt(t){if(kt.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new bt(t):ArrayBuffer.isView(t)?e=new bt(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),kt.readOnly=!1),e}De.exports={concat:Bo,mask:Kr,toArrayBuffer:Do,toBuffer:kt,unmask:zr};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=w("bufferutil");De.exports.mask=function(e,r,n,s,o){o<48?Kr(e,r,n,s,o):t.mask(e,r,n,s,o)},De.exports.unmask=function(e,r){e.length<32?zr(e,r):t.unmask(e,r)}}catch{}});var Xr=x((zl,Yr)=>{"use strict";var Jr=Symbol("kDone"),xt=Symbol("kRun"),St=class{constructor(e){this[Jr]=()=>{this.pending--,this[xt]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[xt]()}[xt](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Jr])}}};Yr.exports=St});var te=x((Jl,tn)=>{"use strict";var ye=w("zlib"),Zr=ge(),Uo=Xr(),{kStatusCode:Qr}=L(),jo=Buffer[Symbol.species],Fo=Buffer.from([0,0,255,255]),je=Symbol("permessage-deflate"),$=Symbol("total-length"),Q=Symbol("callback"),W=Symbol("buffers"),ee=Symbol("error"),Ue,Et=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Ue){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ue=new Uo(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Q];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(s=>!(r.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>s.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&(typeof s.client_max_window_bits=="number"?r.clientMaxWindowBits>s.client_max_window_bits:!s.client_max_window_bits)));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let s=r[n];if(s.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(s=s[0],n==="client_max_window_bits"){if(s!==!0){let o=+s;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else if(n==="server_max_window_bits"){let o=+s;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${n}": ${s}`);s=o}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${s}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=s})}),e}decompress(e,r,n){Ue.add(s=>{this._decompress(e,r,(o,i)=>{s(),n(o,i)})})}compress(e,r,n){Ue.add(s=>{this._compress(e,r,(o,i)=>{s(),n(o,i)})})}_decompress(e,r,n){let s=this._isServer?"client":"server";if(!this._inflate){let o=`${s}_max_window_bits`,i=typeof this.params[o]!="number"?ye.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=ye.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[je]=this,this._inflate[$]=0,this._inflate[W]=[],this._inflate.on("error",Go),this._inflate.on("data",en)}this._inflate[Q]=n,this._inflate.write(e),r&&this._inflate.write(Fo),this._inflate.flush(()=>{let o=this._inflate[ee];if(o){this._inflate.close(),this._inflate=null,n(o);return}let i=Zr.concat(this._inflate[W],this._inflate[$]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[$]=0,this._inflate[W]=[],r&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),n(null,i)})}_compress(e,r,n){let s=this._isServer?"server":"client";if(!this._deflate){let o=`${s}_max_window_bits`,i=typeof this.params[o]!="number"?ye.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=ye.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[$]=0,this._deflate[W]=[],this._deflate.on("data",Wo)}this._deflate[Q]=n,this._deflate.write(e),this._deflate.flush(ye.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Zr.concat(this._deflate[W],this._deflate[$]);r&&(o=new jo(o.buffer,o.byteOffset,o.length-4)),this._deflate[Q]=null,this._deflate[$]=0,this._deflate[W]=[],r&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),n(null,o)})}};tn.exports=Et;function Wo(t){this[W].push(t),this[$]+=t.length}function en(t){if(this[$]+=t.length,this[je]._maxPayload<1||this[$]<=this[je]._maxPayload){this[W].push(t);return}this[ee]=new RangeError("Max payload size exceeded"),this[ee].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ee][Qr]=1009,this.removeListener("data",en),this.reset()}function Go(t){if(this[je]._inflate=null,this[ee]){this[Q](this[ee]);return}t[Qr]=1007,this[Q](t)}});var re=x((Yl,Fe)=>{"use strict";var{isUtf8:rn}=w("buffer"),{hasBlob:qo}=L(),Ho=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Vo(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Tt(t){let e=t.length,r=0;for(;r<e;)if(!(t[r]&128))r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Ko(t){return qo&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Fe.exports={isBlob:Ko,isValidStatusCode:Vo,isValidUTF8:Tt,tokenChars:Ho};if(rn)Fe.exports.isValidUTF8=function(t){return t.length<24?Tt(t):rn(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=w("utf-8-validate");Fe.exports.isValidUTF8=function(e){return e.length<32?Tt(e):t(e)}}catch{}});var Pt=x((Xl,un)=>{"use strict";var{Writable:zo}=w("stream"),nn=te(),{BINARY_TYPES:Jo,EMPTY_BUFFER:sn,kStatusCode:Yo,kWebSocket:Xo}=L(),{concat:Rt,toArrayBuffer:Zo,unmask:Qo}=ge(),{isValidStatusCode:ei,isValidUTF8:on}=re(),We=Buffer[Symbol.species],R=0,an=1,cn=2,ln=3,Ct=4,At=5,Ge=6,Ot=class extends zo{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Jo[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Xo]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=R}_write(e,r,n){if(this._opcode===8&&this._state==R)return n();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){n(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new We(n.buffer,n.byteOffset+e,n.length-e),new We(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],s=r.length-e;e>=n.length?r.set(this._buffers.shift(),s):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),s),this._buffers[0]=new We(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case R:this.getInfo(e);break;case an:this.getPayloadLength16(e);break;case cn:this.getPayloadLength64(e);break;case ln:this.getMask();break;case Ct:this.getData(e);break;case At:case Ge:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if(r[0]&48){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let n=(r[0]&64)===64;if(n&&!this._extensions[nn.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(n){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=an:this._payloadLength===127?this._state=cn:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=ln:this._state=Ct}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ct}getData(e){let r=sn;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&Qo(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let n=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(n);return}if(this._compressed){this._state=At,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[nn.extensionName].decompress(e,this._fin,(s,o)=>{if(s)return r(s);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(o)}this.dataMessage(r),this._state===R&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=R;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Rt(n,r):this._binaryType==="arraybuffer"?s=Zo(Rt(n,r)):this._binaryType==="blob"?s=new Blob(n):s=n,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=R):(this._state=Ge,setImmediate(()=>{this.emit("message",s,!0),this._state=R,this.startLoop(e)}))}else{let s=Rt(n,r);if(!this._skipUTF8Validation&&!on(s)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===At||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=R):(this._state=Ge,setImmediate(()=>{this.emit("message",s,!1),this._state=R,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,sn),this.end();else{let n=e.readUInt16BE(0);if(!ei(n)){let o=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(o);return}let s=new We(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!on(s)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(o);return}this._loop=!1,this.emit("conclude",n,s),this.end()}this._state=R;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=R):(this._state=Ge,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=R,this.startLoop(r)}))}createError(e,r,n,s,o){this._loop=!1,this._errored=!0;let i=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=o,i[Yo]=s,i}};un.exports=Ot});var Nt=x((Ql,fn)=>{"use strict";var{Duplex:Zl}=w("stream"),{randomFillSync:ti}=w("crypto"),{types:{isUint8Array:ri}}=w("util"),dn=te(),{EMPTY_BUFFER:ni,kWebSocket:si,NOOP:oi}=L(),{isBlob:ne,isValidStatusCode:ii}=re(),{mask:pn,toBuffer:H}=ge(),C=Symbol("kByteLength"),ai=Buffer.alloc(4),qe=8*1024,V,se=qe,A=0,ci=1,li=2,It=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=A,this.onerror=oi,this[si]=void 0}static frame(e,r){let n,s=!1,o=2,i=!1;r.mask&&(n=r.maskBuffer||ai,r.generateMask?r.generateMask(n):(se===qe&&(V===void 0&&(V=Buffer.alloc(qe)),ti(V,0,qe),se=0),n[0]=V[se++],n[1]=V[se++],n[2]=V[se++],n[3]=V[se++]),i=(n[0]|n[1]|n[2]|n[3])===0,o=6);let a;typeof e=="string"?(!r.mask||i)&&r[C]!==void 0?a=r[C]:(e=Buffer.from(e),a=e.length):(a=e.length,s=r.mask&&r.readOnly&&!i);let l=a;a>=65536?(o+=8,l=127):a>125&&(o+=2,l=126);let c=Buffer.allocUnsafe(s?a+o:o);return c[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),r.mask?(c[1]|=128,c[o-4]=n[0],c[o-3]=n[1],c[o-2]=n[2],c[o-1]=n[3],i?[c,e]:s?(pn(e,n,c,o,a),[c]):(pn(e,n,e,0,a),[c,e])):[c,e]}close(e,r,n,s){let o;if(e===void 0)o=ni;else{if(typeof e!="number"||!ii(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof r=="string")o.write(r,2);else if(ri(r))o.set(r,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[C]:o.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==A?this.enqueue([this.dispatch,o,!1,i,s]):this.sendFrame(t.frame(o,i),s)}ping(e,r,n){let s,o;if(typeof e=="string"?(s=Buffer.byteLength(e),o=!1):ne(e)?(s=e.size,o=!1):(e=H(e),s=e.length,o=H.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[C]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};ne(e)?this._state!==A?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==A?this.enqueue([this.dispatch,e,!1,i,n]):this.sendFrame(t.frame(e,i),n)}pong(e,r,n){let s,o;if(typeof e=="string"?(s=Buffer.byteLength(e),o=!1):ne(e)?(s=e.size,o=!1):(e=H(e),s=e.length,o=H.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[C]:s,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};ne(e)?this._state!==A?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==A?this.enqueue([this.dispatch,e,!1,i,n]):this.sendFrame(t.frame(e,i),n)}send(e,r,n){let s=this._extensions[dn.extensionName],o=r.binary?2:1,i=r.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):ne(e)?(a=e.size,l=!1):(e=H(e),a=e.length,l=H.readOnly),this._firstFragment?(this._firstFragment=!1,i&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=s._threshold),this._compress=i):(i=!1,o=0),r.fin&&(this._firstFragment=!0);let c={[C]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:l,rsv1:i};ne(e)?this._state!==A?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):this._state!==A?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(e,r,n,s){this._bufferedBytes+=n[C],this._state=li,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Mt,this,a,s);return}this._bufferedBytes-=n[C];let i=H(o);r?this.dispatch(i,r,n,s):(this._state=A,this.sendFrame(t.frame(i,n),s),this.dequeue())}).catch(o=>{process.nextTick(ui,this,o,s)})}dispatch(e,r,n,s){if(!r){this.sendFrame(t.frame(e,n),s);return}let o=this._extensions[dn.extensionName];this._bufferedBytes+=n[C],this._state=ci,o.compress(e,n.fin,(i,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Mt(this,l,s);return}this._bufferedBytes-=n[C],this._state=A,n.readOnly=!1,this.sendFrame(t.frame(a,n),s),this.dequeue()})}dequeue(){for(;this._state===A&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][C],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][C],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};fn.exports=It;function Mt(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let s=t._queue[n],o=s[s.length-1];typeof o=="function"&&o(e)}}function ui(t,e,r){Mt(t,e,r),t.onerror(e)}});var kn=x((eu,bn)=>{"use strict";var{kForOnEventAttribute:_e,kListener:Lt}=L(),hn=Symbol("kCode"),mn=Symbol("kData"),gn=Symbol("kError"),yn=Symbol("kMessage"),_n=Symbol("kReason"),oe=Symbol("kTarget"),wn=Symbol("kType"),vn=Symbol("kWasClean"),B=class{constructor(e){this[oe]=null,this[wn]=e}get target(){return this[oe]}get type(){return this[wn]}};Object.defineProperty(B.prototype,"target",{enumerable:!0});Object.defineProperty(B.prototype,"type",{enumerable:!0});var K=class extends B{constructor(e,r={}){super(e),this[hn]=r.code===void 0?0:r.code,this[_n]=r.reason===void 0?"":r.reason,this[vn]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[hn]}get reason(){return this[_n]}get wasClean(){return this[vn]}};Object.defineProperty(K.prototype,"code",{enumerable:!0});Object.defineProperty(K.prototype,"reason",{enumerable:!0});Object.defineProperty(K.prototype,"wasClean",{enumerable:!0});var ie=class extends B{constructor(e,r={}){super(e),this[gn]=r.error===void 0?null:r.error,this[yn]=r.message===void 0?"":r.message}get error(){return this[gn]}get message(){return this[yn]}};Object.defineProperty(ie.prototype,"error",{enumerable:!0});Object.defineProperty(ie.prototype,"message",{enumerable:!0});var we=class extends B{constructor(e,r={}){super(e),this[mn]=r.data===void 0?null:r.data}get data(){return this[mn]}};Object.defineProperty(we.prototype,"data",{enumerable:!0});var di={addEventListener(t,e,r={}){for(let s of this.listeners(t))if(!r[_e]&&s[Lt]===e&&!s[_e])return;let n;if(t==="message")n=function(o,i){let a=new we("message",{data:i?o:o.toString()});a[oe]=this,He(e,this,a)};else if(t==="close")n=function(o,i){let a=new K("close",{code:o,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[oe]=this,He(e,this,a)};else if(t==="error")n=function(o){let i=new ie("error",{error:o,message:o.message});i[oe]=this,He(e,this,i)};else if(t==="open")n=function(){let o=new B("open");o[oe]=this,He(e,this,o)};else return;n[_e]=!!r[_e],n[Lt]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Lt]===e&&!r[_e]){this.removeListener(t,r);break}}};bn.exports={CloseEvent:K,ErrorEvent:ie,Event:B,EventTarget:di,MessageEvent:we};function He(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Ve=x((tu,xn)=>{"use strict";var{tokenChars:ve}=re();function P(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function pi(t){let e=Object.create(null),r=Object.create(null),n=!1,s=!1,o=!1,i,a,l=-1,c=-1,d=-1,u=0;for(;u<t.length;u++)if(c=t.charCodeAt(u),i===void 0)if(d===-1&&ve[c]===1)l===-1&&(l=u);else if(u!==0&&(c===32||c===9))d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let h=t.slice(l,d);c===44?(P(e,h,r),r=Object.create(null)):i=h,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&ve[c]===1)l===-1&&(l=u);else if(c===32||c===9)d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),P(r,t.slice(l,d),!0),c===44&&(P(e,i,r),r=Object.create(null),i=void 0),l=d=-1}else if(c===61&&l!==-1&&d===-1)a=t.slice(l,u),l=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(ve[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1?l=u:n||(n=!0),s=!1}else if(o)if(ve[c]===1)l===-1&&(l=u);else if(c===34&&l!==-1)o=!1,d=u;else if(c===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===34&&t.charCodeAt(u-1)===61)o=!0;else if(d===-1&&ve[c]===1)l===-1&&(l=u);else if(l!==-1&&(c===32||c===9))d===-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let h=t.slice(l,d);n&&(h=h.replace(/\\/g,""),n=!1),P(r,a,h),c===44&&(P(e,i,r),r=Object.create(null),i=void 0),a=void 0,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(l===-1||o||c===32||c===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let f=t.slice(l,d);return i===void 0?P(e,f,r):(a===void 0?P(r,f,!0):n?P(r,a,f.replace(/\\/g,"")):P(r,a,f),P(e,i,r)),e}function fi(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(s=>{let o=n[s];return Array.isArray(o)||(o=[o]),o.map(i=>i===!0?s:`${s}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}xn.exports={format:fi,parse:pi}});var Ye=x((su,Ln)=>{"use strict";var hi=w("events"),mi=w("https"),gi=w("http"),Tn=w("net"),yi=w("tls"),{randomBytes:_i,createHash:wi}=w("crypto"),{Duplex:ru,Readable:nu}=w("stream"),{URL:$t}=w("url"),G=te(),vi=Pt(),bi=Nt(),{isBlob:ki}=re(),{BINARY_TYPES:Sn,CLOSE_TIMEOUT:xi,EMPTY_BUFFER:Ke,GUID:Si,kForOnEventAttribute:Bt,kListener:Ei,kStatusCode:Ti,kWebSocket:v,NOOP:Rn}=L(),{EventTarget:{addEventListener:Ri,removeEventListener:Ci}}=kn(),{format:Ai,parse:Oi}=Ve(),{toBuffer:Pi}=ge(),Cn=Symbol("kAborted"),Dt=[8,13],D=["CONNECTING","OPEN","CLOSING","CLOSED"],Ii=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_=class t extends hi{constructor(e,r,n){super(),this._binaryType=Sn[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ke,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),An(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Sn.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let s=new vi({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),o=new bi(e,this._extensions,n.generateMask);this._receiver=s,this._sender=o,this._socket=e,s[v]=this,o[v]=this,e[v]=this,s.on("conclude",Li),s.on("drain",$i),s.on("error",Bi),s.on("message",Di),s.on("ping",Ui),s.on("pong",ji),o.onerror=Fi,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",In),e.on("data",Je),e.on("end",Mn),e.on("error",Nn),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[G.extensionName]&&this._extensions[G.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){S(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Pn(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ut(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Ke,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ut(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Ke,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Ut(this,e,n);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[G.extensionName]||(s.compress=!1),this._sender.send(e||Ke,s,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){S(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(_,"CONNECTING",{enumerable:!0,value:D.indexOf("CONNECTING")});Object.defineProperty(_.prototype,"CONNECTING",{enumerable:!0,value:D.indexOf("CONNECTING")});Object.defineProperty(_,"OPEN",{enumerable:!0,value:D.indexOf("OPEN")});Object.defineProperty(_.prototype,"OPEN",{enumerable:!0,value:D.indexOf("OPEN")});Object.defineProperty(_,"CLOSING",{enumerable:!0,value:D.indexOf("CLOSING")});Object.defineProperty(_.prototype,"CLOSING",{enumerable:!0,value:D.indexOf("CLOSING")});Object.defineProperty(_,"CLOSED",{enumerable:!0,value:D.indexOf("CLOSED")});Object.defineProperty(_.prototype,"CLOSED",{enumerable:!0,value:D.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(_.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Bt])return e[Ei];return null},set(e){for(let r of this.listeners(t))if(r[Bt]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Bt]:!0})}})});_.prototype.addEventListener=Ri;_.prototype.removeEventListener=Ci;Ln.exports=_;function An(t,e,r,n){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:xi,protocolVersion:Dt[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=s.autoPong,t._closeTimeout=s.closeTimeout,!Dt.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Dt.join(", ")})`);let o;if(e instanceof $t)o=e;else try{o=new $t(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let i=o.protocol==="wss:",a=o.protocol==="ws+unix:",l;if(o.protocol!=="ws:"&&!i&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?l="The URL's pathname is empty":o.hash&&(l="The URL contains a fragment identifier"),l){let m=new SyntaxError(l);if(t._redirects===0)throw m;ze(t,m);return}let c=i?443:80,d=_i(16).toString("base64"),u=i?mi.request:gi.request,f=new Set,h;if(s.createConnection=s.createConnection||(i?Ni:Mi),s.defaultPort=s.defaultPort||c,s.port=o.port||c,s.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=o.pathname+o.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(h=new G({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Ai({[G.extensionName]:h.offer()})),r.length){for(let m of r){if(typeof m!="string"||!Ii.test(m)||f.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(m)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(o.username||o.password)&&(s.auth=`${o.username}:${o.password}`),a){let m=s.path.split(":");s.socketPath=m[0],s.path=m[1]}let p;if(s.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=i,t._originalHostOrSocketPath=a?s.socketPath:o.host;let m=n&&n.headers;if(n={...n,headers:{}},m)for(let[g,y]of Object.entries(m))n.headers[g.toLowerCase()]=y}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?s.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!i)&&(delete s.headers.authorization,delete s.headers.cookie,m||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=t._req=u(s),t._redirects&&t.emit("redirect",t.url,p)}else p=t._req=u(s);s.timeout&&p.on("timeout",()=>{S(t,p,"Opening handshake has timed out")}),p.on("error",m=>{p===null||p[Cn]||(p=t._req=null,ze(t,m))}),p.on("response",m=>{let g=m.headers.location,y=m.statusCode;if(g&&s.followRedirects&&y>=300&&y<400){if(++t._redirects>s.maxRedirects){S(t,p,"Maximum redirects exceeded");return}p.abort();let le;try{le=new $t(g,e)}catch{let Y=new SyntaxError(`Invalid URL: ${g}`);ze(t,Y);return}An(t,le,r,n)}else t.emit("unexpected-response",p,m)||S(t,p,`Unexpected server response: ${m.statusCode}`)}),p.on("upgrade",(m,g,y)=>{if(t.emit("upgrade",m),t.readyState!==_.CONNECTING)return;p=t._req=null;let le=m.headers.upgrade;if(le===void 0||le.toLowerCase()!=="websocket"){S(t,g,"Invalid Upgrade header");return}let zt=wi("sha1").update(d+Si).digest("base64");if(m.headers["sec-websocket-accept"]!==zt){S(t,g,"Invalid Sec-WebSocket-Accept header");return}let Y=m.headers["sec-websocket-protocol"],ue;if(Y!==void 0?f.size?f.has(Y)||(ue="Server sent an invalid subprotocol"):ue="Server sent a subprotocol but none was requested":f.size&&(ue="Server sent no subprotocol"),ue){S(t,g,ue);return}Y&&(t._protocol=Y);let Jt=m.headers["sec-websocket-extensions"];if(Jt!==void 0){if(!h){S(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ot;try{ot=Oi(Jt)}catch{S(t,g,"Invalid Sec-WebSocket-Extensions header");return}let Yt=Object.keys(ot);if(Yt.length!==1||Yt[0]!==G.extensionName){S(t,g,"Server indicated an extension that was not requested");return}try{h.accept(ot[G.extensionName])}catch{S(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[G.extensionName]=h}t.setSocket(g,y,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxBufferedChunks:s.maxBufferedChunks,maxFragments:s.maxFragments,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(p,t):p.end()}function ze(t,e){t._readyState=_.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Mi(t){return t.path=t.socketPath,Tn.connect(t)}function Ni(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Tn.isIP(t.host)?"":t.host),yi.connect(t)}function S(t,e,r){t._readyState=_.CLOSING;let n=new Error(r);Error.captureStackTrace(n,S),e.setHeader?(e[Cn]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ze,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Ut(t,e,r){if(e){let n=ki(e)?e.size:Pi(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${D[t.readyState]})`);process.nextTick(r,n)}}function Li(t,e){let r=this[v];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[v]!==void 0&&(r._socket.removeListener("data",Je),process.nextTick(On,r._socket),t===1005?r.close():r.close(t,e))}function $i(){let t=this[v];t.isPaused||t._socket.resume()}function Bi(t){let e=this[v];e._socket[v]!==void 0&&(e._socket.removeListener("data",Je),process.nextTick(On,e._socket),e.close(t[Ti])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function En(){this[v].emitClose()}function Di(t,e){this[v].emit("message",t,e)}function Ui(t){let e=this[v];e._autoPong&&e.pong(t,!this._isServer,Rn),e.emit("ping",t)}function ji(t){this[v].emit("pong",t)}function On(t){t.resume()}function Fi(t){let e=this[v];e.readyState!==_.CLOSED&&(e.readyState===_.OPEN&&(e._readyState=_.CLOSING,Pn(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Pn(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function In(){let t=this[v];if(this.removeListener("close",In),this.removeListener("data",Je),this.removeListener("end",Mn),t._readyState=_.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[v]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",En),t._receiver.on("finish",En))}function Je(t){this[v]._receiver.write(t)||this.pause()}function Mn(){let t=this[v];t._readyState=_.CLOSING,t._receiver.end(),this.end()}function Nn(){let t=this[v];this.removeListener("error",Nn),this.on("error",Rn),t&&(t._readyState=_.CLOSING,this.destroy())}});var Un=x((iu,Dn)=>{"use strict";var ou=Ye(),{Duplex:Wi}=w("stream");function $n(t){t.emit("close")}function Gi(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Bn(t){this.removeListener("error",Bn),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function qi(t,e){let r=!0,n=new Wi({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,i){let a=!i&&n._readableState.objectMode?o.toString():o;n.push(a)||t.pause()}),t.once("error",function(o){n.destroyed||(r=!1,n.destroy(o))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(s,o){if(t.readyState===t.CLOSED){o(s),process.nextTick($n,n);return}let i=!1;t.once("error",function(l){i=!0,o(l)}),t.once("close",function(){i||o(s),process.nextTick($n,n)}),r&&t.terminate()},n._final=function(s){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(s)});return}t._socket!==null&&(t._socket._writableState.finished?(s(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){s()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(s,o,i){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(s,o,i)});return}t.send(s,i)},n.on("end",Gi),n.on("error",Bn),n}Dn.exports=qi});var jt=x((au,jn)=>{"use strict";var{tokenChars:Hi}=re();function Vi(t){let e=new Set,r=-1,n=-1,s=0;for(s;s<t.length;s++){let i=t.charCodeAt(s);if(n===-1&&Hi[i]===1)r===-1&&(r=s);else if(s!==0&&(i===32||i===9))n===-1&&r!==-1&&(n=s);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${s}`);n===-1&&(n=s);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(r,s);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}jn.exports={parse:Vi}});var Kn=x((lu,Vn)=>{"use strict";var Ki=w("events"),Xe=w("http"),{Duplex:cu}=w("stream"),{createHash:zi}=w("crypto"),Fn=Ve(),z=te(),Ji=jt(),Yi=Ye(),{CLOSE_TIMEOUT:Xi,GUID:Zi,kWebSocket:Qi}=L(),ea=/^[+/0-9A-Za-z]{22}==$/,Wn=0,Gn=1,Hn=2,Ft=class extends Ki{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Xi,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Yi,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Xe.createServer((n,s)=>{let o=Xe.STATUS_CODES[426];s.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),s.end(o)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=ta(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,o,i)=>{this.handleUpgrade(s,o,i,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Wn}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Hn){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(be,this);return}if(e&&this.once("close",e),this._state!==Gn)if(this._state=Gn,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(be,this):process.nextTick(be,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{be(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,s){r.on("error",qn);let o=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){J(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){J(this,e,r,400,"Invalid Upgrade header");return}if(o===void 0||!ea.test(o)){J(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){J(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ke(r,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Ji.parse(l)}catch{J(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let f=new z({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Fn.parse(d);h[z.extensionName]&&(f.accept(h[z.extensionName]),u[z.extensionName]=f)}catch{J(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(h,p,m,g)=>{if(!h)return ke(r,p||401,m,g);this.completeUpgrade(u,o,c,e,r,n,s)});return}if(!this.options.verifyClient(f))return ke(r,401)}this.completeUpgrade(u,o,c,e,r,n,s)}completeUpgrade(e,r,n,s,o,i,a){if(!o.readable||!o.writable)return o.destroy();if(o[Qi])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Wn)return ke(o,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${zi("sha1").update(r+Zi).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let u=this.options.handleProtocols?this.options.handleProtocols(n,s):n.values().next().value;u&&(c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[z.extensionName]){let u=e[z.extensionName].params,f=Fn.format({[z.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${f}`),d._extensions=e}this.emit("headers",c,s),o.write(c.concat(`\r
9
+ `).join(`\r
10
+ `)),o.removeListener("error",qn),d.setSocket(o,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(be,this)})),a(d,s)}};Vn.exports=Ft;function ta(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function be(t){t._state=Hn,t.emit("close")}function qn(){this.destroy()}function ke(t,e,r,n){r=r||Xe.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Xe.STATUS_CODES[e]}\r
11
+ `+Object.keys(n).map(s=>`${s}: ${n[s]}`).join(`\r
12
+ `)+`\r
13
+ \r
14
+ `+r)}function J(t,e,r,n,s,o){if(t.listenerCount("wsClientError")){let i=new Error(s);Error.captureStackTrace(i,J),t.emit("wsClientError",i,r,e)}else ke(r,n,s,o)}});import{readFileSync as Bs}from"node:fs";import Ds from"node:path";var Ss=["open-weights","frontier"];function Es(t){return Ss.includes(t)}function Te(t){return t==="user-hardware"||t==="user-subscription"||t==="open-weights"||t==="frontier"}function Zt(t){return!Es(t)}var er=2;function tr(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let r=e;switch(r.type){case"ready":return{type:"ready",protocol:rr(r.protocol),workerId:k(r.workerId)};case"error":return{type:"error",message:k(r.message)??"Unknown broker error"};case"cancel":return k(r.runId)?{type:"cancel",runId:r.runId}:null;case"approval_response":{let n=k(r.runId),s=k(r.approvalId);return!n||!s?null:{type:"approval_response",runId:n,approvalId:s,decision:r.decision==="allow"?"allow":"deny",reason:k(r.reason)}}case"tool_result":{let n=k(r.runId),s=k(r.callId);return!n||!s?null:{type:"tool_result",runId:n,callId:s,result:r.result,isError:r.isError===!0}}case"run":{let n=k(r.runId);if(!n)return null;let s=k(r.prompt),o=Ts(r.messages);return!s&&!o?.length?null:{type:"run",runId:n,prompt:s,messages:o,system:k(r.system),model:k(r.model),runtime:k(r.runtime),tools:Cs(r.tools),policy:r.policy&&typeof r.policy=="object"?r.policy:void 0,route:Rs(r.route)}}default:return null}}function k(t){return typeof t=="string"&&t.length>0?t:void 0}function rr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ts(t){if(!Array.isArray(t))return;let e=[];for(let r of t){if(!r||typeof r!="object")continue;let n=r,s=n.role==="assistant"?"assistant":n.role==="user"?"user":null,o=typeof n.content=="string"?n.content:null;s&&o!==null&&e.push({role:s,content:o})}return e.length?e:void 0}function Qt(t){if(Array.isArray(t))return t.filter(Te)}function Rs(t){if(!t||typeof t!="object")return;let e=t,r=Qt(e.prefer)??[],n=Array.isArray(e.allow),s=rr(e.maxCostMicros);if(!(!r.length&&!n&&s===void 0))return{prefer:r,...n?{allow:Qt(e.allow)??[]}:{},...s!==void 0?{maxCostMicros:s}:{}}}function Cs(t){if(!Array.isArray(t))return;let e=[];for(let r of t){if(!r||typeof r!="object")continue;let n=r,s=k(n.name);s&&e.push({name:s,description:k(n.description)??"",inputSchema:n.inputSchema&&typeof n.inputSchema=="object"?n.inputSchema:{type:"object"}})}return e.length?e:void 0}import{readFileSync as Os}from"node:fs";import{mkdir as Ps,realpath as cr}from"node:fs/promises";import Is from"node:os";import E from"node:path";var lr=Is.homedir(),b=process.env.SOBA_HOME??E.join(lr,".soba"),Re=process.env.SOBA_POLICY_FILE??E.join(b,"policy.json"),nr=E.join(b,"workspace");function sr(){return{roots:[nr],defaultCwd:nr,allowTools:["Read","Glob","Grep","WebSearch","WebFetch"],askTools:[],denyTools:[],maxConcurrency:2,maxTimeoutMs:6e5,permissionMode:"deny",allowRuntimes:[],allowAppTools:!0,allowMeteredKeys:!1,approver:"local"}}function at(t){return E.resolve(t.startsWith("~/")?E.join(lr,t.slice(2)):t)}function ur(){let t;try{t=Os(Re,"utf8")}catch{return sr()}let e;try{e=JSON.parse(t)}catch(o){throw new Error(`${Re} is not valid JSON \u2014 refusing to start: ${o.message}`)}let r=sr(),n=(e.roots?.length?e.roots:r.roots).map(at),s=at(e.defaultCwd??n[0]??r.defaultCwd);return{roots:n,defaultCwd:s,allowTools:e.allowTools??r.allowTools,askTools:e.askTools??r.askTools,denyTools:e.denyTools??r.denyTools,maxConcurrency:or(e.maxConcurrency,r.maxConcurrency,1,64),maxTimeoutMs:or(e.maxTimeoutMs,r.maxTimeoutMs,1e3,6*36e5),permissionMode:Ms(e.permissionMode)?e.permissionMode:r.permissionMode,allowRuntimes:e.allowRuntimes??r.allowRuntimes,allowAppTools:e.allowAppTools??r.allowAppTools,allowMeteredKeys:e.allowMeteredKeys??r.allowMeteredKeys,approver:Ns(e.approver)?e.approver:r.approver}}function or(t,e,r,n){return typeof t!="number"||!Number.isFinite(t)?e:Math.min(n,Math.max(r,Math.floor(t)))}function Ms(t){return t==="ask"||t==="deny"||t==="auto"}function Ns(t){return t==="local"||t==="remote"||t==="desktop"||t==="none"}var ir={deny:0,ask:1,auto:2};function ar(t,e){return ir[t??e]<ir[e]?t??e:e}async function dr(t,e){let r=t?.cwd?at(t.cwd):e.defaultCwd;if(r===e.defaultCwd)try{await Ps(e.defaultCwd,{recursive:!0})}catch{}if(!await Ls(r,e.roots))return{ok:!1,reason:`This machine doesn't allow runs in ${r}. Granted roots: ${e.roots.join(", ")}. Edit ${Re} to change that.`};let s=new Set([...e.denyTools,...t?.denyTools??[]].map(X)),o=t?.allowTools?.map(X),i=e.allowTools.filter(u=>{let f=X(u);return s.has(f)?!1:o?o.includes(f):!0}),a=t?.askTools?.map(X),l=new Set(i.map(X)),c=ar(t?.permissionMode,e.permissionMode)==="ask"&&e.approver!=="none"?e.askTools.filter(u=>{let f=X(u);return s.has(f)||l.has(f)?!1:a?a.includes(f):!0}):[],d=ar(t?.permissionMode,e.permissionMode);return{ok:!0,policy:{cwd:r,allowTools:i,askTools:c,denyTools:[...s],timeoutMs:Math.min(t?.timeoutMs??e.maxTimeoutMs,e.maxTimeoutMs),permissionMode:d,allowAppTools:e.allowAppTools,allowMeteredKeys:e.allowMeteredKeys,allowNetwork:t?.allowNetwork}}}function X(t){return t.toLowerCase()}async function Ls(t,e){let r=await $s(t);for(let n of e){let s;try{s=await cr(n)}catch{continue}let o=E.relative(s,r);if(o===""||!o.startsWith("..")&&!E.isAbsolute(o))return!0}return!1}async function $s(t){let e=E.resolve(t),r=[];for(;;)try{let n=await cr(e);return E.join(n,...r.reverse())}catch{let n=E.dirname(e);if(n===e)return E.resolve(t);r.push(E.basename(e)),e=n}}var ct=Re;var Ce=process.env.SOBA_ENDPOINTS_FILE??Ds.join(b,"models.json");function pr(){return[{id:"ollama",displayName:"Ollama",baseUrl:process.env.SOBA_OLLAMA_URL??"http://localhost:11434/v1",costClass:"user-hardware",provider:"ollama"}]}function Us(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.inputMicrosPerMTok=="number"&&typeof e.outputMicrosPerMTok=="number"}function de(){let t;try{t=Bs(Ce,"utf8")}catch{return pr()}let e;try{e=JSON.parse(t)}catch(o){throw new Error(`${Ce} is not valid JSON \u2014 refusing to start: ${o.message}`)}let r=Array.isArray(e)?e:Array.isArray(e?.endpoints)?e.endpoints:null;if(!r)throw new Error(`${Ce} must be an array of endpoints, or { "endpoints": [...] }.`);let n=[];for(let o of r){if(!o||typeof o!="object")continue;let i=o,a=typeof i.id=="string"?i.id:"",l=typeof i.baseUrl=="string"?i.baseUrl:"";!a||!l||!Te(i.costClass)||n.push({id:a,baseUrl:l,costClass:i.costClass,...typeof i.displayName=="string"?{displayName:i.displayName}:{},...typeof i.apiKey=="string"?{apiKey:i.apiKey}:{},...typeof i.apiKeyEnv=="string"?{apiKeyEnv:i.apiKeyEnv}:{},...Us(i.pricing)?{pricing:i.pricing}:{},...typeof i.provider=="string"?{provider:i.provider}:{},...Array.isArray(i.models)?{models:i.models.filter(c=>typeof c=="string")}:{}})}let s=new Set(n.map(o=>o.id));return[...pr().filter(o=>!s.has(o.id)),...n]}function fr(t){return t.apiKeyEnv?process.env[t.apiKeyEnv]:t.apiKey}var hr=Ce;import{spawn as ao}from"node:child_process";var js={"claude-code":["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN"],codex:["OPENAI_API_KEY"]};function Ae(t,e,r=process.env){if(e)return r;let n=js[t]??[];if(!n.some(o=>o in r))return r;let s={...r};for(let o of n)delete s[o];return s}import{randomBytes as Ws}from"node:crypto";import{existsSync as gr,mkdtempSync as Gs,rmSync as Oe,writeFileSync as ut}from"node:fs";import qs from"node:net";import{tmpdir as yr}from"node:os";import j from"node:path";import{fileURLToPath as Hs}from"node:url";import{createRequire as Fs}from"node:module";var M=(()=>{return"0.0.1";try{return Fs(import.meta.url)("../package.json").version??"0.0.0"}catch{return"0.0.0"}})();var _r="soba";function Vs(t){return`mcp__${_r}__${t}`}function Ks(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lt(t){return`"${t.replace(/(["\\$`])/g,"\\$1")}"`}function zs(t){return process.platform==="win32"?j.join("\\\\.\\pipe\\",`soba-${t}`):j.join(yr(),`soba-${t}.sock`)}function mr(t,e,r){if(r){let s=j.join(t,e);return ut(s,r,{mode:448}),s}let n=j.join(j.dirname(Hs(import.meta.url)),e);if(gr(n))return n;throw new Error(`Couldn't locate ${e}.`)}function wr(t,e,r){let n=Ws(6).toString("hex"),s=Gs(j.join(yr(),"soba-mcp-")),o=zs(n),i=qs.createServer(c=>{let d="";c.on("data",u=>{d+=u.toString("utf8");let f;for(;(f=d.indexOf(`
15
+ `))>=0;){let h=d.slice(0,f);if(d=d.slice(f+1),!h.trim())continue;let p;try{p=JSON.parse(h)}catch{continue}let m=g=>g.then(y=>c.write(`${JSON.stringify({ok:!0,result:y})}
16
+ `)).catch(y=>c.write(`${JSON.stringify({ok:!1,error:y.message})}
17
+ `));if(p.kind==="approval"){m(r.onApproval({tool:String(p.tool??""),input:p.input,cwd:String(p.cwd??"")}));continue}p.name&&m(r.onTool(p.name,p.input))}}),c.on("error",()=>c.destroy())});try{process.platform!=="win32"&&gr(o)&&Oe(o)}catch{}i.listen(o);let a=null,l=null;try{if(t.length){let c=mr(s,"bridge.mjs",`// THE TOOL BRIDGE \u2014 spawned by the agent CLI, answers back into the worker.
18
+ //
19
+ // This is what unpins an agentic loop from the broker's own process. The version
20
+ // this replaces POSTed each tool call to http://127.0.0.1:<port>, which meant the
21
+ // CLI and the app server had to be the SAME process on the SAME machine \u2014 so a
22
+ // worker could never run anything with tools. Here the bridge talks to the worker
23
+ // over a local socket, and the worker tunnels the call up its existing WebSocket
24
+ // to whoever actually owns the tool.
25
+ //
26
+ // CLI --(MCP stdio)--> bridge --(unix socket)--> worker --(ws)--> app
27
+ //
28
+ // Deliberately dependency-free and plain .mjs: the CLI spawns it as its own
29
+ // process, so it cannot share the worker's bundle.
30
+ //
31
+ // Env: SOBA_IPC_PATH (socket/pipe), SOBA_TOOLS (JSON tool schemas),
32
+ // SOBA_VERSION (what to introduce itself as over MCP).
33
+
34
+ import net from "node:net"
35
+ import { createInterface } from "node:readline"
36
+
37
+ const IPC_PATH = process.env.SOBA_IPC_PATH ?? ""
38
+ /**
39
+ * Handed down by the worker that spawned this, because a separate process
40
+ * embedded as a string cannot be reached by the build's version substitution.
41
+ * It was a hardcoded literal once, and stayed that way across a release, so the
42
+ * CLI was told a version the package had not been for some time.
43
+ */
44
+ const VERSION = process.env.SOBA_VERSION || "0.0.0"
45
+ const TOOLS = (() => {
46
+ try {
47
+ return JSON.parse(process.env.SOBA_TOOLS ?? "[]")
48
+ } catch {
49
+ return []
50
+ }
51
+ })()
52
+
53
+ // stdout is the MCP channel and must carry nothing but JSON-RPC. Anything
54
+ // diagnostic goes to stderr, which the CLI treats as log output.
55
+ const log = (...a) => console.error("[soba-bridge]", ...a)
56
+
57
+ function reply(msg) {
58
+ process.stdout.write(\`\${JSON.stringify(msg)}\\n\`)
59
+ }
60
+
61
+ /** One request/response round-trip to the worker over the local socket. */
62
+ function askWorker(name, input) {
63
+ return new Promise((resolve, reject) => {
64
+ const socket = net.createConnection(IPC_PATH)
65
+ let buffer = ""
66
+ const done = (fn, arg) => {
67
+ socket.destroy()
68
+ fn(arg)
69
+ }
70
+ socket.on("connect", () => socket.write(\`\${JSON.stringify({ kind: "tool", name, input })}\\n\`))
71
+ socket.on("data", (chunk) => {
72
+ buffer += chunk.toString("utf8")
73
+ const nl = buffer.indexOf("\\n")
74
+ if (nl < 0) return
75
+ let msg
76
+ try {
77
+ msg = JSON.parse(buffer.slice(0, nl))
78
+ } catch (err) {
79
+ return done(reject, new Error(\`bad reply from worker: \${err.message}\`))
80
+ }
81
+ if (msg.ok) done(resolve, msg.result)
82
+ else done(reject, new Error(String(msg.error ?? "tool call failed")))
83
+ })
84
+ socket.on("error", (err) => done(reject, err))
85
+ // The worker closing without answering means the run was cancelled.
86
+ socket.on("close", () => reject(new Error("worker closed the tool channel")))
87
+ })
88
+ }
89
+
90
+ function toolResult(text, isError = false) {
91
+ return { content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) }
92
+ }
93
+
94
+ async function handle(msg) {
95
+ const { id, method, params } = msg
96
+ // Notifications carry no id and take no reply.
97
+ const isRequest = id !== undefined && id !== null
98
+
99
+ switch (method) {
100
+ case "initialize":
101
+ return (
102
+ isRequest &&
103
+ reply({
104
+ jsonrpc: "2.0",
105
+ id,
106
+ result: {
107
+ protocolVersion: params?.protocolVersion ?? "2024-11-05",
108
+ capabilities: { tools: {} },
109
+ serverInfo: { name: "soba", version: VERSION },
110
+ },
111
+ })
112
+ )
113
+ case "notifications/initialized":
114
+ return
115
+ case "ping":
116
+ return isRequest && reply({ jsonrpc: "2.0", id, result: {} })
117
+ case "tools/list":
118
+ return isRequest && reply({ jsonrpc: "2.0", id, result: { tools: TOOLS } })
119
+ case "tools/call": {
120
+ if (!isRequest) return
121
+ const name = params?.name
122
+ if (!TOOLS.some((t) => t.name === name)) {
123
+ // An unknown tool is reported as a tool-level error, not a protocol
124
+ // error, so the model can recover instead of the turn dying.
125
+ return reply({ jsonrpc: "2.0", id, result: toolResult(\`Unknown tool: \${name}\`, true) })
126
+ }
127
+ try {
128
+ const result = await askWorker(name, params?.arguments ?? {})
129
+ const text = typeof result === "string" ? result : JSON.stringify(result ?? null)
130
+ return reply({ jsonrpc: "2.0", id, result: toolResult(text) })
131
+ } catch (err) {
132
+ return reply({ jsonrpc: "2.0", id, result: toolResult(String(err.message ?? err), true) })
133
+ }
134
+ }
135
+ default:
136
+ if (isRequest)
137
+ reply({ jsonrpc: "2.0", id, error: { code: -32601, message: \`Unknown method: \${method}\` } })
138
+ }
139
+ }
140
+
141
+ if (!IPC_PATH) {
142
+ log("SOBA_IPC_PATH is not set \u2014 refusing to start")
143
+ process.exit(1)
144
+ }
145
+
146
+ createInterface({ input: process.stdin }).on("line", (line) => {
147
+ const trimmed = line.trim()
148
+ if (!trimmed) return
149
+ let msg
150
+ try {
151
+ msg = JSON.parse(trimmed)
152
+ } catch {
153
+ return // not our frame; ignore rather than crash the CLI's server
154
+ }
155
+ void handle(msg)
156
+ })
157
+ `);a=j.join(s,"mcp.json"),ut(a,JSON.stringify({mcpServers:{[_r]:{command:process.execPath,args:[c],env:{SOBA_IPC_PATH:o,SOBA_TOOLS:JSON.stringify(t),SOBA_VERSION:M}}}}),{mode:384})}if(e.length){let c=mr(s,"approval-hook.mjs",`// THE APPROVAL HOOK \u2014 spawned by the agent CLI as a PreToolUse hook, once per
158
+ // gated tool call. It asks the worker for a verdict over the same local socket
159
+ // the tool bridge uses.
160
+ //
161
+ // CLI --(PreToolUse)--> this --(local socket)--> worker --> approver
162
+ //
163
+ // FAIL CLOSED. Every error path below prints a denial. A hook that errors open
164
+ // would silently turn \`permissionMode: "ask"\` into \`bypassPermissions\`, which is
165
+ // worse than having no approval channel at all.
166
+ //
167
+ // argv[2] = socket path. stdin = the CLI's hook payload.
168
+
169
+ import net from "node:net"
170
+
171
+ const IPC_PATH = process.argv[2] ?? ""
172
+ const TIMEOUT_MS = 180_000
173
+
174
+ function decide(permissionDecision, reason) {
175
+ process.stdout.write(
176
+ \`\${JSON.stringify({
177
+ hookSpecificOutput: {
178
+ hookEventName: "PreToolUse",
179
+ permissionDecision,
180
+ permissionDecisionReason: reason,
181
+ },
182
+ })}\\n\`,
183
+ )
184
+ process.exit(0)
185
+ }
186
+
187
+ const deny = (reason) => decide("deny", \`Soba: \${reason}\`)
188
+
189
+ async function readStdin() {
190
+ const chunks = []
191
+ for await (const chunk of process.stdin) chunks.push(chunk)
192
+ return Buffer.concat(chunks).toString("utf8")
193
+ }
194
+
195
+ function askWorker(payload) {
196
+ return new Promise((resolve, reject) => {
197
+ const socket = net.createConnection(IPC_PATH)
198
+ let buffer = ""
199
+ let settled = false
200
+ const finish = (fn, arg) => {
201
+ if (settled) return
202
+ settled = true
203
+ socket.destroy()
204
+ fn(arg)
205
+ }
206
+ const timer = setTimeout(
207
+ () => finish(reject, new Error("timed out waiting for the worker")),
208
+ TIMEOUT_MS,
209
+ )
210
+ socket.on("connect", () => socket.write(\`\${JSON.stringify(payload)}\\n\`))
211
+ socket.on("data", (chunk) => {
212
+ buffer += chunk.toString("utf8")
213
+ const nl = buffer.indexOf("\\n")
214
+ if (nl < 0) return
215
+ clearTimeout(timer)
216
+ try {
217
+ finish(resolve, JSON.parse(buffer.slice(0, nl)))
218
+ } catch (err) {
219
+ finish(reject, err)
220
+ }
221
+ })
222
+ socket.on("error", (err) => {
223
+ clearTimeout(timer)
224
+ finish(reject, err)
225
+ })
226
+ socket.on("close", () => {
227
+ clearTimeout(timer)
228
+ finish(reject, new Error("worker closed the approval channel"))
229
+ })
230
+ })
231
+ }
232
+
233
+ try {
234
+ if (!IPC_PATH) deny("no approval channel configured")
235
+ const raw = await readStdin()
236
+ let payload
237
+ try {
238
+ payload = JSON.parse(raw)
239
+ } catch {
240
+ deny("could not read the hook payload")
241
+ }
242
+ const reply = await askWorker({
243
+ kind: "approval",
244
+ tool: payload.tool_name,
245
+ input: payload.tool_input,
246
+ cwd: payload.cwd,
247
+ toolUseId: payload.tool_use_id,
248
+ })
249
+ if (!reply?.ok) deny(String(reply?.error ?? "the approver refused"))
250
+ const result = reply.result ?? {}
251
+ if (result.decision === "allow") decide("allow", \`Soba: \${result.reason ?? "approved"}\`)
252
+ deny(result.reason ?? "not approved")
253
+ } catch (err) {
254
+ deny(err?.message ?? String(err))
255
+ }
256
+ `);l=j.join(s,"settings.json"),ut(l,JSON.stringify({hooks:{PreToolUse:[{matcher:`^(${e.map(Ks).join("|")})$`,hooks:[{type:"command",command:`${lt(process.execPath)} ${lt(c)} ${lt(o)}`}]}]}}),{mode:384})}}catch(c){try{i.close(),Oe(s,{recursive:!0,force:!0})}catch{}throw c}return{configPath:a,settingsPath:l,toolNames:t.map(c=>Vs(c.name)),close:()=>{try{i.close()}catch{}try{Oe(s,{recursive:!0,force:!0}),process.platform!=="win32"&&Oe(o,{force:!0})}catch{}}}}import{spawn as Js}from"node:child_process";function N(t,e,r={}){return new Promise((n,s)=>{let o=Js(t,e,{stdio:["ignore","pipe","pipe"],cwd:r.cwd}),i="",a="",l=r.timeoutMs?setTimeout(()=>{o.kill("SIGKILL"),s(new Error(`${t} timed out`))},r.timeoutMs):null;o.stdout.on("data",c=>i+=c.toString("utf8")),o.stderr.on("data",c=>a+=c.toString("utf8")),o.on("error",c=>{l&&clearTimeout(l),s(c)}),o.on("close",c=>{l&&clearTimeout(l),n({stdout:i,stderr:a,code:c})})})}import{access as Ys,constants as vr}from"node:fs/promises";import Xs from"node:os";import br from"node:path";var dt=process.platform==="win32";async function kr(t){try{return await Ys(t,dt?vr.F_OK:vr.X_OK),!0}catch{return!1}}function xr(){return dt?["",...(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map(e=>e.toLowerCase())]:[""]}async function F(t,e=[]){let r=Xs.homedir(),n=o=>o.startsWith("~/")?br.join(r,o.slice(2)):o;for(let o of e){let i=n(o);for(let a of xr())if(await kr(i+a))return i+a}let s=(process.env.PATH??"").split(dt?";":":").filter(Boolean);for(let o of s)for(let i of xr()){let a=br.join(o,t+i);if(await kr(a))return a}return null}var Z=["~/.local/bin","/opt/homebrew/bin","/usr/local/bin","~/.bun/bin","~/.volta/bin"];import{stat as Zs}from"node:fs/promises";import Qs from"node:os";import Sr from"node:path";function Er(t){let e=t.indexOf("{");if(e<0)return null;try{return JSON.parse(t.slice(e))}catch{return null}}async function Tr(t){let e,r;try{({stdout:e,code:r}=await N(t,["auth","status","--json"],{timeoutMs:1e4}))}catch{return{authHint:"Couldn't run `claude auth status` \u2014 check the CLI is current."}}let n=Er(e);return!n||r!==0?{authHint:"Couldn't read `claude auth status` \u2014 check the CLI is current."}:n.loggedIn!==!0?{authenticated:!1,authHint:"Run `claude auth login`, or `claude setup-token` on a headless box."}:{authenticated:!0,costClass:n.authMethod==="claude.ai"||!!n.subscriptionType?"user-subscription":"frontier"}}function eo(){let t=process.env.CODEX_HOME??Sr.join(Qs.homedir(),".codex");return Sr.join(t,"auth.json")}async function Rr(t){try{let{stdout:e,code:r}=await N(t,["auth","status","--json"],{timeoutMs:1e4}),n=Er(e);if(r===0&&n&&typeof n.loggedIn=="boolean")return n.loggedIn?{authenticated:!0}:{authenticated:!1,authHint:"Run `codex login` on this machine."}}catch{}try{if((await Zs(eo())).size>0)return{authenticated:!0}}catch{return{authenticated:!1,authHint:"Run `codex login` on this machine."}}return{authHint:"Couldn't confirm the Codex login; runs may fail at start."}}var to={websearch:{label:"Searching the web",tool:"search"},web_search:{label:"Searching the web",tool:"search"},webfetch:{label:"Reading a page",tool:"fetch"},web_fetch:{label:"Reading a page",tool:"fetch"},read:{label:"Reading a file",tool:"read"},write:{label:"Writing a file",tool:"write"},edit:{label:"Editing a file",tool:"edit"},notebookedit:{label:"Editing a notebook",tool:"edit"},bash:{label:"Running a command",tool:"bash"},glob:{label:"Finding files",tool:"files"},grep:{label:"Searching files",tool:"files"},task:{label:"Asking a sub-agent",tool:"agent"},todowrite:{label:"Planning the steps",tool:"todo"}};function ro(t){let e=/^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(t);if(!e)return t;let r=(e[1]??"").replace(/_/g," "),n=(e[2]??"").replace(/_/g," ");return`${r.charAt(0).toUpperCase()}${r.slice(1)} ${n}`}function Cr(t,e){if(t==="thinking")return{label:"Thinking",tool:"think"};if(t==="web_search_tool_result")return{label:"Reading sources",tool:"sources"};if(t==="server_tool_use"||t==="tool_use"){if(!e)return{label:"Working",tool:"tool"};let r=to[e.toLowerCase()];return r||{label:`Running ${ro(e)}`,tool:"tool"}}return null}function no(t){return/\b(session|usage)\s+limit\b/i.test(t)||/hit your .*\blimit\b/i.test(t)}function so(t){if(!t||typeof t!="object")return null;let e=t,r=String(e.status??"").toLowerCase();if(!r||r==="allowed"||r==="ok"||!/reject|block|queue|throttl|limit|exceed|wait|pending|deny|denied/.test(r))return null;let n=typeof e.resetsAt=="number"?e.resetsAt:null;if(n){let s=n*1e3-Date.now();if(s>0&&s<6*36e5){let o=new Date(n*1e3),i=o.getHours(),a=o.getMinutes().toString().padStart(2,"0"),l=i>=12?"pm":"am";return i=i%12||12,`Rate limit reached \u2014 resumes ${i}:${a}${l}`}}return"Waiting on rate limit"}function oo(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e?.type==="text").map(e=>e.text??"").join(""):""}function io(t,e){let r=t.usage;if(!r||typeof r!="object")return;let n=s=>typeof s=="number"&&Number.isFinite(s)?s:0;return{model:e,provider:"anthropic",inputTokens:n(r.input_tokens),outputTokens:n(r.output_tokens),cacheReadTokens:n(r.cache_read_input_tokens),cacheWriteTokens:n(r.cache_creation_input_tokens),webSearches:n(r.server_tool_use?.web_search_requests)}}function Ar(t,e="sonnet"){let r="",n="",s=!1,o=!1,i=!1,a,l=d=>{if(d.length>r.length&&d.startsWith(r)){let u=d.slice(r.length);r=d,t({type:"delta",text:u})}else d&&d!==r&&(t({type:"delta",text:d}),r+=d)};return{handleLine:d=>{let u=d.trim();if(!u)return;let f;try{f=JSON.parse(u)}catch{return}if(f.type==="stream_event"&&f.event?.type==="content_block_delta"){let h=f.event.delta;h?.type==="text_delta"&&typeof h.text=="string"?(s=!0,r+=h.text,t({type:"delta",text:h.text})):h?.type==="thinking_delta"&&typeof h.thinking=="string"&&(n+=h.thinking,t({type:"thinking",text:n}));return}if(f.type==="stream_event"&&f.event?.type==="content_block_start"){let h=f.event.content_block,p=Cr(h?.type,h?.name);p&&t({type:"status",message:p.label,tool:p.tool});return}if(f.type==="rate_limit_event"){if(!r){let h=so(f.rate_limit_info);h&&t({type:"status",message:h})}return}if(f.type==="assistant"&&f.message?.content){if(Array.isArray(f.message.content))for(let p of f.message.content){let m=Cr(p?.type,p?.name);m&&t({type:"status",message:m.label,tool:m.tool});let g=p?.thinking;p?.type==="thinking"&&typeof g=="string"&&g.length>n.length&&(n=g,t({type:"thinking",text:n}))}if(s)return;let h=oo(f.message.content);h&&l(h);return}if(f.type==="result"){i=!0,a=io(f,e)??a;let h=typeof f.result=="string"?f.result:"";if(!r&&(f.is_error===!0||no(h))){o=!0,t({type:"error",message:h.trim()||"The agent stopped before replying."});return}!s&&h&&l(h);return}},sent:()=>r,errored:()=>o,finished:()=>i,usage:()=>a}}var Or=["~/.local/bin/claude","/opt/homebrew/bin/claude","/usr/local/bin/claude","~/.claude/local/claude",...Z.map(t=>`${t}/claude`)];function co(t){return t.messages.length===1&&t.messages[0]?t.messages[0].content:t.messages.map(e=>`${e.role==="user"?"User":"Assistant"}: ${e.content}`).join(`
257
+
258
+ `)}function lo(t,e){let r=["--restricted"],n=[...t.policy.allowTools,...t.policy.askTools];r.push("--tools",n.join(","));let s=[...t.policy.allowTools,...e?.toolNames??[]];return s.length&&r.push("--allowedTools",s.join(",")),t.policy.denyTools.length&&r.push("--disallowedTools",t.policy.denyTools.join(",")),r.push("--permission-mode",t.policy.permissionMode==="auto"?"acceptEdits":"default"),e?.configPath&&r.push("--mcp-config",e.configPath,"--strict-mcp-config"),e?.settingsPath&&r.push("--settings",e.settingsPath),r}var pe=class{id="claude-code";displayName="Claude Code";binPath=null;async detect(){let e=await F("claude",Or);if(!e)return null;this.binPath=e;let r;try{let{stdout:s}=await N(e,["--version"],{timeoutMs:5e3});r=s.trim().split(/\s+/)[0]}catch{}let n=await Tr(e);return{id:this.id,displayName:this.displayName,version:r,models:["haiku","sonnet","opus"],tools:["Read","Write","Edit","Bash","Glob","Grep","WebSearch","WebFetch","Task","TodoWrite"],costClass:n.costClass??"user-subscription",supportsTools:!0,authenticated:n.authenticated,authHint:n.authHint}}async run(e,r){let n=this.binPath??await F("claude",Or);if(!n)return r.emit({type:"error",message:"Couldn't find the Claude CLI on this machine. Install it and run `claude` once to sign in."}),{};let s=e.policy.allowAppTools?e.tools??[]:[],o=s.length||e.policy.askTools.length?wr(s,e.policy.askTools,{onTool:(h,p)=>r.callTool(h,p),onApproval:h=>r.requestApproval(h.tool,h.input,h.cwd)}):null,i=["-p",co(e),"--output-format","stream-json","--verbose","--include-partial-messages",...lo(e,o)];e.model&&i.push("--model",e.model),e.system&&i.push("--system-prompt",e.system);let a=Ar(r.emit,e.model??"sonnet"),l="",c="",d=ao(n,i,{stdio:["ignore","pipe","pipe"],cwd:e.policy.cwd,env:Ae(this.id,e.policy.allowMeteredKeys)}),u=()=>d.kill("SIGTERM");e.signal.addEventListener("abort",u);let f=setTimeout(()=>{r.emit({type:"status",message:"Run hit its time limit \u2014 stopping."}),u()},e.policy.timeoutMs);return d.stdout.on("data",h=>{l+=h.toString("utf8");let p;for(;(p=l.indexOf(`
259
+ `))>=0;)a.handleLine(l.slice(0,p)),l=l.slice(p+1)}),d.stderr.on("data",h=>{c+=h.toString("utf8")}),await new Promise(h=>{d.on("close",p=>{l.trim()&&a.handleLine(l),a.errored()||(p!==0&&!a.sent()?r.emit({type:"error",message:c.trim()||`claude exited with code ${p}`}):r.emit({type:"done",usage:a.usage()})),h()}),d.on("error",p=>{r.emit({type:"error",message:String(p)}),h()})}),clearTimeout(f),e.signal.removeEventListener("abort",u),o?.close(),{usage:a.usage()}}};import{spawn as uo}from"node:child_process";var Pr=Z.map(t=>`${t}/codex`);function po(t){let e=t.messages.map(r=>r.role==="user"?r.content:`Assistant: ${r.content}`).join(`
260
+
261
+ `);return t.system?`${t.system}
262
+
263
+ ${e}`:e}function fo(t){let e=t.policy.allowTools.some(r=>/^(write|edit|bash)$/i.test(r));return["--sandbox",e?"workspace-write":"read-only","--ask-for-approval",t.policy.permissionMode==="auto"&&!e?"never":"on-request"]}function pt(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function ho(t,e){let r="",n="",s,o=!1,i=!1,a=()=>{i||(i=!0,t({type:"status",message:"Thinking",tool:"think"}))},l=d=>{d&&(r+=d,t({type:"delta",text:d}))};return{handleLine:d=>{let u=d.trim();if(!u)return;let f;try{f=JSON.parse(u)}catch{l(`${u}
264
+ `);return}o=!0;let h=f.msg??f,p=String(h.type??f.type??"");if(p==="agent_message_delta"&&typeof h.delta=="string")return l(h.delta);if(p==="agent_reasoning_delta"&&typeof h.delta=="string"){a(),n+=h.delta,t({type:"thinking",text:n});return}if(p==="agent_message"||p==="agent_reasoning"||p==="item.completed"){let m=f.item??h,g=typeof m?.text=="string"?m.text:typeof h.message=="string"?h.message:"";if(m?.type==="reasoning"||p==="agent_reasoning"){a(),g.length>n.length&&(n=g,t({type:"thinking",text:g}));return}g&&!r.includes(g)&&l(g);return}if(p.startsWith("exec_command")||p==="command_execution"){t({type:"status",message:"Running a command",tool:"bash"});return}if(p.startsWith("patch_apply")||p==="file_change"){t({type:"status",message:"Editing a file",tool:"edit"});return}if(p==="web_search"||p.startsWith("web_search")){t({type:"status",message:"Searching the web",tool:"search"});return}if(p==="token_count"||h.info?.total_token_usage){let m=h.info?.total_token_usage??h.usage;m&&(s={model:e,provider:"openai",inputTokens:pt(m.input_tokens),outputTokens:pt(m.output_tokens),cacheReadTokens:pt(m.cached_input_tokens),cacheWriteTokens:0,webSearches:0});return}if(p==="error"||h.error){t({type:"error",message:String(h.message??h.error??"Codex reported an error")});return}},sent:()=>r,usage:()=>s,sawStructured:()=>o}}var fe=class{id="codex";displayName="Codex";binPath=null;async detect(){let e=await F("codex",Pr);if(!e)return null;this.binPath=e;let r;try{let{stdout:s}=await N(e,["--version"],{timeoutMs:5e3});r=s.trim().split(/\s+/).pop()}catch{}let n=await Rr(e);return{id:this.id,displayName:this.displayName,version:r,models:[],tools:["shell","apply_patch","web_search"],costClass:n.costClass??"user-subscription",supportsTools:!1,authenticated:n.authenticated,authHint:n.authHint}}async run(e,r){e.policy.askTools.length&&r.emit({type:"status",message:`Codex can't take approvals yet \u2014 running without ${e.policy.askTools.join(", ")}.`});let n=this.binPath??await F("codex",Pr);if(!n)return r.emit({type:"error",message:"Couldn't find the Codex CLI on this machine."}),{};let s=["exec","--json",...fo(e)];e.model&&s.push("--model",e.model),s.push(po(e));let o=ho(r.emit,e.model??"codex"),i="",a="",l=uo(n,s,{stdio:["ignore","pipe","pipe"],cwd:e.policy.cwd,env:Ae(this.id,e.policy.allowMeteredKeys)}),c=()=>l.kill("SIGTERM");e.signal.addEventListener("abort",c);let d=setTimeout(()=>{r.emit({type:"status",message:"Run hit its time limit \u2014 stopping."}),c()},e.policy.timeoutMs);return l.stdout.on("data",u=>{i+=u.toString("utf8");let f;for(;(f=i.indexOf(`
265
+ `))>=0;)o.handleLine(i.slice(0,f)),i=i.slice(f+1)}),l.stderr.on("data",u=>a+=u.toString("utf8")),await new Promise(u=>{l.on("close",f=>{i.trim()&&o.handleLine(i),f!==0&&!o.sent()?r.emit({type:"error",message:a.trim()||`codex exited with code ${f}`}):r.emit({type:"done",usage:o.usage()}),u()}),l.on("error",f=>{r.emit({type:"error",message:String(f)}),u()})}),clearTimeout(d),e.signal.removeEventListener("abort",c),{usage:o.usage()}}};var Ir=t=>t.toLowerCase(),ft=(t,e)=>t.some(r=>Ir(r)===Ir(e));function ht(t,e){return ft(e.denyTools,t)?{decision:"deny",reason:`${t} is not permitted on this machine.`}:ft(e.allowTools,t)?{decision:"allow"}:e.permissionMode==="ask"&&ft(e.askTools,t)?{decision:"ask"}:{decision:"deny",reason:`${t} isn't available for this run.`}}function Mr(t,e){return t.filter(r=>{let n=ht(r.name,e);return n.decision==="allow"||n.decision==="ask"})}function Nr(t,e){let r=t.inputTokens*e.inputMicrosPerMTok,n=t.outputTokens*e.outputMicrosPerMTok;return Math.ceil((r+n)/1e6)}var mo=12;async function Lr(t){let{policy:e,emit:r}=t,n=t.maxTurns??mo,s=new Map(t.tools.map(u=>[u.name.toLowerCase(),u])),o=new Map((t.appTools??[]).map(u=>[u.name.toLowerCase(),u])),i=[...Mr(t.tools,e).map(u=>({name:u.name,description:u.description,inputSchema:u.inputSchema})),...(t.appTools??[]).map(u=>({name:u.name,description:u.description,inputSchema:u.inputSchema}))],a=[];t.system&&a.push({role:"system",content:t.system});for(let u of t.messages)a.push({role:u.role,content:u.content});let l,c=!1;for(let u=0;u<n;u++){if(t.signal.aborted)return{...l?{usage:l}:{}};let f=await t.client.turn({model:t.model,messages:a,tools:i,signal:t.signal},(h,p)=>{if(h==="text")return r({type:"delta",text:p});c||(c=!0,r({type:"status",message:"Thinking",tool:"think"})),r({type:"thinking",text:p})});if(f.usage&&(l=go(l,f.usage)),l&&t.pricing&&(l={...l,costMicros:Nr(l,t.pricing)}),t.maxCostMicros!==void 0&&l?.costMicros!==void 0&&l.costMicros>=t.maxCostMicros)return r({type:"status",message:`Stopped at this run's cost limit (${l.costMicros} of ${t.maxCostMicros} micros).`}),r({type:"done",...l?{usage:l}:{}}),{...l?{usage:l}:{}};if(!f.toolCalls.length)return r({type:"done",...l?{usage:l}:{}}),{...l?{usage:l}:{}};a.push({role:"assistant",content:f.text,toolCalls:f.toolCalls});for(let h of f.toolCalls){let p=await d(h.name,h.input);a.push({role:"tool",toolCallId:h.id,name:h.name,content:p})}}return r({type:"status",message:`Stopped after ${n} tool rounds without a final answer.`}),r({type:"done",...l?{usage:l}:{}}),{...l?{usage:l}:{}};async function d(u,f){let h=o.get(u.toLowerCase());if(h){r({type:"status",message:`Using ${u}`,tool:"tool"});try{let g=await t.callAppTool(h.name,f);return typeof g=="string"?g:JSON.stringify(g??null)}catch(g){return`Error: ${g instanceof Error?g.message:String(g)}`}}let p=s.get(u.toLowerCase());if(!p)return`Error: no tool named "${u}" is available.`;let m=ht(p.name,e);if(m.decision==="deny")return`Error: ${m.reason}`;if(m.decision==="ask"){let g=await t.requestApproval(p.name,f,e.cwd);if(g.decision!=="allow")return`Error: the user declined ${p.name}${g.reason?` (${g.reason})`:""}.`}r({type:"status",message:`Using ${p.name}`,...p.slug?{tool:p.slug}:{}});try{return await p.run(f&&typeof f=="object"?f:{},{cwd:e.cwd,signal:t.signal})}catch(g){return`Error: ${g instanceof Error?g.message:String(g)}`}}}function go(t,e){return t?{model:e.model||t.model,provider:e.provider??t.provider,inputTokens:t.inputTokens+e.inputTokens,outputTokens:t.outputTokens+e.outputTokens,cacheReadTokens:t.cacheReadTokens+e.cacheReadTokens,cacheWriteTokens:t.cacheWriteTokens+e.cacheWriteTokens,webSearches:t.webSearches+e.webSearches}:e}var ol=process.env.SOBA_OPENAI_AUTH_BASE??"https://auth.openai.com";var ul=process.env.SOBA_CHATGPT_BASE??"https://chatgpt.com/backend-api/codex";function yo(t,e,r){if(!t||typeof t!="object")return;let n=t,s=i=>typeof i=="number"&&Number.isFinite(i)?i:0,o=n.prompt_tokens_details??{};return{model:e,provider:r,inputTokens:s(n.prompt_tokens),outputTokens:s(n.completion_tokens),cacheReadTokens:s(o.cached_tokens),cacheWriteTokens:0,webSearches:0}}var Pe=class{constructor(e){this.cfg=e;this.id=e.id,this.displayName=e.displayName}id;displayName;async models(e){try{let r=await fetch(`${this.cfg.baseUrl}/models`,{headers:this.headers(),...e?{signal:e}:{}});return r.ok?((await r.json()).data??[]).map(s=>s.id).filter(s=>!!s):[]}catch{return[]}}headers(){return{"content-type":"application/json",...this.cfg.apiKey?{authorization:`Bearer ${this.cfg.apiKey}`}:{},...this.cfg.headers}}async turn(e,r){let n=await fetch(`${this.cfg.baseUrl}/chat/completions`,{method:"POST",headers:this.headers(),signal:e.signal,body:JSON.stringify({model:e.model,stream:!0,stream_options:{include_usage:!0},messages:e.messages.map(c=>({role:c.role,content:c.content,...c.toolCalls?.length?{tool_calls:c.toolCalls.map(d=>({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.input??{})}}))}:{},...c.toolCallId?{tool_call_id:c.toolCallId}:{},...c.name?{name:c.name}:{}})),...e.tools.length?{tools:e.tools.map(c=>({type:"function",function:{name:c.name,description:c.description,parameters:c.inputSchema}}))}:{}})});if(!n.ok||!n.body){let c=await n.text().catch(()=>"");throw new Error(`${this.displayName} returned ${n.status}${c?`: ${c.slice(0,300)}`:""}`)}let s="",o="",i,a=new Map;for await(let c of wo(n.body)){if(c==="[DONE]")break;let d;try{d=JSON.parse(c)}catch{continue}d.usage&&(i=yo(d.usage,e.model,this.cfg.provider)??i);let u=d.choices?.[0]?.delta;if(!u)continue;let f=u.reasoning_content??u.reasoning;typeof f=="string"&&f&&(o+=f,r("reasoning",f)),typeof u.content=="string"&&u.content&&(s+=u.content,r("text",u.content));for(let h of u.tool_calls??[]){let p=typeof h.index=="number"?h.index:0,m=a.get(p)??{id:"",name:"",args:""};h.id&&(m.id=h.id),h.function?.name&&(m.name+=h.function.name),h.function?.arguments&&(m.args+=h.function.arguments),a.set(p,m)}}let l=[...a.entries()].sort((c,d)=>c[0]-d[0]).map(([c,d])=>({id:d.id||`call_${c}`,name:d.name,input:_o(d.args)})).filter(c=>c.name);return{text:s,reasoning:o,toolCalls:l,...i?{usage:i}:{}}}};function _o(t){if(!t.trim())return{};try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}async function*wo(t){let e=t.getReader(),r=new TextDecoder,n="";for(;;){let{done:s,value:o}=await e.read();if(s)break;n+=r.decode(o,{stream:!0});let i;for(;(i=n.indexOf(`
266
+ `))>=0;){let a=n.slice(0,i).trim();n=n.slice(i+1),a.startsWith("data:")&&(yield a.slice(5).trim())}}}import{spawn as vo}from"node:child_process";import{mkdir as bo,readdir as ko,readFile as $r,realpath as Ie,stat as xo,writeFile as So}from"node:fs/promises";import T from"node:path";var mt=2e5;async function Br(t,e){let r=await Ie(t),n=T.resolve(r,e),s=n;for(;;)try{let o=await Ie(s),i=T.join(o,T.relative(s,n)),a=T.relative(r,i);if(a.startsWith("..")||T.isAbsolute(a))throw new Error(`Path is outside this run's directory: ${e}`);return i}catch(o){if(o.message.startsWith("Path is outside"))throw o;let i=T.dirname(s);if(i===s)throw new Error(`Path is outside this run's directory: ${e}`);s=i}}function Me(t,e){let r=t[e];if(typeof r!="string"||!r)throw new Error(`"${e}" is required.`);return r}var Ne=t=>t.length>mt?`${t.slice(0,mt)}
267
+ \u2026[truncated]`:t;async function gt(t,e,r,n=0){if(n>8||r.length>2e3)return;let s;try{s=await ko(t,{withFileTypes:!0})}catch{return}for(let o of s){if(o.name.startsWith(".")||o.name==="node_modules")continue;let i=T.join(t,o.name);o.isDirectory()?await gt(i,e,r,n+1):r.push(T.relative(e,i))}}var Eo={name:"Read",description:"Read a UTF-8 text file, relative to the working directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path, relative to the working directory."}},required:["path"]},slug:"read",async run(t,e){let r=await Br(e.cwd,Me(t,"path"));return Ne(await $r(r,"utf8"))}},To={name:"Write",description:"Write a UTF-8 text file, creating parent directories as needed.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]},slug:"write",async run(t,e){let r=await Br(e.cwd,Me(t,"path"));await bo(T.dirname(r),{recursive:!0});let n=typeof t.content=="string"?t.content:"";return await So(r,n,"utf8"),`Wrote ${n.length} bytes to ${T.relative(e.cwd,r)}`}},Ro={name:"Glob",description:"List files under the working directory, optionally filtered by a substring.",inputSchema:{type:"object",properties:{pattern:{type:"string",description:"Optional substring to filter paths by."}}},slug:"files",async run(t,e){let r=await Ie(e.cwd),n=[];await gt(r,r,n);let s=typeof t.pattern=="string"?t.pattern:"",o=s?n.filter(i=>i.includes(s)):n;return o.length?Ne(o.join(`
268
+ `)):"(no files)"}},Co={name:"Grep",description:"Search file contents under the working directory for a literal string.",inputSchema:{type:"object",properties:{query:{type:"string"}},required:["query"]},slug:"search",async run(t,e){let r=Me(t,"query"),n=await Ie(e.cwd),s=[];await gt(n,n,s);let o=[];for(let i of s.slice(0,500)){try{if((await xo(T.join(n,i))).size>mt)continue;(await $r(T.join(n,i),"utf8")).split(`
269
+ `).forEach((c,d)=>{c.includes(r)&&o.push(`${i}:${d+1}: ${c.trim()}`)})}catch{}if(o.length>200)break}return o.length?Ne(o.join(`
270
+ `)):"(no matches)"}},Ao={name:"Bash",description:"Run a shell command in the working directory.",inputSchema:{type:"object",properties:{command:{type:"string"}},required:["command"]},slug:"bash",run(t,e){let r=Me(t,"command");return new Promise(n=>{let s=vo("/bin/sh",["-c",r],{cwd:e.cwd,stdio:["ignore","pipe","pipe"]}),o="",i=()=>s.kill("SIGTERM");e.signal.addEventListener("abort",i);let a=setTimeout(i,12e4);s.stdout.on("data",l=>o+=l.toString("utf8")),s.stderr.on("data",l=>o+=l.toString("utf8")),s.on("error",l=>n(`Failed to run: ${l.message}`)),s.on("close",l=>{clearTimeout(a),e.signal.removeEventListener("abort",i),n(Ne(o.trim()||`(no output, exit ${l})`))})})}};function Le(){return[Eo,To,Ro,Co,Ao]}var he=class{constructor(e){this.cfg=e;this.id=e.id,this.displayName=e.displayName??e.id;let r=fr(e);this.client=new Pe({id:e.id,displayName:this.displayName,baseUrl:e.baseUrl,...r?{apiKey:r}:{},...e.provider?{provider:e.provider}:{}})}id;displayName;client;available=[];async detect(){if(this.cfg.apiKeyEnv&&!process.env[this.cfg.apiKeyEnv])return{id:this.id,displayName:this.displayName,models:this.cfg.models??[],tools:Le().map(r=>r.name),costClass:this.cfg.costClass,supportsTools:!0,authenticated:!1,authHint:`Set ${this.cfg.apiKeyEnv} for the "${this.id}" endpoint.`};let e=this.cfg.models?.length?this.cfg.models:await this.client.models(AbortSignal.timeout(5e3));return e.length?(this.available=e,{id:this.id,displayName:this.displayName,models:e,tools:Le().map(r=>r.name),costClass:this.cfg.costClass,...this.cfg.pricing?{pricing:this.cfg.pricing}:{},supportsTools:!0,authenticated:!0}):null}async run(e,r){let n=e.model&&this.available.includes(e.model)?e.model:this.available[0];if(!n)return r.emit({type:"error",message:`No model is available from "${this.id}".`}),{};let s=new AbortController,o=()=>s.abort();e.signal.addEventListener("abort",o);let i=setTimeout(()=>{r.emit({type:"status",message:"Run hit its time limit \u2014 stopping."}),o()},e.policy.timeoutMs);try{return await Lr({client:this.client,model:n,policy:e.policy,...e.system?{system:e.system}:{},messages:e.messages,tools:Le(),...e.policy.allowAppTools&&e.tools?.length?{appTools:e.tools}:{},callAppTool:(a,l)=>r.callTool(a,l),requestApproval:(a,l,c)=>r.requestApproval(a,l,c),emit:r.emit,signal:s.signal,...this.cfg.pricing?{pricing:this.cfg.pricing}:{},...e.route?.maxCostMicros!==void 0?{maxCostMicros:e.route.maxCostMicros}:{}})}catch(a){return r.emit({type:"error",message:a instanceof Error?a.message:String(a)}),{}}finally{clearTimeout(i),e.signal.removeEventListener("abort",o)}}};function $e(t=de()){return[new pe,new fe,...t.map(e=>new he(e))]}var Oo=["login","install","uninstall","service-status"];function Dr(t){let e={};t[0]&&Oo.includes(t[0])&&(e.command=t.shift());for(let r=0;r<t.length;r++){let n=t[r]??"",s=()=>t[++r];n==="--help"||n==="-h"?e.help=!0:n==="--version"||n==="-v"?e.version=!0:n==="--reset"?e.reset=!0:n==="--status"?e.status=!0:n==="--json"?e.json=!0:n==="--system"?e.system=!0:n==="--npx"?e.npx=!0:n==="--install"?e.install=!0:n==="--no-browser"?e.noBrowser=!0:n==="--auto-install"?e.autoInstall=!0:n==="--no-install-prompt"?e.noInstallPrompt=!0:n==="--pair"||n==="--token"?e.pair=s():n==="--broker"||n==="--url"||n==="--cloud"?e.broker=s():n==="--runtime"?e.runtime=s():n==="--label"?e.labels=[...e.labels??[],s()??""].filter(Boolean):n.startsWith("--pair=")?e.pair=n.slice(7):n.startsWith("--broker=")?e.broker=n.slice(9):n.startsWith("--runtime=")&&(e.runtime=n.slice(10))}return e}var yt=`soba-worker \u2014 run agent jobs on this machine, on your own subscription.
271
+
272
+ Usage:
273
+ npx @soba-so/worker login --broker https://broker.example.com
274
+ npx @soba-so/worker (reuses the cached token + broker)
275
+ npx @soba-so/worker --pair <token> --broker wss://\u2026 (a token you already have)
276
+
277
+ Connecting:
278
+ soba-worker login Approve in a browser; no token to copy.
279
+ --install Also install the service once paired.
280
+ --no-browser Print the URL instead of opening it.
281
+
282
+ Keep it running:
283
+ soba-worker install Run in the background, and after reboot.
284
+ soba-worker uninstall Stop and remove it.
285
+ soba-worker service-status Is it installed, and is it up?
286
+
287
+ Works either way. With the package installed the service runs it directly;
288
+ run from npx, the service runs \`npx @soba-so/worker@<version>\` instead \u2014 the
289
+ cache path is never recorded, because npm prunes it.
290
+ npm install -g @soba-so/worker && soba-worker install (direct)
291
+ npx @soba-so/worker install (via npx)
292
+
293
+ Options:
294
+ --pair, --token <t> Pairing token, minted by the app you're connecting to.
295
+ --broker, --url <u> Broker host (wss:// or https://). Cached after first use.
296
+ --runtime <id> Force a runtime (claude-code, codex). Default: first detected.
297
+ --label <l> Tag this machine so an app can route to it. Repeatable.
298
+ --status Show what this machine would offer, then exit.
299
+ --json Emit those facts as JSON, for a program.
300
+ --auto-install Install the service as soon as a run succeeds.
301
+ --no-install-prompt Never offer to.
302
+ --system With install/uninstall: a system unit, not a user one.
303
+ --npx With install: launch via npx instead of a path on disk.
304
+ --reset Forget the cached token + broker, then exit.
305
+ --version, -v Print the version.
306
+ --help, -h Show this help.
307
+
308
+ Environment (overrides the cache):
309
+ SOBA_BROKER_URL, SOBA_PAIR_TOKEN
310
+
311
+ Security:
312
+ Runs are confined to the roots in ~/.soba/policy.json. With no such file, this
313
+ machine grants READ-ONLY tools inside ~/.soba/workspace and nothing else. The
314
+ broker can only narrow that, never widen it.
315
+
316
+ Prerequisite:
317
+ An agent CLI installed and signed in \u2014 \`claude\` and/or \`codex\`. Runs execute on
318
+ YOUR subscription; the broker never sees your credentials.`;import{existsSync as Ur,mkdirSync as Po,readFileSync as Io,writeFileSync as jr}from"node:fs";import Mo from"node:path";var q=Mo.join(b,"worker.json");function Be(){try{if(Ur(q))return JSON.parse(Io(q,"utf8"))}catch{}return{}}function me(t){try{Po(b,{recursive:!0}),jr(q,JSON.stringify(t,null,2),{mode:384})}catch(e){console.warn(`[soba] couldn't cache config to ${q}:`,e.message)}}function Fr(){try{Ur(q)&&jr(q,"{}",{mode:384})}catch{}}function _t(...t){for(let e of t)if(e)return e}function Wr(t){let e=t.replace(/\/+$/,"");return e.startsWith("http")?e.replace(/^http/,"ws"):e}var wt=q;import Sa from"node:os";var vt="soba";function No(t){if(typeof t!="string")return null;let e=new RegExp(`^${vt}_([0-9a-f]{16})\\.([A-Za-z0-9_-]{43})$`).exec(t);return e?{id:e[1],secret:e[2]}:null}function Gr(t){return typeof t!="string"?"":t.replace(new RegExp(`${vt}_[0-9a-f]{16}\\.[A-Za-z0-9_-]{43}`,"g"),e=>Lo(e))}function Lo(t){let e=No(t);return e?`${vt}_${e.id}.\u2026`:t?"<redacted>":""}var Gl=90*24*36e5;var ql=5*6e4;var ra=U(Un(),1),na=U(Ve(),1),sa=U(te(),1),oa=U(Pt(),1),ia=U(Nt(),1),aa=U(jt(),1),zn=U(Ye(),1),ca=U(Kn(),1);var Wt=zn.default;import{randomUUID as Yn}from"node:crypto";import{appendFileSync as la,mkdirSync as ua}from"node:fs";import da from"node:path";import{createInterface as pa}from"node:readline";var fa=da.join(b,"audit.log"),ha=12e4;function ma(t){try{ua(b,{recursive:!0}),la(fa,`${JSON.stringify({at:new Date().toISOString(),...t})}
319
+ `,{mode:384})}catch{}}function ga(t,e){let r="";try{let n=JSON.stringify(e);r=n&&n!=="{}"?n.length>300?`${n.slice(0,300)}\u2026`:n:""}catch{}return r?`${t} ${r}`:t}var Ze=class{constructor(e){this.deps=e}cache=new Map;queue=Promise.resolve();forget(e){this.cache.delete(e)}async request(e,r){if(!r.some(a=>a.toLowerCase()===e.tool.toLowerCase())){let a={decision:"deny",reason:`${e.tool} isn't approvable on this machine.`};return this.record(e,a,"ceiling"),a}let s=this.cache.get(e.runId)?.get(e.tool);if(s)return s;let o=await this.ask(e),i=this.cache.get(e.runId)??new Map;return i.set(e.tool,o),this.cache.set(e.runId,i),o}async ask(e){let{approver:r}=this.deps.grant,n=this.deps.timeoutMs??ha;if(r==="none"){let i={decision:"deny",reason:"This machine doesn't take approvals."};return this.record(e,i,"none"),i}let s;try{s=await ya(this.route(r,e),n)}catch(i){s={decision:"deny",reason:`Approval failed: ${i.message}`}}let o={decision:s?.decision==="allow"?"allow":"deny",reason:s?.reason};return this.record(e,o,r),o}route(e,r){if(e==="local")return this.askLocal(r);if(e==="desktop"){let n=this.deps.askDesktop;return n?n(r):Promise.resolve({decision:"deny",reason:'This build has no desktop approver. Set "approver": "local" or "remote".'})}return this.deps.askRemote(r)}askLocal(e){if(!process.stdin.isTTY)return Promise.resolve({decision:"deny",reason:'No terminal to prompt on. Set "approver": "remote" in ~/.soba/policy.json, or move the tool into allowTools.'});let r=this.queue.then(()=>new Promise(n=>{let s=pa({input:process.stdin,output:process.stdout});s.question(`
320
+ [soba] Allow ${ga(e.tool,e.input)}
321
+ in ${e.cwd}? [y/N] `,o=>{s.close();let i=/^y(es)?$/i.test(o.trim());n({decision:i?"allow":"deny",reason:i?"Approved on the machine.":"Declined on the machine."})})}));return this.queue=r.catch(()=>{}),r}record(e,r,n){ma({kind:"approval",runId:e.runId,tool:e.tool,input:e.input,cwd:e.cwd,decision:r.decision,reason:r.reason,via:n})}};function ya(t,e){return new Promise((r,n)=>{let s=setTimeout(()=>n(new Error(`no answer within ${Math.round(e/1e3)}s`)),e);t.then(o=>{clearTimeout(s),r(o)},o=>{clearTimeout(s),n(o)})})}import{randomUUID as _a}from"node:crypto";import{connect as wa}from"node:net";import va from"node:path";var ba="SOBA_APPROVER_SOCKET";function ka(){let t=process.env[ba];return t||(process.platform==="win32"?"\\\\.\\pipe\\soba-approver":va.join(b,"approver.sock"))}var xa=11e4;function Jn(t,e={}){let r=e.socketPath??ka(),n=e.timeoutMs??xa,s=_a();return new Promise(o=>{let i=!1,a,l=f=>{i||(i=!0,clearTimeout(d),a?.destroy(),o(f))},c=f=>l({decision:"deny",reason:f}),d=setTimeout(()=>c("The approval window did not answer in time."),n);try{a=wa(r)}catch(f){return c(`Could not reach the Soba app: ${f.message}`)}a.setEncoding("utf8"),a.on("error",()=>c('No Soba app is running to ask. Open it, or set "approver": "local".')),a.on("close",()=>c("The approval window closed without answering.")),a.on("connect",()=>{a?.write(`${JSON.stringify({v:1,type:"approval_request",approvalId:s,runId:t.runId,tool:t.tool,input:t.input,cwd:t.cwd})}
322
+ `)});let u="";a.on("data",f=>{u+=f;let h=u.indexOf(`
323
+ `);if(h===-1){u.length>64e3&&c("The approval window sent nonsense.");return}let p=u.slice(0,h),m;try{m=JSON.parse(p)}catch{return c("The approval window sent nonsense.")}if(typeof m.approvalId=="string"&&m.approvalId!==s)return c("The approval window answered a different request.");l({decision:m.decision==="allow"?"allow":"deny",reason:typeof m.reason=="string"?m.reason:m.decision==="allow"?"Approved in the Soba app.":"Declined in the Soba app."})})})}var Qe=class{constructor(e){this.deps=e;this.approver=new Ze({grant:e.grant,askRemote:r=>this.askRemote(r),askDesktop:r=>Jn(r)})}active=new Map;approver;get activeCount(){return this.active.size}get capacity(){return this.deps.grant.maxConcurrency}cancel(e){let r=this.active.get(e);if(r){r.controller.abort();for(let n of r.pendingTools.values())n.reject(new Error("Run cancelled"));for(let n of r.pendingApprovals.values())n({decision:"deny",reason:"Run was cancelled."});this.approver.forget(e),this.active.delete(e)}}cancelAll(){for(let e of[...this.active.keys()])this.cancel(e)}resolveApproval(e,r,n,s){let o=this.active.get(e)?.pendingApprovals.get(r);o&&(this.active.get(e)?.pendingApprovals.delete(r),o({decision:n,reason:s}))}resolveToolCall(e,r,n,s){let o=this.active.get(e)?.pendingTools.get(r);o&&(this.active.get(e)?.pendingTools.delete(r),s?o.reject(new Error(String(n))):o.resolve(n))}async start(e){let{runId:r}=e;if(this.active.has(r))return;let n=!1,s,o,i=p=>{n||((p.type==="done"||p.type==="error")&&(n=!0,p.usage&&o&&(p={...p,usage:{...p.usage,costClass:o}}),p.usage&&(s=p.usage),this.deps.onRunComplete?.(p.type==="done")),this.deps.send({type:"event",runId:r,event:p}))},a=p=>i({type:"error",message:p});if(this.active.size>=this.capacity)return a(`This machine is at capacity (${this.capacity} concurrent runs).`);let l=this.pickAdapter(e.runtime);if(!l)return a(e.runtime?`This machine doesn't have the "${e.runtime}" runtime available.`:"This machine has no agent runtime installed.");o=this.costClassOf(l.id);let c=e.route?.allow;if(c&&o&&!c.includes(o))return a(`This run allows ${c.join(", ")||"no cost class"}, but this machine would serve it as "${o}".`);let d=await dr(e.policy,this.deps.grant);if(!d.ok)return a(d.reason);o&&i({type:"status",message:`Running on ${l.displayName}`,tier:o});let u=new AbortController,f={controller:u,pendingTools:new Map,pendingApprovals:new Map,askTools:d.policy.askTools};this.active.set(r,f);let h=e.messages??(e.prompt?[{role:"user",content:e.prompt}]:[]);try{s=(await l.run({runId:r,messages:h,system:e.system,model:e.model,tools:e.tools,policy:d.policy,...e.route?{route:e.route}:{},signal:u.signal},{emit:i,callTool:(m,g)=>this.callTool(r,m,g),requestApproval:(m,g,y)=>this.approver.request({runId:r,tool:m,input:g,cwd:y},f.askTools)})).usage??s,s&&o&&(s={...s,costClass:o}),n||i({type:"done",usage:s})}catch(p){a(p instanceof Error?p.message:String(p))}finally{this.approver.forget(r),this.active.delete(r),s&&this.deps.send({type:"usage",runId:r,usage:s})}}callTool(e,r,n){let s=this.active.get(e);if(!s)return Promise.reject(new Error("Run is no longer active"));let o=Yn();return new Promise((i,a)=>{s.pendingTools.set(o,{resolve:i,reject:a}),this.deps.send({type:"tool_call",runId:e,callId:o,name:r,input:n})})}askRemote(e){let r=this.active.get(e.runId);if(!r)return Promise.resolve({decision:"deny",reason:"Run is no longer active."});let n=Yn();return new Promise(s=>{r.pendingApprovals.set(n,s),this.deps.send({type:"approval_request",runId:e.runId,approvalId:n,tool:e.tool,input:e.input,cwd:e.cwd})})}pickAdapter(e){return e?this.deps.adapters.get(e):this.deps.adapters.get(this.deps.defaultRuntime)}costClassOf(e){return this.deps.runtimes.find(r=>r.id===e)?.costClass}};var Ea=2e4,et=class{constructor(e){this.deps=e;this.authMode=e.config.auth??"header",this.triedQuery=this.authMode==="query",this.runner=new Qe({adapters:e.adapters,runtimes:e.runtimes,defaultRuntime:e.defaultRuntime,...e.onRunComplete?{onRunComplete:e.onRunComplete}:{},grant:e.grant,send:r=>this.send(r)})}ws=null;backoff=1e3;heartbeat=null;runner;stopped=!1;brokerProtocol=1;authMode;triedQuery=!1;paired=!1;get url(){let e=`${Wr(this.deps.config.broker)}/ws/worker`;return this.authMode==="query"?`${e}?token=${encodeURIComponent(this.deps.config.token)}`:e}connect(){if(this.stopped)return;let e=!1,r=!1;this.paired=!1;let n=()=>{r||(r=!0,this.teardown(),!this.stopped&&(console.log(`[soba] reconnecting in ${Math.round(this.backoff/1e3)}s`),setTimeout(()=>this.connect(),this.backoff),this.backoff=Math.min(this.backoff*2,3e4)))},s=new Wt(this.url,{headers:{Authorization:`Bearer ${this.deps.config.token}`}});this.ws=s,s.on("unexpected-response",(o,i)=>{i.statusCode===401||i.statusCode===403?this.downgrade():console.error(`[soba] broker refused the connection (HTTP ${i.statusCode}).`),i.resume(),o.destroy(),n()}),s.on("open",()=>{e=!0,this.backoff=1e3,console.log(`[soba] connected to ${this.deps.config.broker}`),this.send({type:"hello",protocol:er,worker:{name:Sa.hostname(),version:this.deps.version,platform:process.platform,arch:process.arch,labels:this.deps.labels},runtimes:this.deps.runtimes,concurrency:this.deps.grant.maxConcurrency}),this.heartbeat=setInterval(()=>{this.send({type:"heartbeat",active:this.runner.activeCount,capacity:this.runner.capacity})},Ea)}),s.on("message",o=>this.handle(o.toString())),s.on("close",()=>{e&&!this.paired&&this.downgrade(),n()}),s.on("error",o=>console.error("[soba] socket error:",o.message))}downgrade(){this.triedQuery||this.authMode==="query"||(this.triedQuery=!0,this.authMode="query",console.warn("[soba] this broker doesn't accept the Authorization header; falling back to the deprecated ?token= form. The token will appear in the broker's URLs and logs."),this.persistAuthMode())}persistAuthMode(){try{me({...this.deps.config,auth:this.authMode})}catch{}}stop(){this.stopped=!0,this.teardown();try{this.ws?.close()}catch{}}teardown(){this.heartbeat&&(clearInterval(this.heartbeat),this.heartbeat=null),this.runner.cancelAll()}send(e){this.ws?.readyState===Wt.OPEN&&this.ws.send(JSON.stringify(e))}handle(e){let r=tr(e);if(r)switch(r.type){case"ready":this.paired=!0,this.brokerProtocol=r.protocol??1,this.deps.config.auth!==this.authMode&&this.persistAuthMode(),console.log(`[soba] paired \u2014 ready for runs (broker protocol v${this.brokerProtocol}, auth via ${this.authMode})`);return;case"error":console.error("[soba] broker:",Gr(r.message));return;case"cancel":this.runner.cancel(r.runId);return;case"approval_response":this.runner.resolveApproval(r.runId,r.approvalId,r.decision,r.reason);return;case"tool_result":this.runner.resolveToolCall(r.runId,r.callId,r.result,r.isError===!0);return;case"run":this.runner.start(r);return}}};async function Xn(t,e=$e()){let r=new Map,n=[],s=[];for(let o of e){if(t.allowRuntimes.length&&!t.allowRuntimes.includes(o.id))continue;let i=await o.detect();if(i){if(i.authenticated===!1){s.push(i);continue}r.set(o.id,o),n.push({...i,subscriptionBacked:Zt(i.costClass)})}}return{adapters:r,runtimes:n,unusable:s}}var Ta=/^[iy\r\n]/i;function Zn(t){let e=!1,r=!1,n=async()=>{if(!r){r=!0;try{await t.install(),t.print("[soba] installed. The background service has taken over \u2014 this window is free."),t.standDown?.()}catch(s){t.print(`[soba] couldn't install the service: ${s.message}`),t.print("[soba] still running here. `soba-worker install` will retry.")}}};return{get offered(){return e},runFinished(s){if(!s||e||t.installed)return;if(e=!0,t.auto){t.print("[soba] that worked \u2014 installing the service so it keeps running."),n();return}if(!t.interactive||!t.stdinFree||!t.onKey){t.print("[soba] that worked. `soba-worker install` keeps it running after you close this.");return}t.print("[soba] that worked. Press i to keep it running after you close this window (or ignore this and run `soba-worker install` later).");let o=t.onKey(i=>{o(),Ta.test(i)&&n()})}}}import{spawn as Ra}from"node:child_process";import Ca from"node:os";function es(t){let e=t.replace(/\/+$/,"").replace(/^ws/,"http");return{code:`${e}/v1/device/code`,token:`${e}/v1/device/token`}}function Gt(t){let e;try{e=new URL(t)}catch{return!1}return e.protocol==="https:"?!0:e.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname)}function Qn(t,e){return typeof t=="number"&&Number.isFinite(t)?t:e}function I(t){return typeof t=="string"&&t?t:void 0}async function ts(t){let r=await(t.fetchImpl??fetch)(es(t.broker).code,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client:"soba-worker",version:t.version,hostname:Ca.hostname(),platform:process.platform,arch:process.arch,...t.labels?.length?{labels:t.labels}:{}})});if(!r.ok)throw new Error(`The broker refused to start pairing (${r.status}).`);let n=await r.json(),s=I(n.device_code),o=I(n.user_code),i=I(n.verification_uri);if(!s||!o||!i)throw new Error("The broker's pairing response was missing a required field.");if(!Gt(i))throw new Error(`Refusing to send you to ${i} \u2014 pairing pages must be https.`);let a=I(n.verification_uri_complete);return{deviceCode:s,userCode:o,verificationUri:i,...a&&Gt(a)?{verificationUriComplete:a}:{},expiresAt:Date.now()+Qn(n.expires_in,900)*1e3,intervalMs:Math.max(1e3,Qn(n.interval,5)*1e3)}}async function Aa(t,e,r=fetch){let n=await r(es(t).token,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:e})}),s={};try{s=await n.json()}catch{}let o=I(s.token)??I(s.access_token);if(n.ok&&o)return{status:"ok",result:{token:o,...I(s.broker)?{broker:I(s.broker)}:{}}};switch(s.error){case"authorization_pending":return{status:"pending"};case"slow_down":return{status:"slow_down"};case"access_denied":return{status:"denied",...I(s.error_description)?{reason:I(s.error_description)}:{}};case"expired_token":return{status:"expired"};default:return n.ok?{status:"pending"}:{status:"denied",reason:`broker returned ${n.status}`}}}async function rs(t){let e=t.sleep??(o=>new Promise(i=>setTimeout(i,o))),r=t.now??(()=>Date.now()),n=r(),s=t.device.intervalMs;for(;;){if(r()>=t.device.expiresAt)throw new Error("That pairing code expired. Run `soba-worker login` again.");await e(s),t.onTick?.(r()-n);let o=await Aa(t.broker,t.device.deviceCode,t.fetchImpl);switch(o.status){case"ok":return o.result;case"slow_down":s+=5e3;break;case"denied":throw new Error(`Pairing was declined${o.reason?`: ${o.reason}`:"."}`);case"expired":throw new Error("That pairing code expired. Run `soba-worker login` again.");case"pending":break}}}function ns(t){if(!Gt(t))return;let[e,r]=process.platform==="darwin"?["open",[t]]:process.platform==="win32"?["cmd",["/c","start","",t]]:["xdg-open",[t]];try{Ra(e,r,{stdio:"ignore",detached:!0}).unref()}catch{}}import{existsSync as us,mkdirSync as ss,rmSync as Oa,writeFileSync as os}from"node:fs";import qt from"node:os";import Ee from"node:path";var Ht=["SOBA_HOME","SOBA_POLICY_FILE","SOBA_ENDPOINTS_FILE","SOBA_SERVICE_ENV_FILE"];function is(t=process.env){let e={};for(let r of Ht){let n=t[r];n&&(e[r]=n)}return e}var ae="dev.soba.worker",Se="soba-worker",rt=Ee.join(b,"logs"),as=Ee.join(rt,"worker.log");function Pa(){return Ee.join(qt.homedir(),"Library","LaunchAgents",`${ae}.plist`)}function Ia(t){return t==="system"?`/etc/systemd/system/${Se}.service`:Ee.join(qt.homedir(),".config","systemd","user",`${Se}.service`)}function Vt(t){return process.platform==="darwin"?Pa():Ia(t)}function Ma(t){return/[\\/]_npx[\\/]|[\\/]\.npm[\\/]_cacache[\\/]|^\/tmp\/|[\\/]T[\\/]npx-/.test(t)}function cs(t){let e=/[\\/](\.nvm|\.fnm|\.volta|\.asdf|n)[\\/]/.exec(t);return e?`This command points into ${e[1]}, which changes when you upgrade Node \u2014 re-run \`install\` after a Node upgrade.`:null}async function Na(t={}){let e=t.script??process.argv[1]??"",r=t.execPath??process.execPath;if(t.npx||Ma(e)){let a=await(t.findNpx??(()=>F("npx",Z.map(u=>`${u}/npx`))))();if(!a)throw new Error(`This worker is running from a temporary npx cache, which npm deletes, and \`npx\` itself isn't on PATH to run instead.
324
+ Install the package, then install the service:
325
+ npm install -g @soba-so/worker
326
+ soba-worker install`);let l=t.version?`@soba-so/worker@${t.version}`:"@soba-so/worker",c=[],d=cs(a);return d&&c.push(d),t.version||c.push("No version pinned \u2014 a restart may pick up a newer worker. Prefer a pinned install."),{mode:"npx",argv:[a,"-y",l],warnings:c}}if(!e)throw new Error("Couldn't work out how this worker was started.");let s=[],o=cs(r);return o&&s.push(o),{mode:"direct",argv:[r,e],warnings:s}}function xe(t){return t.replace(/[<>&'"]/g,e=>({"<":"&lt;",">":"&gt;","&":"&amp;","'":"&apos;",'"':"&quot;"})[e])}function La(t,e,r={}){let n=[...t,...e],s=Object.keys(r).length?` <key>EnvironmentVariables</key>
327
+ <dict>
328
+ ${Object.entries(r).map(([o,i])=>` <key>${xe(o)}</key><string>${xe(i)}</string>`).join(`
329
+ `)}
330
+ </dict>
331
+ `:"";return`<?xml version="1.0" encoding="UTF-8"?>
332
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
333
+ <plist version="1.0">
334
+ <dict>
335
+ <key>Label</key><string>${ae}</string>
336
+ <key>ProgramArguments</key>
337
+ <array>
338
+ ${n.map(o=>` <string>${xe(o)}</string>`).join(`
339
+ `)}
340
+ </array>
341
+ ${s} <key>RunAtLoad</key><true/>
342
+ <key>KeepAlive</key><true/>
343
+ <key>ProcessType</key><string>Background</string>
344
+ <key>StandardOutPath</key><string>${xe(as)}</string>
345
+ <key>StandardErrorPath</key><string>${xe(as)}</string>
346
+ </dict>
347
+ </plist>
348
+ `}function $a(t,e,r={}){let n=[...t,...e].map(ls).join(" "),s=Object.entries(r).map(([o,i])=>`Environment=${o}=${ls(i)}`).join(`
349
+ `);return`[Unit]
350
+ Description=Soba worker \u2014 runs agent jobs on this machine, on your own subscription
351
+ After=network-online.target
352
+ Wants=network-online.target
353
+
354
+ [Service]
355
+ Type=simple
356
+ ExecStart=${n}
357
+ ${s}${s?`
358
+ `:""}Restart=always
359
+ RestartSec=5
360
+ # Nothing sensitive here on purpose: the token lives in ~/.soba/worker.json and
361
+ # the rest in ~/.soba/service.env, both 0600. A unit file is world-readable.
362
+
363
+ [Install]
364
+ WantedBy=default.target
365
+ `}function ls(t){return/[\s"'\\]/.test(t)?`"${t.replace(/(["\\])/g,"\\$1")}"`:t}async function O(t,e){try{let{stdout:r,stderr:n,code:s}=await N(t,e,{timeoutMs:2e4});return{ok:s===0,out:`${r}${n}`.trim()}}catch(r){return{ok:!1,out:r.message}}}async function ds(t={}){let e=t.scope??"user",r=t.args??[],n=await Na(t);ss(rt,{recursive:!0});let s=Vt(e);if(ss(Ee.dirname(s),{recursive:!0}),process.platform==="darwin"){os(s,La(n.argv,r,is()),{mode:420});let o=`gui/${process.getuid?.()??""}`;await O("launchctl",["bootout",`${o}/${ae}`]);let i=await O("launchctl",["bootstrap",o,s]);if(!i.ok)throw new Error(`launchctl couldn't load the agent: ${i.out}`);return await O("launchctl",["kickstart",`${o}/${ae}`]),{...await ce(e),mode:n.mode,command:n.argv,warnings:n.warnings}}if(process.platform==="linux"){os(s,$a(n.argv,r,is()),{mode:420});let o=tt(e);await O(o[0],[...o.slice(1),"daemon-reload"]);let i=await O(o[0],[...o.slice(1),"enable","--now",Se]);if(!i.ok)throw new Error(`systemctl couldn't start the service: ${i.out}`);return{...await ce(e),mode:n.mode,command:n.argv,warnings:n.warnings}}throw new Error(`No service manager is wired up for ${process.platform} yet.`)}async function ps(t="user"){let e=Vt(t);if(process.platform==="darwin")await O("launchctl",["bootout",`gui/${process.getuid?.()??""}/${ae}`]);else if(process.platform==="linux"){let r=tt(t);await O(r[0],[...r.slice(1),"disable","--now",Se])}if(us(e)&&Oa(e,{force:!0}),process.platform==="linux"){let r=tt(t);await O(r[0],[...r.slice(1),"daemon-reload"])}}async function ce(t="user"){let e=Vt(t);if(process.platform!=="darwin"&&process.platform!=="linux")return{state:"unsupported",scope:t,unitPath:e,detail:`${process.platform} isn't supported yet.`};if(!us(e))return{state:"absent",scope:t,unitPath:e};if(process.platform==="darwin"){let s=await O("launchctl",["print",`gui/${process.getuid?.()??""}/${ae}`]);if(!s.ok)return{state:"installed",scope:t,unitPath:e,detail:"not loaded"};let o=/\bpid = (\d+)/.exec(s.out)?.[1];return o?{state:"running",scope:t,unitPath:e,detail:`pid ${o}`}:{state:"installed",scope:t,unitPath:e,detail:"loaded, not running"}}let r=tt(t),n=await O(r[0],[...r.slice(1),"is-active",Se]);return n.out.trim()==="active"?{state:"running",scope:t,unitPath:e}:{state:"installed",scope:t,unitPath:e,detail:n.out.trim()||"inactive"}}function tt(t){return t==="system"?["systemctl"]:["systemctl","--user"]}async function fs(t){if(process.platform!=="linux"||t!=="user")return null;let e=qt.userInfo().username,r=await O("loginctl",["show-user",e,"--property=Linger"]);return r.ok&&/Linger=yes/.test(r.out)?null:`Run \`sudo loginctl enable-linger ${e}\` so the worker keeps running after you log out.`}import{existsSync as Ba,mkdirSync as Da,readFileSync as Ua,writeFileSync as ja}from"node:fs";import Fa from"node:path";var nt=process.env.SOBA_SERVICE_ENV_FILE??Fa.join(b,"service.env");function Wa(t){let e={};for(let r of t.split(`
366
+ `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let s=n.indexOf("=");if(s<=0)continue;let o=n.slice(0,s).trim(),i=n.slice(s+1).trim();(i.startsWith('"')&&i.endsWith('"')&&i.length>1||i.startsWith("'")&&i.endsWith("'")&&i.length>1)&&(i=i.slice(1,-1)),o&&(e[o]=i)}return e}function Ga(t){return`${["# Written by `soba-worker install`. Loaded by the worker at startup.","# Mode 0600 on purpose: the service definition stays secret-free.",...Object.entries(t).map(([r,n])=>`${r}=${JSON.stringify(n).slice(1,-1)}`)].join(`
367
+ `)}
368
+ `}function hs(t=process.env){if(!Ba(nt))return[];let e;try{e=Wa(Ua(nt,"utf8"))}catch{return[]}let r=[];for(let[n,s]of Object.entries(e))t[n]===void 0&&(t[n]=s,r.push(n));return r}function ms(t){Da(b,{recursive:!0}),ja(nt,Ga(t),{mode:384})}var gs=nt;function qa(t,e,r){return[`soba-worker ${M}`,"","Runtimes detected:",...t.length?t.map(s=>` ${s.id.padEnd(14)} ${(s.version??"(unknown version)").padEnd(12)} ${s.costClass}`):[" (none \u2014 install the `claude` or `codex` CLI)"],...e.length?["","Installed but NOT usable (withheld from the broker):",...e.map(s=>` ${s.id.padEnd(14)} ${s.authHint??"signed out"}`)]:[],"",`Policy (${ct}):`,` roots ${r.roots.join(", ")}`,` tools ${r.allowTools.join(", ")||"(none)"}`,` ask ${r.askTools.join(", ")||"(none)"}`,` denied ${r.denyTools.join(", ")||"(none)"}`,` concurrency ${r.maxConcurrency}`,` mode ${r.permissionMode}`,` app tools ${r.allowAppTools?"allowed":"refused"}`,` metered keys ${r.allowMeteredKeys?"MAY be spent":"stripped from runs"}`,` approver ${r.approver}`,"",`Config: ${wt}`,`Endpoints: ${hr}`].join(`
369
+ `)}function st(t){return`${t.state==="running"?"running":t.state==="installed"?`installed but ${t.detail??"not running"}`:t.state==="absent"?"not installed":t.detail??"unsupported"}${t.state==="running"&&t.detail?` (${t.detail})`:""}`}function Ha(t){return process.stdin.isTTY?(process.stdout.write(t),new Promise(e=>{let r=n=>{process.stdin.pause(),process.stdout.write(`
370
+ `),e(n)};process.stdin.resume(),process.stdin.once("data",n=>r(!/^n/i.test(n.toString().trim())))})):Promise.resolve(!1)}async function Va(t){let e=t.broker??process.env.SOBA_BROKER_URL??Be().broker;if(!e)throw new Error("Which broker? Pass --broker https://your-app.example.com");let r=await ts({broker:e,version:M,...t.labels?{labels:t.labels}:{}}),n=r.verificationUriComplete??r.verificationUri;console.log(`
371
+ Your code: ${r.userCode}
372
+ Approve at: ${r.verificationUri}
373
+ `),!t.noBrowser&&await Ha(" Press Enter to open that in your browser (or n to skip)\u2026 ")&&ns(n),console.log("[soba] waiting for you to approve\u2026");let s=await rs({broker:e,device:r}),o={broker:s.broker??e,token:s.token};if(me(o),t.broker=o.broker,t.pair=o.token,console.log(`[soba] paired. The token is in ${wt} (0600) \u2014 it was never shown or pasted.`),t.install){await Kt({...t,command:"install"});return}console.log("[soba] starting. Run `soba-worker install` to keep it running after you close this.")}async function Kt(t){let e=t.system?"system":"user";if(t.command==="service-status"){let o=await ce(e);console.log(`[soba] service ${st(o)}
374
+ ${o.unitPath}`);return}if(t.command==="uninstall"){await ps(e),console.log("[soba] service removed. The pairing token is untouched \u2014 `--reset` clears that.");return}Ka();let r=[];for(let o of t.labels??[])r.push("--label",o);t.runtime&&r.push("--runtime",t.runtime);let n=await ds({scope:e,args:r,version:M,...t.npx?{npx:!0}:{}});console.log(`[soba] service ${st(n)}
375
+ via ${n.mode==="npx"?"npx":"the installed package"}: ${n.command.join(" ")}
376
+ unit ${n.unitPath}
377
+ logs ${rt}
378
+ env ${gs} (0600; the unit itself carries no secrets)`);for(let o of n.warnings)console.log(`[soba] note: ${o}`);let s=await fs(e);s&&console.log(`[soba] ${s}`)}function Ka(){let t=new Set;try{for(let n of de())n.apiKeyEnv&&t.add(n.apiKeyEnv)}catch{}let e=new Set(Ht);for(let n of Object.keys(process.env))!n.startsWith("SOBA_")||n==="SOBA_PAIR_TOKEN"||e.has(n)||t.add(n);let r={};for(let n of t){let s=process.env[n];s&&(r[n]=s)}Object.keys(r).length&&(ms(r),console.log(`[soba] captured for the service: ${Object.keys(r).sort().join(", ")}`))}async function za(){let t=Dr(process.argv.slice(2));if(t.help)return void console.log(yt);if(t.version)return void console.log(M);if(t.reset)return Fr(),void console.log("[soba] cleared cached token + broker.");if(hs(),t.command)try{if(t.command!=="login")return await Kt(t);if(await Va(t),t.install)return}catch(m){return console.error(`[soba] ${m.message}`),process.exit(1)}let e;try{e=ur()}catch(m){console.error(`[soba] ${m.message}`),process.exit(1)}let r;try{r=$e(de())}catch(m){return console.error(`[soba] ${m.message}`),process.exit(1)}let{adapters:n,runtimes:s,unusable:o}=await Xn(e,r);if(t.status){let m=await ce(t.system?"system":"user");if(t.json){let g=Be();return void console.log(JSON.stringify({version:M,paired:!!g.token,broker:g.broker??null,runtimes:s.map(y=>({id:y.id,displayName:y.displayName,version:y.version??null,costClass:y.costClass,authenticated:y.authenticated??null})),unusable:o.map(y=>({id:y.id,displayName:y.displayName,authHint:y.authHint??null})),policy:{path:ct,roots:e.roots,allowTools:e.allowTools,askTools:e.askTools,denyTools:e.denyTools,maxConcurrency:e.maxConcurrency},service:{state:st(m),unitPath:m.unitPath??null}}))}return void console.log(`${qa(s,o,e)}
379
+ Service: ${st(m)}`)}s.length||(console.error(o.length?`[soba] no usable agent runtime on this machine.
380
+ `+o.map(m=>` ${m.id}: ${m.authHint??"signed out"}`).join(`
381
+ `):"[soba] no agent runtime found on this machine.\nInstall the Claude CLI (`claude`) or the Codex CLI (`codex`) and sign in, then try again."),process.exit(1));let i=Be(),a=_t(t.broker,process.env.SOBA_BROKER_URL,i.broker),l=_t(t.pair,process.env.SOBA_PAIR_TOKEN,i.token);(!a||!l)&&(console.error(`[soba] missing ${l?"broker host":"pairing token"}.
382
+
383
+ ${yt}`),process.exit(1));let c={broker:a,token:l};(i.broker!==a||i.token!==l)&&me(c);let d=t.runtime??s[0]?.id??"";n.has(d)||(console.error(`[soba] runtime "${d}" isn't available on this machine.`),process.exit(1)),console.log(`[soba] serving ${s.map(m=>m.id).join(", ")} \xB7 default ${d} \xB7 ${e.maxConcurrency} concurrent \xB7 roots ${e.roots.join(", ")}`);let u=await ce(t.system?"system":"user"),f=Zn({installed:u.state!=="absent",interactive:!!process.stdin.isTTY,stdinFree:!(e.approver==="local"&&e.askTools.length>0),auto:!!t.autoInstall,print:m=>console.log(m),install:async()=>{await Kt({...t,command:"install"})},standDown:()=>{h.stop(),process.exit(0)},onKey:m=>{let g=y=>m(y.toString());return process.stdin.once("data",g),process.stdin.resume(),()=>{process.stdin.off("data",g),process.stdin.pause()}}}),h=new et({config:c,version:M,adapters:n,runtimes:s,defaultRuntime:d,grant:e,labels:t.labels??[],...t.noInstallPrompt?{}:{onRunComplete:m=>f.runFinished(m)}}),p=()=>{console.log(`
384
+ [soba] shutting down.`),h.stop(),process.exit(0)};process.on("SIGINT",p),process.on("SIGTERM",p),h.connect()}za();
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@soba-so/worker",
3
+ "version": "0.0.1",
4
+ "description": "Run agent jobs on your own machine, on your own subscription. Dials out to a Soba broker; opens no ports.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://soba.so/docs/connect",
7
+ "type": "module",
8
+ "bin": {
9
+ "soba-worker": "dist/worker.mjs"
10
+ },
11
+ "files": [
12
+ "dist/worker.mjs",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "prepublishOnly": "node ../../scripts/build-worker.mjs"
17
+ },
18
+ "engines": {
19
+ "node": ">=22"
20
+ },
21
+ "keywords": [
22
+ "soba",
23
+ "agent",
24
+ "claude",
25
+ "codex",
26
+ "worker",
27
+ "byoc"
28
+ ],
29
+ "devDependencies": {
30
+ "@soba-so/protocol": "workspace:*",
31
+ "@soba-so/runtime": "workspace:*",
32
+ "@soba-so/tokens": "workspace:*",
33
+ "ws": "^8.18.0"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/andreachello/soba.git",
41
+ "directory": "packages/worker"
42
+ }
43
+ }