@2digits/tlo-mcp 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -1
- package/dist/bin.mjs +13 -13
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -55,6 +55,19 @@ Run `pitchfork boot enable` so the supervisor starts at login. Boot-started supe
|
|
|
55
55
|
absolute paths for `npx`/`node` if they are not found. Manage it with `pitchfork status global/tlo`,
|
|
56
56
|
`pitchfork logs global/tlo`, and `pitchfork restart global/tlo`.
|
|
57
57
|
|
|
58
|
+
## Run behind your own HTTPS URL
|
|
59
|
+
|
|
60
|
+
On an always-on host that already terminates HTTPS (for example an Amp Box deployment), skip OpenTunnel:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
tlo-mcp --public-url https://tlo.example.com --port "$PORT"
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The gateway listens on `0.0.0.0:<port>` and reports `https://tlo.example.com/mcp`. It cannot open a browser there, so it
|
|
67
|
+
needs an existing Orbit session: run `tlo-mcp login` on a Linux machine you can open the login URL from and copy
|
|
68
|
+
`2digits/tlo-mcp/session.json` (mode `0600`) from its config directory (`$XDG_CONFIG_HOME` or `~/.config`) to the same
|
|
69
|
+
place on the host. macOS keeps the session in the Keychain instead, so it produces no `session.json` to copy. Without a session the gateway exits instead of waiting for a login.
|
|
70
|
+
|
|
58
71
|
## Connect Executor Cloud
|
|
59
72
|
|
|
60
73
|
Paste the printed prompt into an agent with Executor tools. It registers a Streamable HTTP MCP integration with
|
|
@@ -86,7 +99,8 @@ handoff for the API key and verify one read-only tool after connecting.
|
|
|
86
99
|
- Tools, schemas, annotations, instructions, structured content, errors and rate limits come from official Orbit.
|
|
87
100
|
Only the allowlisted tools in `src/mcp/tools.ts` (timesheet, time entries, timers, tickets, todos and read-only
|
|
88
101
|
planning/project lookups) are forwarded; other Orbit tools are hidden and cannot be called. Startup warns when Orbit
|
|
89
|
-
no longer offers an allowlisted tool.
|
|
102
|
+
no longer offers an allowlisted tool. `AddProjectTask` is the gateway's own tool with a stricter schema; each call
|
|
103
|
+
is still exactly one Orbit write. Only tools are forwarded; resources/prompts/reverse requests are not exposed. No tool call is automatically replayed.
|
|
90
104
|
- To rotate the gateway key, stop the gateway, remove only `gateway.key`, restart, and update the Executor connection.
|
|
91
105
|
|
|
92
106
|
## Re-login and logout
|
package/dist/bin.mjs
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";import*as t from"@effect/platform-node/NodeRuntime";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*as o from"@yielded/oauth/OAuth";import*as s from"@yielded/oauth/Pkce";import*as c from"effect/Clock";import*as l from"effect/Context";import*as u from"effect/Equal";import*as d from"effect/Exit";import*as f from"effect/Layer";import*as p from"effect/Match";import*as m from"effect/Redacted";import*as h from"effect/Semaphore";import*as g from"effect/crypto/Digest";import*as ee from"effect/crypto/SecureRandom";import*as te from"effect/http/FetchHttpClient";import*as _ from"effect/http/HttpClient";import*as ne from"effect/http/HttpClientRequest";import*as re from"effect/process/ChildProcess";import*as ie from"effect/process/ChildProcessSpawner";import{timingSafeEqual as ae}from"node:crypto";import{createServer as oe}from"node:http";import*as se from"@effect/platform-node/NodeHttpServer";import*as ce from"effect/Deferred";import*as v from"effect/Predicate";import*as le from"effect/http/HttpRouter";import*as ue from"effect/http/HttpServer";import*as de from"effect/http/HttpServerRequest";import*as y from"effect/http/HttpServerResponse";import*as fe from"effect/FileSystem";import*as pe from"effect/Path";import*as me from"effect/Stream";import*as b from"effect/String";import*as he from"@effect/platform-node/NodeCrypto";import*as ge from"@effect/platform-node/NodeServices";import*as _e from"effect/persistence/UserDirectories";import{Context as ve,Effect as x,Layer as S,Option as ye,Queue as be,Schema as C,Stream as xe}from"effect";import{FetchHttpClient as Se,HttpClient as Ce,HttpClientError as we,HttpClientRequest as Te}from"effect/http";import{HttpApi as Ee,HttpApiClient as De,HttpApiEndpoint as w,HttpApiGroup as Oe,HttpApiMiddleware as ke,HttpApiSchema as Ae,HttpApiSecurity as je,OpenApi as Me}from"effect/http-api";import*as T from"node:fs/promises";import*as Ne from"node:os";import*as E from"node:path";import*as Pe from"node:net";import{Duplex as Fe}from"node:stream";import*as Ie from"node:tls";import*as Le from"effect/ByteSize";import*as Re from"effect/ai/McpProtocol";import*as ze from"effect/ai/McpServer";import*as Be from"effect/encoding/Hex";import*as Ve from"effect/http/HttpIncomingMessage";import*as D from"effect/Array";import*as O from"effect/Struct";import*as He from"effect/ai/McpClient";import*as Ue from"effect/http/HttpClientError";import*as k from"effect/Option";import*as We from"effect/ai/McpSchema";import*as Ge from"effect/ai/Toolkit";import*as Ke from"effect/ai/McpClientError";import*as A from"effect/ai/Tool";import*as qe from"effect/Record";import*as j from"effect/SchemaGetter";import*as M from"effect/DateTime";import*as Je from"effect/SchemaIssue";import*as Ye from"effect/Order";const Xe=`https://api.orbit.teamleader.eu`,Ze=`${Xe}/mcp`,Qe=r.String.check(r.isMinLength(1)).pipe(r.RedactedFromValue);var $e=class extends r.Class(`Session`)({clientId:r.String.check(r.isMinLength(1)),clientSecret:Qe.pipe(r.optionalKey),accessToken:Qe,refreshToken:Qe.pipe(r.optionalKey),expiresAt:r.Finite.pipe(r.optionalKey)}){static update(e,t,n){let r=t.refreshToken??e.refreshToken;return this.make({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}})}static needsRefresh(e,t){return e.expiresAt===void 0||e.expiresAt<=t+6e4}},N=class extends r.TaggedError()(`OrbitAuthError`,{message:r.String}){};function et(e){return e.clientSecret===void 0?{method:`none`,publicClient:!0}:{method:`client_secret_post`,secret:e.clientSecret.pipe(m.value,m.make)}}const tt={"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,"referrer-policy":`no-referrer`,"content-security-policy":`default-src 'none'`},nt=y.text(`Invalid callback.`,{status:400,headers:tt}),rt=y.text(`Authorization received. Return to your terminal to complete login.`,{headers:tt}),it=y.text(`Authorization denied. Return to your terminal.`,{status:400,headers:tt});function at(e,t){let n=e.searchParams.getAll(t);return n.length===1?n[0]:void 0}function ot(e,t){let n=at(e,`state`);if(n===void 0||e.pathname!==`/callback`)return;let r=Buffer.from(t),i=Buffer.from(n);if(r.length!==i.length||!ae(r,i))return;if(e.searchParams.has(`error`))throw Error(`Orbit authorization was denied.`);let a=at(e,`code`);return a===``?void 0:a}const st=n.fn(`OrbitAuth.listenForLogin`)(function*(e){let t=yield*ce.make(),r=yield*n.sync(oe),i=yield*se.make(()=>r,{port:0,host:`127.0.0.1`}).pipe(n.mapError(()=>N.make({message:`Could not bind OAuth callback.`})));if(!v.isTagged(i.address,`InetAddressV4`))return yield*N.make({message:`Could not bind OAuth callback.`});let a=`127.0.0.1:${i.address.port}`,o=`http://${a}/callback`,s=n.fn(`OrbitAuth.handleCallback`)(function*(){let r=yield*de.HttpServerRequest;return r.method!==`GET`||r.headers.host!==a||(yield*ce.isDone(t))?nt:yield*n.try({try:()=>ot(new URL(r.url,o),e),catch:()=>N.make({message:`Orbit authorization was denied.`})}).pipe(n.matchEffect({onFailure:e=>ce.fail(t,e).pipe(n.map(e=>e?it:nt)),onSuccess:e=>e===void 0?n.succeed(nt):ce.succeed(t,e).pipe(n.map(e=>e?rt:nt))}))}),c=yield*le.toHttpEffect(le.add(`*`,`*`,s()));return yield*ue.serveEffect(c).pipe(n.provideService(ue.HttpServer,i)),yield*n.addFinalizer(()=>n.sync(()=>r.closeAllConnections())),{redirectUri:o,code:ce.await(t).pipe(n.timeout(`3 minutes`),n.mapError(()=>N.make({message:`Login denied or timed out. Run tlo-mcp login again.`})))}}),ct=f.mergeAll(ge.layer,he.layerDigest,he.layerSecureRandom,_e.layer),lt=n.fn(`TloMcp.configDirectory`)(function*(e){let t=yield*fe.FileSystem,n=yield*pe.Path,r=yield*_e.UserDirectories,i=yield*r.config(`2digits`),a=yield*r.home,o=n.join(i,`tlo-mcp`),s=n.join(a,`.config`,`2digits`,`tlo-mcp`),c=yield*t.exists(n.join(o,e)),l=yield*t.exists(n.join(s,e));return!c&&l?s:o}),ut=$e.pipe(r.fromJsonString),dt=r.decodeEffect(ut),ft=r.encodeEffect(ut),pt=`@2digits/tlo-mcp/orbit`,mt=[`-a`,`orbit`,`-s`,pt];var ht=class extends l.Service()(`@2digits/tlo-mcp/oauth/store/SessionStore`){};function gt(e){return`"${b.replaceAll(/["\\]/g,b.String.raw`\$&`)(e)}"`}function _t(e={}){return f.effect(ht,n.gen(function*(){let t=yield*fe.FileSystem,r=yield*pe.Path,i=yield*ie.ChildProcessSpawner,a=e.platform??process.platform,o=e.directory??(yield*lt(`session.json`)),s=r.join(o,`session.json`),c=r.join(o,`session.lock`),l=t.makeDirectory(o,{recursive:!0,mode:448}).pipe(n.andThen(t.chmod(o,448))),u=n.fn(`SessionStore.security`)(function*(e,t){let r=yield*i.spawn(re.make(`/usr/bin/security`,e,{stdin:t===void 0?`ignore`:me.succeed(new TextEncoder().encode(t)),stderr:`ignore`}));return yield*n.all({output:r.stdout.pipe(me.decodeText(),me.mkString),exitCode:r.exitCode},{concurrency:`unbounded`})},n.scoped),d=n.fn(`SessionStore.load`)(function*(){if(a===`darwin`){let e=yield*u([`find-generic-password`,...mt,`-w`]);return e.exitCode===44?void 0:e.exitCode===0?yield*dt(b.trim(e.output)):yield*N.make({message:`Could not read macOS Keychain.`})}let e=yield*t.readFileString(s).pipe(n.catchReason(`PlatformError`,`NotFound`,()=>n.undefined));return e===void 0?void 0:yield*dt(e)},n.mapError(()=>N.make({message:`Could not read credentials. Run tlo-mcp login again.`}))),f=n.fn(`SessionStore.save`)(function*(e){let n=yield*ft(e);if(a===`darwin`){if((yield*u([`-q`,`-i`],`add-generic-password -U -a orbit -s ${gt(pt)} -w ${gt(n)}\n`)).exitCode!==0)return yield*N.make({message:`Could not save macOS Keychain credentials.`})}else{yield*l;let e=yield*t.makeTempDirectoryScoped({directory:o,prefix:`session-`}),i=r.join(e,`session.json`);yield*t.writeFileString(i,n,{mode:384}),yield*t.rename(i,s)}},n.scoped,n.mapError(()=>N.make({message:`Could not persist OAuth credentials. Run tlo-mcp login again.`}))),p=n.fn(`SessionStore.clear`)(function*(){if(a===`darwin`){let e=yield*u([`delete-generic-password`,...mt]);if(e.exitCode!==0&&e.exitCode!==44)return yield*N.make({message:`Could not remove Keychain credentials.`})}else yield*t.remove(s,{force:!0})},n.mapError(()=>N.make({message:`Could not remove OAuth credentials.`}))),m=n.fn(`SessionStore.lock`)(function*(){yield*l,yield*n.acquireRelease(t.writeFileString(c,process.pid.toString(),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>N.make({message:`OAuth credentials locked. Close other login/refresh processes. After a crash only, remove ${c}.`}))),()=>t.remove(c).pipe(n.orDie))},n.catchTag(`PlatformError`,()=>N.make({message:`Could not acquire OAuth credential lock. Check directory permissions.`})));return ht.of({load:d(),save:f,clear:p(),lock:m()})}))}const vt=_t(),yt=r.Struct({client_id:r.String.check(r.isMinLength(1)),client_secret:r.String.check(r.isMinLength(1)).pipe(r.RedactedFromValue,r.optionalKey)}),bt=r.is(N),xt=re.make({stdout:`ignore`,stderr:`ignore`,forceKillAfter:`1 second`});var St=class extends l.Service()(`@2digits/tlo-mcp/oauth/OrbitAuth`){};const Ct=f.effect(St,n.gen(function*(){let e=yield*ht,t=yield*g.Digest,i=yield*ee.SecureRandom,a=yield*_.HttpClient,l=yield*ie.ChildProcessSpawner,f=yield*h.make(1),re=yield*n.fn(`OrbitAuth.discover`)(function*(){let e=yield*_.withScope(a).get(`${Xe}/.well-known/oauth-authorization-server`);if(e.status!==200)return yield*N.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*N.make({message:`Unexpected Orbit endpoints; refusing to send credentials.`}):t},n.scoped,n.timeout(`15 seconds`),n.mapError(()=>N.make({message:`Invalid or unavailable Orbit OAuth metadata.`})))().pipe(n.cachedWithTTL(e=>d.isSuccess(e)?1/0:0)),ae=n.fn(`OrbitAuth.accessToken`)(function*(){let t=yield*e.load;if(t===void 0)return yield*N.make({message:`Not authenticated. Run tlo-mcp login first.`});let r=yield*c.currentTimeMillis;if(!$e.needsRefresh(t,r))return t.accessToken;if(t.refreshToken===void 0)return t.expiresAt===void 0?t.accessToken:yield*N.make({message:`Orbit session expired without a refresh token. Run tlo-mcp login.`});let i=yield*re,a=yield*(yield*o.make({metadata:i,clientId:t.clientId,authentication:et(t),timeoutMs:15e3})).refreshGrant({refreshToken:t.refreshToken,resources:[Ze]}).pipe(n.flatMap(o.tokens)),s=yield*c.currentTimeMillis,l=$e.update(t,a,s);return yield*e.save(l),l.accessToken}),oe=n.fn(`OrbitAuth.register`)(function*(e){let t=yield*ne.post(`${Xe}/oauth2/register`).pipe(ne.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(a).execute));return t.status!==200&&t.status!==201?yield*N.make({message:`Orbit client registration failed (HTTP ${t.status}).`}):yield*t.json.pipe(n.flatMap(r.decodeUnknownEffect(yt)))},n.scoped,n.timeout(`15 seconds`)),se=n.fn(`OrbitAuth.openBrowser`)(function*(e){return yield*(yield*p.value(process.platform).pipe(p.when(`darwin`,()=>xt`open ${e}`),p.when(`win32`,()=>xt`rundll32 url.dll,FileProtocolHandler ${e}`),p.orElse(()=>xt`xdg-open ${e}`))).exitCode},n.scoped,n.timeout(`5 seconds`),n.filterOrFail(u.equals(ie.ExitCode(0)),()=>N.make({message:`Could not open browser.`})),(e,t)=>e.pipe(n.catch(()=>n.sync(()=>{process.stderr.write(`Open this URL in your browser:\n${m.value(t)}\n`)})))),ce=n.fn(`OrbitAuth.login`)(function*(){let t=yield*re,r=yield*s.random(),i=yield*s.make(),a=yield*r.pipe(m.value,st),l=yield*oe(a.redirectUri),u={clientId:l.client_id,...l.client_secret===void 0?{}:{clientSecret:l.client_secret}},d=yield*o.make({metadata:t,...u,authentication:et(u),timeoutMs:15e3}),f=yield*d.authorizationUrl({redirectUri:a.redirectUri,scopes:[],state:r,codeChallenge:i.challenge,resources:[Ze]});yield*se(f);let p=yield*a.code,h=yield*d.codeGrant({code:m.make(p),redirectUri:a.redirectUri,pkceVerifier:i.verifier,resources:[Ze]}).pipe(n.flatMap(o.tokens)),g=yield*c.currentTimeMillis;yield*e.save($e.update(u,h,g)),yield*n.sync(()=>{process.stderr.write(`Orbit login complete.
|
|
3
|
-
`)})}),
|
|
4
|
-
`)}-----END CERTIFICATE REQUEST-----`}var vn=class extends C.TaggedError()(`OpenTunnelClientError`,{message:C.String,code:C.optional(C.String),cause:C.optional(C.Defect())}){},L=class extends C.TaggedError()(`OpenTunnelStorageError`,{message:C.String,cause:C.optional(C.Defect())}){};function yn(e={}){let t=e.env??process.env,n=e.home??Ne.homedir(),r=t.XDG_DATA_HOME??E.join(n,`.local`,`share`),i=E.join(r,`opentunnel`),a=e=>E.join(i,e),o=e=>x.tryPromise({try:()=>T.readFile(e,`utf8`),catch:e=>e}).pipe(x.catch(t=>x.gen(function*(){if(!(typeof t==`object`&&t&&`code`in t&&t.code===`ENOENT`))return yield*new L({message:`Failed to read ${e}`,cause:t})}))),s=x.fn(`OpenTunnelStorage.profiles`)(function*(){return(yield*x.tryPromise({try:()=>T.readdir(i,{withFileTypes:!0}),catch:e=>e}).pipe(x.catch(e=>x.gen(function*(){return typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`?[]:yield*new L({message:`Failed to list ${i}`,cause:e})})))).filter(e=>e.isDirectory()).map(e=>e.name).sort()}),c=x.fn(`OpenTunnelStorage.load`)(function*(e){let t=a(e),n=yield*o(E.join(t,`tunnel.json`));if(!n)return;let[r,i,s,c]=yield*x.all([o(E.join(t,`token`)),o(E.join(t,`private-key.pem`)),o(E.join(t,`certificate.pem`)),o(E.join(t,`chain.pem`))]);if(!r||!i||!s||c===void 0)return yield*new L({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=x.fn(`OpenTunnelStorage.loadPending`)(function*(e){let t=a(e),n=yield*o(E.join(t,`pending.json`));if(!n)return;let[r,i]=yield*x.all([o(E.join(t,`token`)),o(E.join(t,`private-key.pem`))]);if(!r||!i)return yield*new L({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)=>x.tryPromise({try:async()=>{let n=a(e);await T.mkdir(n,{recursive:!0,mode:448}),await Promise.all([T.writeFile(E.join(n,`pending.json`),JSON.stringify({id:t.id,hostname:t.hostname,csr:t.csr},null,2),{mode:384}),T.writeFile(E.join(n,`token`),`${t.token}\n`,{mode:384}),T.writeFile(E.join(n,`private-key.pem`),t.privateKey,{mode:384})])},catch:t=>new L({message:`Failed to save pending tunnel identity for ${e}`,cause:t})}),save:(e,t)=>x.tryPromise({try:async()=>{let n=a(e);await T.mkdir(n,{recursive:!0,mode:448}),await Promise.all([T.writeFile(E.join(n,`tunnel.json`),JSON.stringify({id:t.id,hostname:t.hostname,certificateExpiry:t.certificateExpiry.toISOString()},null,2),{mode:384}),T.writeFile(E.join(n,`token`),`${t.token}\n`,{mode:384}),T.writeFile(E.join(n,`private-key.pem`),t.privateKey,{mode:384}),T.writeFile(E.join(n,`certificate.pem`),t.certificate,{mode:384}),T.writeFile(E.join(n,`chain.pem`),t.chain,{mode:384})]),await T.rm(E.join(n,`pending.json`),{force:!0})},catch:t=>new L({message:`Failed to save tunnel identity for ${e}`,cause:t})}),remove:e=>x.tryPromise({try:()=>T.rm(a(e),{recursive:!0,force:!0}),catch:t=>new L({message:`Failed to remove tunnel identity for ${e}`,cause:t})}),list:()=>s().pipe(x.flatMap(e=>x.forEach(e,e=>c(e).pipe(x.map(t=>t?{profile:e,tunnel:t}:void 0)))),x.map(e=>e.filter(e=>e!==void 0)))}}const bn=/* @__PURE__ */ new Set([`http:`,`https:`]),xn=(e,t)=>{let n=e.trim(),r;try{r=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`http://${n}`)}catch{throw Error(`${t} is not a valid proxy URL`)}if(!bn.has(r.protocol))throw Error(`${t} uses an unsupported proxy scheme '${r.protocol.slice(0,-1)}': OpenTunnel connects through http:// and https:// proxies`);return r},Sn=e=>e.protocol===`https:`||e.protocol===`wss:`,Cn=(e,t)=>{let[n,r]=e.split(`/`,2),i=Pe.isIP(n);if(i===0||Pe.isIP(t)!==i)return!1;let a=i===4?`ipv4`:`ipv6`,o=new Pe.BlockList;if(r===void 0)o.addAddress(n,a);else if(/^\d+$/.test(r))o.addSubnet(n,Number(r),a);else return!1;return o.check(t,a)},wn=(e,t)=>{let n=e.hostname.toLowerCase().replace(/^\[(.*)\]$/,`$1`),r=e.port===``?Sn(e)?443:80:Number(e.port);for(let e of t.toLowerCase().split(/[\s,]+/)){if(e===``)continue;if(e===`*`)return!0;let t=e,i,a=/^\[([^\]]+)\](?::(\d+))?$/.exec(e);if(a)t=a[1],i=a[2]===void 0?void 0:Number(a[2]);else{let n=e.split(`:`);n.length===2&&/^\d+$/.test(n[1])&&(t=n[0],i=Number(n[1]))}if(i!==void 0&&i!==r)continue;if(Cn(t,n))return!0;let o=t.replace(/^\*?\./,``);if(o!==``&&(n===o||n.endsWith(`.${o}`)))return!0}return!1},Tn=(e,t)=>{let n=(Sn(e)?[`HTTPS_PROXY`,`https_proxy`,`ALL_PROXY`,`all_proxy`]:[`HTTP_PROXY`,`http_proxy`,`ALL_PROXY`,`all_proxy`]).find(e=>t[e]?.trim());if(n!==void 0&&!wn(e,t.NO_PROXY||t.no_proxy||``))return xn(t[n],n)},En=(e,t)=>new WebSocket(e,t),Dn=(e,t)=>((n,r)=>e(n,{...r,...t})),On=()=>{try{return e(import.meta.url)(`undici`)}catch(e){throw Error(`The proxy option needs the 'undici' package on Node: install it next to @opentunnel/client, or let Node use HTTPS_PROXY with NODE_USE_ENV_PROXY=1`,{cause:e})}},kn=()=>`Bun`in globalThis?`bun`:`Deno`in globalThis?`deno`:`node`,An=(e,t=process.env)=>{let n=e===void 0?void 0:xn(e,`The proxy option`).href;switch(kn()){case`bun`:return{...n===void 0?{}:{fetch:Dn(globalThis.fetch,{proxy:n})},webSocket:(e,r,i)=>{let a=n??Tn(e,t)?.href;return En(e,{protocols:r,headers:i,...a?{proxy:a}:{}})}};case`deno`:{if(n===void 0)break;let e=globalThis.Deno.createHttpClient({proxy:{url:n}});return{fetch:Dn(globalThis.fetch,{client:e}),webSocket:(t,n,r)=>En(t,{protocols:n,headers:r,client:e})}}case`node`:{if(n===void 0)break;let e=On(),t=new e.ProxyAgent({uri:n,proxyTunnel:!0});return{fetch:Dn(e.fetch,{dispatcher:t}),webSocket:(n,r,i)=>new e.WebSocket(n,{protocols:r,headers:i,dispatcher:t})}}}return{webSocket:(e,t,n)=>En(e,{protocols:t,headers:n})}},jn=C.Int.check(C.isBetween({minimum:0,maximum:4294967295}));var Mn=class extends C.Class(`BridgeProtocol/ClientInfo`)({version:C.String,max_conns:C.Number}){},Nn=class extends C.Class(`BridgeProtocol/AttachMessage`)({type:C.Literal(`attach`),token:C.String,transport:C.Literal(`ws`),client:Mn,routes:C.Array(C.String).pipe(C.optional)}){},Pn=class extends C.Class(`BridgeProtocol/AttachedMessage`)({type:C.Literal(`attached`),session:C.String,routes:C.Array(C.String),heartbeat_ms:C.Number,idle_timeout_ms:C.Number}){},Fn=class extends C.Class(`BridgeProtocol/AttachErrorMessage`)({type:C.Literal(`attach_error`),code:C.String}){},In=class extends C.Class(`BridgeProtocol/PingMessage`)({type:C.Literal(`ping`),time_sent:C.Number}){},Ln=class extends C.Class(`BridgeProtocol/PongMessage`)({type:C.Literal(`pong`),time_sent:C.Number}){},Rn=class extends C.Class(`BridgeProtocol/DrainMessage`)({type:C.Literal(`drain`),reason:C.String}){},zn=class extends C.Class(`BridgeProtocol/OpenMessage`)({type:C.Literal(`open`),conn:jn,peer:C.String,sni:C.String,alpn:C.String}){},Bn=class extends C.Class(`BridgeProtocol/EndMessage`)({type:C.Literal(`end`),conn:jn}){},Vn=class extends C.Class(`BridgeProtocol/ResetMessage`)({type:C.Literal(`reset`),conn:jn,code:C.String}){};C.Union([Nn,In,Ln,Rn,Bn,Vn]);const Hn=C.Union([Pn,Fn,In,Ln,Rn,zn,Bn,Vn]),Un=C.decodeUnknownOption(Hn);function Wn(e){try{return Un(JSON.parse(e))}catch{return ye.none()}}C.Union([Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn]);const R={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`},Gn={HEARTBEAT_MS:15e3,IDLE_TIMEOUT_MS:45e3,CONNECT_TIMEOUT_MS:1e4,RECONNECT_BACKOFF_MIN_MS:250,RECONNECT_BACKOFF_MAX_MS:3e4},z={CONN_ID_SIZE:4,MAX_PAYLOAD_SIZE:32768};function Kn(e){return e.length<z.CONN_ID_SIZE?null:{conn:new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!1),payload:e.slice(z.CONN_ID_SIZE)}}function qn(e,t){let n=new Uint8Array(z.CONN_ID_SIZE+t.length);return new DataView(n.buffer).setUint32(0,e,!1),n.set(t,z.CONN_ID_SIZE),n}const Jn=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Yn=e=>e===`@`||Jn.test(e),Xn=(e,t)=>e===`@`?t:`${e}.${t}`,Zn=(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 Jn.test(a)?a:void 0},Qn=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}},$n=e=>e===`v1`||e===`v2`,er=Uint8Array.of(13,10,13,10,0,13,10,81,85,73,84,10),tr=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},nr=(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=tr(i);if(!e)return;n.push(e[0]<<8|e[1],e[2]<<8|e[3])}else{if(!/^[0-9A-Fa-f]{1,4}$/.test(i))return;n.push(Number.parseInt(i,16))}return n},rr=e=>{let t=e.indexOf(`::`),n;if(t===-1){if(n=nr(e,!0),n?.length!==8)return}else{if(e.indexOf(`::`,t+1)!==-1)return;let r=nr(e.slice(0,t),!1),i=nr(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},ir=e=>{if(!/^[0-9]{1,5}$/.test(e))return;let t=Number(e);return t<=65535?t:void 0},ar=e=>e.subarray(0,10).every(e=>e===0)&&e[10]===255&&e[11]===255,or=(e,t)=>e.length===16&&ar(e)?{family:4,bytes:e.slice(12),port:t}:e.length===4?{family:4,bytes:e,port:t}:{family:6,bytes:e,port:t},sr=e=>{let t=tr(e)??rr(e);if(t)return or(t,0);if(e.startsWith(`[`)){let t=e.indexOf(`]:`);if(t===-1)return;let n=rr(e.slice(1,t)),r=ir(e.slice(t+2));return n&&r!==void 0?or(n,r):void 0}let n=e.lastIndexOf(`:`);if(n===-1)return;let r=tr(e.slice(0,n)),i=ir(e.slice(n+1));return r&&i!==void 0?or(r,i):void 0},cr=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))}`},lr=new TextEncoder,ur=(e,t,n)=>{let r=sr(t);return e===`v1`?dr(r):fr(r,n)},dr=e=>{if(!e)return lr.encode(`PROXY UNKNOWN\r
|
|
5
|
-
`);let[t,n]=e.family===4?[`TCP4`,`0.0.0.0`]:[`TCP6`,`::`];return lr.encode(`PROXY ${t} ${cr(e)} ${n} ${e.port} 443\r\n`)},fr=(e,t)=>{let n=lr.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(er,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},pr=e=>Yn(e),mr=(e,t)=>`https://${Xn(e,t)}`,hr=(e,t)=>Object.fromEntries(Object.keys(e).map(e=>[e,mr(e,t)]));var gr=class extends Error{code;constructor(e){super(e===R.ROUTE_CONFLICT?`Bridge attach failed: ${e} (another client holds a route)`:`Bridge attach failed: ${e}`),this.code=e}};const _r=/* @__PURE__ */ new Set([R.BAD_TOKEN,R.CERT_NOT_READY]),vr=/* @__PURE__ */ new Set([`target`,`proxyProtocol`]),yr=(e,t)=>{if(!pr(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(!vr.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(!$n(i.proxyProtocol))throw Error(`Invalid proxyProtocol '${String(i.proxyProtocol)}' for route '${e}': use "v1" or "v2"`);r=i.proxyProtocol}}let i=typeof n==`string`?Qn(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}},br=e=>{for(let[t,n]of Object.entries(e))yr(t,n)},xr=e=>new Map(Object.entries(e).map(([e,t])=>[e,yr(e,t)])),Sr=e=>Ie.createSecureContext({key:e.privateKey,cert:`${e.certificate}\n${e.chain}`}),Cr=(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])},wr=e=>{let t=Math.min(Gn.RECONNECT_BACKOFF_MIN_MS*2**Math.min(e,16),Gn.RECONNECT_BACKOFF_MAX_MS);return Math.round(t/2+t/2*Math.random())};var Tr=class{options;routes;resolved;identity;secureContext;refreshTimer;refreshAbort=new AbortController;transport;session;shutdown=!1;wake;status;ready;closed;constructor(e){this.options=e,this.resolved=xr(e.routes),this.transport=e.transport??An(),this.routes={...e.routes},this.identity=e.identity,this.secureContext=Sr(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(this.transport.fetch??fetch)(e,{headers:{authorization:`Bearer ${this.identity.token}`},signal:this.refreshAbort.signal}),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=Sr(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}}}getUrls(){return hr(this.routes,this.identity.hostname)}setRoutes(e){let t=xr(e),n=this.routes;this.resolved=t,this.routes={...e},this.status.routes=this.routes,Cr(n,this.routes)||this.session?.end({type:`routes-changed`}),this.wake?.()}close(){return this.shutdown=!0,clearTimeout(this.refreshTimer),this.refreshAbort.abort(),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 Er(this.options,this.transport,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=wr(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}}},Er=class{options;transport;routes;secureContext;hooks;socket;finish;channels=/* @__PURE__ */ new Map;drainWaiters=[];drainTimer;heartbeat;attachTimeout;lastReceived=Date.now();attached=!1;constructor(e,t,n,r,i){this.options=e,this.transport=t,this.routes=n,this.secureContext=r,this.hooks=i}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;try{n=this.transport.webSocket(t,[`opentunnel`],{"user-agent":rn})}catch(e){this.end({type:`fatal`,error:e instanceof Error?e:Error(String(e))});return}n.binaryType=`arraybuffer`,this.socket=n,this.attachTimeout=setTimeout(()=>this.end({type:`retry`,error:`bridge attach timed out`,attached:!1}),Gn.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=Wn(e);if(ye.isNone(t))return;let n=t.value;if(this.attached)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})}else 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(()=>{Date.now()-this.lastReceived>t?this.end({type:`retry`,error:`bridge idle timeout`,attached:!0}):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 if(n.type===`attach_error`){let e=n.code===R.ROUTE_CONFLICT;e&&this.hooks.emit({type:`route-conflict`,routes:Object.keys(this.routes).sort()}),this.end(_r.has(n.code)||e&&this.options.onRouteConflict===`fail`?{type:`fatal`,error:new gr(n.code)}:{type:`retry`,error:`attach failed: ${n.code}`,attached:!1})}}onData(e){let t=Kn(e);t&&this.channels.get(t.conn)?.push(t.payload)}open(e,t,n){let r=Zn(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:R.UNKNOWN_ROUTE});return}if(this.channels.size>=256){this.sendControl({type:`reset`,conn:e,code:R.TOO_MANY_CONNECTIONS});return}let a=i.proxyProtocol===void 0?void 0:ur(i.proxyProtocol,n,t),o=new Dr(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`));else{for(let n=0;n<t.byteLength;n+=z.MAX_PAYLOAD_SIZE){let i=t.subarray(n,n+z.MAX_PAYLOAD_SIZE);r.send(qn(e,i))}r.bufferedAmount<1048576?n():(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))}}},Dr=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 Fe({allowHalfOpen:!0,read(){},write:(t,n,r)=>a.sendData(e,t,r),final:t=>{a.sendControl({type:`end`,conn:e}),t()}}),this.tls=new Ie.TLSSocket(this.raw,{isServer:!0,secureContext:i}),this.tls.on(`secure`,()=>{let e=Pe.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?R.UPSTREAM_CONNECT_FAILED:R.UPSTREAM_IO_ERROR,!0,t.message)),this.tls.pipe(e),e.pipe(this.tls)}),this.tls.on(`error`,e=>this.destroy(R.UPSTREAM_IO_ERROR,!0,e.message)),this.tls.on(`close`,()=>this.finish(void 0))}push(e){this.done||(this.raw.readableLength>8388608?this.destroy(R.UPSTREAM_IO_ERROR,!0,`local connection stalled`):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 B=e=>e?.profile??`default`,Or=e=>{if(we.isHttpClientError(e)){let t=e.response;if(!t)return e.message;let n=kt(t.status,``);return n.startsWith(`HTTP `)?n:`${n} (HTTP ${t.status})`}if(typeof e==`object`&&e){let{_tag:t,message:n}=e;if(typeof t==`string`&&typeof n==`string`)return`${t}: ${n}`}return e instanceof Error?e.message:void 0},V=(e,t)=>{let n=Or(t);return new vn({message:n?`${e}: ${n}`:e,cause:t})},kr=(e,t)=>{let n=Or(t);return new vn({message:n?`${e}: ${n}`:e,...t instanceof gr?{code:t.code}:{},cause:t})},Ar=e=>we.isHttpClientError(e)&&(e.reason._tag===`TransportError`||e.response!==void 0&&Tt(e.response.status,`idempotent`)),jr=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`},
|
|
7
|
-
`),e=>
|
|
8
|
-
`),e=>
|
|
9
|
-
`),e=>b.isNonEmpty(b.trim(e))&&!D.some(Oi,t=>t.test(e))),r=b.startsWith(`- `);return{header:t,columns:D.filter(n,e=>e===Ei),days:D.filter(n,e=>e!==Ei&&!r(e)),entries:D.filter(n,r)}}const Ai={name:`GetTimesheetWeek`,args:r.Struct({date:W}),result:r.String.pipe(r.decodeTo(Di,{decode:j.transform(ki),encode:j.forbiddenEncoding}),r.decodeTo(bi,{decode:j.transform(({header:e,days:t,entries:n})=>({...e,days:D.map(t,e=>({...e,entries:D.map(D.filter(n,({weekday:t})=>t===e.weekday),({time:t,...n})=>Si(`${e.date} ${t}`,n))}))})),encode:j.forbiddenEncoding}))};var ji=class extends r.Class(`Absence`)({id:U,date:W,type:r.String.annotate({description:`Absence type, e.g. "Holiday" or "Office Closed"`}),minutes:G,state:r.Literals([`approved`,`pending`,`refused`,`revoked`]),note:r.String.pipe(r.optionalKey)}){};const Mi=J(/^- (?<date>\S+) \| .+? \| (?<type>(?:(?! \| ).)+) (?<minutes>\d+h\d*) \| (?<state>[A-Z]+)(?: approval)?(?: — (?<note>.+?))? {2}\(api_id: (?<id>[A-Z0-9]{15})\)$/s,{...ji.fields,minutes:K,state:r.Literals([`APPROVED`,`PENDING`,`REFUSED`,`REVOKED`]).pipe(r.decodeTo(ji.fields.state,{decode:j.transform(b.toLowerCase),encode:j.transform(b.toUpperCase)}))}).pipe(r.decodeTo(ji)),Ni={name:`ListAbsences`,args:r.Struct({dateFrom:W,dateTo:W}),result:Y(Mi,/^\d+ absence\(s\):$/,/^Approve\/refuse pending requests/,/^No absences match these filters\.$/)};var Pi=class extends r.Class(`BookableTask`)({id:U,label:r.String.annotate({description:`Project and task; Orbit separates both with " | ", as inside names`}),projectNumber:r.String.pipe(r.optionalKey),remainingMinutes:G.annotate({description:`Remaining budget; absent when unlimited`}).pipe(r.optionalKey)}){};const Fi=J(/^\| (?<label>(?:(?<projectNumber>\d+) )?.+?) \| (?:unlimited|(?<remainingMinutes>\d+h\d*)) \| (?<id>[A-Z0-9]{15}) \|$/,{...Pi.fields,remainingMinutes:K.pipe(r.optionalKey)}).pipe(r.decodeTo(Pi)),Ii={name:`ListMyTasks`,args:r.Record(r.String,r.Never),result:Y(Fi,/^\d+ assignable task\(s\):$/,/^\| Project \|/,/^\|---/,/^No assignable tasks found/)},Li=r.Literals([`planned`,`fixed-time`,`request`,`refused`]),Ri=J(/^- (?<start>\d{4}-\d{2}-\d{2} \d{2}:\d{2}) \| .+? \| (?<minutes>\d+h\d*) \| (?<kind>[a-z-]+) \| (?<work>.+?)(?: \| series (?<seriesId>[A-Z0-9]{15}))? {2}\(api_id: (?<id>[A-Z0-9]{15})\)$/s,{id:U,start:q,minutes:K,kind:Li,work:r.String,seriesId:U.pipe(r.optionalKey)}),zi={name:`ListPlannedEntries`,args:r.Struct({dateFrom:W,dateTo:W}),result:Y(Ri,/^\d+ planning entries:$/,/^No planning entries match these filters\.$/)},Z=1050;var Bi=class extends r.Class(`TimeSlot`)({from:r.String.annotate({description:`HH:mm, Europe/Amsterdam`}),to:r.String.annotate({description:`HH:mm, Europe/Amsterdam`}),minutes:G}){},Vi=class extends r.Class(`Overlap`)({first:U,second:U,minutes:G}){},Hi=class extends r.Class(`UnconfirmedPlanned`)({id:U.annotate({description:`Entry api_id for ConfirmPlannedEntry`}),start:q,minutes:G,work:r.String,taskId:U.pipe(r.optionalKey),planningKind:Li.annotate({description:`From ListPlannedEntries`}).pipe(r.optionalKey),seriesId:U.pipe(r.optionalKey)}){},Ui=class extends r.Class(`WorkdayDay`)({date:W,weekday:r.String,state:r.Literals([`OPEN`,`FINAL`]),capacityMinutes:G,loggedMinutes:G,plannedMinutes:G,absenceMinutes:G,missingMinutes:G.annotate({description:`Capacity minus logged and absence time`}),dayOff:r.Boolean.annotate({description:`No capacity, or absence covers it`}),entries:r.Array(vi).annotate({description:`Entries, after the taskId/kind filters`}),unconfirmedPlanned:r.Array(Hi),gaps:r.Array(Bi).annotate({description:`Time within working hours without any entry; unconfirmed planned entries count as occupied`}),overlaps:r.Array(Vi),outsideWorkingHours:r.Array(U).annotate({description:`Entries starting before or ending after working hours`})}){},Wi=class extends r.Class(`Workday`)({from:W,to:W,timeZone:r.String,workingHours:Bi,totals:r.Struct({capacityMinutes:G,loggedMinutes:G,plannedMinutes:G,absenceMinutes:G,missingMinutes:G}),days:r.Array(Ui),absences:r.Array(ji),runningTimer:pi,bookableTasks:r.Array(Pi)}){};const Gi=A.make(`GetMyWorkday`,{description:`Read-only overview of your own timesheet for one day, its week, or a range of up to 62 days, in one call. Per day: OPEN/FINAL state, logged/planned/absence time vs capacity, every entry with api_id, task/ticket api_id and edit lock, planned entries still to confirm, gaps, overlaps and entries outside 09:00–17:30. Also lists absences with approval state, the running timer and bookable tasks with remaining budget. Times are Europe/Amsterdam. Use Orbit's write tools for changes.`,parameters:r.Struct({date:W.annotate({description:`The day to show, or the first day of the range (yyyy-MM-dd)`}),scope:r.Literals([`day`,`week`]).annotate({description:`day (default) or the Monday–Sunday week containing date; ignored when to is set`}).pipe(r.withDecodingDefault(n.succeed(`day`))),to:W.annotate({description:`Optional last day of the range, inclusive (yyyy-MM-dd)`}).pipe(r.optional),taskId:U.annotate({description:`Only list entries on this task api_id`}).pipe(r.optional),kind:_i.annotate({description:`Only list entries of this kind`}).pipe(r.optional)}),success:Wi,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0);function Ki(e){return M.makeUnsafe(`${e}T00:00:00Z`)}function qi(e,t){return M.formatIsoDateUtc(M.add(Ki(e),{days:t}))}function Ji(e){return qi(e,-((M.toPartsUtc(Ki(e)).weekDay+6)%7))}function Yi(e){let{hour:t,minute:n}=M.toParts(e);return t*60+n}function Xi(e){let t=b.padStart(2,`0`);return`${t(String(Math.floor(e/60)))}:${t(String(e%60))}`}function Zi(e,t){return Bi.make({from:Xi(e),to:Xi(t),minutes:t-e})}function Qi(e){let t=Yi(e.start);return{id:e.id,from:t,to:t+e.minutes}}function $i(e){let t=[],n=540,r=D.sortWith(e,({from:e})=>e,Ye.Number);for(let e of r)e.from>n&&n<Z&&t.push(Zi(n,Math.min(e.from,Z))),n=Math.max(n,e.to);return n<Z?[...t,Zi(n,Z)]:t}function ea(e){let t=D.sortWith(e,({from:e})=>e,Ye.Number);return D.flatMap(t,(e,n)=>D.flatMap(D.drop(t,n+1),t=>t.from<e.to?[Vi.make({first:e.id,second:t.id,minutes:Math.min(e.to,t.to)-t.from})]:[]))}function ta(e,t,n){let r=D.map(e.entries,Qi),i=e.capacityMinutes===0||e.absenceMinutes>=e.capacityMinutes;return Ui.make({date:e.date,weekday:e.weekday,state:e.state,capacityMinutes:e.capacityMinutes,loggedMinutes:e.loggedMinutes,plannedMinutes:e.plannedMinutes,absenceMinutes:e.absenceMinutes,missingMinutes:Math.max(0,e.capacityMinutes-e.loggedMinutes-e.absenceMinutes),dayOff:i,entries:D.filter(e.entries,e=>(n.taskId===void 0||e.taskId===n.taskId)&&(n.kind===void 0||e.kind===n.kind)),unconfirmedPlanned:D.flatMap(e.entries,e=>{if(e.kind!==`planned`)return[];let n=D.findFirst(t,({id:t})=>t===e.id);return[Hi.make({...O.pick(e,[`id`,`start`,`minutes`,`work`,`taskId`]),...k.match(n,{onNone:()=>({}),onSome:e=>({planningKind:e.kind,...O.pick(e,[`seriesId`])})})})]}),gaps:i?[]:$i(r),overlaps:ea(r),outsideWorkingHours:D.flatMap(r,({id:e,from:t,to:n})=>t<540||n>Z?[e]:[])})}const na=n.fn(`GetMyWorkday`)(function*(e,t){let r=t.to===void 0&&t.scope===`week`?Ji(t.date):t.date,i=t.to??(t.scope===`week`?qi(r,6):r);if(i<r||i>qi(r,61))return yield*n.fail(H.make({message:`Range ${r}..${i} must be 1 to 62 days.`}));let a=D.unfold(Ji(r),e=>e>i?k.none():k.some([e,qi(e,7)])),o={dateFrom:r,dateTo:i},[s,c,l,u,d]=yield*n.all([n.forEach(a,t=>e.call(Ai,{date:t}),{concurrency:4}),e.call(Ni,o),e.call(zi,o),e.call(gi,{}),e.call(Ii,{})],{concurrency:`unbounded`}),f=D.filter(D.flatMap(s,e=>e.days),e=>e.date>=r&&e.date<=i),p=D.unfold(r,e=>e>i?k.none():k.some([e,qi(e,1)]));if(D.join(D.map(f,({date:e})=>e),`,`)!==D.join(p,`,`))return yield*n.fail(H.make({message:`Orbit's timesheets do not cover every day of ${r}..${i}.`}));let m=D.map(f,e=>ta(e,l,t));function h(e){return D.reduce(m,0,(t,n)=>t+n[e])}return Wi.make({from:r,to:i,timeZone:Ur,workingHours:Zi(540,Z),totals:{capacityMinutes:h(`capacityMinutes`),loggedMinutes:h(`loggedMinutes`),plannedMinutes:h(`plannedMinutes`),absenceMinutes:h(`absenceMinutes`),missingMinutes:h(`missingMinutes`)},days:m,absences:c,runningTimer:u,bookableTasks:d})},n.mapError(zr)),ra=J(/^- (?<start>\d{4}-\d{2}-\d{2} \d{2}:\d{2}) \| .+? \| (?<minutes>\d+h\d*)(?: (?<planned>\[PLANNED\]))? \| (?:(?<absence>ABSENCE(?: \(pending approval\))?) )?(?![[(]|ABSENCE)(?<work>ticket ".*?"(?= — \d+ )|.+?)(?: — (?<description>.+?))? {2}\(api_id: (?<id>[A-Z0-9]{15})\)(?: \[locked: (?<lock>.+)\])?$/s,{start:r.String,...xi}).pipe(r.decodeTo(vi,{decode:j.transform(({start:e,...t})=>Si(e,t)),encode:j.forbiddenEncoding})),ia=r.Struct({entries:Y(ra,/^\d+ time entries/,/^Total duration: /,/^No time entries match these filters\.$/),truncated:r.Boolean.annotate({description:`Orbit capped the list at 100 rows; narrow the range`})}),aa={name:`ListTimeEntries`,args:r.Struct({dateFrom:W,dateTo:W,text:r.String.pipe(r.optionalKey)}),result:r.String.pipe(r.decodeTo(ia,{decode:j.transform(e=>({entries:e,truncated:/^\d+ time entries \(more exist/.test(e)})),encode:j.forbiddenEncoding}))},Q=r.String.pipe(r.NullOr),$=q.pipe(r.NullOr);var oa=class extends r.Class(`TicketSummary`)({ticketId:U,number:r.String,name:r.String,state:r.String}){},sa=class extends r.Class(`TicketDetail`)({ticketId:U,number:r.String,name:r.String,description:r.String,state:r.String,priority:r.String,category:Q,queue:Q,client:Q,clientId:U.pipe(r.NullOr),contact:Q,owner:Q,assignee:Q,project:Q,projectId:U.pipe(r.NullOr),task:Q,taskId:U.pipe(r.NullOr),loggedMinutes:G,invoicedMinutes:G,billable:r.Boolean,slaResponseDue:$,slaCloseDue:$,followUpAction:Q,followUpDate:$,createdDate:q,closedDate:$,lastClientInput:$,lastAgentReply:$,attachments:r.Array(r.Struct({fileId:U,name:r.String,downloadUrl:r.String})),downloadLinksNote:r.String.pipe(r.optionalKey),otherOpenTicketsOfClient:r.Array(oa)}){},ca=class extends r.Class(`TicketComment`)({commentId:U,date:q,isInternal:r.Boolean,author:Q,title:Q,content:r.String,loggedMinutes:G,timeEntryId:U.pipe(r.NullOr)}){};const la=r.Struct({count:r.Int,tickets:r.Array(oa)}),ua=r.Struct({count:r.Int,comments:r.Array(ca)}),da={name:`ListTickets`,args:r.Struct({query:r.String,state:r.String,limit:r.Int}),result:la.pipe(r.fromJsonString)},fa={name:`GetTicketDetail`,args:r.Struct({ticketId:U}),result:sa.pipe(r.fromJsonString)},pa={name:`ListTicketComments`,args:r.Struct({ticketId:U,limit:r.Int}),result:ua.pipe(r.fromJsonString)},ma=/^[A-Z0-9]{15}$/;var ha=class extends r.Class(`TicketContext`)({ticket:sa,comments:r.Array(ca).annotate({description:`Newest first, internal notes included`}),commentCount:r.Int.annotate({description:`Number of comments returned, not the ticket total`}),commentsTruncated:r.Boolean.annotate({description:`Orbit returns at most 100 comments; true when that cap was reached, so older comments may be missing`}),timeEntries:r.Array(vi).annotate({description:`Your entries booked on this ticket`}),timeEntriesTruncated:r.Boolean.annotate({description:`Orbit capped the entry search at 100 rows`}),loggedMinutes:G.annotate({description:`Sum of the logged timeEntries; planned entries are not counted`}),mentionedIn:r.Array(U).annotate({description:`Your other entries whose description mentions the ticket number`})}){};const ga=A.make(`GetTicketContext`,{description:`Read-only context for one support ticket by its number (e.g. 9087) or api_id, in one call: full detail, the conversation (newest first), and your time entries on it. Finds closed tickets too. Times are Europe/Amsterdam. Use Orbit write tools (ReplyToTicket, AddInternalComment, CloseTicket) for changes.`,parameters:r.Struct({ticket:r.String.annotate({description:`Ticket number such as "9087", or the ticket api_id`})}),success:ha,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0),_a=n.fn(`GetTicketContext`)(function*(e,{ticket:t}){let r=b.trim(t),i=r;if(!ma.test(r)){let{tickets:t}=yield*e.call(da,{query:r,state:`NEW|OPEN|WAIT|CLOSED|DELETED|REQCLOSE`,limit:100}),a=D.findFirst(t,({number:e})=>e===r);if(k.isNone(a))return yield*n.fail(H.make({message:t.length>=100?`Ticket ${r} is not in the first 100 search results Orbit returned; pass the ticket api_id instead.`:`No ticket with number ${r} found.`}));i=a.value.ticketId}let[a,o]=yield*n.all([e.call(fa,{ticketId:i}),e.call(pa,{ticketId:i,limit:100})],{concurrency:`unbounded`}),s=yield*M.now,c=yield*e.call(aa,{dateFrom:M.formatIsoDate(a.createdDate),dateTo:M.formatIsoDate(M.setZoneNamedUnsafe(s,Ur)),text:a.number});function l({work:e,description:t=``}){let[n]=b.split(t,` `);return b.startsWith(`ticket "`)(e)&&n===a.number}function u({work:e,description:t=``}){return D.contains(b.split(`${e} ${t}`,/\D+/),a.number)}let d=D.filter(c.entries,l),f=D.filter(c.entries,e=>!l(e)&&u(e));return ha.make({ticket:a,comments:o.comments,commentCount:o.count,commentsTruncated:o.comments.length>=100,timeEntries:d,timeEntriesTruncated:c.truncated,loggedMinutes:D.reduce(d,0,(e,t)=>t.kind===`logged`?e+t.minutes:e),mentionedIn:D.map(f,({id:e})=>e)})},n.mapError(zr)),va=Ge.make(Gi,ga,ui),ya=va.toLayer(n.gen(function*(){let e=yield*Vr;return va.of({GetMyWorkday:t=>na(e,t),GetTicketContext:t=>_a(e,t),GetBoardContext:t=>fi(e,t)})})),ba=r.decodeUnknownEffect(r.JsonObject),xa=r.decodeUnknownOption(H.pipe(r.fromJsonString));function Sa(e){return We.CallToolResult.make({isError:!0,content:[{type:`text`,text:`Orbit rate limited this call; retry after ${e??`the server cooldown`}. Not replayed.`}],_meta:{"tlo-mcp/httpStatus":429,...e===void 0?{}:{"tlo-mcp/retryAfter":e}}})}function Ca(e){let[t]=`content`in e&&e.isError===!0?e.content:[];return k.match(t?.type===`text`?xa(t.text):k.none(),{onNone:()=>e,onSome:({message:e,status:t,retryAfter:n})=>t===429?Sa(n):We.CallToolResult.make({isError:!0,content:[{type:`text`,text:e}]})})}const wa=f.effectDiscard(n.gen(function*(){let e=yield*Fr,t=yield*ze.McpServer;yield*n.forEach(e.tools,n.fn(`OrbitProxyLive.tool`)(function*(r){yield*t.addTool({tool:r,annotations:l.empty(),handle:n.fn(`handle`)(function*(e){return yield*ba(e)},n.mapError(e=>We.InvalidParams.make({message:`Tool arguments must be a JSON object.`,data:e})),n.flatMap(t=>e.callTool(r,t).pipe(n.catchReason(`McpClientError`,`HttpError`,({status:e,retryAfter:t},r)=>e===429?n.succeed(Sa(t)):n.fail(r)),n.mapError(e=>We.InternalError.make({message:e.message})))))})}),{discard:!0}),yield*ze.registerToolkit(va).pipe(n.provideService(ze.McpServer,ze.McpServer.of({...t,addTool:n.fn(`OrbitProxyLive.composite`)(function*(e){yield*t.addTool({...e,handle:t=>e.handle(t).pipe(n.map(Ca))})})})))})).pipe(f.provide(f.provideMerge(ya,Hr))),Ta=n.gen(function*(){let e=yield*pe.Path,t=yield*lt(`gateway.key`);return e.join(t,`gateway.key`)}),Ea=Le.mebibytes(1),Da=y.empty({status:401,headers:{"www-authenticate":`Bearer`,"cache-control":`no-store`}}),Oa=y.empty({status:403,headers:{"cache-control":`no-store`}}),ka=new TextEncoder,Aa=r.String.check(r.isPattern(/^[a-f0-9]{64}$/)).pipe(r.RedactedFromValue);var ja=class extends r.TaggedError()(`GatewayError`,{message:r.String}){};const Ma=n.fn(`Gateway.loadKey`)(function*(e){let t=yield*fe.FileSystem,i=yield*ee.SecureRandom,a=(yield*pe.Path).dirname(e);yield*t.makeDirectory(a,{recursive:!0,mode:448}),yield*t.chmod(a,448);let o=yield*i.randomBytes(32);yield*t.writeFileString(e,Be.encode(o),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>n.void));let s=yield*t.stat(e);return s.type!==`File`||s.mode&63?yield*ja.make({message:`Gateway key must be a private file (chmod 600).`}):yield*t.readFileString(e).pipe(n.flatMap(r.decodeEffect(Aa)))},n.mapError(()=>ja.make({message:`Cannot load private gateway key. Check its permissions and format.`})));function Na(e,t){return e.digest(g.sha256,ka.encode(t))}function Pa(e){return f.unwrap(n.gen(function*(){let t=yield*g.Digest,r=yield*Na(t,`Bearer ${m.value(e)}`);return le.middleware(e=>n.gen(function*(){let i=yield*de.HttpServerRequest,a=yield*Na(t,i.headers.authorization??``);return ae(r,a)?i.headers.origin===void 0?yield*e.pipe(n.provideService(Ve.MaxBodySize,Ea),n.map(e=>y.setHeader(e,`cache-control`,`no-store`))):Oa:Da}),{global:!0})}))}function Fa(e){let t=f.unwrap(n.gen(function*(){let e=yield*Fr;return wa.pipe(f.provide(ze.layerHttp({name:`tlo-mcp`,version:`1.0.0`,instructions:e.instructions,path:`/mcp`,protocols:[Re.v2025_11_25,Re.v2025_06_18,Re.v2025_03_26]})))}));return f.merge(t,Pa(e))}const Ia=r.String.check(r.isPattern(/^[a-z0-9]+\.opentunnel\.xyz$/)),La=r.decodeEffect(Ia),Ra=n.fn(`Gateway.openTunnel`)(function*(e){let t=yield*(yield*Nr).tunnel.connect({profile:`tlo-mcp`,routes:{tlo:`127.0.0.1:${e}`}}),r=yield*La(t.tunnel.hostname);return yield*t.events.pipe(me.filter(e=>e.type===`reconnecting`),me.runForEach(()=>n.sync(()=>process.stderr.write(`OpenTunnel reconnecting...
|
|
10
|
-
`))),n.forkScoped),{endpoint:`https://tlo.${r}/mcp`,closed:t.closed.pipe(n.mapError(()
|
|
2
|
+
import{createRequire as e}from"node:module";import*as t from"@effect/platform-node/NodeRuntime";import*as n from"effect/Effect";import*as r from"effect/Option";import*as i from"effect/Schema";import*as a from"effect/cli/Command";import*as o from"effect/cli/Flag";import*as s from"@yielded/oauth/OAuth";import*as c from"@yielded/oauth/Pkce";import*as l from"effect/Clock";import*as u from"effect/Context";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 g from"effect/Semaphore";import*as ee from"effect/crypto/Digest";import*as te from"effect/crypto/SecureRandom";import*as ne from"effect/http/FetchHttpClient";import*as _ from"effect/http/HttpClient";import*as re from"effect/http/HttpClientRequest";import*as ie from"effect/process/ChildProcess";import*as ae from"effect/process/ChildProcessSpawner";import{createServer as oe}from"node:http";import*as se from"@effect/platform-node/NodeHttpServer";import*as v from"effect/Deferred";import*as y from"effect/Predicate";import*as ce from"effect/crypto/Mac";import*as le from"effect/http/HttpRouter";import*as ue from"effect/http/HttpServer";import*as de from"effect/http/HttpServerRequest";import*as b from"effect/http/HttpServerResponse";import*as fe from"effect/FileSystem";import*as pe from"effect/Path";import*as me from"effect/Stream";import*as x from"effect/String";import*as he from"@effect/platform-node/NodeCrypto";import*as ge from"@effect/platform-node/NodeServices";import*as _e from"effect/persistence/UserDirectories";import{Context as ve,Effect as S,Layer as C,Option as ye,Queue as be,Schema as w,Stream as xe}from"effect";import{FetchHttpClient as Se,HttpClient as Ce,HttpClientError as we,HttpClientRequest as Te}from"effect/http";import{HttpApi as Ee,HttpApiClient as De,HttpApiEndpoint as T,HttpApiGroup as Oe,HttpApiMiddleware as ke,HttpApiSchema as Ae,HttpApiSecurity as je,OpenApi as Me}from"effect/http-api";import*as E from"node:fs/promises";import*as Ne from"node:os";import*as D from"node:path";import*as Pe from"node:net";import{Duplex as Fe}from"node:stream";import*as Ie from"node:tls";import*as Le from"effect/net/NetAddress";import*as Re from"effect/ByteSize";import*as ze from"effect/ai/McpProtocol";import*as Be from"effect/ai/McpServer";import*as Ve from"effect/encoding/Hex";import*as He from"effect/http/HttpIncomingMessage";import*as O from"effect/Array";import*as k from"effect/Struct";import*as Ue from"effect/ai/McpClient";import*as We from"effect/http/HttpClientError";import*as Ge from"effect/ai/McpSchema";import*as Ke from"effect/ai/Toolkit";import*as A from"effect/ai/Tool";import*as j from"effect/SchemaGetter";import*as M from"effect/DateTime";import*as qe from"effect/Record";import*as Je from"effect/SchemaIssue";import*as Ye from"effect/ai/McpClientError";import*as Xe from"effect/Order";const Ze=`https://api.orbit.teamleader.eu`,Qe=`${Ze}/mcp`,$e=i.String.check(i.isMinLength(1)).pipe(i.RedactedFromValue);var et=class extends i.Class(`Session`)({clientId:i.String.check(i.isMinLength(1)),clientSecret:$e.pipe(i.optionalKey),accessToken:$e,refreshToken:$e.pipe(i.optionalKey),expiresAt:i.Finite.pipe(i.optionalKey)}){static update(e,t,n){let r=t.refreshToken??e.refreshToken;return this.make({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}})}static needsRefresh(e,t){return e.expiresAt===void 0||e.expiresAt<=t+6e4}},N=class extends i.TaggedError()(`OrbitAuthError`,{message:i.String}){};function tt(e){return e.clientSecret===void 0?{method:`none`,publicClient:!0}:{method:`client_secret_post`,secret:e.clientSecret.pipe(h.value,h.make)}}const nt={"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,"referrer-policy":`no-referrer`,"content-security-policy":`default-src 'none'`},rt=b.text(`Invalid callback.`,{status:400,headers:nt}),it=b.text(`Authorization received. Return to your terminal to complete login.`,{headers:nt}),at=b.text(`Authorization denied. Return to your terminal.`,{status:400,headers:nt});function ot(e,t){let n=e.searchParams.getAll(t);return n.length===1?n[0]:void 0}function st(e,t){let n=ot(e,`state`);if(n===void 0||e.pathname!==`/callback`)return;let r=new TextEncoder;if(!ce.timingSafeEqual(r.encode(t),r.encode(n)))return;if(e.searchParams.has(`error`))throw Error(`Orbit authorization was denied.`);let i=ot(e,`code`);return i===``?void 0:i}const ct=n.fn(`OrbitAuth.listenForLogin`)(function*(e){let t=yield*v.make(),r=yield*n.sync(oe),i=yield*se.make(()=>r,{port:0,host:`127.0.0.1`}).pipe(n.mapError(()=>N.make({message:`Could not bind OAuth callback.`})));if(!y.isTagged(i.address,`InetAddressV4`))return yield*N.make({message:`Could not bind OAuth callback.`});let a=`127.0.0.1:${i.address.port}`,o=`http://${a}/callback`,s=n.fn(`OrbitAuth.handleCallback`)(function*(){let r=yield*de.HttpServerRequest;return r.method!==`GET`||r.headers.host!==a||(yield*v.isDone(t))?rt:yield*n.try({try:()=>st(new URL(r.url,o),e),catch:()=>N.make({message:`Orbit authorization was denied.`})}).pipe(n.matchEffect({onFailure:e=>v.fail(t,e).pipe(n.map(e=>e?at:rt)),onSuccess:e=>e===void 0?n.succeed(rt):v.succeed(t,e).pipe(n.map(e=>e?it:rt))}))}),c=yield*le.toHttpEffect(le.add(`*`,`*`,s()));return yield*ue.serveEffect(c).pipe(n.provideService(ue.HttpServer,i)),yield*n.addFinalizer(()=>n.sync(()=>r.closeAllConnections())),{redirectUri:o,code:v.await(t).pipe(n.timeout(`3 minutes`),n.mapError(()=>N.make({message:`Login denied or timed out. Run tlo-mcp login again.`})))}}),lt=p.mergeAll(ge.layer,he.layerDigest,he.layerSecureRandom,_e.layer),ut=n.fn(`TloMcp.configDirectory`)(function*(e){let t=yield*fe.FileSystem,n=yield*pe.Path,r=yield*_e.UserDirectories,i=yield*r.config(`2digits`),a=yield*r.home,o=n.join(i,`tlo-mcp`),s=n.join(a,`.config`,`2digits`,`tlo-mcp`),c=yield*t.exists(n.join(o,e)),l=yield*t.exists(n.join(s,e));return!c&&l?s:o}),dt=et.pipe(i.fromJsonString),ft=i.decodeEffect(dt),pt=i.encodeEffect(dt),mt=`@2digits/tlo-mcp/orbit`,ht=[`-a`,`orbit`,`-s`,mt];var gt=class extends u.Service()(`@2digits/tlo-mcp/oauth/store/SessionStore`){};function _t(e){return`"${x.replaceAll(/["\\]/g,x.String.raw`\$&`)(e)}"`}function vt(e={}){return p.effect(gt,n.gen(function*(){let t=yield*fe.FileSystem,r=yield*pe.Path,i=yield*ae.ChildProcessSpawner,a=e.platform??process.platform,o=e.directory??(yield*ut(`session.json`)),s=r.join(o,`session.json`),c=r.join(o,`session.lock`),l=t.makeDirectory(o,{recursive:!0,mode:448}).pipe(n.andThen(t.chmod(o,448))),u=n.fn(`SessionStore.security`)(function*(e,t){let r=yield*i.spawn(ie.make(`/usr/bin/security`,e,{stdin:t===void 0?`ignore`:me.succeed(new TextEncoder().encode(t)),stderr:`ignore`}));return yield*n.all({output:r.stdout.pipe(me.decodeText(),me.mkString),exitCode:r.exitCode},{concurrency:`unbounded`})},n.scoped),d=n.fn(`SessionStore.load`)(function*(){if(a===`darwin`){let e=yield*u([`find-generic-password`,...ht,`-w`]);return e.exitCode===44?void 0:e.exitCode===0?yield*ft(x.trim(e.output)):yield*N.make({message:`Could not read macOS Keychain.`})}let e=yield*t.readFileString(s).pipe(n.catchReason(`PlatformError`,`NotFound`,()=>n.undefined));return e===void 0?void 0:yield*ft(e)},n.mapError(()=>N.make({message:`Could not read credentials. Run tlo-mcp login again.`}))),f=n.fn(`SessionStore.save`)(function*(e){let n=yield*pt(e);if(a===`darwin`){if((yield*u([`-q`,`-i`],`add-generic-password -U -a orbit -s ${_t(mt)} -w ${_t(n)}\n`)).exitCode!==0)return yield*N.make({message:`Could not save macOS Keychain credentials.`})}else{yield*l;let e=yield*t.makeTempDirectoryScoped({directory:o,prefix:`session-`}),i=r.join(e,`session.json`);yield*t.writeFileString(i,n,{mode:384}),yield*t.rename(i,s)}},n.scoped,n.mapError(()=>N.make({message:`Could not persist OAuth credentials. Run tlo-mcp login again.`}))),p=n.fn(`SessionStore.clear`)(function*(){if(a===`darwin`){let e=yield*u([`delete-generic-password`,...ht]);if(e.exitCode!==0&&e.exitCode!==44)return yield*N.make({message:`Could not remove Keychain credentials.`})}else yield*t.remove(s,{force:!0})},n.mapError(()=>N.make({message:`Could not remove OAuth credentials.`}))),m=n.fn(`SessionStore.lock`)(function*(){yield*l,yield*n.acquireRelease(t.writeFileString(c,process.pid.toString(),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>N.make({message:`OAuth credentials locked. Close other login/refresh processes. After a crash only, remove ${c}.`}))),()=>t.remove(c).pipe(n.orDie))},n.catchTag(`PlatformError`,()=>N.make({message:`Could not acquire OAuth credential lock. Check directory permissions.`})));return gt.of({load:d(),save:f,clear:p(),lock:m()})}))}const yt=vt(),bt=i.Struct({client_id:i.String.check(i.isMinLength(1)),client_secret:i.String.check(i.isMinLength(1)).pipe(i.RedactedFromValue,i.optionalKey)}),xt=i.is(N),St=ie.make({stdout:`ignore`,stderr:`ignore`,forceKillAfter:`1 second`});var Ct=class extends u.Service()(`@2digits/tlo-mcp/oauth/OrbitAuth`){};const wt=p.effect(Ct,n.gen(function*(){let e=yield*gt,t=yield*ee.Digest,r=yield*te.SecureRandom,a=yield*_.HttpClient,o=yield*ae.ChildProcessSpawner,u=yield*g.make(1),p=yield*n.fn(`OrbitAuth.discover`)(function*(){let e=yield*_.withScope(a).get(`${Ze}/.well-known/oauth-authorization-server`);if(e.status!==200)return yield*N.make({message:`Could not discover Orbit OAuth endpoints.`});let t=yield*e.json.pipe(n.flatMap(i.decodeUnknownEffect(s.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*N.make({message:`Unexpected Orbit endpoints; refusing to send credentials.`}):t},n.scoped,n.timeout(`15 seconds`),n.mapError(()=>N.make({message:`Invalid or unavailable Orbit OAuth metadata.`})))().pipe(n.cachedWithTTL(e=>f.isSuccess(e)?1/0:0)),ie=n.fn(`OrbitAuth.accessToken`)(function*(){let t=yield*e.load;if(t===void 0)return yield*N.make({message:`Not authenticated. Run tlo-mcp login first.`});let r=yield*l.currentTimeMillis;if(!et.needsRefresh(t,r))return t.accessToken;if(t.refreshToken===void 0)return t.expiresAt===void 0?t.accessToken:yield*N.make({message:`Orbit session expired without a refresh token. Run tlo-mcp login.`});let i=yield*p,a=yield*(yield*s.make({metadata:i,clientId:t.clientId,authentication:tt(t),timeoutMs:15e3})).refreshGrant({refreshToken:t.refreshToken,resources:[Qe]}).pipe(n.flatMap(s.tokens)),o=yield*l.currentTimeMillis,c=et.update(t,a,o);return yield*e.save(c),c.accessToken}),oe=n.fn(`OrbitAuth.register`)(function*(e){let t=yield*re.post(`${Ze}/oauth2/register`).pipe(re.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(a).execute));return t.status!==200&&t.status!==201?yield*N.make({message:`Orbit client registration failed (HTTP ${t.status}).`}):yield*t.json.pipe(n.flatMap(i.decodeUnknownEffect(bt)))},n.scoped,n.timeout(`15 seconds`)),se=n.fn(`OrbitAuth.openBrowser`)(function*(e){return yield*(yield*m.value(process.platform).pipe(m.when(`darwin`,()=>St`open ${e}`),m.when(`win32`,()=>St`rundll32 url.dll,FileProtocolHandler ${e}`),m.orElse(()=>St`xdg-open ${e}`))).exitCode},n.scoped,n.timeout(`5 seconds`),n.filterOrFail(d.equals(ae.ExitCode(0)),()=>N.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`)})))),v=n.fn(`OrbitAuth.login`)(function*(){let t=yield*p,r=yield*c.random(),i=yield*c.make(),a=yield*r.pipe(h.value,ct),o=yield*oe(a.redirectUri),u={clientId:o.client_id,...o.client_secret===void 0?{}:{clientSecret:o.client_secret}},d=yield*s.make({metadata:t,...u,authentication:tt(u),timeoutMs:15e3}),f=yield*d.authorizationUrl({redirectUri:a.redirectUri,scopes:[],state:r,codeChallenge:i.challenge,resources:[Qe]});yield*se(f);let m=yield*a.code,g=yield*d.codeGrant({code:h.make(m),redirectUri:a.redirectUri,pkceVerifier:i.verifier,resources:[Qe]}).pipe(n.flatMap(s.tokens)),ee=yield*l.currentTimeMillis;yield*e.save(et.update(u,g,ee)),yield*n.sync(()=>{process.stderr.write(`Orbit login complete.
|
|
3
|
+
`)})}),y=n.fn(`OrbitAuth.locked`)(function*(t){return yield*e.lock,yield*t},n.scoped,u.withPermit,n.provideService(_.HttpClient,a),n.provideService(ee.Digest,t),n.provideService(te.SecureRandom,r),n.provideService(ae.ChildProcessSpawner,o),n.provideService(ne.RequestInit,{redirect:`error`}),n.mapError(e=>xt(e)?e:N.make({message:`Orbit authentication unavailable. Check connectivity or run tlo-mcp login again.`})));return Ct.of({accessToken:y(ie()),login:y(v()),logout:y(e.clear)})})).pipe(p.provide(yt),p.provide(ne.layer)),Tt=8e3,Et=(e,t)=>t===`idempotent`?e===429||e>=500&&e<=599:[429,503,521,522,523,525].includes(e),Dt=(e,t)=>{let n=t?.trim();if(n&&/^\d+$/.test(n)){let e=Math.min(Number(n)*1e3,Tt);return[e,e]}let r=Math.min(250*2**Math.min(e,16),Tt);return[r/2,r]},Ot={520:`the server returned an unknown error`,521:`the server refused the connection`,522:`the connection to the server timed out`,523:`the server is unreachable`,524:`the server did not answer in time`,525:`the SSL handshake with the server failed`,526:`the server's certificate is invalid`,527:`the connection to the server failed`},kt=e=>Ot[e],At=(e,t)=>{let n=kt(e);if(n)return`Cloudflare ${e}: ${n}`;let r=t.trim();return r?Array.from(r).slice(0,200).join(``):`HTTP ${e}`},jt=w.String.pipe(w.brand(`CSR.Raw`)),Mt=w.String.pipe(w.brand(`Hostname`));function Nt(){return(e,t)=>{class n{static makeUnsafe(e){return e}}return Object.setPrototypeOf(n,t),n}}var Pt=class extends Nt()(`CertificateID`,w.String){};w.String.pipe(w.brand(`ChallengeToken`));var Ft=class extends w.Class(`Certificate/StateChallenge`)({type:w.Literal(`challenge`),token:w.String,key:w.String}){},It=class extends w.Class(`Certificate/StateIssuing`)({type:w.Literal(`issuing`)}){},Lt=class extends w.Class(`Certificate/StateReady`)({type:w.Literal(`ready`),certificate:w.String,chain:w.String,expiry:w.String}){},Rt=class extends w.Class(`Certificate/StateFailed`)({type:w.Literal(`failed`),reason:w.String}){};const zt=w.Union([Ft,It,Lt,Rt]);var Bt=class extends w.Class(`Certificate`)({id:Pt,state:zt}){},P=class extends Nt()(`TunnelID`,w.String){};const Vt=w.String.pipe(w.brand(`TunnelToken`));w.TaggedError()(`NotFound`,{tunnelID:P}),w.TaggedError()(`NoCertificate`,{tunnelID:P}),w.TaggedError()(`CertificateNotReady`,{tunnelID:P,currentState:w.String}),w.TaggedError()(`InvalidHostname`,{provided:Mt,expected:Mt});const Ht=w.Literals([`offline`,`online`]);var Ut=class extends w.Class(`Tunnel/Info`)({id:P,hostname:Mt,state:Ht,certificateID:Pt.pipe(w.optional)}){},Wt=`0.6.2`,Gt=class extends w.TaggedError()(`InvalidRequestError`,{message:w.String},{httpApiStatus:400}){},Kt=class extends w.TaggedError()(`UnauthorizedError`,{message:w.String},{httpApiStatus:401}){},qt=class extends w.TaggedError()(`TunnelNotFoundError`,{tunnelID:w.String,message:w.String},{httpApiStatus:404}){},Jt=class extends w.TaggedError()(`CertificateNotFoundError`,{tunnelID:w.String,message:w.String},{httpApiStatus:404}){},Yt=class extends w.TaggedError()(`InvalidHostnameError`,{provided:w.String,expected:w.String,message:w.String},{httpApiStatus:400}){},Xt=class extends w.TaggedError()(`HostnameUnavailableError`,{name:w.String,message:w.String},{httpApiStatus:409}){},Zt=class extends w.TaggedError()(`CertificateInProgressError`,{tunnelID:w.String,message:w.String},{httpApiStatus:409}){},Qt=class extends w.TaggedError()(`ServiceUnavailableError`,{message:w.String},{httpApiStatus:503}){};ve.Service()(`@opentunnel/protocol/OpenTunnelAuthorizationToken`);var $t=class extends ke.Service()(`@opentunnel/protocol/OpenTunnelAuthorization`,{security:{bearer:je.bearer},error:Kt}){};const en=w.Struct({name:w.String.pipe(w.optional)}),tn=w.Struct({tunnel:Ut,token:Vt}).pipe(Ae.status(201)),nn=Oe.make(`tunnel`).add(T.post(`tunnel.create`,`/api/tunnel`,{payload:en,success:tn,error:[Gt,Xt,Qt]})).add(T.get(`tunnel.get`,`/api/tunnel/:id`,{params:w.Struct({id:P}),success:Ut,error:[qt,Qt]}).middleware($t)).add(T.post(`tunnel.bindCertificate`,`/api/tunnel/:id/certificate`,{params:w.Struct({id:P}),payload:w.Struct({csr:jt}),success:Bt.pipe(Ae.status(202)),error:[Gt,Yt,qt,Zt,Qt]}).middleware($t)).add(T.get(`tunnel.getCertificate`,`/api/tunnel/:id/certificate`,{params:w.Struct({id:P}),success:Bt,error:[qt,Jt,Qt]}).middleware($t)).add(T.delete(`tunnel.remove`,`/api/tunnel/:id`,{params:w.Struct({id:P}),success:Ae.NoContent,error:[qt,Qt]}).middleware($t)).add(T.get(`tunnel.connect`,`/api/tunnel/:id/connect`,{params:w.Struct({id:P}),success:w.Boolean,error:[qt]}).annotateMerge(Me.annotations({summary:`Connect a bridge WebSocket`,description:`This endpoint upgrades to the opentunnel WebSocket protocol.`}))).annotateMerge(Me.annotations({title:`tunnel`})),rn=Ee.make(`opentunnel`).add(nn).annotateMerge(Me.annotations({title:`OpenTunnel API`,version:`0.1.0`,description:`Create and manage blind TLS tunnels.`})),an=`opentunnel-sdk/${Wt}`,on=/* @__PURE__ */ new Set([`ConnectionRefused`,`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`FailedToOpenSocket`,`UND_ERR_CONNECT_TIMEOUT`]),sn=e=>{if(typeof e!=`object`||!e)return;let{code:t,cause:n}=e;return typeof t==`string`?t:sn(n)},cn=e=>e.method===`GET`||e.method===`POST`&&e.url.endsWith(`/certificate`)?`idempotent`:`once`,ln=(e,t)=>we.isHttpClientError(e)&&e.reason._tag===`TransportError`&&(t===`idempotent`||on.has(sn(e.reason.cause)??``)),un=e=>Ce.transform(e,(e,t)=>{let n=cn(t),r=(e,t)=>{let[n,r]=Dt(e,t);return S.sleep(n+Math.random()*(r-n))},i=t=>S.matchEffect(e,{onFailure:e=>t<6&&ln(e,n)?S.andThen(r(t),()=>i(t+1)):S.fail(e),onSuccess:e=>t<6&&Et(e.status,n)?S.andThen(r(t,e.headers[`retry-after`]),()=>i(t+1)):S.succeed(e)});return i(0)});var dn=class e extends ve.Service()(`@opentunnel/client/OpenTunnelApiClient`){static layer(t){return C.effect(e,S.gen(function*(){let e=(yield*Ce.HttpClient).pipe(Ce.mapRequest(Te.setHeader(`user-agent`,an)),un);return{client:yield*De.makeWith(rn,{baseUrl:t.api,httpClient:e}),authorized:n=>De.makeWith(rn,{baseUrl:t.api,httpClient:e.pipe(Ce.mapRequest(Te.bearerToken(n)))})}})).pipe(C.provide(t.fetch?Se.layer.pipe(C.provide(C.succeed(Se.Fetch,t.fetch))):Se.layer))}};const F=(e,...t)=>{let n=fn(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 fn([new Uint8Array([e,...r]),n])},fn=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},I=(...e)=>F(48,...e),pn=(...e)=>F(49,...e),mn=e=>F(12,new TextEncoder().encode(e)),hn=e=>F(130,new TextEncoder().encode(e)),gn=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 F(6,new Uint8Array(i))},_n=e=>{let t=0;for(;t<e.length-1&&e[t]===0;)t++;let n=e.subarray(t);return F(2,n[0]&128?fn([new Uint8Array([0]),n]):n)};async function vn(e,t){let n=new Uint8Array(await crypto.subtle.exportKey(`spki`,t.publicKey)),r=I(F(2,new Uint8Array([0])),I(pn(I(gn(`2.5.4.3`),mn(e)))),n,F(160,I(gn(`1.2.840.113549.1.9.14`),pn(I(I(gn(`2.5.29.17`),F(4,I(hn(e),hn(`*.${e}`))))))))),i=new Uint8Array(await crypto.subtle.sign({name:`ECDSA`,hash:`SHA-256`},t.privateKey,r)),a=I(_n(i.subarray(0,32)),_n(i.subarray(32))),o=I(r,I(gn(`1.2.840.10045.4.3.2`)),F(3,new Uint8Array([0]),a));return`-----BEGIN CERTIFICATE REQUEST-----\n${Buffer.from(o).toString(`base64`).replace(/.{1,64}/g,`$&
|
|
4
|
+
`)}-----END CERTIFICATE REQUEST-----`}var yn=class extends w.TaggedError()(`OpenTunnelClientError`,{message:w.String,code:w.optional(w.String),cause:w.optional(w.Defect())}){},L=class extends w.TaggedError()(`OpenTunnelStorageError`,{message:w.String,cause:w.optional(w.Defect())}){};function bn(e={}){let t=e.env??process.env,n=e.home??Ne.homedir(),r=t.XDG_DATA_HOME??D.join(n,`.local`,`share`),i=D.join(r,`opentunnel`),a=e=>D.join(i,e),o=e=>S.tryPromise({try:()=>E.readFile(e,`utf8`),catch:e=>e}).pipe(S.catch(t=>S.gen(function*(){if(!(typeof t==`object`&&t&&`code`in t&&t.code===`ENOENT`))return yield*new L({message:`Failed to read ${e}`,cause:t})}))),s=S.fn(`OpenTunnelStorage.profiles`)(function*(){return(yield*S.tryPromise({try:()=>E.readdir(i,{withFileTypes:!0}),catch:e=>e}).pipe(S.catch(e=>S.gen(function*(){return typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`?[]:yield*new L({message:`Failed to list ${i}`,cause:e})})))).filter(e=>e.isDirectory()).map(e=>e.name).sort()}),c=S.fn(`OpenTunnelStorage.load`)(function*(e){let t=a(e),n=yield*o(D.join(t,`tunnel.json`));if(!n)return;let[r,i,s,c]=yield*S.all([o(D.join(t,`token`)),o(D.join(t,`private-key.pem`)),o(D.join(t,`certificate.pem`)),o(D.join(t,`chain.pem`))]);if(!r||!i||!s||c===void 0)return yield*new L({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=S.fn(`OpenTunnelStorage.loadPending`)(function*(e){let t=a(e),n=yield*o(D.join(t,`pending.json`));if(!n)return;let[r,i]=yield*S.all([o(D.join(t,`token`)),o(D.join(t,`private-key.pem`))]);if(!r||!i)return yield*new L({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)=>S.tryPromise({try:async()=>{let n=a(e);await E.mkdir(n,{recursive:!0,mode:448}),await Promise.all([E.writeFile(D.join(n,`pending.json`),JSON.stringify({id:t.id,hostname:t.hostname,csr:t.csr},null,2),{mode:384}),E.writeFile(D.join(n,`token`),`${t.token}\n`,{mode:384}),E.writeFile(D.join(n,`private-key.pem`),t.privateKey,{mode:384})])},catch:t=>new L({message:`Failed to save pending tunnel identity for ${e}`,cause:t})}),save:(e,t)=>S.tryPromise({try:async()=>{let n=a(e);await E.mkdir(n,{recursive:!0,mode:448}),await Promise.all([E.writeFile(D.join(n,`tunnel.json`),JSON.stringify({id:t.id,hostname:t.hostname,certificateExpiry:t.certificateExpiry.toISOString()},null,2),{mode:384}),E.writeFile(D.join(n,`token`),`${t.token}\n`,{mode:384}),E.writeFile(D.join(n,`private-key.pem`),t.privateKey,{mode:384}),E.writeFile(D.join(n,`certificate.pem`),t.certificate,{mode:384}),E.writeFile(D.join(n,`chain.pem`),t.chain,{mode:384})]),await E.rm(D.join(n,`pending.json`),{force:!0})},catch:t=>new L({message:`Failed to save tunnel identity for ${e}`,cause:t})}),remove:e=>S.tryPromise({try:()=>E.rm(a(e),{recursive:!0,force:!0}),catch:t=>new L({message:`Failed to remove tunnel identity for ${e}`,cause:t})}),list:()=>s().pipe(S.flatMap(e=>S.forEach(e,e=>c(e).pipe(S.map(t=>t?{profile:e,tunnel:t}:void 0)))),S.map(e=>e.filter(e=>e!==void 0)))}}const xn=/* @__PURE__ */ new Set([`http:`,`https:`]),Sn=(e,t)=>{let n=e.trim(),r;try{r=new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`http://${n}`)}catch{throw Error(`${t} is not a valid proxy URL`)}if(!xn.has(r.protocol))throw Error(`${t} uses an unsupported proxy scheme '${r.protocol.slice(0,-1)}': OpenTunnel connects through http:// and https:// proxies`);return r},Cn=e=>e.protocol===`https:`||e.protocol===`wss:`,wn=(e,t)=>{let[n,r]=e.split(`/`,2),i=Pe.isIP(n);if(i===0||Pe.isIP(t)!==i)return!1;let a=i===4?`ipv4`:`ipv6`,o=new Pe.BlockList;if(r===void 0)o.addAddress(n,a);else if(/^\d+$/.test(r))o.addSubnet(n,Number(r),a);else return!1;return o.check(t,a)},Tn=(e,t)=>{let n=e.hostname.toLowerCase().replace(/^\[(.*)\]$/,`$1`),r=e.port===``?Cn(e)?443:80:Number(e.port);for(let e of t.toLowerCase().split(/[\s,]+/)){if(e===``)continue;if(e===`*`)return!0;let t=e,i,a=/^\[([^\]]+)\](?::(\d+))?$/.exec(e);if(a)t=a[1],i=a[2]===void 0?void 0:Number(a[2]);else{let n=e.split(`:`);n.length===2&&/^\d+$/.test(n[1])&&(t=n[0],i=Number(n[1]))}if(i!==void 0&&i!==r)continue;if(wn(t,n))return!0;let o=t.replace(/^\*?\./,``);if(o!==``&&(n===o||n.endsWith(`.${o}`)))return!0}return!1},En=(e,t)=>{let n=(Cn(e)?[`HTTPS_PROXY`,`https_proxy`,`ALL_PROXY`,`all_proxy`]:[`HTTP_PROXY`,`http_proxy`,`ALL_PROXY`,`all_proxy`]).find(e=>t[e]?.trim());if(n!==void 0&&!Tn(e,t.NO_PROXY||t.no_proxy||``))return Sn(t[n],n)},Dn=(e,t)=>new WebSocket(e,t),On=(e,t)=>((n,r)=>e(n,{...r,...t})),kn=()=>{try{return e(import.meta.url)(`undici`)}catch(e){throw Error(`The proxy option needs the 'undici' package on Node: install it next to @opentunnel/client, or let Node use HTTPS_PROXY with NODE_USE_ENV_PROXY=1`,{cause:e})}},An=()=>`Bun`in globalThis?`bun`:`Deno`in globalThis?`deno`:`node`,jn=(e,t=process.env)=>{let n=e===void 0?void 0:Sn(e,`The proxy option`).href;switch(An()){case`bun`:return{...n===void 0?{}:{fetch:On(globalThis.fetch,{proxy:n})},webSocket:(e,r,i)=>{let a=n??En(e,t)?.href;return Dn(e,{protocols:r,headers:i,...a?{proxy:a}:{}})}};case`deno`:{if(n===void 0)break;let e=globalThis.Deno.createHttpClient({proxy:{url:n}});return{fetch:On(globalThis.fetch,{client:e}),webSocket:(t,n,r)=>Dn(t,{protocols:n,headers:r,client:e})}}case`node`:{if(n===void 0)break;let e=kn(),t=new e.ProxyAgent({uri:n,proxyTunnel:!0});return{fetch:On(e.fetch,{dispatcher:t}),webSocket:(n,r,i)=>new e.WebSocket(n,{protocols:r,headers:i,dispatcher:t})}}}return{webSocket:(e,t,n)=>Dn(e,{protocols:t,headers:n})}},Mn=w.Int.check(w.isBetween({minimum:0,maximum:4294967295}));var Nn=class extends w.Class(`BridgeProtocol/ClientInfo`)({version:w.String,max_conns:w.Number}){},Pn=class extends w.Class(`BridgeProtocol/AttachMessage`)({type:w.Literal(`attach`),token:w.String,transport:w.Literal(`ws`),client:Nn,routes:w.Array(w.String).pipe(w.optional)}){},Fn=class extends w.Class(`BridgeProtocol/AttachedMessage`)({type:w.Literal(`attached`),session:w.String,routes:w.Array(w.String),heartbeat_ms:w.Number,idle_timeout_ms:w.Number}){},In=class extends w.Class(`BridgeProtocol/AttachErrorMessage`)({type:w.Literal(`attach_error`),code:w.String}){},Ln=class extends w.Class(`BridgeProtocol/PingMessage`)({type:w.Literal(`ping`),time_sent:w.Number}){},Rn=class extends w.Class(`BridgeProtocol/PongMessage`)({type:w.Literal(`pong`),time_sent:w.Number}){},zn=class extends w.Class(`BridgeProtocol/DrainMessage`)({type:w.Literal(`drain`),reason:w.String}){},Bn=class extends w.Class(`BridgeProtocol/OpenMessage`)({type:w.Literal(`open`),conn:Mn,peer:w.String,sni:w.String,alpn:w.String}){},Vn=class extends w.Class(`BridgeProtocol/EndMessage`)({type:w.Literal(`end`),conn:Mn}){},Hn=class extends w.Class(`BridgeProtocol/ResetMessage`)({type:w.Literal(`reset`),conn:Mn,code:w.String}){};w.Union([Pn,Ln,Rn,zn,Vn,Hn]);const Un=w.Union([Fn,In,Ln,Rn,zn,Bn,Vn,Hn]),Wn=w.decodeUnknownOption(Un);function Gn(e){try{return Wn(JSON.parse(e))}catch{return ye.none()}}w.Union([Pn,Fn,In,Ln,Rn,zn,Bn,Vn,Hn]);const R={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`},Kn={HEARTBEAT_MS:15e3,IDLE_TIMEOUT_MS:45e3,CONNECT_TIMEOUT_MS:1e4,RECONNECT_BACKOFF_MIN_MS:250,RECONNECT_BACKOFF_MAX_MS:3e4},z={CONN_ID_SIZE:4,MAX_PAYLOAD_SIZE:32768};function qn(e){return e.length<z.CONN_ID_SIZE?null:{conn:new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!1),payload:e.slice(z.CONN_ID_SIZE)}}function Jn(e,t){let n=new Uint8Array(z.CONN_ID_SIZE+t.length);return new DataView(n.buffer).setUint32(0,e,!1),n.set(t,z.CONN_ID_SIZE),n}const Yn=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,Xn=e=>e===`@`||Yn.test(e),Zn=(e,t)=>e===`@`?t:`${e}.${t}`,Qn=(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 Yn.test(a)?a:void 0},$n=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}},er=e=>e===`v1`||e===`v2`,tr=Uint8Array.of(13,10,13,10,0,13,10,81,85,73,84,10),nr=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},rr=(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=nr(i);if(!e)return;n.push(e[0]<<8|e[1],e[2]<<8|e[3])}else{if(!/^[0-9A-Fa-f]{1,4}$/.test(i))return;n.push(Number.parseInt(i,16))}return n},ir=e=>{let t=e.indexOf(`::`),n;if(t===-1){if(n=rr(e,!0),n?.length!==8)return}else{if(e.indexOf(`::`,t+1)!==-1)return;let r=rr(e.slice(0,t),!1),i=rr(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},ar=e=>{if(!/^[0-9]{1,5}$/.test(e))return;let t=Number(e);return t<=65535?t:void 0},or=e=>e.subarray(0,10).every(e=>e===0)&&e[10]===255&&e[11]===255,sr=(e,t)=>e.length===16&&or(e)?{family:4,bytes:e.slice(12),port:t}:e.length===4?{family:4,bytes:e,port:t}:{family:6,bytes:e,port:t},cr=e=>{let t=nr(e)??ir(e);if(t)return sr(t,0);if(e.startsWith(`[`)){let t=e.indexOf(`]:`);if(t===-1)return;let n=ir(e.slice(1,t)),r=ar(e.slice(t+2));return n&&r!==void 0?sr(n,r):void 0}let n=e.lastIndexOf(`:`);if(n===-1)return;let r=nr(e.slice(0,n)),i=ar(e.slice(n+1));return r&&i!==void 0?sr(r,i):void 0},lr=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))}`},ur=new TextEncoder,dr=(e,t,n)=>{let r=cr(t);return e===`v1`?fr(r):pr(r,n)},fr=e=>{if(!e)return ur.encode(`PROXY UNKNOWN\r
|
|
5
|
+
`);let[t,n]=e.family===4?[`TCP4`,`0.0.0.0`]:[`TCP6`,`::`];return ur.encode(`PROXY ${t} ${lr(e)} ${n} ${e.port} 443\r\n`)},pr=(e,t)=>{let n=ur.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(tr,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},mr=e=>Xn(e),hr=(e,t)=>`https://${Zn(e,t)}`,gr=(e,t)=>Object.fromEntries(Object.keys(e).map(e=>[e,hr(e,t)]));var _r=class extends Error{code;constructor(e){super(e===R.ROUTE_CONFLICT?`Bridge attach failed: ${e} (another client holds a route)`:`Bridge attach failed: ${e}`),this.code=e}};const vr=/* @__PURE__ */ new Set([R.BAD_TOKEN,R.CERT_NOT_READY]),yr=/* @__PURE__ */ new Set([`target`,`proxyProtocol`]),br=(e,t)=>{if(!mr(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(!yr.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(!er(i.proxyProtocol))throw Error(`Invalid proxyProtocol '${String(i.proxyProtocol)}' for route '${e}': use "v1" or "v2"`);r=i.proxyProtocol}}let i=typeof n==`string`?$n(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}},xr=e=>{for(let[t,n]of Object.entries(e))br(t,n)},Sr=e=>new Map(Object.entries(e).map(([e,t])=>[e,br(e,t)])),Cr=e=>Ie.createSecureContext({key:e.privateKey,cert:`${e.certificate}\n${e.chain}`}),wr=(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])},Tr=e=>{let t=Math.min(Kn.RECONNECT_BACKOFF_MIN_MS*2**Math.min(e,16),Kn.RECONNECT_BACKOFF_MAX_MS);return Math.round(t/2+t/2*Math.random())};var Er=class{options;routes;resolved;identity;secureContext;refreshTimer;refreshAbort=new AbortController;transport;session;shutdown=!1;wake;status;ready;closed;constructor(e){this.options=e,this.resolved=Sr(e.routes),this.transport=e.transport??jn(),this.routes={...e.routes},this.identity=e.identity,this.secureContext=Cr(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(this.transport.fetch??fetch)(e,{headers:{authorization:`Bearer ${this.identity.token}`},signal:this.refreshAbort.signal}),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=Cr(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}}}getUrls(){return gr(this.routes,this.identity.hostname)}setRoutes(e){let t=Sr(e),n=this.routes;this.resolved=t,this.routes={...e},this.status.routes=this.routes,wr(n,this.routes)||this.session?.end({type:`routes-changed`}),this.wake?.()}close(){return this.shutdown=!0,clearTimeout(this.refreshTimer),this.refreshAbort.abort(),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 Dr(this.options,this.transport,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=Tr(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}}},Dr=class{options;transport;routes;secureContext;hooks;socket;finish;channels=/* @__PURE__ */ new Map;drainWaiters=[];drainTimer;heartbeat;attachTimeout;lastReceived=Date.now();attached=!1;constructor(e,t,n,r,i){this.options=e,this.transport=t,this.routes=n,this.secureContext=r,this.hooks=i}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;try{n=this.transport.webSocket(t,[`opentunnel`],{"user-agent":an})}catch(e){this.end({type:`fatal`,error:e instanceof Error?e:Error(String(e))});return}n.binaryType=`arraybuffer`,this.socket=n,this.attachTimeout=setTimeout(()=>this.end({type:`retry`,error:`bridge attach timed out`,attached:!1}),Kn.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=Gn(e);if(ye.isNone(t))return;let n=t.value;if(this.attached)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})}else 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(()=>{Date.now()-this.lastReceived>t?this.end({type:`retry`,error:`bridge idle timeout`,attached:!0}):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 if(n.type===`attach_error`){let e=n.code===R.ROUTE_CONFLICT;e&&this.hooks.emit({type:`route-conflict`,routes:Object.keys(this.routes).sort()}),this.end(vr.has(n.code)||e&&this.options.onRouteConflict===`fail`?{type:`fatal`,error:new _r(n.code)}:{type:`retry`,error:`attach failed: ${n.code}`,attached:!1})}}onData(e){let t=qn(e);t&&this.channels.get(t.conn)?.push(t.payload)}open(e,t,n){let r=Qn(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:R.UNKNOWN_ROUTE});return}if(this.channels.size>=256){this.sendControl({type:`reset`,conn:e,code:R.TOO_MANY_CONNECTIONS});return}let a=i.proxyProtocol===void 0?void 0:dr(i.proxyProtocol,n,t),o=new Or(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`));else{for(let n=0;n<t.byteLength;n+=z.MAX_PAYLOAD_SIZE){let i=t.subarray(n,n+z.MAX_PAYLOAD_SIZE);r.send(Jn(e,i))}r.bufferedAmount<1048576?n():(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))}}},Or=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 Fe({allowHalfOpen:!0,read(){},write:(t,n,r)=>a.sendData(e,t,r),final:t=>{a.sendControl({type:`end`,conn:e}),t()}}),this.tls=new Ie.TLSSocket(this.raw,{isServer:!0,secureContext:i}),this.tls.on(`secure`,()=>{let e=Pe.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?R.UPSTREAM_CONNECT_FAILED:R.UPSTREAM_IO_ERROR,!0,t.message)),this.tls.pipe(e),e.pipe(this.tls)}),this.tls.on(`error`,e=>this.destroy(R.UPSTREAM_IO_ERROR,!0,e.message)),this.tls.on(`close`,()=>this.finish(void 0))}push(e){this.done||(this.raw.readableLength>8388608?this.destroy(R.UPSTREAM_IO_ERROR,!0,`local connection stalled`):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 B=e=>e?.profile??`default`,kr=e=>{if(we.isHttpClientError(e)){let t=e.response;if(!t)return e.message;let n=At(t.status,``);return n.startsWith(`HTTP `)?n:`${n} (HTTP ${t.status})`}if(typeof e==`object`&&e){let{_tag:t,message:n}=e;if(typeof t==`string`&&typeof n==`string`)return`${t}: ${n}`}return e instanceof Error?e.message:void 0},V=(e,t)=>{let n=kr(t);return new yn({message:n?`${e}: ${n}`:e,cause:t})},Ar=(e,t)=>{let n=kr(t);return new yn({message:n?`${e}: ${n}`:e,...t instanceof _r?{code:t.code}:{},cause:t})},jr=e=>we.isHttpClientError(e)&&(e.reason._tag===`TransportError`||e.response!==void 0&&Et(e.response.status,`idempotent`)),Mr=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`},Nr=e=>{try{return jn(e)}catch(e){throw new yn({message:e instanceof Error?e.message:String(e),cause:e})}};var Pr=class e extends ve.Service()(`@opentunnel/client/OpenTunnelClient`){static layer(t={}){let n=t.storage??bn(),r=Nr(t.proxy),i=t.api??(process.env.OPENTUNNEL_API||`https://opentunnel.xyz`);return C.effect(e,S.gen(function*(){let e=yield*dn,t=new URL(i),a=S.fn(`OpenTunnelClient.tunnel.get`)(function*(e){return yield*n.load(B(e))}),o=S.fn(`OpenTunnelClient.tunnel.completePending`)(function*(t){let r=yield*e.authorized(Vt.make(t.pending.token));yield*S.sync(()=>t.onProgress?.(`requesting-certificate`)),yield*r.tunnel[`tunnel.bindCertificate`]({params:{id:P.make(t.pending.id)},payload:{csr:t.pending.csr}}).pipe(S.catchTag(`CertificateInProgressError`,()=>S.void),S.mapError(e=>V(`Failed to start certificate issuance`,e)));let i=yield*S.gen(function*(){for(;;){yield*S.sync(()=>t.onProgress?.(`waiting-certificate`));let e=yield*r.tunnel[`tunnel.getCertificate`]({params:{id:P.make(t.pending.id)}}).pipe(S.mapError(e=>V(`Failed to read certificate`,e)));if(e.state.type===`ready`)return e.state;if(e.state.type===`failed`)return yield*new yn({message:`Certificate issuance failed: ${e.state.reason}`});yield*S.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*S.sync(()=>t.onProgress?.(`saving-identity`)),yield*n.save(t.profile,a),yield*S.sync(()=>t.onProgress?.(`ready`)),a}),s=S.fn(`OpenTunnelClient.tunnel.provision`)(function*(e){yield*S.sync(()=>e.onProgress?.(`generating-key`));let t=yield*S.tryPromise({try:()=>crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!0,[`sign`,`verify`]),catch:e=>V(`Failed to generate certificate key`,e)});yield*S.sync(()=>e.onProgress?.(`generating-csr`));let r=yield*S.tryPromise({try:()=>vn(e.hostname,t),catch:e=>V(`Failed to generate certificate request`,e)}),i=yield*S.tryPromise({try:()=>crypto.subtle.exportKey(`pkcs8`,t.privateKey),catch:e=>V(`Failed to export certificate key`,e)}),a={id:String(e.id),hostname:e.hostname,token:e.token,privateKey:Mr(i),csr:r};return yield*n.savePending(e.profile,a),yield*o({profile:e.profile,pending:a,onProgress:e.onProgress})}),c=S.fn(`OpenTunnelClient.tunnel.create`)(function*(t){let r=B(t);if(yield*n.load(r))return yield*new yn({message:`Profile '${r}' already has a tunnel`});let i=yield*n.loadPending(r);if(i)return yield*S.sync(()=>t?.onProgress?.(`resuming-certificate`)),yield*o({profile:r,pending:i,onProgress:t?.onProgress});yield*S.sync(()=>t?.onProgress?.(`creating-tunnel`));let a=yield*e.client.tunnel[`tunnel.create`]({payload:{}}).pipe(S.mapError(e=>V(`Failed to create tunnel`,e)));return yield*s({profile:r,id:a.tunnel.id,hostname:String(a.tunnel.hostname),token:a.token,onProgress:t?.onProgress})}),l=S.fn(`OpenTunnelClient.tunnel.ensure`)(function*(t){let r=yield*a(t);if(!r)return yield*c(t);let i=e=>S.sync(()=>t?.onProgress?.(e));yield*i(`checking-certificate`);let o=yield*(yield*e.authorized(Vt.make(r.token))).tunnel[`tunnel.getCertificate`]({params:{id:P.make(r.id)}}).pipe(S.catchIf(e=>jr(e)&&r.certificateExpiry.getTime()>Date.now(),()=>S.succeed(void 0)),S.mapError(e=>V(`Failed to read certificate`,e)));if(!o)return yield*i(`ready`),r;let l=o.state;if(l.type===`ready`&&l.certificate!==r.certificate){let e={...r,certificate:l.certificate,chain:l.chain,certificateExpiry:new Date(l.expiry)};return yield*i(`saving-identity`),yield*n.save(B(t),e),yield*i(`ready`),e}return l.type===`failed`?yield*s({profile:B(t),id:P.make(r.id),hostname:r.hostname,token:Vt.make(r.token),onProgress:t?.onProgress}):(yield*i(`ready`),r)}),u=S.fn(`OpenTunnelClient.tunnel.pending`)(function*(e){let t=yield*n.loadPending(B(e));return t?{id:t.id,hostname:t.hostname}:void 0}),d=S.fn(`OpenTunnelClient.tunnel.resume`)(function*(e){let t=B(e),r=yield*n.loadPending(t);if(r)return yield*S.sync(()=>e?.onProgress?.(`resuming-certificate`)),yield*o({profile:t,pending:r,onProgress:e?.onProgress})});return{profile:{list:n.profiles},tunnel:{list:n.list,get:a,pending:u,resume:d,create:c,ensure:l,remove:S.fn(`OpenTunnelClient.tunnel.remove`)(function*(t){let r=B(t),i=yield*n.load(r);i&&(yield*(yield*e.authorized(Vt.make(i.token))).tunnel[`tunnel.remove`]({params:{id:P.make(i.id)}}).pipe(S.mapError(e=>V(`Failed to remove tunnel`,e))),yield*n.remove(r))}),connect:S.fn(`OpenTunnelClient.tunnel.connect`)(function*(e){yield*S.try({try:()=>xr(e.routes),catch:e=>V(e instanceof Error?e.message:`Invalid routes`,e)});let i=yield*l({profile:e.profile}),a=yield*be.unbounded(),o=yield*S.acquireRelease(S.sync(()=>new Er({api:t,identity:i,routes:e.routes,onRouteConflict:e.onRouteConflict,transport:r,onEvent:t=>{e.onEvent?.(t),be.offerUnsafe(a,t),t.type===`stopped`&&be.endUnsafe(a)},onRenewed:t=>{S.runFork(n.save(B(e),t).pipe(S.ignore))}})),e=>S.promise(()=>e.close()).pipe(S.andThen(be.end(a))));return yield*S.tryPromise({try:()=>o.ready,catch:e=>Ar(`Failed to connect tunnel`,e)}).pipe(S.onInterrupt(()=>S.promise(()=>o.close()))),{tunnel:i,events:xe.fromQueue(a),status:S.sync(()=>o.getStatus()),urls:S.sync(()=>o.getUrls()),setRoutes:e=>S.try({try:()=>o.setRoutes(e),catch:e=>V(e instanceof Error?e.message:`Invalid routes`,e)}),closed:S.tryPromise({try:()=>o.closed,catch:e=>Ar(`Tunnel stopped`,e)}),close:S.promise(()=>o.close())}})}}})).pipe(C.provide(dn.layer({api:i,...r.fetch?{fetch:r.fetch}:{}})))}};const Fr=/* @__PURE__ */ `GetTimesheetWeek.GetTimesheetStatus.ListTimeEntries.GetTimeEntry.CreateTimeEntry.UpdateTimeEntry.MoveTimeEntry.SplitTimeEntry.DeleteTimeEntry.ConfirmPlannedEntry.SubmitTimesheet.GetRunningTimer.StartTimer.StopTimer.ListMyTasks.SearchProjectItems.ListPlannableTasks.ListProjects.GetProject.GetProjectOpenItems.ListRates.AddProjectTask.ListPlannedEntries.GetPlannedEntry.GetPlannerBoard.ListAbsences.ListReservations.FindFreeCapacity.ListTickets.GetTicket.GetTicketDetail.ListTicketComments.AddInternalComment.ReplyToTicket.CloseTicket.ListBoards.ListBoardLists.ListTodos.GetTodo.GetTodoDetail.MoveTodo.ListMessages.AddMessage.ListUsers.SearchCrm`.split(`.`);var Ir=class extends u.Service()(`@2digits/tlo-mcp/mcp/OrbitClient`){};const Lr=p.effect(_.HttpClient,n.gen(function*(){let e=yield*Ct;return yield*e.accessToken,(yield*_.HttpClient).pipe(_.mapRequestEffect(t=>e.accessToken.pipe(n.mapBoth({onSuccess:e=>re.bearerToken(t,e),onFailure:e=>new We.HttpClientError({reason:new We.TransportError({request:t,cause:e,description:e.message})})}))),_.transform(n.provideService(ne.RequestInit,{redirect:`error`})))})).pipe(p.provide(ne.layer)),Rr=p.effect(Ir,n.gen(function*(){let e=yield*Ue.McpClient,t=yield*e.listTools(),r=O.difference(Fr,O.map(t,k.get(`name`)));return O.isReadonlyArrayNonEmpty(r)&&(yield*n.logWarning(`Orbit no longer offers these exposed tools: ${O.join(r,`, `)}`)),Ir.of({tools:O.filter(t,e=>O.contains(Fr,e.name)),instructions:e.instructions,callTool:n.fn(`OrbitClient.callTool`)(function*(t,n){return yield*e.callTool({tool:t,arguments:n},{timeout:`120 seconds`})})})})).pipe(p.provide(Ue.layerHttp({name:`@2digits/tlo-mcp`,version:`1.0.0`,protocol:ze.v2025_11_25,url:Qe})),p.provide(Lr));var H=class extends i.Class(`OrbitReadError`)({message:i.String,status:i.Int.annotate({description:`HTTP status of the failed Orbit call`}).pipe(i.optionalKey),retryAfter:i.String.pipe(i.optionalKey)}){};const zr=i.is(H);function Br(e){if(zr(e))return e;let t=y.isTagged(e,`McpClientError`)&&y.isTagged(e.reason,`HttpError`)?e.reason:void 0;return H.make({message:e.message,...t===void 0?{}:k.pick(t,[`status`,`retryAfter`])})}const Vr=`Europe/Amsterdam`,U=i.String.check(i.isPattern(/^[A-Z0-9]{15}$/u)).annotate({description:`Orbit api_id`}),W=i.String.check(i.makeFilter(e=>M.make(e).pipe(r.exists(t=>M.formatIsoDateUtc(t)===e)),{expected:`an existing date as yyyy-MM-dd`})).annotate({description:`Date as yyyy-MM-dd`}),G=i.Int.check(i.isGreaterThanOrEqualTo(0)),K=i.String.check(i.isPattern(/^\d+h(?:[0-5]\d)?$/)).pipe(i.decodeTo(G,{decode:j.transform(e=>{let[t,n=``]=x.split(e,`h`);return Number(t)*60+Number(n)}),encode:j.transform(e=>`${Math.floor(e/60)}h${x.padStart(2,`0`)(String(e%60))}`)})),q=i.String.pipe(i.decodeTo(i.DateTimeZoned,{decode:j.transformEffect((e,t)=>{let i=x.replace(` `,`T`)(e);return M.makeZoned(`${i}:00Z`,{timeZone:Vr,adjustForTimeZone:!0}).pipe(r.filter(e=>e.pipe(M.formatIsoZoned,x.startsWith(`${i}:00`))),n.fromOption,n.mapError(()=>new Je.InvalidValue({message:`Expected an existing yyyy-MM-dd HH:mm`},e,t)))}),encode:j.transform(M.formatIsoZoned)})).annotate({description:`ISO 8601 date-time with offset, in Europe/Amsterdam`});function J(e,t){let r=i.Struct(t);return i.String.pipe(i.decodeTo(r,{decode:j.transformEffect((t,r)=>{let i=e.exec(t);return i===null?n.fail(new Je.InvalidValue({message:`Unexpected line: ${JSON.stringify(t)}`},t,r)):n.succeed(qe.filter(i.groups??{},y.isNotUndefined))}),encode:j.forbiddenEncoding}))}function Y(e,...t){return i.String.pipe(i.decodeTo(i.Array(e),{decode:j.transform(e=>O.filter(x.split(e,`\r
|
|
7
|
+
`),e=>x.isNonEmpty(x.trim(e))&&!O.some(t,t=>t.test(e)))),encode:j.forbiddenEncoding}))}var Hr=class extends i.Class(`ProjectTaskAdded`)({taskId:U.annotate({description:`api_id of the new task, for CreateTimeEntry or StartTimer`}).pipe(i.optionalKey),projectId:U.annotate({description:`api_id of the project`}).pipe(i.optionalKey),message:i.String.annotate({description:`Orbit's confirmation, with the rate card and assignees it applied`})}){};const Ur=i.String.pipe(i.decodeTo(Hr,{decode:j.transform(e=>{let t=/\bapi_id: (?<id>[A-Z0-9]{15})\b/.exec(e)?.groups?.id,n=/\bproject \(api_id (?<id>[A-Z0-9]{15})\)/.exec(e)?.groups?.id;return{message:e,...t===void 0?{}:{taskId:t},...n===void 0?{}:{projectId:n}}}),encode:j.forbiddenEncoding})),Wr={name:`AddProjectTask`,args:i.Struct({projectId:i.String,name:i.String,description:i.String.pipe(i.optionalKey),workloadHours:i.Finite.pipe(i.optionalKey),startDt:i.String.pipe(i.optionalKey),endDt:i.String.pipe(i.optionalKey),assignedTo:i.String.pipe(i.optionalKey),chapterId:i.String.pipe(i.optionalKey),rateId:i.String.pipe(i.optionalKey),rate:i.Finite.pipe(i.optionalKey),nonBillable:i.Boolean.pipe(i.optionalKey),recurring:i.Boolean.pipe(i.optionalKey),billingMode:i.String.pipe(i.optionalKey),retainerId:i.String.pipe(i.optionalKey)}),result:Ur},Gr=i.decodeUnknownEffect(i.Tuple([i.Struct({type:i.Literal(`text`),text:i.String})]));var Kr=class extends u.Service()(`@2digits/tlo-mcp/orbit/Orbit`){};const qr=p.effect(Kr,n.gen(function*(){let e=yield*Ir;function t(t,a){return n.gen(function*(){let n=O.findFirst(e.tools,({name:e})=>e===t.name);if(r.isNone(n))return yield*Ye.McpClientError.make({reason:Ye.UnsupportedError.make({description:`Orbit does not offer ${t.name}`})});let o=yield*i.encodeEffect(t.args)(a),s=yield*e.callTool(n.value,o);if(O.some(s.content,e=>e.type===`text`&&x.startsWith(`Error: `)(e.text))||s.isError===!0)return yield*Ye.McpClientError.make({reason:Ye.ToolError.make({result:s})});let[{text:c}]=yield*Gr(s.content);return yield*i.decodeEffect(t.result)(c)}).pipe(n.withSpan(`Orbit.${t.name}`))}return Kr.of({call:t})})),Jr=i.String.check(i.isTrimmed(),i.isNonEmpty()),Yr=i.Finite.check(i.isGreaterThanOrEqualTo(0)),Xr=i.String.check(i.isPattern(/^\S+$/u)).annotate({description:`Project number the user sees, such as "2238"`}),Zr=Jr.check(i.isPattern(/^[^,]+$/u)).annotate({description:`Unique user name`}),Qr=A.make(`AddProjectTask`,{description:`Add a work task to a DRAFT or OPEN project, so time can be booked on it. Check GetProject first: it lists the chapters and existing tasks, so you do not add a duplicate. Orbit extends the project end date when endDate is later. If the result is unexpected, check GetProject before calling again: a repeated call adds a second task.`,parameters:i.Struct({projectId:i.Union([U,Xr]).annotate({description:`Project api_id or project number`}),name:Jr.annotate({description:`Task name as shown in the project and in time entries`}),description:Jr.annotate({description:`Task description`}).pipe(i.optionalKey),workloadHours:Yr.annotate({description:`Budgeted hours; per invoicing period when recurring. Omit for no budget`}).pipe(i.optionalKey),startDate:W.annotateKey({description:`Start date as yyyy-MM-dd`}).pipe(i.optionalKey),endDate:W.annotateKey({description:`End date as yyyy-MM-dd, not before startDate. A date after the project end extends the project`}).pipe(i.optionalKey),assignees:i.NonEmptyArray(i.Union([U,Zr]).annotate({description:`User, group or division api_id, or a unique user name`})).annotate({description:`Who may book time on the task without being planned first (Desk "Assign this task to"). Omit to leave it open to everyone`}).pipe(i.optionalKey),chapterId:U.annotate({description:`Chapter api_id from GetProject; omit for the root level`}).pipe(i.optionalKey),rateId:U.annotate({description:`Rate card api_id from ListRates whose name matches the work. Omit when none matches: the default card applies`}).pipe(i.optionalKey),rate:i.Finite.check(i.isGreaterThan(0)).annotate({description:`Hourly rate; only when the user gave one`}).pipe(i.optionalKey),nonBillable:i.Boolean.annotate({description:`Only when the user explicitly asks for a non-billable task`}).pipe(i.optionalKey),recurring:i.Boolean.annotate({description:`SUBSCRIPTION projects only: the task repeats every invoicing period`}).pipe(i.optionalKey),billingMode:i.Literals([`ESTIMATE`,`HOURS`]).annotate({description:`SUBSCRIPTION projects only: ESTIMATE bills the budgeted hours each period, HOURS the delivered hours. Omit for the account default`}).pipe(i.optionalKey),retainerId:U.pipe(i.NullOr).annotate({description:`Retainer api_id to charge the hours on, or null for no retainer. Omit for the default: the project retainer on HOURS projects`}).pipe(i.optionalKey)}),success:Hr,failure:H,failureMode:`return`}).annotate(A.Readonly,!1).annotate(A.Destructive,!1).annotate(A.Idempotent,!1),$r=n.gen(function*(){let e=yield*Kr;return n.fn(`AddProjectTask`)(function*({startDate:t,endDate:r,assignees:i,retainerId:a,...o}){return t!==void 0&&r!==void 0&&r<t?yield*n.fail(H.make({message:`endDate ${r} is before startDate ${t}.`})):yield*e.call(Wr,{...o,...t===void 0?{}:{startDt:t},...r===void 0?{}:{endDt:r},...i===void 0?{}:{assignedTo:O.join(i,`,`)},...a===void 0?{}:{retainerId:a??`NONE`}})},n.mapError(Br))});var ei=class extends i.Class(`Board`)({id:U,name:i.String,listCount:i.Int,cardCount:i.Int,ownerId:U}){},ti=class extends i.Class(`BoardList`)({id:U,name:i.String,cardCount:i.Int,done:i.Boolean.annotate({description:`Final column: cards here count as done`})}){};const X={id:U,boardId:U,listId:U,list:i.String,done:i.Boolean,due:W.pipe(i.optionalKey),ownerId:U.pipe(i.optionalKey),priority:i.String.annotate({description:`As Orbit shows it, e.g. "high" or "medium"`}).pipe(i.optionalKey)};var ni=class extends i.Class(`Card`)({...X,heading:i.String.annotate({description:`Card name and board name as ListTodos shows them, "<card> | <board>". Both can contain " | ", so only the caller that knows the board name can split them.`})}){},ri=class extends i.Class(`CardDetail`)({...X,name:i.String,description:i.String.pipe(i.optionalKey),checklist:i.String.annotate({description:`Checklist progress and counts as Orbit shows them`}).pipe(i.optionalKey),labels:i.Array(i.Struct({id:U,name:i.String})),linked:i.Array(i.Struct({type:i.String,id:U,summary:i.String}))}){};const ii=i.FiniteFromString.check(i.isInt()),ai=i.String.pipe(i.optionalKey,i.decodeTo(i.Boolean,{decode:j.transformOptional(e=>e.pipe(r.isSome,r.some)),encode:j.forbiddenEncoding})),oi=J(/^- (?<id>[A-Z0-9]{15}) \| (?<name>.+) \| lists (?<listCount>\d+), cards (?<cardCount>\d+) \| owner (?<ownerId>[A-Z0-9]{15})$/,{...ei.fields,listCount:ii,cardCount:ii}).pipe(i.decodeTo(ei)),si=J(/^- (?<id>[A-Z0-9]{15}) \| (?<name>.+?) \| cards (?<cardCount>\d+)(?<done> \| FINAL\/done)?$/,{...ti.fields,cardCount:ii,done:ai}).pipe(i.decodeTo(ti)),ci=J(/^- (?<id>[A-Z0-9]{15}) \| (?<heading>.+) \((?<boardId>[A-Z0-9]{15})\) \/ (?<list>.+?) \((?<listId>[A-Z0-9]{15})\)(?<done> \(done\))?(?: \| due (?<due>\S+))?(?: \| prio (?<priority>[a-z]+))?(?: \| (?:owner (?<ownerId>[A-Z0-9]{15})|unassigned))?$/,{...ni.fields,done:ai}).pipe(i.decodeTo(ni)),li=/^(?:Owner|Description|Checklist|Label): /,ui=i.Struct({header:J(/^Card (?<id>[A-Z0-9]{15}) — (?<name>.+)$/,{id:U,name:i.String}),board:J(/^Board\/list: .+ \((?<boardId>[A-Z0-9]{15})\) \/ (?<list>.+?) \((?<listId>[A-Z0-9]{15})\)(?<done> \(done\))?$/,{boardId:U,list:i.String,listId:U,done:ai}),owner:J(/^Owner: (?:(?<ownerId>[A-Z0-9]{15})|unassigned)(?: \| due (?<due>\S+))?(?: \| priority (?<priority>[a-z]+))?$/,{ownerId:X.ownerId,due:X.due,priority:X.priority}).pipe(i.optionalKey),description:J(/^Description: (?<text>.*)$/s,{text:i.String}).pipe(i.optionalKey),checklist:J(/^Checklist: (?<text>.*)$/,{text:i.String}).pipe(i.optionalKey),labels:i.Array(J(/^Label: (?<name>.+) \((?<id>[A-Z0-9]{15})\)$/,{id:U,name:i.String})),linked:i.Array(J(/^- (?<type>[A-Z_]+) (?<id>[A-Z0-9]{15}) \| (?<summary>.+)$/,{type:i.String,id:U,summary:i.Trim}))});function di(e){let[t=``,n=``,...r]=O.filter(x.split(e,`\r
|
|
8
|
+
`),e=>x.isNonEmpty(x.trim(e))&&e!==`Linked:`);return{header:t,board:n,...qe.getSomes({owner:O.findFirst(r,x.startsWith(`Owner: `)),description:O.findFirst(r,x.startsWith(`Description: `)),checklist:O.findFirst(r,x.startsWith(`Checklist: `))}),labels:O.filter(r,x.startsWith(`Label: `)),linked:O.filter(r,e=>!li.test(e))}}const fi={name:`ListBoards`,args:i.Struct({search:i.String.pipe(i.optionalKey),limit:i.Int}),result:Y(oi,/^\d+ board\(s\):$/,/^No boards found\.$/)},pi={name:`ListBoardLists`,args:i.Struct({boardId:U}),result:Y(si)},mi={name:`ListTodos`,args:i.Struct({boardId:U,state:i.Literals([`open`,`all`]),limit:i.Int}),result:Y(ci,/^\d+ card\(s\):$/,/^No cards match\.$/)},hi={name:`GetTodoDetail`,args:i.Struct({todoId:U}),result:i.String.pipe(i.decodeTo(ui,{decode:j.transform(di),encode:j.forbiddenEncoding}),i.decodeTo(ri,{decode:j.transform(({header:e,board:t,owner:n,description:r,checklist:i,labels:a,linked:o})=>({...e,...t,...n,...r===void 0?{}:{description:r.text},...i===void 0?{}:{checklist:i.text},labels:a,linked:o})),encode:j.forbiddenEncoding}))},gi=i.is(U);var _i=class extends i.Class(`BoardCard`)({...X,name:i.String,description:i.String.pipe(i.optionalKey),checklist:i.String.pipe(i.optionalKey),labels:ri.fields.labels.pipe(i.optionalKey),linked:ri.fields.linked.pipe(i.optionalKey)}){},vi=class extends i.Class(`BoardColumn`)({...ti.fields,cards:i.Array(_i)}){},yi=class extends i.Class(`BoardContext`)({board:ei,columns:i.Array(vi).annotate({description:`In board order; column ids are MoveTodo targets`}),cardsTruncated:i.Boolean.annotate({description:`Orbit returns at most 100 cards per board; true when that cap was reached, so cards may be missing`})}){};const bi=A.make(`GetBoardContext`,{description:`Read-only view of one todo board in one call: its columns in order (api_ids for MoveTodo, done flag) with their cards, each with due date, owner and, unless details is false, description, checklist progress and linked tasks. Pass the board api_id or a name that matches exactly one board. Use Orbit write tools (MoveTodo, AddMessage) for changes.`,parameters:i.Struct({board:i.String.annotate({description:`Board api_id, or (part of) its name`}),includeDone:i.Boolean.annotate({description:`Include done cards (default false)`}).pipe(i.withDecodingDefault(n.succeed(!1))),details:i.Boolean.annotate({description:`Fetch card detail for every card (default true)`}).pipe(i.withDecodingDefault(n.succeed(!0)))}),success:yi,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0);function xi(e,t,n){return _i.make({...k.pick(e,[`id`,`boardId`,`listId`,`list`,`done`,`due`,`ownerId`,`priority`]),name:t,...n===void 0?{}:k.pick(n,[`description`,`checklist`,`labels`,`linked`])})}const Si=n.gen(function*(){let e=yield*Kr;return n.fn(`GetBoardContext`)(function*(t){let r=x.trim(t.board),i=yield*e.call(fi,gi(r)?{limit:100}:{search:r,limit:100}),a=O.filter(i,({id:e})=>e===r),o=O.filter(i,({name:e})=>x.toLowerCase(e)===x.toLowerCase(r)),s=gi(r)?a:o.length>0?o:i,[c]=s;if(c===void 0||s.length>1)return yield*n.fail(H.make({message:c===void 0?i.length>=100?`No board matches "${r}" in the first 100 boards Orbit returned; pass the board name instead.`:`No board matches "${r}".`:`"${r}" matches ${s.length} boards: ${O.join(O.map(s,({id:e,name:t})=>`${t} (${e})`),`; `)}. Pass the board api_id.`}));let[l,u]=yield*n.all([e.call(pi,{boardId:c.id}),e.call(mi,{boardId:c.id,state:t.includeDone?`all`:`open`,limit:100})],{concurrency:`unbounded`}),d=new Set(O.map(l,({id:e})=>e)),f=O.filter(u,({listId:e})=>!d.has(e));if(O.isReadonlyArrayNonEmpty(f))return yield*n.fail(H.make({message:`The board changed while it was read: ${O.join(O.map(f,({id:e,list:t,listId:n})=>`card ${e} is in column ${t} (${n})`),`; `)}, which ListBoardLists did not return. Call GetBoardContext again.`}));let p=` | ${c.name}`,m=O.filter(u,({heading:e})=>!x.endsWith(p)(e));if(!t.details&&O.isReadonlyArrayNonEmpty(m))return yield*n.fail(H.make({message:`Cannot split the card name from board "${c.name}" in: ${O.join(O.map(m,({heading:e})=>JSON.stringify(e)),`; `)}. Call again with details: true.`}));let h=t.details?yield*n.forEach(u,t=>e.call(hi,{todoId:t.id}),{concurrency:5}):[],g=O.map(u,(e,t)=>{let n=h[t];return xi(e,n?.name??x.slice(0,e.heading.length-p.length)(e.heading),n)});return yi.make({board:c,columns:O.map(l,e=>vi.make({id:e.id,name:e.name,cardCount:e.cardCount,done:e.done,cards:O.filter(g,({listId:t})=>t===e.id)})),cardsTruncated:u.length>=100})},n.mapError(Br))});var Ci=class extends i.Class(`RunningTimer`)({running:i.Boolean,summary:i.String.annotate({description:`Orbit's description of the running timer`}).pipe(i.optionalKey)}){};const wi=J(/^No timer is running\./,{}).pipe(i.decodeTo(Ci,{decode:j.succeed({running:!1}),encode:j.forbiddenEncoding})),Ti=J(/^(?!No )(?<summary>\S.*)$/s,{summary:i.Trim}).pipe(i.decodeTo(Ci,{decode:j.transform(({summary:e})=>({running:!0,summary:e})),encode:j.forbiddenEncoding})),Ei={name:`GetRunningTimer`,args:i.Record(i.String,i.Never),result:i.Union([wi,Ti])},Di=i.Literals([`logged`,`planned`,`absence`]);var Oi=class extends i.Class(`TimeEntry`)({id:U,start:q,minutes:G,kind:Di,work:i.String.annotate({description:`Project / task, ticket or absence type as Orbit shows it`}),description:i.String.pipe(i.optionalKey),taskId:U.pipe(i.optionalKey),ticketId:U.pipe(i.optionalKey),pendingApproval:i.Boolean.annotate({description:`Absence still awaiting approval`}).pipe(i.optionalKey),lock:i.String.annotate({description:`Why Orbit refuses edits, e.g. "timesheet submitted (FINAL)"`}).pipe(i.optionalKey),editable:i.Boolean}){},ki=class extends i.Class(`TimesheetDay`)({date:W,weekday:i.String,state:i.Literals([`OPEN`,`FINAL`]),loggedMinutes:G,plannedMinutes:G,absenceMinutes:G,capacityMinutes:G,entries:i.Array(Oi)}){},Ai=class extends i.Class(`TimesheetWeek`)({weekOf:W,userId:U,days:i.Array(ki)}){};const ji={id:U,minutes:K,planned:i.Literal(`[PLANNED]`).pipe(i.optionalKey),absence:i.Literals([`ABSENCE`,`ABSENCE (pending approval)`]).pipe(i.optionalKey),work:i.Trim,description:i.String.pipe(i.optionalKey),taskId:U.pipe(i.optionalKey),ticketId:U.pipe(i.optionalKey),lock:i.String.pipe(i.optionalKey)};function Mi(e,t){let{planned:n,absence:r}=t;return{...k.pick(t,[`id`,`minutes`,`work`,`description`,`taskId`,`ticketId`,`lock`]),start:e,kind:Ni(n,r),...r===void 0?{}:{pendingApproval:r===`ABSENCE (pending approval)`},editable:t.lock===void 0}}function Ni(e,t){return t===void 0?e===void 0?`logged`:`planned`:`absence`}const Pi=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],Fi=i.Literals(Pi),Ii=`| Day | State | Logged | Planned | Absence | Capacity |`,Li=i.Struct({header:J(/^Timesheet week of (?<weekOf>\S+) for .+ \(user api_id: (?<userId>[A-Z0-9]{15})\)$/,{weekOf:W,userId:U}),days:i.Array(J(/^\| (?<weekday>\w+) (?<date>\S+) \| (?<state>[A-Z]+) \| (?<loggedMinutes>\S+) \| (?<plannedMinutes>\S+) \| (?<absenceMinutes>\S+) \| (?<capacityMinutes>\S+) \|$/,{weekday:Fi,date:W,state:ki.fields.state,loggedMinutes:K,plannedMinutes:K,absenceMinutes:K,capacityMinutes:K})).check(i.isBetweenLength(7,7)),columns:i.Array(i.String).check(i.isBetweenLength(1,1)),entries:i.Array(J(/^- (?<weekday>\w+) (?<time>\d{2}:\d{2}) (?<minutes>\d+h\d*) (?:(?<planned>\[PLANNED\]) |(?<absence>ABSENCE(?: \(pending approval\))?) )?(?![[(]|ABSENCE)(?<work>ticket ".*?"(?= — \d+ )|.+?)(?: — (?<description>.+?))? {2}\(api_id: (?<id>[A-Z0-9]{15})(?:, task api_id: (?<taskId>[A-Z0-9]{15})|, ticket api_id: (?<ticketId>[A-Z0-9]{15}))?\)(?: \[locked: (?<lock>.+)\])?$/s,{weekday:Fi,time:i.String,...ji}))}).check(i.makeFilter(({header:e,days:t})=>O.every(t,(t,n)=>t.weekday===Pi[n]&&t.date===M.formatIsoDateUtc(M.add(M.makeUnsafe(e.weekOf),{days:n}))),{expected:`day rows Mon to Sun with consecutive dates from the week start`})),Ri=[/^\|---/,/^Week total: /,/^Entries:$/,/^Planned entries can be confirmed/];function zi(e){let[t=``,...n]=O.filter(x.split(e,`\r
|
|
9
|
+
`),e=>x.isNonEmpty(x.trim(e))&&!O.some(Ri,t=>t.test(e))),r=x.startsWith(`- `);return{header:t,columns:O.filter(n,e=>e===Ii),days:O.filter(n,e=>e!==Ii&&!r(e)),entries:O.filter(n,r)}}const Bi={name:`GetTimesheetWeek`,args:i.Struct({date:W}),result:i.String.pipe(i.decodeTo(Li,{decode:j.transform(zi),encode:j.forbiddenEncoding}),i.decodeTo(Ai,{decode:j.transform(({header:e,days:t,entries:n})=>({...e,days:O.map(t,e=>({...e,entries:O.map(O.filter(n,({weekday:t})=>t===e.weekday),({time:t,...n})=>Mi(`${e.date} ${t}`,n))}))})),encode:j.forbiddenEncoding}))};var Vi=class extends i.Class(`Absence`)({id:U,date:W,type:i.String.annotate({description:`Absence type, e.g. "Holiday" or "Office Closed"`}),minutes:G,state:i.Literals([`approved`,`pending`,`refused`,`revoked`]),note:i.String.pipe(i.optionalKey)}){};const Hi=J(/^- (?<date>\S+) \| .+? \| (?<type>(?:(?! \| ).)+) (?<minutes>\d+h\d*) \| (?<state>[A-Z]+)(?: approval)?(?: — (?<note>.+?))? {2}\(api_id: (?<id>[A-Z0-9]{15})\)$/s,{...Vi.fields,minutes:K,state:i.Literals([`APPROVED`,`PENDING`,`REFUSED`,`REVOKED`]).pipe(i.decodeTo(Vi.fields.state,{decode:j.transform(x.toLowerCase),encode:j.transform(x.toUpperCase)}))}).pipe(i.decodeTo(Vi)),Ui={name:`ListAbsences`,args:i.Struct({dateFrom:W,dateTo:W}),result:Y(Hi,/^\d+ absence\(s\):$/,/^Approve\/refuse pending requests/,/^No absences match these filters\.$/)};var Wi=class extends i.Class(`BookableTask`)({id:U,label:i.String.annotate({description:`Project and task; Orbit separates both with " | ", as inside names`}),projectNumber:i.String.pipe(i.optionalKey),remainingMinutes:G.annotate({description:`Remaining budget; absent when unlimited`}).pipe(i.optionalKey)}){};const Gi=J(/^\| (?<label>(?:(?<projectNumber>\d+) )?.+?) \| (?:unlimited|(?<remainingMinutes>\d+h\d*)) \| (?<id>[A-Z0-9]{15}) \|$/,{...Wi.fields,remainingMinutes:K.pipe(i.optionalKey)}).pipe(i.decodeTo(Wi)),Ki={name:`ListMyTasks`,args:i.Record(i.String,i.Never),result:Y(Gi,/^\d+ assignable task\(s\):$/,/^\| Project \|/,/^\|---/,/^No assignable tasks found/)},qi=i.Literals([`planned`,`fixed-time`,`request`,`refused`]),Ji=J(/^- (?<start>\d{4}-\d{2}-\d{2} \d{2}:\d{2}) \| .+? \| (?<minutes>\d+h\d*) \| (?<kind>[a-z-]+) \| (?<work>.+?)(?: \| series (?<seriesId>[A-Z0-9]{15}))? {2}\(api_id: (?<id>[A-Z0-9]{15})\)$/s,{id:U,start:q,minutes:K,kind:qi,work:i.String,seriesId:U.pipe(i.optionalKey)}),Yi={name:`ListPlannedEntries`,args:i.Struct({dateFrom:W,dateTo:W}),result:Y(Ji,/^\d+ planning entries:$/,/^No planning entries match these filters\.$/)},Xi=1050;var Zi=class extends i.Class(`TimeSlot`)({from:i.String.annotate({description:`HH:mm, Europe/Amsterdam`}),to:i.String.annotate({description:`HH:mm, Europe/Amsterdam`}),minutes:G}){},Qi=class extends i.Class(`Overlap`)({first:U,second:U,minutes:G}){},$i=class extends i.Class(`UnconfirmedPlanned`)({id:U.annotate({description:`Entry api_id for ConfirmPlannedEntry`}),start:q,minutes:G,work:i.String,taskId:U.pipe(i.optionalKey),planningKind:qi.annotate({description:`From ListPlannedEntries`}).pipe(i.optionalKey),seriesId:U.pipe(i.optionalKey)}){},ea=class extends i.Class(`WorkdayDay`)({date:W,weekday:i.String,state:i.Literals([`OPEN`,`FINAL`]),capacityMinutes:G,loggedMinutes:G,plannedMinutes:G,absenceMinutes:G,missingMinutes:G.annotate({description:`Capacity minus logged and absence time`}),dayOff:i.Boolean.annotate({description:`No capacity, or absence covers it`}),entries:i.Array(Oi).annotate({description:`Entries, after the taskId/kind filters`}),unconfirmedPlanned:i.Array($i),gaps:i.Array(Zi).annotate({description:`Time within working hours without any entry; unconfirmed planned entries count as occupied`}),overlaps:i.Array(Qi),outsideWorkingHours:i.Array(U).annotate({description:`Entries starting before or ending after working hours`})}){},ta=class extends i.Class(`Workday`)({from:W,to:W,timeZone:i.String,workingHours:Zi,totals:i.Struct({capacityMinutes:G,loggedMinutes:G,plannedMinutes:G,absenceMinutes:G,missingMinutes:G}),days:i.Array(ea),absences:i.Array(Vi),runningTimer:Ci,bookableTasks:i.Array(Wi)}){};const na=A.make(`GetMyWorkday`,{description:`Read-only overview of your own timesheet for one day, its week, or a range of up to 62 days, in one call. Per day: OPEN/FINAL state, logged/planned/absence time vs capacity, every entry with api_id, task/ticket api_id and edit lock, planned entries still to confirm, gaps, overlaps and entries outside 09:00–17:30. Also lists absences with approval state, the running timer and bookable tasks with remaining budget. Times are Europe/Amsterdam. Use Orbit's write tools for changes.`,parameters:i.Struct({date:W.annotate({description:`The day to show, or the first day of the range (yyyy-MM-dd)`}),scope:i.Literals([`day`,`week`]).annotate({description:`day (default) or the Monday–Sunday week containing date; ignored when to is set`}).pipe(i.withDecodingDefault(n.succeed(`day`))),to:W.annotate({description:`Optional last day of the range, inclusive (yyyy-MM-dd)`}).pipe(i.optional),taskId:U.annotate({description:`Only list entries on this task api_id`}).pipe(i.optional),kind:Di.annotate({description:`Only list entries of this kind`}).pipe(i.optional)}),success:ta,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0);function ra(e){return M.makeUnsafe(`${e}T00:00:00Z`)}function ia(e,t){return M.formatIsoDateUtc(M.add(ra(e),{days:t}))}function aa(e){return ia(e,-((M.toPartsUtc(ra(e)).weekDay+6)%7))}function oa(e){let{hour:t,minute:n}=M.toParts(e);return t*60+n}function sa(e){let t=x.padStart(2,`0`);return`${t(String(Math.floor(e/60)))}:${t(String(e%60))}`}function ca(e,t){return Zi.make({from:sa(e),to:sa(t),minutes:t-e})}function la(e){let t=oa(e.start);return{id:e.id,from:t,to:t+e.minutes}}function ua(e){let t=[],n=540,r=O.sortWith(e,({from:e})=>e,Xe.Number);for(let e of r)e.from>n&&n<Xi&&t.push(ca(n,Math.min(e.from,Xi))),n=Math.max(n,e.to);return n<Xi?[...t,ca(n,Xi)]:t}function da(e){let t=O.sortWith(e,({from:e})=>e,Xe.Number);return O.flatMap(t,(e,n)=>O.flatMap(O.drop(t,n+1),t=>t.from<e.to?[Qi.make({first:e.id,second:t.id,minutes:Math.min(e.to,t.to)-t.from})]:[]))}function fa(e,t,n){let i=O.map(e.entries,la),a=e.capacityMinutes===0||e.absenceMinutes>=e.capacityMinutes;return ea.make({date:e.date,weekday:e.weekday,state:e.state,capacityMinutes:e.capacityMinutes,loggedMinutes:e.loggedMinutes,plannedMinutes:e.plannedMinutes,absenceMinutes:e.absenceMinutes,missingMinutes:Math.max(0,e.capacityMinutes-e.loggedMinutes-e.absenceMinutes),dayOff:a,entries:O.filter(e.entries,e=>(n.taskId===void 0||e.taskId===n.taskId)&&(n.kind===void 0||e.kind===n.kind)),unconfirmedPlanned:O.flatMap(e.entries,e=>{if(e.kind!==`planned`)return[];let n=O.findFirst(t,({id:t})=>t===e.id);return[$i.make({...k.pick(e,[`id`,`start`,`minutes`,`work`,`taskId`]),...r.match(n,{onNone:()=>({}),onSome:e=>({planningKind:e.kind,...k.pick(e,[`seriesId`])})})})]}),gaps:a?[]:ua(i),overlaps:da(i),outsideWorkingHours:O.flatMap(i,({id:e,from:t,to:n})=>t<540||n>Xi?[e]:[])})}const pa=n.gen(function*(){let e=yield*Kr;return n.fn(`GetMyWorkday`)(function*(t){let i=t.to===void 0&&t.scope===`week`?aa(t.date):t.date,a=t.to??(t.scope===`week`?ia(i,6):i);if(a<i||a>ia(i,61))return yield*n.fail(H.make({message:`Range ${i}..${a} must be 1 to 62 days.`}));let o=O.unfold(aa(i),e=>e>a?r.none():r.some([e,ia(e,7)])),s={dateFrom:i,dateTo:a},[c,l,u,d,f]=yield*n.all([n.forEach(o,t=>e.call(Bi,{date:t}),{concurrency:4}),e.call(Ui,s),e.call(Yi,s),e.call(Ei,{}),e.call(Ki,{})],{concurrency:`unbounded`}),p=O.filter(O.flatMap(c,e=>e.days),e=>e.date>=i&&e.date<=a),m=O.unfold(i,e=>e>a?r.none():r.some([e,ia(e,1)]));if(O.join(O.map(p,({date:e})=>e),`,`)!==O.join(m,`,`))return yield*n.fail(H.make({message:`Orbit's timesheets do not cover every day of ${i}..${a}.`}));let h=O.map(p,e=>fa(e,u,t));function g(e){return O.reduce(h,0,(t,n)=>t+n[e])}return ta.make({from:i,to:a,timeZone:Vr,workingHours:ca(540,Xi),totals:{capacityMinutes:g(`capacityMinutes`),loggedMinutes:g(`loggedMinutes`),plannedMinutes:g(`plannedMinutes`),absenceMinutes:g(`absenceMinutes`),missingMinutes:g(`missingMinutes`)},days:h,absences:l,runningTimer:d,bookableTasks:f})},n.mapError(Br))}),ma=J(/^- (?<start>\d{4}-\d{2}-\d{2} \d{2}:\d{2}) \| .+? \| (?<minutes>\d+h\d*)(?: (?<planned>\[PLANNED\]))? \| (?:(?<absence>ABSENCE(?: \(pending approval\))?) )?(?![[(]|ABSENCE)(?<work>ticket ".*?"(?= — \d+ )|.+?)(?: — (?<description>.+?))? {2}\(api_id: (?<id>[A-Z0-9]{15})\)(?: \[locked: (?<lock>.+)\])?$/s,{start:i.String,...ji}).pipe(i.decodeTo(Oi,{decode:j.transform(({start:e,...t})=>Mi(e,t)),encode:j.forbiddenEncoding})),ha=i.Struct({entries:Y(ma,/^\d+ time entries/,/^Total duration: /,/^No time entries match these filters\.$/),truncated:i.Boolean.annotate({description:`Orbit capped the list at 100 rows; narrow the range`})}),ga={name:`ListTimeEntries`,args:i.Struct({dateFrom:W,dateTo:W,text:i.String.pipe(i.optionalKey)}),result:i.String.pipe(i.decodeTo(ha,{decode:j.transform(e=>({entries:e,truncated:/^\d+ time entries \(more exist/.test(e)})),encode:j.forbiddenEncoding}))},Z=i.String.pipe(i.NullOr),Q=q.pipe(i.NullOr);var _a=class extends i.Class(`TicketSummary`)({ticketId:U,number:i.String,name:i.String,state:i.String}){},va=class extends i.Class(`TicketDetail`)({ticketId:U,number:i.String,name:i.String,description:i.String,state:i.String,priority:i.String,category:Z,queue:Z,client:Z,clientId:U.pipe(i.NullOr),contact:Z,owner:Z,assignee:Z,project:Z,projectId:U.pipe(i.NullOr),task:Z,taskId:U.pipe(i.NullOr),loggedMinutes:G,invoicedMinutes:G,billable:i.Boolean,slaResponseDue:Q,slaCloseDue:Q,followUpAction:Z,followUpDate:Q,createdDate:q,closedDate:Q,lastClientInput:Q,lastAgentReply:Q,attachments:i.Array(i.Struct({fileId:U,name:i.String,downloadUrl:i.String})),downloadLinksNote:i.String.pipe(i.optionalKey),otherOpenTicketsOfClient:i.Array(_a)}){},ya=class extends i.Class(`TicketComment`)({commentId:U,date:q,isInternal:i.Boolean,author:Z,title:Z,content:i.String,loggedMinutes:G,timeEntryId:U.pipe(i.NullOr)}){};const ba=i.Struct({count:i.Int,tickets:i.Array(_a)}),xa=i.Struct({count:i.Int,comments:i.Array(ya)}),Sa={name:`ListTickets`,args:i.Struct({query:i.String,state:i.String,limit:i.Int}),result:ba.pipe(i.fromJsonString)},Ca={name:`GetTicketDetail`,args:i.Struct({ticketId:U}),result:va.pipe(i.fromJsonString)},wa={name:`ListTicketComments`,args:i.Struct({ticketId:U,limit:i.Int}),result:xa.pipe(i.fromJsonString)},Ta=/^[A-Z0-9]{15}$/;var Ea=class extends i.Class(`TicketContext`)({ticket:va,comments:i.Array(ya).annotate({description:`Newest first, internal notes included`}),commentCount:i.Int.annotate({description:`Number of comments returned, not the ticket total`}),commentsTruncated:i.Boolean.annotate({description:`Orbit returns at most 100 comments; true when that cap was reached, so older comments may be missing`}),timeEntries:i.Array(Oi).annotate({description:`Your entries booked on this ticket`}),timeEntriesTruncated:i.Boolean.annotate({description:`Orbit capped the entry search at 100 rows`}),loggedMinutes:G.annotate({description:`Sum of the logged timeEntries; planned entries are not counted`}),mentionedIn:i.Array(U).annotate({description:`Your other entries whose description mentions the ticket number`})}){};const Da=A.make(`GetTicketContext`,{description:`Read-only context for one support ticket by its number (e.g. 9087) or api_id, in one call: full detail, the conversation (newest first), and your time entries on it. Finds closed tickets too. Times are Europe/Amsterdam. Use Orbit write tools (ReplyToTicket, AddInternalComment, CloseTicket) for changes.`,parameters:i.Struct({ticket:i.String.annotate({description:`Ticket number such as "9087", or the ticket api_id`})}),success:Ea,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0),Oa=n.gen(function*(){let e=yield*Kr;return n.fn(`GetTicketContext`)(function*({ticket:t}){let i=x.trim(t),a=i;if(!Ta.test(i)){let{tickets:t}=yield*e.call(Sa,{query:i,state:`NEW|OPEN|WAIT|CLOSED|DELETED|REQCLOSE`,limit:100}),o=O.findFirst(t,({number:e})=>e===i);if(r.isNone(o))return yield*n.fail(H.make({message:t.length>=100?`Ticket ${i} is not in the first 100 search results Orbit returned; pass the ticket api_id instead.`:`No ticket with number ${i} found.`}));a=o.value.ticketId}let[o,s]=yield*n.all([e.call(Ca,{ticketId:a}),e.call(wa,{ticketId:a,limit:100})],{concurrency:`unbounded`}),c=yield*M.now,l=yield*e.call(ga,{dateFrom:M.formatIsoDate(o.createdDate),dateTo:M.formatIsoDate(M.setZoneNamedUnsafe(c,Vr)),text:o.number});function u({work:e,description:t=``}){let[n]=x.split(t,` `);return x.startsWith(`ticket "`)(e)&&n===o.number}function d({work:e,description:t=``}){return O.contains(x.split(`${e} ${t}`,/\D+/),o.number)}let f=O.filter(l.entries,u),p=O.filter(l.entries,e=>!u(e)&&d(e));return Ea.make({ticket:o,comments:s.comments,commentCount:s.count,commentsTruncated:s.comments.length>=100,timeEntries:f,timeEntriesTruncated:l.truncated,loggedMinutes:O.reduce(f,0,(e,t)=>t.kind===`logged`?e+t.minutes:e),mentionedIn:O.map(p,({id:e})=>e)})},n.mapError(Br))}),ka=Ke.make(na,Da,bi,Qr),Aa=ka.toLayer(n.all({GetMyWorkday:pa,GetTicketContext:Oa,GetBoardContext:Si,AddProjectTask:$r})),ja=i.decodeUnknownEffect(i.JsonObject),Ma=i.decodeUnknownOption(H.pipe(i.fromJsonString));function Na(e){return Ge.CallToolResult.make({isError:!0,content:[{type:`text`,text:`Orbit rate limited this call; retry after ${e??`the server cooldown`}. Not replayed.`}],_meta:{"tlo-mcp/httpStatus":429,...e===void 0?{}:{"tlo-mcp/retryAfter":e}}})}function Pa(e){let[t]=`content`in e&&e.isError===!0?e.content:[];return r.match(t?.type===`text`?Ma(t.text):r.none(),{onNone:()=>e,onSome:({message:e,status:t,retryAfter:n})=>t===429?Na(n):Ge.CallToolResult.make({isError:!0,content:[{type:`text`,text:e}]})})}const Fa=p.effectDiscard(n.gen(function*(){let e=yield*Ir,t=yield*Be.McpServer;yield*n.forEach(O.filter(e.tools,({name:e})=>!(e in ka.tools)),n.fn(`OrbitProxyLive.tool`)(function*(r){yield*t.addTool({tool:r,annotations:u.empty(),handle:n.fn(`handle`)(function*(e){return yield*ja(e)},n.mapError(e=>Ge.InvalidParams.make({message:`Tool arguments must be a JSON object.`,data:e})),n.flatMap(t=>e.callTool(r,t).pipe(n.catchReason(`McpClientError`,`HttpError`,({status:e,retryAfter:t},r)=>e===429?n.succeed(Na(t)):n.fail(r)),n.mapError(e=>Ge.InternalError.make({message:e.message})))))})}),{discard:!0}),yield*Be.registerToolkit(ka).pipe(n.provideService(Be.McpServer,Be.McpServer.of({...t,addTool:n.fn(`OrbitProxyLive.composite`)(function*(e){yield*t.addTool({...e,handle:t=>e.handle(t).pipe(n.map(Pa))})})})))})).pipe(p.provide(p.provideMerge(Aa,qr))),Ia=n.gen(function*(){let e=yield*pe.Path,t=yield*ut(`gateway.key`);return e.join(t,`gateway.key`)}),La=Re.mebibytes(1),Ra=b.empty({status:401,headers:{"www-authenticate":`Bearer`,"cache-control":`no-store`}}),za=b.empty({status:403,headers:{"cache-control":`no-store`}}),Ba=new TextEncoder,Va=i.String.check(i.isPattern(/^[a-f0-9]{64}$/)).pipe(i.RedactedFromValue);var $=class extends i.TaggedError()(`GatewayError`,{message:i.String}){};const Ha=n.fn(`Gateway.loadKey`)(function*(e){let t=yield*fe.FileSystem,r=yield*te.SecureRandom,a=(yield*pe.Path).dirname(e);yield*t.makeDirectory(a,{recursive:!0,mode:448}),yield*t.chmod(a,448);let o=yield*r.randomBytes(32);yield*t.writeFileString(e,Ve.encode(o),{flag:`wx`,mode:384}).pipe(n.catchReason(`PlatformError`,`AlreadyExists`,()=>n.void));let s=yield*t.stat(e);return s.type!==`File`||s.mode&63?yield*$.make({message:`Gateway key must be a private file (chmod 600).`}):yield*t.readFileString(e).pipe(n.flatMap(i.decodeEffect(Va)))},n.mapError(()=>$.make({message:`Cannot load private gateway key. Check its permissions and format.`})));function Ua(e,t){return e.digest(ee.sha256,Ba.encode(t))}function Wa(e){return p.unwrap(n.gen(function*(){let t=yield*ee.Digest,r=yield*Ua(t,`Bearer ${h.value(e)}`);return le.middleware(e=>n.gen(function*(){let i=yield*de.HttpServerRequest,a=yield*Ua(t,i.headers.authorization??``);return ce.timingSafeEqual(r,a)?i.headers.origin===void 0?yield*e.pipe(n.provideService(He.MaxBodySize,La),n.map(e=>b.setHeader(e,`cache-control`,`no-store`))):za:Ra}),{global:!0})}))}function Ga(e){let t=p.unwrap(n.gen(function*(){let e=yield*Ir;return Fa.pipe(p.provide(Be.layerHttp({name:`tlo-mcp`,version:`1.0.0`,instructions:e.instructions,path:`/mcp`,protocols:[ze.v2025_11_25,ze.v2025_06_18,ze.v2025_03_26]})))}));return p.merge(t,Wa(e))}const Ka=i.String.check(i.isPattern(/^[a-z0-9]+\.opentunnel\.xyz$/)),qa=i.decodeEffect(Ka),Ja=n.fn(`Gateway.openTunnel`)(function*(e){let t=yield*(yield*Pr).tunnel.connect({profile:`tlo-mcp`,routes:{tlo:`127.0.0.1:${e}`}}),r=yield*qa(t.tunnel.hostname);return yield*t.events.pipe(me.filter(e=>e.type===`reconnecting`),me.runForEach(()=>n.sync(()=>process.stderr.write(`OpenTunnel reconnecting...
|
|
10
|
+
`))),n.forkScoped),{endpoint:`https://tlo.${r}/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 Ya(e){return`Connect my personal Teamleader Orbit MCP to Executor Cloud.
|
|
11
11
|
Endpoint: ${e}
|
|
12
12
|
Transport: Streamable HTTP. Authentication: API key in Authorization: Bearer <key>.
|
|
13
13
|
Register an MCP integration named Teamleader Orbit (slug tlo_mcp) with a bearer-header API-key template, not OAuth.
|
|
14
14
|
Use a secure credential handoff so I enter the gateway key directly in Executor; never ask me to paste it into chat.
|
|
15
15
|
Create a personal connection, discover tools, and verify with one read-only tool. Do not change business data.
|
|
16
16
|
If this endpoint already exists, reuse its integration/connection instead of creating duplicates.
|
|
17
|
-
Orbit login and refresh are handled
|
|
18
|
-
`}const
|
|
19
|
-
`));let{endpoint:
|
|
17
|
+
Orbit login and refresh are handled by the gateway; do not register another Orbit OAuth client.
|
|
18
|
+
`}const Xa=n.fn(`TloMcp.connect`)(function*(e,t){let r=yield*Ia,i=yield*Ha(r),a=yield*gt,o=yield*Ct;if((yield*a.load)===void 0){if(t!==void 0)return yield*$.make({message:`No Orbit session. Run tlo-mcp login on a machine with a browser first.`});yield*o.login}if(yield*p.build(le.serve(Ga(i),{disableLogger:!0,disableListenLog:!0}).pipe(p.provide(Rr),p.provide(se.layer(()=>oe({maxHeaderSize:8192,requestTimeout:13e4}),{host:Le.formatIp(t===void 0?Le.ipv4Loopback:Le.ipv4Unspecified),port:e})))),t!==void 0){let e=new URL(`/mcp`,t).href;return yield*n.sync(()=>{process.stderr.write(`TLO gateway ready: ${e}\nGateway key: ${r} (private; not printed)\n`),process.stdout.write(Ya(e))}),yield*n.never}yield*n.sync(()=>process.stderr.write(`Connecting OpenTunnel (first certificate may take a few minutes)...
|
|
19
|
+
`));let{endpoint:s,closed:c}=yield*Ja(e);return yield*n.sync(()=>{process.stderr.write(`TLO gateway ready: ${s}\nGateway key: ${r} (private; not printed)\n`),process.platform===`darwin`&&process.stderr.write(`Copy the key for Executor's secure credential form: pbcopy < "${r}"\n`),process.stderr.write(`Keep this process running and your Mac awake. Ctrl-C closes the gateway and tunnel.
|
|
20
20
|
|
|
21
21
|
Copy this prompt to your agent:
|
|
22
22
|
|
|
23
|
-
`),process.stdout.write(
|
|
23
|
+
`),process.stdout.write(Ya(s))}),yield*c,yield*$.make({message:`The OpenTunnel connection stopped. Restart tlo-mcp.`})},n.scoped,n.provide([wt,yt,Pr.layer()]));function Za(e){return a.make(e,{},n.fn(`TloMcp.${e}`)(function*(){yield*(yield*Ct)[e]},n.provide(wt),n.scoped))}const Qa=a.make(`tlo-mcp`,{port:o.Int(`port`).pipe(o.withSchema(i.Int.check(i.isBetween({minimum:1024,maximum:65535}))),o.withDefault(4790)),publicUrl:o.String(`public-url`).pipe(o.withSchema(i.URLFromString.check(i.makeFilter(e=>e.protocol===`https:`&&e.href===`${e.origin}/`||`Expected an HTTPS origin, such as https://tlo.example.com`))),o.withDescription(`Serve on 0.0.0.0 behind this HTTPS origin instead of opening OpenTunnel`),o.optional)},({port:e,publicUrl:t})=>Xa(e,r.getOrUndefined(t))).pipe(a.withSubcommands([Za(`login`),Za(`logout`)]));n.fn(`TloMcp.run`)(function*(e){return yield*a.runWith(Qa,{version:`1.0.0`})(e)})(process.argv.slice(2)).pipe(n.provide(lt),t.runMain);export{};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@2digits/tlo-mcp",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/2digits-agency/configs.git",
|
|
@@ -19,12 +19,12 @@
|
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
21
|
"@effect/platform-node": "4.1.2",
|
|
22
|
-
"@opentunnel/client": "0.6.
|
|
22
|
+
"@opentunnel/client": "0.6.2",
|
|
23
23
|
"@yielded/oauth": "0.1.0-beta.47",
|
|
24
24
|
"effect": "4.1.2"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
|
-
"@2digits/tsconfig": "1.2.
|
|
27
|
+
"@2digits/tsconfig": "1.2.4",
|
|
28
28
|
"@effect/vitest": "4.1.2",
|
|
29
29
|
"publint": "0.3.25",
|
|
30
30
|
"tsrs": "0.21.0-ts7.1.0-beta",
|