@hallohuman/hightea 0.1.32 → 0.1.34

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hallohuman/hightea",
3
- "version": "0.1.32",
3
+ "version": "0.1.34",
4
4
  "description": "The Hightea command line: join this machine to a Hightea workspace as a host.",
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
@@ -27,7 +27,7 @@
27
27
  "@ahpd/deploy": "https://github.com/beorn/ahpd/releases/download/hh-38499-dc5a62e1/ahpd-deploy-0.15.0-beorn.dc5a62e1.tgz",
28
28
  "@ahpd/sdk": "https://github.com/beorn/ahpd/releases/download/hh-38499-dc5a62e1/ahpd-sdk-0.15.0-beorn.dc5a62e1.tgz",
29
29
  "@ahpd/server": "https://github.com/beorn/ahpd/releases/download/hh-38499-dc5a62e1/ahpd-server-0.15.0-beorn.dc5a62e1.tgz",
30
- "@hallohuman/hightea-services": "https://github.com/beorn/ahpd/releases/download/hh-38499-dc5a62e1/hallohuman-hightea-services-0.16.0-beorn.dc5a62e1.tgz",
30
+ "@hallohuman/hightea-services": "https://github.com/beorn/ahpd/releases/download/hh-38899-7ef4f3e5/hallohuman-hightea-services-0.16.0-beorn.7ef4f3e5.tgz",
31
31
  "@silvery/commander": "0.29.3",
32
32
  "ws": "8.21.0"
33
33
  },
