@2digits/tlo-mcp 2.0.0 → 2.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.
Files changed (2) hide show
  1. package/dist/bin.mjs +8 -7
  2. package/package.json +7 -7
package/dist/bin.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import*as e from"@effect/platform-node/NodeRuntime";import*as t from"@effect/platform-node/NodeServices";import*as n from"effect/Effect";import*as r from"effect/Schema";import*as i from"effect/cli/Command";import*as a from"effect/cli/Flag";import{OAuth as o,Pkce as s}from"@yielded/oauth";import*as c from"effect/Clock";import*as l from"effect/Context";import*as u from"effect/Crypto";import*as d from"effect/Equal";import*as f from"effect/Exit";import*as p from"effect/Layer";import*as m from"effect/Match";import*as h from"effect/Redacted";import*as ee from"effect/Semaphore";import{FetchHttpClient as g,HttpClient as _,HttpClientRequest as v,HttpClientResponse as te,HttpIncomingMessage as ne,HttpRouter as y,HttpServer as re,HttpServerRequest as b,HttpServerResponse as x}from"effect/http";import{ChildProcess as S,ChildProcessSpawner as C}from"effect/process";import{createHash as ie,randomBytes as ae,timingSafeEqual as oe}from"node:crypto";import{createServer as se}from"node:http";import*as ce from"@effect/platform-node/NodeHttpServer";import*as w from"effect/Deferred";import*as le from"effect/Predicate";import*as ue from"node:os";import{homedir as de}from"node:os";import*as fe from"effect/FileSystem";import*as pe from"effect/Path";import*as T from"effect/Stream";import{Context as me,Effect as E,Layer as D,Option as he,Queue as O,Schema as k,Stream as ge}from"effect";import{HttpApi as _e,HttpApiClient as ve,HttpApiEndpoint as A,HttpApiGroup as ye,HttpApiMiddleware as be,HttpApiSchema as xe,HttpApiSecurity as Se,OpenApi as Ce}from"effect/http-api";import*as j from"node:fs/promises";import*as M from"node:path";import*as we from"node:net";import{Duplex as Te}from"node:stream";import*as Ee from"node:tls";import*as De from"effect/ByteSize";import*as N from"effect/ai/McpProtocol";import*as Oe from"effect/ai/McpServer";import*as ke from"effect/Option";import*as Ae from"effect/Struct";import*as P from"effect/ai/McpSchema";import*as je from"effect/encoding/Sse";const Me=`https://api.orbit.teamleader.eu`,F=`${Me}/mcp`,Ne=r.RedactedFromValue(r.String.check(r.isMinLength(1))),Pe=r.Struct({clientId:r.String.check(r.isMinLength(1)),clientSecret:r.optionalKey(Ne),accessToken:Ne,refreshToken:r.optionalKey(Ne),expiresAt:r.optionalKey(r.Finite)});var I=class extends r.TaggedError()(`OrbitAuthError`,{message:r.String}){};function Fe(e,t,n){let r=t.refreshToken??e.refreshToken;return{clientId:e.clientId,...e.clientSecret===void 0?{}:{clientSecret:e.clientSecret},accessToken:t.accessToken,...r===void 0?{}:{refreshToken:r},...t.expiresIn===void 0?{}:{expiresAt:n+t.expiresIn*1e3}}}function Ie(e,t){return e.expiresAt===void 0||e.expiresAt<=t+6e4}function Le(e){return e.clientSecret===void 0?{method:`none`,publicClient:!0}:{method:`client_secret_post`,secret:e.clientSecret.pipe(h.value,h.make)}}function Re(e,t){let n=e.searchParams.get(`state`);if(n===null||e.pathname!==`/callback`||e.searchParams.getAll(`state`).length!==1)return;let r=Buffer.from(t),i=Buffer.from(n);if(r.length!==i.length||!oe(r,i))return;if(e.searchParams.has(`error`))throw Error(`Orbit authorization was denied.`);let a=e.searchParams.get(`code`);if(a!==null&&a.length!==0&&e.searchParams.getAll(`code`).length===1)return a}const ze=n.fn(`OrbitAuth.listenForLogin`)(function*(e){let t=yield*w.make(),r=yield*n.sync(se),i=yield*ce.make(()=>r,{port:0,host:`127.0.0.1`}).pipe(n.mapError(()=>I.make({message:`Could not bind OAuth callback.`})));if(!le.isTagged(i.address,`InetAddressV4`))return yield*I.make({message:`Could not bind OAuth callback.`});let a=`127.0.0.1:${i.address.port}`,o=`http://${a}/callback`,s={"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,"referrer-policy":`no-referrer`,"content-security-policy":`default-src 'none'`},c=x.text(`Invalid callback.`,{status:400,headers:s}),l=x.text(`Authorization received. Return to your terminal to complete login.`,{headers:s}),u=x.text(`Authorization denied. Return to your terminal.`,{status:400,headers:s}),d=n.fn(`OrbitAuth.handleCallback`)(function*(){let r=yield*b.HttpServerRequest;return r.method!==`GET`||r.headers.host!==a||(yield*w.isDone(t))?c:yield*n.try({try:()=>Re(new URL(r.url,o),e),catch:()=>I.make({message:`Orbit authorization was denied.`})}).pipe(n.matchEffect({onFailure:e=>w.fail(t,e).pipe(n.map(e=>e?u:c)),onSuccess:e=>e===void 0?n.succeed(c):w.succeed(t,e).pipe(n.map(e=>e?l:c))}))}),f=yield*y.toHttpEffect(y.add(`*`,`*`,d()));return yield*re.serveEffect(f).pipe(n.provideService(re.HttpServer,i)),yield*n.addFinalizer(()=>n.sync(()=>r.closeAllConnections())),{redirectUri:o,code:w.await(t).pipe(n.timeout(`3 minutes`),n.mapError(()=>I.make({message:`Login denied or timed out. Run tlo-mcp login again.`})))}}),Be=r.fromJsonString(Pe),Ve=`@2digits/tlo-mcp/orbit`;var L=class extends l.Service()(`@2digits/tlo-mcp/oauth/store/SessionStore`){};function He(e){return`"${e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}"`}function Ue(e={}){return p.effect(L,n.gen(function*(){let t=yield*fe.FileSystem,i=yield*pe.Path,a=yield*C.ChildProcessSpawner,o=e.platform??process.platform,s=e.directory??i.join(de(),`.config`,`2digits`,`tlo-mcp`),c=i.join(s,`session.json`),l=i.join(s,`session.lock`),u=t.makeDirectory(s,{recursive:!0,mode:448}).pipe(n.andThen(t.chmod(s,448))),d=n.fn(`SessionStore.security`)(function*(e,t){let r=yield*a.spawn(S.make(`/usr/bin/security`,e,{stdin:t===void 0?`ignore`:T.succeed(new TextEncoder().encode(t)),stderr:`ignore`}));return yield*n.all({output:r.stdout.pipe(T.decodeText(),T.mkString),exitCode:r.exitCode},{concurrency:`unbounded`})},n.scoped),f=n.fn(`SessionStore.load`)(function*(){let e;if(o===`darwin`){let t=yield*d([`find-generic-password`,`-a`,`orbit`,`-s`,Ve,`-w`]);if(t.exitCode===44)return;if(t.exitCode!==0)return yield*I.make({message:`Could not read macOS Keychain.`});e=t.output.trim()}else{let r=yield*t.readFileString(c).pipe(n.catchReason(`PlatformError`,`NotFound`,()=>n.void));if(r===void 0)return;e=r}return yield*r.decodeEffect(Be)(e)},n.mapError(()=>I.make({message:`Could not read credentials. Run tlo-mcp login again.`}))),p=n.fn(`SessionStore.save`)(function*(e){let n=yield*r.encodeEffect(Be)(e);if(o===`darwin`){if((yield*d([`-q`,`-i`],`add-generic-password -U -a orbit -s ${He(Ve)} -w ${He(n)}\n`)).exitCode!==0)return yield*I.make({message:`Could not save macOS Keychain credentials.`})}else{yield*u;let e=yield*t.makeTempDirectoryScoped({directory:s,prefix:`session-`}),r=i.join(e,`session.json`);yield*t.writeFileString(r,n,{mode:384}),yield*t.rename(r,c)}},n.scoped,n.mapError(()=>I.make({message:`Could not persist OAuth credentials. Run tlo-mcp login again.`}))),m=n.fn(`SessionStore.clear`)(function*(){if(o===`darwin`){let e=yield*d([`delete-generic-password`,`-a`,`orbit`,`-s`,Ve]);if(e.exitCode!==0&&e.exitCode!==44)return yield*I.make({message:`Could not remove Keychain credentials.`})}else yield*t.remove(c,{force:!0})},n.mapError(()=>I.make({message:`Could not remove OAuth credentials.`}))),h=n.fn(`SessionStore.lock`)(function*(){yield*u,yield*n.acquireRelease(t.writeFileString(l,String(process.pid),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>I.make({message:`OAuth credentials locked. Close other login/refresh processes. After a crash only, remove ${l}.`}))),()=>t.remove(l).pipe(n.orDie))},n.mapError(e=>r.is(I)(e)?e:I.make({message:`Could not acquire OAuth credential lock. Check directory permissions.`})));return L.of({load:f(),save:p,clear:m(),lock:h()})}))}const We=Ue(),Ge=r.Struct({client_id:r.String.check(r.isMinLength(1)),client_secret:r.String.check(r.isMinLength(1)).pipe(r.RedactedFromValue,r.optionalKey)});var R=class extends l.Service()(`@2digits/tlo-mcp/oauth/OrbitAuth`){};const Ke=p.effect(R,n.gen(function*(){let e=yield*L,t=yield*u.Crypto,i=yield*_.HttpClient,a=yield*C.ChildProcessSpawner,l=yield*ee.make(1),p=yield*n.fn(`OrbitAuth.discover`)(function*(){let e=yield*_.withScope(i).get(`${Me}/.well-known/oauth-authorization-server`);if(e.status!==200)return yield*I.make({message:`Could not discover Orbit OAuth endpoints.`});let t=yield*e.json.pipe(n.flatMap(r.decodeUnknownEffect(o.Metadata)));return t.issuer!==`https://api.orbit.teamleader.eu`||t.authorization_endpoint!==`https://api.orbit.teamleader.eu/oauth2/Authorize`||t.token_endpoint!==`https://api.orbit.teamleader.eu/oauth2/access_token`?yield*I.make({message:`Unexpected Orbit endpoints; refusing to send credentials.`}):t},n.scoped,n.timeout(`15 seconds`),n.mapError(()=>I.make({message:`Invalid or unavailable Orbit OAuth metadata.`})))().pipe(n.cachedWithTTL(e=>f.isSuccess(e)?1/0:0)),te=n.fn(`OrbitAuth.accessToken`)(function*(){let t=yield*e.load;if(t===void 0)return yield*I.make({message:`Not authenticated. Run tlo-mcp login first.`});if(!Ie(t,yield*c.currentTimeMillis))return t.accessToken;if(t.refreshToken===void 0)return t.expiresAt===void 0?t.accessToken:yield*I.make({message:`Orbit session expired without a refresh token. Run tlo-mcp login.`});let r=yield*p,i=Fe(t,yield*(yield*o.make({metadata:r,clientId:t.clientId,authentication:Le(t),timeoutMs:15e3})).refreshGrant({refreshToken:t.refreshToken,resources:[F]}).pipe(n.flatMap(o.tokens)),yield*c.currentTimeMillis);return yield*e.save(i),i.accessToken}),ne=n.fn(`OrbitAuth.register`)(function*(e){let t=yield*v.post(`${Me}/oauth2/register`).pipe(v.bodyJson({client_name:`@2digits/tlo-mcp`,redirect_uris:[e],response_types:[`code`],grant_types:[`authorization_code`,`refresh_token`],token_endpoint_auth_method:`none`}),n.flatMap(_.withScope(i).execute));return t.status!==200&&t.status!==201?yield*I.make({message:`Orbit client registration failed (HTTP ${t.status}).`}):yield*t.json.pipe(n.flatMap(r.decodeUnknownEffect(Ge)))},n.scoped,n.timeout(`15 seconds`)),y=n.fn(`OrbitAuth.openBrowser`)(function*(e){return yield*(yield*m.value(process.platform).pipe(m.when(`darwin`,()=>S.make({stdout:`ignore`,stderr:`ignore`,forceKillAfter:`1 second`})`open ${h.value(e)}`),m.when(`win32`,()=>S.make({stdout:`ignore`,stderr:`ignore`,forceKillAfter:`1 second`})`rundll32 url.dll,FileProtocolHandler ${h.value(e)}`),m.orElse(()=>S.make({stdout:`ignore`,stderr:`ignore`,forceKillAfter:`1 second`})`xdg-open ${h.value(e)}`))).exitCode},n.scoped,n.timeout(`5 seconds`),n.filterOrFail(d.equals(C.ExitCode(0)),()=>I.make({message:`Could not open browser.`})),(e,t)=>e.pipe(n.catch(()=>n.sync(()=>{process.stderr.write(`Open this URL in your browser:\n${h.value(t)}\n`)})))),re=n.fn(`OrbitAuth.login`)(function*(){let t=yield*p,r=yield*s.random(),i=yield*s.make(),a=yield*r.pipe(h.value,ze),l=yield*ne(a.redirectUri),u={clientId:l.client_id,...l.client_secret===void 0?{}:{clientSecret:l.client_secret}},d=yield*o.make({metadata:t,...u,authentication:Le(u),timeoutMs:15e3}),f=yield*d.authorizationUrl({redirectUri:a.redirectUri,scopes:[],state:r,codeChallenge:i.challenge,resources:[F]});yield*y(f);let m=yield*a.code,ee=yield*d.codeGrant({code:h.make(m),redirectUri:a.redirectUri,pkceVerifier:i.verifier,resources:[F]}).pipe(n.flatMap(o.tokens));yield*e.save(Fe(u,ee,yield*c.currentTimeMillis)),yield*n.sync(()=>{process.stderr.write(`Orbit login complete.
3
- `)})}),b=n.fn(`OrbitAuth.locked`)(function*(t){return yield*e.lock,yield*t},n.scoped,l.withPermit,n.provideService(_.HttpClient,i),n.provideService(u.Crypto,t),n.provideService(C.ChildProcessSpawner,a),n.provideService(g.RequestInit,{redirect:`error`}),n.mapError(e=>r.is(I)(e)?e:I.make({message:`Orbit authentication unavailable. Check connectivity or run tlo-mcp login again.`})));return R.of({accessToken:b(te()),login:b(re()),logout:b(e.clear)})})).pipe(p.provide(We),p.provide(g.layer)),qe=k.String.pipe(k.brand(`CSR.Raw`)),Je=k.String.pipe(k.brand(`Hostname`));function Ye(){return(e,t)=>{class n{static makeUnsafe(e){return e}}return Object.setPrototypeOf(n,t),n}}var Xe=class extends Ye()(`CertificateID`,k.String){};k.String.pipe(k.brand(`ChallengeToken`));var Ze=class extends k.Class(`Certificate/StateChallenge`)({type:k.Literal(`challenge`),token:k.String,key:k.String}){},Qe=class extends k.Class(`Certificate/StateIssuing`)({type:k.Literal(`issuing`)}){},$e=class extends k.Class(`Certificate/StateReady`)({type:k.Literal(`ready`),certificate:k.String,chain:k.String,expiry:k.String}){},et=class extends k.Class(`Certificate/StateFailed`)({type:k.Literal(`failed`),reason:k.String}){};const tt=k.Union([Ze,Qe,$e,et]);var nt=class extends k.Class(`Certificate`)({id:Xe,state:tt}){},z=class extends Ye()(`TunnelID`,k.String){};const B=k.String.pipe(k.brand(`TunnelToken`));k.TaggedError()(`NotFound`,{tunnelID:z}),k.TaggedError()(`NoCertificate`,{tunnelID:z}),k.TaggedError()(`CertificateNotReady`,{tunnelID:z,currentState:k.String}),k.TaggedError()(`InvalidHostname`,{provided:Je,expected:Je});const rt=k.Literals([`offline`,`online`]);var it=class extends k.Class(`Tunnel/Info`)({id:z,hostname:Je,state:rt,certificateID:Xe.pipe(k.optional)}){},at=`0.2.2`,ot=class extends k.TaggedError()(`InvalidRequestError`,{message:k.String},{httpApiStatus:400}){},st=class extends k.TaggedError()(`UnauthorizedError`,{message:k.String},{httpApiStatus:401}){},V=class extends k.TaggedError()(`TunnelNotFoundError`,{tunnelID:k.String,message:k.String},{httpApiStatus:404}){},ct=class extends k.TaggedError()(`CertificateNotFoundError`,{tunnelID:k.String,message:k.String},{httpApiStatus:404}){},lt=class extends k.TaggedError()(`InvalidHostnameError`,{provided:k.String,expected:k.String,message:k.String},{httpApiStatus:400}){},ut=class extends k.TaggedError()(`HostnameUnavailableError`,{name:k.String,message:k.String},{httpApiStatus:409}){},dt=class extends k.TaggedError()(`CertificateInProgressError`,{tunnelID:k.String,message:k.String},{httpApiStatus:409}){},H=class extends k.TaggedError()(`ServiceUnavailableError`,{message:k.String},{httpApiStatus:503}){};me.Service()(`@opentunnel/protocol/OpenTunnelAuthorizationToken`);var U=class extends be.Service()(`@opentunnel/protocol/OpenTunnelAuthorization`,{security:{bearer:Se.bearer},error:st}){};const ft=k.Struct({name:k.String.pipe(k.optional)}),pt=k.Struct({tunnel:it,token:B}).pipe(xe.status(201)),mt=ye.make(`tunnel`).add(A.post(`tunnel.create`,`/api/tunnel`,{payload:ft,success:pt,error:[ot,ut,H]})).add(A.get(`tunnel.get`,`/api/tunnel/:id`,{params:k.Struct({id:z}),success:it,error:[V,H]}).middleware(U)).add(A.post(`tunnel.bindCertificate`,`/api/tunnel/:id/certificate`,{params:k.Struct({id:z}),payload:k.Struct({csr:qe}),success:nt.pipe(xe.status(202)),error:[ot,lt,V,dt,H]}).middleware(U)).add(A.get(`tunnel.getCertificate`,`/api/tunnel/:id/certificate`,{params:k.Struct({id:z}),success:nt,error:[V,ct,H]}).middleware(U)).add(A.delete(`tunnel.remove`,`/api/tunnel/:id`,{params:k.Struct({id:z}),success:xe.NoContent,error:[V,H]}).middleware(U)).add(A.get(`tunnel.connect`,`/api/tunnel/:id/connect`,{params:k.Struct({id:z}),success:k.Boolean,error:[V]}).annotateMerge(Ce.annotations({summary:`Connect a bridge WebSocket`,description:`This endpoint upgrades to the opentunnel WebSocket protocol.`}))).annotateMerge(Ce.annotations({title:`tunnel`})),ht=_e.make(`opentunnel`).add(mt).annotateMerge(Ce.annotations({title:`OpenTunnel API`,version:`0.1.0`,description:`Create and manage blind TLS tunnels.`})),gt=`opentunnel-sdk/${at}`;var _t=class e extends me.Service()(`@opentunnel/client/OpenTunnelApiClient`){static layer(t){return D.effect(e,E.gen(function*(){let e=(yield*_.HttpClient).pipe(_.mapRequest(v.setHeader(`user-agent`,gt)));return{client:yield*ve.makeWith(ht,{baseUrl:t.api,httpClient:e}),authorized:n=>ve.makeWith(ht,{baseUrl:t.api,httpClient:e.pipe(_.mapRequest(v.bearerToken(n)))})}})).pipe(D.provide(g.layer))}};const W=(e,...t)=>{let n=vt(t),r=n.length<128?[n.length]:(()=>{let e=[];for(let t=n.length;t>0;t>>=8)e.unshift(t&255);return[128|e.length,...e]})();return vt([new Uint8Array([e,...r]),n])},vt=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},G=(...e)=>W(48,...e),yt=(...e)=>W(49,...e),bt=e=>W(12,new TextEncoder().encode(e)),xt=e=>W(130,new TextEncoder().encode(e)),K=e=>{let[t,n,...r]=e.split(`.`).map(Number),i=[t*40+n];for(let e of r){let t=[e&127];for(let n=e>>7;n>0;n>>=7)t.unshift(n&127|128);i.push(...t)}return W(6,new Uint8Array(i))},St=e=>{let t=0;for(;t<e.length-1&&e[t]===0;)t++;let n=e.subarray(t);return W(2,n[0]&128?vt([new Uint8Array([0]),n]):n)};async function Ct(e,t){let n=new Uint8Array(await crypto.subtle.exportKey(`spki`,t.publicKey)),r=G(W(2,new Uint8Array([0])),G(yt(G(K(`2.5.4.3`),bt(e)))),n,W(160,G(K(`1.2.840.113549.1.9.14`),yt(G(G(K(`2.5.29.17`),W(4,G(xt(e),xt(`*.${e}`))))))))),i=new Uint8Array(await crypto.subtle.sign({name:`ECDSA`,hash:`SHA-256`},t.privateKey,r)),a=G(St(i.subarray(0,32)),St(i.subarray(32))),o=G(r,G(K(`1.2.840.10045.4.3.2`)),W(3,new Uint8Array([0]),a));return`-----BEGIN CERTIFICATE REQUEST-----\n${Buffer.from(o).toString(`base64`).replace(/.{1,64}/g,`$&
4
- `)}-----END CERTIFICATE REQUEST-----`}var wt=class extends k.TaggedError()(`OpenTunnelClientError`,{message:k.String,cause:k.optional(k.Defect())}){},q=class extends k.TaggedError()(`OpenTunnelStorageError`,{message:k.String,cause:k.optional(k.Defect())}){};function Tt(e={}){let t=e.env??process.env,n=e.home??ue.homedir(),r=t.XDG_DATA_HOME??M.join(n,`.local`,`share`),i=M.join(r,`opentunnel`),a=e=>M.join(i,e),o=e=>E.tryPromise({try:()=>j.readFile(e,`utf8`),catch:e=>e}).pipe(E.catch(t=>E.gen(function*(){if(!(typeof t==`object`&&t&&`code`in t&&t.code===`ENOENT`))return yield*new q({message:`Failed to read ${e}`,cause:t})}))),s=E.fn(`OpenTunnelStorage.profiles`)(function*(){return(yield*E.tryPromise({try:()=>j.readdir(i,{withFileTypes:!0}),catch:e=>e}).pipe(E.catch(e=>E.gen(function*(){return typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`?[]:yield*new q({message:`Failed to list ${i}`,cause:e})})))).filter(e=>e.isDirectory()).map(e=>e.name).sort()}),c=E.fn(`OpenTunnelStorage.load`)(function*(e){let t=a(e),n=yield*o(M.join(t,`tunnel.json`));if(!n)return;let[r,i,s,c]=yield*E.all([o(M.join(t,`token`)),o(M.join(t,`private-key.pem`)),o(M.join(t,`certificate.pem`)),o(M.join(t,`chain.pem`))]);if(!r||!i||!s||c===void 0)return yield*new q({message:`Incomplete tunnel identity for ${e}`});let l=JSON.parse(n);return{id:l.id,hostname:l.hostname,token:r.trim(),privateKey:i,certificate:s,chain:c,certificateExpiry:new Date(l.certificateExpiry)}}),l=E.fn(`OpenTunnelStorage.loadPending`)(function*(e){let t=a(e),n=yield*o(M.join(t,`pending.json`));if(!n)return;let[r,i]=yield*E.all([o(M.join(t,`token`)),o(M.join(t,`private-key.pem`))]);if(!r||!i)return yield*new q({message:`Incomplete pending tunnel identity for ${e}`});let s=JSON.parse(n);return{id:s.id,hostname:s.hostname,token:r.trim(),privateKey:i,csr:s.csr}});return{profiles:()=>s(),load:e=>c(e),loadPending:e=>l(e),savePending:(e,t)=>E.tryPromise({try:async()=>{let n=a(e);await j.mkdir(n,{recursive:!0,mode:448}),await Promise.all([j.writeFile(M.join(n,`pending.json`),JSON.stringify({id:t.id,hostname:t.hostname,csr:t.csr},null,2),{mode:384}),j.writeFile(M.join(n,`token`),`${t.token}\n`,{mode:384}),j.writeFile(M.join(n,`private-key.pem`),t.privateKey,{mode:384})])},catch:t=>new q({message:`Failed to save pending tunnel identity for ${e}`,cause:t})}),save:(e,t)=>E.tryPromise({try:async()=>{let n=a(e);await j.mkdir(n,{recursive:!0,mode:448}),await Promise.all([j.writeFile(M.join(n,`tunnel.json`),JSON.stringify({id:t.id,hostname:t.hostname,certificateExpiry:t.certificateExpiry.toISOString()},null,2),{mode:384}),j.writeFile(M.join(n,`token`),`${t.token}\n`,{mode:384}),j.writeFile(M.join(n,`private-key.pem`),t.privateKey,{mode:384}),j.writeFile(M.join(n,`certificate.pem`),t.certificate,{mode:384}),j.writeFile(M.join(n,`chain.pem`),t.chain,{mode:384})]),await j.rm(M.join(n,`pending.json`),{force:!0})},catch:t=>new q({message:`Failed to save tunnel identity for ${e}`,cause:t})}),remove:e=>E.tryPromise({try:()=>j.rm(a(e),{recursive:!0,force:!0}),catch:t=>new q({message:`Failed to remove tunnel identity for ${e}`,cause:t})}),list:()=>s().pipe(E.flatMap(e=>E.forEach(e,e=>c(e).pipe(E.map(t=>t?{profile:e,tunnel:t}:void 0)))),E.map(e=>e.filter(e=>e!==void 0)))}}const Et=k.Int.check(k.isBetween({minimum:0,maximum:4294967295}));var Dt=class extends k.Class(`BridgeProtocol/ClientInfo`)({version:k.String,max_conns:k.Number}){},Ot=class extends k.Class(`BridgeProtocol/AttachMessage`)({type:k.Literal(`attach`),token:k.String,transport:k.Literal(`ws`),client:Dt,routes:k.Array(k.String).pipe(k.optional)}){},kt=class extends k.Class(`BridgeProtocol/AttachedMessage`)({type:k.Literal(`attached`),session:k.String,routes:k.Array(k.String),heartbeat_ms:k.Number,idle_timeout_ms:k.Number}){},At=class extends k.Class(`BridgeProtocol/AttachErrorMessage`)({type:k.Literal(`attach_error`),code:k.String}){},jt=class extends k.Class(`BridgeProtocol/PingMessage`)({type:k.Literal(`ping`),time_sent:k.Number}){},Mt=class extends k.Class(`BridgeProtocol/PongMessage`)({type:k.Literal(`pong`),time_sent:k.Number}){},Nt=class extends k.Class(`BridgeProtocol/DrainMessage`)({type:k.Literal(`drain`),reason:k.String}){},Pt=class extends k.Class(`BridgeProtocol/OpenMessage`)({type:k.Literal(`open`),conn:Et,peer:k.String,sni:k.String,alpn:k.String}){},Ft=class extends k.Class(`BridgeProtocol/EndMessage`)({type:k.Literal(`end`),conn:Et}){},It=class extends k.Class(`BridgeProtocol/ResetMessage`)({type:k.Literal(`reset`),conn:Et,code:k.String}){};k.Union([Ot,jt,Mt,Nt,Ft,It]);const Lt=k.Union([kt,At,jt,Mt,Nt,Pt,Ft,It]),Rt=k.decodeUnknownOption(Lt);function zt(e){try{return Rt(JSON.parse(e))}catch{return he.none()}}k.Union([Ot,kt,At,jt,Mt,Nt,Pt,Ft,It]);const J={BAD_ATTACH:`bad_attach`,BAD_TOKEN:`bad_token`,TUNNEL_NOT_BOUND:`tunnel_not_bound`,CERT_NOT_READY:`cert_not_ready`,REPLACED:`replaced`,UPSTREAM_CONNECT_FAILED:`upstream_connect_failed`,UPSTREAM_IO_ERROR:`upstream_io_error`,CLIENT_IO_ERROR:`client_io_error`,IDLE_TIMEOUT:`idle_timeout`,ROUTE_CONFLICT:`route_conflict`,INVALID_ROUTE:`invalid_route`,UNKNOWN_ROUTE:`unknown_route`},Bt={HEARTBEAT_MS:15e3,IDLE_TIMEOUT_MS:45e3,CONNECT_TIMEOUT_MS:1e4,RECONNECT_BACKOFF_MIN_MS:250,RECONNECT_BACKOFF_MAX_MS:3e4},Y={CONN_ID_SIZE:4,MAX_PAYLOAD_SIZE:32768};function Vt(e){return e.length<Y.CONN_ID_SIZE?null:{conn:new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!1),payload:e.slice(Y.CONN_ID_SIZE)}}function Ht(e,t){let n=new Uint8Array(Y.CONN_ID_SIZE+t.length);return new DataView(n.buffer).setUint32(0,e,!1),n.set(t,Y.CONN_ID_SIZE),n}const Ut=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Wt=e=>e===`@`||Ut.test(e),Gt=(e,t)=>{let n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return`@`;let i=`.${r}`;if(!n.endsWith(i))return;let a=n.slice(0,-i.length);return Ut.test(a)?a:void 0},Kt=e=>{let t=e.lastIndexOf(`:`);if(t===-1)return;let n=e.slice(t+1);if(!/^\d{1,5}$/.test(n))return;let r=Number(n);if(r<1||r>65535)return;let i=e.slice(0,t);if(i.startsWith(`[`)){if(!i.endsWith(`]`))return;i=i.slice(1,-1)}if(i&&/^[A-Za-z0-9.\-:_]+$/.test(i))return{host:i,port:r}};var qt=class extends Error{code;constructor(e){super(`Bridge attach failed: ${e}`),this.code=e}};const Jt=/* @__PURE__ */ new Set([J.BAD_TOKEN,J.CERT_NOT_READY]),Yt=e=>{for(let[t,n]of Object.entries(e)){if(!Wt(t))throw Error(`Invalid route name '${t}'`);if(!Kt(n))throw Error(`Invalid target '${n}' for route '${t}': use host:port`)}},Xt=e=>Ee.createSecureContext({key:e.privateKey,cert:`${e.certificate}\n${e.chain}`}),Zt=(e,t)=>{let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])},Qt=e=>{let t=Math.min(Bt.RECONNECT_BACKOFF_MIN_MS*2**Math.min(e,16),Bt.RECONNECT_BACKOFF_MAX_MS);return Math.round(t/2+t/2*Math.random())};var $t=class{routes;identity;secureContext;refreshTimer;session;shutdown=!1;wake;status;ready;closed;options;constructor(e){this.options=e,Yt(e.routes),this.routes={...e.routes},this.identity=e.identity,this.secureContext=Xt(e.identity),this.status={state:`connecting`,hostname:e.identity.hostname,routes:this.routes,connections:0};let t,n;this.ready=new Promise((e,r)=>{t=e,n=r}),this.closed=this.run(t).then(()=>t(),e=>{throw n(e),e}),this.ready.catch(()=>void 0),this.refreshCertificate()}async refreshCertificate(){if(this.shutdown)return;try{let e=new URL(`/api/tunnel/${encodeURIComponent(this.identity.id)}/certificate`,this.options.api),t=await fetch(e,{headers:{authorization:`Bearer ${this.identity.token}`}}),n=(t.ok?await t.json():void 0)?.state;if(n?.type===`ready`&&n.certificate&&n.expiry&&n.certificate!==this.identity.certificate){let e={...this.identity,certificate:n.certificate,chain:n.chain??``,certificateExpiry:new Date(n.expiry)};this.secureContext=Xt(e),this.identity=e,this.options.onRenewed?.(e),this.emit({type:`certificate-renewed`,expiry:n.expiry})}}catch{}if(this.shutdown)return;let e=this.identity.certificateExpiry.getTime()-Date.now()<2592e6;this.refreshTimer=setTimeout(()=>void this.refreshCertificate(),e?6e4:432e5),this.refreshTimer.unref?.()}getStatus(){return{...this.status,routes:{...this.status.routes}}}setRoutes(e){Yt(e);let t=this.routes;this.routes={...e},this.status.routes=this.routes,Zt(t,this.routes)||this.session?.end({type:`routes-changed`}),this.wake?.()}close(){return this.shutdown=!0,clearTimeout(this.refreshTimer),this.session?.end({type:`shutdown`}),this.wake?.(),this.closed.catch(()=>void 0)}emit(e){this.options.onEvent(e)}sleep(e){return new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),t()}this.wake=r}).finally(()=>{this.wake=void 0})}async run(e){let t=0;try{for(;!this.shutdown;){if(Object.keys(this.routes).length===0){this.status.state=`waiting-routes`,await this.sleep(2**31-1);continue}this.status.state=`connecting`,this.emit({type:`connecting`,attempt:t});let n=new en(this.options,this.routes,()=>this.secureContext,{emit:e=>this.emit(e),target:e=>this.routes[e],attached:t=>{this.status.state=`connected`,this.status.session=t,this.status.lastError=void 0,this.status.connectedAt=Date.now(),e()},connections:e=>{this.status.connections=e}});this.session=n;let r=await n.run();if(this.session=void 0,this.status.session=void 0,this.status.connections=0,r.type===`shutdown`)break;if(r.type===`fatal`)throw r.error;if(r.type===`routes-changed`){this.emit({type:`disconnected`,reason:`routes changed`}),t=0;continue}r.attached&&(t=0),this.emit({type:`disconnected`,reason:r.error});let i=Qt(t);t++,this.status.state=`reconnecting`,this.status.lastError=r.error,this.emit({type:`reconnecting`,attempt:t,delayMs:i}),await this.sleep(i)}this.status.state=`stopped`,this.emit({type:`stopped`})}catch(e){throw this.status.state=`stopped`,this.status.lastError=e instanceof Error?e.message:String(e),this.emit({type:`stopped`,error:this.status.lastError}),e}}},en=class{socket;finish;channels=/* @__PURE__ */ new Map;drainWaiters=[];drainTimer;heartbeat;attachTimeout;lastReceived=Date.now();attached=!1;options;routes;secureContext;hooks;constructor(e,t,n,r){this.options=e,this.routes=t,this.secureContext=n,this.hooks=r}run(){return new Promise(e=>{this.finish=e;let t=new URL(`/api/tunnel/${encodeURIComponent(this.options.identity.id)}/connect`,this.options.api);t.protocol=t.protocol===`https:`?`wss:`:`ws:`;let n=new WebSocket(t,[`opentunnel`]);n.binaryType=`arraybuffer`,this.socket=n,this.attachTimeout=setTimeout(()=>this.end({type:`retry`,error:`bridge attach timed out`,attached:!1}),Bt.CONNECT_TIMEOUT_MS),n.addEventListener(`open`,()=>{this.sendControl({type:`attach`,token:this.options.identity.token,transport:`ws`,routes:Object.keys(this.routes).sort(),client:{version:`0.1.0`,max_conns:256}})}),n.addEventListener(`message`,e=>{this.lastReceived=Date.now(),typeof e.data==`string`?this.onControl(e.data):this.onData(new Uint8Array(e.data))}),n.addEventListener(`close`,e=>{let t=`${e.code} ${e.reason}`.trim();this.end({type:`retry`,error:`bridge closed: ${t}`,attached:this.attached})}),n.addEventListener(`error`,()=>{this.end({type:`retry`,error:`bridge WebSocket failed`,attached:this.attached})})})}end(e){let t=this.finish;if(t){this.finish=void 0,clearTimeout(this.attachTimeout),clearInterval(this.heartbeat),clearInterval(this.drainTimer);for(let e of this.drainWaiters.splice(0))e();for(let e of[...this.channels.values()])e.destroy(`bridge disconnected`);this.socket&&this.socket.readyState<=WebSocket.OPEN&&this.socket.close(1e3),t(e)}}onControl(e){let t=zt(e);if(he.isNone(t))return;let n=t.value;if(!this.attached){if(n.type===`attached`){this.attached=!0,clearTimeout(this.attachTimeout);let e=Math.max(n.heartbeat_ms,1e3),t=Math.max(n.idle_timeout_ms,5e3);this.heartbeat=setInterval(()=>{if(Date.now()-this.lastReceived>t){this.end({type:`retry`,error:`bridge idle timeout`,attached:!0});return}this.sendControl({type:`ping`,time_sent:Date.now()})},e),this.hooks.attached(n.session),this.hooks.emit({type:`connected`,session:n.session,routes:[...n.routes]})}else n.type===`attach_error`&&this.end(Jt.has(n.code)?{type:`fatal`,error:new qt(n.code)}:{type:`retry`,error:`attach failed: ${n.code}`,attached:!1});return}switch(n.type){case`open`:return this.open(n.conn,n.sni,n.peer);case`end`:return this.channels.get(n.conn)?.endInbound();case`reset`:return this.channels.get(n.conn)?.destroy(n.code,!1);case`ping`:return this.sendControl({type:`pong`,time_sent:n.time_sent});case`drain`:return this.end({type:`retry`,error:`server draining: ${n.reason}`,attached:!0})}}onData(e){let t=Vt(e);t&&this.channels.get(t.conn)?.push(t.payload)}open(e,t,n){let r=Gt(t,this.options.identity.hostname),i=r===void 0?void 0:this.hooks.target(r),a=i===void 0?void 0:Kt(i);if(r===void 0||!a){this.sendControl({type:`reset`,conn:e,code:J.UNKNOWN_ROUTE});return}let o=new tn(e,r,a,this.secureContext(),this);this.channels.set(e,o),this.hooks.connections(this.channels.size),this.hooks.emit({type:`connection-opened`,conn:e,route:r,peer:n})}closed(e,t){this.channels.get(e.conn)===e&&(this.channels.delete(e.conn),this.hooks.connections(this.channels.size),this.hooks.emit({type:`connection-closed`,conn:e.conn,route:e.route,...t===void 0?{}:{error:t}}))}sendControl(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}sendData(e,t,n){let r=this.socket;if(!this.finish||r?.readyState!==WebSocket.OPEN){n(/* @__PURE__ */ Error(`bridge closed`));return}for(let n=0;n<t.byteLength;n+=Y.MAX_PAYLOAD_SIZE){let i=t.subarray(n,n+Y.MAX_PAYLOAD_SIZE);r.send(Ht(e,i))}if(r.bufferedAmount<1048576){n();return}this.drainWaiters.push(()=>n()),this.drainTimer??=setInterval(()=>{if(!(this.socket&&this.socket.bufferedAmount>262144&&this.finish)){clearInterval(this.drainTimer),this.drainTimer=void 0;for(let e of this.drainWaiters.splice(0))e()}},5)}},tn=class{conn;route;session;raw;tls;upstream;done=!1;constructor(e,t,n,r,i){this.conn=e,this.route=t,this.session=i,this.raw=new Te({allowHalfOpen:!0,read(){},write:(t,n,r)=>i.sendData(e,t,r),final:t=>{i.sendControl({type:`end`,conn:e}),t()}}),this.tls=new Ee.TLSSocket(this.raw,{isServer:!0,secureContext:r}),this.tls.on(`secure`,()=>{let e=we.connect({host:n.host,port:n.port,allowHalfOpen:!0});this.upstream=e,e.setNoDelay(!0),e.on(`error`,t=>this.destroy(e.connecting?J.UPSTREAM_CONNECT_FAILED:J.UPSTREAM_IO_ERROR,!0,t.message)),this.tls.pipe(e),e.pipe(this.tls)}),this.tls.on(`error`,e=>this.destroy(J.UPSTREAM_IO_ERROR,!0,e.message)),this.tls.on(`close`,()=>this.finish(void 0))}push(e){if(!this.done){if(this.raw.readableLength>8388608){this.destroy(J.UPSTREAM_IO_ERROR,!0,`local connection stalled`);return}this.raw.push(e)}}endInbound(){this.done||this.raw.push(null)}destroy(e,t=!0,n=e){this.done||(t&&this.session.sendControl({type:`reset`,conn:this.conn,code:e}),this.finish(n))}finish(e){this.done||(this.done=!0,this.upstream?.destroy(),this.tls.destroy(),this.raw.destroy(),this.session.closed(this,e))}};const X=e=>e?.profile??`default`,Z=(e,t)=>new wt({message:e,cause:t}),nn=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);let r=btoa(n);return`-----BEGIN PRIVATE KEY-----\n${r.match(/.{1,64}/g)?.join(`
5
- `)??r}\n-----END PRIVATE KEY-----\n`};var rn=class e extends me.Service()(`@opentunnel/client/OpenTunnelClient`){static layer(t={}){let n=t.storage??Tt();return D.effect(e,E.gen(function*(){let e=yield*_t,r=new URL(t.api??`https://opentunnel.xyz`),i=E.fn(`OpenTunnelClient.tunnel.get`)(function*(e){return yield*n.load(X(e))}),a=E.fn(`OpenTunnelClient.tunnel.completePending`)(function*(t){let r=yield*e.authorized(B.make(t.pending.token));yield*E.sync(()=>t.onProgress?.(`requesting-certificate`)),yield*r.tunnel[`tunnel.bindCertificate`]({params:{id:z.make(t.pending.id)},payload:{csr:t.pending.csr}}).pipe(E.catchTag(`CertificateInProgressError`,()=>E.void),E.mapError(e=>Z(`Failed to start certificate issuance`,e)));let i=yield*E.gen(function*(){for(;;){yield*E.sync(()=>t.onProgress?.(`waiting-certificate`));let e=yield*r.tunnel[`tunnel.getCertificate`]({params:{id:z.make(t.pending.id)}}).pipe(E.mapError(e=>Z(`Failed to read certificate`,e)));if(e.state.type===`ready`)return e.state;if(e.state.type===`failed`)return yield*new wt({message:`Certificate issuance failed: ${e.state.reason}`});yield*E.sleep(`2 seconds`)}}),a={id:t.pending.id,hostname:t.pending.hostname,token:t.pending.token,privateKey:t.pending.privateKey,certificate:i.certificate,chain:i.chain,certificateExpiry:new Date(i.expiry)};return yield*E.sync(()=>t.onProgress?.(`saving-identity`)),yield*n.save(t.profile,a),yield*E.sync(()=>t.onProgress?.(`ready`)),a}),o=E.fn(`OpenTunnelClient.tunnel.provision`)(function*(e){yield*E.sync(()=>e.onProgress?.(`generating-key`));let t=yield*E.tryPromise({try:()=>crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!0,[`sign`,`verify`]),catch:e=>Z(`Failed to generate certificate key`,e)});yield*E.sync(()=>e.onProgress?.(`generating-csr`));let r=yield*E.tryPromise({try:()=>Ct(e.hostname,t),catch:e=>Z(`Failed to generate certificate request`,e)}),i=yield*E.tryPromise({try:()=>crypto.subtle.exportKey(`pkcs8`,t.privateKey),catch:e=>Z(`Failed to export certificate key`,e)}),o={id:String(e.id),hostname:e.hostname,token:e.token,privateKey:nn(i),csr:r};return yield*n.savePending(e.profile,o),yield*a({profile:e.profile,pending:o,onProgress:e.onProgress})}),s=E.fn(`OpenTunnelClient.tunnel.create`)(function*(t){let r=X(t);if(yield*n.load(r))return yield*new wt({message:`Profile '${r}' already has a tunnel`});let i=yield*n.loadPending(r);if(i)return yield*E.sync(()=>t?.onProgress?.(`resuming-certificate`)),yield*a({profile:r,pending:i,onProgress:t?.onProgress});yield*E.sync(()=>t?.onProgress?.(`creating-tunnel`));let s=yield*e.client.tunnel[`tunnel.create`]({payload:{}}).pipe(E.mapError(e=>Z(`Failed to create tunnel`,e)));return yield*o({profile:r,id:s.tunnel.id,hostname:String(s.tunnel.hostname),token:s.token,onProgress:t?.onProgress})}),c=E.fn(`OpenTunnelClient.tunnel.ensure`)(function*(t){let r=yield*i(t);if(!r)return yield*s(t);let a=(yield*(yield*e.authorized(B.make(r.token))).tunnel[`tunnel.getCertificate`]({params:{id:z.make(r.id)}}).pipe(E.mapError(e=>Z(`Failed to read certificate`,e)))).state;if(a.type===`ready`&&a.certificate!==r.certificate){let e={...r,certificate:a.certificate,chain:a.chain,certificateExpiry:new Date(a.expiry)};return yield*n.save(X(t),e),e}return a.type===`failed`?yield*o({profile:X(t),id:z.make(r.id),hostname:r.hostname,token:B.make(r.token)}):r}),l=E.fn(`OpenTunnelClient.tunnel.pending`)(function*(e){let t=yield*n.loadPending(X(e));return t?{id:t.id,hostname:t.hostname}:void 0}),u=E.fn(`OpenTunnelClient.tunnel.resume`)(function*(e){let t=X(e),r=yield*n.loadPending(t);if(r)return yield*E.sync(()=>e?.onProgress?.(`resuming-certificate`)),yield*a({profile:t,pending:r,onProgress:e?.onProgress})});return{profile:{list:n.profiles},tunnel:{list:n.list,get:i,pending:l,resume:u,create:s,ensure:c,remove:E.fn(`OpenTunnelClient.tunnel.remove`)(function*(t){let r=X(t),i=yield*n.load(r);i&&(yield*(yield*e.authorized(B.make(i.token))).tunnel[`tunnel.remove`]({params:{id:z.make(i.id)}}).pipe(E.mapError(e=>Z(`Failed to remove tunnel`,e))),yield*n.remove(r))}),connect:E.fn(`OpenTunnelClient.tunnel.connect`)(function*(e){yield*E.try({try:()=>Yt(e.routes),catch:e=>Z(e instanceof Error?e.message:`Invalid routes`,e)});let t=yield*c(e),i=yield*O.unbounded(),a=yield*E.acquireRelease(E.sync(()=>new $t({api:r,identity:t,routes:e.routes,onEvent:e=>{O.offerUnsafe(i,e),e.type===`stopped`&&O.endUnsafe(i)},onRenewed:t=>{E.runFork(n.save(X(e),t).pipe(E.ignore))}})),e=>E.promise(()=>e.close()).pipe(E.andThen(O.end(i))));return yield*E.tryPromise({try:()=>a.ready,catch:e=>Z(`Failed to connect tunnel`,e)}),{tunnel:t,events:ge.fromQueue(i),status:E.sync(()=>a.getStatus()),setRoutes:e=>E.try({try:()=>a.setRoutes(e),catch:e=>Z(e instanceof Error?e.message:`Invalid routes`,e)}),closed:E.tryPromise({try:()=>a.closed,catch:e=>Z(`Tunnel stopped`,e)}),close:E.promise(()=>a.close())}})}}})).pipe(D.provide(_t.layer({api:t.api??`https://opentunnel.xyz`})))}};const an=r.Union([r.Struct({jsonrpc:r.Literal(`2.0`),id:P.RequestId,result:r.Unknown}),r.Struct({jsonrpc:r.Literal(`2.0`),id:r.NullOr(P.RequestId),error:P.McpErrorBase}),r.Struct({jsonrpc:r.Literal(`2.0`),method:r.String,params:r.optionalKey(r.Unknown)})]),on=r.fromJsonString(an),sn=N.v2025_06_18.protocolVersion;var Q=class extends r.TaggedError()(`OrbitMcpError`,{message:r.String}){},cn=class extends l.Service()(`@2digits/tlo-mcp/mcp/OrbitClient`){};const ln=p.effect(cn,n.gen(function*(){let e=yield*R,t=(yield*_.HttpClient).pipe(_.withScope,_.transformResponse(n.flatMap(te.matchStatus({"2xx":e=>n.succeed(e),401:e=>Q.make({message:`Orbit HTTP ${e.status}: authorization rejected. Run tlo-mcp login; a 403 can also mean insufficient rights.`}),403:e=>Q.make({message:`Orbit HTTP ${e.status}: authorization rejected. Run tlo-mcp login; a 403 can also mean insufficient rights.`}),429:e=>Q.make({message:`Orbit rate limited. Retry after ${e.headers[`retry-after`]??`the server cooldown`}; request not replayed.`}),orElse:e=>Q.make({message:`Orbit HTTP ${e.status}. Request not replayed.`})})))),i=0,a,o=n.fn(`OrbitClient.send`)(function*(o,s,c=!1){let l=++i,u=yield*e.accessToken,d=yield*v.post(F).pipe(v.bearerToken(u),v.setHeader(`accept`,`application/json, text/event-stream`),v.setHeader(`mcp-protocol-version`,sn),e=>a===void 0?e:v.setHeader(e,`mcp-session-id`,a),v.bodyJson({jsonrpc:`2.0`,...c?{}:{id:l},method:o,params:s})),f=yield*t.execute(d),p=f.headers[`mcp-session-id`];if(o===`initialize`&&(a=p),c)return;let m=f.headers[`content-type`]?.startsWith(`text/event-stream`)?yield*f.stream.pipe(T.decodeText(),T.pipeThroughChannel(je.decode({maxEventSize:10485760})),T.filter(e=>e.event===`message`||e.event===``),T.map(Ae.get(`data`)),T.mapEffect(e=>r.decodeEffect(on)(e)),T.filter(e=>`id`in e&&e.id===l),T.runHead,n.flatMap(e=>ke.isSome(e)?n.succeed(e.value):Q.make({message:`Orbit stream ended before replying.`}))):yield*te.schemaBodyJson(an)(f);return!(`id`in m)||m.id!==l?yield*Q.make({message:`Unexpected Orbit response ID.`}):`error`in m?yield*Q.make({message:m.error.message}):m.result},n.timeout(`120 seconds`),n.scoped,n.provideService(g.RequestInit,{redirect:`error`}),n.mapError(e=>r.is(Q)(e)?e:Q.make({message:`Orbit connection or response failed. Request not replayed.`}))),s=yield*o(`initialize`,{protocolVersion:sn,capabilities:{},clientInfo:{name:`@2digits/tlo-mcp`,version:`0.1.38`}}).pipe(n.flatMap(r.decodeUnknownEffect(P.InitializeResult)));if(s.protocolVersion!==sn)return yield*Q.make({message:`Unsupported upstream MCP protocol: ${s.protocolVersion}.`});yield*o(`notifications/initialized`,{},!0);let c=/* @__PURE__ */ new Set,l=yield*T.paginate(void 0,n.fn(`OrbitClient.listToolsPage`)(function*(e){let t=yield*o(`tools/list`,e===void 0?{}:{cursor:e}).pipe(n.flatMap(r.decodeUnknownEffect(P.ListToolsResult)));if(t.nextCursor!==void 0){if(c.has(t.nextCursor))return yield*Q.make({message:`Orbit returned a repeated tools cursor.`});c.add(t.nextCursor)}return[t.tools,ke.fromUndefinedOr(t.nextCursor)]})).pipe(T.runCollect);return cn.of({tools:l,instructions:s.instructions,callTool:n.fn(`OrbitClient.callTool`)(function*(e,t){return yield*o(`tools/call`,{name:e,arguments:t})},n.flatMap(r.decodeUnknownEffect(P.CallToolResult)),n.catchTag(`SchemaError`,()=>Q.make({message:`Invalid Orbit tool result. Request not replayed.`})))})})).pipe(p.provide(g.layer)),un=p.effectDiscard(n.gen(function*(){let e=yield*cn,t=yield*Oe.McpServer;yield*n.forEach(e.tools,n.fn(`OrbitProxyLive.tool`)(function*(i){yield*t.addTool({tool:i,annotations:l.empty(),handle:n.fn(`handle`)(function*(e){return yield*r.decodeUnknownEffect(r.JsonObject)(e)},n.mapError(e=>P.InvalidParams.make({message:`Tool arguments must be a JSON object.`,data:e})),n.flatMap(t=>e.callTool(i.name,t).pipe(n.mapError(e=>P.InternalError.make({message:e.message})))))})}),{discard:!0})})),dn=`${de()}/.config/2digits/tlo-mcp/gateway.key`,fn=r.String.check(r.isPattern(/^[a-f0-9]{64}$/)).pipe(r.RedactedFromValue);var $=class extends r.TaggedError()(`GatewayError`,{message:r.String}){};const pn=n.fn(`Gateway.loadKey`)(function*(e){let t=yield*fe.FileSystem,i=(yield*pe.Path).dirname(e);yield*t.makeDirectory(i,{recursive:!0,mode:448}),yield*t.chmod(i,448),yield*t.writeFileString(e,ae(32).toString(`hex`),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>n.void));let a=yield*t.stat(e);return a.type!==`File`||a.mode&63?yield*$.make({message:`Gateway key must be a private file (chmod 600).`}):yield*t.readFileString(e).pipe(n.flatMap(r.decodeEffect(fn)))},n.mapError(()=>$.make({message:`Cannot load private gateway key. Check its permissions and format.`})));function mn(e){let t=ie(`sha256`).update(`Bearer ${h.value(e)}`).digest();return y.middleware(e=>n.gen(function*(){let r=yield*b.HttpServerRequest,i=ie(`sha256`).update(r.headers.authorization??``).digest();return oe(t,i)?r.headers.origin===void 0?yield*e.pipe(n.provideService(ne.MaxBodySize,De.bytes(1048576)),n.map(e=>x.setHeader(e,`cache-control`,`no-store`))):x.empty({status:403,headers:{"cache-control":`no-store`}}):x.empty({status:401,headers:{"www-authenticate":`Bearer`,"cache-control":`no-store`}})}),{global:!0})}function hn(e){let t=p.unwrap(n.gen(function*(){let e=yield*cn;return un.pipe(p.provide(Oe.layerHttp({name:`tlo-mcp`,version:`1.0.0`,instructions:e.instructions,path:`/mcp`,protocols:[N.v2025_11_25,N.v2025_06_18,N.v2025_03_26]})))}));return p.merge(t,mn(e))}const gn=r.String.check(r.isPattern(/^[a-z0-9]+\.opentunnel\.xyz$/)),_n=n.fn(`Gateway.openTunnel`)(function*(e){let t=yield*(yield*rn).tunnel.connect({profile:`tlo-mcp`,routes:{tlo:`127.0.0.1:${e}`}}),i=yield*r.decodeEffect(gn)(t.tunnel.hostname);return yield*t.events.pipe(T.runForEach(e=>e.type===`reconnecting`?n.sync(()=>process.stderr.write(`OpenTunnel reconnecting...
6
- `)):n.void),n.forkScoped),{endpoint:`https://tlo.${i}/mcp`,closed:t.closed.pipe(n.mapError(()=>$.make({message:`OpenTunnel stopped unexpectedly. Restart tlo-mcp.`})))}},n.timeout(`180 seconds`),n.mapError(()=>$.make({message:`Could not connect OpenTunnel. Check network access and retry; existing tunnel identity is preserved.`})));function vn(e){return`Connect my personal Teamleader Orbit MCP to Executor Cloud.
3
+ `)})}),b=n.fn(`OrbitAuth.locked`)(function*(t){return yield*e.lock,yield*t},n.scoped,l.withPermit,n.provideService(_.HttpClient,i),n.provideService(u.Crypto,t),n.provideService(C.ChildProcessSpawner,a),n.provideService(g.RequestInit,{redirect:`error`}),n.mapError(e=>r.is(I)(e)?e:I.make({message:`Orbit authentication unavailable. Check connectivity or run tlo-mcp login again.`})));return R.of({accessToken:b(te()),login:b(re()),logout:b(e.clear)})})).pipe(p.provide(We),p.provide(g.layer)),qe=k.String.pipe(k.brand(`CSR.Raw`)),Je=k.String.pipe(k.brand(`Hostname`));function Ye(){return(e,t)=>{class n{static makeUnsafe(e){return e}}return Object.setPrototypeOf(n,t),n}}var Xe=class extends Ye()(`CertificateID`,k.String){};k.String.pipe(k.brand(`ChallengeToken`));var Ze=class extends k.Class(`Certificate/StateChallenge`)({type:k.Literal(`challenge`),token:k.String,key:k.String}){},Qe=class extends k.Class(`Certificate/StateIssuing`)({type:k.Literal(`issuing`)}){},$e=class extends k.Class(`Certificate/StateReady`)({type:k.Literal(`ready`),certificate:k.String,chain:k.String,expiry:k.String}){},et=class extends k.Class(`Certificate/StateFailed`)({type:k.Literal(`failed`),reason:k.String}){};const tt=k.Union([Ze,Qe,$e,et]);var nt=class extends k.Class(`Certificate`)({id:Xe,state:tt}){},z=class extends Ye()(`TunnelID`,k.String){};const B=k.String.pipe(k.brand(`TunnelToken`));k.TaggedError()(`NotFound`,{tunnelID:z}),k.TaggedError()(`NoCertificate`,{tunnelID:z}),k.TaggedError()(`CertificateNotReady`,{tunnelID:z,currentState:k.String}),k.TaggedError()(`InvalidHostname`,{provided:Je,expected:Je});const rt=k.Literals([`offline`,`online`]);var it=class extends k.Class(`Tunnel/Info`)({id:z,hostname:Je,state:rt,certificateID:Xe.pipe(k.optional)}){},at=`0.5.0`,ot=class extends k.TaggedError()(`InvalidRequestError`,{message:k.String},{httpApiStatus:400}){},st=class extends k.TaggedError()(`UnauthorizedError`,{message:k.String},{httpApiStatus:401}){},V=class extends k.TaggedError()(`TunnelNotFoundError`,{tunnelID:k.String,message:k.String},{httpApiStatus:404}){},ct=class extends k.TaggedError()(`CertificateNotFoundError`,{tunnelID:k.String,message:k.String},{httpApiStatus:404}){},lt=class extends k.TaggedError()(`InvalidHostnameError`,{provided:k.String,expected:k.String,message:k.String},{httpApiStatus:400}){},ut=class extends k.TaggedError()(`HostnameUnavailableError`,{name:k.String,message:k.String},{httpApiStatus:409}){},dt=class extends k.TaggedError()(`CertificateInProgressError`,{tunnelID:k.String,message:k.String},{httpApiStatus:409}){},H=class extends k.TaggedError()(`ServiceUnavailableError`,{message:k.String},{httpApiStatus:503}){};me.Service()(`@opentunnel/protocol/OpenTunnelAuthorizationToken`);var U=class extends be.Service()(`@opentunnel/protocol/OpenTunnelAuthorization`,{security:{bearer:Se.bearer},error:st}){};const ft=k.Struct({name:k.String.pipe(k.optional)}),pt=k.Struct({tunnel:it,token:B}).pipe(xe.status(201)),mt=ye.make(`tunnel`).add(A.post(`tunnel.create`,`/api/tunnel`,{payload:ft,success:pt,error:[ot,ut,H]})).add(A.get(`tunnel.get`,`/api/tunnel/:id`,{params:k.Struct({id:z}),success:it,error:[V,H]}).middleware(U)).add(A.post(`tunnel.bindCertificate`,`/api/tunnel/:id/certificate`,{params:k.Struct({id:z}),payload:k.Struct({csr:qe}),success:nt.pipe(xe.status(202)),error:[ot,lt,V,dt,H]}).middleware(U)).add(A.get(`tunnel.getCertificate`,`/api/tunnel/:id/certificate`,{params:k.Struct({id:z}),success:nt,error:[V,ct,H]}).middleware(U)).add(A.delete(`tunnel.remove`,`/api/tunnel/:id`,{params:k.Struct({id:z}),success:xe.NoContent,error:[V,H]}).middleware(U)).add(A.get(`tunnel.connect`,`/api/tunnel/:id/connect`,{params:k.Struct({id:z}),success:k.Boolean,error:[V]}).annotateMerge(Ce.annotations({summary:`Connect a bridge WebSocket`,description:`This endpoint upgrades to the opentunnel WebSocket protocol.`}))).annotateMerge(Ce.annotations({title:`tunnel`})),ht=_e.make(`opentunnel`).add(mt).annotateMerge(Ce.annotations({title:`OpenTunnel API`,version:`0.1.0`,description:`Create and manage blind TLS tunnels.`})),gt=`opentunnel-sdk/${at}`;var _t=class e extends me.Service()(`@opentunnel/client/OpenTunnelApiClient`){static layer(t){return D.effect(e,E.gen(function*(){let e=(yield*_.HttpClient).pipe(_.mapRequest(v.setHeader(`user-agent`,gt)));return{client:yield*ve.makeWith(ht,{baseUrl:t.api,httpClient:e}),authorized:n=>ve.makeWith(ht,{baseUrl:t.api,httpClient:e.pipe(_.mapRequest(v.bearerToken(n)))})}})).pipe(D.provide(g.layer))}};const W=(e,...t)=>{let n=vt(t),r=n.length<128?[n.length]:(()=>{let e=[];for(let t=n.length;t>0;t>>=8)e.unshift(t&255);return[128|e.length,...e]})();return vt([new Uint8Array([e,...r]),n])},vt=e=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},G=(...e)=>W(48,...e),yt=(...e)=>W(49,...e),bt=e=>W(12,new TextEncoder().encode(e)),xt=e=>W(130,new TextEncoder().encode(e)),K=e=>{let[t,n,...r]=e.split(`.`).map(Number),i=[t*40+n];for(let e of r){let t=[e&127];for(let n=e>>7;n>0;n>>=7)t.unshift(n&127|128);i.push(...t)}return W(6,new Uint8Array(i))},St=e=>{let t=0;for(;t<e.length-1&&e[t]===0;)t++;let n=e.subarray(t);return W(2,n[0]&128?vt([new Uint8Array([0]),n]):n)};async function Ct(e,t){let n=new Uint8Array(await crypto.subtle.exportKey(`spki`,t.publicKey)),r=G(W(2,new Uint8Array([0])),G(yt(G(K(`2.5.4.3`),bt(e)))),n,W(160,G(K(`1.2.840.113549.1.9.14`),yt(G(G(K(`2.5.29.17`),W(4,G(xt(e),xt(`*.${e}`))))))))),i=new Uint8Array(await crypto.subtle.sign({name:`ECDSA`,hash:`SHA-256`},t.privateKey,r)),a=G(St(i.subarray(0,32)),St(i.subarray(32))),o=G(r,G(K(`1.2.840.10045.4.3.2`)),W(3,new Uint8Array([0]),a));return`-----BEGIN CERTIFICATE REQUEST-----\n${Buffer.from(o).toString(`base64`).replace(/.{1,64}/g,`$&
4
+ `)}-----END CERTIFICATE REQUEST-----`}var wt=class extends k.TaggedError()(`OpenTunnelClientError`,{message:k.String,cause:k.optional(k.Defect())}){},q=class extends k.TaggedError()(`OpenTunnelStorageError`,{message:k.String,cause:k.optional(k.Defect())}){};function Tt(e={}){let t=e.env??process.env,n=e.home??ue.homedir(),r=t.XDG_DATA_HOME??M.join(n,`.local`,`share`),i=M.join(r,`opentunnel`),a=e=>M.join(i,e),o=e=>E.tryPromise({try:()=>j.readFile(e,`utf8`),catch:e=>e}).pipe(E.catch(t=>E.gen(function*(){if(!(typeof t==`object`&&t&&`code`in t&&t.code===`ENOENT`))return yield*new q({message:`Failed to read ${e}`,cause:t})}))),s=E.fn(`OpenTunnelStorage.profiles`)(function*(){return(yield*E.tryPromise({try:()=>j.readdir(i,{withFileTypes:!0}),catch:e=>e}).pipe(E.catch(e=>E.gen(function*(){return typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`?[]:yield*new q({message:`Failed to list ${i}`,cause:e})})))).filter(e=>e.isDirectory()).map(e=>e.name).sort()}),c=E.fn(`OpenTunnelStorage.load`)(function*(e){let t=a(e),n=yield*o(M.join(t,`tunnel.json`));if(!n)return;let[r,i,s,c]=yield*E.all([o(M.join(t,`token`)),o(M.join(t,`private-key.pem`)),o(M.join(t,`certificate.pem`)),o(M.join(t,`chain.pem`))]);if(!r||!i||!s||c===void 0)return yield*new q({message:`Incomplete tunnel identity for ${e}`});let l=JSON.parse(n);return{id:l.id,hostname:l.hostname,token:r.trim(),privateKey:i,certificate:s,chain:c,certificateExpiry:new Date(l.certificateExpiry)}}),l=E.fn(`OpenTunnelStorage.loadPending`)(function*(e){let t=a(e),n=yield*o(M.join(t,`pending.json`));if(!n)return;let[r,i]=yield*E.all([o(M.join(t,`token`)),o(M.join(t,`private-key.pem`))]);if(!r||!i)return yield*new q({message:`Incomplete pending tunnel identity for ${e}`});let s=JSON.parse(n);return{id:s.id,hostname:s.hostname,token:r.trim(),privateKey:i,csr:s.csr}});return{profiles:()=>s(),load:e=>c(e),loadPending:e=>l(e),savePending:(e,t)=>E.tryPromise({try:async()=>{let n=a(e);await j.mkdir(n,{recursive:!0,mode:448}),await Promise.all([j.writeFile(M.join(n,`pending.json`),JSON.stringify({id:t.id,hostname:t.hostname,csr:t.csr},null,2),{mode:384}),j.writeFile(M.join(n,`token`),`${t.token}\n`,{mode:384}),j.writeFile(M.join(n,`private-key.pem`),t.privateKey,{mode:384})])},catch:t=>new q({message:`Failed to save pending tunnel identity for ${e}`,cause:t})}),save:(e,t)=>E.tryPromise({try:async()=>{let n=a(e);await j.mkdir(n,{recursive:!0,mode:448}),await Promise.all([j.writeFile(M.join(n,`tunnel.json`),JSON.stringify({id:t.id,hostname:t.hostname,certificateExpiry:t.certificateExpiry.toISOString()},null,2),{mode:384}),j.writeFile(M.join(n,`token`),`${t.token}\n`,{mode:384}),j.writeFile(M.join(n,`private-key.pem`),t.privateKey,{mode:384}),j.writeFile(M.join(n,`certificate.pem`),t.certificate,{mode:384}),j.writeFile(M.join(n,`chain.pem`),t.chain,{mode:384})]),await j.rm(M.join(n,`pending.json`),{force:!0})},catch:t=>new q({message:`Failed to save tunnel identity for ${e}`,cause:t})}),remove:e=>E.tryPromise({try:()=>j.rm(a(e),{recursive:!0,force:!0}),catch:t=>new q({message:`Failed to remove tunnel identity for ${e}`,cause:t})}),list:()=>s().pipe(E.flatMap(e=>E.forEach(e,e=>c(e).pipe(E.map(t=>t?{profile:e,tunnel:t}:void 0)))),E.map(e=>e.filter(e=>e!==void 0)))}}const Et=k.Int.check(k.isBetween({minimum:0,maximum:4294967295}));var Dt=class extends k.Class(`BridgeProtocol/ClientInfo`)({version:k.String,max_conns:k.Number}){},Ot=class extends k.Class(`BridgeProtocol/AttachMessage`)({type:k.Literal(`attach`),token:k.String,transport:k.Literal(`ws`),client:Dt,routes:k.Array(k.String).pipe(k.optional)}){},kt=class extends k.Class(`BridgeProtocol/AttachedMessage`)({type:k.Literal(`attached`),session:k.String,routes:k.Array(k.String),heartbeat_ms:k.Number,idle_timeout_ms:k.Number}){},At=class extends k.Class(`BridgeProtocol/AttachErrorMessage`)({type:k.Literal(`attach_error`),code:k.String}){},jt=class extends k.Class(`BridgeProtocol/PingMessage`)({type:k.Literal(`ping`),time_sent:k.Number}){},Mt=class extends k.Class(`BridgeProtocol/PongMessage`)({type:k.Literal(`pong`),time_sent:k.Number}){},Nt=class extends k.Class(`BridgeProtocol/DrainMessage`)({type:k.Literal(`drain`),reason:k.String}){},Pt=class extends k.Class(`BridgeProtocol/OpenMessage`)({type:k.Literal(`open`),conn:Et,peer:k.String,sni:k.String,alpn:k.String}){},Ft=class extends k.Class(`BridgeProtocol/EndMessage`)({type:k.Literal(`end`),conn:Et}){},It=class extends k.Class(`BridgeProtocol/ResetMessage`)({type:k.Literal(`reset`),conn:Et,code:k.String}){};k.Union([Ot,jt,Mt,Nt,Ft,It]);const Lt=k.Union([kt,At,jt,Mt,Nt,Pt,Ft,It]),Rt=k.decodeUnknownOption(Lt);function zt(e){try{return Rt(JSON.parse(e))}catch{return he.none()}}k.Union([Ot,kt,At,jt,Mt,Nt,Pt,Ft,It]);const J={BAD_ATTACH:`bad_attach`,BAD_TOKEN:`bad_token`,TUNNEL_NOT_BOUND:`tunnel_not_bound`,CERT_NOT_READY:`cert_not_ready`,REPLACED:`replaced`,UPSTREAM_CONNECT_FAILED:`upstream_connect_failed`,UPSTREAM_IO_ERROR:`upstream_io_error`,CLIENT_IO_ERROR:`client_io_error`,IDLE_TIMEOUT:`idle_timeout`,ROUTE_CONFLICT:`route_conflict`,INVALID_ROUTE:`invalid_route`,UNKNOWN_ROUTE:`unknown_route`,TOO_MANY_CONNECTIONS:`too_many_connections`},Bt={HEARTBEAT_MS:15e3,IDLE_TIMEOUT_MS:45e3,CONNECT_TIMEOUT_MS:1e4,RECONNECT_BACKOFF_MIN_MS:250,RECONNECT_BACKOFF_MAX_MS:3e4},Y={CONN_ID_SIZE:4,MAX_PAYLOAD_SIZE:32768};function Vt(e){return e.length<Y.CONN_ID_SIZE?null:{conn:new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!1),payload:e.slice(Y.CONN_ID_SIZE)}}function Ht(e,t){let n=new Uint8Array(Y.CONN_ID_SIZE+t.length);return new DataView(n.buffer).setUint32(0,e,!1),n.set(t,Y.CONN_ID_SIZE),n}const Ut=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Wt=e=>e===`@`||Ut.test(e),Gt=(e,t)=>{let n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return`@`;let i=`.${r}`;if(!n.endsWith(i))return;let a=n.slice(0,-i.length);return Ut.test(a)?a:void 0},Kt=e=>{let t=e.lastIndexOf(`:`);if(t===-1)return;let n=e.slice(t+1);if(!/^\d{1,5}$/.test(n))return;let r=Number(n);if(r<1||r>65535)return;let i=e.slice(0,t);if(i.startsWith(`[`)){if(!i.endsWith(`]`))return;i=i.slice(1,-1)}if(i&&/^[A-Za-z0-9.\-:_]+$/.test(i))return{host:i,port:r}},qt=e=>e===`v1`||e===`v2`,Jt=Uint8Array.of(13,10,13,10,0,13,10,81,85,73,84,10),Yt=e=>{let t=e.split(`.`);if(t.length!==4)return;let n=/* @__PURE__ */ new Uint8Array(4);for(let[e,r]of t.entries()){if(!/^(?:0|[1-9][0-9]{0,2})$/.test(r))return;let t=Number(r);if(t>255)return;n[e]=t}return n},Xt=(e,t)=>{if(e===``)return[];let n=[],r=e.split(`:`);for(let[e,i]of r.entries()){if(t&&e===r.length-1&&i.includes(`.`)){let e=Yt(i);if(!e)return;n.push(e[0]<<8|e[1],e[2]<<8|e[3]);continue}if(!/^[0-9A-Fa-f]{1,4}$/.test(i))return;n.push(Number.parseInt(i,16))}return n},Zt=e=>{let t=e.indexOf(`::`),n;if(t===-1){if(n=Xt(e,!0),n?.length!==8)return}else{if(e.indexOf(`::`,t+1)!==-1)return;let r=Xt(e.slice(0,t),!1),i=Xt(e.slice(t+2),!0);if(!r||!i||r.length+i.length>7)return;n=[...r,...Array(8-r.length-i.length).fill(0),...i]}let r=/* @__PURE__ */ new Uint8Array(16);for(let[e,t]of n.entries())r[e*2]=t>>8,r[e*2+1]=t&255;return r},Qt=e=>{if(!/^[0-9]{1,5}$/.test(e))return;let t=Number(e);return t<=65535?t:void 0},$t=e=>e.subarray(0,10).every(e=>e===0)&&e[10]===255&&e[11]===255,en=(e,t)=>e.length===16&&$t(e)?{family:4,bytes:e.slice(12),port:t}:e.length===4?{family:4,bytes:e,port:t}:{family:6,bytes:e,port:t},tn=e=>{let t=Yt(e)??Zt(e);if(t)return en(t,0);if(e.startsWith(`[`)){let t=e.indexOf(`]:`);if(t===-1)return;let n=Zt(e.slice(1,t)),r=Qt(e.slice(t+2));return n&&r!==void 0?en(n,r):void 0}let n=e.lastIndexOf(`:`);if(n===-1)return;let r=Yt(e.slice(0,n)),i=Qt(e.slice(n+1));return r&&i!==void 0?en(r,i):void 0},nn=e=>{if(e.family===4)return[...e.bytes].join(`.`);let t=Array.from({length:8},(t,n)=>e.bytes[n*2]<<8|e.bytes[n*2+1]),n=-1,r=1;for(let e=0;e<8;){if(t[e]!==0){e++;continue}let i=e;for(;i<8&&t[i]===0;)i++;i-e>r&&(n=e,r=i-e),e=i}let i=e=>e.map(e=>e.toString(16)).join(`:`);return n===-1?i(t):`${i(t.slice(0,n))}::${i(t.slice(n+r))}`},rn=new TextEncoder,an=(e,t,n)=>{let r=tn(t);return e===`v1`?on(r):sn(r,n)},on=e=>{if(!e)return rn.encode(`PROXY UNKNOWN\r
5
+ `);let[t,n]=e.family===4?[`TCP4`,`0.0.0.0`]:[`TCP6`,`::`];return rn.encode(`PROXY ${t} ${nn(e)} ${n} ${e.port} 443\r\n`)},sn=(e,t)=>{let n=rn.encode(t),r=n.length>0&&n.length<=255?3+n.length:0,i=(e===void 0?0:e.family===4?12:36)+r,a=new Uint8Array(16+i),o=new DataView(a.buffer);a.set(Jt,0),a[12]=e?33:32,a[13]=e===void 0?0:e.family===4?17:33,o.setUint16(14,i);let s=16;if(e){let t=e.bytes.length;a.set(e.bytes,s),s+=t*2,o.setUint16(s,e.port),o.setUint16(s+2,443),s+=4}return r>0&&(a[s]=2,o.setUint16(s+1,n.length),a.set(n,s+3)),a},cn=WebSocket;var ln=class extends Error{code;constructor(e){super(`Bridge attach failed: ${e}`),this.code=e}};const un=/* @__PURE__ */ new Set([J.BAD_TOKEN,J.CERT_NOT_READY]),dn=/* @__PURE__ */ new Set([`target`,`proxyProtocol`]),fn=(e,t)=>{if(!Wt(e))throw Error(`Invalid route name '${e}'`);let n=t,r;if(typeof t==`object`&&t&&!Array.isArray(t)){for(let n of Object.keys(t))if(!dn.has(n))throw Error(`Unknown option '${n}' for route '${e}': expected target or proxyProtocol`);let i=t;if(i.target===void 0)throw Error(`Route '${e}' has no target`);if(n=i.target,i.proxyProtocol!==void 0){if(!qt(i.proxyProtocol))throw Error(`Invalid proxyProtocol '${String(i.proxyProtocol)}' for route '${e}': use "v1" or "v2"`);r=i.proxyProtocol}}let i=typeof n==`string`?Kt(n):void 0;if(!i)throw Error(`Invalid target '${String(n)}' for route '${e}': use host:port`);return r===void 0?{target:i}:{target:i,proxyProtocol:r}},pn=e=>{for(let[t,n]of Object.entries(e))fn(t,n)},mn=e=>new Map(Object.entries(e).map(([e,t])=>[e,fn(e,t)])),hn=e=>Ee.createSecureContext({key:e.privateKey,cert:`${e.certificate}\n${e.chain}`}),gn=(e,t)=>{let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((e,t)=>e===r[t])},_n=e=>{let t=Math.min(Bt.RECONNECT_BACKOFF_MIN_MS*2**Math.min(e,16),Bt.RECONNECT_BACKOFF_MAX_MS);return Math.round(t/2+t/2*Math.random())};var vn=class{options;routes;resolved;identity;secureContext;refreshTimer;session;shutdown=!1;wake;status;ready;closed;constructor(e){this.options=e,this.resolved=mn(e.routes),this.routes={...e.routes},this.identity=e.identity,this.secureContext=hn(e.identity),this.status={state:`connecting`,hostname:e.identity.hostname,routes:this.routes,connections:0};let t,n;this.ready=new Promise((e,r)=>{t=e,n=r}),this.closed=this.run(t).then(()=>t(),e=>{throw n(e),e}),this.ready.catch(()=>void 0),this.refreshCertificate()}async refreshCertificate(){if(this.shutdown)return;try{let e=new URL(`/api/tunnel/${encodeURIComponent(this.identity.id)}/certificate`,this.options.api),t=await fetch(e,{headers:{authorization:`Bearer ${this.identity.token}`}}),n=(t.ok?await t.json():void 0)?.state;if(n?.type===`ready`&&n.certificate&&n.expiry&&n.certificate!==this.identity.certificate){let e={...this.identity,certificate:n.certificate,chain:n.chain??``,certificateExpiry:new Date(n.expiry)};this.secureContext=hn(e),this.identity=e,this.options.onRenewed?.(e),this.emit({type:`certificate-renewed`,expiry:n.expiry})}}catch{}if(this.shutdown)return;let e=this.identity.certificateExpiry.getTime()-Date.now()<2592e6;this.refreshTimer=setTimeout(()=>void this.refreshCertificate(),e?6e4:432e5),this.refreshTimer.unref?.()}getStatus(){return{...this.status,routes:{...this.status.routes}}}setRoutes(e){let t=mn(e),n=this.routes;this.resolved=t,this.routes={...e},this.status.routes=this.routes,gn(n,this.routes)||this.session?.end({type:`routes-changed`}),this.wake?.()}close(){return this.shutdown=!0,clearTimeout(this.refreshTimer),this.session?.end({type:`shutdown`}),this.wake?.(),this.closed.catch(()=>void 0)}emit(e){this.options.onEvent(e)}sleep(e){return new Promise(t=>{let n=setTimeout(r,e);function r(){clearTimeout(n),t()}this.wake=r}).finally(()=>{this.wake=void 0})}async run(e){let t=0;try{for(;!this.shutdown;){if(Object.keys(this.routes).length===0){this.status.state=`waiting-routes`,await this.sleep(2**31-1);continue}this.status.state=`connecting`,this.emit({type:`connecting`,attempt:t});let n=new yn(this.options,this.routes,()=>this.secureContext,{emit:e=>this.emit(e),route:e=>this.resolved.get(e),attached:t=>{this.status.state=`connected`,this.status.session=t,this.status.lastError=void 0,this.status.connectedAt=Date.now(),e()},connections:e=>{this.status.connections=e}});this.session=n;let r=await n.run();if(this.session=void 0,this.status.session=void 0,this.status.connections=0,r.type===`shutdown`)break;if(r.type===`fatal`)throw r.error;if(r.type===`routes-changed`){this.emit({type:`disconnected`,reason:`routes changed`}),t=0;continue}r.attached&&(t=0),this.emit({type:`disconnected`,reason:r.error});let i=_n(t);t++,this.status.state=`reconnecting`,this.status.lastError=r.error,this.emit({type:`reconnecting`,attempt:t,delayMs:i}),await this.sleep(i)}this.status.state=`stopped`,this.emit({type:`stopped`})}catch(e){throw this.status.state=`stopped`,this.status.lastError=e instanceof Error?e.message:String(e),this.emit({type:`stopped`,error:this.status.lastError}),e}}},yn=class{options;routes;secureContext;hooks;socket;finish;channels=/* @__PURE__ */ new Map;drainWaiters=[];drainTimer;heartbeat;attachTimeout;lastReceived=Date.now();attached=!1;constructor(e,t,n,r){this.options=e,this.routes=t,this.secureContext=n,this.hooks=r}run(){return new Promise(e=>{this.finish=e;let t=new URL(`/api/tunnel/${encodeURIComponent(this.options.identity.id)}/connect`,this.options.api);t.protocol=t.protocol===`https:`?`wss:`:`ws:`;let n=new cn(t,{protocols:[`opentunnel`],headers:{"user-agent":gt}});n.binaryType=`arraybuffer`,this.socket=n,this.attachTimeout=setTimeout(()=>this.end({type:`retry`,error:`bridge attach timed out`,attached:!1}),Bt.CONNECT_TIMEOUT_MS),n.addEventListener(`open`,()=>{this.sendControl({type:`attach`,token:this.options.identity.token,transport:`ws`,routes:Object.keys(this.routes).sort(),client:{version:`0.1.0`,max_conns:256}})}),n.addEventListener(`message`,e=>{this.lastReceived=Date.now(),typeof e.data==`string`?this.onControl(e.data):this.onData(new Uint8Array(e.data))}),n.addEventListener(`close`,e=>{let t=`${e.code} ${e.reason}`.trim();this.end({type:`retry`,error:`bridge closed: ${t}`,attached:this.attached})})})}end(e){let t=this.finish;if(t){this.finish=void 0,clearTimeout(this.attachTimeout),clearInterval(this.heartbeat),clearInterval(this.drainTimer);for(let e of this.drainWaiters.splice(0))e();for(let e of[...this.channels.values()])e.destroy(`bridge disconnected`);this.socket&&this.socket.readyState<=WebSocket.OPEN&&this.socket.close(1e3),t(e)}}onControl(e){let t=zt(e);if(he.isNone(t))return;let n=t.value;if(!this.attached){if(n.type===`attached`){this.attached=!0,clearTimeout(this.attachTimeout);let e=Math.max(n.heartbeat_ms,1e3),t=Math.max(n.idle_timeout_ms,5e3);this.heartbeat=setInterval(()=>{if(Date.now()-this.lastReceived>t){this.end({type:`retry`,error:`bridge idle timeout`,attached:!0});return}this.sendControl({type:`ping`,time_sent:Date.now()})},e),this.hooks.attached(n.session),this.hooks.emit({type:`connected`,session:n.session,routes:[...n.routes]})}else n.type===`attach_error`&&this.end(un.has(n.code)?{type:`fatal`,error:new ln(n.code)}:{type:`retry`,error:`attach failed: ${n.code}`,attached:!1});return}switch(n.type){case`open`:return this.open(n.conn,n.sni,n.peer);case`end`:return this.channels.get(n.conn)?.endInbound();case`reset`:return this.channels.get(n.conn)?.destroy(n.code,!1);case`ping`:return this.sendControl({type:`pong`,time_sent:n.time_sent});case`drain`:return this.end({type:`retry`,error:`server draining: ${n.reason}`,attached:!0})}}onData(e){let t=Vt(e);t&&this.channels.get(t.conn)?.push(t.payload)}open(e,t,n){let r=Gt(t,this.options.identity.hostname),i=r===void 0?void 0:this.hooks.route(r);if(r===void 0||!i){this.sendControl({type:`reset`,conn:e,code:J.UNKNOWN_ROUTE});return}if(this.channels.size>=256){this.sendControl({type:`reset`,conn:e,code:J.TOO_MANY_CONNECTIONS});return}let a=i.proxyProtocol===void 0?void 0:an(i.proxyProtocol,n,t),o=new bn(e,r,i.target,a,this.secureContext(),this);this.channels.set(e,o),this.hooks.connections(this.channels.size),this.hooks.emit({type:`connection-opened`,conn:e,route:r,peer:n})}closed(e,t){this.channels.get(e.conn)===e&&(this.channels.delete(e.conn),this.hooks.connections(this.channels.size),this.hooks.emit({type:`connection-closed`,conn:e.conn,route:e.route,...t===void 0?{}:{error:t}}))}sendControl(e){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(e))}sendData(e,t,n){let r=this.socket;if(!this.finish||r?.readyState!==WebSocket.OPEN){n(/* @__PURE__ */ Error(`bridge closed`));return}for(let n=0;n<t.byteLength;n+=Y.MAX_PAYLOAD_SIZE){let i=t.subarray(n,n+Y.MAX_PAYLOAD_SIZE);r.send(Ht(e,i))}if(r.bufferedAmount<1048576){n();return}this.drainWaiters.push(()=>n()),this.drainTimer??=setInterval(()=>{if(!(this.socket&&this.socket.bufferedAmount>262144&&this.finish)){clearInterval(this.drainTimer),this.drainTimer=void 0;for(let e of this.drainWaiters.splice(0))e()}},5)}},bn=class{conn;route;session;raw;tls;upstream;done=!1;constructor(e,t,n,r,i,a){this.conn=e,this.route=t,this.session=a,this.raw=new Te({allowHalfOpen:!0,read(){},write:(t,n,r)=>a.sendData(e,t,r),final:t=>{a.sendControl({type:`end`,conn:e}),t()}}),this.tls=new Ee.TLSSocket(this.raw,{isServer:!0,secureContext:i}),this.tls.on(`secure`,()=>{let e=we.connect({host:n.host,port:n.port,allowHalfOpen:!0});this.upstream=e,e.setNoDelay(!0),r&&e.write(r),e.on(`error`,t=>this.destroy(e.connecting?J.UPSTREAM_CONNECT_FAILED:J.UPSTREAM_IO_ERROR,!0,t.message)),this.tls.pipe(e),e.pipe(this.tls)}),this.tls.on(`error`,e=>this.destroy(J.UPSTREAM_IO_ERROR,!0,e.message)),this.tls.on(`close`,()=>this.finish(void 0))}push(e){if(!this.done){if(this.raw.readableLength>8388608){this.destroy(J.UPSTREAM_IO_ERROR,!0,`local connection stalled`);return}this.raw.push(e)}}endInbound(){this.done||this.raw.push(null)}destroy(e,t=!0,n=e){this.done||(t&&this.session.sendControl({type:`reset`,conn:this.conn,code:e}),this.finish(n))}finish(e){this.done||(this.done=!0,this.upstream?.destroy(),this.tls.destroy(),this.raw.destroy(),this.session.closed(this,e))}};const X=e=>e?.profile??`default`,Z=(e,t)=>new wt({message:e,cause:t}),xn=e=>{let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);let r=btoa(n);return`-----BEGIN PRIVATE KEY-----\n${r.match(/.{1,64}/g)?.join(`
6
+ `)??r}\n-----END PRIVATE KEY-----\n`};var Sn=class e extends me.Service()(`@opentunnel/client/OpenTunnelClient`){static layer(t={}){let n=t.storage??Tt();return D.effect(e,E.gen(function*(){let e=yield*_t,r=new URL(t.api??`https://opentunnel.xyz`),i=E.fn(`OpenTunnelClient.tunnel.get`)(function*(e){return yield*n.load(X(e))}),a=E.fn(`OpenTunnelClient.tunnel.completePending`)(function*(t){let r=yield*e.authorized(B.make(t.pending.token));yield*E.sync(()=>t.onProgress?.(`requesting-certificate`)),yield*r.tunnel[`tunnel.bindCertificate`]({params:{id:z.make(t.pending.id)},payload:{csr:t.pending.csr}}).pipe(E.catchTag(`CertificateInProgressError`,()=>E.void),E.mapError(e=>Z(`Failed to start certificate issuance`,e)));let i=yield*E.gen(function*(){for(;;){yield*E.sync(()=>t.onProgress?.(`waiting-certificate`));let e=yield*r.tunnel[`tunnel.getCertificate`]({params:{id:z.make(t.pending.id)}}).pipe(E.mapError(e=>Z(`Failed to read certificate`,e)));if(e.state.type===`ready`)return e.state;if(e.state.type===`failed`)return yield*new wt({message:`Certificate issuance failed: ${e.state.reason}`});yield*E.sleep(`2 seconds`)}}),a={id:t.pending.id,hostname:t.pending.hostname,token:t.pending.token,privateKey:t.pending.privateKey,certificate:i.certificate,chain:i.chain,certificateExpiry:new Date(i.expiry)};return yield*E.sync(()=>t.onProgress?.(`saving-identity`)),yield*n.save(t.profile,a),yield*E.sync(()=>t.onProgress?.(`ready`)),a}),o=E.fn(`OpenTunnelClient.tunnel.provision`)(function*(e){yield*E.sync(()=>e.onProgress?.(`generating-key`));let t=yield*E.tryPromise({try:()=>crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!0,[`sign`,`verify`]),catch:e=>Z(`Failed to generate certificate key`,e)});yield*E.sync(()=>e.onProgress?.(`generating-csr`));let r=yield*E.tryPromise({try:()=>Ct(e.hostname,t),catch:e=>Z(`Failed to generate certificate request`,e)}),i=yield*E.tryPromise({try:()=>crypto.subtle.exportKey(`pkcs8`,t.privateKey),catch:e=>Z(`Failed to export certificate key`,e)}),o={id:String(e.id),hostname:e.hostname,token:e.token,privateKey:xn(i),csr:r};return yield*n.savePending(e.profile,o),yield*a({profile:e.profile,pending:o,onProgress:e.onProgress})}),s=E.fn(`OpenTunnelClient.tunnel.create`)(function*(t){let r=X(t);if(yield*n.load(r))return yield*new wt({message:`Profile '${r}' already has a tunnel`});let i=yield*n.loadPending(r);if(i)return yield*E.sync(()=>t?.onProgress?.(`resuming-certificate`)),yield*a({profile:r,pending:i,onProgress:t?.onProgress});yield*E.sync(()=>t?.onProgress?.(`creating-tunnel`));let s=yield*e.client.tunnel[`tunnel.create`]({payload:{}}).pipe(E.mapError(e=>Z(`Failed to create tunnel`,e)));return yield*o({profile:r,id:s.tunnel.id,hostname:String(s.tunnel.hostname),token:s.token,onProgress:t?.onProgress})}),c=E.fn(`OpenTunnelClient.tunnel.ensure`)(function*(t){let r=yield*i(t);if(!r)return yield*s(t);let a=(yield*(yield*e.authorized(B.make(r.token))).tunnel[`tunnel.getCertificate`]({params:{id:z.make(r.id)}}).pipe(E.mapError(e=>Z(`Failed to read certificate`,e)))).state;if(a.type===`ready`&&a.certificate!==r.certificate){let e={...r,certificate:a.certificate,chain:a.chain,certificateExpiry:new Date(a.expiry)};return yield*n.save(X(t),e),e}return a.type===`failed`?yield*o({profile:X(t),id:z.make(r.id),hostname:r.hostname,token:B.make(r.token)}):r}),l=E.fn(`OpenTunnelClient.tunnel.pending`)(function*(e){let t=yield*n.loadPending(X(e));return t?{id:t.id,hostname:t.hostname}:void 0}),u=E.fn(`OpenTunnelClient.tunnel.resume`)(function*(e){let t=X(e),r=yield*n.loadPending(t);if(r)return yield*E.sync(()=>e?.onProgress?.(`resuming-certificate`)),yield*a({profile:t,pending:r,onProgress:e?.onProgress})});return{profile:{list:n.profiles},tunnel:{list:n.list,get:i,pending:l,resume:u,create:s,ensure:c,remove:E.fn(`OpenTunnelClient.tunnel.remove`)(function*(t){let r=X(t),i=yield*n.load(r);i&&(yield*(yield*e.authorized(B.make(i.token))).tunnel[`tunnel.remove`]({params:{id:z.make(i.id)}}).pipe(E.mapError(e=>Z(`Failed to remove tunnel`,e))),yield*n.remove(r))}),connect:E.fn(`OpenTunnelClient.tunnel.connect`)(function*(e){yield*E.try({try:()=>pn(e.routes),catch:e=>Z(e instanceof Error?e.message:`Invalid routes`,e)});let t=yield*c(e),i=yield*O.unbounded(),a=yield*E.acquireRelease(E.sync(()=>new vn({api:r,identity:t,routes:e.routes,onEvent:e=>{O.offerUnsafe(i,e),e.type===`stopped`&&O.endUnsafe(i)},onRenewed:t=>{E.runFork(n.save(X(e),t).pipe(E.ignore))}})),e=>E.promise(()=>e.close()).pipe(E.andThen(O.end(i))));return yield*E.tryPromise({try:()=>a.ready,catch:e=>Z(`Failed to connect tunnel`,e)}),{tunnel:t,events:ge.fromQueue(i),status:E.sync(()=>a.getStatus()),setRoutes:e=>E.try({try:()=>a.setRoutes(e),catch:e=>Z(e instanceof Error?e.message:`Invalid routes`,e)}),closed:E.tryPromise({try:()=>a.closed,catch:e=>Z(`Tunnel stopped`,e)}),close:E.promise(()=>a.close())}})}}})).pipe(D.provide(_t.layer({api:t.api??`https://opentunnel.xyz`})))}};const Cn=r.Union([r.Struct({jsonrpc:r.Literal(`2.0`),id:P.RequestId,result:r.Unknown}),r.Struct({jsonrpc:r.Literal(`2.0`),id:r.NullOr(P.RequestId),error:P.McpErrorBase}),r.Struct({jsonrpc:r.Literal(`2.0`),method:r.String,params:r.optionalKey(r.Unknown)})]),wn=r.fromJsonString(Cn),Tn=N.v2025_06_18.protocolVersion;var Q=class extends r.TaggedError()(`OrbitMcpError`,{message:r.String}){},En=class extends l.Service()(`@2digits/tlo-mcp/mcp/OrbitClient`){};const Dn=p.effect(En,n.gen(function*(){let e=yield*R,t=(yield*_.HttpClient).pipe(_.withScope,_.transformResponse(n.flatMap(te.matchStatus({"2xx":e=>n.succeed(e),401:e=>Q.make({message:`Orbit HTTP ${e.status}: authorization rejected. Run tlo-mcp login; a 403 can also mean insufficient rights.`}),403:e=>Q.make({message:`Orbit HTTP ${e.status}: authorization rejected. Run tlo-mcp login; a 403 can also mean insufficient rights.`}),429:e=>Q.make({message:`Orbit rate limited. Retry after ${e.headers[`retry-after`]??`the server cooldown`}; request not replayed.`}),orElse:e=>Q.make({message:`Orbit HTTP ${e.status}. Request not replayed.`})})))),i=0,a,o=n.fn(`OrbitClient.send`)(function*(o,s,c=!1){let l=++i,u=yield*e.accessToken,d=yield*v.post(F).pipe(v.bearerToken(u),v.setHeader(`accept`,`application/json, text/event-stream`),v.setHeader(`mcp-protocol-version`,Tn),e=>a===void 0?e:v.setHeader(e,`mcp-session-id`,a),v.bodyJson({jsonrpc:`2.0`,...c?{}:{id:l},method:o,params:s})),f=yield*t.execute(d),p=f.headers[`mcp-session-id`];if(o===`initialize`&&(a=p),c)return;let m=f.headers[`content-type`]?.startsWith(`text/event-stream`)?yield*f.stream.pipe(T.decodeText(),T.pipeThroughChannel(je.decode({maxEventSize:10485760})),T.filter(e=>e.event===`message`||e.event===``),T.map(Ae.get(`data`)),T.mapEffect(e=>r.decodeEffect(wn)(e)),T.filter(e=>`id`in e&&e.id===l),T.runHead,n.flatMap(e=>ke.isSome(e)?n.succeed(e.value):Q.make({message:`Orbit stream ended before replying.`}))):yield*te.schemaBodyJson(Cn)(f);return!(`id`in m)||m.id!==l?yield*Q.make({message:`Unexpected Orbit response ID.`}):`error`in m?yield*Q.make({message:m.error.message}):m.result},n.timeout(`120 seconds`),n.scoped,n.provideService(g.RequestInit,{redirect:`error`}),n.mapError(e=>r.is(Q)(e)?e:Q.make({message:`Orbit connection or response failed. Request not replayed.`}))),s=yield*o(`initialize`,{protocolVersion:Tn,capabilities:{},clientInfo:{name:`@2digits/tlo-mcp`,version:`0.1.38`}}).pipe(n.flatMap(r.decodeUnknownEffect(P.InitializeResult)));if(s.protocolVersion!==Tn)return yield*Q.make({message:`Unsupported upstream MCP protocol: ${s.protocolVersion}.`});yield*o(`notifications/initialized`,{},!0);let c=/* @__PURE__ */ new Set,l=yield*T.paginate(void 0,n.fn(`OrbitClient.listToolsPage`)(function*(e){let t=yield*o(`tools/list`,e===void 0?{}:{cursor:e}).pipe(n.flatMap(r.decodeUnknownEffect(P.ListToolsResult)));if(t.nextCursor!==void 0){if(c.has(t.nextCursor))return yield*Q.make({message:`Orbit returned a repeated tools cursor.`});c.add(t.nextCursor)}return[t.tools,ke.fromUndefinedOr(t.nextCursor)]})).pipe(T.runCollect);return En.of({tools:l,instructions:s.instructions,callTool:n.fn(`OrbitClient.callTool`)(function*(e,t){return yield*o(`tools/call`,{name:e,arguments:t})},n.flatMap(r.decodeUnknownEffect(P.CallToolResult)),n.catchTag(`SchemaError`,()=>Q.make({message:`Invalid Orbit tool result. Request not replayed.`})))})})).pipe(p.provide(g.layer)),On=p.effectDiscard(n.gen(function*(){let e=yield*En,t=yield*Oe.McpServer;yield*n.forEach(e.tools,n.fn(`OrbitProxyLive.tool`)(function*(i){yield*t.addTool({tool:i,annotations:l.empty(),handle:n.fn(`handle`)(function*(e){return yield*r.decodeUnknownEffect(r.JsonObject)(e)},n.mapError(e=>P.InvalidParams.make({message:`Tool arguments must be a JSON object.`,data:e})),n.flatMap(t=>e.callTool(i.name,t).pipe(n.mapError(e=>P.InternalError.make({message:e.message})))))})}),{discard:!0})})),kn=`${de()}/.config/2digits/tlo-mcp/gateway.key`,An=r.String.check(r.isPattern(/^[a-f0-9]{64}$/)).pipe(r.RedactedFromValue);var $=class extends r.TaggedError()(`GatewayError`,{message:r.String}){};const jn=n.fn(`Gateway.loadKey`)(function*(e){let t=yield*fe.FileSystem,i=(yield*pe.Path).dirname(e);yield*t.makeDirectory(i,{recursive:!0,mode:448}),yield*t.chmod(i,448),yield*t.writeFileString(e,ae(32).toString(`hex`),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>n.void));let a=yield*t.stat(e);return a.type!==`File`||a.mode&63?yield*$.make({message:`Gateway key must be a private file (chmod 600).`}):yield*t.readFileString(e).pipe(n.flatMap(r.decodeEffect(An)))},n.mapError(()=>$.make({message:`Cannot load private gateway key. Check its permissions and format.`})));function Mn(e){let t=ie(`sha256`).update(`Bearer ${h.value(e)}`).digest();return y.middleware(e=>n.gen(function*(){let r=yield*b.HttpServerRequest,i=ie(`sha256`).update(r.headers.authorization??``).digest();return oe(t,i)?r.headers.origin===void 0?yield*e.pipe(n.provideService(ne.MaxBodySize,De.bytes(1048576)),n.map(e=>x.setHeader(e,`cache-control`,`no-store`))):x.empty({status:403,headers:{"cache-control":`no-store`}}):x.empty({status:401,headers:{"www-authenticate":`Bearer`,"cache-control":`no-store`}})}),{global:!0})}function Nn(e){let t=p.unwrap(n.gen(function*(){let e=yield*En;return On.pipe(p.provide(Oe.layerHttp({name:`tlo-mcp`,version:`1.0.0`,instructions:e.instructions,path:`/mcp`,protocols:[N.v2025_11_25,N.v2025_06_18,N.v2025_03_26]})))}));return p.merge(t,Mn(e))}const Pn=r.String.check(r.isPattern(/^[a-z0-9]+\.opentunnel\.xyz$/)),Fn=n.fn(`Gateway.openTunnel`)(function*(e){let t=yield*(yield*Sn).tunnel.connect({profile:`tlo-mcp`,routes:{tlo:`127.0.0.1:${e}`}}),i=yield*r.decodeEffect(Pn)(t.tunnel.hostname);return yield*t.events.pipe(T.runForEach(e=>e.type===`reconnecting`?n.sync(()=>process.stderr.write(`OpenTunnel reconnecting...
7
+ `)):n.void),n.forkScoped),{endpoint:`https://tlo.${i}/mcp`,closed:t.closed.pipe(n.mapError(()=>$.make({message:`OpenTunnel stopped unexpectedly. Restart tlo-mcp.`})))}},n.timeout(`180 seconds`),n.mapError(()=>$.make({message:`Could not connect OpenTunnel. Check network access and retry; existing tunnel identity is preserved.`})));function In(e){return`Connect my personal Teamleader Orbit MCP to Executor Cloud.
7
8
  Endpoint: ${e}
8
9
  Transport: Streamable HTTP. Authentication: API key in Authorization: Bearer <key>.
9
10
  Register an MCP integration named Teamleader Orbit (slug tlo_mcp) with a bearer-header API-key template, not OAuth.
@@ -11,9 +12,9 @@ Use a secure credential handoff so I enter the gateway key directly in Executor;
11
12
  Create a personal connection, discover tools, and verify with one read-only tool. Do not change business data.
12
13
  If this endpoint already exists, reuse its integration/connection instead of creating duplicates.
13
14
  Orbit login and refresh are handled on my Mac; do not register another Orbit OAuth client.
14
- `}const yn=n.fn(`TloMcp.connect`)(function*(e){let t=yield*pn(dn),r=yield*L,i=yield*R;(yield*r.load)===void 0&&(yield*i.login),yield*p.build(y.serve(hn(t),{disableLogger:!0,disableListenLog:!0}).pipe(p.provide(ln),p.provide(ce.layer(()=>se({maxHeaderSize:8192,requestTimeout:13e4}),{host:`127.0.0.1`,port:e})))),yield*n.sync(()=>process.stderr.write(`Connecting OpenTunnel (first certificate may take a few minutes)...
15
- `));let{endpoint:a,closed:o}=yield*_n(e);return yield*n.sync(()=>{process.stderr.write(`TLO gateway ready: ${a}\nGateway key: ${dn} (private; not printed)\n`),process.platform===`darwin`&&process.stderr.write(`Copy the key for Executor's secure credential form: pbcopy < "${dn}"\n`),process.stderr.write(`Keep this process running and your Mac awake. Ctrl-C closes the gateway and tunnel.
15
+ `}const Ln=n.fn(`TloMcp.connect`)(function*(e){let t=yield*jn(kn),r=yield*L,i=yield*R;(yield*r.load)===void 0&&(yield*i.login),yield*p.build(y.serve(Nn(t),{disableLogger:!0,disableListenLog:!0}).pipe(p.provide(Dn),p.provide(ce.layer(()=>se({maxHeaderSize:8192,requestTimeout:13e4}),{host:`127.0.0.1`,port:e})))),yield*n.sync(()=>process.stderr.write(`Connecting OpenTunnel (first certificate may take a few minutes)...
16
+ `));let{endpoint:a,closed:o}=yield*Fn(e);return yield*n.sync(()=>{process.stderr.write(`TLO gateway ready: ${a}\nGateway key: ${kn} (private; not printed)\n`),process.platform===`darwin`&&process.stderr.write(`Copy the key for Executor's secure credential form: pbcopy < "${kn}"\n`),process.stderr.write(`Keep this process running and your Mac awake. Ctrl-C closes the gateway and tunnel.
16
17
 
17
18
  Copy this prompt to your agent:
18
19
 
19
- `),process.stdout.write(vn(a))}),yield*o,yield*$.make({message:`The OpenTunnel connection stopped. Restart tlo-mcp.`})},n.scoped,n.provide(p.mergeAll(Ke,We,rn.layer()))),bn=i.make(`login`,{},n.fn(`TloMcp.login`)(function*(){yield*(yield*R).login},n.provide(Ke),n.scoped)),xn=i.make(`logout`,{},n.fn(`TloMcp.logout`)(function*(){yield*(yield*R).logout},n.provide(Ke),n.scoped)),Sn=i.make(`tlo-mcp`,{port:a.Int(`port`).pipe(a.withSchema(r.Int.check(r.isBetween({minimum:1024,maximum:65535}))),a.withDefault(4790))},({port:e})=>yn(e)).pipe(i.withSubcommands([bn,xn]));n.fn(`TloMcp.run`)(function*(e){return yield*i.runWith(Sn,{version:`1.0.0`})(e)})(process.argv.slice(2)).pipe(n.provide(t.layer),e.runMain);export{};
20
+ `),process.stdout.write(In(a))}),yield*o,yield*$.make({message:`The OpenTunnel connection stopped. Restart tlo-mcp.`})},n.scoped,n.provide(p.mergeAll(Ke,We,Sn.layer()))),Rn=i.make(`login`,{},n.fn(`TloMcp.login`)(function*(){yield*(yield*R).login},n.provide(Ke),n.scoped)),zn=i.make(`logout`,{},n.fn(`TloMcp.logout`)(function*(){yield*(yield*R).logout},n.provide(Ke),n.scoped)),Bn=i.make(`tlo-mcp`,{port:a.Int(`port`).pipe(a.withSchema(r.Int.check(r.isBetween({minimum:1024,maximum:65535}))),a.withDefault(4790))},({port:e})=>Ln(e)).pipe(i.withSubcommands([Rn,zn]));n.fn(`TloMcp.run`)(function*(e){return yield*i.runWith(Bn,{version:`1.0.0`})(e)})(process.argv.slice(2)).pipe(n.provide(t.layer),e.runMain);export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@2digits/tlo-mcp",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/2digits-agency/configs.git",
@@ -18,19 +18,19 @@
18
18
  "access": "public"
19
19
  },
20
20
  "dependencies": {
21
- "@effect/platform-node": "4.0.2",
22
- "@opentunnel/client": "0.2.2",
23
- "@yielded/oauth": "0.1.0-beta.30",
24
- "effect": "4.0.2"
21
+ "@effect/platform-node": "4.0.3",
22
+ "@opentunnel/client": "0.5.0",
23
+ "@yielded/oauth": "0.1.0-beta.37",
24
+ "effect": "4.0.3"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@2digits/tsconfig": "0.9.2",
28
28
  "@arethetypeswrong/core": "0.18.5",
29
- "@effect/vitest": "4.0.2",
29
+ "@effect/vitest": "4.0.3",
30
30
  "publint": "0.3.25",
31
31
  "typescript": "7.0.2",
32
32
  "vite-plus": "1.1.0",
33
- "vitest": "5.0.3"
33
+ "vitest": "5.0.4"
34
34
  },
35
35
  "engines": {
36
36
  "node": ">=24"