@hallohuman/hightea 0.1.34 → 0.1.35

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.
@@ -1,5 +1,5 @@
1
- import{_,A,l,a,d,u,p,w}from"./chunk-tay0pyz4.js";import{r}from"./chunk-evg5apz3.js";import{readdir as ue,readFile as q,realpath as Te,rm as hn}from"node:fs/promises";import{createRequire as xt}from"node:module";import{homedir as Ft,hostname as Kt}from"node:os";import{basename as ie,dirname as L,isAbsolute as In,join as J,resolve as jt}from"node:path";import{fromEnvRef as Gt,isRecord as U,readJsonObject as On,readSecret as Bt,secretRef as Mt,writeJsonAtomic as Ae}from"@ahpd/sdk";import{fileVault as Vt}from"@ahpd/server/dist/vault.js";import{createHash as $e,randomBytes as En}from"node:crypto";import{constants as ne}from"node:fs";import{link as An,lstat as he,mkdir as Ue,mkdtemp as Hn,open as Pe,realpath as Rn,rm as kn}from"node:fs/promises";import{dirname as ae,join as M}from"node:path";import{isDeepStrictEqual as Je}from"node:util";import{fileVault as Le}from"@ahpd/server/dist/vault.js";function v(e){throw Error(e)}function xe(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(xe(s)!=="EEXIST")v("HOST_JOIN_CUSTODY_IO")});let t=await he(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&63)!==0)v("HOST_JOIN_UNSAFE_PATH")}async function bn(e){let t=await Pe(e,ne.O_RDONLY|ne.O_DIRECTORY|ne.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}}async function Z(e){let t=await Pe(e,ne.O_RDONLY|ne.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}for(let s=ae(e);;s=ae(s))if(await bn(s),s===ae(s))break}function pe(e){if(typeof e.origin!=="string"||typeof e.workspaceSlug!=="string"||typeof e.code!=="string"||typeof e.pluginVersion!=="string"||typeof e.ahpdVersion!=="string")v("HOST_JOIN_INVALID_INTENT");let t;try{t=new URL(e.origin)}catch{return v("HOST_JOIN_INVALID_INTENT")}let s=l(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)v("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 f=y.codePointAt(0)??0;return f<32||f===127})))v("HOST_JOIN_INVALID_INTENT");if(e.app!==void 0&&!A(e.app))v("HOST_JOIN_INVALID_INTENT");if(e.hostId!==void 0&&(typeof e.hostId!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(e.hostId)))v("HOST_JOIN_INVALID_INTENT");if(e.ownerConfiguration===null&&e.app===void 0)v("HOST_JOIN_INVALID_INTENT");let c;try{c=e.ownerConfiguration===null?null:JSON.parse(JSON.stringify(e.ownerConfiguration))}catch{return v("HOST_JOIN_INVALID_INTENT")}if(c!==null&&(typeof c!=="object"||!Je(c,e.ownerConfiguration)))v("HOST_JOIN_INVALID_INTENT");return{...e,origin:t.origin,code:s,ownerConfiguration:c}}async function Fe(e,t){let s=pe(t),c=await je(e),y=M(c,"hightea"),f=M(y,"claims"),I=$e("sha256").update(JSON.stringify([s.origin,s.workspaceSlug,s.code])).digest("hex"),O=M(f,I),S=M(O,"ahpd");try{for(let T of[y,f,O,S])await Y(T);let E=M(S,"vault.json"),h=await Hn(M(S,".claim-"));try{let T=M(h,"vault.json"),b=Le({file:T});await b.set("host:hightea",`Bearer ${En(32).toString("base64url")}`),await b.set("host:hightea-join",JSON.stringify({schema:1,...s}));try{await An(T,E)}catch(D){if(xe(D)!=="EEXIST")v("HOST_JOIN_CUSTODY_PUBLICATION_FAILED")}let{authorization:H,credentialHash:k,intent:F}=await Ge(E);if(F.origin!==s.origin||F.workspaceSlug!==s.workspaceSlug||F.code!==s.code||F.app!==s.app||F.hostId!==s.hostId||!Je(F.ownerConfiguration,s.ownerConfiguration))v("HOST_JOIN_CLAIM_CONFLICT");return await Z(E),{home:O,vaultFile:E,authorization:H,credentialHash:k,intent:F}}finally{await kn(h,{recursive:!0})}}catch(E){if(E instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(E.message))throw E;return v("HOST_JOIN_CUSTODY_IO")}}async function Ke(e,t,s){let c=pe(s);if(c.hostId===void 0)v("HOST_JOIN_INVALID_INTENT");try{let y=await je(e),f=M(y,"hightea"),I=M(f,"claims");if(ae(t)!==I)v("HOST_JOIN_NO_CLAIM_FOR_HOST");let O=M(t,"ahpd");for(let h of[f,I,t,O])await Y(h);let S=M(O,"vault.json"),E=await Ge(S);if(E.intent.origin!==c.origin||E.intent.workspaceSlug!==c.workspaceSlug||E.intent.hostId!==void 0&&c.hostId!==E.intent.hostId)v("HOST_JOIN_CLAIM_CONFLICT");return await Z(S),{home:t,vaultFile:S,authorization:E.authorization,credentialHash:E.credentialHash,intent:c}}catch(y){if(y instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(y.message))throw y;return v("HOST_JOIN_NO_CLAIM_FOR_HOST")}}async function je(e){try{await Ue(e,{recursive:!0,mode:448});let t=await he(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&18)!==0)v("HOST_JOIN_UNSAFE_PATH");return await Rn(e)}catch{return v("HOST_JOIN_UNSAFE_PATH")}}async function Ge(e){let t=await he(e);if(!t.isFile()||t.uid!==process.getuid?.()||(t.mode&511)!==384)v("HOST_JOIN_UNSAFE_PATH");let s=Le({file:e}),c=await s.get("host:hightea"),y=await s.get("host:hightea-join");if(!c||!/^Bearer [A-Za-z0-9_-]{43}$/u.test(c)||!y)v("HOST_JOIN_CLAIM_CORRUPT");let f;try{f=JSON.parse(y)}catch{return v("HOST_JOIN_CLAIM_CORRUPT")}if(!f||typeof f!=="object"||!("schema"in f)||f.schema!==1)v("HOST_JOIN_CLAIM_CORRUPT");let I;try{I=pe(f)}catch{return v("HOST_JOIN_CLAIM_CORRUPT")}return{authorization:c,credentialHash:`sha256:${$e("sha256").update(c.slice(7),"utf8").digest("hex")}`,intent:I}}import{link as vn,lstat as Cn,mkdtemp as Dn,rm as $n}from"node:fs/promises";import{join as te}from"node:path";import{isDeepStrictEqual as Un}from"node:util";import{isRecordSlug as Pn,readJsonObject as Jn,writeJsonAtomic as Be}from"@ahpd/sdk";async function Me(e,t){return We(e,te(e.home,"ahpd"),"config.json",t)}async function Ve(e,t){if(!Pn(t.id))throw Error("HOST_JOIN_CONFIG_CONFLICT");let s=te(e.home,"ahpd","agents");await Y(s),await We(e,s,`${t.id}.json`,{...t})}async function We(e,t,s,c){let y=te(t,s),f;try{if(JSON.stringify(c).includes(e.authorization))throw Error("HOST_JOIN_CONFIG_SECRET");f=await Dn(te(t,".config-"));let I=te(f,"config.json");Be(I,c,{mode:384});try{await vn(I,y)}catch(h){if(!h||typeof h!=="object"||!("code"in h)||h.code!=="EEXIST")throw Error("HOST_JOIN_CONFIG_PUBLICATION_FAILED")}let O=await Cn(y);if(!O.isFile()||O.uid!==process.getuid?.()||(O.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");let S=Jn(y);if(!S.ok)throw Error("HOST_JOIN_CONFIG_CORRUPT");let E={};for(let[h,T]of Object.entries(c)){let b=h==="unattendedAutoApprove"&&T===!1||h==="pluginMarketplaces"&&Array.isArray(T)&&T.length===0;if(s==="config.json"&&b&&!Object.hasOwn(S.value,h)){E[h]=T;continue}if(!Un(S.value[h],T))throw Error("HOST_JOIN_CONFIG_CONFLICT")}if(Object.keys(E).length>0)Be(y,{...S.value,...E},{mode:384});return await Z(y),y}catch(I){if(I instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(I.message))throw I;throw Error("HOST_JOIN_CONFIG_IO")}finally{if(f!==void 0)await $n(f,{recursive:!0})}}import{isRecord as W}from"@ahpd/sdk";class re extends Error{kind;status;serverCode;constructor(e,t,s){super(e);this.kind=e;this.status=t;this.serverCode=s}}function Ln(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 ze(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}})}),c;try{c=await fetch(s)}catch{throw Error("HOST_JOIN_NETWORK_UNKNOWN")}if(c.status===410){let f;try{f=await c.json()}catch{}if(W(f)&&W(f.error)&&f.error.code==="HOST_REGISTRATION_CANCELLED")throw Error("HOST_JOIN_CANCELLED");throw Error("HOST_JOIN_LINK_UNAVAILABLE")}if(c.status>=500){let f;try{f=await c.json()}catch{}let I=W(f)&&W(f.error)&&_(f.error.code)?f.error.code:void 0;if(I==="HOST_REGISTRATION_UNSETTLED")throw new re("HOST_JOIN_UNSETTLED",c.status,I);throw Error("HOST_JOIN_REMOTE_UNAVAILABLE")}if(!c.ok){let f;try{f=await c.json()}catch{}let I=W(f)&&W(f.error)&&_(f.error.code)?f.error.code:void 0;throw new re(Ln(c.status,I),c.status,I)}let y;try{y=await c.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 xn,stat as me}from"node:fs/promises";import{constants as Fn}from"node:fs";import{delimiter as Kn,dirname as Ye,isAbsolute as jn,join as Gn}from"node:path";import{fileURLToPath as Bn}from"node:url";import{fromEnvRef as Mn,isRecord as V,isRecordSlug as Vn,readJsonObject as Wn,scopeOf as zn,secretPaths as Yn,secretRef as Zn}from"@ahpd/sdk";import{checkManifest as Xn,checkStandalone as qn,readManifest as Qn,readStandalone as et,resolvePlugin as nt}from"@ahpd/server/dist/plugins.js";function P(e="HOST_JOIN_OWNER_RESOURCE"){throw Error(e)}function Ze(e){let t=Mn(e);if(t!==void 0){if(!process.env[t])P();return!0}let s=Zn(e);if(s===void 0)return!1;return zn(s),!0}async function tt(e){let t=jn(e)?[e]:(process.env.PATH??"").split(Kn).map((s)=>Gn(s,e));for(let s of t)try{if(await xn(s,Fn.X_OK),(await me(s)).isFile())return}catch{}P()}async function oe(e){let t=Wn(e);if(!t.ok)P("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))P();let c=new Set,y=new Set,f=[];try{for(let h of s.plugins){let T=typeof h==="string"?{source:h}:h;if(!V(T)||typeof T.source!=="string"||T.enabled===!1)P();let H=nt(T,{cwd:Ye(e),configDir:Ye(e)});if(!H.path||!(await me(H.path)).isFile())P();let k=H.manifestPath?et(H.manifestPath):H.packageDir?Qn(H.packageDir):void 0;if(!k||k.problem||(k.standalone?qn(k):Xn(k,H.packageDir)))P();if(k.name==="@ahpd/bot"||k.name==="bot")P("HOST_JOIN_OWNER_BOT");for(let D of k.contracts?.engines??[])c.add(D);for(let D of k.contracts?.agents??[])y.add(D);if(T.options!==void 0&&!V(T.options))P();let F=V(T.options)?T.options:{};for(let D of Yn(k.optionsSchema??{},F)){let K=F;for(let G of D.split("."))K=V(K)?K[G]:void 0;if(K!==void 0&&!Ze(K))P("HOST_JOIN_OWNER_SECRET")}f.push({...T,source:H.manifestPath??H.packageDir??H.path})}let I=[],O=new Set(y);for(let h of s.records){if(!V(h)||typeof h.id!=="string"||!Vn(h.id)||O.has(h.id)||typeof h.engine!=="string"||!c.has(h.engine)||typeof h.owner!=="string"||typeof h.name!=="string"||!V(h.config)||h.mode!==void 0&&h.mode!=="enabled")P();if(h.model!==void 0&&(typeof h.model!=="string"||h.model.trim()===""))P();if(h.engine==="acp"&&typeof h.config.command!=="string")P();if(h.config.command!==void 0){if(typeof h.config.command!=="string"||!h.config.command)P();await tt(h.config.command)}if(h.config.env!==void 0){if(!V(h.config.env))P();for(let T of Object.values(h.config.env))if(!Ze(T))P("HOST_JOIN_OWNER_SECRET")}O.add(h.id),I.push(h)}let S=[],E=new Set;for(let h of s.agents){if(!Array.isArray(h)||h.length!==2||typeof h[0]!=="string"||!h[0]||E.has(h[0])||!V(h[1])||typeof h[1].provider!=="string"||!O.has(h[1].provider)||typeof h[1].workingDirectory!=="string")P();let T=new URL(h[1].workingDirectory);if(T.protocol!=="file:"||T.hostname||!(await me(Bn(T))).isDirectory())P();if(h[1].settings!==void 0&&!V(h[1].settings))P();E.add(h[0]),S.push([h[0],{provider:h[1].provider,workingDirectory:T.href,...h[1].settings===void 0?{}:{settings:h[1].settings}}])}return{agents:S,plugins:f,records:I}}catch(I){if(I instanceof Error&&/^HOST_JOIN_OWNER_[A-Z_]+$/u.test(I.message))throw I;return P()}}import{constants as rt}from"node:fs";import{access as ot,mkdir as it,stat as st,writeFile as at}from"node:fs/promises";import{createRequire as dt}from"node:module";import{dirname as qe,resolve as Qe}from"node:path";import{pathToFileURL as ct}from"node:url";class de extends Error{file;entry;constructor(e,t){super("HOST_JOIN_OWNER_CONFIG_NEEDS_AGENT");this.file=e;this.entry=t}}function lt(){try{return qe(dt(import.meta.url).resolve("@ahpd/agent-acp/package.json"))}catch{throw Error("HOST_JOIN_AGENT_PLUGIN_MISSING")}}function en(e,t,s){return[t,{provider:e.id,workingDirectory:ct(Qe(s)).href}]}function ut(e,t,s){return JSON.stringify(en(e,t,s))}function gt(e,t){let[s,c]=en(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,c]]},null,2)}
2
- `}async function nn(e){let t=Qe(e.file);if(await ot(t,rt.F_OK).then(()=>!0,()=>!1))return Xe(t,e);await it(qe(t),{recursive:!0,mode:448});try{await at(t,gt(e,lt()),{flag:"wx",mode:384})}catch(c){if(c!==null&&typeof c==="object"&&"code"in c&&c.code==="EEXIST")return Xe(t,e);throw Error("HOST_JOIN_OWNER_FILE_IO")}let s=await st(t);if(!s.isFile()||s.uid!==process.getuid?.()||(s.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");return oe(t)}async function Xe(e,t){let s=await oe(e);if(s.agents.some(([c])=>c===t.agentMemberId))return s;throw new de(e,ut(t.app,t.agentMemberId,t.workingDirectory))}import{access as Wt}from"node:fs/promises";import{constants as zt}from"node:fs";import{createHash as ft}from"node:crypto";import{lstat as tn,mkdir as ht,mkdtemp as pt,readFile as we,rename as mt,rm as yt,writeFile as ye}from"node:fs/promises";import{isAbsolute as rn,join as j,normalize as ce}from"node:path";var wt="hightea-pipe",Ie="bundle.json";function Oe(e){return j(e,"hightea","plugins")}async function on(e){let t;try{t=await we(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 c=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,f=typeof s==="object"&&s!==null&&"version"in s?s.version:void 0;if(y!==wt||typeof f!=="string"||typeof c!=="string"||rn(c)||ce(c).startsWith("..")||ce(c).includes("/")||["plugin.json",Ie].includes(ce(c)))throw Error("HOST_JOIN_PLUGIN_BUNDLE");let I;try{I=await we(j(e,c))}catch{throw Error("HOST_JOIN_PLUGIN_BUNDLE")}return{manifestBytes:t,version:f,main:ce(c),mainBytes:I,sha256:_t(t,I)}}function _t(e,t){return ft("sha256").update(e).update("\x00").update(t).digest("hex")}async function le(e){let t=j(e,".."),s;try{s=JSON.parse(await we(j(t,Ie),"utf8"))}catch(y){return{ok:!1,reason:sn(y)?"missing":"corrupt"}}let c;try{c=await on(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!==c.sha256)return{ok:!1,reason:"corrupt"};return{ok:!0,bundle:{manifest:e,version:s.version,sha256:c.sha256}}}async function Se(e,t,s){if(!rn(e)||!/^[0-9A-Za-z.+-]+$/u.test(s))throw Error("HOST_JOIN_UNSAFE_PATH");let c=await on(t);if(c.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE");try{await ht(e,{recursive:!0,mode:448});let S=await tn(e);if(!S.isDirectory()||S.uid!==process.getuid?.()||(S.mode&18)!==0)throw Error("unsafe")}catch{throw Error("HOST_JOIN_UNSAFE_PATH")}let y=Oe(e);for(let S of[j(e,"hightea"),y])await Y(S);let f=j(y,s),I=j(f,"plugin.json");if(!await It(f)){let S=await pt(j(y,`.${s}-`));try{await ye(j(S,"plugin.json"),c.manifestBytes,{mode:384}),await ye(j(S,c.main),c.mainBytes,{mode:384}),await ye(j(S,Ie),`${JSON.stringify({version:s,sha256:c.sha256})}
3
- `,{mode:384});try{await mt(S,f)}catch(E){if(!_e(E,"EEXIST")&&!_e(E,"ENOTEMPTY"))throw Error("HOST_JOIN_CONFIG_IO")}}finally{await yt(S,{recursive:!0,force:!0})}}let O=await le(I);if(!O.ok||O.bundle.sha256!==c.sha256||O.bundle.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE_CONFLICT");return O.bundle}async function It(e){try{return await tn(e),!0}catch(t){if(sn(t))return!1;throw Error("HOST_JOIN_UNSAFE_PATH")}}function sn(e){return _e(e,"ENOENT")}function _e(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}import{createPrivateKey as kt,createPublicKey as bt,generateKeyPairSync as vt,sign as po}from"node:crypto";import{appendFile as yo,chmod as Ct,readFile as an,rename as Dt,writeFile as $t}from"node:fs/promises";import{join as dn}from"node:path";var io=Buffer.from("302a300506032b6570032100","hex");import{createHash as St}from"node:crypto";import{existsSync as Tt,readFileSync as Nt}from"node:fs";import{join as Et}from"node:path";var At="trusted-keys.json",m=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,Ht=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,Rt=(e)=>Buffer.from(e).toString("base64url");function o(e){if(!Ht.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:Rt(St("sha256").update(Buffer.from(e,"base64url")).digest())}}function g(e){let t=Et(e,At);if(!Tt(t))return{state:"missing",file:t};let s;try{s=JSON.parse(Nt(t,"utf8"))}catch(y){throw Error(`TRUST_FILE_UNREADABLE: ${t} is not JSON (${y.message})`)}let c=s;if(typeof s!=="object"||s===null||c.v!==1||!Array.isArray(c.keys))throw Error(`TRUST_FILE_UNREADABLE: ${t} is not a version 1 list of trusted keys`);for(let y of c.keys){let f=y,I=typeof f.publicKey==="string"?o(f.publicKey):void 0;if(typeof f.name!=="string"||!m.test(f.name)||I===void 0||"error"in I||f.keyId!==I.keyId||typeof f.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:c.keys}}var cn="host-signing-key";async function ln(e){try{await an(dn(e,cn))}catch(t){if(t.code==="ENOENT")return{state:"missing"}}try{return{state:"ok",key:await Ut(e)}}catch(t){return{state:"unreadable",reason:t instanceof Error?t.message:String(t)}}}async function Ut(e,t=()=>Date.now()){let s=dn(e,cn),c;try{c=await an(s,"utf8")}catch(O){if(O.code!=="ENOENT")throw Error(`HOST_KEY_UNREADABLE: ${s} exists but cannot be read (${String(O)}); it is never regenerated, fix or remove it by hand`)}if(c===void 0){let O=vt("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),S=`${s}.${String(process.pid)}.tmp`;await $t(S,O,{mode:384,flag:"wx"}),await Ct(S,384),await Dt(S,s),c=O}let y;try{if(y=kt({key:c,format:"pem"}),y.asymmetricKeyType!=="ed25519")throw Error(`a ${String(y.asymmetricKeyType)} key, not Ed25519`)}catch(O){throw Error(`HOST_KEY_UNREADABLE: ${s} is not an Ed25519 PKCS8 key (${String(O)}); it is never regenerated, fix or remove it by hand`)}let f=bt(y).export({format:"jwk"}).x,I=f===void 0?{error:"no public key"}:o(f);if("error"in I)throw Error(`HOST_KEY_UNREADABLE: ${s}: ${I.error}`);return{privateKey:y,trusted:{name:"this-host",keyId:I.keyId,publicKey:f,addedAt:new Date(t()).toISOString()}}}import{createServer as Pt}from"node:net";var un="hightea";function gn(e){return`http://127.0.0.1:${String(e)}/mcp`}function Jt(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 fn(e){let t=Jt(e);for(let s=0;s<200;s+=1){let c=40000+(t-40000+s)%20000;if(await Lt(c))return c}throw Error(`HOST_TOOLS_PORT_UNAVAILABLE: every port from ${String(t)} to ${String(t+199)} on 127.0.0.1 is taken`)}async function Lt(e){let t=Pt();return await new Promise((s)=>{t.once("error",()=>{s(!1)}),t.listen(e,"127.0.0.1",()=>{t.close(()=>{s(!0)})})})}var Yt="hightea host join --origin https://your-deployment --workspace SLUG --code CODE --owner-config /absolute/owner.json",Zt=(e)=>[...e].some((t)=>{let s=t.codePointAt(0)??0;return s<32||s===127});function Xt(e=Kt()){let t=e.trim();return t===""||t.length>64||Zt(t)?void 0:t}var qt="https://hightea.ai/docs/host#owner";class He extends Error{file;constructor(e){super("HOST_JOIN_OWNER_CONFIG_MISSING");this.file=e}}var Qt=(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 ${qt} — then run the same command again. Nothing was redeemed and nothing was written.`,er=(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 Re extends Error{appName;install;constructor(e,t){super("HOST_JOIN_APP_MISSING");this.appName=e;this.install=t}}var nr=(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: ${Yt}`,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]||J(Ft(),t);if(!In(s))throw Error("HOST_JOIN_UNSAFE_PATH");return s}function tr(){let e=xt(import.meta.url).resolve("@ahpd/server/package.json");return{node:process.execPath,main:J(L(e),"dist","main.js")}}var Ne=(e)=>`'${e.replaceAll("'","'\\''")}'`;function se(e,t=tr()){return`XDG_CONFIG_HOME=${Ne(e)} ${Ne(t.node)} ${Ne(t.main)} start`}var rr={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"},or={HOST_JOIN_NOT_AUTHORIZED:3,HOST_JOIN_AGENT_BOUND:4,HOST_JOIN_REJECTED:1,HOST_JOIN_UNSETTLED:2};function ir(e){let t=e.serverCode===void 0?"":` The deployment says ${rr[e.serverCode]}.`;return`${e.kind}: ${Q[e.kind]}${t} (HTTP ${e.status}, server code ${e.serverCode??"unrecognised"})`}async function N(e,t){try{let{origin:s,workspace:c,code:y,ownerConfig:f}=e;if(!s||!c||!y||!f)throw Error("HOST_JOIN_USAGE");let I=jt(f),O=await Wt(I,zt.F_OK).then(()=>!0,()=>!1);if(!O&&e.ownerConfigIsDefault!==!0)throw Error("HOST_JOIN_OWNER_INPUT");if(!O&&e.app===void 0)throw new He(I);let S=e.app===void 0?void 0:p(e.app);if(S!==void 0&&!await w(S))throw new Re(S.name,u(S));let E=O?await oe(I):null,h=z("XDG_CONFIG_HOME",".config"),T=z("XDG_DATA_HOME",J(".local","share")),b=Xt(),H={origin:s,workspaceSlug:c,code:y,pluginVersion:t.version,ahpdVersion:"0.15.0-rc.4",ownerConfiguration:E,...b===void 0?{}:{name:b},...e.app===void 0?{}:{app:e.app},...e.hostId===void 0?{}:{hostId:e.hostId}},k;if(e.hostId===void 0)k=await Fe(h,H);else{let B=await n(e.hostId);if("error"in B)throw Error("HOST_JOIN_NO_CLAIM_FOR_HOST");k=await Ke(h,B.claim,H)}if(k.intent.pluginVersion!==t.version)throw Error("HOST_JOIN_CLAIM_VERSION");let F=Vt({file:k.vaultFile}),D=async(B)=>{let Ce=Mt(B),De=Gt(B);if(De!==void 0){if(!process.env[De])throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(Ce!==void 0)try{await Bt(F,Ce)}catch{throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(Array.isArray(B))for(let fe of B)await D(fe);else if(U(B))for(let fe of Object.values(B))await D(fe)};if(E!==null)await D(E);let K=await Se(T,t.directory,t.version),G=await ze(k);if(G.state==="pending")return console.log("Host registration pending. Run the same command again to resume."),2;let ee=S===void 0?E:await nn({file:I,app:S,agentMemberId:_r(G.agentMemberId),workingDirectory:e.workingDirectory??process.cwd()});if(ee===null)throw Error("HOST_JOIN_OWNER_INPUT");if(S!==void 0)await D(ee);for(let B of ee.records)await Ve(k,B);let be=new URL(`/gateway/${encodeURIComponent(G.workspaceId)}/host`,k.intent.origin);be.protocol="wss:";let ve=await fn(k.home);return await Me(k,{host:"127.0.0.1",updateCheck:!1,httpApi:!1,modelApi:!1,mcpTools:"none",unattendedAutoApprove:!1,pluginMarketplaces:[],mcpServers:{[un]:{type:"http",url:gn(ve)}},plugins:[...ee.plugins,{source:K.manifest,grants:[...Sn],options:{cloudUrl:be.href,workspaceId:G.workspaceId,agents:ee.agents,mcpUrl:new URL(`/w/${encodeURIComponent(G.workspaceId)}`,k.intent.origin).href,hostToolsPort:ve,headers:{[a]:G.hostId,authorization:{$secret:"host:hightea"}}}}]}),console.log(`Host registered; local configuration saved. Start it with: ${se(k.home)}`),0}catch(s){if(s instanceof re)return console.error(ir(s)),or[s.kind];if(s instanceof He)return console.error(Qt(s.file)),1;if(s instanceof de)return console.error(er(s.file,s.entry)),1;if(s instanceof Re)return console.error(nr(s)),1;let c=s instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(s.message)?s.message:"HOST_JOIN_INPUT";return console.error(`${c}: ${Q[c]??"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 ge(e){return U(e)&&U(e.options)&&typeof(e.options.workspaceId??e.options.houseId)==="string"&&U(e.options.headers)&&typeof(e.options.headers[a]??e.options.headers[d])==="string"}async function ke(e){let t=J(e,"ahpd","config.json"),s;try{s=await q(t,"utf8")}catch(E){return typeof E==="object"&&E!==null&&"code"in E&&E.code==="ENOENT"?{claim:e,state:"pending"}:{claim:e,state:"unreadable",config:t}}let c;try{c=JSON.parse(s)}catch{return{claim:e,state:"unreadable",config:t}}let f=(U(c)&&Array.isArray(c.plugins)?c.plugins:[]).find(ge);if(f===void 0||typeof f.source!=="string"||!U(f.options)||!U(f.options.headers))return{claim:e,state:"unreadable",config:t};let I=f.source,O=await le(I),S=!O.ok?O.reason:O.bundle.version===ie(L(I))?"ok":"wrong-version";return{claim:e,state:"joined",config:t,start:se(e),pluginBundle:I,bundle:S,...O.ok?{pluginVersion:O.bundle.version}:{},workspaceId:String(f.options.workspaceId??f.options.houseId),hostId:String(f.options.headers[a]??f.options.headers[d]),...typeof f.options.cloudUrl==="string"?{gateway:f.options.cloudUrl}:{},signingKey:await ar(L(t)),...await sr(L(t))}}async function sr(e){let t=await Tn(e);if(t===void 0||t instanceof Error)return{};return{heldBundle:{from:t.from,toVersion:t.toVersion,connected:await Nn(e)===t.toVersion}}}async function ar(e){let t=await ln(e);if(t.state==="ok")return{state:"ok",keyId:t.key.trusted.keyId,publicKey:t.key.trusted.publicKey};return t}function dr(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 cr(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=J(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 ue(t)).filter((f)=>!f.startsWith(".")).sort()}catch(f){if(!(typeof f==="object"&&f!==null&&("code"in f)&&f.code==="ENOENT"))return console.error(`HOST_STATUS_UNREADABLE: cannot list ${t}`),1}let c=await Promise.all(s.map((f)=>ke(J(t,f))));if(e.json)console.log(JSON.stringify({version:e.version,claims:t,hosts:c},null,2));else for(let f of c)if(f.state==="pending")console.log(`pending ${f.claim} (registration not finished; rerun the same join command)`);else if(f.state==="unreadable")console.log(`unreadable ${f.config}`);else console.log([`joined workspace ${f.workspaceId} host ${f.hostId}`,` gateway ${f.gateway??"(none)"}`,` config ${f.config}`,` start ${f.start}`,` plugin ${f.pluginBundle} (${f.bundle}${cr(f.pluginVersion,e.version)})`,` key ${dr(f.signingKey)}`,...f.heldBundle===void 0?[]:[` held ${f.heldBundle.from} until this host connects at ${f.heldBundle.toVersion}${f.heldBundle.connected?" (it has; the next `hightea host update` removes it)":""}`]].join(`
4
- `));let y=c.filter((f)=>f.state==="joined"&&f.bundle!=="ok");for(let f of y){let I=f.bundle==="missing"?"is missing":f.bundle==="corrupt"?"does not match its recorded hash":`records version ${f.pluginVersion}, not the version its directory names`,O=f.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 ${f.pluginBundle} ${I}; the host cannot load it. ${O}`)}if(y.length>0)return 2;if(c.some((f)=>f.state==="unreadable"))return console.error("HOST_STATUS_CONFIG_UNREADABLE: a saved host configuration could not be read; it was left unchanged."),1;if(!c.some((f)=>f.state==="joined"))return console.error(`HOST_STATUS_NONE: no joined host under ${t}.`),1;return 0}var Sn=["session:write","session:state","session:list","chat:turns","agent:list"],Ee=["service:watch","service:logs","service:put","service:remove","service:start","service:stop","service:restart","service:accept"],pn=["services:list","services:get","services:put","services:delete","services:control"],lr=/(^|[\\/])(@hallohuman[\\/]hightea-services|@ahpd[\\/](services|deploy)|packages[\\/](services|deploy)|(services|deploy)[\\/]plugin)([\\/]|$)/u;function ur(e){if(!U(e)||typeof e.source!=="string"||!U(e.options))return!1;if(lr.test(e.source))return!0;return Array.isArray(e.options.files)&&typeof e.options.socket==="string"}function gr(e){if(ie(e)!=="ahpd")return;let t=L(e);if(ie(t)!=="xdg-config")return;let s=ie(L(t));return s===""||s==="."||s==="/"?void 0:s}async function fr(e){let t;try{t=JSON.parse(await q(e.config,"utf8"))}catch{return}let s=U(t)&&Array.isArray(t.plugins)?t.plugins:[],c=s.find(ge),y=s.some(ur),f=c!==void 0&&U(c.options)&&U(c.options.headers)?String(c.options.headers[a]??c.options.headers[d]??""):"",I=gr(e.configDir),O=f||e.hostIds[0]||(y?I:void 0);if(O===void 0||O==="")return;let S=c!==void 0&&U(c.options)?String(c.options.workspaceId??c.options.houseId??""):"",E=c!==void 0&&U(c.options)&&typeof c.options.cloudUrl==="string"?c.options.cloudUrl:void 0,h=[...new Set([O,...e.hostIds,...I===void 0?[]:[I]])].filter((T)=>T!=="");return{row:e,names:h,hasServices:y,host:{claim:L(e.configDir),configDir:e.configDir,config:e.config,workspaceId:S,hostId:O,...E===void 0?{}:{gateway:E}}}}function mn(e,t){let s=t.filter((y)=>y.names.includes(e.hostId));if(s.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: ${String(s.length)} running ahpd processes serve ${e.hostId} (${s.map((y)=>`${String(y.row.pid)} at ${y.row.configDir}`).join(", ")}); stop the extras or name one with --config-dir`};let c=s[0];if(c===void 0)return e;return{...e,claim:c.host.claim,configDir:c.host.configDir,config:c.host.config,...c.host.workspaceId!==""?{workspaceId:c.host.workspaceId}:{},...c.host.gateway!==void 0?{gateway:c.host.gateway}:{}}}async function n(e,t){let s;try{s=J(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`SERVICE_UNSAFE_PATH: ${Q.HOST_JOIN_UNSAFE_PATH}`}}let c=[];try{c=(await ue(s)).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 ${s}`}}let y=await Promise.all(c.map((h)=>ke(J(s,h)))),f=y.filter((h)=>h.state==="joined"),I=t?.runningAhpds!==void 0?await t.runningAhpds():[],O=(await Promise.all(I.map(fr))).filter((h)=>h!==void 0),S=e?.trim();if(S!==void 0&&S!==""){let h=f.find((H)=>H.hostId===S);if(h!==void 0)return mn(yn(h),O);let T=O.filter((H)=>H.names.includes(S));if(T.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: ${String(T.length)} running ahpd processes serve ${S} (${T.map((H)=>`${String(H.row.pid)} at ${H.row.configDir}`).join(", ")}); stop the extras or name one with --config-dir`};if(T.length===1)return T[0].host;let b=[...new Set([...f.map((H)=>H.hostId),...O.map((H)=>H.host.hostId)])];return{error:`SERVICE_HOST_UNKNOWN: no joined host ${S} on this machine (joined here: ${b.join(", ")||"none"})`}}if(f.length===1)return mn(yn(f[0]),O);if(f.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: this machine holds ${f.length} joined hosts (${f.map((h)=>h.hostId).join(", ")}); name one with --host <id>`};if(O.length>0){let h=O.filter((b)=>b.hasServices),T=h.length>0?h:O;if(T.length===1)return T[0].host;return{error:`SERVICE_HOST_AMBIGUOUS: this machine holds ${T.length} joined hosts (${T.map((b)=>b.host.hostId).join(", ")}); name one with --host <id>`}}let E=y.find((h)=>h.state==="unreadable");return{error:E===void 0?`SERVICE_NO_HOST: no joined host under ${s}; join this machine with \`hightea host join\` first`:`SERVICE_HOST_UNREADABLE: ${E.config} could not be read; it was left unchanged`}}function yn(e){let t=e.config;return{claim:e.claim,configDir:L(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 ue(e)}catch{return[]}let s=[],c=new Set;for(let y of t){if(!/^\d+$/u.test(y))continue;let f;try{f=(await q(J(e,y,"cmdline"),"utf8")).split("\x00").filter((k)=>k!=="")}catch{continue}let I=f.indexOf("--config-file"),O=I<0?void 0:f[I+1];if(O===void 0||!In(O)||c.has(O))continue;c.add(O);let S=L(O),E=(k)=>{let F=f.indexOf(k),D=F<0?void 0:f[F+1];return D===void 0||D===""?void 0:D},h=E("--port"),T=h!==void 0&&/^\d{1,5}$/u.test(h)?Number(h):void 0,b=E("--connection-token-file"),H=E("--host")??"127.0.0.1";s.push({pid:Number(y),config:O,configDir:S,hostIds:await hr(O),host:H,...T===void 0?{}:{port:T},...b===void 0?{}:{connectionTokenFile:b}})}return s}async function hr(e){let t;try{t=JSON.parse(await q(e,"utf8"))}catch{return[]}if(!U(t)||!Array.isArray(t.plugins))return[];let s=new Set;for(let c of t.plugins){if(!U(c)||!U(c.options)||!U(c.options.headers))continue;let y=c.options.headers[a]??c.options.headers[d];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=On(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 c=Array.isArray(s.value.plugins)?s.value.plugins:[],y=c.findIndex(ge),f=c[y];if(f===void 0)return console.error(`SERVICE_CONFIG_UNREADABLE: ${t.config} holds no Hightea plugin entry; it was left unchanged`),1;if(f.grants!==void 0&&!(Array.isArray(f.grants)&&f.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 I=f.grants??[],O=[...Ee,...pn],S=pn,E=I.filter((H)=>!S.includes(H)),h=e.enable?[...E,...Ee.filter((H)=>!E.includes(H))]:I.filter((H)=>!O.includes(H)),T=`Hightea managing this machine's services (host ${t.hostId})`;if(h.length===I.length&&h.every((H,k)=>H===I[k]))return console.log(`${T} is already ${e.enable?"enabled":"disabled"}; ${t.config} was left unchanged.`),0;let b=c.slice();b[y]={...f,grants:h};try{Ae(t.config,{...s.value,plugins:b},{mode:384})}catch(H){return console.error(`SERVICE_CONFIG_UNWRITABLE: ${t.config}: ${H.message}`),1}return console.log(`${T} is now ${e.enable?"enabled":"disabled"}: ${e.enable?"added":"removed"} ${Ee.join(", ")} in ${t.config}.`),console.log(`It takes effect when this host's ahpd next loads its configuration; restart it with: ${se(t.claim)}`),0}function wn(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 pr(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",mr="pipe-connected.json";async function Tn(e){let t;try{t=await q(J(e,X),"utf8")}catch(c){return U(c)&&c.code==="ENOENT"?void 0:Error(`cannot read ${J(e,X)}`)}let s;try{s=JSON.parse(t)}catch{return Error(`${J(e,X)} is not JSON`)}if(!U(s)||typeof s.from!=="string"||typeof s.to!=="string"||typeof s.fromVersion!=="string"||typeof s.toVersion!=="string"||typeof s.at!=="string")return Error(`${J(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 Nn(e){try{let t=JSON.parse(await q(J(e,mr),"utf8"));return U(t)&&typeof t.version==="string"?t.version:void 0}catch{return}}async function yr(){let e;try{e=J(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`HOST_UPDATE_UNSAFE_PATH: ${Q.HOST_JOIN_UNSAFE_PATH}`}}let t;try{t=(await ue(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(J(e,s))))}}async function wr(e,t){let s,c;try{s=await Te(L(e.from))}catch{return{refused:"it cannot be resolved"}}try{c=await Te(Oe(z("XDG_DATA_HOME",J(".local","share"))))}catch{return{refused:"the plugin bundles root cannot be resolved"}}if(L(s)!==c)return{refused:`it is not directly under the plugin bundles root ${c}`};if(ie(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 f;try{f=await Te(L(y.pluginBundle))}catch{continue}if(f===s)return{refused:`${y.config} names it now`}}return{directory:s}}async function _n(e){let t=await Tn(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 Nn(e.configDir)!==t.toVersion){console.log(`Keeping the previous plugin bundle ${L(t.from)} until this host connects at ${t.toVersion}; restart it with: ${se(e.claim)}`);return}let c=await yr();if("error"in c){console.error(`${c.error}; the previous bundle ${L(t.from)} was kept`);return}let y=c.entries.filter((I)=>I.pluginBundle===t.from||I.state==="unreadable");if(y.length>0){console.log(`Keeping the previous plugin bundle ${L(t.from)}: ${y.map((I)=>I.state==="unreadable"?`${I.config} (unreadable)`:I.config).join(", ")} may still name it.`);return}let f=await wr(t,c.entries);if("refused"in f){console.error(`HOST_UPDATE_PRUNE_REFUSED: ${L(t.from)}: ${f.refused}; nothing was removed`);return}try{await hn(f.directory,{recursive:!0,force:!0}),await hn(J(e.configDir,X),{force:!0})}catch(I){console.error(`HOST_UPDATE_PRUNE_FAILED: ${L(t.from)}: ${I.message}`);return}console.log(`Removed the previous plugin bundle ${L(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 c=On(s.config);if(!c.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(c.value.plugins)?c.value.plugins:[],f=y.findIndex(ge),I=y[f];if(I===void 0||typeof I.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 O=await le(I.source);if(!O.ok)return console.error(`HOST_UPDATE_BUNDLE_UNREADABLE: the installed plugin bundle ${I.source} is ${O.reason}; nothing changed. \`hightea host status\` names the repair.`),1;let S=O.bundle.version,E=wn(S),h=wn(t.version);if(E===void 0||h===void 0)return console.error(`HOST_UPDATE_VERSION_UNREADABLE: cannot order the installed bundle ${S} against this CLI's ${t.version} (each must be x.y.z or x.y.z-dev.<hash8>); nothing changed`),1;let T=pr(h,E)||(t.version===S?0:1);if(T<0)return console.error(`HOST_UPDATE_DOWNGRADE: host ${s.hostId} runs plugin bundle ${S}, newer than this CLI's ${t.version}; nothing changed. Update the CLI instead.`),1;if(T===0)return console.log(`Host ${s.hostId} already runs plugin bundle ${S}; ${s.config} was left unchanged.`),await _n(s),0;await _n(s);let b;try{b=await Se(z("XDG_DATA_HOME",J(".local","share")),t.directory,t.version)}catch(K){let G=K instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(K.message)?K.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:I.source,to:b.manifest,fromVersion:S,toVersion:b.version,at:new Date().toISOString()},k=y.slice(),F=Array.isArray(I.grants)?I.grants.filter((K)=>typeof K==="string"):[],D=Sn.filter((K)=>!F.includes(K));k[f]={...I,source:b.manifest,...D.length===0?{}:{grants:[...F,...D]}};try{Ae(J(s.configDir,X),H,{mode:384}),Ae(s.config,{...c.value,plugins:k},{mode:384})}catch(K){return console.error(`HOST_UPDATE_CONFIG_UNWRITABLE: ${s.config}: ${K.message}`),1}return console.log(`Host ${s.hostId} now loads plugin bundle ${b.version} (was ${S}), 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 ${L(I.source)} is kept until the host connects at ${b.version}. Restart it with: ${se(s.claim)}`),0}function _r(e){if(e===void 0||e==="")throw Error("HOST_JOIN_RECEIPT_INVALID");return e}
1
+ import{_,A,l,a,d,u,p,w}from"./chunk-tay0pyz4.js";import{r}from"./chunk-evg5apz3.js";import{readdir as ue,readFile as q,realpath as Te,rm as hn}from"node:fs/promises";import{createRequire as Ft}from"node:module";import{homedir as Kt,hostname as Gt}from"node:os";import{basename as ie,dirname as L,isAbsolute as In,join as J,resolve as jt}from"node:path";import{fromEnvRef as Bt,isRecord as U,readJsonObject as On,readSecret as Mt,secretRef as Vt,writeJsonAtomic as Ae}from"@ahpd/sdk";import{fileVault as Wt}from"@ahpd/server/dist/vault.js";import{createHash as $e,randomBytes as En}from"node:crypto";import{constants as ne}from"node:fs";import{link as An,lstat as he,mkdir as Ue,mkdtemp as Hn,open as Pe,realpath as Rn,rm as kn}from"node:fs/promises";import{dirname as ae,join as M}from"node:path";import{isDeepStrictEqual as Je}from"node:util";import{fileVault as Le}from"@ahpd/server/dist/vault.js";function v(e){throw Error(e)}function xe(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(xe(s)!=="EEXIST")v("HOST_JOIN_CUSTODY_IO")});let t=await he(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&63)!==0)v("HOST_JOIN_UNSAFE_PATH")}async function bn(e){let t=await Pe(e,ne.O_RDONLY|ne.O_DIRECTORY|ne.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}}async function Z(e){let t=await Pe(e,ne.O_RDONLY|ne.O_NOFOLLOW);try{await t.sync()}finally{await t.close()}for(let s=ae(e);;s=ae(s))if(await bn(s),s===ae(s))break}function pe(e){if(typeof e.origin!=="string"||typeof e.workspaceSlug!=="string"||typeof e.code!=="string"||typeof e.pluginVersion!=="string"||typeof e.ahpdVersion!=="string")v("HOST_JOIN_INVALID_INTENT");let t;try{t=new URL(e.origin)}catch{return v("HOST_JOIN_INVALID_INTENT")}let s=l(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)v("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 f=y.codePointAt(0)??0;return f<32||f===127})))v("HOST_JOIN_INVALID_INTENT");if(e.app!==void 0&&!A(e.app))v("HOST_JOIN_INVALID_INTENT");if(e.hostId!==void 0&&(typeof e.hostId!=="string"||!/^[A-Za-z0-9_.:-]{1,128}$/u.test(e.hostId)))v("HOST_JOIN_INVALID_INTENT");if(e.ownerConfiguration===null&&e.app===void 0)v("HOST_JOIN_INVALID_INTENT");let c;try{c=e.ownerConfiguration===null?null:JSON.parse(JSON.stringify(e.ownerConfiguration))}catch{return v("HOST_JOIN_INVALID_INTENT")}if(c!==null&&(typeof c!=="object"||!Je(c,e.ownerConfiguration)))v("HOST_JOIN_INVALID_INTENT");return{...e,origin:t.origin,code:s,ownerConfiguration:c}}async function Fe(e,t){let s=pe(t),c=await Ge(e),y=M(c,"hightea"),f=M(y,"claims"),I=$e("sha256").update(JSON.stringify([s.origin,s.workspaceSlug,s.code])).digest("hex"),O=M(f,I),S=M(O,"ahpd");try{for(let T of[y,f,O,S])await Y(T);let E=M(S,"vault.json"),h=await Hn(M(S,".claim-"));try{let T=M(h,"vault.json"),b=Le({file:T});await b.set("host:hightea",`Bearer ${En(32).toString("base64url")}`),await b.set("host:hightea-join",JSON.stringify({schema:1,...s}));try{await An(T,E)}catch(D){if(xe(D)!=="EEXIST")v("HOST_JOIN_CUSTODY_PUBLICATION_FAILED")}let{authorization:H,credentialHash:k,intent:F}=await je(E);if(F.origin!==s.origin||F.workspaceSlug!==s.workspaceSlug||F.code!==s.code||F.app!==s.app||F.hostId!==s.hostId||!Je(F.ownerConfiguration,s.ownerConfiguration))v("HOST_JOIN_CLAIM_CONFLICT");return await Z(E),{home:O,vaultFile:E,authorization:H,credentialHash:k,intent:F}}finally{await kn(h,{recursive:!0})}}catch(E){if(E instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(E.message))throw E;return v("HOST_JOIN_CUSTODY_IO")}}async function Ke(e,t,s){let c=pe(s);if(c.hostId===void 0)v("HOST_JOIN_INVALID_INTENT");try{let y=await Ge(e),f=M(y,"hightea"),I=M(f,"claims");if(ae(t)!==I)v("HOST_JOIN_NO_CLAIM_FOR_HOST");let O=M(t,"ahpd");for(let h of[f,I,t,O])await Y(h);let S=M(O,"vault.json"),E=await je(S);if(E.intent.origin!==c.origin||E.intent.workspaceSlug!==c.workspaceSlug||E.intent.hostId!==void 0&&c.hostId!==E.intent.hostId)v("HOST_JOIN_CLAIM_CONFLICT");return await Z(S),{home:t,vaultFile:S,authorization:E.authorization,credentialHash:E.credentialHash,intent:c}}catch(y){if(y instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(y.message))throw y;return v("HOST_JOIN_NO_CLAIM_FOR_HOST")}}async function Ge(e){try{await Ue(e,{recursive:!0,mode:448});let t=await he(e);if(!t.isDirectory()||t.uid!==process.getuid?.()||(t.mode&18)!==0)v("HOST_JOIN_UNSAFE_PATH");return await Rn(e)}catch{return v("HOST_JOIN_UNSAFE_PATH")}}async function je(e){let t=await he(e);if(!t.isFile()||t.uid!==process.getuid?.()||(t.mode&511)!==384)v("HOST_JOIN_UNSAFE_PATH");let s=Le({file:e}),c=await s.get("host:hightea"),y=await s.get("host:hightea-join");if(!c||!/^Bearer [A-Za-z0-9_-]{43}$/u.test(c)||!y)v("HOST_JOIN_CLAIM_CORRUPT");let f;try{f=JSON.parse(y)}catch{return v("HOST_JOIN_CLAIM_CORRUPT")}if(!f||typeof f!=="object"||!("schema"in f)||f.schema!==1)v("HOST_JOIN_CLAIM_CORRUPT");let I;try{I=pe(f)}catch{return v("HOST_JOIN_CLAIM_CORRUPT")}return{authorization:c,credentialHash:`sha256:${$e("sha256").update(c.slice(7),"utf8").digest("hex")}`,intent:I}}import{link as Cn,lstat as vn,mkdtemp as Dn,rm as $n}from"node:fs/promises";import{join as te}from"node:path";import{isDeepStrictEqual as Un}from"node:util";import{isRecordSlug as Pn,readJsonObject as Jn,writeJsonAtomic as Be}from"@ahpd/sdk";async function Me(e,t){return We(e,te(e.home,"ahpd"),"config.json",t)}async function Ve(e,t){if(!Pn(t.id))throw Error("HOST_JOIN_CONFIG_CONFLICT");let s=te(e.home,"ahpd","agents");await Y(s),await We(e,s,`${t.id}.json`,{...t})}async function We(e,t,s,c){let y=te(t,s),f;try{if(JSON.stringify(c).includes(e.authorization))throw Error("HOST_JOIN_CONFIG_SECRET");f=await Dn(te(t,".config-"));let I=te(f,"config.json");Be(I,c,{mode:384});try{await Cn(I,y)}catch(h){if(!h||typeof h!=="object"||!("code"in h)||h.code!=="EEXIST")throw Error("HOST_JOIN_CONFIG_PUBLICATION_FAILED")}let O=await vn(y);if(!O.isFile()||O.uid!==process.getuid?.()||(O.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");let S=Jn(y);if(!S.ok)throw Error("HOST_JOIN_CONFIG_CORRUPT");let E={};for(let[h,T]of Object.entries(c)){let b=h==="unattendedAutoApprove"&&T===!1||h==="pluginMarketplaces"&&Array.isArray(T)&&T.length===0;if(s==="config.json"&&b&&!Object.hasOwn(S.value,h)){E[h]=T;continue}if(!Un(S.value[h],T))throw Error("HOST_JOIN_CONFIG_CONFLICT")}if(Object.keys(E).length>0)Be(y,{...S.value,...E},{mode:384});return await Z(y),y}catch(I){if(I instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(I.message))throw I;throw Error("HOST_JOIN_CONFIG_IO")}finally{if(f!==void 0)await $n(f,{recursive:!0})}}import{isRecord as W}from"@ahpd/sdk";class re extends Error{kind;status;serverCode;constructor(e,t,s){super(e);this.kind=e;this.status=t;this.serverCode=s}}function Ln(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 ze(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}})}),c;try{c=await fetch(s)}catch{throw Error("HOST_JOIN_NETWORK_UNKNOWN")}if(c.status===410){let f;try{f=await c.json()}catch{}if(W(f)&&W(f.error)&&f.error.code==="HOST_REGISTRATION_CANCELLED")throw Error("HOST_JOIN_CANCELLED");throw Error("HOST_JOIN_LINK_UNAVAILABLE")}if(c.status>=500){let f;try{f=await c.json()}catch{}let I=W(f)&&W(f.error)&&_(f.error.code)?f.error.code:void 0;if(I==="HOST_REGISTRATION_UNSETTLED")throw new re("HOST_JOIN_UNSETTLED",c.status,I);throw Error("HOST_JOIN_REMOTE_UNAVAILABLE")}if(!c.ok){let f;try{f=await c.json()}catch{}let I=W(f)&&W(f.error)&&_(f.error.code)?f.error.code:void 0;throw new re(Ln(c.status,I),c.status,I)}let y;try{y=await c.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 xn,stat as me}from"node:fs/promises";import{constants as Fn}from"node:fs";import{delimiter as Kn,dirname as Ye,isAbsolute as Gn,join as jn}from"node:path";import{fileURLToPath as Bn}from"node:url";import{fromEnvRef as Mn,isRecord as V,isRecordSlug as Vn,readJsonObject as Wn,scopeOf as zn,secretPaths as Yn,secretRef as Zn}from"@ahpd/sdk";import{checkManifest as Xn,checkStandalone as qn,readManifest as Qn,readStandalone as et,resolvePlugin as nt}from"@ahpd/server/dist/plugins.js";function P(e="HOST_JOIN_OWNER_RESOURCE"){throw Error(e)}function Ze(e){let t=Mn(e);if(t!==void 0){if(!process.env[t])P();return!0}let s=Zn(e);if(s===void 0)return!1;return zn(s),!0}async function tt(e){let t=Gn(e)?[e]:(process.env.PATH??"").split(Kn).map((s)=>jn(s,e));for(let s of t)try{if(await xn(s,Fn.X_OK),(await me(s)).isFile())return}catch{}P()}async function oe(e){let t=Wn(e);if(!t.ok)P("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))P();let c=new Set,y=new Set,f=[];try{for(let h of s.plugins){let T=typeof h==="string"?{source:h}:h;if(!V(T)||typeof T.source!=="string"||T.enabled===!1)P();let H=nt(T,{cwd:Ye(e),configDir:Ye(e)});if(!H.path||!(await me(H.path)).isFile())P();let k=H.manifestPath?et(H.manifestPath):H.packageDir?Qn(H.packageDir):void 0;if(!k||k.problem||(k.standalone?qn(k):Xn(k,H.packageDir)))P();if(k.name==="@ahpd/bot"||k.name==="bot")P("HOST_JOIN_OWNER_BOT");for(let D of k.contracts?.engines??[])c.add(D);for(let D of k.contracts?.agents??[])y.add(D);if(T.options!==void 0&&!V(T.options))P();let F=V(T.options)?T.options:{};for(let D of Yn(k.optionsSchema??{},F)){let K=F;for(let j of D.split("."))K=V(K)?K[j]:void 0;if(K!==void 0&&!Ze(K))P("HOST_JOIN_OWNER_SECRET")}f.push({...T,source:H.manifestPath??H.packageDir??H.path})}let I=[],O=new Set(y);for(let h of s.records){if(!V(h)||typeof h.id!=="string"||!Vn(h.id)||O.has(h.id)||typeof h.engine!=="string"||!c.has(h.engine)||typeof h.owner!=="string"||typeof h.name!=="string"||!V(h.config)||h.mode!==void 0&&h.mode!=="enabled")P();if(h.model!==void 0&&(typeof h.model!=="string"||h.model.trim()===""))P();if(h.engine==="acp"&&typeof h.config.command!=="string")P();if(h.config.command!==void 0){if(typeof h.config.command!=="string"||!h.config.command)P();await tt(h.config.command)}if(h.config.env!==void 0){if(!V(h.config.env))P();for(let T of Object.values(h.config.env))if(!Ze(T))P("HOST_JOIN_OWNER_SECRET")}O.add(h.id),I.push(h)}let S=[],E=new Set;for(let h of s.agents){if(!Array.isArray(h)||h.length!==2||typeof h[0]!=="string"||!h[0]||E.has(h[0])||!V(h[1])||typeof h[1].provider!=="string"||!O.has(h[1].provider)||typeof h[1].workingDirectory!=="string")P();let T=new URL(h[1].workingDirectory);if(T.protocol!=="file:"||T.hostname||!(await me(Bn(T))).isDirectory())P();if(h[1].settings!==void 0&&!V(h[1].settings))P();E.add(h[0]),S.push([h[0],{provider:h[1].provider,workingDirectory:T.href,...h[1].settings===void 0?{}:{settings:h[1].settings}}])}return{agents:S,plugins:f,records:I}}catch(I){if(I instanceof Error&&/^HOST_JOIN_OWNER_[A-Z_]+$/u.test(I.message))throw I;return P()}}import{constants as rt}from"node:fs";import{access as ot,mkdir as it,stat as st,writeFile as at}from"node:fs/promises";import{createRequire as dt}from"node:module";import{dirname as qe,resolve as Qe}from"node:path";import{pathToFileURL as ct}from"node:url";class de extends Error{file;entry;constructor(e,t){super("HOST_JOIN_OWNER_CONFIG_NEEDS_AGENT");this.file=e;this.entry=t}}function lt(){try{return qe(dt(import.meta.url).resolve("@ahpd/agent-acp/package.json"))}catch{throw Error("HOST_JOIN_AGENT_PLUGIN_MISSING")}}function en(e,t,s){return[t,{provider:e.id,workingDirectory:ct(Qe(s)).href}]}function ut(e,t,s){return JSON.stringify(en(e,t,s))}function gt(e,t){let[s,c]=en(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,c]]},null,2)}
2
+ `}async function nn(e){let t=Qe(e.file);if(await ot(t,rt.F_OK).then(()=>!0,()=>!1))return Xe(t,e);await it(qe(t),{recursive:!0,mode:448});try{await at(t,gt(e,lt()),{flag:"wx",mode:384})}catch(c){if(c!==null&&typeof c==="object"&&"code"in c&&c.code==="EEXIST")return Xe(t,e);throw Error("HOST_JOIN_OWNER_FILE_IO")}let s=await st(t);if(!s.isFile()||s.uid!==process.getuid?.()||(s.mode&511)!==384)throw Error("HOST_JOIN_UNSAFE_PATH");return oe(t)}async function Xe(e,t){let s=await oe(e);if(s.agents.some(([c])=>c===t.agentMemberId))return s;throw new de(e,ut(t.app,t.agentMemberId,t.workingDirectory))}import{access as zt}from"node:fs/promises";import{constants as Yt}from"node:fs";import{createHash as ft}from"node:crypto";import{lstat as tn,mkdir as ht,mkdtemp as pt,readFile as we,rename as mt,rm as yt,writeFile as ye}from"node:fs/promises";import{isAbsolute as rn,join as G,normalize as ce}from"node:path";var wt="hightea-host",_t="hightea-pipe",Ie="bundle.json";function Oe(e){return G(e,"hightea","plugins")}async function on(e){let t;try{t=await we(G(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 c=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,f=typeof s==="object"&&s!==null&&"version"in s?s.version:void 0;if(y!==wt&&y!==_t||typeof f!=="string"||typeof c!=="string"||rn(c)||ce(c).startsWith("..")||ce(c).includes("/")||["plugin.json",Ie].includes(ce(c)))throw Error("HOST_JOIN_PLUGIN_BUNDLE");let I;try{I=await we(G(e,c))}catch{throw Error("HOST_JOIN_PLUGIN_BUNDLE")}return{manifestBytes:t,version:f,main:ce(c),mainBytes:I,sha256:It(t,I)}}function It(e,t){return ft("sha256").update(e).update("\x00").update(t).digest("hex")}async function le(e){let t=G(e,".."),s;try{s=JSON.parse(await we(G(t,Ie),"utf8"))}catch(y){return{ok:!1,reason:sn(y)?"missing":"corrupt"}}let c;try{c=await on(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!==c.sha256)return{ok:!1,reason:"corrupt"};return{ok:!0,bundle:{manifest:e,version:s.version,sha256:c.sha256}}}async function Se(e,t,s){if(!rn(e)||!/^[0-9A-Za-z.+-]+$/u.test(s))throw Error("HOST_JOIN_UNSAFE_PATH");let c=await on(t);if(c.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE");try{await ht(e,{recursive:!0,mode:448});let S=await tn(e);if(!S.isDirectory()||S.uid!==process.getuid?.()||(S.mode&18)!==0)throw Error("unsafe")}catch{throw Error("HOST_JOIN_UNSAFE_PATH")}let y=Oe(e);for(let S of[G(e,"hightea"),y])await Y(S);let f=G(y,s),I=G(f,"plugin.json");if(!await Ot(f)){let S=await pt(G(y,`.${s}-`));try{await ye(G(S,"plugin.json"),c.manifestBytes,{mode:384}),await ye(G(S,c.main),c.mainBytes,{mode:384}),await ye(G(S,Ie),`${JSON.stringify({version:s,sha256:c.sha256})}
3
+ `,{mode:384});try{await mt(S,f)}catch(E){if(!_e(E,"EEXIST")&&!_e(E,"ENOTEMPTY"))throw Error("HOST_JOIN_CONFIG_IO")}}finally{await yt(S,{recursive:!0,force:!0})}}let O=await le(I);if(!O.ok||O.bundle.sha256!==c.sha256||O.bundle.version!==s)throw Error("HOST_JOIN_PLUGIN_BUNDLE_CONFLICT");return O.bundle}async function Ot(e){try{return await tn(e),!0}catch(t){if(sn(t))return!1;throw Error("HOST_JOIN_UNSAFE_PATH")}}function sn(e){return _e(e,"ENOENT")}function _e(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}import{createPrivateKey as bt,createPublicKey as Ct,generateKeyPairSync as vt,sign as mo}from"node:crypto";import{appendFile as wo,chmod as Dt,readFile as an,rename as $t,writeFile as Ut}from"node:fs/promises";import{join as dn}from"node:path";var so=Buffer.from("302a300506032b6570032100","hex");import{createHash as Tt}from"node:crypto";import{existsSync as Nt,readFileSync as Et}from"node:fs";import{join as At}from"node:path";var Ht="trusted-keys.json",m=/^(?=.{1,64}$)[A-Za-z0-9][A-Za-z0-9._-]*(?: [A-Za-z0-9._-]+)*$/u,Rt=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/u,kt=(e)=>Buffer.from(e).toString("base64url");function o(e){if(!Rt.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:kt(Tt("sha256").update(Buffer.from(e,"base64url")).digest())}}function g(e){let t=At(e,Ht);if(!Nt(t))return{state:"missing",file:t};let s;try{s=JSON.parse(Et(t,"utf8"))}catch(y){throw Error(`TRUST_FILE_UNREADABLE: ${t} is not JSON (${y.message})`)}let c=s;if(typeof s!=="object"||s===null||c.v!==1||!Array.isArray(c.keys))throw Error(`TRUST_FILE_UNREADABLE: ${t} is not a version 1 list of trusted keys`);for(let y of c.keys){let f=y,I=typeof f.publicKey==="string"?o(f.publicKey):void 0;if(typeof f.name!=="string"||!m.test(f.name)||I===void 0||"error"in I||f.keyId!==I.keyId||typeof f.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:c.keys}}var cn="host-signing-key";async function ln(e){try{await an(dn(e,cn))}catch(t){if(t.code==="ENOENT")return{state:"missing"}}try{return{state:"ok",key:await Pt(e)}}catch(t){return{state:"unreadable",reason:t instanceof Error?t.message:String(t)}}}async function Pt(e,t=()=>Date.now()){let s=dn(e,cn),c;try{c=await an(s,"utf8")}catch(O){if(O.code!=="ENOENT")throw Error(`HOST_KEY_UNREADABLE: ${s} exists but cannot be read (${String(O)}); it is never regenerated, fix or remove it by hand`)}if(c===void 0){let O=vt("ed25519").privateKey.export({format:"pem",type:"pkcs8"}).toString(),S=`${s}.${String(process.pid)}.tmp`;await Ut(S,O,{mode:384,flag:"wx"}),await Dt(S,384),await $t(S,s),c=O}let y;try{if(y=bt({key:c,format:"pem"}),y.asymmetricKeyType!=="ed25519")throw Error(`a ${String(y.asymmetricKeyType)} key, not Ed25519`)}catch(O){throw Error(`HOST_KEY_UNREADABLE: ${s} is not an Ed25519 PKCS8 key (${String(O)}); it is never regenerated, fix or remove it by hand`)}let f=Ct(y).export({format:"jwk"}).x,I=f===void 0?{error:"no public key"}:o(f);if("error"in I)throw Error(`HOST_KEY_UNREADABLE: ${s}: ${I.error}`);return{privateKey:y,trusted:{name:"this-host",keyId:I.keyId,publicKey:f,addedAt:new Date(t()).toISOString()}}}import{createServer as Jt}from"node:net";var un="hightea";function gn(e){return`http://127.0.0.1:${String(e)}/mcp`}function Lt(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 fn(e){let t=Lt(e);for(let s=0;s<200;s+=1){let c=40000+(t-40000+s)%20000;if(await xt(c))return c}throw Error(`HOST_TOOLS_PORT_UNAVAILABLE: every port from ${String(t)} to ${String(t+199)} on 127.0.0.1 is taken`)}async function xt(e){let t=Jt();return await new Promise((s)=>{t.once("error",()=>{s(!1)}),t.listen(e,"127.0.0.1",()=>{t.close(()=>{s(!0)})})})}var Zt="hightea host join --origin https://your-deployment --workspace SLUG --code CODE --owner-config /absolute/owner.json",Xt=(e)=>[...e].some((t)=>{let s=t.codePointAt(0)??0;return s<32||s===127});function qt(e=Gt()){let t=e.trim();return t===""||t.length>64||Xt(t)?void 0:t}var Qt="https://hightea.ai/docs/host#owner";class He extends Error{file;constructor(e){super("HOST_JOIN_OWNER_CONFIG_MISSING");this.file=e}}var er=(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 ${Qt} — then run the same command again. Nothing was redeemed and nothing was written.`,nr=(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 Re extends Error{appName;install;constructor(e,t){super("HOST_JOIN_APP_MISSING");this.appName=e;this.install=t}}var tr=(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: ${Zt}`,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]||J(Kt(),t);if(!In(s))throw Error("HOST_JOIN_UNSAFE_PATH");return s}function rr(){let e=Ft(import.meta.url).resolve("@ahpd/server/package.json");return{node:process.execPath,main:J(L(e),"dist","main.js")}}var Ne=(e)=>`'${e.replaceAll("'","'\\''")}'`;function se(e,t=rr()){return`XDG_CONFIG_HOME=${Ne(e)} ${Ne(t.node)} ${Ne(t.main)} start`}var or={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"},ir={HOST_JOIN_NOT_AUTHORIZED:3,HOST_JOIN_AGENT_BOUND:4,HOST_JOIN_REJECTED:1,HOST_JOIN_UNSETTLED:2};function sr(e){let t=e.serverCode===void 0?"":` The deployment says ${or[e.serverCode]}.`;return`${e.kind}: ${Q[e.kind]}${t} (HTTP ${e.status}, server code ${e.serverCode??"unrecognised"})`}async function N(e,t){try{let{origin:s,workspace:c,code:y,ownerConfig:f}=e;if(!s||!c||!y||!f)throw Error("HOST_JOIN_USAGE");let I=jt(f),O=await zt(I,Yt.F_OK).then(()=>!0,()=>!1);if(!O&&e.ownerConfigIsDefault!==!0)throw Error("HOST_JOIN_OWNER_INPUT");if(!O&&e.app===void 0)throw new He(I);let S=e.app===void 0?void 0:p(e.app);if(S!==void 0&&!await w(S))throw new Re(S.name,u(S));let E=O?await oe(I):null,h=z("XDG_CONFIG_HOME",".config"),T=z("XDG_DATA_HOME",J(".local","share")),b=qt(),H={origin:s,workspaceSlug:c,code:y,pluginVersion:t.version,ahpdVersion:"0.15.0-rc.4",ownerConfiguration:E,...b===void 0?{}:{name:b},...e.app===void 0?{}:{app:e.app},...e.hostId===void 0?{}:{hostId:e.hostId}},k;if(e.hostId===void 0)k=await Fe(h,H);else{let B=await n(e.hostId);if("error"in B)throw Error("HOST_JOIN_NO_CLAIM_FOR_HOST");k=await Ke(h,B.claim,H)}if(k.intent.pluginVersion!==t.version)throw Error("HOST_JOIN_CLAIM_VERSION");let F=Wt({file:k.vaultFile}),D=async(B)=>{let ve=Vt(B),De=Bt(B);if(De!==void 0){if(!process.env[De])throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(ve!==void 0)try{await Mt(F,ve)}catch{throw Error("HOST_JOIN_OWNER_RESOURCE")}else if(Array.isArray(B))for(let fe of B)await D(fe);else if(U(B))for(let fe of Object.values(B))await D(fe)};if(E!==null)await D(E);let K=await Se(T,t.directory,t.version),j=await ze(k);if(j.state==="pending")return console.log("Host registration pending. Run the same command again to resume."),2;let ee=S===void 0?E:await nn({file:I,app:S,agentMemberId:Ir(j.agentMemberId),workingDirectory:e.workingDirectory??process.cwd()});if(ee===null)throw Error("HOST_JOIN_OWNER_INPUT");if(S!==void 0)await D(ee);for(let B of ee.records)await Ve(k,B);let be=new URL(`/gateway/${encodeURIComponent(j.workspaceId)}/host`,k.intent.origin);be.protocol="wss:";let Ce=await fn(k.home);return await Me(k,{host:"127.0.0.1",updateCheck:!1,httpApi:!1,modelApi:!1,mcpTools:"none",unattendedAutoApprove:!1,pluginMarketplaces:[],mcpServers:{[un]:{type:"http",url:gn(Ce)}},plugins:[...ee.plugins,{source:K.manifest,grants:[...Sn],options:{cloudUrl:be.href,workspaceId:j.workspaceId,agents:ee.agents,mcpUrl:new URL(`/w/${encodeURIComponent(j.workspaceId)}`,k.intent.origin).href,hostToolsPort:Ce,headers:{[a]:j.hostId,authorization:{$secret:"host:hightea"}}}}]}),console.log(`Host registered; local configuration saved. Start it with: ${se(k.home)}`),0}catch(s){if(s instanceof re)return console.error(sr(s)),ir[s.kind];if(s instanceof He)return console.error(er(s.file)),1;if(s instanceof de)return console.error(nr(s.file,s.entry)),1;if(s instanceof Re)return console.error(tr(s)),1;let c=s instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(s.message)?s.message:"HOST_JOIN_INPUT";return console.error(`${c}: ${Q[c]??"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 ge(e){return U(e)&&U(e.options)&&typeof(e.options.workspaceId??e.options.houseId)==="string"&&U(e.options.headers)&&typeof(e.options.headers[a]??e.options.headers[d])==="string"}async function ke(e){let t=J(e,"ahpd","config.json"),s;try{s=await q(t,"utf8")}catch(E){return typeof E==="object"&&E!==null&&"code"in E&&E.code==="ENOENT"?{claim:e,state:"pending"}:{claim:e,state:"unreadable",config:t}}let c;try{c=JSON.parse(s)}catch{return{claim:e,state:"unreadable",config:t}}let f=(U(c)&&Array.isArray(c.plugins)?c.plugins:[]).find(ge);if(f===void 0||typeof f.source!=="string"||!U(f.options)||!U(f.options.headers))return{claim:e,state:"unreadable",config:t};let I=f.source,O=await le(I),S=!O.ok?O.reason:O.bundle.version===ie(L(I))?"ok":"wrong-version";return{claim:e,state:"joined",config:t,start:se(e),pluginBundle:I,bundle:S,...O.ok?{pluginVersion:O.bundle.version}:{},workspaceId:String(f.options.workspaceId??f.options.houseId),hostId:String(f.options.headers[a]??f.options.headers[d]),...typeof f.options.cloudUrl==="string"?{gateway:f.options.cloudUrl}:{},signingKey:await dr(L(t)),...await ar(L(t))}}async function ar(e){let t=await Tn(e);if(t===void 0||t instanceof Error)return{};return{heldBundle:{from:t.from,toVersion:t.toVersion,connected:await Nn(e)===t.toVersion}}}async function dr(e){let t=await ln(e);if(t.state==="ok")return{state:"ok",keyId:t.key.trusted.keyId,publicKey:t.key.trusted.publicKey};return t}function cr(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 lr(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=J(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 ue(t)).filter((f)=>!f.startsWith(".")).sort()}catch(f){if(!(typeof f==="object"&&f!==null&&("code"in f)&&f.code==="ENOENT"))return console.error(`HOST_STATUS_UNREADABLE: cannot list ${t}`),1}let c=await Promise.all(s.map((f)=>ke(J(t,f))));if(e.json)console.log(JSON.stringify({version:e.version,claims:t,hosts:c},null,2));else for(let f of c)if(f.state==="pending")console.log(`pending ${f.claim} (registration not finished; rerun the same join command)`);else if(f.state==="unreadable")console.log(`unreadable ${f.config}`);else console.log([`joined workspace ${f.workspaceId} host ${f.hostId}`,` gateway ${f.gateway??"(none)"}`,` config ${f.config}`,` start ${f.start}`,` plugin ${f.pluginBundle} (${f.bundle}${lr(f.pluginVersion,e.version)})`,` key ${cr(f.signingKey)}`,...f.heldBundle===void 0?[]:[` held ${f.heldBundle.from} until this host connects at ${f.heldBundle.toVersion}${f.heldBundle.connected?" (it has; the next `hightea host update` removes it)":""}`]].join(`
4
+ `));let y=c.filter((f)=>f.state==="joined"&&f.bundle!=="ok");for(let f of y){let I=f.bundle==="missing"?"is missing":f.bundle==="corrupt"?"does not match its recorded hash":`records version ${f.pluginVersion}, not the version its directory names`,O=f.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 ${f.pluginBundle} ${I}; the host cannot load it. ${O}`)}if(y.length>0)return 2;if(c.some((f)=>f.state==="unreadable"))return console.error("HOST_STATUS_CONFIG_UNREADABLE: a saved host configuration could not be read; it was left unchanged."),1;if(!c.some((f)=>f.state==="joined"))return console.error(`HOST_STATUS_NONE: no joined host under ${t}.`),1;return 0}var Sn=["session:write","session:state","session:list","chat:turns","agent:list"],Ee=["service:watch","service:logs","service:put","service:remove","service:start","service:stop","service:restart","service:accept"],pn=["services:list","services:get","services:put","services:delete","services:control"],ur=/(^|[\\/])(@hallohuman[\\/]hightea-services|@ahpd[\\/](services|deploy)|packages[\\/](services|deploy)|(services|deploy)[\\/]plugin)([\\/]|$)/u;function gr(e){if(!U(e)||typeof e.source!=="string"||!U(e.options))return!1;if(ur.test(e.source))return!0;return Array.isArray(e.options.files)&&typeof e.options.socket==="string"}function fr(e){if(ie(e)!=="ahpd")return;let t=L(e);if(ie(t)!=="xdg-config")return;let s=ie(L(t));return s===""||s==="."||s==="/"?void 0:s}async function hr(e){let t;try{t=JSON.parse(await q(e.config,"utf8"))}catch{return}let s=U(t)&&Array.isArray(t.plugins)?t.plugins:[],c=s.find(ge),y=s.some(gr),f=c!==void 0&&U(c.options)&&U(c.options.headers)?String(c.options.headers[a]??c.options.headers[d]??""):"",I=fr(e.configDir),O=f||e.hostIds[0]||(y?I:void 0);if(O===void 0||O==="")return;let S=c!==void 0&&U(c.options)?String(c.options.workspaceId??c.options.houseId??""):"",E=c!==void 0&&U(c.options)&&typeof c.options.cloudUrl==="string"?c.options.cloudUrl:void 0,h=[...new Set([O,...e.hostIds,...I===void 0?[]:[I]])].filter((T)=>T!=="");return{row:e,names:h,hasServices:y,host:{claim:L(e.configDir),configDir:e.configDir,config:e.config,workspaceId:S,hostId:O,...E===void 0?{}:{gateway:E}}}}function mn(e,t){let s=t.filter((y)=>y.names.includes(e.hostId));if(s.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: ${String(s.length)} running ahpd processes serve ${e.hostId} (${s.map((y)=>`${String(y.row.pid)} at ${y.row.configDir}`).join(", ")}); stop the extras or name one with --config-dir`};let c=s[0];if(c===void 0)return e;return{...e,claim:c.host.claim,configDir:c.host.configDir,config:c.host.config,...c.host.workspaceId!==""?{workspaceId:c.host.workspaceId}:{},...c.host.gateway!==void 0?{gateway:c.host.gateway}:{}}}async function n(e,t){let s;try{s=J(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`SERVICE_UNSAFE_PATH: ${Q.HOST_JOIN_UNSAFE_PATH}`}}let c=[];try{c=(await ue(s)).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 ${s}`}}let y=await Promise.all(c.map((h)=>ke(J(s,h)))),f=y.filter((h)=>h.state==="joined"),I=t?.runningAhpds!==void 0?await t.runningAhpds():[],O=(await Promise.all(I.map(hr))).filter((h)=>h!==void 0),S=e?.trim();if(S!==void 0&&S!==""){let h=f.find((H)=>H.hostId===S);if(h!==void 0)return mn(yn(h),O);let T=O.filter((H)=>H.names.includes(S));if(T.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: ${String(T.length)} running ahpd processes serve ${S} (${T.map((H)=>`${String(H.row.pid)} at ${H.row.configDir}`).join(", ")}); stop the extras or name one with --config-dir`};if(T.length===1)return T[0].host;let b=[...new Set([...f.map((H)=>H.hostId),...O.map((H)=>H.host.hostId)])];return{error:`SERVICE_HOST_UNKNOWN: no joined host ${S} on this machine (joined here: ${b.join(", ")||"none"})`}}if(f.length===1)return mn(yn(f[0]),O);if(f.length>1)return{error:`SERVICE_HOST_AMBIGUOUS: this machine holds ${f.length} joined hosts (${f.map((h)=>h.hostId).join(", ")}); name one with --host <id>`};if(O.length>0){let h=O.filter((b)=>b.hasServices),T=h.length>0?h:O;if(T.length===1)return T[0].host;return{error:`SERVICE_HOST_AMBIGUOUS: this machine holds ${T.length} joined hosts (${T.map((b)=>b.host.hostId).join(", ")}); name one with --host <id>`}}let E=y.find((h)=>h.state==="unreadable");return{error:E===void 0?`SERVICE_NO_HOST: no joined host under ${s}; join this machine with \`hightea host join\` first`:`SERVICE_HOST_UNREADABLE: ${E.config} could not be read; it was left unchanged`}}function yn(e){let t=e.config;return{claim:e.claim,configDir:L(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 ue(e)}catch{return[]}let s=[],c=new Set;for(let y of t){if(!/^\d+$/u.test(y))continue;let f;try{f=(await q(J(e,y,"cmdline"),"utf8")).split("\x00").filter((k)=>k!=="")}catch{continue}let I=f.indexOf("--config-file"),O=I<0?void 0:f[I+1];if(O===void 0||!In(O)||c.has(O))continue;c.add(O);let S=L(O),E=(k)=>{let F=f.indexOf(k),D=F<0?void 0:f[F+1];return D===void 0||D===""?void 0:D},h=E("--port"),T=h!==void 0&&/^\d{1,5}$/u.test(h)?Number(h):void 0,b=E("--connection-token-file"),H=E("--host")??"127.0.0.1";s.push({pid:Number(y),config:O,configDir:S,hostIds:await pr(O),host:H,...T===void 0?{}:{port:T},...b===void 0?{}:{connectionTokenFile:b}})}return s}async function pr(e){let t;try{t=JSON.parse(await q(e,"utf8"))}catch{return[]}if(!U(t)||!Array.isArray(t.plugins))return[];let s=new Set;for(let c of t.plugins){if(!U(c)||!U(c.options)||!U(c.options.headers))continue;let y=c.options.headers[a]??c.options.headers[d];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=On(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 c=Array.isArray(s.value.plugins)?s.value.plugins:[],y=c.findIndex(ge),f=c[y];if(f===void 0)return console.error(`SERVICE_CONFIG_UNREADABLE: ${t.config} holds no Hightea plugin entry; it was left unchanged`),1;if(f.grants!==void 0&&!(Array.isArray(f.grants)&&f.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 I=f.grants??[],O=[...Ee,...pn],S=pn,E=I.filter((H)=>!S.includes(H)),h=e.enable?[...E,...Ee.filter((H)=>!E.includes(H))]:I.filter((H)=>!O.includes(H)),T=`Hightea managing this machine's services (host ${t.hostId})`;if(h.length===I.length&&h.every((H,k)=>H===I[k]))return console.log(`${T} is already ${e.enable?"enabled":"disabled"}; ${t.config} was left unchanged.`),0;let b=c.slice();b[y]={...f,grants:h};try{Ae(t.config,{...s.value,plugins:b},{mode:384})}catch(H){return console.error(`SERVICE_CONFIG_UNWRITABLE: ${t.config}: ${H.message}`),1}return console.log(`${T} is now ${e.enable?"enabled":"disabled"}: ${e.enable?"added":"removed"} ${Ee.join(", ")} in ${t.config}.`),console.log(`It takes effect when this host's ahpd next loads its configuration; restart it with: ${se(t.claim)}`),0}function wn(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 mr(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",yr="pipe-connected.json";async function Tn(e){let t;try{t=await q(J(e,X),"utf8")}catch(c){return U(c)&&c.code==="ENOENT"?void 0:Error(`cannot read ${J(e,X)}`)}let s;try{s=JSON.parse(t)}catch{return Error(`${J(e,X)} is not JSON`)}if(!U(s)||typeof s.from!=="string"||typeof s.to!=="string"||typeof s.fromVersion!=="string"||typeof s.toVersion!=="string"||typeof s.at!=="string")return Error(`${J(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 Nn(e){try{let t=JSON.parse(await q(J(e,yr),"utf8"));return U(t)&&typeof t.version==="string"?t.version:void 0}catch{return}}async function wr(){let e;try{e=J(z("XDG_CONFIG_HOME",".config"),"hightea","claims")}catch{return{error:`HOST_UPDATE_UNSAFE_PATH: ${Q.HOST_JOIN_UNSAFE_PATH}`}}let t;try{t=(await ue(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(J(e,s))))}}async function _r(e,t){let s,c;try{s=await Te(L(e.from))}catch{return{refused:"it cannot be resolved"}}try{c=await Te(Oe(z("XDG_DATA_HOME",J(".local","share"))))}catch{return{refused:"the plugin bundles root cannot be resolved"}}if(L(s)!==c)return{refused:`it is not directly under the plugin bundles root ${c}`};if(ie(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 f;try{f=await Te(L(y.pluginBundle))}catch{continue}if(f===s)return{refused:`${y.config} names it now`}}return{directory:s}}async function _n(e){let t=await Tn(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 Nn(e.configDir)!==t.toVersion){console.log(`Keeping the previous plugin bundle ${L(t.from)} until this host connects at ${t.toVersion}; restart it with: ${se(e.claim)}`);return}let c=await wr();if("error"in c){console.error(`${c.error}; the previous bundle ${L(t.from)} was kept`);return}let y=c.entries.filter((I)=>I.pluginBundle===t.from||I.state==="unreadable");if(y.length>0){console.log(`Keeping the previous plugin bundle ${L(t.from)}: ${y.map((I)=>I.state==="unreadable"?`${I.config} (unreadable)`:I.config).join(", ")} may still name it.`);return}let f=await _r(t,c.entries);if("refused"in f){console.error(`HOST_UPDATE_PRUNE_REFUSED: ${L(t.from)}: ${f.refused}; nothing was removed`);return}try{await hn(f.directory,{recursive:!0,force:!0}),await hn(J(e.configDir,X),{force:!0})}catch(I){console.error(`HOST_UPDATE_PRUNE_FAILED: ${L(t.from)}: ${I.message}`);return}console.log(`Removed the previous plugin bundle ${L(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 c=On(s.config);if(!c.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(c.value.plugins)?c.value.plugins:[],f=y.findIndex(ge),I=y[f];if(I===void 0||typeof I.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 O=await le(I.source);if(!O.ok)return console.error(`HOST_UPDATE_BUNDLE_UNREADABLE: the installed plugin bundle ${I.source} is ${O.reason}; nothing changed. \`hightea host status\` names the repair.`),1;let S=O.bundle.version,E=wn(S),h=wn(t.version);if(E===void 0||h===void 0)return console.error(`HOST_UPDATE_VERSION_UNREADABLE: cannot order the installed bundle ${S} against this CLI's ${t.version} (each must be x.y.z or x.y.z-dev.<hash8>); nothing changed`),1;let T=mr(h,E)||(t.version===S?0:1);if(T<0)return console.error(`HOST_UPDATE_DOWNGRADE: host ${s.hostId} runs plugin bundle ${S}, newer than this CLI's ${t.version}; nothing changed. Update the CLI instead.`),1;if(T===0)return console.log(`Host ${s.hostId} already runs plugin bundle ${S}; ${s.config} was left unchanged.`),await _n(s),0;await _n(s);let b;try{b=await Se(z("XDG_DATA_HOME",J(".local","share")),t.directory,t.version)}catch(K){let j=K instanceof Error&&/^HOST_JOIN_[A-Z_]+$/u.test(K.message)?K.message:"HOST_JOIN_CONFIG_IO";return console.error(`${j.replace(/^HOST_JOIN_/u,"HOST_UPDATE_")}: ${Q[j]??"the new bundle could not be installed"} ${s.config} was left unchanged.`),1}let H={from:I.source,to:b.manifest,fromVersion:S,toVersion:b.version,at:new Date().toISOString()},k=y.slice(),F=Array.isArray(I.grants)?I.grants.filter((K)=>typeof K==="string"):[],D=Sn.filter((K)=>!F.includes(K));k[f]={...I,source:b.manifest,...D.length===0?{}:{grants:[...F,...D]}};try{Ae(J(s.configDir,X),H,{mode:384}),Ae(s.config,{...c.value,plugins:k},{mode:384})}catch(K){return console.error(`HOST_UPDATE_CONFIG_UNWRITABLE: ${s.config}: ${K.message}`),1}return console.log(`Host ${s.hostId} now loads plugin bundle ${b.version} (was ${S}), 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 ${L(I.source)} is kept until the host connects at ${b.version}. Restart it with: ${se(s.claim)}`),0}function Ir(e){if(e===void 0||e==="")throw Error("HOST_JOIN_RECEIPT_INVALID");return e}
5
5
  export{m,o,g,N,R,n,i,x,C};
@@ -1 +1 @@
1
- import{N,R,n,i,x,C}from"./chunk-kq5y08g7.js";import"./chunk-tay0pyz4.js";export{N as hostJoin,x as hostServicesGrants,R as hostStatus,C as hostUpdate,n as localHost,i as runningAhpds};
1
+ import{N,R,n,i,x,C}from"./chunk-8td27k15.js";import"./chunk-tay0pyz4.js";export{N as hostJoin,x as hostServicesGrants,R as hostStatus,C as hostUpdate,n as localHost,i as runningAhpds};
@@ -0,0 +1,13 @@
1
+ import"./chunk-kjkww5cr.js";import{t,e}from"./chunk-vzkbknwq.js";var u=`hightea source bind --origin https://your-deployment --workspace SLUG --source SOURCE --host HOST [--every 1h] [--session-file FILE] [--json]
2
+ hightea source bind-linear --origin https://your-deployment --workspace SLUG --team TEAM [--every 5m] [--session-file FILE] [--json]
3
+ hightea source teams --origin https://your-deployment --workspace SLUG [--session-file FILE] [--json]
4
+ hightea source unbind --origin https://your-deployment --workspace SLUG --source SOURCE [--session-file FILE] [--json]
5
+ hightea source refresh --origin https://your-deployment --workspace SLUG --source SOURCE --every 1h [--session-file FILE] [--json]
6
+ hightea source status --origin https://your-deployment --workspace SLUG --source SOURCE [--session-file FILE] [--json]`;function l(n){let r=n.trim().toLowerCase();if(r==="")return"INVALID";if(r==="none"||r==="off")return null;let o=/^(\d+)(s|m|h|d)$/u.exec(r);if(o===null)return"INVALID";let s={s:1000,m:60000,h:3600000,d:86400000}[o[2]],i=Number(o[1])*s;return Number.isSafeInteger(i)&&i>0?i:"INVALID"}var f={SOURCE_BINDING_CONFLICT:4};function a(){return t()}async function h(n,r,o){if(n.workspace.trim().length===0||n.source.trim().length===0)return{exit:1,error:`SOURCE_INPUT: --workspace and --source are required.
7
+ ${u}`};return e(n,r,{...o,label:"SOURCE",extraExits:f,path:`/sources/${encodeURIComponent(n.source)}${o.path}`})}function d(n){let r=(s)=>n[s]===null||n[s]===void 0?"none":String(n[s]),o=n.listing===!0?", first list running":n.listing===!1?", no list running":"";return`${r("status")} on ${r("hostId")} as dataset ${r("dataset")} (freshness ${r("freshness")}${o})`}async function S(n,r=a()){if(n.host.trim().length===0)return r.err(`SOURCE_INPUT: --host is required (the host id that serves the source).
8
+ ${u}`),1;let o=n.refresh===void 0?void 0:l(n.refresh);if(o==="INVALID"||o===null)return r.err(`SOURCE_INPUT: --every takes a whole count and one unit — 30m, 1h, 2d — and a bind never clears a schedule.
9
+ ${u}`),1;let s=await h(n,r,{method:"POST",path:"/bind",body:o===void 0?{hostId:n.host.trim()}:{hostId:n.host.trim(),refreshMs:o},what:"bind"});if("error"in s)return r.err(s.error),s.exit;if(n.json)return r.out(JSON.stringify(s.answer)),0;let i=s.answer.source??{};return r.out(`bound ${String(i.sourceId??n.source)} to ${String(i.hostId??n.host)}: ${d(i)}`),r.out("The source's first list fills its dataset; run `hightea source status` to watch its freshness."),0}async function y(n,r=a()){let o=n.team.trim();if(n.workspace.trim().length===0||o.length===0)return r.err(`SOURCE_INPUT: --workspace and --team are required (the Linear team id; \`hightea source teams\` lists them).
10
+ ${u}`),1;let s=n.refresh===void 0?void 0:l(n.refresh);if(s==="INVALID"||s===null)return r.err(`SOURCE_INPUT: --every takes a whole count and one unit — 5m, 1h, 2d — and a bind never clears a schedule.
11
+ ${u}`),1;let i=await e(n,r,{method:"POST",label:"SOURCE",extraExits:f,path:`/linear/teams/${encodeURIComponent(o)}/bind`,body:s===void 0?{}:{refreshMs:s},what:"bind-linear"});if("error"in i)return r.err(i.error),i.exit;if(n.json)return r.out(JSON.stringify(i.answer)),0;let c=i.answer.source??{};return r.out(`bound Linear team ${o} as ${String(c.sourceId??`linear:${o}`)}: ${d(c)}`),r.out("The first sweep is queued with the binding; `hightea source status` watches its freshness."),0}async function p(n,r=a()){let o=await e(n,r,{method:"GET",label:"SOURCE",extraExits:f,path:"/linear/teams",what:"teams"});if("error"in o)return r.err(o.error),o.exit;if(n.json)return r.out(JSON.stringify(o.answer)),0;let s=o.answer.teams??[];if(s.length===0)return r.out("Linear sees no teams for this workspace's token; authorize Linear first."),0;for(let i of s)r.out(`${String(i.id)} ${String(i.key)} ${String(i.name)}`);return 0}async function w(n,r=a()){let o=await h(n,r,{method:"POST",path:"/unbind",what:"unbind"});if("error"in o)return r.err(o.error),o.exit;if(n.json)return r.out(JSON.stringify(o.answer)),0;let s=o.answer.source??{};return r.out(`unbound ${String(s.sourceId??n.source)} from ${String(s.hostId??"its host")}: ${d(s)}`),r.out("Rows kept; rebind refreshes them."),0}async function g(n,r=a()){let o=await h(n,r,{method:"GET",path:"",what:"read"});if("error"in o)return r.err(o.error),o.exit;if(n.json)return r.out(JSON.stringify(o.answer)),0;let s=o.answer.source??{},i=s.position;return r.out(`${String(s.sourceId??n.source)}: ${d(s)}`),r.out(`position ${i===null||i===void 0?"none":`${String(i.epoch)}/${String(i.ordinal)}`}, last error ${s.lastError===null||s.lastError===void 0?"none":String(s.lastError)}, dropped ${String(s.dropped??0)}, duplicates ${String(s.duplicates??0)}`),0}async function I(n,r=a()){if(n.every.trim().length===0)return r.err(`SOURCE_INPUT: --every is required (1h, 30m, 2d, or none).
12
+ ${u}`),1;let o=l(n.every);if(o==="INVALID")return r.err(`SOURCE_INPUT: --every takes a whole count and one unit — 45s, 30m, 1h, 2d — or none.
13
+ ${u}`),1;let s=await h(n,r,{method:"POST",path:"/schedule",body:{everyMs:o},what:"set its refresh interval"});if("error"in s)return r.err(s.error),s.exit;if(n.json)return r.out(JSON.stringify(s.answer)),0;let i=s.answer.source??{},c=i.reconcileMs===null||i.reconcileMs===void 0?"no schedule (refreshes only when the host reports a gap)":`refresh every ${Math.round(Number(i.reconcileMs)/60000)} min`;return r.out(`${String(i.sourceId??n.source)}: ${c}; ${d(i)}`),0}export{S as sourceBind,y as sourceBindLinear,I as sourceSetRefresh,g as sourceShow,p as sourceTeams,w as sourceUnbind};
@@ -1 +1 @@
1
- import"./chunk-tay0pyz4.js";import{o,n}from"./chunk-kq5y08g7.js";import{h}from"./chunk-3w7svm2r.js";import{r}from"./chunk-evg5apz3.js";var P='That code is not waiting here. It may have expired, or already have been used. On the browser, press "Approve this browser" again for a new code.';async function O(e){let{createInterface:s}=await import("node:readline/promises"),t=s({input:process.stdin,output:process.stderr});try{return/^y(es)?$/iu.test((await t.question(e)).trim())}finally{t.close()}}function l(e){return typeof e==="string"?e:""}async function R(e){try{let s=await e.json();return typeof s==="object"&&s!==null?s:null}catch{return null}}function N(e,s){let t=e?.error;if(typeof t==="object"&&t!==null){let a=t,m=l(a.code),d=l(a.message);if(m!==""&&d!=="")return`${m}: ${d}`;if(d!=="")return d}return`the deployment answered ${String(s)}`}async function H(e,s={localHost:(t)=>n(t),trust:(t)=>h(t),confirm:O,fetch:(t,a)=>fetch(t,a)}){try{r(e.caller,"key-trust")}catch(i){return console.error(`${i.message}; nothing was approved`),1}let t=await s.localHost(e.host);if("error"in t)return console.error(t.error.replace(/^SERVICE_/u,"APPROVE_")),1;let a=(e.origin??t.gateway??"").trim().replace(/\/+$/u,"");if(a==="")return console.error(`APPROVE_ORIGIN_UNKNOWN: this machine's claim for host ${t.hostId} records no deployment address; name it with --origin <url> and the workspace with --workspace <slug>; nothing was approved`),1;let m=(e.workspace??t.workspaceId).trim();if(m==="")return console.error("APPROVE_WORKSPACE_UNKNOWN: no workspace slug to ask about; name it with --workspace <slug>; nothing was approved"),1;let d=e.code.trim();if(d==="")return console.error("APPROVE_CODE_MISSING: give the code the browser shows, e.g. `hightea approve 7QK4-2M8X`; nothing was approved"),1;let A=`${a}/api/ws/${encodeURIComponent(m)}/browser-approval/${encodeURIComponent(d)}`,u;try{u=await s.fetch(A,{headers:{accept:"application/json"},redirect:"error"})}catch(i){return console.error(`APPROVE_UNREACHABLE: could not reach ${a} (${i.message}); nothing was approved`),1}if(u.status===404)return console.error(P),1;let c=await R(u);if(c===null)return console.error(`APPROVE_ANSWER_INVALID: ${a} answered ${String(u.status)} without a JSON body; nothing was approved`),1;if(u.status!==200)return console.error(`APPROVE_REFUSED: ${N(c,u.status)}; nothing was approved`),1;let y=l(c.state);if(y==="approved")return console.error(P),1;if(y!=="pending")return console.error(`APPROVE_ANSWER_INVALID: ${a} answered a state this command does not know (${JSON.stringify(y)}); nothing was approved`),1;let p=l(c.browser).trim(),k=l(c.check).trim(),v=l(c.publicKey),w=l(c.personName).trim(),E=l(c.expiresAt),b=o(v);if(p===""||k===""||"error"in b)return console.error("APPROVE_ANSWER_INVALID: the deployment's answer names no browser and check characters, or carries no usable public key; nothing was approved"),1;let g=e.json===!0?(i)=>console.error(i):(i)=>console.log(i);if(g("Approve this browser?"),g(""),g(` ${p}`),g(` Check that your browser shows ${k}.`),g(w===""?" For: the person who asked on that browser":` For: ${w}, to ask this computer's agents`),g(""),!await s.confirm("Type y to approve, anything else to cancel: "))return console.error("Nothing was approved. The code is still waiting until it expires."),1;if(await s.trust({action:"add",caller:e.caller,name:p,publicKey:v,quiet:!0,...w===""?{}:{personName:w},...e.host===void 0?{}:{host:e.host},...e.configDir===void 0?{}:{configDir:e.configDir}})!==0)return console.error("Nothing was approved on the browser side; the code is still waiting."),1;let I=`${A}/approved`,f;try{f=await s.fetch(I,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({keyFingerprint:b.keyId}),redirect:"error"})}catch(i){return console.error(`APPROVE_NOT_MARKED: this computer now trusts ${p}, but ${a} could not be told (${i.message}). The browser keeps waiting; press "Approve this browser" again for a new code.`),1}if(f.status!==204)return console.error(`APPROVE_NOT_MARKED: this computer now trusts ${p}, but the deployment did not mark the code spent (${N(await R(f),f.status)}). The browser keeps waiting; press "Approve this browser" again for a new code.`),1;if(e.json===!0)return console.log(JSON.stringify({approved:!0,browser:p,keyId:b.keyId,personName:w===""?null:w,expiresAt:E})),0;return console.log(`Approved. ${p} can ask this computer's agents from now on.`),console.log(`Remove it later: hightea browsers remove "${p}"`),0}export{H as hostApprove};
1
+ import"./chunk-tay0pyz4.js";import{o,n}from"./chunk-8td27k15.js";import{h}from"./chunk-3pxbkmsq.js";import{r}from"./chunk-evg5apz3.js";var P='That code is not waiting here. It may have expired, or already have been used. On the browser, press "Approve this browser" again for a new code.';async function O(e){let{createInterface:s}=await import("node:readline/promises"),t=s({input:process.stdin,output:process.stderr});try{return/^y(es)?$/iu.test((await t.question(e)).trim())}finally{t.close()}}function l(e){return typeof e==="string"?e:""}async function R(e){try{let s=await e.json();return typeof s==="object"&&s!==null?s:null}catch{return null}}function N(e,s){let t=e?.error;if(typeof t==="object"&&t!==null){let a=t,m=l(a.code),d=l(a.message);if(m!==""&&d!=="")return`${m}: ${d}`;if(d!=="")return d}return`the deployment answered ${String(s)}`}async function H(e,s={localHost:(t)=>n(t),trust:(t)=>h(t),confirm:O,fetch:(t,a)=>fetch(t,a)}){try{r(e.caller,"key-trust")}catch(i){return console.error(`${i.message}; nothing was approved`),1}let t=await s.localHost(e.host);if("error"in t)return console.error(t.error.replace(/^SERVICE_/u,"APPROVE_")),1;let a=(e.origin??t.gateway??"").trim().replace(/\/+$/u,"");if(a==="")return console.error(`APPROVE_ORIGIN_UNKNOWN: this machine's claim for host ${t.hostId} records no deployment address; name it with --origin <url> and the workspace with --workspace <slug>; nothing was approved`),1;let m=(e.workspace??t.workspaceId).trim();if(m==="")return console.error("APPROVE_WORKSPACE_UNKNOWN: no workspace slug to ask about; name it with --workspace <slug>; nothing was approved"),1;let d=e.code.trim();if(d==="")return console.error("APPROVE_CODE_MISSING: give the code the browser shows, e.g. `hightea approve 7QK4-2M8X`; nothing was approved"),1;let A=`${a}/api/ws/${encodeURIComponent(m)}/browser-approval/${encodeURIComponent(d)}`,u;try{u=await s.fetch(A,{headers:{accept:"application/json"},redirect:"error"})}catch(i){return console.error(`APPROVE_UNREACHABLE: could not reach ${a} (${i.message}); nothing was approved`),1}if(u.status===404)return console.error(P),1;let c=await R(u);if(c===null)return console.error(`APPROVE_ANSWER_INVALID: ${a} answered ${String(u.status)} without a JSON body; nothing was approved`),1;if(u.status!==200)return console.error(`APPROVE_REFUSED: ${N(c,u.status)}; nothing was approved`),1;let y=l(c.state);if(y==="approved")return console.error(P),1;if(y!=="pending")return console.error(`APPROVE_ANSWER_INVALID: ${a} answered a state this command does not know (${JSON.stringify(y)}); nothing was approved`),1;let p=l(c.browser).trim(),k=l(c.check).trim(),v=l(c.publicKey),w=l(c.personName).trim(),E=l(c.expiresAt),b=o(v);if(p===""||k===""||"error"in b)return console.error("APPROVE_ANSWER_INVALID: the deployment's answer names no browser and check characters, or carries no usable public key; nothing was approved"),1;let g=e.json===!0?(i)=>console.error(i):(i)=>console.log(i);if(g("Approve this browser?"),g(""),g(` ${p}`),g(` Check that your browser shows ${k}.`),g(w===""?" For: the person who asked on that browser":` For: ${w}, to ask this computer's agents`),g(""),!await s.confirm("Type y to approve, anything else to cancel: "))return console.error("Nothing was approved. The code is still waiting until it expires."),1;if(await s.trust({action:"add",caller:e.caller,name:p,publicKey:v,quiet:!0,...w===""?{}:{personName:w},...e.host===void 0?{}:{host:e.host},...e.configDir===void 0?{}:{configDir:e.configDir}})!==0)return console.error("Nothing was approved on the browser side; the code is still waiting."),1;let I=`${A}/approved`,f;try{f=await s.fetch(I,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({keyFingerprint:b.keyId}),redirect:"error"})}catch(i){return console.error(`APPROVE_NOT_MARKED: this computer now trusts ${p}, but ${a} could not be told (${i.message}). The browser keeps waiting; press "Approve this browser" again for a new code.`),1}if(f.status!==204)return console.error(`APPROVE_NOT_MARKED: this computer now trusts ${p}, but the deployment did not mark the code spent (${N(await R(f),f.status)}). The browser keeps waiting; press "Approve this browser" again for a new code.`),1;if(e.json===!0)return console.log(JSON.stringify({approved:!0,browser:p,keyId:b.keyId,personName:w===""?null:w,expiresAt:E})),0;return console.log(`Approved. ${p} can ask this computer's agents from now on.`),console.log(`Remove it later: hightea browsers remove "${p}"`),0}export{H as hostApprove};
@@ -0,0 +1 @@
1
+ import{h}from"./chunk-3pxbkmsq.js";import"./chunk-8td27k15.js";import"./chunk-tay0pyz4.js";export{h as hostTrust};
@@ -1,7 +1,7 @@
1
1
  {
2
- "id": "hightea-pipe",
2
+ "id": "hightea-host",
3
3
  "main": "./plugin.mjs",
4
- "version": "0.1.34",
4
+ "version": "0.1.35",
5
5
  "grants": [
6
6
  "session:write",
7
7
  "session:state",