@@ -1,5 +0,0 @@
1
- import{_,A,d,c,l,u,p,w}from"./chunk-ah99zytf.js";import{r}from"./chunk-v221hgba.js";import{readdir as le,readFile as oe,realpath as Oe,rm as gt}from"node:fs/promises";import{createRequire as Ln}from"node:module";import{homedir as xn,hostname as Fn}from"node:os";import{basename as yt,dirname as F,isAbsolute as wt,join as P,resolve as Kn}from"node:path";import{fromEnvRef as jn,isRecord as K,readJsonObject as _t,readSecret as Gn,secretRef as Bn,writeJsonAtomic as Ne}from"@ahpd/sdk";import{fileVault as Mn}from"@ahpd/server/dist/vault.js";import{createHash as De,randomBytes as Tt}from"node:crypto";import{constants as ee}from"node:fs";import{link as Nt,lstat as ge,mkdir as Ue,mkdtemp as Et,open as $e,realpath as At,rm as Ht}from"node:fs/promises";import{dirname as se,join as M}from"node:path";import{isDeepStrictEqual as Pe}from"node:util";import{fileVault as Je}from"@ahpd/server/dist/vault.js";function b(e){throw Error(e)}function Le(e){return e!==null&&typeof e==="object"&&"code"in e&&typeof e.code==="string"?e.code:void 0}async function Y(e){await Ue(e,{mode:448}).catch((s)=>{if(Le(s)!=="EEXIST")b("HOST_JOIN_CUSTODY_IO")});let t=await ge(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&63)!==0)b("HOST_JOIN_UNSAFE_PATH")}async function kt(e){let t=await $e(e,ee.O_RDONLY|ee.O_DIRECTORY|ee.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}}async function Z(e){let t=await $e(e,ee.O_RDONLY|ee.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}for(let s=se(e);;s=se(s))if(await kt(s),s===se(s))break}function fe(e){if(typeof e.origin!=="string"||typeof e.workspaceSlug!=="string"||typeof e.code!=="string"||typeof e.pluginVersion!=="string"||typeof e.ahpdVersion!=="string")b("HOST_JOIN_INVALID_INTENT");let t;try{t=new URL(e.origin)}catch{return b("HOST_JOIN_INVALID_INTENT")}let s=d(e.code);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/"||!s||!e.workspaceSlug||/[\s/\\?#]/u.test(e.workspaceSlug)||!e.pluginVersion||!e.ahpdVersion)b("HOST_JOIN_INVALID_INTENT");if(e.name!==void 0&&(typeof e.name!=="string"||e.name.trim()===""||e.name.length>64||[...e.name].some((y)=>{let a=y.codePointAt(0)??0;return a<32||a===127})))b("HOST_JOIN_INVALID_INTENT");if(e.app!==void 0&&!A(e.app))b("HOST_JOIN_INVALID_INTENT");if(e.hostId!==void 0&&(typeof e.hostId!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(e.hostId)))b("HOST_JOIN_INVALID_INTENT");if(e.ownerConfiguration===null&&e.app===void 0)b("HOST_JOIN_INVALID_INTENT");let f;try{f=e.ownerConfiguration===null?null:JSON.parse(JSON.stringify(e.ownerConfiguration))}catch{return b("HOST_JOIN_INVALID_INTENT")}if(f!==null&&(typeof f!=="object"||!Pe(f,e.ownerConfiguration)))b("HOST_JOIN_INVALID_INTENT");return{...e,origin:t.origin,code:s,ownerConfiguration:f}}async function xe(e,t){let s=fe(t),f=await Ke(e),y=M(f,"hightea"),a=M(y,"claims"),h=De("sha256").update(JSON.stringify([s.origin,s.workspaceSlug,s.code])).digest("hex"),S=M(a,h),T=M(S,"ahpd");try{for(let E of[y,a,S,T])await Y(E);let N=M(T,"vault.json"),I=await Et(M(T,".claim-"));try{let E=M(I,"vault.json"),v=Je({file:E});await v.set("host:hightea",`Bearer ${Tt(32).toString("base64url")}`),await v.set("host:hightea-join",JSON.stringify({schema:1,...s}));try{await Nt(E,N)}catch(D){if(Le(D)!=="EEXIST")b("HOST_JOIN_CUSTODY_PUBLICATION_FAILED")}let{authorization:H,credentialHash:k,intent:J}=await je(N);if(J.origin!==s.origin||J.workspaceSlug!==s.workspaceSlug||J.code!==s.code||J.app!==s.app||J.hostId!==s.hostId||!Pe(J.ownerConfiguration,s.ownerConfiguration))b("HOST_JOIN_CLAIM_CONFLICT");return await Z(N),{home:S,vaultFile:N,authorization:H,credentialHash:k,intent:J}}finally{await Ht(I,{recursive:!0})}}catch(N){if(N instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(N.message))throw N;return b("HOST_JOIN_CUSTODY_IO")}}async function Fe(e,t,s){let f=fe(s);if(f.hostId===void 0)b("HOST_JOIN_INVALID_INTENT");try{let y=await Ke(e),a=M(y,"hightea"),h=M(a,"claims");if(se(t)!==h)b("HOST_JOIN_NO_CLAIM_FOR_HOST");let S=M(t,"ahpd");for(let I of[a,h,t,S])await Y(I);let T=M(S,"vault.json"),N=await je(T);if(N.intent.origin!==f.origin||N.intent.workspaceSlug!==f.workspaceSlug||N.intent.hostId!==void 0&&f.hostId!==N.intent.hostId)b("HOST_JOIN_CLAIM_CONFLICT");return await Z(T),{home:t,vaultFile:T,authorization:N.authorization,credentialHash:N.credentialHash,intent:f}}catch(y){if(y instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(y.message))throw y;return b("HOST_JOIN_NO_CLAIM_FOR_HOST")}}async function Ke(e){try{await Ue(e,{recursive:!0,mode:448});let t=await ge(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&18)!==0)b("HOST_JOIN_UNSAFE_PATH");return await At(e)}catch{return b("HOST_JOIN_UNSAFE_PATH")}}async function je(e){let t=await ge(e);if(!t.isFile()||t.uid!==process.getuid?.()||(t.mode&511)!==384)b("HOST_JOIN_UNSAFE_PATH");let s=Je({file:e}),f=await s.get("host:hightea"),y=await s.get("host:hightea-join");if(!f||!/^Bearer [A-Za-z0-9_-]{43}$/u.test(f)||!y)b("HOST_JOIN_CLAIM_CORRUPT");let a;try{a=JSON.parse(y)}catch{return b("HOST_JOIN_CLAIM_CORRUPT")}if(!a||typeof a!=="object"||!("schema"in a)||a.schema!==1)b("HOST_JOIN_CLAIM_CORRUPT");let h;try{h=fe(a)}catch{return b("HOST_JOIN_CLAIM_CORRUPT")}return{authorization:f,credentialHash:`sha256:${De("sha256").update(f.slice(7),"utf8").digest("hex")}`,intent:h}}import{link as Rt,lstat as bt,mkdtemp as vt,rm as Ct}from"node:fs/promises";import{join as te}from"node:path";import{isDeepStrictEqual as Dt}from"node:util";import{isRecordSlug as Ut,readJsonObject as $t,writeJsonAtomic as Ge}from"@ahpd/sdk";async function Be(e,t){return Ve(e,te(e.home,"ahpd"),"config.json",t)}async function Me(e,t){if(!Ut(t.id))throw Error("HOST_JOIN_CONFIG_CONFLICT");let s=te(e.home,"ahpd","agents");await Y(s),await Ve(e,s,`${t.id}.json`,{...t})}async function Ve(e,t,s,f){let y=te(t,s),a;try{if(JSON.stringify(f).includes(e.authorization))throw Error("HOST_JOIN_CONFIG_SECRET");a=await vt(te(t,".config-"));let h=te(a,"config.json");Ge(h,f,{mode:384});try{await Rt(h,y)}catch(I){if(!I||typeof I!=="object"||!("code"in I)||I.code!=="EEXIST")throw Error("HOST_JOIN_CONFIG_PUBLICATION_FAILED")}let S=await bt(y);if(!S.isFile()||S.uid!==process.getuid?.()||(S.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");let T=$t(y);if(!T.ok)throw Error("HOST_JOIN_CONFIG_CORRUPT");let N={};for(let[I,E]of Object.entries(f)){let v=I==="unattendedAutoApprove"&&E===!1||I==="pluginMarketplaces"&&Array.isArray(E)&&E.length===0;if(s==="config.json"&&v&&!Object.hasOwn(T.value,I)){N[I]=E;continue}if(!Dt(T.value[I],E))throw Error("HOST_JOIN_CONFIG_CONFLICT")}if(Object.keys(N).length>0)Ge(y,{...T.value,...N},{mode:384});return await Z(y),y}catch(h){if(h instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(h.message))throw h;throw Error("HOST_JOIN_CONFIG_IO")}finally{if(a!==void 0)await Ct(a,{recursive:!0})}}import{isRecord as W}from"@ahpd/sdk";class ne extends Error{kind;status;serverCode;constructor(e,t,s){super(e);this.kind=e;this.status=t;this.serverCode=s}}function Pt(e,t){if(e===401||e===403)return"HOST_JOIN_NOT_AUTHORIZED";if(t==="AGENT_HOST_CONFLICT"||t==="HOST_REGISTRATION_CONFLICT")return"HOST_JOIN_AGENT_BOUND";if(t==="HOST_REGISTRATION_UNSETTLED")return"HOST_JOIN_UNSETTLED";return"HOST_JOIN_REJECTED"}async function We(e){await Z(e.vaultFile);let t=e.intent,s=new Request(`${t.origin}/api/ws/${encodeURIComponent(t.workspaceSlug)}/join/${encodeURIComponent(t.code)}`,{method:"POST",redirect:"error",headers:{"content-type":"application/json"},signal:AbortSignal.timeout(1e4),body:JSON.stringify({credentialHash:e.credentialHash,pluginVersion:t.pluginVersion,ahpdVersion:t.ahpdVersion,...t.name===void 0?{}:{name:t.name},...t.app===void 0?{}:{app:t.app},...t.hostId===void 0?{}:{hostId:t.hostId}})}),f;try{f=await fetch(s)}catch{throw Error("HOST_JOIN_NETWORK_UNKNOWN")}if(f.status===410){let a;try{a=await f.json()}catch{}if(W(a)&&W(a.error)&&a.error.code==="HOST_REGISTRATION_CANCELLED")throw Error("HOST_JOIN_CANCELLED");throw Error("HOST_JOIN_LINK_UNAVAILABLE")}if(f.status>=500){let a;try{a=await f.json()}catch{}let h=W(a)&&W(a.error)&&_(a.error.code)?a.error.code:void 0;if(h==="HOST_REGISTRATION_UNSETTLED")throw new ne("HOST_JOIN_UNSETTLED",f.status,h);throw Error("HOST_JOIN_REMOTE_UNAVAILABLE")}if(!f.ok){let a;try{a=await f.json()}catch{}let h=W(a)&&W(a.error)&&_(a.error.code)?a.error.code:void 0;throw new ne(Pt(f.status,h),f.status,h)}let y;try{y=await f.json()}catch{throw Error("HOST_JOIN_RECEIPT_INVALID")}if(!W(y)||typeof y.workspaceId!=="string"||!/^ws_[A-Za-z0-9_-]{1,64}$/u.test(y.workspaceId)||typeof y.hostId!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(y.hostId)||y.state!=="pending"&&y.state!=="registered"||y.agentMemberId!==void 0&&(typeof y.agentMemberId!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(y.agentMemberId)))throw Error("HOST_JOIN_RECEIPT_INVALID");return{workspaceId:y.workspaceId,hostId:y.hostId,state:y.state,...y.agentMemberId===void 0?{}:{agentMemberId:y.agentMemberId}}}import{access as Jt,stat as he}from"node:fs/promises";import{constants as Lt}from"node:fs";import{delimiter as xt,dirname as ze,isAbsolute as Ft,join as Kt}from"node:path";import{fileURLToPath as jt}from"node:url";import{fromEnvRef as Gt,isRecord as V,isRecordSlug as Bt,readJsonObject as Mt,scopeOf as Vt,secretPaths as Wt,secretRef as zt}from"@ahpd/sdk";import{checkManifest as Yt,checkStandalone as Zt,readManifest as Xt,readStandalone as qt,resolvePlugin as Qt}from"@ahpd/server/dist/plugins.js";function U(e="HOST_JOIN_OWNER_RESOURCE"){throw Error(e)}function Ye(e){let t=Gt(e);if(t!==void 0){if(!process.env[t])U();return!0}let s=zt(e);if(s===void 0)return!1;return Vt(s),!0}async function en(e){let t=Ft(e)?[e]:(process.env.PATH??"").split(xt).map((s)=>Kt(s,e));for(let s of t)try{if(await Jt(s,Lt.X_OK),(await he(s)).isFile())return}catch{}U()}async function re(e){let t=Mt(e);if(!t.ok)U("HOST_JOIN_OWNER_INPUT");let s=t.value;if(!Array.isArray(s.agents)||s.agents.length===0||!Array.isArray(s.plugins)||s.plugins.length===0||!Array.isArray(s.records))U();let f=new Set,y=new Set,a=[];try{for(let I of s.plugins){let E=typeof I==="string"?{source:I}:I;if(!V(E)||typeof E.source!=="string"||E.enabled===!1)U();let H=Qt(E,{cwd:ze(e),configDir:ze(e)});if(!H.path||!(await he(H.path)).isFile())U();let k=H.manifestPath?qt(H.manifestPath):H.packageDir?Xt(H.packageDir):void 0;if(!k||k.problem||(k.standalone?Zt(k):Yt(k,H.packageDir)))U();if(k.name==="@ahpd/bot"||k.name==="bot")U("HOST_JOIN_OWNER_BOT");for(let D of k.contracts?.engines??[])f.add(D);for(let D of k.contracts?.agents??[])y.add(D);if(E.options!==void 0&&!V(E.options))U();let J=V(E.options)?E.options:{};for(let D of Wt(k.optionsSchema??{},J)){let L=J;for(let G of D.split("."))L=V(L)?L[G]:void 0;if(L!==void 0&&!Ye(L))U("HOST_JOIN_OWNER_SECRET")}a.push({...E,source:H.manifestPath??H.packageDir??H.path})}let h=[],S=new Set(y);for(let I of s.records){if(!V(I)||typeof I.id!=="string"||!Bt(I.id)||S.has(I.id)||typeof I.engine!=="string"||!f.has(I.engine)||typeof I.owner!=="string"||typeof I.name!=="string"||!V(I.config)||I.mode!==void 0&&I.mode!=="enabled")U();if(I.model!==void 0&&(typeof I.model!=="string"||I.model.trim()===""))U();if(I.engine==="acp"&&typeof I.config.command!=="string")U();if(I.config.command!==void 0){if(typeof I.config.command!=="string"||!I.config.command)U();await en(I.config.command)}if(I.config.env!==void 0){if(!V(I.config.env))U();for(let E of Object.values(I.config.env))if(!Ye(E))U("HOST_JOIN_OWNER_SECRET")}S.add(I.id),h.push(I)}let T=[],N=new Set;for(let I of s.agents){if(!Array.isArray(I)||I.length!==2||typeof I[0]!=="string"||!I[0]||N.has(I[0])||!V(I[1])||typeof I[1].provider!=="string"||!S.has(I[1].provider)||typeof I[1].workingDirectory!=="string")U();let E=new URL(I[1].workingDirectory);if(E.protocol!=="file:"||E.hostname||!(await he(jt(E))).isDirectory())U();if(I[1].settings!==void 0&&!V(I[1].settings))U();N.add(I[0]),T.push([I[0],{provider:I[1].provider,workingDirectory:E.href,...I[1].settings===void 0?{}:{settings:I[1].settings}}])}return{agents:T,plugins:a,records:h}}catch(h){if(h instanceof Error&&/^HOST_JOIN_OWNER_[A-Z_]+$/u.test(h.message))throw h;return U()}}import{constants as tn}from"node:fs";import{access as nn,mkdir as rn,stat as on,writeFile as sn}from"node:fs/promises";import{createRequire as an}from"node:module";import{dirname as Xe,resolve as qe}from"node:path";import{pathToFileURL as dn}from"node:url";class ae extends Error{file;entry;constructor(e,t){super("HOST_JOIN_OWNER_CONFIG_NEEDS_AGENT");this.file=e;this.entry=t}}function cn(){try{return Xe(an(import.meta.url).resolve("@ahpd/agent-acp/package.json"))}catch{throw Error("HOST_JOIN_AGENT_PLUGIN_MISSING")}}function Qe(e,t,s){return[t,{provider:e.id,workingDirectory:dn(qe(s)).href}]}function ln(e,t,s){return JSON.stringify(Qe(e,t,s))}function un(e,t){let[s,f]=Qe(e.app,e.agentMemberId,e.workingDirectory);return`${JSON.stringify({plugins:[t],records:[{id:e.app.id,engine:"acp",owner:"host",name:e.app.name,config:{command:e.app.command}}],agents:[[s,f]]},null,2)}
2
- `}async function et(e){let t=qe(e.file);if(await nn(t,tn.F_OK).then(()=>!0,()=>!1))return Ze(t,e);await rn(Xe(t),{recursive:!0,mode:448});try{await sn(t,un(e,cn()),{flag:"wx",mode:384})}catch(f){if(f!==null&&typeof f==="object"&&"code"in f&&f.code==="EEXIST")return Ze(t,e);throw Error("HOST_JOIN_OWNER_FILE_IO")}let s=await on(t);if(!s.isFile()||s.uid!==process.getuid?.()||(s.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");return re(t)}async function Ze(e,t){let s=await re(e);if(s.agents.some(([f])=>f===t.agentMemberId))return s;throw new ae(e,ln(t.app,t.agentMemberId,t.workingDirectory))}import{access as Vn}from"node:fs/promises";import{constants as Wn}from"node:fs";import{createHash as gn}from"node:crypto";import{lstat as tt,mkdir as fn,mkdtemp as hn,readFile as me,rename as pn,rm as mn,writeFile as pe}from"node:fs/promises";import{isAbsolute as nt,join as j,normalize as de}from"node:path";var yn="hightea-pipe",we="bundle.json";function _e(e){return j(e,"hightea","plugins")}async function rt(e){let t;try{t=await me(j(e,"plugin.json"))}catch{throw Error("HOST_JOIN_PLUGIN_BUNDLE")}let s;try{s=JSON.parse(t.toString("utf8"))}catch{throw Error("HOST_JOIN_PLUGIN_BUNDLE")}let f=typeof s==="object"&&s!==null&&"main"in s?s.main:void 0,y=typeof s==="object"&&s!==null&&"id"in s?s.id:void 0,a=typeof s==="object"&&s!==null&&"version"in s?s.version:void 0;if(y!==yn||typeof a!=="string"||typeof f!=="string"||nt(f)||de(f).startsWith("..")||de(f).includes("/")||["plugin.json",we].includes(de(f)))throw Error("HOST_JOIN_PLUGIN_BUNDLE");let h;try{h=await me(j(e,f))}catch{throw Error("HOST_JOIN_PLUGIN_BUNDLE")}return{manifestBytes:t,version:a,main:de(f),mainBytes:h,sha256:wn(t,h)}}function wn(e,t){return gn("sha256").update(e).update("\x00").update(t).digest("hex")}async function ce(e){let t=j(e,".."),s;try{s=JSON.parse(await me(j(t,we),"utf8"))}catch(y){return{ok:!1,reason:ot(y)?"missing":"corrupt"}}let f;try{f=await rt(t)}catch{return{ok:!1,reason:"corrupt"}}if(typeof s!=="object"||s===null||!("version"in s)||!("sha256"in s)||typeof s.version!=="string"||s.sha256!==f.sha256)return{ok:!1,reason:"corrupt"};return{ok:!0,bundle:{manifest:e,version:s.version,sha256:f.sha256}}}async function Ie(e,t,s){if(!nt(e)||!/^[0-9A-Za-z.+-]+$/u.test(s))throw Error("HOST_JOIN_UNSAFE_PATH");let f=await rt(t);if(f.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE");try{await fn(e,{recursive:!0,mode:448});let T=await tt(e);if(!T.isDirectory()||T.uid!==process.getuid?.()||(T.mode&18)!==0)throw Error("unsafe")}catch{throw Error("HOST_JOIN_UNSAFE_PATH")}let y=_e(e);for(let T of[j(e,"hightea"),y])await Y(T);let a=j(y,s),h=j(a,"plugin.json");if(!await _n(a)){let T=await hn(j(y,`.${s}-`));try{await pe(j(T,"plugin.json"),f.manifestBytes,{mode:384}),await pe(j(T,f.main),f.mainBytes,{mode:384}),await pe(j(T,we),`${JSON.stringify({version:s,sha256:f.sha256})}
3
- `,{mode:384});try{await pn(T,a)}catch(N){if(!ye(N,"EEXIST")&&!ye(N,"ENOTEMPTY"))throw Error("HOST_JOIN_CONFIG_IO")}}finally{await mn(T,{recursive:!0,force:!0})}}let S=await ce(h);if(!S.ok||S.bundle.sha256!==f.sha256||S.bundle.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE_CONFLICT");return S.bundle}async function _n(e){try{return await tt(e),!0}catch(t){if(ot(t))return!1;throw Error("HOST_JOIN_UNSAFE_PATH")}}function ot(e){return ye(e,"ENOENT")}function ye(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}import{createPrivateKey as kn,createPublicKey as Rn,generateKeyPairSync as bn,sign as lo}from"node:crypto";import{appendFile as go,chmod as vn,readFile as it,rename as Cn,writeFile as Dn}from"node:fs/promises";import{join as st}from"node:path";var eo=Buffer.from("302a300506032b6570032100","hex");import{createHash as On}from"node:crypto";import{existsSync as Sn,readFileSync as Tn}from"node:fs";import{join as Nn}from"node:path";var En="trusted-keys.json",m=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,An=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,Hn=(e)=>Buffer.from(e).toString("base64url");function o(e){if(!An.test(e))return{error:"TRUST_KEY_INVALID: the public key must be 43 base64url characters (a raw 32-byte Ed25519 key), as the browser's Members page shows it"};return{keyId:Hn(On("sha256").update(Buffer.from(e,"base64url")).digest())}}function g(e){let t=Nn(e,En);if(!Sn(t))return{state:"missing",file:t};let s;try{s=JSON.parse(Tn(t,"utf8"))}catch(y){throw Error(`TRUST_FILE_UNREADABLE: ${t} is not JSON (${y.message})`)}let f=s;if(typeof s!=="object"||s===null||f.v!==1||!Array.isArray(f.keys))throw Error(`TRUST_FILE_UNREADABLE: ${t} is not a version 1 list of trusted keys`);for(let y of f.keys){let a=y,h=typeof a.publicKey==="string"?o(a.publicKey):void 0;if(typeof a.name!=="string"||!m.test(a.name)||h===void 0||"error"in h||a.keyId!==h.keyId||typeof a.addedAt!=="string")throw Error(`TRUST_FILE_UNREADABLE: ${t} holds an entry that is not a valid trusted key: ${JSON.stringify(y)}`)}return{state:"read",file:t,keys:f.keys}}var at="host-signing-key";async function dt(e){try{await it(st(e,at))}catch(t){if(t.code==="ENOENT")return{state:"missing"}}try{return{state:"ok",key:await Un(e)}}catch(t){return{state:"unreadable",reason:t instanceof Error?t.message:String(t)}}}async function Un(e,t=()=>Date.now()){let s=st(e,at),f;try{f=await it(s,"utf8")}catch(S){if(S.code!=="ENOENT")throw Error(`HOST_KEY_UNREADABLE: ${s} exists but cannot be read (${String(S)}); it is never regenerated, fix or remove it by hand`)}if(f===void 0){let S=bn("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),T=`${s}.${String(process.pid)}.tmp`;await Dn(T,S,{mode:384,flag:"wx"}),await vn(T,384),await Cn(T,s),f=S}let y;try{if(y=kn({key:f,format:"pem"}),y.asymmetricKeyType!=="ed25519")throw Error(`a ${String(y.asymmetricKeyType)} key, not Ed25519`)}catch(S){throw Error(`HOST_KEY_UNREADABLE: ${s} is not an Ed25519 PKCS8 key (${String(S)}); it is never regenerated, fix or remove it by hand`)}let a=Rn(y).export({format:"jwk"}).x,h=a===void 0?{error:"no public key"}:o(a);if("error"in h)throw Error(`HOST_KEY_UNREADABLE: ${s}: ${h.error}`);return{privateKey:y,trusted:{name:"this-host",keyId:h.keyId,publicKey:a,addedAt:new Date(t()).toISOString()}}}import{createServer as $n}from"node:net";var ct="hightea";function lt(e){return`http://127.0.0.1:${String(e)}/mcp`}function Pn(e){let t=2166136261;for(let s of new TextEncoder().encode(e))t^=s,t=Math.imul(t,16777619)>>>0;return 40000+t%20000}async function ut(e){let t=Pn(e);for(let s=0;s<200;s+=1){let f=40000+(t-40000+s)%20000;if(await Jn(f))return f}throw Error(`HOST_TOOLS_PORT_UNAVAILABLE: every port from ${String(t)} to ${String(t+199)} on 127.0.0.1 is taken`)}async function Jn(e){let t=$n();return await new Promise((s)=>{t.once("error",()=>{s(!1)}),t.listen(e,"127.0.0.1",()=>{t.close(()=>{s(!0)})})})}var zn="hightea host join --origin https://your-deployment --workspace SLUG --code CODE --owner-config /absolute/owner.json",Yn=(e)=>[...e].some((t)=>{let s=t.codePointAt(0)??0;return s<32||s===127});function Zn(e=Fn()){let t=e.trim();return t===""||t.length>64||Yn(t)?void 0:t}var Xn="https://hightea.ai/docs/host#owner";class Ee extends Error{file;constructor(e){super("HOST_JOIN_OWNER_CONFIG_MISSING");this.file=e}}var qn=(e)=>`no owner config at ${e}: write one listing the plugins, agent records and agents this computer runs — `+`the three fields with an example of each are at ${Xn} — then run the same command again. Nothing was redeemed and nothing was written.`,Qn=(e,t)=>`the owner config at ${e} does not map the agent this computer just created. Add this pair to its "agents" array — `+`${t} — then run the same command again; the registration is pending and resumes.`;class Ae extends Error{appName;install;constructor(e,t){super("HOST_JOIN_APP_MISSING");this.appName=e;this.install=t}}var er=(e)=>`${e.appName} is not on this computer: install it with \`${e.install}\`, then run the same command again. Nothing was redeemed and nothing was written.`,q={HOST_JOIN_USAGE:`Expected: ${zn}`,HOST_JOIN_INPUT:"Command input could not be read. Use --help for the supported options.",HOST_JOIN_INVALID_INTENT:"Use an HTTPS deployment origin, workspace slug and valid join code.",HOST_JOIN_OWNER_INPUT:"The --owner-config file must exist and contain a JSON object; its contents were not printed.",HOST_JOIN_OWNER_RESOURCE:"Check the explicit agent mappings, provider plugins, working directories, executables and referenced credentials in --owner-config. No code was redeemed.",HOST_JOIN_OWNER_SECRET:"Replace inline provider secrets with existing ahpd fromEnv or SecretRef values; the referenced resource must be available locally.",HOST_JOIN_OWNER_BOT:"@ahpd/bot is not allowed on a member host (bots run on the server); remove it from this owner's plugin list",HOST_JOIN_UNSAFE_PATH:"The selected configuration path must be owned by this user and private; symlinks and shared files are not used.",HOST_JOIN_CLAIM_CONFLICT:"This claim already holds different deployment or owner settings. Keep its vault and use the original settings to resume.",HOST_JOIN_CLAIM_CORRUPT:"The selected claim vault is invalid. Keep it for recovery; joining will not replace its credential.",HOST_JOIN_NO_CLAIM_FOR_HOST:"This computer holds no claim for that host. Join without --host to register this computer as a new host; --host only extends a host this computer already holds, reusing its credential.",HOST_JOIN_NETWORK_UNKNOWN:"The registration result is unknown. Keep this claim and rerun the same command to recover its receipt.",HOST_JOIN_REMOTE_UNAVAILABLE:"The deployment could not complete registration. Keep this claim and rerun the same command later.",HOST_JOIN_CANCELLED:"The owner cancelled this host registration. Keep the existing claim; request a new join code for another registration.",HOST_JOIN_LINK_UNAVAILABLE:"This join code is expired or unavailable. Keep the existing claim; request a new code if registration was not completed.",HOST_JOIN_REJECTED:"The deployment rejected registration. Check the deployment and workspace; the selected credential was retained.",HOST_JOIN_NOT_AUTHORIZED:"The deployment refused this account for that workspace or agent. Join with the account that owns the agents in --owner-config; the selected credential was retained.",HOST_JOIN_AGENT_BOUND:"The deployment refused this registration; the server code on this line says which case it is. AGENT_HOST_CONFLICT: an agent in --owner-config already belongs to another active host — revoke that host, then mint a new code. HOST_REGISTRATION_CONFLICT: this code was already redeemed by a different host registration — join with the claim that computer already holds, or mint a new code. Never revoke a host on the strength of this line alone; the selected credential was retained.",HOST_JOIN_UNSETTLED:"The workspace did not answer this registration within a minute. The code is unspent and this claim is intact; wait a minute, then run the same command again.",HOST_JOIN_RECEIPT_INVALID:"The deployment returned an invalid registration receipt. Keep this claim and retry against the correct deployment.",HOST_JOIN_CONFIG_CONFLICT:"Existing host configuration has different bindings or required settings. It was preserved; reconcile it with the original claim before retrying.",HOST_JOIN_CONFIG_CORRUPT:"Existing host configuration is invalid JSON. It was preserved for local repair; rerun after repairing it.",HOST_JOIN_CLAIM_VERSION:"This join code's claim was started by another hightea version. Finish it with that version, or request a new join code; nothing was redeemed or written.",HOST_JOIN_PLUGIN_BUNDLE:"This installation's host plugin is missing or unreadable. Reinstall @hallohuman/hightea; no configuration was written.",HOST_JOIN_PLUGIN_BUNDLE_CONFLICT:"The installed host plugin for this version differs from this installation's copy. It was preserved; reinstall the same version or repair that directory. No configuration was written.",HOST_JOIN_AGENT_PLUGIN_MISSING:"This installation cannot find @ahpd/agent-acp, the plugin that runs agent apps. Reinstall @hallohuman/hightea; nothing was redeemed.",HOST_JOIN_APPS_ROW_MISSING:"This installation's app list and the daemon's rows disagree. Reinstall @hallohuman/hightea; nothing was redeemed.",HOST_JOIN_OWNER_FILE_IO:"The owner config could not be written. No existing file was replaced; check the folder's permissions and retry."};function z(e,t){let s=process.env[e]||P(xn(),t);if(!wt(s))throw Error("HOST_JOIN_UNSAFE_PATH");return s}function tr(){let e=Ln(import.meta.url).resolve("@ahpd/server/package.json");return{node:process.execPath,main:P(F(e),"dist","main.js")}}var Se=(e)=>`'${e.replaceAll("'","'\\''")}'`;function ie(e,t=tr()){return`XDG_CONFIG_HOME=${Se(e)} ${Se(t.node)} ${Se(t.main)} start`}var nr={JOIN_LINK_INVALID:"the join code is no longer valid",JOIN_LINK_NOT_FOUND:"no such join code in that workspace",ROLE_NOT_ALLOWED:"the join code does not allow this role",NOT_A_MEMBER:"the signed-in account is not a member of that workspace",FORBIDDEN:"an agent in --owner-config belongs to another account",HOST_REGISTRATION_CANCELLED:"the owner cancelled this registration",HOST_REGISTRATION_CONFLICT:"this code was redeemed for a different host registration; a computer that already has a host joins with the claim it already holds",AGENT_HOST_CONFLICT:"an agent already belongs to another active host; revoke that host, then mint a new code",HOST_REGISTRATION_MISSING:"the pending registration is gone",HOST_REGISTRATION_UNSETTLED:"the workspace has not answered the registration within a minute; run the same command again",INVALID_REQUEST:"the deployment did not accept this request's shape",BAD_ORIGIN:"the request came from another site",UNAUTHENTICATED:"the request carried no signed-in account",WORKSPACE_NOT_FOUND:"no such workspace for this account",PEOPLE_LIMIT:"that workspace is at its beta limit of people",AGENTS_LIMIT:"that workspace is at its beta limit of agents"},rr={HOST_JOIN_NOT_AUTHORIZED:3,HOST_JOIN_AGENT_BOUND:4,HOST_JOIN_REJECTED:1,HOST_JOIN_UNSETTLED:2};function or(e){let t=e.serverCode===void 0?"":` The deployment says ${nr[e.serverCode]}.`;return`${e.kind}: ${q[e.kind]}${t} (HTTP ${e.status}, server code ${e.serverCode??"unrecognised"})`}async function O(e,t){try{let{origin:s,workspace:f,code:y,ownerConfig:a}=e;if(!s||!f||!y||!a)throw Error("HOST_JOIN_USAGE");let h=Kn(a),S=await Vn(h,Wn.F_OK).then(()=>!0,()=>!1);if(!S&&e.ownerConfigIsDefault!==!0)throw Error("HOST_JOIN_OWNER_INPUT");if(!S&&e.app===void 0)throw new Ee(h);let T=e.app===void 0?void 0:p(e.app);if(T!==void 0&&!await w(T))throw new Ae(T.name,u(T));let N=S?await re(h):null,I=z("XDG_CONFIG_HOME",".config"),E=z("XDG_DATA_HOME",P(".local","share")),v=Zn(),H={origin:s,workspaceSlug:f,code:y,pluginVersion:t.version,ahpdVersion:"0.15.0-rc.4",ownerConfiguration:N,...v===void 0?{}:{name:v},...e.app===void 0?{}:{app:e.app},...e.hostId===void 0?{}:{hostId:e.hostId}},k;if(e.hostId===void 0)k=await xe(I,H);else{let B=await n(e.hostId);if("error"in B)throw Error("HOST_JOIN_NO_CLAIM_FOR_HOST");k=await Fe(I,B.claim,H)}if(k.intent.pluginVersion!==t.version)throw Error("HOST_JOIN_CLAIM_VERSION");let J=Mn({file:k.vaultFile}),D=async(B)=>{let ve=Bn(B),Ce=jn(B);if(Ce!==void 0){if(!process.env[Ce])throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(ve!==void 0)try{await Gn(J,ve)}catch{throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(Array.isArray(B))for(let ue of B)await D(ue);else if(K(B))for(let ue of Object.values(B))await D(ue)};if(N!==null)await D(N);let L=await Ie(E,t.directory,t.version),G=await We(k);if(G.state==="pending")return console.log("Host registration pending. Run the same command again to resume."),2;let Q=T===void 0?N:await et({file:h,app:T,agentMemberId:hr(G.agentMemberId),workingDirectory:e.workingDirectory??process.cwd()});if(Q===null)throw Error("HOST_JOIN_OWNER_INPUT");if(T!==void 0)await D(Q);for(let B of Q.records)await Me(k,B);let Re=new URL(`/gateway/${encodeURIComponent(G.workspaceId)}/host`,k.intent.origin);Re.protocol="wss:";let be=await ut(k.home);return await Be(k,{host:"127.0.0.1",updateCheck:!1,httpApi:!1,modelApi:!1,mcpTools:"none",unattendedAutoApprove:!1,pluginMarketplaces:[],mcpServers:{[ct]:{type:"http",url:lt(be)}},plugins:[...Q.plugins,{source:L.manifest,grants:[...It],options:{cloudUrl:Re.href,workspaceId:G.workspaceId,agents:Q.agents,mcpUrl:new URL(`/w/${encodeURIComponent(G.workspaceId)}`,k.intent.origin).href,hostToolsPort:be,headers:{[c]:G.hostId,authorization:{$secret:"host:hightea"}}}}]}),console.log(`Host registered; local configuration saved. Start it with: ${ie(k.home)}`),0}catch(s){if(s instanceof ne)return console.error(or(s)),rr[s.kind];if(s instanceof Ee)return console.error(qn(s.file)),1;if(s instanceof ae)return console.error(Qn(s.file,s.entry)),1;if(s instanceof Ae)return console.error(er(s)),1;let f=s instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(s.message)?s.message:"HOST_JOIN_INPUT";return console.error(`${f}: ${q[f]??"Local claim storage could not be safely published or flushed. Keep the existing files, check filesystem access and retry; no replacement credential was selected."}`),1}}function He(e){return K(e)&&K(e.options)&&typeof(e.options.workspaceId??e.options.houseId)==="string"&&K(e.options.headers)&&typeof(e.options.headers[c]??e.options.headers[l])==="string"}async function ke(e){let t=P(e,"ahpd","config.json"),s;try{s=await oe(t,"utf8")}catch(N){return typeof N==="object"&&N!==null&&"code"in N&&N.code==="ENOENT"?{claim:e,state:"pending"}:{claim:e,state:"unreadable",config:t}}let f;try{f=JSON.parse(s)}catch{return{claim:e,state:"unreadable",config:t}}let a=(K(f)&&Array.isArray(f.plugins)?f.plugins:[]).find(He);if(a===void 0||typeof a.source!=="string"||!K(a.options)||!K(a.options.headers))return{claim:e,state:"unreadable",config:t};let h=a.source,S=await ce(h),T=!S.ok?S.reason:S.bundle.version===yt(F(h))?"ok":"wrong-version";return{claim:e,state:"joined",config:t,start:ie(e),pluginBundle:h,bundle:T,...S.ok?{pluginVersion:S.bundle.version}:{},workspaceId:String(a.options.workspaceId??a.options.houseId),hostId:String(a.options.headers[c]??a.options.headers[l]),...typeof a.options.cloudUrl==="string"?{gateway:a.options.cloudUrl}:{},signingKey:await sr(F(t)),...await ir(F(t))}}async function ir(e){let t=await Ot(e);if(t===void 0||t instanceof Error)return{};return{heldBundle:{from:t.from,toVersion:t.toVersion,connected:await St(e)===t.toVersion}}}async function sr(e){let t=await dt(e);if(t.state==="ok")return{state:"ok",keyId:t.key.trusted.keyId,publicKey:t.key.trusted.publicKey};return t}function ar(e){if(e===void 0||e.state==="missing")return"(made on this host's first start)";if(e.state==="unreadable")return`unreadable: ${e.reason}`;return`${e.keyId} public ${e.publicKey} (another machine trusts it with: hightea host trust add <name> ${e.publicKey})`}function dr(e,t){if(e===void 0)return"";return e===t?`, version ${e}`:`, version ${e}; this CLI is ${t}`}async function R(e){let t;try{t=P(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return console.error(`HOST_STATUS_UNSAFE_PATH: ${q.HOST_JOIN_UNSAFE_PATH}`),1}let s=[];try{s=(await le(t)).filter((a)=>!a.startsWith(".")).sort()}catch(a){if(!(typeof a==="object"&&a!==null&&("code"in a)&&a.code==="ENOENT"))return console.error(`HOST_STATUS_UNREADABLE: cannot list ${t}`),1}let f=await Promise.all(s.map((a)=>ke(P(t,a))));if(e.json)console.log(JSON.stringify({version:e.version,claims:t,hosts:f},null,2));else for(let a of f)if(a.state==="pending")console.log(`pending ${a.claim} (registration not finished; rerun the same join command)`);else if(a.state==="unreadable")console.log(`unreadable ${a.config}`);else console.log([`joined workspace ${a.workspaceId} host ${a.hostId}`,` gateway ${a.gateway??"(none)"}`,` config ${a.config}`,` start ${a.start}`,` plugin ${a.pluginBundle} (${a.bundle}${dr(a.pluginVersion,e.version)})`,` key ${ar(a.signingKey)}`,...a.heldBundle===void 0?[]:[` held ${a.heldBundle.from} until this host connects at ${a.heldBundle.toVersion}${a.heldBundle.connected?" (it has; the next `hightea host update` removes it)":""}`]].join(`
4
- `));let y=f.filter((a)=>a.state==="joined"&&a.bundle!=="ok");for(let a of y){let h=a.bundle==="missing"?"is missing":a.bundle==="corrupt"?"does not match its recorded hash":`records version ${a.pluginVersion}, not the version its directory names`,S=a.bundle==="wrong-version"?"Restore the bundle that directory name records, or re-join with a new code to install this CLI's bundle.":"Re-join with a new code to install this version's bundle.";console.error(`HOST_STATUS_PLUGIN_BUNDLE: the plugin bundle ${a.pluginBundle} ${h}; the host cannot load it. ${S}`)}if(y.length>0)return 2;if(f.some((a)=>a.state==="unreadable"))return console.error("HOST_STATUS_CONFIG_UNREADABLE: a saved host configuration could not be read; it was left unchanged."),1;if(!f.some((a)=>a.state==="joined"))return console.error(`HOST_STATUS_NONE: no joined host under ${t}.`),1;return 0}var It=["session:write","session:state","session:list","chat:turns","agent:list"],Te=["service:watch","service:logs","service:put","service:remove","service:start","service:stop","service:restart","service:accept"],ft=["services:list","services:get","services:put","services:delete","services:control"];async function n(e){let t;try{t=P(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`SERVICE_UNSAFE_PATH: ${q.HOST_JOIN_UNSAFE_PATH}`}}let s=[];try{s=(await le(t)).filter((h)=>!h.startsWith(".")).sort()}catch(h){if(!(typeof h==="object"&&h!==null&&("code"in h)&&h.code==="ENOENT"))return{error:`SERVICE_HOST_UNREADABLE: cannot list ${t}`}}let f=await Promise.all(s.map((h)=>ke(P(t,h)))),y=f.filter((h)=>h.state==="joined"),a=e?.trim();if(a!==void 0&&a!==""){let h=y.find((S)=>S.hostId===a);if(h===void 0)return{error:`SERVICE_HOST_UNKNOWN: no joined host ${a} on this machine (joined here: ${y.map((S)=>S.hostId).join(", ")||"none"})`};return ht(h)}if(y.length===0){let h=f.find((S)=>S.state==="unreadable");return{error:h===void 0?`SERVICE_NO_HOST: no joined host under ${t}; join this machine with \`hightea host join\` first`:`SERVICE_HOST_UNREADABLE: ${h.config} could not be read; it was left unchanged`}}if(y.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: this machine holds ${y.length} joined hosts (${y.map((h)=>h.hostId).join(", ")}); name one with --host <id>`};return ht(y[0])}function ht(e){let t=e.config;return{claim:e.claim,configDir:F(t),config:t,workspaceId:e.workspaceId,hostId:e.hostId,...e.gateway===void 0?{}:{gateway:e.gateway}}}async function i(e="/proc"){let t;try{t=await le(e)}catch{return[]}let s=[],f=new Set;for(let y of t){if(!/^\d+$/u.test(y))continue;let a;try{a=(await oe(P(e,y,"cmdline"),"utf8")).split("\x00").filter((k)=>k!=="")}catch{continue}let h=a.indexOf("--config-file"),S=h<0?void 0:a[h+1];if(S===void 0||!wt(S)||f.has(S))continue;f.add(S);let T=F(S),N=(k)=>{let J=a.indexOf(k),D=J<0?void 0:a[J+1];return D===void 0||D===""?void 0:D},I=N("--port"),E=I!==void 0&&/^\d{1,5}$/u.test(I)?Number(I):void 0,v=N("--connection-token-file"),H=N("--host")??"127.0.0.1";s.push({pid:Number(y),config:S,configDir:T,hostIds:await cr(S),host:H,...E===void 0?{}:{port:E},...v===void 0?{}:{connectionTokenFile:v}})}return s}async function cr(e){let t;try{t=JSON.parse(await oe(e,"utf8"))}catch{return[]}if(!K(t)||!Array.isArray(t.plugins))return[];let s=new Set;for(let f of t.plugins){if(!K(f)||!K(f.options)||!K(f.options.headers))continue;let y=f.options.headers[c]??f.options.headers[l];if(typeof y==="string"&&y!=="")s.add(y)}return[...s]}async function x(e){try{r(e.caller,"grant")}catch(H){return console.error(`${H.message}; nothing was changed`),1}let t=await n(e.host);if("error"in t)return console.error(t.error),1;let s=_t(t.config);if(!s.ok)return console.error(`SERVICE_CONFIG_UNREADABLE: ${t.config} could not be read as a JSON object; it was left unchanged`),1;let f=Array.isArray(s.value.plugins)?s.value.plugins:[],y=f.findIndex(He),a=f[y];if(a===void 0)return console.error(`SERVICE_CONFIG_UNREADABLE: ${t.config} holds no Hightea plugin entry; it was left unchanged`),1;if(a.grants!==void 0&&!(Array.isArray(a.grants)&&a.grants.every((H)=>typeof H==="string")))return console.error(`SERVICE_CONFIG_UNREADABLE: the Hightea plugin entry's grants in ${t.config} are not a list of grants; it was left unchanged`),1;let h=a.grants??[],S=[...Te,...ft],T=ft,N=h.filter((H)=>!T.includes(H)),I=e.enable?[...N,...Te.filter((H)=>!N.includes(H))]:h.filter((H)=>!S.includes(H)),E=`Hightea managing this machine's services (host ${t.hostId})`;if(I.length===h.length&&I.every((H,k)=>H===h[k]))return console.log(`${E} is already ${e.enable?"enabled":"disabled"}; ${t.config} was left unchanged.`),0;let v=f.slice();v[y]={...a,grants:I};try{Ne(t.config,{...s.value,plugins:v},{mode:384})}catch(H){return console.error(`SERVICE_CONFIG_UNWRITABLE: ${t.config}: ${H.message}`),1}return console.log(`${E} is now ${e.enable?"enabled":"disabled"}: ${e.enable?"added":"removed"} ${Te.join(", ")} in ${t.config}.`),console.log(`It takes effect when this host's ahpd next loads its configuration; restart it with: ${ie(t.claim)}`),0}function pt(e){let t=/^(\d+)\.(\d+)\.(\d+)(-dev\.[0-9a-f]{8})?$/u.exec(e);return t===null?void 0:[Number(t[1]),Number(t[2]),Number(t[3]),t[4]===void 0?1:0]}function lr(e,t){for(let s=0;s<4;s++)if(e[s]!==t[s])return e[s]-t[s];return 0}var X="pipe-update.json",ur="pipe-connected.json";async function Ot(e){let t;try{t=await oe(P(e,X),"utf8")}catch(f){return K(f)&&f.code==="ENOENT"?void 0:Error(`cannot read ${P(e,X)}`)}let s;try{s=JSON.parse(t)}catch{return Error(`${P(e,X)} is not JSON`)}if(!K(s)||typeof s.from!=="string"||typeof s.to!=="string"||typeof s.fromVersion!=="string"||typeof s.toVersion!=="string"||typeof s.at!=="string")return Error(`${P(e,X)} is not an update record`);return{from:s.from,to:s.to,fromVersion:s.fromVersion,toVersion:s.toVersion,at:s.at}}async function St(e){try{let t=JSON.parse(await oe(P(e,ur),"utf8"));return K(t)&&typeof t.version==="string"?t.version:void 0}catch{return}}async function gr(){let e;try{e=P(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`HOST_UPDATE_UNSAFE_PATH: ${q.HOST_JOIN_UNSAFE_PATH}`}}let t;try{t=(await le(e)).filter((s)=>!s.startsWith(".")).sort()}catch{return{error:`HOST_UPDATE_HOST_UNREADABLE: cannot list ${e}`}}return{claims:e,entries:await Promise.all(t.map((s)=>ke(P(e,s))))}}async function fr(e,t){let s,f;try{s=await Oe(F(e.from))}catch{return{refused:"it cannot be resolved"}}try{f=await Oe(_e(z("XDG_DATA_HOME",P(".local","share"))))}catch{return{refused:"the plugin bundles root cannot be resolved"}}if(F(s)!==f)return{refused:`it is not directly under the plugin bundles root ${f}`};if(yt(s)!==e.fromVersion)return{refused:`it is not the bundle directory of version ${e.fromVersion}`};for(let y of t){if(y.pluginBundle===void 0)continue;let a;try{a=await Oe(F(y.pluginBundle))}catch{continue}if(a===s)return{refused:`${y.config} names it now`}}return{directory:s}}async function mt(e){let t=await Ot(e.configDir);if(t===void 0)return;if(t instanceof Error){console.error(`HOST_UPDATE_RECORD_UNREADABLE: ${t.message}; no bundle was removed`);return}if(await St(e.configDir)!==t.toVersion){console.log(`Keeping the previous plugin bundle ${F(t.from)} until this host connects at ${t.toVersion}; restart it with: ${ie(e.claim)}`);return}let f=await gr();if("error"in f){console.error(`${f.error}; the previous bundle ${F(t.from)} was kept`);return}let y=f.entries.filter((h)=>h.pluginBundle===t.from||h.state==="unreadable");if(y.length>0){console.log(`Keeping the previous plugin bundle ${F(t.from)}: ${y.map((h)=>h.state==="unreadable"?`${h.config} (unreadable)`:h.config).join(", ")} may still name it.`);return}let a=await fr(t,f.entries);if("refused"in a){console.error(`HOST_UPDATE_PRUNE_REFUSED: ${F(t.from)}: ${a.refused}; nothing was removed`);return}try{await gt(a.directory,{recursive:!0,force:!0}),await gt(P(e.configDir,X),{force:!0})}catch(h){console.error(`HOST_UPDATE_PRUNE_FAILED: ${F(t.from)}: ${h.message}`);return}console.log(`Removed the previous plugin bundle ${F(t.from)} (${t.fromVersion}); this host has connected at ${t.toVersion}.`)}async function C(e,t){let s=await n(e.host);if("error"in s)return console.error(s.error.replace(/^SERVICE_/u,"HOST_UPDATE_")),1;let f=_t(s.config);if(!f.ok)return console.error(`HOST_UPDATE_CONFIG_UNREADABLE: ${s.config} could not be read as a JSON object; it was left unchanged`),1;let y=Array.isArray(f.value.plugins)?f.value.plugins:[],a=y.findIndex(He),h=y[a];if(h===void 0||typeof h.source!=="string")return console.error(`HOST_UPDATE_CONFIG_UNREADABLE: ${s.config} holds no Hightea plugin entry with a source; it was left unchanged`),1;let S=await ce(h.source);if(!S.ok)return console.error(`HOST_UPDATE_BUNDLE_UNREADABLE: the installed plugin bundle ${h.source} is ${S.reason}; nothing changed. \`hightea host status\` names the repair.`),1;let T=S.bundle.version,N=pt(T),I=pt(t.version);if(N===void 0||I===void 0)return console.error(`HOST_UPDATE_VERSION_UNREADABLE: cannot order the installed bundle ${T} against this CLI's ${t.version} (each must be x.y.z or x.y.z-dev.<hash8>); nothing changed`),1;let E=lr(I,N)||(t.version===T?0:1);if(E<0)return console.error(`HOST_UPDATE_DOWNGRADE: host ${s.hostId} runs plugin bundle ${T}, newer than this CLI's ${t.version}; nothing changed. Update the CLI instead.`),1;if(E===0)return console.log(`Host ${s.hostId} already runs plugin bundle ${T}; ${s.config} was left unchanged.`),await mt(s),0;await mt(s);let v;try{v=await Ie(z("XDG_DATA_HOME",P(".local","share")),t.directory,t.version)}catch(L){let G=L instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(L.message)?L.message:"HOST_JOIN_CONFIG_IO";return console.error(`${G.replace(/^HOST_JOIN_/u,"HOST_UPDATE_")}: ${q[G]??"the new bundle could not be installed"} ${s.config} was left unchanged.`),1}let H={from:h.source,to:v.manifest,fromVersion:T,toVersion:v.version,at:new Date().toISOString()},k=y.slice(),J=Array.isArray(h.grants)?h.grants.filter((L)=>typeof L==="string"):[],D=It.filter((L)=>!J.includes(L));k[a]={...h,source:v.manifest,...D.length===0?{}:{grants:[...J,...D]}};try{Ne(P(s.configDir,X),H,{mode:384}),Ne(s.config,{...f.value,plugins:k},{mode:384})}catch(L){return console.error(`HOST_UPDATE_CONFIG_UNWRITABLE: ${s.config}: ${L.message}`),1}return console.log(`Host ${s.hostId} now loads plugin bundle ${v.version} (was ${T}), same host id and credentials; ${s.config} changed only its source${D.length===0?"":` and added the missing ${D.join(", ")} grants`}.`),console.log(`The previous bundle ${F(h.source)} is kept until the host connects at ${v.version}. Restart it with: ${ie(s.claim)}`),0}function hr(e){if(e===void 0||e==="")throw Error("HOST_JOIN_RECEIPT_INVALID");return e}
5
- export{m,o,g,O,R,n,i,x,C};
@@ -1 +0,0 @@
1
- import{O,R,n,i,x,C}from"./chunk-c7atktnb.js";import"./chunk-ah99zytf.js";export{O as hostJoin,x as hostServicesGrants,R as hostStatus,C as hostUpdate,n as localHost,i as runningAhpds};
@@ -1 +0,0 @@
1
- import{h}from"./chunk-nfmmht3j.js";import"./chunk-c7atktnb.js";import"./chunk-ah99zytf.js";export{h as hostTrust};
@@ -1,13 +0,0 @@
1
- import"./chunk-dvsftn8z.js";import{t,e}from"./chunk-55a0ndzw.js";var E=`hightea service list (--host HOST --origin URL --workspace SLUG | --local [--host HOST]) [--json]
2
- `+`hightea service add|change NAME [--command CMD] [--cwd DIR] [--patch JSON] (--host … | --local)
3
- `+`hightea service remove|start|stop|restart NAME (--host … | --local)
4
- `+`hightea service logs NAME [--limit N] [--end N] (--host … | --local)
5
- `+`hightea service acknowledge (--host … | --local)
6
- `+`hightea service backup --host HOST --origin URL --workspace SLUG [--json]
7
- hightea service restore [NAME...] --from OLD_HOST (--host NEW_HOST | --local) --origin URL --workspace SLUG [--yes] [--json]
8
- hightea service enable|disable [--host HOST] (run on the machine)`,O=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n)&&typeof n.ok==="boolean"?n:void 0;function N(n,o){let r=encodeURIComponent((n.host??"").trim()),l=async(c,s,i,m)=>{let u=await e(n,o,{method:c,path:`/hosts/${r}/services${s}`,what:i,label:"SERVICE",...m===void 0?{}:{body:m}});if("error"in u){let f=O(u.body?.answer);return f===void 0?u:{answer:f}}let g=O(u.answer.answer);return g===void 0?{exit:1,error:`SERVICE_ANSWER_INVALID: ${i} answered without the host's answer: ${JSON.stringify(u.answer).slice(0,300)}`}:{answer:g}},a=(c)=>`/${encodeURIComponent(c)}`;return{machine:(n.host??"").trim(),list:()=>l("GET","","list"),put:(c)=>l("PUT",a(String(c.service.name)),"put",c),remove:(c)=>l("DELETE",a(c.name),"remove",{ifVersion:c.ifVersion}),control:(c,s)=>l("POST",`${a(c)}/${s}`,s),logs:(c)=>{let s=new URLSearchParams;if(c.end!==void 0)s.set("end",String(c.end));if(c.limit!==void 0)s.set("limit",String(c.limit));let i=s.size===0?"":`?${s}`;return l("GET",`${a(c.name)}/logs${i}`,"logs")},acknowledge:(c)=>l("POST","/acknowledge","acknowledge",c)}}async function T(n){let{localHost:o}=await import("./chunk-gbwfgq6g.js"),r=await o(n.host);if("error"in r)return r;let{localServices:l,LOG_LINES_MAX:a}=await import("@hallohuman/hightea-services"),c=l(r.configDir);if(typeof c==="string")return{error:`SERVICE_NOT_CONFIGURED: ${c}`};let s=(i)=>({answer:i});return{machine:c.machine.name,list:async()=>s(c.list()),put:async(i)=>s(await c.put(i)),remove:async(i)=>s(await c.remove(i)),control:async(i,m)=>s(await c.control(i,m)),logs:async(i)=>s(await c.logs({name:i.name,endOffset:i.end??0,limit:Math.min(i.limit??100,a)})),acknowledge:async(i)=>s(await c.acknowledge(i))}}async function J(n,o,r=t(),l={}){let a=!n.local;if(a&&((n.host??"").trim()===""||n.workspace.trim()===""))return r.err(`SERVICE_INPUT: name the host with --host and --workspace, or act on this machine with --local.
9
- ${E}`),1;let c=o.command!=="list"&&o.command!=="acknowledge",s=o.name?.trim()??"";if(c&&s==="")return r.err(`SERVICE_INPUT: ${o.command} names one service.
10
- ${E}`),1;let i=a?N(n,r):await(l.local??T)(n);if("error"in i)return r.err(i.error),1;let m=(u,g)=>{if("error"in u)return r.err(u.error),u.exit;let f=u.answer;if(!f.ok){if(r.err(`${String(f.code??"SERVICE_REFUSED")}: ${String(f.message??"the machine refused")}`),typeof f.diff==="string"&&f.diff!=="")r.err(f.diff);if(n.json)r.out(JSON.stringify(f));return 1}if(n.json)r.out(JSON.stringify(f));else g(f);return 0};switch(o.command){case"list":return m(await i.list(),(u)=>r.out(C(u,i.machine)));case"start":case"stop":case"restart":return m(await i.control(s,o.command),()=>r.out(`${o.command}: ${s} on ${i.machine}`));case"logs":{let u=A(o.end,0),g=A(o.limit,1);if(u===null||g===null)return r.err("SERVICE_INPUT: --end and --limit are whole numbers of lines; --limit is at least 1"),1;let f=await i.logs({name:s,...u===void 0?{}:{end:u},...g===void 0?{}:{limit:g}});return m(f,(w)=>{r.out(`raw output from ${s} on ${i.machine}:`);for(let h of Array.isArray(w.lines)?w.lines:[])r.out(String(h))})}case"acknowledge":case"add":case"change":case"remove":{let u=await i.list();if("error"in u)return r.err(u.error),u.exit;if(!u.answer.ok)return m(u,()=>{});let g=String(u.answer.ifVersion??""),w=(Array.isArray(u.answer.services)?u.answer.services:[]).some((d)=>d.name===s);if(o.command==="acknowledge"){let d=u.answer.hashes??{};return m(await i.acknowledge({hashes:d}),()=>r.out(`acknowledged ${Object.keys(d).join(", ")||"no files"} on ${i.machine} as they are now`))}if(o.command==="remove")return m(await i.remove({name:s,ifVersion:g}),()=>r.out(`removed ${s} on ${i.machine}`));if(o.command==="add"&&w)return r.err(`SERVICE_EXISTS: ${s} is already a service on ${i.machine}; use \`hightea service change\``),1;if(o.command==="change"&&!w)return r.err(`SERVICE_NOT_FOUND: ${s} is not a service on ${i.machine}; use \`hightea service add\``),1;let h=j(s,o.fields??{});if(typeof h==="string")return r.err(`SERVICE_INPUT: ${h}`),1;let y=P(u.answer.capabilities,h,i.machine);if(y!==void 0)return r.err(`SERVICE_UNSUPPORTED: ${y} Nothing was sent.`),1;if(o.command==="add"&&h.command===void 0)return r.err("SERVICE_INPUT: a new service needs --command"),1;return m(await i.put({service:h,ifVersion:g}),(d)=>r.out(d.changed===!1?`${s} on ${i.machine} already reads so; nothing was written`:`${o.command==="add"?"added":"changed"} ${s} on ${i.machine}`))}}}function j(n,o){let r={};if(o.patch!==void 0){try{r=JSON.parse(o.patch)}catch{return"--patch is a JSON object of service fields"}if(typeof r!=="object"||r===null||Array.isArray(r))return"--patch is a JSON object of service fields";if(r.name!==void 0&&r.name!==n)return"--patch names another service"}return{...r,name:n,...o.command===void 0?{}:{command:o.command},...o.cwd===void 0?{}:{cwd:o.cwd}}}function P(n,o,r){if(typeof n!=="object"||n===null)return;let{fields:l,schedule:a}=n;if(Array.isArray(l)){let s=Object.keys(o).filter((i)=>!l.includes(i));if(s.length>0)return`${r}'s driver does not take ${s.join(", ")}; it takes ${l.join(", ")}.`}let c=o.schedule;if(Array.isArray(a)&&typeof c==="object"&&c!==null){let i=Object.keys(c).filter((m)=>m==="cron"||m==="interval").filter((m)=>!a.includes(m));if(i.length>0)return`${r}'s driver does not take ${i.map((m)=>`schedule.${m}`).join(", ")}; it takes ${a.map((m)=>`schedule.${String(m)}`).join(", ")}.`}return}function A(n,o){if(n===void 0)return;return/^\d{1,7}$/u.test(n.trim())&&Number(n)>=o?Number(n):null}function C(n,o){let r=Array.isArray(n.services)?n.services:[],l=Array.isArray(n.readOnly)?n.readOnly:[],a=r.map((s)=>{let i=Array.isArray(s.plainEnv)&&s.plainEnv.length>0?` (plain env: ${s.plainEnv.join("; ")})`:"";return`${String(s.name)} ${String(s.command??"")}${i}`});for(let s of l)a.push(`${String(s.name)} read-only: ${String(s.reason)}`);if(a.length===0)a.push(`no services on ${o} (${String(n.file??"its file")})`);let c=U(n);if(c.length>0){a.push(`drift on ${o} (${c.length}), shown only; nothing was repaired:`);for(let s of c)a.push(` ${s.level}: ${s.text}`)}return a.join(`
11
- `)}function U(n){let o=(l)=>(Array.isArray(l)?l:[]).filter((a)=>p(a)&&typeof a.text==="string").map((a)=>({level:typeof a.level==="string"?a.level:"warning",text:String(a.text)})),r=Array.isArray(n.rows)?n.rows:[];return[...o(n.alerts),...r.flatMap((l)=>p(l)?o(l.alerts):[])]}var p=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n);async function x(n,o,r){let l=await e(n,o,{method:"GET",path:`/hosts/${encodeURIComponent(r)}/services/backup`,what:"backup",label:"SERVICE"});if("error"in l)return l;let a=l.answer.backup;if(!p(a)||typeof a.label!=="string"||!p(a.listing)||!Array.isArray(a.lines))return{exit:1,error:`SERVICE_ANSWER_INVALID: backup answered without a backup: ${JSON.stringify(l.answer).slice(0,300)}`};return{backup:a}}function D(n){if(n.unreadable===!0)return`unreadable line at ${String(n.offset)} (${String(n.bytes)} bytes)`;if(n.boundary===!0)return`--- ${String(n.message)} ---`;let o=p(n.refused)?` refused ${String(n.refused.code)}`:"",r=typeof n.name==="string"&&n.name!==""?` ${n.name}`:"";return`${String(n.at??"")} ${String(n.principal??"")} ${String(n.op??"")}${r}${o}`}async function H(n,o=t()){let r=(n.host??"").trim();if(r===""||n.workspace.trim()===""||n.local)return o.err(`SERVICE_INPUT: name the host with --host and --workspace; a backup is read from Hightea, never --local.
12
- ${E}`),1;let l=await x(n,o,r);if("error"in l)return o.err(l.error),l.exit;let{backup:a}=l;if(n.json)return o.out(JSON.stringify(a)),0;let c=a.hostStatus==="revoked"?`revoked ${a.revokedAt??""}`.trim():a.connected?"connected":"offline";if(o.out(`${r} (${c}): ${a.label}`),typeof a.reason==="string")o.out(`last pull: ${a.reason}`);o.out(C({ok:!0,...a.listing},r)),o.out(a.lines.length===0?"no changes backed up":`changes, oldest first (${a.lines.length}):`);for(let{line:s}of a.lines)o.out(` ${D(s)}`);return 0}function L(){return{...t(),confirm:async(n)=>{let{createInterface:o}=await import("node:readline/promises"),r=o({input:process.stdin,output:process.stderr});try{return/^y(es)?$/iu.test((await r.question(n)).trim())}finally{r.close()}}}}async function B(n,o,r=L(),l={}){let a=o.from.trim(),c=(n.host??"").trim();if(a===""||n.workspace.trim()===""||!n.local&&c==="")return r.err(`SERVICE_INPUT: restore names the old host with --from, the workspace with --workspace, and the new host with --host or --local.
13
- ${E}`),1;let s=await x(n,r,a);if("error"in s)return r.err(s.error),s.exit;let{backup:i}=s,m=Array.isArray(i.listing.services)?i.listing.services.filter(p):[],u=o.names.filter((d)=>!m.some((S)=>S.name===d));if(u.length>0)return r.err(`SERVICE_NOT_IN_BACKUP: ${u.join(", ")} ${u.length===1?"is":"are"} not in ${a}'s backup (${i.label}); it holds ${m.map((d)=>String(d.name)).join(", ")||"no services"}`),1;let g=o.names.length===0?m:m.filter((d)=>o.names.includes(String(d.name)));if(g.length===0)return r.err(`SERVICE_NOTHING_TO_RESTORE: ${a}'s backup (${i.label}) holds no services`),1;let f=n.local?await(l.local??T)(n):N(n,r);if("error"in f)return r.err(f.error),1;let w=(d)=>p(d.env)?Object.entries(d.env).map(([S,v])=>`${S} (${String(p(v)?v.$secret:v)})`):[],h=(d)=>Array.isArray(d.plainEnv)?d.plainEnv.map(String):[];r.err(`restore from ${a} (${i.label}) to ${f.machine}, create only:`);for(let d of g){r.err(` ${String(d.name)} ${String(d.command??"")}`);let S=w(d);if(S.length>0)r.err(` secrets to enter again on ${f.machine}: ${S.join(", ")}`)}if(!o.yes&&!await r.confirm(`create ${g.length} service${g.length===1?"":"s"} on ${f.machine}? [y/N] `))return r.err("SERVICE_RESTORE_DECLINED: nothing was sent"),1;let y=[];for(let d of g){let{plainEnv:S,...v}=d,R=String(d.name),b=w(d),I=h(d),k=await f.put({service:v,ifVersion:"absent"});if("error"in k){let[V="SERVICE_FAILED",..._]=k.error.split(": ");y.push({name:R,outcome:"failed",code:V,message:_.join(": "),secrets:b,plainEnv:I})}else if(!k.answer.ok)y.push({name:R,outcome:"refused",code:String(k.answer.code??"SERVICE_REFUSED"),message:String(k.answer.message??""),secrets:b,plainEnv:I});else y.push({name:R,outcome:"created",secrets:b,plainEnv:I})}if(n.json)r.out(JSON.stringify({from:a,to:f.machine,label:i.label,results:y}));else for(let d of y){if(r.out(d.outcome==="created"?`created ${d.name}`:`${d.outcome} ${d.name}: ${d.code}: ${d.message}`),d.outcome==="created"&&d.secrets.length>0)r.out(` secrets to enter again: ${d.secrets.join(", ")}`);if(d.outcome==="created"&&d.plainEnv.length>0)r.out(` plain values never backed up: ${d.plainEnv.join("; ")}`)}return y.every((d)=>d.outcome==="created")?0:1}export{H as serviceBackupCommand,J as serviceCommand,B as serviceRestore};
@@ -1 +0,0 @@
1
- import{s,f,I,v,N}from"./chunk-dvsftn8z.js";export{I as authLogin,N as authLogout,v as authStatus,s as checkedOrigin,f as ensureCredential};