@2digits/tlo-mcp 2.4.0 → 2.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/bin.mjs +12 -12
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -97,9 +97,10 @@ handoff for the API key and verify one read-only tool after connecting.
|
|
|
97
97
|
- The hostname is public/discoverable; route names are not authentication. Anyone possessing the gateway key
|
|
98
98
|
can use your Orbit tools with your permissions, including writes. Executor policies do not protect against a leaked key.
|
|
99
99
|
- Tools, schemas, annotations, instructions, structured content, errors and rate limits come from official Orbit.
|
|
100
|
-
Only the allowlisted tools in `src/mcp/tools.ts` (timesheet, time entries, timers, tickets, todos and
|
|
101
|
-
planning
|
|
102
|
-
no longer offers an allowlisted tool. `AddProjectTask`
|
|
100
|
+
Only the allowlisted tools in `src/mcp/tools.ts` (timesheet, time entries, timers, tickets, todos, projects and their
|
|
101
|
+
tasks, and read-only planning lookups) are forwarded; other Orbit tools are hidden and cannot be called. Startup warns when Orbit
|
|
102
|
+
no longer offers an allowlisted tool. `AddProjectTask`, `CloseProjectTask`, `UpdateProject`, `UpdateProjectTask`, `CloseTicketSilently`, `SetTicketOwner` and
|
|
103
|
+
`LinkTicketToProject` are the gateway's own tools with stricter schemas; each call
|
|
103
104
|
is still exactly one Orbit write. Only tools are forwarded; resources/prompts/reverse requests are not exposed. No tool call is automatically replayed.
|
|
104
105
|
- To rotate the gateway key, stop the gateway, remove only `gateway.key`, restart, and update the Executor connection.
|
|
105
106
|
|
package/dist/bin.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
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/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
|
-
`)})}),
|
|
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`},
|
|
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 X=class extends u.Service()(`@2digits/tlo-mcp/orbit/Orbit`){};const Kr=p.effect(X,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 X.of({call:t})})),qr=i.String.check(i.isTrimmed(),i.isNonEmpty()),Jr=i.Finite.check(i.isGreaterThanOrEqualTo(0)),Yr=i.String.check(i.isPattern(/^\S+$/u)).annotate({description:`Project number the user sees, such as "2238"`}),Xr=qr.check(i.isPattern(/^[^,]+$/u)).annotate({description:`Unique user name`}),Zr=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,Yr]).annotate({description:`Project api_id or project number`}),name:qr.annotate({description:`Task name as shown in the project and in time entries`}),description:qr.annotate({description:`Task description`}).pipe(i.optionalKey),workloadHours:Jr.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,Xr]).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),Qr=n.gen(function*(){let e=yield*X;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))}),Z=i.String.pipe(i.NullOr),Q=q.pipe(i.NullOr);var $r=class extends i.Class(`TicketSummary`)({ticketId:U,number:i.String,name:i.String,state:i.String}){},ei=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($r)}){},ti=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 ni=i.Struct({count:i.Int,tickets:i.Array($r)}),ri=i.Struct({count:i.Int,comments:i.Array(ti)}),ii={name:`ListTickets`,args:i.Struct({query:i.String,state:i.String,limit:i.Int}),result:ni.pipe(i.fromJsonString)},ai={name:`GetTicketDetail`,args:i.Struct({ticketId:U}),result:ei.pipe(i.fromJsonString)},oi={name:`ListTicketComments`,args:i.Struct({ticketId:U,limit:i.Int}),result:ri.pipe(i.fromJsonString)},si={name:`CloseTicketSilently`,args:i.Struct({ticketId:U}),result:i.String},ci=i.Literals([`logged`,`planned`,`absence`]);var li=class extends i.Class(`TimeEntry`)({id:U,start:q,minutes:G,kind:ci,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}){},ui=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(li)}){},di=class extends i.Class(`TimesheetWeek`)({weekOf:W,userId:U,days:i.Array(ui)}){};const fi={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 pi(e,t){let{planned:n,absence:r}=t;return{...k.pick(t,[`id`,`minutes`,`work`,`description`,`taskId`,`ticketId`,`lock`]),start:e,kind:mi(n,r),...r===void 0?{}:{pendingApproval:r===`ABSENCE (pending approval)`},editable:t.lock===void 0}}function mi(e,t){return t===void 0?e===void 0?`logged`:`planned`:`absence`}const hi=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],gi=i.Literals(hi),_i=`| Day | State | Logged | Planned | Absence | Capacity |`,vi=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:gi,date:W,state:ui.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:gi,time:i.String,...fi}))}).check(i.makeFilter(({header:e,days:t})=>O.every(t,(t,n)=>t.weekday===hi[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`})),yi=[/^\|---/,/^Week total: /,/^Entries:$/,/^Planned entries can be confirmed/];function bi(e){let[t=``,...n]=O.filter(x.split(e,`\r
|
|
8
|
-
`),e=>x.isNonEmpty(x.trim(e))&&!
|
|
9
|
-
`),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=>!Ui.test(e))}}const Ki={name:`ListBoards`,args:i.Struct({search:i.String.pipe(i.optionalKey),limit:i.Int}),result:Y(Bi,/^\d+ board\(s\):$/,/^No boards found\.$/)},qi={name:`ListBoardLists`,args:i.Struct({boardId:U}),result:Y(Vi)},Ji={name:`ListTodos`,args:i.Struct({boardId:U,state:i.Literals([`open`,`all`]),limit:i.Int}),result:Y(Hi,/^\d+ card\(s\):$/,/^No cards match\.$/)},Yi={name:`GetTodoDetail`,args:i.Struct({todoId:U}),result:i.String.pipe(i.decodeTo(Wi,{decode:j.transform(Gi),encode:j.forbiddenEncoding}),i.decodeTo(Li,{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}))},Xi=i.is(U);var Zi=class extends i.Class(`BoardCard`)({...$,name:i.String,description:i.String.pipe(i.optionalKey),checklist:i.String.pipe(i.optionalKey),labels:Li.fields.labels.pipe(i.optionalKey),linked:Li.fields.linked.pipe(i.optionalKey)}){},Qi=class extends i.Class(`BoardColumn`)({...Fi.fields,cards:i.Array(Zi)}){},$i=class extends i.Class(`BoardContext`)({board:Pi,columns:i.Array(Qi).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 ea=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:$i,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0);function ta(e,t,n){return Zi.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 na=n.gen(function*(){let e=yield*X;return n.fn(`GetBoardContext`)(function*(t){let r=x.trim(t.board),i=yield*e.call(Ki,Xi(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=Xi(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(qi,{boardId:c.id}),e.call(Ji,{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(Yi,{todoId:t.id}),{concurrency:5}):[],g=O.map(u,(e,t)=>{let n=h[t];return ta(e,n?.name??x.slice(0,e.heading.length-p.length)(e.heading),n)});return $i.make({board:c,columns:O.map(l,e=>Qi.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 ra=class extends i.Class(`RunningTimer`)({running:i.Boolean,summary:i.String.annotate({description:`Orbit's description of the running timer`}).pipe(i.optionalKey)}){};const ia=J(/^No timer is running\./,{}).pipe(i.decodeTo(ra,{decode:j.succeed({running:!1}),encode:j.forbiddenEncoding})),aa=J(/^(?!No )(?<summary>\S.*)$/s,{summary:i.Trim}).pipe(i.decodeTo(ra,{decode:j.transform(({summary:e})=>({running:!0,summary:e})),encode:j.forbiddenEncoding})),oa={name:`GetRunningTimer`,args:i.Record(i.String,i.Never),result:i.Union([ia,aa])};var sa=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 ca=J(/^- (?<date>\S+) \| .+? \| (?<type>(?:(?! \| ).)+) (?<minutes>\d+h\d*) \| (?<state>[A-Z]+)(?: approval)?(?: — (?<note>.+?))? {2}\(api_id: (?<id>[A-Z0-9]{15})\)$/s,{...sa.fields,minutes:K,state:i.Literals([`APPROVED`,`PENDING`,`REFUSED`,`REVOKED`]).pipe(i.decodeTo(sa.fields.state,{decode:j.transform(x.toLowerCase),encode:j.transform(x.toUpperCase)}))}).pipe(i.decodeTo(sa)),la={name:`ListAbsences`,args:i.Struct({dateFrom:W,dateTo:W}),result:Y(ca,/^\d+ absence\(s\):$/,/^Approve\/refuse pending requests/,/^No absences match these filters\.$/)};var ua=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 da=J(/^\| (?<label>(?:(?<projectNumber>\d+) )?.+?) \| (?:unlimited|(?<remainingMinutes>\d+h\d*)) \| (?<id>[A-Z0-9]{15}) \|$/,{...ua.fields,remainingMinutes:K.pipe(i.optionalKey)}).pipe(i.decodeTo(ua)),fa={name:`ListMyTasks`,args:i.Record(i.String,i.Never),result:Y(da,/^\d+ assignable task\(s\):$/,/^\| Project \|/,/^\|---/,/^No assignable tasks found/)},pa=i.Literals([`planned`,`fixed-time`,`request`,`refused`]),ma=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:pa,work:i.String,seriesId:U.pipe(i.optionalKey)}),ha={name:`ListPlannedEntries`,args:i.Struct({dateFrom:W,dateTo:W}),result:Y(ma,/^\d+ planning entries:$/,/^No planning entries match these filters\.$/)},ga=1050;var _a=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}){},va=class extends i.Class(`Overlap`)({first:U,second:U,minutes:G}){},ya=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:pa.annotate({description:`From ListPlannedEntries`}).pipe(i.optionalKey),seriesId:U.pipe(i.optionalKey)}){},ba=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(li).annotate({description:`Entries, after the taskId/kind filters`}),unconfirmedPlanned:i.Array(ya),gaps:i.Array(_a).annotate({description:`Time within working hours without any entry; unconfirmed planned entries count as occupied`}),overlaps:i.Array(va),outsideWorkingHours:i.Array(U).annotate({description:`Entries starting before or ending after working hours`})}){},xa=class extends i.Class(`Workday`)({from:W,to:W,timeZone:i.String,workingHours:_a,totals:i.Struct({capacityMinutes:G,loggedMinutes:G,plannedMinutes:G,absenceMinutes:G,missingMinutes:G}),days:i.Array(ba),absences:i.Array(sa),runningTimer:ra,bookableTasks:i.Array(ua)}){};const Sa=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:ci.annotate({description:`Only list entries of this kind`}).pipe(i.optional)}),success:xa,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0);function Ca(e){return M.makeUnsafe(`${e}T00:00:00Z`)}function wa(e,t){return M.formatIsoDateUtc(M.add(Ca(e),{days:t}))}function Ta(e){return wa(e,-((M.toPartsUtc(Ca(e)).weekDay+6)%7))}function Ea(e){let{hour:t,minute:n}=M.toParts(e);return t*60+n}function Da(e){let t=x.padStart(2,`0`);return`${t(String(Math.floor(e/60)))}:${t(String(e%60))}`}function Oa(e,t){return _a.make({from:Da(e),to:Da(t),minutes:t-e})}function ka(e){let t=Ea(e.start);return{id:e.id,from:t,to:t+e.minutes}}function Aa(e){let t=[],n=540,r=O.sortWith(e,({from:e})=>e,Xe.Number);for(let e of r)e.from>n&&n<ga&&t.push(Oa(n,Math.min(e.from,ga))),n=Math.max(n,e.to);return n<ga?[...t,Oa(n,ga)]:t}function ja(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?[va.make({first:e.id,second:t.id,minutes:Math.min(e.to,t.to)-t.from})]:[]))}function Ma(e,t,n){let i=O.map(e.entries,ka),a=e.capacityMinutes===0||e.absenceMinutes>=e.capacityMinutes;return ba.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[ya.make({...k.pick(e,[`id`,`start`,`minutes`,`work`,`taskId`]),...r.match(n,{onNone:()=>({}),onSome:e=>({planningKind:e.kind,...k.pick(e,[`seriesId`])})})})]}),gaps:a?[]:Aa(i),overlaps:ja(i),outsideWorkingHours:O.flatMap(i,({id:e,from:t,to:n})=>t<540||n>ga?[e]:[])})}const Na=n.gen(function*(){let e=yield*X;return n.fn(`GetMyWorkday`)(function*(t){let i=t.to===void 0&&t.scope===`week`?Ta(t.date):t.date,a=t.to??(t.scope===`week`?wa(i,6):i);if(a<i||a>wa(i,61))return yield*n.fail(H.make({message:`Range ${i}..${a} must be 1 to 62 days.`}));let o=O.unfold(Ta(i),e=>e>a?r.none():r.some([e,wa(e,7)])),s={dateFrom:i,dateTo:a},[c,l,u,d,f]=yield*n.all([n.forEach(o,t=>e.call(xi,{date:t}),{concurrency:4}),e.call(la,s),e.call(ha,s),e.call(oa,{}),e.call(fa,{})],{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,wa(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=>Ma(e,u,t));function g(e){return O.reduce(h,0,(t,n)=>t+n[e])}return xa.make({from:i,to:a,timeZone:Vr,workingHours:Oa(540,ga),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))}),Pa=Ke.make(Sa,Oi,ea,Zr,Mi),Fa=Pa.toLayer(n.all({GetMyWorkday:Na,GetTicketContext:ki,GetBoardContext:na,AddProjectTask:Qr,CloseTicketSilently:Ni})),Ia=i.decodeUnknownEffect(i.JsonObject),La=i.decodeUnknownOption(H.pipe(i.fromJsonString));function Ra(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 za(e){let[t]=`content`in e&&e.isError===!0?e.content:[];return r.match(t?.type===`text`?La(t.text):r.none(),{onNone:()=>e,onSome:({message:e,status:t,retryAfter:n})=>t===429?Ra(n):Ge.CallToolResult.make({isError:!0,content:[{type:`text`,text:e}]})})}const Ba=p.effectDiscard(n.gen(function*(){let e=yield*Ir,t=yield*Be.McpServer;yield*n.forEach(O.filter(e.tools,({name:e})=>!(e in Pa.tools)),n.fn(`OrbitProxyLive.tool`)(function*(r){yield*t.addTool({tool:r,annotations:u.empty(),handle:n.fn(`handle`)(function*(e){return yield*Ia(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(Ra(t)):n.fail(r)),n.mapError(e=>Ge.InternalError.make({message:e.message})))))})}),{discard:!0}),yield*Be.registerToolkit(Pa).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(za))})})})))})).pipe(p.provide(p.provideMerge(Fa,Kr))),Va=n.gen(function*(){let e=yield*pe.Path,t=yield*ut(`gateway.key`);return e.join(t,`gateway.key`)}),Ha=Re.mebibytes(1),Ua=b.empty({status:401,headers:{"www-authenticate":`Bearer`,"cache-control":`no-store`}}),Wa=b.empty({status:403,headers:{"cache-control":`no-store`}}),Ga=new TextEncoder,Ka=i.String.check(i.isPattern(/^[a-f0-9]{64}$/)).pipe(i.RedactedFromValue);var qa=class extends i.TaggedError()(`GatewayError`,{message:i.String}){};const Ja=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*qa.make({message:`Gateway key must be a private file (chmod 600).`}):yield*t.readFileString(e).pipe(n.flatMap(i.decodeEffect(Ka)))},n.mapError(()=>qa.make({message:`Cannot load private gateway key. Check its permissions and format.`})));function Ya(e,t){return e.digest(ee.sha256,Ga.encode(t))}function Xa(e){return p.unwrap(n.gen(function*(){let t=yield*ee.Digest,r=yield*Ya(t,`Bearer ${h.value(e)}`);return le.middleware(e=>n.gen(function*(){let i=yield*de.HttpServerRequest,a=yield*Ya(t,i.headers.authorization??``);return ce.timingSafeEqual(r,a)?i.headers.origin===void 0?yield*e.pipe(n.provideService(He.MaxBodySize,Ha),n.map(e=>b.setHeader(e,`cache-control`,`no-store`))):Wa:Ua}),{global:!0})}))}function Za(e){let t=p.unwrap(n.gen(function*(){let e=yield*Ir;return Ba.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,Xa(e))}const Qa=i.String.check(i.isPattern(/^[a-z0-9]+\.opentunnel\.xyz$/)),$a=i.decodeEffect(Qa),eo=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*$a(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/Predicate";import*as g from"effect/Redacted";import*as _ 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 v 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 y from"effect/Array";import*as b from"effect/Deferred";import*as ce from"effect/Result";import*as x from"effect/String";import*as le from"effect/crypto/Mac";import*as ue from"effect/http/HttpRouter";import*as de from"effect/http/HttpServer";import*as fe from"effect/http/HttpServerRequest";import*as S from"effect/http/HttpServerResponse";import*as pe from"effect/http/HttpStatus";import*as me from"effect/http/Url";import*as he from"effect/FileSystem";import*as ge from"effect/Path";import*as _e from"effect/Stream";import*as ve from"@effect/platform-node/NodeCrypto";import*as ye from"@effect/platform-node/NodeServices";import*as be from"effect/persistence/UserDirectories";import{Context as xe,Effect as C,Layer as w,Option as Se,Queue as Ce,Schema as T,Stream as we}from"effect";import{FetchHttpClient as Te,HttpClient as Ee,HttpClientError as De,HttpClientRequest as Oe}from"effect/http";import{HttpApi as ke,HttpApiClient as Ae,HttpApiEndpoint as E,HttpApiGroup as je,HttpApiMiddleware as Me,HttpApiSchema as Ne,HttpApiSecurity as Pe,OpenApi as Fe}from"effect/http-api";import*as D from"node:fs/promises";import*as Ie from"node:os";import*as O from"node:path";import*as Le from"node:net";import{Duplex as Re}from"node:stream";import*as ze from"node:tls";import*as Be from"effect/net/NetAddress";import*as Ve from"effect/ByteSize";import*as He from"effect/ai/McpProtocol";import*as Ue from"effect/ai/McpServer";import*as We from"effect/encoding/Hex";import*as Ge from"effect/http/HttpIncomingMessage";import*as Ke from"effect/ai/McpClient";import*as qe from"effect/http/HttpClientError";import*as Je from"effect/ai/McpSchema";import*as k from"effect/Struct";import*as Ye 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 Xe from"effect/Record";import*as Ze from"effect/SchemaIssue";import*as Qe from"effect/ai/McpClientError";import*as $e from"effect/Number";import*as et from"effect/Order";const tt=`https://api.orbit.teamleader.eu`,nt=`${tt}/mcp`,rt=i.String.check(i.isMinLength(1)).pipe(i.RedactedFromValue);var it=class extends i.Class(`Session`)({clientId:i.String.check(i.isMinLength(1)),clientSecret:rt.pipe(i.optionalKey),accessToken:rt,refreshToken:rt.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,...h.isUndefined(e.clientSecret)?{}:{clientSecret:e.clientSecret},accessToken:t.accessToken,...h.isUndefined(r)?{}:{refreshToken:r},...h.isUndefined(t.expiresIn)?{}:{expiresAt:n+t.expiresIn*1e3}})}static needsRefresh(e,t){return h.isUndefined(e.expiresAt)||e.expiresAt<=t+6e4}},N=class extends i.TaggedError()(`OrbitAuthError`,{message:i.String,cause:i.Defect().pipe(i.optional)}){};function at(e){return h.isUndefined(e.clientSecret)?{method:`none`,publicClient:!0}:{method:`client_secret_post`,secret:e.clientSecret.pipe(g.value,g.make)}}const ot={"content-type":`text/plain; charset=utf-8`,"cache-control":`no-store`,"referrer-policy":`no-referrer`,"content-security-policy":`default-src 'none'`},st=S.text(`Invalid callback.`,{status:pe.fromLiteral(`BadRequest`),headers:ot}),ct=S.text(`Authorization received. Return to your terminal to complete login.`,{headers:ot}),lt=S.text(`Authorization denied. Return to your terminal.`,{status:pe.fromLiteral(`BadRequest`),headers:ot});function ut(e,t){return y.matchLeft(e.searchParams.getAll(t),{onEmpty:r.none,onNonEmpty:(e,t)=>y.isArrayEmpty(t)?r.some(e):r.none()})}var dt=class extends i.TaggedError()(`InvalidCallback`,{}){};function ft(e,t){let n=new TextEncoder;return e.pathname===`/callback`&&r.exists(ut(e,`state`),e=>le.timingSafeEqual(n.encode(t),n.encode(e)))?e.searchParams.has(`error`)?ce.fail(N.make({message:`Orbit authorization was denied.`})):ce.fromOption(r.filter(ut(e,`code`),x.isNonEmpty),()=>dt.make()):ce.fail(dt.make())}const pt=n.fn(`OrbitAuth.listenForLogin`)(function*(e){let t=yield*b.make(),r=yield*n.sync(oe),i=yield*se.make(()=>r,{port:0,host:`127.0.0.1`}).pipe(n.mapError(e=>N.make({message:`Could not bind OAuth callback.`,cause:e})));if(!h.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*fe.HttpServerRequest;if(r.method!==`GET`||r.headers.host!==a||(yield*b.isDone(t)))return st;let i=me.fromString(r.url,o).pipe(ce.mapError(()=>dt.make()),ce.flatMap(t=>ft(t,e)));return yield*ce.match(i,{onSuccess:e=>b.succeed(t,e).pipe(n.map(e=>e?ct:st)),onFailure:m.typeTags()({InvalidCallback:()=>n.succeed(st),OrbitAuthError:e=>b.fail(t,e).pipe(n.map(e=>e?lt:st))})})}),c=yield*ue.toHttpEffect(ue.add(`*`,`*`,s()));return yield*de.serveEffect(c).pipe(n.provideService(de.HttpServer,i)),yield*n.addFinalizer(()=>n.sync(()=>r.closeAllConnections())),{redirectUri:o,code:b.await(t).pipe(n.timeout(`3 minutes`),n.mapError(e=>N.make({message:`Login denied or timed out. Run tlo-mcp login again.`,cause:e})))}}),mt=p.mergeAll(ye.layer,ve.layerDigest,ve.layerSecureRandom,be.layer),ht=n.fn(`TloMcp.configDirectory`)(function*(e){let t=yield*he.FileSystem,n=yield*ge.Path,r=yield*be.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}),gt=it.pipe(i.fromJsonString),_t=i.decodeEffect(gt),vt=i.encodeEffect(gt),yt=`@2digits/tlo-mcp/orbit`,bt=[`-a`,`orbit`,`-s`,yt];var xt=class extends u.Service()(`@2digits/tlo-mcp/oauth/store/SessionStore`){};function St(e){return`"${x.replaceAll(/["\\]/g,x.String.raw`\$&`)(e)}"`}function Ct(e={}){return p.effect(xt,n.gen(function*(){let t=yield*he.FileSystem,r=yield*ge.Path,i=yield*ae.ChildProcessSpawner,a=e.platform??process.platform,o=e.directory??(yield*ht(`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:h.isUndefined(t)?`ignore`:_e.succeed(new TextEncoder().encode(t)),stderr:`ignore`}));return yield*n.all({output:r.stdout.pipe(_e.decodeText(),_e.mkString),exitCode:r.exitCode},{concurrency:`unbounded`})},n.scoped),d=n.fn(`SessionStore.load`)(function*(){if(a===`darwin`){let e=yield*u([`find-generic-password`,...bt,`-w`]);return e.exitCode===44?void 0:e.exitCode===0?yield*_t(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 h.isUndefined(e)?void 0:yield*_t(e)},n.mapError(e=>N.make({message:`Could not read credentials. Run tlo-mcp login again.`,cause:e}))),f=n.fn(`SessionStore.save`)(function*(e){let n=yield*vt(e);if(a===`darwin`){if((yield*u([`-q`,`-i`],`add-generic-password -U -a orbit -s ${St(yt)} -w ${St(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(e=>N.make({message:`Could not persist OAuth credentials. Run tlo-mcp login again.`,cause:e}))),p=n.fn(`SessionStore.clear`)(function*(){if(a===`darwin`){let e=yield*u([`delete-generic-password`,...bt]);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(e=>N.make({message:`Could not remove OAuth credentials.`,cause:e}))),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 xt.of({load:d(),save:f,clear:p(),lock:m()})}))}const wt=Ct(),Tt=i.Struct({client_id:i.String.check(i.isMinLength(1)),client_secret:i.String.check(i.isMinLength(1)).pipe(i.RedactedFromValue,i.optionalKey)}),Et=i.is(N),Dt=ie.make({stdout:`ignore`,stderr:`ignore`,forceKillAfter:`1 second`});var Ot=class extends u.Service()(`@2digits/tlo-mcp/oauth/OrbitAuth`){};const kt=p.effect(Ot,n.gen(function*(){let e=yield*xt,t=yield*ee.Digest,r=yield*te.SecureRandom,a=yield*v.HttpClient,o=yield*ae.ChildProcessSpawner,u=yield*_.make(1),p=yield*n.fn(`OrbitAuth.discover`)(function*(){let e=yield*v.withScope(a).get(`${tt}/.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(e=>N.make({message:`Invalid or unavailable Orbit OAuth metadata.`,cause:e})))().pipe(n.cachedWithTTL(f.match({onFailure:()=>0,onSuccess:()=>1/0}))),ie=n.fn(`OrbitAuth.accessToken`)(function*(){let t=yield*e.load;if(h.isUndefined(t))return yield*N.make({message:`Not authenticated. Run tlo-mcp login first.`});let r=yield*l.currentTimeMillis;if(!it.needsRefresh(t,r))return t.accessToken;if(h.isUndefined(t.refreshToken))return h.isUndefined(t.expiresAt)?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:at(t),timeoutMs:15e3})).refreshGrant({refreshToken:t.refreshToken,resources:[nt]}).pipe(n.flatMap(s.tokens)),o=yield*l.currentTimeMillis,c=it.update(t,a,o);return yield*e.save(c),c.accessToken}),oe=n.fn(`OrbitAuth.register`)(function*(e){let t=yield*re.post(`${tt}/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(v.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(Tt)))},n.scoped,n.timeout(`15 seconds`)),se=n.fn(`OrbitAuth.openBrowser`)(function*(e){return yield*(yield*m.value(process.platform).pipe(m.when(`darwin`,()=>Dt`open ${e}`),m.when(`win32`,()=>Dt`rundll32 url.dll,FileProtocolHandler ${e}`),m.orElse(()=>Dt`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${g.value(t)}\n`)})))),y=n.fn(`OrbitAuth.login`)(function*(){let t=yield*p,r=yield*c.random(),i=yield*c.make(),a=yield*r.pipe(g.value,pt),o=yield*oe(a.redirectUri),u={clientId:o.client_id,...h.isUndefined(o.client_secret)?{}:{clientSecret:o.client_secret}},d=yield*s.make({metadata:t,...u,authentication:at(u),timeoutMs:15e3}),f=yield*d.authorizationUrl({redirectUri:a.redirectUri,scopes:[],state:r,codeChallenge:i.challenge,resources:[nt]});yield*se(f);let m=yield*a.code,_=yield*d.codeGrant({code:g.make(m),redirectUri:a.redirectUri,pkceVerifier:i.verifier,resources:[nt]}).pipe(n.flatMap(s.tokens)),ee=yield*l.currentTimeMillis;yield*e.save(it.update(u,_,ee)),yield*n.sync(()=>{process.stderr.write(`Orbit login complete.
|
|
3
|
+
`)})}),b=n.fn(`OrbitAuth.locked`)(function*(t){return yield*e.lock,yield*t},n.scoped,u.withPermit,n.provideService(v.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=>Et(e)?e:N.make({message:`Orbit authentication unavailable. Check connectivity or run tlo-mcp login again.`,cause:e})));return Ot.of({accessToken:b(ie()),login:b(y()),logout:b(e.clear)})})).pipe(p.provide(wt),p.provide(ne.layer)),At=8e3,jt=(e,t)=>t===`idempotent`?e===429||e>=500&&e<=599:[429,503,521,522,523,525].includes(e),Mt=(e,t)=>{let n=t?.trim();if(n&&/^\d+$/.test(n)){let e=Math.min(Number(n)*1e3,At);return[e,e]}let r=Math.min(250*2**Math.min(e,16),At);return[r/2,r]},Nt={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`},Pt=e=>Nt[e],Ft=(e,t)=>{let n=Pt(e);if(n)return`Cloudflare ${e}: ${n}`;let r=t.trim();return r?Array.from(r).slice(0,200).join(``):`HTTP ${e}`},It=T.String.pipe(T.brand(`CSR.Raw`)),Lt=T.String.pipe(T.brand(`Hostname`));function Rt(){return(e,t)=>{class n{static makeUnsafe(e){return e}}return Object.setPrototypeOf(n,t),n}}var zt=class extends Rt()(`CertificateID`,T.String){};T.String.pipe(T.brand(`ChallengeToken`));var Bt=class extends T.Class(`Certificate/StateChallenge`)({type:T.Literal(`challenge`),token:T.String,key:T.String}){},Vt=class extends T.Class(`Certificate/StateIssuing`)({type:T.Literal(`issuing`)}){},Ht=class extends T.Class(`Certificate/StateReady`)({type:T.Literal(`ready`),certificate:T.String,chain:T.String,expiry:T.String}){},Ut=class extends T.Class(`Certificate/StateFailed`)({type:T.Literal(`failed`),reason:T.String}){};const Wt=T.Union([Bt,Vt,Ht,Ut]);var Gt=class extends T.Class(`Certificate`)({id:zt,state:Wt}){},P=class extends Rt()(`TunnelID`,T.String){};const Kt=T.String.pipe(T.brand(`TunnelToken`));T.TaggedError()(`NotFound`,{tunnelID:P}),T.TaggedError()(`NoCertificate`,{tunnelID:P}),T.TaggedError()(`CertificateNotReady`,{tunnelID:P,currentState:T.String}),T.TaggedError()(`InvalidHostname`,{provided:Lt,expected:Lt});const qt=T.Literals([`offline`,`online`]);var Jt=class extends T.Class(`Tunnel/Info`)({id:P,hostname:Lt,state:qt,certificateID:zt.pipe(T.optional)}){},Yt=`0.6.2`,Xt=class extends T.TaggedError()(`InvalidRequestError`,{message:T.String},{httpApiStatus:400}){},Zt=class extends T.TaggedError()(`UnauthorizedError`,{message:T.String},{httpApiStatus:401}){},Qt=class extends T.TaggedError()(`TunnelNotFoundError`,{tunnelID:T.String,message:T.String},{httpApiStatus:404}){},$t=class extends T.TaggedError()(`CertificateNotFoundError`,{tunnelID:T.String,message:T.String},{httpApiStatus:404}){},en=class extends T.TaggedError()(`InvalidHostnameError`,{provided:T.String,expected:T.String,message:T.String},{httpApiStatus:400}){},tn=class extends T.TaggedError()(`HostnameUnavailableError`,{name:T.String,message:T.String},{httpApiStatus:409}){},nn=class extends T.TaggedError()(`CertificateInProgressError`,{tunnelID:T.String,message:T.String},{httpApiStatus:409}){},rn=class extends T.TaggedError()(`ServiceUnavailableError`,{message:T.String},{httpApiStatus:503}){};xe.Service()(`@opentunnel/protocol/OpenTunnelAuthorizationToken`);var an=class extends Me.Service()(`@opentunnel/protocol/OpenTunnelAuthorization`,{security:{bearer:Pe.bearer},error:Zt}){};const on=T.Struct({name:T.String.pipe(T.optional)}),sn=T.Struct({tunnel:Jt,token:Kt}).pipe(Ne.status(201)),cn=je.make(`tunnel`).add(E.post(`tunnel.create`,`/api/tunnel`,{payload:on,success:sn,error:[Xt,tn,rn]})).add(E.get(`tunnel.get`,`/api/tunnel/:id`,{params:T.Struct({id:P}),success:Jt,error:[Qt,rn]}).middleware(an)).add(E.post(`tunnel.bindCertificate`,`/api/tunnel/:id/certificate`,{params:T.Struct({id:P}),payload:T.Struct({csr:It}),success:Gt.pipe(Ne.status(202)),error:[Xt,en,Qt,nn,rn]}).middleware(an)).add(E.get(`tunnel.getCertificate`,`/api/tunnel/:id/certificate`,{params:T.Struct({id:P}),success:Gt,error:[Qt,$t,rn]}).middleware(an)).add(E.delete(`tunnel.remove`,`/api/tunnel/:id`,{params:T.Struct({id:P}),success:Ne.NoContent,error:[Qt,rn]}).middleware(an)).add(E.get(`tunnel.connect`,`/api/tunnel/:id/connect`,{params:T.Struct({id:P}),success:T.Boolean,error:[Qt]}).annotateMerge(Fe.annotations({summary:`Connect a bridge WebSocket`,description:`This endpoint upgrades to the opentunnel WebSocket protocol.`}))).annotateMerge(Fe.annotations({title:`tunnel`})),ln=ke.make(`opentunnel`).add(cn).annotateMerge(Fe.annotations({title:`OpenTunnel API`,version:`0.1.0`,description:`Create and manage blind TLS tunnels.`})),un=`opentunnel-sdk/${Yt}`,dn=/* @__PURE__ */ new Set([`ConnectionRefused`,`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`FailedToOpenSocket`,`UND_ERR_CONNECT_TIMEOUT`]),fn=e=>{if(typeof e!=`object`||!e)return;let{code:t,cause:n}=e;return typeof t==`string`?t:fn(n)},pn=e=>e.method===`GET`||e.method===`POST`&&e.url.endsWith(`/certificate`)?`idempotent`:`once`,mn=(e,t)=>De.isHttpClientError(e)&&e.reason._tag===`TransportError`&&(t===`idempotent`||dn.has(fn(e.reason.cause)??``)),hn=e=>Ee.transform(e,(e,t)=>{let n=pn(t),r=(e,t)=>{let[n,r]=Mt(e,t);return C.sleep(n+Math.random()*(r-n))},i=t=>C.matchEffect(e,{onFailure:e=>t<6&&mn(e,n)?C.andThen(r(t),()=>i(t+1)):C.fail(e),onSuccess:e=>t<6&&jt(e.status,n)?C.andThen(r(t,e.headers[`retry-after`]),()=>i(t+1)):C.succeed(e)});return i(0)});var gn=class e extends xe.Service()(`@opentunnel/client/OpenTunnelApiClient`){static layer(t){return w.effect(e,C.gen(function*(){let e=(yield*Ee.HttpClient).pipe(Ee.mapRequest(Oe.setHeader(`user-agent`,un)),hn);return{client:yield*Ae.makeWith(ln,{baseUrl:t.api,httpClient:e}),authorized:n=>Ae.makeWith(ln,{baseUrl:t.api,httpClient:e.pipe(Ee.mapRequest(Oe.bearerToken(n)))})}})).pipe(w.provide(t.fetch?Te.layer.pipe(w.provide(w.succeed(Te.Fetch,t.fetch))):Te.layer))}};const F=(e,...t)=>{let n=_n(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 _n([new Uint8Array([e,...r]),n])},_n=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),vn=(...e)=>F(49,...e),yn=e=>F(12,new TextEncoder().encode(e)),bn=e=>F(130,new TextEncoder().encode(e)),xn=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))},Sn=e=>{let t=0;for(;t<e.length-1&&e[t]===0;)t++;let n=e.subarray(t);return F(2,n[0]&128?_n([new Uint8Array([0]),n]):n)};async function Cn(e,t){let n=new Uint8Array(await crypto.subtle.exportKey(`spki`,t.publicKey)),r=I(F(2,new Uint8Array([0])),I(vn(I(xn(`2.5.4.3`),yn(e)))),n,F(160,I(xn(`1.2.840.113549.1.9.14`),vn(I(I(xn(`2.5.29.17`),F(4,I(bn(e),bn(`*.${e}`))))))))),i=new Uint8Array(await crypto.subtle.sign({name:`ECDSA`,hash:`SHA-256`},t.privateKey,r)),a=I(Sn(i.subarray(0,32)),Sn(i.subarray(32))),o=I(r,I(xn(`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 wn=class extends T.TaggedError()(`OpenTunnelClientError`,{message:T.String,code:T.optional(T.String),cause:T.optional(T.Defect())}){},L=class extends T.TaggedError()(`OpenTunnelStorageError`,{message:T.String,cause:T.optional(T.Defect())}){};function Tn(e={}){let t=e.env??process.env,n=e.home??Ie.homedir(),r=t.XDG_DATA_HOME??O.join(n,`.local`,`share`),i=O.join(r,`opentunnel`),a=e=>O.join(i,e),o=e=>C.tryPromise({try:()=>D.readFile(e,`utf8`),catch:e=>e}).pipe(C.catch(t=>C.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=C.fn(`OpenTunnelStorage.profiles`)(function*(){return(yield*C.tryPromise({try:()=>D.readdir(i,{withFileTypes:!0}),catch:e=>e}).pipe(C.catch(e=>C.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=C.fn(`OpenTunnelStorage.load`)(function*(e){let t=a(e),n=yield*o(O.join(t,`tunnel.json`));if(!n)return;let[r,i,s,c]=yield*C.all([o(O.join(t,`token`)),o(O.join(t,`private-key.pem`)),o(O.join(t,`certificate.pem`)),o(O.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=C.fn(`OpenTunnelStorage.loadPending`)(function*(e){let t=a(e),n=yield*o(O.join(t,`pending.json`));if(!n)return;let[r,i]=yield*C.all([o(O.join(t,`token`)),o(O.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)=>C.tryPromise({try:async()=>{let n=a(e);await D.mkdir(n,{recursive:!0,mode:448}),await Promise.all([D.writeFile(O.join(n,`pending.json`),JSON.stringify({id:t.id,hostname:t.hostname,csr:t.csr},null,2),{mode:384}),D.writeFile(O.join(n,`token`),`${t.token}\n`,{mode:384}),D.writeFile(O.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)=>C.tryPromise({try:async()=>{let n=a(e);await D.mkdir(n,{recursive:!0,mode:448}),await Promise.all([D.writeFile(O.join(n,`tunnel.json`),JSON.stringify({id:t.id,hostname:t.hostname,certificateExpiry:t.certificateExpiry.toISOString()},null,2),{mode:384}),D.writeFile(O.join(n,`token`),`${t.token}\n`,{mode:384}),D.writeFile(O.join(n,`private-key.pem`),t.privateKey,{mode:384}),D.writeFile(O.join(n,`certificate.pem`),t.certificate,{mode:384}),D.writeFile(O.join(n,`chain.pem`),t.chain,{mode:384})]),await D.rm(O.join(n,`pending.json`),{force:!0})},catch:t=>new L({message:`Failed to save tunnel identity for ${e}`,cause:t})}),remove:e=>C.tryPromise({try:()=>D.rm(a(e),{recursive:!0,force:!0}),catch:t=>new L({message:`Failed to remove tunnel identity for ${e}`,cause:t})}),list:()=>s().pipe(C.flatMap(e=>C.forEach(e,e=>c(e).pipe(C.map(t=>t?{profile:e,tunnel:t}:void 0)))),C.map(e=>e.filter(e=>e!==void 0)))}}const En=/* @__PURE__ */ new Set([`http:`,`https:`]),Dn=(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(!En.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},On=e=>e.protocol===`https:`||e.protocol===`wss:`,kn=(e,t)=>{let[n,r]=e.split(`/`,2),i=Le.isIP(n);if(i===0||Le.isIP(t)!==i)return!1;let a=i===4?`ipv4`:`ipv6`,o=new Le.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)},An=(e,t)=>{let n=e.hostname.toLowerCase().replace(/^\[(.*)\]$/,`$1`),r=e.port===``?On(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(kn(t,n))return!0;let o=t.replace(/^\*?\./,``);if(o!==``&&(n===o||n.endsWith(`.${o}`)))return!0}return!1},jn=(e,t)=>{let n=(On(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&&!An(e,t.NO_PROXY||t.no_proxy||``))return Dn(t[n],n)},Mn=(e,t)=>new WebSocket(e,t),Nn=(e,t)=>((n,r)=>e(n,{...r,...t})),Pn=()=>{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})}},Fn=()=>`Bun`in globalThis?`bun`:`Deno`in globalThis?`deno`:`node`,In=(e,t=process.env)=>{let n=e===void 0?void 0:Dn(e,`The proxy option`).href;switch(Fn()){case`bun`:return{...n===void 0?{}:{fetch:Nn(globalThis.fetch,{proxy:n})},webSocket:(e,r,i)=>{let a=n??jn(e,t)?.href;return Mn(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:Nn(globalThis.fetch,{client:e}),webSocket:(t,n,r)=>Mn(t,{protocols:n,headers:r,client:e})}}case`node`:{if(n===void 0)break;let e=Pn(),t=new e.ProxyAgent({uri:n,proxyTunnel:!0});return{fetch:Nn(e.fetch,{dispatcher:t}),webSocket:(n,r,i)=>new e.WebSocket(n,{protocols:r,headers:i,dispatcher:t})}}}return{webSocket:(e,t,n)=>Mn(e,{protocols:t,headers:n})}},Ln=T.Int.check(T.isBetween({minimum:0,maximum:4294967295}));var Rn=class extends T.Class(`BridgeProtocol/ClientInfo`)({version:T.String,max_conns:T.Number}){},zn=class extends T.Class(`BridgeProtocol/AttachMessage`)({type:T.Literal(`attach`),token:T.String,transport:T.Literal(`ws`),client:Rn,routes:T.Array(T.String).pipe(T.optional)}){},Bn=class extends T.Class(`BridgeProtocol/AttachedMessage`)({type:T.Literal(`attached`),session:T.String,routes:T.Array(T.String),heartbeat_ms:T.Number,idle_timeout_ms:T.Number}){},Vn=class extends T.Class(`BridgeProtocol/AttachErrorMessage`)({type:T.Literal(`attach_error`),code:T.String}){},Hn=class extends T.Class(`BridgeProtocol/PingMessage`)({type:T.Literal(`ping`),time_sent:T.Number}){},Un=class extends T.Class(`BridgeProtocol/PongMessage`)({type:T.Literal(`pong`),time_sent:T.Number}){},Wn=class extends T.Class(`BridgeProtocol/DrainMessage`)({type:T.Literal(`drain`),reason:T.String}){},Gn=class extends T.Class(`BridgeProtocol/OpenMessage`)({type:T.Literal(`open`),conn:Ln,peer:T.String,sni:T.String,alpn:T.String}){},Kn=class extends T.Class(`BridgeProtocol/EndMessage`)({type:T.Literal(`end`),conn:Ln}){},qn=class extends T.Class(`BridgeProtocol/ResetMessage`)({type:T.Literal(`reset`),conn:Ln,code:T.String}){};T.Union([zn,Hn,Un,Wn,Kn,qn]);const Jn=T.Union([Bn,Vn,Hn,Un,Wn,Gn,Kn,qn]),Yn=T.decodeUnknownOption(Jn);function Xn(e){try{return Yn(JSON.parse(e))}catch{return Se.none()}}T.Union([zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn]);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`},Zn={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 $n(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 er=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,tr=e=>e===`@`||er.test(e),nr=(e,t)=>e===`@`?t:`${e}.${t}`,rr=(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 er.test(a)?a:void 0},ir=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}},ar=e=>e===`v1`||e===`v2`,or=Uint8Array.of(13,10,13,10,0,13,10,81,85,73,84,10),sr=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},cr=(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=sr(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},lr=e=>{let t=e.indexOf(`::`),n;if(t===-1){if(n=cr(e,!0),n?.length!==8)return}else{if(e.indexOf(`::`,t+1)!==-1)return;let r=cr(e.slice(0,t),!1),i=cr(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},ur=e=>{if(!/^[0-9]{1,5}$/.test(e))return;let t=Number(e);return t<=65535?t:void 0},dr=e=>e.subarray(0,10).every(e=>e===0)&&e[10]===255&&e[11]===255,fr=(e,t)=>e.length===16&&dr(e)?{family:4,bytes:e.slice(12),port:t}:e.length===4?{family:4,bytes:e,port:t}:{family:6,bytes:e,port:t},pr=e=>{let t=sr(e)??lr(e);if(t)return fr(t,0);if(e.startsWith(`[`)){let t=e.indexOf(`]:`);if(t===-1)return;let n=lr(e.slice(1,t)),r=ur(e.slice(t+2));return n&&r!==void 0?fr(n,r):void 0}let n=e.lastIndexOf(`:`);if(n===-1)return;let r=sr(e.slice(0,n)),i=ur(e.slice(n+1));return r&&i!==void 0?fr(r,i):void 0},mr=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))}`},hr=new TextEncoder,gr=(e,t,n)=>{let r=pr(t);return e===`v1`?_r(r):vr(r,n)},_r=e=>{if(!e)return hr.encode(`PROXY UNKNOWN\r
|
|
5
|
+
`);let[t,n]=e.family===4?[`TCP4`,`0.0.0.0`]:[`TCP6`,`::`];return hr.encode(`PROXY ${t} ${mr(e)} ${n} ${e.port} 443\r\n`)},vr=(e,t)=>{let n=hr.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(or,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},yr=e=>tr(e),br=(e,t)=>`https://${nr(e,t)}`,xr=(e,t)=>Object.fromEntries(Object.keys(e).map(e=>[e,br(e,t)]));var Sr=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 Cr=/* @__PURE__ */ new Set([R.BAD_TOKEN,R.CERT_NOT_READY]),wr=/* @__PURE__ */ new Set([`target`,`proxyProtocol`]),Tr=(e,t)=>{if(!yr(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(!wr.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(!ar(i.proxyProtocol))throw Error(`Invalid proxyProtocol '${String(i.proxyProtocol)}' for route '${e}': use "v1" or "v2"`);r=i.proxyProtocol}}let i=typeof n==`string`?ir(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}},Er=e=>{for(let[t,n]of Object.entries(e))Tr(t,n)},Dr=e=>new Map(Object.entries(e).map(([e,t])=>[e,Tr(e,t)])),Or=e=>ze.createSecureContext({key:e.privateKey,cert:`${e.certificate}\n${e.chain}`}),kr=(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])},Ar=e=>{let t=Math.min(Zn.RECONNECT_BACKOFF_MIN_MS*2**Math.min(e,16),Zn.RECONNECT_BACKOFF_MAX_MS);return Math.round(t/2+t/2*Math.random())};var jr=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=Dr(e.routes),this.transport=e.transport??In(),this.routes={...e.routes},this.identity=e.identity,this.secureContext=Or(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=Or(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 xr(this.routes,this.identity.hostname)}setRoutes(e){let t=Dr(e),n=this.routes;this.resolved=t,this.routes={...e},this.status.routes=this.routes,kr(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 Mr(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=Ar(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}}},Mr=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":un})}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}),Zn.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=Xn(e);if(Se.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(Cr.has(n.code)||e&&this.options.onRouteConflict===`fail`?{type:`fatal`,error:new Sr(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=rr(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:gr(i.proxyProtocol,n,t),o=new Nr(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($n(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))}}},Nr=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 Re({allowHalfOpen:!0,read(){},write:(t,n,r)=>a.sendData(e,t,r),final:t=>{a.sendControl({type:`end`,conn:e}),t()}}),this.tls=new ze.TLSSocket(this.raw,{isServer:!0,secureContext:i}),this.tls.on(`secure`,()=>{let e=Le.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`,Pr=e=>{if(De.isHttpClientError(e)){let t=e.response;if(!t)return e.message;let n=Ft(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=Pr(t);return new wn({message:n?`${e}: ${n}`:e,cause:t})},Fr=(e,t)=>{let n=Pr(t);return new wn({message:n?`${e}: ${n}`:e,...t instanceof Sr?{code:t.code}:{},cause:t})},Ir=e=>De.isHttpClientError(e)&&(e.reason._tag===`TransportError`||e.response!==void 0&&jt(e.response.status,`idempotent`)),Lr=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`},Rr=e=>{try{return In(e)}catch(e){throw new wn({message:e instanceof Error?e.message:String(e),cause:e})}};var zr=class e extends xe.Service()(`@opentunnel/client/OpenTunnelClient`){static layer(t={}){let n=t.storage??Tn(),r=Rr(t.proxy),i=t.api??(process.env.OPENTUNNEL_API||`https://opentunnel.xyz`);return w.effect(e,C.gen(function*(){let e=yield*gn,t=new URL(i),a=C.fn(`OpenTunnelClient.tunnel.get`)(function*(e){return yield*n.load(B(e))}),o=C.fn(`OpenTunnelClient.tunnel.completePending`)(function*(t){let r=yield*e.authorized(Kt.make(t.pending.token));yield*C.sync(()=>t.onProgress?.(`requesting-certificate`)),yield*r.tunnel[`tunnel.bindCertificate`]({params:{id:P.make(t.pending.id)},payload:{csr:t.pending.csr}}).pipe(C.catchTag(`CertificateInProgressError`,()=>C.void),C.mapError(e=>V(`Failed to start certificate issuance`,e)));let i=yield*C.gen(function*(){for(;;){yield*C.sync(()=>t.onProgress?.(`waiting-certificate`));let e=yield*r.tunnel[`tunnel.getCertificate`]({params:{id:P.make(t.pending.id)}}).pipe(C.mapError(e=>V(`Failed to read certificate`,e)));if(e.state.type===`ready`)return e.state;if(e.state.type===`failed`)return yield*new wn({message:`Certificate issuance failed: ${e.state.reason}`});yield*C.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*C.sync(()=>t.onProgress?.(`saving-identity`)),yield*n.save(t.profile,a),yield*C.sync(()=>t.onProgress?.(`ready`)),a}),s=C.fn(`OpenTunnelClient.tunnel.provision`)(function*(e){yield*C.sync(()=>e.onProgress?.(`generating-key`));let t=yield*C.tryPromise({try:()=>crypto.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!0,[`sign`,`verify`]),catch:e=>V(`Failed to generate certificate key`,e)});yield*C.sync(()=>e.onProgress?.(`generating-csr`));let r=yield*C.tryPromise({try:()=>Cn(e.hostname,t),catch:e=>V(`Failed to generate certificate request`,e)}),i=yield*C.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:Lr(i),csr:r};return yield*n.savePending(e.profile,a),yield*o({profile:e.profile,pending:a,onProgress:e.onProgress})}),c=C.fn(`OpenTunnelClient.tunnel.create`)(function*(t){let r=B(t);if(yield*n.load(r))return yield*new wn({message:`Profile '${r}' already has a tunnel`});let i=yield*n.loadPending(r);if(i)return yield*C.sync(()=>t?.onProgress?.(`resuming-certificate`)),yield*o({profile:r,pending:i,onProgress:t?.onProgress});yield*C.sync(()=>t?.onProgress?.(`creating-tunnel`));let a=yield*e.client.tunnel[`tunnel.create`]({payload:{}}).pipe(C.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=C.fn(`OpenTunnelClient.tunnel.ensure`)(function*(t){let r=yield*a(t);if(!r)return yield*c(t);let i=e=>C.sync(()=>t?.onProgress?.(e));yield*i(`checking-certificate`);let o=yield*(yield*e.authorized(Kt.make(r.token))).tunnel[`tunnel.getCertificate`]({params:{id:P.make(r.id)}}).pipe(C.catchIf(e=>Ir(e)&&r.certificateExpiry.getTime()>Date.now(),()=>C.succeed(void 0)),C.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:Kt.make(r.token),onProgress:t?.onProgress}):(yield*i(`ready`),r)}),u=C.fn(`OpenTunnelClient.tunnel.pending`)(function*(e){let t=yield*n.loadPending(B(e));return t?{id:t.id,hostname:t.hostname}:void 0}),d=C.fn(`OpenTunnelClient.tunnel.resume`)(function*(e){let t=B(e),r=yield*n.loadPending(t);if(r)return yield*C.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:C.fn(`OpenTunnelClient.tunnel.remove`)(function*(t){let r=B(t),i=yield*n.load(r);i&&(yield*(yield*e.authorized(Kt.make(i.token))).tunnel[`tunnel.remove`]({params:{id:P.make(i.id)}}).pipe(C.mapError(e=>V(`Failed to remove tunnel`,e))),yield*n.remove(r))}),connect:C.fn(`OpenTunnelClient.tunnel.connect`)(function*(e){yield*C.try({try:()=>Er(e.routes),catch:e=>V(e instanceof Error?e.message:`Invalid routes`,e)});let i=yield*l({profile:e.profile}),a=yield*Ce.unbounded(),o=yield*C.acquireRelease(C.sync(()=>new jr({api:t,identity:i,routes:e.routes,onRouteConflict:e.onRouteConflict,transport:r,onEvent:t=>{e.onEvent?.(t),Ce.offerUnsafe(a,t),t.type===`stopped`&&Ce.endUnsafe(a)},onRenewed:t=>{C.runFork(n.save(B(e),t).pipe(C.ignore))}})),e=>C.promise(()=>e.close()).pipe(C.andThen(Ce.end(a))));return yield*C.tryPromise({try:()=>o.ready,catch:e=>Fr(`Failed to connect tunnel`,e)}).pipe(C.onInterrupt(()=>C.promise(()=>o.close()))),{tunnel:i,events:we.fromQueue(a),status:C.sync(()=>o.getStatus()),urls:C.sync(()=>o.getUrls()),setRoutes:e=>C.try({try:()=>o.setRoutes(e),catch:e=>V(e instanceof Error?e.message:`Invalid routes`,e)}),closed:C.tryPromise({try:()=>o.closed,catch:e=>Fr(`Tunnel stopped`,e)}),close:C.promise(()=>o.close())}})}}})).pipe(w.provide(gn.layer({api:i,...r.fetch?{fetch:r.fetch}:{}})))}};const Br=/* @__PURE__ */ `GetTimesheetWeek.GetTimesheetStatus.ListTimeEntries.GetTimeEntry.CreateTimeEntry.UpdateTimeEntry.MoveTimeEntry.SplitTimeEntry.DeleteTimeEntry.ConfirmPlannedEntry.SubmitTimesheet.GetRunningTimer.StartTimer.StopTimer.ListMyTasks.SearchProjectItems.ListPlannableTasks.ListProjects.GetProject.GetProjectOpenItems.ListRates.AddProjectTask.CloseProjectTask.UpdateProject.UpdateProjectTask.ListPlannedEntries.GetPlannedEntry.GetPlannerBoard.ListAbsences.ListReservations.FindFreeCapacity.ListTickets.GetTicket.GetTicketDetail.ListTicketComments.AddInternalComment.ReplyToTicket.CloseTicket.CloseTicketSilently.SetTicketOwner.LinkTicketToProject.ListBoards.ListBoardLists.ListTodos.GetTodo.GetTodoDetail.MoveTodo.ListMessages.AddMessage.ListUsers.SearchCrm`.split(`.`);var Vr=class extends u.Service()(`@2digits/tlo-mcp/mcp/OrbitClient`){};const Hr=p.effect(v.HttpClient,n.gen(function*(){let e=yield*Ot;return yield*e.accessToken,(yield*v.HttpClient).pipe(v.mapRequestEffect(t=>e.accessToken.pipe(n.mapBoth({onSuccess:e=>re.bearerToken(t,e),onFailure:e=>new qe.HttpClientError({reason:new qe.TransportError({request:t,cause:e,description:e.message})})}))),v.transform(n.provideService(ne.RequestInit,{redirect:`error`})))})).pipe(p.provide(ne.layer)),Ur=y.containsWith((e,t)=>(h.isString(e)?e:e.name)===(h.isString(t)?t:t.name)),Wr=p.effect(Vr,n.gen(function*(){let e=yield*Ke.McpClient,t=yield*e.listTools().pipe(n.map(y.filter(e=>Ur(Br,e)))),r=y.filter(Br,e=>!Ur(t,e));return y.isReadonlyArrayNonEmpty(r)&&(yield*n.logWarning(`Orbit no longer offers these exposed tools: ${y.join(r,`, `)}`)),Vr.of({tools:t,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(Ke.layerHttp({name:`@2digits/tlo-mcp`,version:`1.0.0`,protocol:He.v2025_11_25,url:nt})),p.provide(Hr));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 Gr=i.is(H);function U(e){if(Gr(e))return e;let t=h.isTagged(e,`McpClientError`)&&h.isTagged(e.reason,`HttpError`)?e.reason:void 0;return H.make({message:e.message,...h.isUndefined(t)?{}:k.pick(t,[`status`,`retryAfter`])})}const Kr=`Europe/Amsterdam`,W=i.String.check(i.isPattern(/^[A-Z0-9]{15}$/u)).annotate({description:`Orbit api_id`}),qr=i.String.check(i.isPattern(/^PR[A-Z0-9]{13}$/u)).annotate({description:`Project api_id, starting with PR`}),G=i.String.check(i.isPattern(/^PT[A-Z0-9]{13}$/u)).annotate({description:`Project task api_id, starting with PT`}),Jr=i.String.check(i.isPattern(/^US[A-Z0-9]{13}$/u)).annotate({description:`User api_id, starting with US`});function K(e){return i.String.pipe(i.decodeTo(i.String.pipe(i.NullOr),{decode:j.transform(t=>t===e?null:t),encode:j.transform(t=>t??e)}))}const Yr=i.String.pipe(i.decodeTo(i.NonEmptyArray(i.String).pipe(i.NullOr),{decode:j.transform(e=>e===``?null:x.split(e,`,`)),encode:j.transform(e=>h.isNull(e)?``:y.join(e,`,`))})),q=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`}),J=i.Int.check(i.isGreaterThanOrEqualTo(0)),Y=i.String.check(i.isPattern(/^\d+h(?:[0-5]\d)?$/)).pipe(i.decodeTo(J,{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))}`)})),Xr=i.String.pipe(i.decodeTo(i.DateTimeZoned,{decode:j.transformEffect((e,t)=>{let i=x.replace(` `,`T`)(e);return M.makeZoned(`${i}:00Z`,{timeZone:Kr,adjustForTimeZone:!0}).pipe(r.filter(e=>e.pipe(M.formatIsoZoned,x.startsWith(`${i}:00`))),n.fromOption,n.mapError(()=>new Ze.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 X(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 h.isNull(i)?n.fail(new Ze.InvalidValue({message:`Unexpected line: ${JSON.stringify(t)}`},t,r)):n.succeed(Xe.filter(i.groups??{},h.isNotUndefined))}),encode:j.forbiddenEncoding}))}function Z(e,...t){return i.String.pipe(i.decodeTo(i.Array(e),{decode:j.transform(e=>y.filter(x.split(e,`\r
|
|
7
|
+
`),e=>x.isNonEmpty(x.trim(e))&&!y.some(t,t=>t.test(e)))),encode:j.forbiddenEncoding}))}var Zr=class extends i.Class(`ProjectTaskAdded`)({taskId:W.annotate({description:`api_id of the new task, for CreateTimeEntry or StartTimer`}).pipe(i.optionalKey),projectId:W.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 Qr=i.String.pipe(i.decodeTo(Zr,{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,...h.isUndefined(t)?{}:{taskId:t},...h.isUndefined(n)?{}:{projectId:n}}}),encode:j.forbiddenEncoding})),$r={name:`AddProjectTask`,args:i.Struct({projectId:i.String,name:i.String,description:i.String.pipe(i.optionalKey),workloadHours:i.Finite.pipe(i.optionalKey),startDate:i.String.pipe(i.optionalKey),endDate:i.String.pipe(i.optionalKey),assignees:Yr.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:K(`NONE`).pipe(i.optionalKey)}).pipe(i.encodeKeys({startDate:`startDt`,endDate:`endDt`,assignees:`assignedTo`})),result:Qr},ei=i.decodeUnknownEffect(i.Tuple([i.Struct({type:i.Literal(`text`),text:i.String})]));var Q=class extends u.Service()(`@2digits/tlo-mcp/orbit/Orbit`){};const ti=p.effect(Q,n.gen(function*(){let e=yield*Vr;function t(t,a){return n.gen(function*(){let n=y.findFirst(e.tools,({name:e})=>e===t.name);if(r.isNone(n))return yield*Qe.McpClientError.make({reason:Qe.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(y.some(s.content,e=>e.type===`text`&&x.startsWith(`Error: `)(e.text))||s.isError===!0)return yield*Qe.McpClientError.make({reason:Qe.ToolError.make({result:s})});let[{text:c}]=yield*ei(s.content);return yield*i.decodeEffect(t.result)(c)}).pipe(n.withSpan(`Orbit.${t.name}`))}return Q.of({call:t})})),ni=i.String.check(i.isTrimmed(),i.isNonEmpty()),ri=i.Finite.check(i.isGreaterThanOrEqualTo(0)),ii=i.String.check(i.isPattern(/^\S+$/u)).annotate({description:`Project number the user sees, such as "2238"`}),ai=ni.check(i.isPattern(/^[^,]+$/u)).annotate({description:`Unique user name`}),oi=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([W,ii]).annotate({description:`Project api_id or project number`}),name:ni.annotate({description:`Task name as shown in the project and in time entries`}),description:ni.annotate({description:`Task description`}).pipe(i.optionalKey),workloadHours:ri.annotate({description:`Budgeted hours; per invoicing period when recurring. Omit for no budget`}).pipe(i.optionalKey),startDate:q.annotateKey({description:`Start date as yyyy-MM-dd`}).pipe(i.optionalKey),endDate:q.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([W,ai]).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:W.annotate({description:`Chapter api_id from GetProject; omit for the root level`}).pipe(i.optionalKey),rateId:W.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:W.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:Zr,failure:H,failureMode:`return`}).annotate(A.Readonly,!1).annotate(A.Destructive,!1).annotate(A.Idempotent,!1),si=n.gen(function*(){let e=yield*Q;return n.fn(`AddProjectTask`)(function*(t){let{startDate:r,endDate:i}=t;return h.isNotUndefined(r)&&h.isNotUndefined(i)&&i<r?yield*n.fail(H.make({message:`endDate ${i} is before startDate ${r}.`})):yield*e.call($r,t)},n.mapError(U))}),ci={name:`CloseProjectTask`,args:i.Struct({taskId:G,force:i.Boolean.pipe(i.optionalKey)}),result:i.String},li=i.Literals([0,1]).pipe(i.decodeTo(i.Boolean,{decode:j.transform(e=>e===1),encode:j.transform(e=>+!!e)})),ui=i.Struct({name:i.String.pipe(i.optionalKey),description:i.String.pipe(i.optionalKey),purchaseOrder:i.String.pipe(i.optionalKey),startDate:i.String.pipe(i.optionalKey),endDate:K(``).pipe(i.optionalKey),fixedPrice:i.Finite.pipe(i.optionalKey),ownerId:K(``).pipe(i.optionalKey),folderId:i.String.pipe(i.optionalKey),dealId:K(`0`).pipe(i.optionalKey),analyticalCategoryId:K(``).pipe(i.optionalKey)}).pipe(i.encodeKeys({name:`NAME`,description:`DESCRIPTION`,purchaseOrder:`PO`,startDate:`START_DT`,endDate:`END_DT`,fixedPrice:`BILLING_BUDGET`,ownerId:`OWNERID`,folderId:`FOLDERID`,dealId:`DEALID`,analyticalCategoryId:`ACATID`})),di={name:`UpdateProject`,args:i.Struct({projectId:i.String,fieldsJson:ui.pipe(i.fromJsonString)}),result:i.String},fi=i.Struct({name:i.String.pipe(i.optionalKey),description:i.String.pipe(i.optionalKey),workloadHours:i.Finite.pipe(i.optionalKey),rateId:i.String.pipe(i.optionalKey),rate:i.Finite.pipe(i.optionalKey),startDate:i.String.pipe(i.optionalKey),endDate:K(``).pipe(i.optionalKey),recurring:li.pipe(i.optionalKey),billingMode:i.String.pipe(i.optionalKey),assignees:Yr.pipe(i.optionalKey),retainerId:K(`NONE`).pipe(i.optionalKey),analyticalCategoryId:K(``).pipe(i.optionalKey)}).pipe(i.encodeKeys({name:`NAME`,description:`DESCRIPTION`,workloadHours:`WORKLOAD`,rateId:`RATEID`,rate:`RATE`,startDate:`START_DT`,endDate:`END_DT`,recurring:`RECURRING`,billingMode:`BILLING_MODE`,assignees:`ASSIGNEDTO`,retainerId:`RETAINERID`,analyticalCategoryId:`ACATID`})),pi={name:`UpdateProjectTask`,args:i.Struct({taskId:G,fieldsJson:fi.pipe(i.fromJsonString)}),result:i.String};var mi=class extends i.Class(`ProjectTaskCloseResult`)({taskId:G,message:i.String.annotate({description:`Orbit's answer: a confirmation, or the warnings that stopped the close. Warnings mean the task is still open`})}){};const hi=A.make(`CloseProjectTask`,{description:`Close (complete) a project task, for example one added by mistake; Orbit cannot delete tasks. Orbit first runs the Desk checks, such as remaining workload and open planning. Warnings are returned WITHOUT closing: show them to the user and call again with force true only when the user still wants to close it. Hard blockers, such as open planned hours, refuse even with force. ReopenProjectTask is not available through this gateway.`,parameters:i.Struct({taskId:G.annotate({description:`Project task api_id (starts with PT), from GetProject`}),force:i.Boolean.annotate({description:`Close despite the warnings of a previous call. Only after the user confirmed those warnings`}).pipe(i.optionalKey)}),success:mi,failure:H,failureMode:`return`}).annotate(A.Readonly,!1).annotate(A.Destructive,!1).annotate(A.Idempotent,!0),gi=n.gen(function*(){let e=yield*Q;return n.fn(`CloseProjectTask`)(function*(t){let n=yield*e.call(ci,t);return mi.make({taskId:t.taskId,message:n})},n.mapError(U))}),$=i.String.pipe(i.NullOr),_i=Xr.pipe(i.NullOr);var vi=class extends i.Class(`TicketSummary`)({ticketId:W,number:i.String,name:i.String,state:i.String}){},yi=class extends i.Class(`TicketDetail`)({ticketId:W,number:i.String,name:i.String,description:i.String,state:i.String,priority:i.String,category:$,queue:$,client:$,clientId:W.pipe(i.NullOr),contact:$,owner:$,assignee:$,project:$,projectId:W.pipe(i.NullOr),task:$,taskId:W.pipe(i.NullOr),loggedMinutes:J,invoicedMinutes:J,billable:i.Boolean,slaResponseDue:_i,slaCloseDue:_i,followUpAction:$,followUpDate:_i,createdDate:Xr,closedDate:_i,lastClientInput:_i,lastAgentReply:_i,attachments:i.Array(i.Struct({fileId:W,name:i.String,downloadUrl:i.String})),downloadLinksNote:i.String.pipe(i.optionalKey),otherOpenTicketsOfClient:i.Array(vi)}){},bi=class extends i.Class(`TicketComment`)({commentId:W,date:Xr,isInternal:i.Boolean,author:$,title:$,content:i.String,loggedMinutes:J,timeEntryId:W.pipe(i.NullOr)}){};const xi=i.Struct({count:i.Int,tickets:i.Array(vi)}),Si=i.Struct({count:i.Int,comments:i.Array(bi)}),Ci={name:`ListTickets`,args:i.Struct({query:i.String,state:i.String,limit:i.Int}),result:xi.pipe(i.fromJsonString)},wi={name:`GetTicketDetail`,args:i.Struct({ticketId:W}),result:yi.pipe(i.fromJsonString)},Ti={name:`ListTicketComments`,args:i.Struct({ticketId:W,limit:i.Int}),result:Si.pipe(i.fromJsonString)},Ei={name:`CloseTicketSilently`,args:i.Struct({ticketId:W}),result:i.String},Di={name:`SetTicketOwner`,args:i.Struct({ticketId:W,user:Jr}),result:i.String},Oi={name:`LinkTicketToProject`,args:i.Struct({ticketId:W,taskId:i.Union([G,i.Literal(``)])}),result:i.String},ki=i.Literals([`logged`,`planned`,`absence`]);var Ai=class extends i.Class(`TimeEntry`)({id:W,start:Xr,minutes:J,kind:ki,work:i.String.annotate({description:`Project / task, ticket or absence type as Orbit shows it`}),description:i.String.pipe(i.optionalKey),taskId:W.pipe(i.optionalKey),ticketId:W.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}){},ji=class extends i.Class(`TimesheetDay`)({date:q,weekday:i.String,state:i.Literals([`OPEN`,`FINAL`]),loggedMinutes:J,plannedMinutes:J,absenceMinutes:J,capacityMinutes:J,entries:i.Array(Ai)}){},Mi=class extends i.Class(`TimesheetWeek`)({weekOf:q,userId:W,days:i.Array(ji)}){};const Ni={id:W,minutes:Y,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:W.pipe(i.optionalKey),ticketId:W.pipe(i.optionalKey),lock:i.String.pipe(i.optionalKey)};function Pi(e,t){let{planned:n,absence:r}=t;return{...k.pick(t,[`id`,`minutes`,`work`,`description`,`taskId`,`ticketId`,`lock`]),start:e,kind:Fi(n,r),...h.isUndefined(r)?{}:{pendingApproval:r===`ABSENCE (pending approval)`},editable:h.isUndefined(t.lock)}}function Fi(e,t){return h.isNotUndefined(t)?`absence`:h.isUndefined(e)?`logged`:`planned`}const Ii=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`],Li=i.Literals(Ii),Ri=`| Day | State | Logged | Planned | Absence | Capacity |`,zi=i.Struct({header:X(/^Timesheet week of (?<weekOf>\S+) for .+ \(user api_id: (?<userId>[A-Z0-9]{15})\)$/,{weekOf:q,userId:W}),days:i.Array(X(/^\| (?<weekday>\w+) (?<date>\S+) \| (?<state>[A-Z]+) \| (?<loggedMinutes>\S+) \| (?<plannedMinutes>\S+) \| (?<absenceMinutes>\S+) \| (?<capacityMinutes>\S+) \|$/,{weekday:Li,date:q,state:ji.fields.state,loggedMinutes:Y,plannedMinutes:Y,absenceMinutes:Y,capacityMinutes:Y})).check(i.isBetweenLength(7,7)),columns:i.Array(i.String).check(i.isBetweenLength(1,1)),entries:i.Array(X(/^- (?<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:Li,time:i.String,...Ni}))}).check(i.makeFilter(({header:e,days:t})=>y.every(t,(t,n)=>t.weekday===Ii[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`})),Bi=[/^\|---/,/^Week total: /,/^Entries:$/,/^Planned entries can be confirmed/];function Vi(e){let[t=``,...n]=y.filter(x.split(e,`\r
|
|
8
|
+
`),e=>x.isNonEmpty(x.trim(e))&&!y.some(Bi,t=>t.test(e))),r=x.startsWith(`- `);return{header:t,columns:y.filter(n,e=>e===Ri),days:y.filter(n,e=>e!==Ri&&!r(e)),entries:y.filter(n,r)}}const Hi={name:`GetTimesheetWeek`,args:i.Struct({date:q}),result:i.String.pipe(i.decodeTo(zi,{decode:j.transform(Vi),encode:j.forbiddenEncoding}),i.decodeTo(Mi,{decode:j.transform(({header:e,days:t,entries:n})=>k.assign(e,{days:y.map(t,e=>k.assign(e,{entries:y.map(y.filter(n,({weekday:t})=>t===e.weekday),({time:t,...n})=>Pi(`${e.date} ${t}`,n))}))})),encode:j.forbiddenEncoding}))},Ui=X(/^- (?<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,...Ni}).pipe(i.decodeTo(Ai,{decode:j.transform(({start:e,...t})=>Pi(e,t)),encode:j.forbiddenEncoding})),Wi=i.Struct({entries:Z(Ui,/^\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`})}),Gi={name:`ListTimeEntries`,args:i.Struct({dateFrom:q,dateTo:q,text:i.String.pipe(i.optionalKey)}),result:i.String.pipe(i.decodeTo(Wi,{decode:j.transform(e=>({entries:e,truncated:/^\d+ time entries \(more exist/.test(e)})),encode:j.forbiddenEncoding}))},Ki=/^[A-Z0-9]{15}$/,qi=m.type().pipe(m.when({kind:`logged`},({minutes:e})=>e),m.orElse(()=>0)),Ji=i.String.check(i.isPattern(/^\d+$/u)).annotate({description:`Ticket number the user sees, such as "9481"`}),Yi=i.Union([W,Ji]).annotate({description:`Ticket api_id or ticket number`}),Xi=n.fn(`findTicketId`)(function*(e,t){let i=x.trim(t);if(Ki.test(i))return i;let{tickets:a}=yield*e.call(Ci,{query:i,state:`NEW|OPEN|WAIT|CLOSED|DELETED|REQCLOSE`,limit:100}),o=y.findFirst(a,({number:e})=>e===i);return r.isNone(o)?yield*n.fail(H.make({message:a.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.`})):o.value.ticketId});var Zi=class extends i.Class(`TicketContext`)({ticket:yi,comments:i.Array(bi).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(Ai).annotate({description:`Your entries booked on this ticket`}),timeEntriesTruncated:i.Boolean.annotate({description:`Orbit capped the entry search at 100 rows`}),loggedMinutes:J.annotate({description:`Sum of the logged timeEntries; planned entries are not counted`}),mentionedIn:i.Array(W).annotate({description:`Your other entries whose description mentions the ticket number`})}){};const Qi=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 the write tools (ReplyToTicket, AddInternalComment, SetTicketOwner, LinkTicketToProject, CloseTicket, CloseTicketSilently) for changes.`,parameters:i.Struct({ticket:i.String.annotate({description:`Ticket number such as "9087", or the ticket api_id`})}),success:Zi,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0),$i=n.gen(function*(){let e=yield*Q;return n.fn(`GetTicketContext`)(function*({ticket:t}){let r=yield*Xi(e,t),[i,a]=yield*n.all([e.call(wi,{ticketId:r}),e.call(Ti,{ticketId:r,limit:100})],{concurrency:`unbounded`}),o=yield*M.now,s=yield*e.call(Gi,{dateFrom:M.formatIsoDate(i.createdDate),dateTo:M.formatIsoDate(M.setZoneNamedUnsafe(o,Kr)),text:i.number});function c({work:e,description:t=``}){let[n]=x.split(t,` `);return x.startsWith(`ticket "`)(e)&&n===i.number}function l({work:e,description:t=``}){return y.contains(x.split(`${e} ${t}`,/\D+/),i.number)}let u=y.filter(s.entries,c),d=y.filter(s.entries,e=>!c(e)&&l(e));return Zi.make({ticket:i,comments:a.comments,commentCount:a.count,commentsTruncated:a.comments.length>=100,timeEntries:u,timeEntriesTruncated:s.truncated,loggedMinutes:$e.sumAll(y.map(u,qi)),mentionedIn:y.map(d,({id:e})=>e)})},n.mapError(U))});var ea=class extends i.Class(`TicketClosedSilently`)({ticketId:W.annotate({description:`api_id of the closed ticket`}),message:i.String.annotate({description:`Orbit's confirmation`})}){};const ta=A.make(`CloseTicketSilently`,{description:`Close a ticket WITHOUT notifying the client: no closing message is sent and nothing is added to the conversation the client sees. Use it for tickets that need no answer, such as automatic reports or emails that only copied the support address. Use CloseTicket when the client should get a closing message. Only open tickets can be closed; Orbit rejects a ticket that is already closed.`,parameters:i.Struct({ticket:Yi}),success:ea,failure:H,failureMode:`return`}).annotate(A.Readonly,!1).annotate(A.Destructive,!1).annotate(A.Idempotent,!0),na=n.gen(function*(){let e=yield*Q;return n.fn(`CloseTicketSilently`)(function*({ticket:t}){let n=yield*Xi(e,t),r=yield*e.call(Ei,{ticketId:n});return ea.make({ticketId:n,message:r})},n.mapError(U))});var ra=class extends i.Class(`Board`)({id:W,name:i.String,listCount:i.Int,cardCount:i.Int,ownerId:W}){},ia=class extends i.Class(`BoardList`)({id:W,name:i.String,cardCount:i.Int,done:i.Boolean.annotate({description:`Final column: cards here count as done`})}){};const aa={id:W,boardId:W,listId:W,list:i.String,done:i.Boolean,due:q.pipe(i.optionalKey),ownerId:W.pipe(i.optionalKey),priority:i.String.annotate({description:`As Orbit shows it, e.g. "high" or "medium"`}).pipe(i.optionalKey)};var oa=class extends i.Class(`Card`)(k.assign(aa,{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.`})})){},sa=class extends i.Class(`CardDetail`)(k.assign(aa,{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:W,name:i.String})),linked:i.Array(i.Struct({type:i.String,id:W,summary:i.String}))})){};const ca=i.FiniteFromString.check(i.isInt()),la=i.String.pipe(i.optionalKey,i.decodeTo(i.Boolean,{decode:j.transformOptional(e=>e.pipe(r.isSome,r.some)),encode:j.forbiddenEncoding})),ua=X(/^- (?<id>[A-Z0-9]{15}) \| (?<name>.+) \| lists (?<listCount>\d+), cards (?<cardCount>\d+) \| owner (?<ownerId>[A-Z0-9]{15})$/,{...ra.fields,listCount:ca,cardCount:ca}).pipe(i.decodeTo(ra)),da=X(/^- (?<id>[A-Z0-9]{15}) \| (?<name>.+?) \| cards (?<cardCount>\d+)(?<done> \| FINAL\/done)?$/,{...ia.fields,cardCount:ca,done:la}).pipe(i.decodeTo(ia)),fa=X(/^- (?<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))?$/,{...oa.fields,done:la}).pipe(i.decodeTo(oa)),pa=/^(?:Owner|Description|Checklist|Label): /,ma=i.Struct({header:X(/^Card (?<id>[A-Z0-9]{15}) — (?<name>.+)$/,{id:W,name:i.String}),board:X(/^Board\/list: .+ \((?<boardId>[A-Z0-9]{15})\) \/ (?<list>.+?) \((?<listId>[A-Z0-9]{15})\)(?<done> \(done\))?$/,{boardId:W,list:i.String,listId:W,done:la}),owner:X(/^Owner: (?:(?<ownerId>[A-Z0-9]{15})|unassigned)(?: \| due (?<due>\S+))?(?: \| priority (?<priority>[a-z]+))?$/,{ownerId:aa.ownerId,due:aa.due,priority:aa.priority}).pipe(i.optionalKey),description:X(/^Description: (?<text>.*)$/s,{text:i.String}).pipe(i.optionalKey),checklist:X(/^Checklist: (?<text>.*)$/,{text:i.String}).pipe(i.optionalKey),labels:i.Array(X(/^Label: (?<name>.+) \((?<id>[A-Z0-9]{15})\)$/,{id:W,name:i.String})),linked:i.Array(X(/^- (?<type>[A-Z_]+) (?<id>[A-Z0-9]{15}) \| (?<summary>.+)$/,{type:i.String,id:W,summary:i.Trim}))});function ha(e){let[t=``,n=``,...r]=y.filter(x.split(e,`\r
|
|
9
|
+
`),e=>x.isNonEmpty(x.trim(e))&&e!==`Linked:`);return{header:t,board:n,...Xe.getSomes({owner:y.findFirst(r,x.startsWith(`Owner: `)),description:y.findFirst(r,x.startsWith(`Description: `)),checklist:y.findFirst(r,x.startsWith(`Checklist: `))}),labels:y.filter(r,x.startsWith(`Label: `)),linked:y.filter(r,e=>!pa.test(e))}}const ga={name:`ListBoards`,args:i.Struct({search:i.String.pipe(i.optionalKey),limit:i.Int}),result:Z(ua,/^\d+ board\(s\):$/,/^No boards found\.$/)},_a={name:`ListBoardLists`,args:i.Struct({boardId:W}),result:Z(da)},va={name:`ListTodos`,args:i.Struct({boardId:W,state:i.Literals([`open`,`all`]),limit:i.Int}),result:Z(fa,/^\d+ card\(s\):$/,/^No cards match\.$/)},ya={name:`GetTodoDetail`,args:i.Struct({todoId:W}),result:i.String.pipe(i.decodeTo(ma,{decode:j.transform(ha),encode:j.forbiddenEncoding}),i.decodeTo(sa,{decode:j.transform(({header:e,board:t,owner:n,description:r,checklist:i,labels:a,linked:o})=>({...e,...t,...n,...h.isUndefined(r)?{}:{description:r.text},...h.isUndefined(i)?{}:{checklist:i.text},labels:a,linked:o})),encode:j.forbiddenEncoding}))},ba=i.is(W);var xa=class extends i.Class(`BoardCard`)(k.assign(aa,{name:i.String,description:i.String.pipe(i.optionalKey),checklist:i.String.pipe(i.optionalKey),labels:sa.fields.labels.pipe(i.optionalKey),linked:sa.fields.linked.pipe(i.optionalKey)})){},Sa=class extends i.Class(`BoardColumn`)({...ia.fields,cards:i.Array(xa)}){},Ca=class extends i.Class(`BoardContext`)({board:ra,columns:i.Array(Sa).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 wa=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:Ca,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0);function Ta(e,t,n){return xa.make({...k.pick(e,[`id`,`boardId`,`listId`,`list`,`done`,`due`,`ownerId`,`priority`]),name:t,...h.isUndefined(n)?{}:k.pick(n,[`description`,`checklist`,`labels`,`linked`])})}const Ea=n.gen(function*(){let e=yield*Q;return n.fn(`GetBoardContext`)(function*(t){let r=x.trim(t.board),i=yield*e.call(ga,ba(r)?{limit:100}:{search:r,limit:100}),a=y.filter(i,({id:e})=>e===r),o=y.filter(i,({name:e})=>x.toLowerCase(e)===x.toLowerCase(r)),s=ba(r)?a:y.isReadonlyArrayNonEmpty(o)?o:i,[c]=s;if(h.isUndefined(c)||s.length>1)return yield*n.fail(H.make({message:h.isUndefined(c)?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: ${y.join(y.map(s,({id:e,name:t})=>`${t} (${e})`),`; `)}. Pass the board api_id.`}));let[l,u]=yield*n.all([e.call(_a,{boardId:c.id}),e.call(va,{boardId:c.id,state:t.includeDone?`all`:`open`,limit:100})],{concurrency:`unbounded`}),d=new Set(y.map(l,({id:e})=>e)),f=y.filter(u,({listId:e})=>!d.has(e));if(y.isReadonlyArrayNonEmpty(f))return yield*n.fail(H.make({message:`The board changed while it was read: ${y.join(y.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=y.filter(u,({heading:e})=>!x.endsWith(p)(e));if(!t.details&&y.isReadonlyArrayNonEmpty(m))return yield*n.fail(H.make({message:`Cannot split the card name from board "${c.name}" in: ${y.join(y.map(m,({heading:e})=>JSON.stringify(e)),`; `)}. Call again with details: true.`}));let g=t.details?yield*n.forEach(u,t=>e.call(ya,{todoId:t.id}),{concurrency:5}):[],_=y.map(u,(e,t)=>{let n=g[t];return Ta(e,n?.name??x.slice(0,e.heading.length-p.length)(e.heading),n)});return Ca.make({board:c,columns:y.map(l,e=>Sa.make({id:e.id,name:e.name,cardCount:e.cardCount,done:e.done,cards:y.filter(_,({listId:t})=>t===e.id)})),cardsTruncated:u.length>=100})},n.mapError(U))});var Da=class extends i.Class(`RunningTimer`)({running:i.Boolean,summary:i.String.annotate({description:`Orbit's description of the running timer`}).pipe(i.optionalKey)}){};const Oa=X(/^No timer is running\./,{}).pipe(i.decodeTo(Da,{decode:j.succeed({running:!1}),encode:j.forbiddenEncoding})),ka=X(/^(?!No )(?<summary>\S.*)$/s,{summary:i.Trim}).pipe(i.decodeTo(Da,{decode:j.transform(({summary:e})=>({running:!0,summary:e})),encode:j.forbiddenEncoding})),Aa={name:`GetRunningTimer`,args:i.Record(i.String,i.Never),result:i.Union([Oa,ka])};var ja=class extends i.Class(`Absence`)({id:W,date:q,type:i.String.annotate({description:`Absence type, e.g. "Holiday" or "Office Closed"`}),minutes:J,state:i.Literals([`approved`,`pending`,`refused`,`revoked`]),note:i.String.pipe(i.optionalKey)}){};const Ma=X(/^- (?<date>\S+) \| .+? \| (?<type>(?:(?! \| ).)+) (?<minutes>\d+h\d*) \| (?<state>[A-Z]+)(?: approval)?(?: — (?<note>.+?))? {2}\(api_id: (?<id>[A-Z0-9]{15})\)$/s,{...ja.fields,minutes:Y,state:i.Literals([`APPROVED`,`PENDING`,`REFUSED`,`REVOKED`]).pipe(i.decodeTo(ja.fields.state,{decode:j.transform(x.toLowerCase),encode:j.transform(x.toUpperCase)}))}).pipe(i.decodeTo(ja)),Na={name:`ListAbsences`,args:i.Struct({dateFrom:q,dateTo:q}),result:Z(Ma,/^\d+ absence\(s\):$/,/^Approve\/refuse pending requests/,/^No absences match these filters\.$/)};var Pa=class extends i.Class(`BookableTask`)({id:W,label:i.String.annotate({description:`Project and task; Orbit separates both with " | ", as inside names`}),projectNumber:i.String.pipe(i.optionalKey),remainingMinutes:J.annotate({description:`Remaining budget; absent when unlimited`}).pipe(i.optionalKey)}){};const Fa=X(/^\| (?<label>(?:(?<projectNumber>\d+) )?.+?) \| (?:unlimited|(?<remainingMinutes>\d+h\d*)) \| (?<id>[A-Z0-9]{15}) \|$/,{...Pa.fields,remainingMinutes:Y.pipe(i.optionalKey)}).pipe(i.decodeTo(Pa)),Ia={name:`ListMyTasks`,args:i.Record(i.String,i.Never),result:Z(Fa,/^\d+ assignable task\(s\):$/,/^\| Project \|/,/^\|---/,/^No assignable tasks found/)},La=i.Literals([`planned`,`fixed-time`,`request`,`refused`]),Ra=X(/^- (?<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:W,start:Xr,minutes:Y,kind:La,work:i.String,seriesId:W.pipe(i.optionalKey)}),za={name:`ListPlannedEntries`,args:i.Struct({dateFrom:q,dateTo:q}),result:Z(Ra,/^\d+ planning entries:$/,/^No planning entries match these filters\.$/)},Ba=1050;var Va=class extends i.Class(`TimeSlot`)({from:i.String.annotate({description:`HH:mm, Europe/Amsterdam`}),to:i.String.annotate({description:`HH:mm, Europe/Amsterdam`}),minutes:J}){},Ha=class extends i.Class(`Overlap`)({first:W,second:W,minutes:J}){},Ua=class extends i.Class(`UnconfirmedPlanned`)({id:W.annotate({description:`Entry api_id for ConfirmPlannedEntry`}),start:Xr,minutes:J,work:i.String,taskId:W.pipe(i.optionalKey),planningKind:La.annotate({description:`From ListPlannedEntries`}).pipe(i.optionalKey),seriesId:W.pipe(i.optionalKey)}){},Wa=class extends i.Class(`WorkdayDay`)({date:q,weekday:i.String,state:i.Literals([`OPEN`,`FINAL`]),capacityMinutes:J,loggedMinutes:J,plannedMinutes:J,absenceMinutes:J,missingMinutes:J.annotate({description:`Capacity minus logged and absence time`}),dayOff:i.Boolean.annotate({description:`No capacity, or absence covers it`}),entries:i.Array(Ai).annotate({description:`Entries, after the taskId/kind filters`}),unconfirmedPlanned:i.Array(Ua),gaps:i.Array(Va).annotate({description:`Time within working hours without any entry; unconfirmed planned entries count as occupied`}),overlaps:i.Array(Ha),outsideWorkingHours:i.Array(W).annotate({description:`Entries starting before or ending after working hours`})}){},Ga=class extends i.Class(`Workday`)({from:q,to:q,timeZone:i.String,workingHours:Va,totals:i.Struct({capacityMinutes:J,loggedMinutes:J,plannedMinutes:J,absenceMinutes:J,missingMinutes:J}),days:i.Array(Wa),absences:i.Array(ja),runningTimer:Da,bookableTasks:i.Array(Pa)}){};const Ka=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:q.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:q.annotate({description:`Optional last day of the range, inclusive (yyyy-MM-dd)`}).pipe(i.optional),taskId:W.annotate({description:`Only list entries on this task api_id`}).pipe(i.optional),kind:ki.annotate({description:`Only list entries of this kind`}).pipe(i.optional)}),success:Ga,failure:H,failureMode:`return`}).annotate(A.Readonly,!0).annotate(A.Destructive,!1).annotate(A.Idempotent,!0);function qa(e){return M.makeUnsafe(`${e}T00:00:00Z`)}function Ja(e,t){return M.formatIsoDateUtc(M.add(qa(e),{days:t}))}function Ya(e){return Ja(e,-((M.toPartsUtc(qa(e)).weekDay+6)%7))}function Xa(e){let{hour:t,minute:n}=M.toParts(e);return t*60+n}function Za(e){let t=x.padStart(2,`0`);return`${t(String(Math.floor(e/60)))}:${t(String(e%60))}`}function Qa(e,t){return Va.make({from:Za(e),to:Za(t),minutes:t-e})}function $a(e){let t=Xa(e.start);return{id:e.id,from:t,to:t+e.minutes}}function eo(e){let t=[],n=540,r=y.sortWith(e,({from:e})=>e,et.Number);for(let e of r)e.from>n&&n<Ba&&t.push(Qa(n,Math.min(e.from,Ba))),n=Math.max(n,e.to);return n<Ba?[...t,Qa(n,Ba)]:t}function to(e){let t=y.sortWith(e,({from:e})=>e,et.Number);return y.flatMap(t,(e,n)=>y.flatMap(y.drop(t,n+1),t=>t.from<e.to?[Ha.make({first:e.id,second:t.id,minutes:Math.min(e.to,t.to)-t.from})]:[]))}function no(e,t,n){let i=y.map(e.entries,$a),a=e.capacityMinutes===0||e.absenceMinutes>=e.capacityMinutes;return Wa.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:y.filter(e.entries,e=>(h.isUndefined(n.taskId)||e.taskId===n.taskId)&&(h.isUndefined(n.kind)||e.kind===n.kind)),unconfirmedPlanned:y.flatMap(e.entries,m.type().pipe(m.when({kind:`planned`},e=>[Ua.make(k.assign(k.pick(e,[`id`,`start`,`minutes`,`work`,`taskId`]),r.match(y.findFirst(t,({id:t})=>t===e.id),{onNone:()=>({}),onSome:e=>({planningKind:e.kind,...k.pick(e,[`seriesId`])})})))]),m.orElse(()=>[]))),gaps:a?[]:eo(i),overlaps:to(i),outsideWorkingHours:y.flatMap(i,({id:e,from:t,to:n})=>t<540||n>Ba?[e]:[])})}const ro=n.gen(function*(){let e=yield*Q;return n.fn(`GetMyWorkday`)(function*(t){let i=h.isUndefined(t.to)&&t.scope===`week`?Ya(t.date):t.date,a=t.to??(t.scope===`week`?Ja(i,6):i);if(a<i||a>Ja(i,61))return yield*n.fail(H.make({message:`Range ${i}..${a} must be 1 to 62 days.`}));let o=y.unfold(Ya(i),e=>e>a?r.none():r.some([e,Ja(e,7)])),s={dateFrom:i,dateTo:a},[c,l,u,d,f]=yield*n.all([n.forEach(o,t=>e.call(Hi,{date:t}),{concurrency:4}),e.call(Na,s),e.call(za,s),e.call(Aa,{}),e.call(Ia,{})],{concurrency:`unbounded`}),p=y.filter(y.flatMap(c,e=>e.days),e=>e.date>=i&&e.date<=a),m=y.unfold(i,e=>e>a?r.none():r.some([e,Ja(e,1)]));if(y.join(y.map(p,({date:e})=>e),`,`)!==y.join(m,`,`))return yield*n.fail(H.make({message:`Orbit's timesheets do not cover every day of ${i}..${a}.`}));let g=y.map(p,e=>no(e,u,t));function _(e){return y.reduce(g,0,(t,n)=>t+n[e])}return Ga.make({from:i,to:a,timeZone:Kr,workingHours:Qa(540,Ba),totals:{capacityMinutes:_(`capacityMinutes`),loggedMinutes:_(`loggedMinutes`),plannedMinutes:_(`plannedMinutes`),absenceMinutes:_(`absenceMinutes`),missingMinutes:_(`missingMinutes`)},days:g,absences:l,runningTimer:d,bookableTasks:f})},n.mapError(U))});var io=class extends i.Class(`TicketLinked`)({ticketId:W.annotate({description:`api_id of the ticket`}),taskId:G.pipe(i.NullOr).annotate({description:`The linked project task, or null when unlinked`}),message:i.String.annotate({description:`Orbit's confirmation`})}){};const ao=A.make(`LinkTicketToProject`,{description:`Link a ticket to a PROJECT TASK, so time logged on the ticket is booked on that task. Orbit also moves the ticket's existing uninvoiced time to the task. It takes a task, not a project: find the task api_id with GetProject or SearchProjectItems. Pass taskId null to unlink. GetTicketDetail shows the current link.`,parameters:i.Struct({ticket:Yi,taskId:G.pipe(i.NullOr).annotate({description:`Project task api_id (starts with PT), or null to unlink the ticket`})}),success:io,failure:H,failureMode:`return`}).annotate(A.Readonly,!1).annotate(A.Destructive,!1).annotate(A.Idempotent,!0),oo=n.gen(function*(){let e=yield*Q;return n.fn(`LinkTicketToProject`)(function*({ticket:t,taskId:n}){let r=yield*Xi(e,t),i=yield*e.call(Oi,{ticketId:r,taskId:n??``});return io.make({ticketId:r,taskId:n,message:i})},n.mapError(U))});var so=class extends i.Class(`TicketOwnerSet`)({ticketId:W.annotate({description:`api_id of the ticket`}),ownerId:Jr.annotate({description:`api_id of the new owner`}),message:i.String.annotate({description:`Orbit's confirmation`})}){};const co=A.make(`SetTicketOwner`,{description:`Make a user the OWNER of a ticket: the person responsible for it. This is not the assignee; ReplyToTicket's assignToUser changes who works on it. The new owner must be an agent on the ticket's queue, or Orbit refuses. GetTicketDetail shows the current owner.`,parameters:i.Struct({ticket:Yi,owner:Jr.annotate({description:`User api_id of the new owner (starts with US), from ListUsers or SearchCrm`})}),success:so,failure:H,failureMode:`return`}).annotate(A.Readonly,!1).annotate(A.Destructive,!1).annotate(A.Idempotent,!0),lo=n.gen(function*(){let e=yield*Q;return n.fn(`SetTicketOwner`)(function*({ticket:t,owner:n}){let r=yield*Xi(e,t),i=yield*e.call(Di,{ticketId:r,user:n});return so.make({ticketId:r,ownerId:n,message:i})},n.mapError(U))});var uo=class extends i.Class(`ProjectUpdated`)({project:i.String.annotate({description:`The project as given: api_id or project number`}),message:i.String.annotate({description:`Orbit's confirmation`})}){};const fo=A.make(`UpdateProject`,{description:`Change header fields of a project; fields left out stay unchanged. Orbit recalculates the end date to cover the project's tasks and milestones, so an endDate before those dates does not stick: move the task dates with UpdateProjectTask first. The billing mode, retainer, client entity, color and custom fields cannot be changed here. Check the result with GetProject.`,parameters:i.Struct({project:i.Union([qr,ii]).annotate({description:`Project api_id or project number`}),changes:i.Struct({name:ni.annotate({description:`Project name`}).pipe(i.optionalKey),description:i.String.annotate({description:`Project description`}).pipe(i.optionalKey),purchaseOrder:i.String.annotate({description:`The client's purchase order (PO) number`}).pipe(i.optionalKey),startDate:q.annotateKey({description:`Start date as yyyy-MM-dd`}).pipe(i.optionalKey),endDate:q.pipe(i.NullOr).annotateKey({description:`End date as yyyy-MM-dd, not before startDate; null clears it`}).pipe(i.optionalKey),fixedPrice:i.Finite.check(i.isGreaterThanOrEqualTo(0)).annotate({description:`The agreed fixed price (billing budget). FIXED-price projects only: other billing modes calculate their budget from the project content`}).pipe(i.optionalKey),ownerId:Jr.pipe(i.NullOr).annotate({description:`User api_id of the new owner (starts with US), or null to remove the owner`}).pipe(i.optionalKey),folderId:W.annotate({description:`Folder api_id`}).pipe(i.optionalKey),dealId:W.pipe(i.NullOr).annotate({description:`Deal api_id, or null to unlink the deal`}).pipe(i.optionalKey),analyticalCategoryId:W.pipe(i.NullOr).annotate({description:`Analytical category api_id, or null for none, so the project folder's category applies`}).pipe(i.optionalKey)}).check(i.isMinProperties(1)).annotate({description:`The fields to change; at least one`})}),success:uo,failure:H,failureMode:`return`}).annotate(A.Readonly,!1).annotate(A.Destructive,!1).annotate(A.Idempotent,!0),po=n.gen(function*(){let e=yield*Q;return n.fn(`UpdateProject`)(function*({project:t,changes:r}){let{startDate:i,endDate:a}=r;if(h.isNotUndefined(i)&&h.isNotNullish(a)&&a<i)return yield*n.fail(H.make({message:`endDate ${a} is before startDate ${i}.`}));let o=yield*e.call(di,{projectId:t,fieldsJson:r});return uo.make({project:t,message:o})},n.mapError(U))});var mo=class extends i.Class(`ProjectTaskUpdated`)({taskId:G,message:i.String.annotate({description:`Orbit's confirmation`})}){};const ho=A.make(`UpdateProjectTask`,{description:`Change fields of a project task; fields left out stay unchanged. Moving task dates is how a project's end date moves earlier, because Orbit stretches the project end over its tasks. Use CloseProjectTask to close a task. Check the result with GetProject.`,parameters:i.Struct({taskId:G.annotate({description:`Project task api_id (starts with PT), from GetProject`}),changes:i.Struct({name:ni.annotate({description:`Task name as shown in the project and in time entries`}).pipe(i.optionalKey),description:i.String.annotate({description:`Task description`}).pipe(i.optionalKey),workloadHours:ri.annotate({description:`Budgeted hours; per invoicing period when the task is recurring`}).pipe(i.optionalKey),rateId:W.annotate({description:`Rate card api_id from ListRates`}).pipe(i.optionalKey),rate:i.Finite.check(i.isGreaterThan(0)).annotate({description:`Hourly rate; only together with rateId, and only when the user gave one`}).pipe(i.optionalKey),startDate:q.annotateKey({description:`Start date as yyyy-MM-dd`}).pipe(i.optionalKey),endDate:q.pipe(i.NullOr).annotateKey({description:`End date as yyyy-MM-dd, not before startDate; null clears it. A recurring task with an end date only bills the periods before it`}).pipe(i.optionalKey),recurring:i.Boolean.annotate({description:`SUBSCRIPTION projects only: the task repeats every invoicing period, with workloadHours per 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`}).pipe(i.optionalKey),assignees:i.NonEmptyArray(i.Union([W,ai]).annotate({description:`User, group or division api_id, or a unique user name`})).pipe(i.NullOr).annotate({description:`Who may book time on the task without being planned first. REPLACES the current list; null opens the task to everyone`}).pipe(i.optionalKey),retainerId:W.pipe(i.NullOr).annotate({description:`Retainer api_id of the project's client to charge the task's hours on; its uninvoiced hours move onto the retainer. null takes the task off its retainer. Billable tasks only`}).pipe(i.optionalKey),analyticalCategoryId:W.pipe(i.NullOr).annotate({description:`Analytical category api_id, or null for none, so the rate card's category applies`}).pipe(i.optionalKey)}).check(i.isMinProperties(1)).annotate({description:`The fields to change; at least one`})}),success:mo,failure:H,failureMode:`return`}).annotate(A.Readonly,!1).annotate(A.Destructive,!1).annotate(A.Idempotent,!0),go=n.gen(function*(){let e=yield*Q;return n.fn(`UpdateProjectTask`)(function*({taskId:t,changes:r}){let{startDate:i,endDate:a,rate:o,rateId:s}=r;if(h.isNotUndefined(i)&&h.isNotNullish(a)&&a<i)return yield*n.fail(H.make({message:`endDate ${a} is before startDate ${i}.`}));if(h.isNotUndefined(o)&&h.isUndefined(s))return yield*n.fail(H.make({message:`rate needs rateId: Orbit only sets a rate with its card.`}));let c=yield*e.call(pi,{taskId:t,fieldsJson:r});return mo.make({taskId:t,message:c})},n.mapError(U))}),_o=Ye.make(Ka,Qi,wa,oi,hi,fo,ho,ta,co,ao),vo=_o.toLayer(n.all({GetMyWorkday:ro,GetTicketContext:$i,GetBoardContext:Ea,AddProjectTask:si,CloseProjectTask:gi,UpdateProject:po,UpdateProjectTask:go,CloseTicketSilently:na,SetTicketOwner:lo,LinkTicketToProject:oo},{concurrency:`unbounded`})),yo=i.decodeUnknownEffect(i.JsonObject),bo=i.decodeUnknownOption(H.pipe(i.fromJsonString));function xo(e){return Je.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,...h.isUndefined(e)?{}:{"tlo-mcp/retryAfter":e}}})}function So(e){let[t]=`content`in e&&e.isError===!0?e.content:[];return r.match(t?.type===`text`?bo(t.text):r.none(),{onNone:()=>e,onSome:({message:e,status:t,retryAfter:n})=>t===429?xo(n):Je.CallToolResult.make({isError:!0,content:[{type:`text`,text:e}]})})}const Co=p.effectDiscard(n.gen(function*(){let e=yield*Vr,t=yield*Ue.McpServer;yield*n.forEach(y.filter(e.tools,({name:e})=>!(e in _o.tools)),n.fn(`OrbitProxyLive.tool`)(function*(r){yield*t.addTool({tool:r,annotations:u.empty(),handle:n.fn(`handle`)(function*(e){return yield*yo(e)},n.mapError(e=>Je.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(xo(t)):n.fail(r)),n.mapError(e=>Je.InternalError.make({message:e.message})))))})}),{concurrency:1,discard:!0}),yield*Ue.registerToolkit(_o).pipe(n.provideService(Ue.McpServer,Ue.McpServer.of({...t,addTool:n.fn(`OrbitProxyLive.composite`)(function*(e){yield*t.addTool({...e,handle:t=>e.handle(t).pipe(n.map(So))})})})))})).pipe(p.provide(p.provideMerge(vo,ti))),wo=n.gen(function*(){let e=yield*ge.Path,t=yield*ht(`gateway.key`);return e.join(t,`gateway.key`)}),To=Ve.mebibytes(1),Eo=S.empty({status:pe.fromLiteral(`Unauthorized`),headers:{"www-authenticate":`Bearer`,"cache-control":`no-store`}}),Do=S.empty({status:pe.fromLiteral(`Forbidden`),headers:{"cache-control":`no-store`}}),Oo=new TextEncoder,ko=i.String.check(i.isPattern(/^[a-f0-9]{64}$/)).pipe(i.RedactedFromValue);var Ao=class extends i.TaggedError()(`GatewayError`,{message:i.String,cause:i.Defect().pipe(i.optional)}){};const jo=n.fn(`Gateway.loadKey`)(function*(e){let t=yield*he.FileSystem,r=yield*te.SecureRandom,a=(yield*ge.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,We.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*Ao.make({message:`Gateway key must be a private file (chmod 600).`}):yield*t.readFileString(e).pipe(n.flatMap(i.decodeEffect(ko)))},n.mapError(e=>Ao.make({message:`Cannot load private gateway key. Check its permissions and format.`,cause:e})));function Mo(e,t){return e.digest(ee.sha256,Oo.encode(t))}function No(e){return p.unwrap(n.gen(function*(){let t=yield*ee.Digest,r=yield*Mo(t,`Bearer ${g.value(e)}`);return ue.middleware(e=>n.gen(function*(){let i=yield*fe.HttpServerRequest,a=yield*Mo(t,i.headers.authorization??``);return le.timingSafeEqual(r,a)?h.isNotUndefined(i.headers.origin)?Do:yield*e.pipe(n.provideService(Ge.MaxBodySize,To),n.map(e=>S.setHeader(e,`cache-control`,`no-store`))):Eo}),{global:!0})}))}function Po(e){let t=p.unwrap(n.gen(function*(){let e=yield*Vr;return Co.pipe(p.provide(Ue.layerHttp({name:`tlo-mcp`,version:`1.0.0`,instructions:e.instructions,path:`/mcp`,protocols:[He.v2025_11_25,He.v2025_06_18,He.v2025_03_26]})))}));return p.merge(t,No(e))}const Fo=i.String.check(i.isPattern(/^[a-z0-9]+\.opentunnel\.xyz$/)),Io=i.decodeEffect(Fo),Lo=n.fn(`Gateway.openTunnel`)(function*(e){let t=yield*(yield*zr).tunnel.connect({profile:`tlo-mcp`,routes:{tlo:`127.0.0.1:${e}`}}),r=yield*Io(t.tunnel.hostname);return yield*t.events.pipe(_e.filter(e=>e.type===`reconnecting`),_e.runForEach(()=>n.sync(()=>process.stderr.write(`OpenTunnel reconnecting...
|
|
10
|
+
`))),n.forkScoped),{endpoint:`https://tlo.${r}/mcp`,closed:t.closed.pipe(n.mapError(e=>Ao.make({message:`OpenTunnel stopped unexpectedly. Restart tlo-mcp.`,cause:e})))}},n.timeout(`180 seconds`),n.mapError(e=>Ao.make({message:`Could not connect OpenTunnel. Check network access and retry; existing tunnel identity is preserved.`,cause:e})));function Ro(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.
|
|
@@ -15,9 +15,9 @@ Use a secure credential handoff so I enter the gateway key directly in Executor;
|
|
|
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
17
|
Orbit login and refresh are handled by the gateway; do not register another Orbit OAuth client.
|
|
18
|
-
`}const
|
|
19
|
-
`));let{endpoint:
|
|
18
|
+
`}const zo=n.fn(`TloMcp.connect`)(function*(e,t){let r=yield*wo,i=yield*jo(r),a=yield*xt,o=yield*Ot,s=yield*a.load;if(h.isUndefined(s)){if(h.isNotUndefined(t))return yield*Ao.make({message:`No Orbit session. Run tlo-mcp login on a machine with a browser first.`});yield*o.login}if(yield*p.build(ue.serve(Po(i),{disableLogger:!0,disableListenLog:!0}).pipe(p.provide(Wr),p.provide(se.layer(()=>oe({maxHeaderSize:8192,requestTimeout:13e4}),{host:Be.formatIp(h.isUndefined(t)?Be.ipv4Loopback:Be.ipv4Unspecified),port:e})))),h.isNotUndefined(t)){let e=me.setPathname(t,`/mcp`).href;return yield*n.sync(()=>{process.stderr.write(`TLO gateway ready: ${e}\nGateway key: ${r} (private; not printed)\n`),process.stdout.write(Ro(e))}),yield*n.never}yield*n.sync(()=>process.stderr.write(`Connecting OpenTunnel (first certificate may take a few minutes)...
|
|
19
|
+
`));let{endpoint:c,closed:l}=yield*Lo(e);return yield*n.sync(()=>{process.stderr.write(`TLO gateway ready: ${c}\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(Ro(c))}),yield*l,yield*Ao.make({message:`The OpenTunnel connection stopped. Restart tlo-mcp.`})},n.scoped,n.provide([kt,wt,zr.layer()]));function Bo(e){return a.make(e,{},n.fn(`TloMcp.${e}`)(function*(){yield*(yield*Ot)[e]},n.provide(kt),n.scoped))}const Vo=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})=>zo(e,r.getOrUndefined(t))).pipe(a.withSubcommands([Bo(`login`),Bo(`logout`)]));n.fn(`TloMcp.run`)(function*(e){return yield*a.runWith(Vo,{version:`1.0.0`})(e)})(process.argv.slice(2)).pipe(n.provide(mt),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.5.1",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/2digits-agency/configs.git",
|
|
@@ -18,19 +18,19 @@
|
|
|
18
18
|
"access": "public"
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@effect/platform-node": "4.1.
|
|
21
|
+
"@effect/platform-node": "4.1.4",
|
|
22
22
|
"@opentunnel/client": "0.6.2",
|
|
23
|
-
"@yielded/oauth": "0.1.0-beta.
|
|
24
|
-
"effect": "4.1.
|
|
23
|
+
"@yielded/oauth": "0.1.0-beta.49",
|
|
24
|
+
"effect": "4.1.4"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
|
-
"@2digits/tsconfig": "1.2.
|
|
28
|
-
"@effect/vitest": "4.1.
|
|
27
|
+
"@2digits/tsconfig": "1.2.10",
|
|
28
|
+
"@effect/vitest": "4.1.4",
|
|
29
29
|
"publint": "0.3.25",
|
|
30
|
-
"tsrs": "0.
|
|
30
|
+
"tsrs": "0.25.0-ts7.1.0-beta",
|
|
31
31
|
"typescript": "7.1.0-beta",
|
|
32
|
-
"vite-plus": "1.
|
|
33
|
-
"vitest": "5.1.
|
|
32
|
+
"vite-plus": "1.7.0",
|
|
33
|
+
"vitest": "5.1.1"
|
|
34
34
|
},
|
|
35
35
|
"engines": {
|
|
36
36
|
"node": ">=24"
|