@hallohuman/hightea 0.1.32 → 0.1.33

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,4 +1,4 @@
1
- import"./chunk-dvsftn8z.js";import{t,e}from"./chunk-55a0ndzw.js";var u=`hightea source bind --origin https://your-deployment --workspace SLUG --source SOURCE --host HOST [--refresh 1h] [--session-file FILE] [--json]
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 [--refresh 1h] [--session-file FILE] [--json]
2
2
  hightea source bind-linear --origin https://your-deployment --workspace SLUG --team TEAM [--refresh 5m] [--session-file FILE] [--json]
3
3
  hightea source teams --origin https://your-deployment --workspace SLUG [--session-file FILE] [--json]
4
4
  hightea source unbind --origin https://your-deployment --workspace SLUG --source SOURCE [--session-file FILE] [--json]
@@ -1,4 +1,4 @@
1
- import"./chunk-dvsftn8z.js";import{t,e}from"./chunk-55a0ndzw.js";var c={ADMIN_SEAT_REQUIRED:4},m=`hightea admin room create --origin https://your-deployment --workspace SLUG --slug ROOM --seat @chief [--title TITLE] [--session-file FILE] [--json]
1
+ import"./chunk-kjkww5cr.js";import{t,e}from"./chunk-vzkbknwq.js";var c={ADMIN_SEAT_REQUIRED:4},m=`hightea admin room create --origin https://your-deployment --workspace SLUG --slug ROOM --seat @chief [--title TITLE] [--session-file FILE] [--json]
2
2
  hightea admin member remove --origin https://your-deployment --workspace SLUG MEMBER_ID --seat @chief [--session-file FILE] [--json]
3
3
  hightea admin members --origin https://your-deployment --workspace SLUG [--session-file FILE] [--json]
4
4
  hightea admin activity --origin https://your-deployment --workspace SLUG [--seat @chief] [--limit 100] [--session-file FILE] [--json]`;function d(){return t()}function f(r){if(r.seat===void 0||r.seat.trim().length===0)return{};let n=r.seat.trim();if(!/^@[A-Za-z0-9][A-Za-z0-9._/-]*$/u.test(n))return null;return{"x-hightea-seat":n}}async function u(r,n,i){if(r.workspace.trim().length===0)return{exit:1,error:`ADMIN_INPUT: --workspace is required.
@@ -0,0 +1 @@
1
+ import{h}from"./chunk-3w7svm2r.js";import"./chunk-kq5y08g7.js";import"./chunk-tay0pyz4.js";export{h as hostTrust};
@@ -0,0 +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};
@@ -0,0 +1 @@
1
+ import{s,f,I,v,O}from"./chunk-kjkww5cr.js";export{I as authLogin,O as authLogout,v as authStatus,s as checkedOrigin,f as ensureCredential};
@@ -1,4 +1,4 @@
1
- import{a}from"./chunk-pexgyagn.js";import"./chunk-ah99zytf.js";import{i}from"./chunk-c7atktnb.js";import{S,E}from"./chunk-v221hgba.js";import{readFile as D}from"node:fs/promises";import{join as O}from"node:path";var h=`hightea deploy <service> --pin <sha> [--host <id>] [--json]
2
- hightea deploy status <service> [--host <id>] [--json]`,P=/^[0-9a-fA-F]{40}$/u,y=()=>({out:(e)=>console.log(e),err:(e)=>console.error(e)}),_=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),u=(e)=>e.hostIds.length>0?`${e.hostIds.join(",")} (pid ${String(e.pid)})`:`pid ${String(e.pid)}`;async function N(e,n){if(e.port!==void 0)return e.port;try{let s=JSON.parse(await n(e.config));if(_(s)&&typeof s.port==="number"&&Number.isInteger(s.port))return s.port}catch{return}return}async function R(e,n){let s=e.connectionTokenFile??O(e.configDir,"connection.token");try{return(await n(s)).trim()||void 0}catch{return}}async function f(e,n={}){let s=n.readFile??((t)=>D(t,"utf8")),d;try{d=await(n.runningAhpds??i)()}catch(t){return{error:`DEPLOY_NO_AHPD: the process table could not be read: ${t.message}`}}let l=e?.trim(),r;if(l!==void 0&&l!==""){let t=d.filter((p)=>p.hostIds.includes(l));if(t.length===0)return{error:`DEPLOY_NO_AHPD: no running ahpd on this machine serves host ${l} (running: ${d.map(u).join("; ")||"none"})`};if(t.length>1)return{error:`DEPLOY_NO_AHPD: ${String(t.length)} running ahpds serve host ${l} (${t.map(u).join("; ")}); the process table cannot tell them apart`};r=t[0]}else{if(d.length===0)return{error:"DEPLOY_NO_AHPD: no running ahpd on this machine; start one with `hightea host join` first"};if(d.length>1)return{error:`DEPLOY_NO_AHPD: this machine runs ${String(d.length)} ahpds (${d.map(u).join("; ")}); name one with --host <id>`};r=d[0]}if(r===void 0)return{error:"DEPLOY_NO_AHPD: no running ahpd on this machine"};let c=await N(r,s);if(c===void 0)return{error:`DEPLOY_NO_AHPD: ${r.config} names no port and its command line has no --port; cannot reach this ahpd`};let o=await R(r,s);return{url:`ws://${r.host??"127.0.0.1"}:${String(c)}`,...o===void 0?{}:{token:o},label:r.hostIds[0]??`pid ${String(r.pid)}`}}async function g(e,n){try{return await(n.connect??a)(e.url,{token:e.token,clientId:"hightea-deploy"})}catch(s){return{error:`DEPLOY_NO_AHPD: ${e.url} did not answer: ${s.message}`}}}var I=(e,n)=>{if(e==="RUNNING")return`DEPLOY_RUNNING: ${n}`;if(e==="UNKNOWN_SERVICE")return`DEPLOY_UNKNOWN_SERVICE: ${n}`;return`DEPLOY_REFUSED ${e}: ${n}`},m=(e)=>/No channel at x-hh-deploys:\/\//u.test(e.message)?"DEPLOY_NO_DRIVER: this ahpd has no deploy driver loaded (x-hh-deploys://); its deploy plugin is not in its configuration":`DEPLOY_DRIVER_UNREADABLE: ${e.message}`;async function x(e,n=y(),s={}){let d=e.service.trim();if(d==="")return n.err(`DEPLOY_SERVICE_REQUIRED: name the service to deploy
3
- ${h}`),1;let l=e.pin.trim();if(!P.test(l))return n.err(`DEPLOY_PIN_NOT_SHA: --pin must be a full 40-character commit sha; '${l}' is not`),1;let r=await f(e.host,s);if("error"in r)return n.err(r.error),1;let c=await g(r,s);if("error"in c)return n.err(c.error),1;try{let o=await S(c,{service:d,version:l.toLowerCase()});if(!o.ok)return n.err(I(o.code,o.message)),1;if(e.json)n.out(JSON.stringify({machine:r.label,service:o.service,pin:o.sha,deployId:o.deployId,state:o.state}));else n.out(`started ${o.service} at ${o.sha}: deploy ${o.deployId} on ${r.label}`);return 0}catch(o){return n.err(m(o)),1}finally{c.close()}}var A=(e,n)=>({machine:n,service:e.service,state:e.state,pin:e.to??null,from:e.from??null,...e.step===void 0?{}:{step:e.step},...e.reason===void 0?{}:{reason:e.reason},...e.exit===void 0?{}:{exit:e.exit},deployId:e.deployId,...e.at===void 0?{}:{at:e.at}});async function j(e,n=y(),s={}){let d=e.service.trim();if(d==="")return n.err(`DEPLOY_SERVICE_REQUIRED: name the service to read
4
- ${h}`),1;let l=await f(e.host,s);if("error"in l)return n.err(l.error),1;let r=await g(l,s);if("error"in r)return n.err(r.error),1;try{let c=await E(r),o=c.runs.filter((p)=>p.service===d);if(o.length===0){let p=c.error===void 0?"":` (${c.error})`;return n.err(`DEPLOY_UNKNOWN_SERVICE: ${d} has no deploy on ${c.machine||l.label}${p}`),1}let t=A(o[0],c.machine||l.label);if(e.json)n.out(JSON.stringify(t));else n.out(`${t.state} ${t.service} pin ${t.pin??"?"} ${t.step===void 0?"":`${t.step} `}deploy ${t.deployId}${t.reason===void 0?"":` last error: ${t.reason}`}`);return 0}catch(c){return n.err(m(c)),1}finally{r.close()}}export{x as deployPlace,j as deployStatus};
1
+ import{c}from"./chunk-jaf9mk6s.js";import"./chunk-tay0pyz4.js";import{i}from"./chunk-kq5y08g7.js";import{S,E}from"./chunk-evg5apz3.js";import{readFile as D}from"node:fs/promises";import{join as O}from"node:path";var h=`hightea deploy <service> --pin <sha> [--host <id>] [--json]
2
+ hightea deploy status <service> [--host <id>] [--json]`,P=/^[0-9a-fA-F]{40}$/u,y=()=>({out:(e)=>console.log(e),err:(e)=>console.error(e)}),_=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),u=(e)=>e.hostIds.length>0?`${e.hostIds.join(",")} (pid ${String(e.pid)})`:`pid ${String(e.pid)}`;async function N(e,n){if(e.port!==void 0)return e.port;try{let s=JSON.parse(await n(e.config));if(_(s)&&typeof s.port==="number"&&Number.isInteger(s.port))return s.port}catch{return}return}async function R(e,n){let s=e.connectionTokenFile??O(e.configDir,"connection.token");try{return(await n(s)).trim()||void 0}catch{return}}async function f(e,n={}){let s=n.readFile??((t)=>D(t,"utf8")),a;try{a=await(n.runningAhpds??i)()}catch(t){return{error:`DEPLOY_NO_AHPD: the process table could not be read: ${t.message}`}}let d=e?.trim(),r;if(d!==void 0&&d!==""){let t=a.filter((p)=>p.hostIds.includes(d));if(t.length===0)return{error:`DEPLOY_NO_AHPD: no running ahpd on this machine serves host ${d} (running: ${a.map(u).join("; ")||"none"})`};if(t.length>1)return{error:`DEPLOY_NO_AHPD: ${String(t.length)} running ahpds serve host ${d} (${t.map(u).join("; ")}); the process table cannot tell them apart`};r=t[0]}else{if(a.length===0)return{error:"DEPLOY_NO_AHPD: no running ahpd on this machine; start one with `hightea host join` first"};if(a.length>1)return{error:`DEPLOY_NO_AHPD: this machine runs ${String(a.length)} ahpds (${a.map(u).join("; ")}); name one with --host <id>`};r=a[0]}if(r===void 0)return{error:"DEPLOY_NO_AHPD: no running ahpd on this machine"};let l=await N(r,s);if(l===void 0)return{error:`DEPLOY_NO_AHPD: ${r.config} names no port and its command line has no --port; cannot reach this ahpd`};let o=await R(r,s);return{url:`ws://${r.host??"127.0.0.1"}:${String(l)}`,...o===void 0?{}:{token:o},label:r.hostIds[0]??`pid ${String(r.pid)}`}}async function g(e,n){try{return await(n.connect??c)(e.url,{token:e.token,clientId:"hightea-deploy"})}catch(s){return{error:`DEPLOY_NO_AHPD: ${e.url} did not answer: ${s.message}`}}}var I=(e,n)=>{if(e==="RUNNING")return`DEPLOY_RUNNING: ${n}`;if(e==="UNKNOWN_SERVICE")return`DEPLOY_UNKNOWN_SERVICE: ${n}`;return`DEPLOY_REFUSED ${e}: ${n}`},m=(e)=>/No channel at x-hh-deploys:\/\//u.test(e.message)?"DEPLOY_NO_DRIVER: this ahpd has no deploy driver loaded (x-hh-deploys://); its deploy plugin is not in its configuration":`DEPLOY_DRIVER_UNREADABLE: ${e.message}`;async function x(e,n=y(),s={}){let a=e.service.trim();if(a==="")return n.err(`DEPLOY_SERVICE_REQUIRED: name the service to deploy
3
+ ${h}`),1;let d=e.pin.trim();if(!P.test(d))return n.err(`DEPLOY_PIN_NOT_SHA: --pin must be a full 40-character commit sha; '${d}' is not`),1;let r=await f(e.host,s);if("error"in r)return n.err(r.error),1;let l=await g(r,s);if("error"in l)return n.err(l.error),1;try{let o=await S(l,{service:a,version:d.toLowerCase()});if(!o.ok)return n.err(I(o.code,o.message)),1;if(e.json)n.out(JSON.stringify({machine:r.label,service:o.service,pin:o.sha,deployId:o.deployId,state:o.state}));else n.out(`started ${o.service} at ${o.sha}: deploy ${o.deployId} on ${r.label}`);return 0}catch(o){return n.err(m(o)),1}finally{l.close()}}var A=(e,n)=>({machine:n,service:e.service,state:e.state,pin:e.to??null,from:e.from??null,...e.step===void 0?{}:{step:e.step},...e.reason===void 0?{}:{reason:e.reason},...e.exit===void 0?{}:{exit:e.exit},deployId:e.deployId,...e.at===void 0?{}:{at:e.at}});async function j(e,n=y(),s={}){let a=e.service.trim();if(a==="")return n.err(`DEPLOY_SERVICE_REQUIRED: name the service to read
4
+ ${h}`),1;let d=await f(e.host,s);if("error"in d)return n.err(d.error),1;let r=await g(d,s);if("error"in r)return n.err(r.error),1;try{let l=await E(r),o=l.runs.filter((p)=>p.service===a);if(o.length===0){let p=l.error===void 0?"":` (${l.error})`;return n.err(`DEPLOY_UNKNOWN_SERVICE: ${a} has no deploy on ${l.machine||d.label}${p}`),1}let t=A(o[0],l.machine||d.label);if(e.json)n.out(JSON.stringify(t));else n.out(`${t.state} ${t.service} pin ${t.pin??"?"} ${t.step===void 0?"":`${t.step} `}deploy ${t.deployId}${t.reason===void 0?"":` last error: ${t.reason}`}`);return 0}catch(l){return n.err(m(l)),1}finally{r.close()}}export{x as deployPlace,j as deployStatus};
@@ -1,2 +1,2 @@
1
- var y=(e,t)=>({kind:e,id:t}),O=(e,t)=>e!==void 0&&t!==void 0&&e.kind===t.kind&&e.id===t.id,A=(e)=>`${e.kind}:${e.id}`;function r(e,t){if(e.kind==="agent")throw Error(`${t}: a person must grant this; agent ${e.id} cannot`)}var N="source",w="x-hh/source",J=["command","cwd","env","schedule","restart","depends_on","health"],C=(e)=>({command:e.command,cwd:e.cwd,env:e.env,schedule:e.schedule,restart:e.restart,depends_on:e.depends_on,health:e.health}),h=(e)=>{if(e===void 0)return"undefined";if(Array.isArray(e))return`[${e.map(h).join(",")}]`;if(e!==null&&typeof e==="object")return`{${Object.keys(e).sort().map((n)=>`${JSON.stringify(n)}:${h(e[n])}`).join(",")}}`;return JSON.stringify(e)},L=(e,t)=>{let n=C(e),o=C(t);return J.filter((i)=>h(n[i])!==h(o[i]))},R="x-hh-services://",v=(e,t,n)=>e.call("x-ahpd/invokeOperation",{channel:R,operationId:t,...n}),F=async(e)=>{let t=await e.call("subscribe",{channel:R});await e.call("unsubscribe",{channel:R});let n=t?.snapshot?.state;if(typeof n?.error==="string")throw Error(`the machine's services could not be read: ${n.error}`);if(n===void 0||!Array.isArray(n.rows))throw Error("the services channel answered no rows");let o=n.rows;return{services:o.flatMap((i)=>i.record===void 0?[]:[U(i.record,i.state)]),readOnly:o.flatMap((i)=>i.readOnly===void 0?[]:[{name:i.name,reason:i.readOnly}]),capabilities:n.capabilities,ifVersion:n.ifVersion,...typeof n.file==="string"?{file:n.file}:{}}},U=(e,t)=>{if(!p(t)||typeof t.status!=="string")return e;return{...e,state:{status:t.status,...typeof t.why==="string"?{why:t.why}:{}}}},H="x-hh-deploys://";async function S(e,t){if(typeof t?.service!=="string"||t.service.trim()==="")throw Error("deployService: service is a non-empty name");if(typeof t?.version!=="string"||t.version.trim()==="")throw Error("deployService: version is a branch, a tag or a commit sha");let n=await e.call("x-ahpd/invokeOperation",{channel:H,operationId:"deploy",target:{id:t.service},input:{service:t.service,version:t.version}});if(!p(n))throw Error(`the deploys channel answered no record: ${JSON.stringify(n)}`);if(n.ok===!0){let{service:a,sha:f,deployId:c}=n;if(typeof a!=="string"||typeof f!=="string"||typeof c!=="string"||n.state!=="started")throw Error(`the deploys channel answered a start without service, sha, deployId and state: ${JSON.stringify(n)}`);return{ok:!0,service:a,sha:f,deployId:c,state:"started"}}let{code:o,message:i}=n;if(n.ok===!1&&typeof o==="string"&&o!==""&&typeof i==="string")return{ok:!1,code:o,message:i};throw Error(`the deploys channel answered neither a start nor a named refusal: ${JSON.stringify(n)}`)}var W=(e)=>{if(!p(e))return;let{service:t,deployId:n,state:o}=e;if(typeof t!=="string"||typeof n!=="string"||typeof o!=="string")return;let{step:i,from:a,to:f,at:c,last:l}=e,s=p(l)&&typeof l.reason==="string"?l.reason:void 0,d=p(l)&&(l.exit===null||typeof l.exit==="number")?l.exit:void 0;return{service:t,deployId:n,state:o,...typeof i==="string"?{step:i}:{},...a===null||typeof a==="string"?{from:a}:{},...typeof f==="string"?{to:f}:{},...typeof c==="string"?{at:c}:{},...s===void 0?{}:{reason:s},...d===void 0?{}:{exit:d}}};async function E(e){let t=await e.call("subscribe",{channel:H});await e.call("unsubscribe",{channel:H});let n=t?.snapshot?.state;if(n===void 0)throw Error("the deploys channel answered no state");let o=Array.isArray(n.runs)?n.runs.flatMap((f)=>{let c=W(f);return c===void 0?[]:[c]}):[],i=typeof n.machine==="string"?n.machine:"",a=typeof n.error==="string"?n.error:void 0;return{machine:i,runs:o,...a===void 0?{}:{error:a}}}async function b(e,t,n){let o=Y(e);return{...(e.services===void 0?void 0:await G(e.services,t,n))??{create:[],change:[],unchanged:[],readOnly:[],remove:[],keep:[],unmanaged:[]},...e.agents===void 0?{}:{agents:await ee(e.agents,t,n)},...o.length===0?{}:{hosts:await q(o,n)}}}async function G(e,t,n){let o=await F(t),i=o.capabilities?.fields??[];if(!i.includes(N))throw Error(`this machine's services driver records no "${N}" (its fields are ${i.join(", ")}); it cannot say which client wrote an entry, so nothing is written`);let a=new Map(o.services.map((u)=>[u.name,u])),f=new Map(o.readOnly.map((u)=>[u.name,u.reason])),c=[],l=[],s=[],d=new Set;for(let u of e){d.add(u.name);let m=a.get(u.name);if(f.has(u.name))throw Error(`${u.name} is read-only on this machine: ${f.get(u.name)??""}`);if(m===void 0)c.push(u);else{let P=L(m,u);if(P.length===0)s.push(u.name);else l.push({name:u.name,before:m,after:u,changed:P})}}let g=n.prune===!0?o.services.filter((u)=>O(u.source,n.source)&&!d.has(u.name)):[];if(g.length>0&&n.removal===void 0){let u=g.map((m)=>`${m.name} (${m.state?.status??"state unknown"})`).join(", ");throw Error(`prune would remove ${u}: pass stop (stop each program, then remove the entry) or keep (leave it running here and clear its source)`)}let x=n.removal==="stop"?g:[],j=n.removal==="keep"?g:[],V=n.prune===!0?o.services.filter((u)=>!O(u.source,n.source)&&!d.has(u.name)):[];return{ifVersion:o.ifVersion,create:c,change:l,unchanged:s,readOnly:o.readOnly,remove:x,keep:j,unmanaged:V}}function Y(e){let t=e.hosts;if(t===void 0)return[];if(!Array.isArray(t))throw Error("the plan's hosts is not a list: a host entry is {name, agents}");let n=new Set;return t.map((o,i)=>{if(!p(o))throw Error(`host entry ${i+1} is not an object: a host entry is {name, agents}`);let a=o.name;if(typeof a!=="string"||a.trim().length===0)throw Error(`host entry ${i+1} names no machine: every host entry needs a non-empty "name"`);let f=Object.keys(o).filter((l)=>l!=="name"&&l!=="agents");if(f.length>0)throw Error(`host entry ${a}: unknown ${f.length===1?"field":"fields"} ${f.join(", ")} (a host entry is {name, agents})`);if(n.has(a))throw Error(`${a} is named twice in one plan`);n.add(a);let c=o.agents;if(c!==void 0&&(!Array.isArray(c)||!c.every((l)=>typeof l==="string"&&l.length>0&&l.length<=256)))throw Error(`host entry ${a}: agents must be a list of agent member ids`);return c===void 0?{name:a}:{name:a,agents:c}})}function K(e,t){let n=t.hostJoin;if(n!==void 0)return n;let o=e.map((i)=>`host:${i.name}`).join(", ");throw Error(`host entries need a workspace to mint their join links and this apply has none: ${o}. Nothing is sent and no host is created from a plan: run it with the workspace's origin and slug, signed in as a person, or take the hosts out of the plan.`)}async function q(e,t){r(t.source.kind==="agent"?{kind:"agent",id:t.source.id}:{kind:"person",id:t.source.id},"host-join"),K(e,t);let n=e.map((o)=>({name:o.name,agents:[...o.agents??[]]}));if(t.prune!==!0)return{pending:n};return{pending:n,pruneNote:"host links are not pruned; each unconsumed link expires on its own, and its expiry is printed when it is minted"}}var _="x-ahpd-agents://",z=["engine","owner","name","description","tags","model"],p=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),B=(e,t)=>{let n=t[w];if(n===void 0)return;if(!p(n))throw Error(`${e}: config.${w} is not a source ({kind, id})`);let{kind:o,id:i}=n;if(o!=="file"&&o!=="program"&&o!=="agent"&&o!=="ci")throw Error(`${e}: config.${w}.kind is not one of file, program, agent, ci`);if(typeof i!=="string"||i==="")throw Error(`${e}: config.${w}.id is empty`);return{kind:o,id:i}},Q=(e)=>{if(!p(e))throw Error("the agents channel answered an entry that is not an object");let t=p(e.record)?e.record:e,n=e.id;if(typeof n!=="string"||n==="")throw Error("the agents channel answered a record that names no id");let o=typeof t.revision==="number"&&Number.isInteger(t.revision)&&t.revision>=0?t.revision:void 0,i=p(t.config)?t.config:{},a=B(n,i);return{id:n,...o===void 0?{}:{revision:o},record:t,...a===void 0?{}:{source:a}}};async function X(e){let t=await e.call("subscribe",{channel:_});await e.call("unsubscribe",{channel:_});let n=t?.snapshot?.state,o=p(n)?n.records:void 0;if(!Array.isArray(o))throw Error("the agents channel answered no records");return o.map(Q)}var I=(e)=>({engine:e.engine,owner:e.owner,name:e.name,...e.description===void 0?{}:{description:e.description},...e.tags===void 0?{}:{tags:e.tags},...e.model===void 0?{}:{model:e.model}}),M=(e)=>Object.fromEntries(Object.entries(e).filter(([t])=>t!==w)),Z=(e,t)=>{let n=I(t),o=z.filter((a)=>h(e.record[a])!==h(n[a])),i=p(e.record.config)?e.record.config:{};if(h(M(i))!==h(M(t.config??{})))o.push("config");return o};async function ee(e,t,n){let o=await X(t),i=new Map(o.map((d)=>[d.id,d])),a=[],f=[],c=[],l=new Set;for(let d of e){if(l.has(d.id))throw Error(`${d.id} is named twice in one plan`);l.add(d.id);let g=i.get(d.id);if(g===void 0)a.push(d);else{let x=Z(g,d);if(x.length===0)c.push(d.id);else if(g.revision===void 0)throw Error(`${d.id} has no revision on this machine; it cannot be edited from here`);else f.push({id:d.id,before:g,after:d,changed:x})}}let s=n.prune===!0?o.filter((d)=>O(d.source,n.source)&&!l.has(d.id)):[];for(let d of s)if(d.revision===void 0)throw Error(`${d.id} has no revision on this machine; it cannot be removed from here`);return{create:a,change:f,unchanged:c,remove:s}}async function k(e,t,n){let o=e.ifVersion??"",i=[],a=[];for(let s of e.hosts?.pending??[]){if(n===void 0)throw Error(`host ${s.name}: host links need a workspace to mint them and this apply has none; nothing was minted`);let d;try{d=await n.mintHostJoin(s.agents)}catch(g){throw Error(`host ${s.name} was not minted: ${g.message}`)}a.push({name:s.name,link:d})}for(let s of e.create)o=(await v(t,"put",{input:{service:s,ifVersion:"absent"}})).ifVersion??o,i.push(s.name);for(let s of e.change)o=(await v(t,"put",{input:{service:s.after,ifVersion:o}})).ifVersion??o,i.push(s.name);let f=[];for(let s of e.keep??[])o=(await v(t,"put",{input:{service:{name:s.name,source:null},ifVersion:o}})).ifVersion??o,f.push(s.name);let c=[];for(let s of e.remove??[]){if(s.state?.status.toLowerCase()==="running")await v(t,"stop",{target:{id:s.name},input:{}});o=(await v(t,"remove",{target:{id:s.name},input:{ifVersion:o}})).ifVersion??o,c.push(s.name)}if(e.agents!==void 0){for(let s of e.agents.create)await D(t,s,0),i.push(`agent:${s.id}`);for(let s of e.agents.change){if(s.before.revision===void 0)throw Error(`${s.id} has no revision on this machine; it cannot be edited from here`);await D(t,s.after,s.before.revision),i.push(`agent:${s.id}`)}for(let s of e.agents.remove){if(s.revision===void 0)throw Error(`${s.id} has no revision on this machine; it cannot be removed from here`);await ne(t,s.id,s.revision),c.push(`agent:${s.id}`)}}let l=e.hosts?.pruneNote===void 0?void 0:a.length===0?"host links are not pruned; this apply minted none, so nothing of its own is outstanding":`host links are not pruned; unconsumed ones expire at ${a.map((s)=>s.link.expiresAt).sort()[0]}`;return{preview:e,written:i,removed:c,kept:f,...e.hosts===void 0?{}:{hostLinks:a},...l===void 0?{}:{hostNote:l}}}var D=(e,t,n)=>e.call("x-ahpd/agents/put",{id:t.id,...I(t),config:{...t.config,[w]:t.source},ifRevision:n}),ne=(e,t,n)=>e.call("x-ahpd/agents/remove",{id:t,ifRevision:n});function T(e){let t=[];for(let n of e.create)t.push(`+ ${n.name}`);for(let n of e.change)t.push(`~ ${n.name} (${n.changed.join(", ")})`);for(let n of e.remove??[]){let o=n.state?.status.toLowerCase()==="running";t.push(`- ${n.name} (${o?"stop, then remove":"remove"}; source ${A(n.source)})`)}for(let n of e.keep??[])t.push(`= ${n.name} (kept: left running here, source cleared)`);for(let n of e.unmanaged??[]){let o=n.source===void 0?"no source":`source ${A(n.source)}`;t.push(`? ${n.name} (not managed by this apply: ${o})`)}for(let n of e.unchanged)t.push(`= ${n}`);for(let n of e.readOnly)t.push(`! ${n.name} read-only: ${n.reason}`);if(e.hosts!==void 0){for(let n of e.hosts.pending){let o=n.agents.length===0?"no agents":`agents ${n.agents.join(",")}`;t.push(`+ host:${n.name} (pending link: the machine must join; ${o})`)}if(e.hosts.pruneNote!==void 0)t.push(`note: ${e.hosts.pruneNote}`)}if(e.agents!==void 0){for(let n of e.agents.create)t.push(`+ agent:${n.id}`);for(let n of e.agents.change)t.push(`~ agent:${n.id} (${n.changed.join(", ")})`);for(let n of e.agents.remove)t.push(`- agent:${n.id} (source ${n.source===void 0?"unknown":A(n.source)})`);for(let n of e.agents.unchanged)t.push(`= agent:${n}`)}return t}
2
- export{y,r,S,E,b,k,T};
1
+ var y=(e,t)=>({kind:e,id:t}),O=(e,t)=>e!==void 0&&t!==void 0&&e.kind===t.kind&&e.id===t.id,A=(e)=>`${e.kind}:${e.id}`;function r(e,t){if(e.kind==="agent")throw Error(`${t}: a person must grant this; agent ${e.id} cannot`)}var N="source",w="x-hh/source",J=["command","cwd","env","schedule","restart","depends_on","health"],C=(e)=>({command:e.command,cwd:e.cwd,env:e.env,schedule:e.schedule,restart:e.restart,depends_on:e.depends_on,health:e.health}),h=(e)=>{if(e===void 0)return"undefined";if(Array.isArray(e))return`[${e.map(h).join(",")}]`;if(e!==null&&typeof e==="object")return`{${Object.keys(e).sort().map((n)=>`${JSON.stringify(n)}:${h(e[n])}`).join(",")}}`;return JSON.stringify(e)},L=(e,t)=>{let n=C(e),o=C(t);return J.filter((i)=>h(n[i])!==h(o[i]))},R="x-hh-services://",v=(e,t,n)=>e.call("x-ahpd/invokeOperation",{channel:R,operationId:t,...n}),F=async(e)=>{let t=await e.call("subscribe",{channel:R});await e.call("unsubscribe",{channel:R});let n=t?.snapshot?.state;if(typeof n?.error==="string")throw Error(`the machine's services could not be read: ${n.error}`);if(n===void 0||!Array.isArray(n.rows))throw Error("the services channel answered no rows");let o=n.rows;return{services:o.flatMap((i)=>i.record===void 0?[]:[U(i.record,i.state)]),readOnly:o.flatMap((i)=>i.readOnly===void 0?[]:[{name:i.name,reason:i.readOnly}]),capabilities:n.capabilities,ifVersion:n.ifVersion,...typeof n.file==="string"?{file:n.file}:{}}},U=(e,t)=>{if(!p(t)||typeof t.status!=="string")return e;return{...e,state:{status:t.status,...typeof t.why==="string"?{why:t.why}:{}}}},H="x-hh-deploys://";async function S(e,t){if(typeof t?.service!=="string"||t.service.trim()==="")throw Error("deployService: service is a non-empty name");if(typeof t?.version!=="string"||t.version.trim()==="")throw Error("deployService: version is a branch, a tag or a commit sha");let n=await e.call("x-ahpd/invokeOperation",{channel:H,operationId:"deploy",target:{id:t.service},input:{service:t.service,version:t.version}});if(!p(n))throw Error(`the deploys channel answered no record: ${JSON.stringify(n)}`);if(n.ok===!0){let{service:a,sha:f,deployId:c}=n;if(typeof a!=="string"||typeof f!=="string"||typeof c!=="string"||n.state!=="started")throw Error(`the deploys channel answered a start without service, sha, deployId and state: ${JSON.stringify(n)}`);return{ok:!0,service:a,sha:f,deployId:c,state:"started"}}let{code:o,message:i}=n;if(n.ok===!1&&typeof o==="string"&&o!==""&&typeof i==="string")return{ok:!1,code:o,message:i};throw Error(`the deploys channel answered neither a start nor a named refusal: ${JSON.stringify(n)}`)}var W=(e)=>{if(!p(e))return;let{service:t,deployId:n,state:o}=e;if(typeof t!=="string"||typeof n!=="string"||typeof o!=="string")return;let{step:i,from:a,to:f,at:c,last:l}=e,s=p(l)&&typeof l.reason==="string"?l.reason:void 0,d=p(l)&&(l.exit===null||typeof l.exit==="number")?l.exit:void 0;return{service:t,deployId:n,state:o,...typeof i==="string"?{step:i}:{},...a===null||typeof a==="string"?{from:a}:{},...typeof f==="string"?{to:f}:{},...typeof c==="string"?{at:c}:{},...s===void 0?{}:{reason:s},...d===void 0?{}:{exit:d}}};async function E(e){let t=await e.call("subscribe",{channel:H});await e.call("unsubscribe",{channel:H});let n=t?.snapshot?.state;if(n===void 0)throw Error("the deploys channel answered no state");let o=Array.isArray(n.runs)?n.runs.flatMap((f)=>{let c=W(f);return c===void 0?[]:[c]}):[],i=typeof n.machine==="string"?n.machine:"",a=typeof n.error==="string"?n.error:void 0;return{machine:i,runs:o,...a===void 0?{}:{error:a}}}async function k(e,t,n){let o=Y(e);return{...(e.services===void 0?void 0:await G(e.services,t,n))??{create:[],change:[],unchanged:[],readOnly:[],remove:[],keep:[],unmanaged:[]},...e.agents===void 0?{}:{agents:await ee(e.agents,t,n)},...o.length===0?{}:{hosts:await q(o,n)}}}async function G(e,t,n){let o=await F(t),i=o.capabilities?.fields??[];if(!i.includes(N))throw Error(`this machine's services driver records no "${N}" (its fields are ${i.join(", ")}); it cannot say which client wrote an entry, so nothing is written`);let a=new Map(o.services.map((u)=>[u.name,u])),f=new Map(o.readOnly.map((u)=>[u.name,u.reason])),c=[],l=[],s=[],d=new Set;for(let u of e){d.add(u.name);let m=a.get(u.name);if(f.has(u.name))throw Error(`${u.name} is read-only on this machine: ${f.get(u.name)??""}`);if(m===void 0)c.push(u);else{let P=L(m,u);if(P.length===0)s.push(u.name);else l.push({name:u.name,before:m,after:u,changed:P})}}let g=n.prune===!0?o.services.filter((u)=>O(u.source,n.source)&&!d.has(u.name)):[];if(g.length>0&&n.removal===void 0){let u=g.map((m)=>`${m.name} (${m.state?.status??"state unknown"})`).join(", ");throw Error(`prune would remove ${u}: pass stop (stop each program, then remove the entry) or keep (leave it running here and clear its source)`)}let x=n.removal==="stop"?g:[],j=n.removal==="keep"?g:[],V=n.prune===!0?o.services.filter((u)=>!O(u.source,n.source)&&!d.has(u.name)):[];return{ifVersion:o.ifVersion,create:c,change:l,unchanged:s,readOnly:o.readOnly,remove:x,keep:j,unmanaged:V}}function Y(e){let t=e.hosts;if(t===void 0)return[];if(!Array.isArray(t))throw Error("the plan's hosts is not a list: a host entry is {name, agents}");let n=new Set;return t.map((o,i)=>{if(!p(o))throw Error(`host entry ${i+1} is not an object: a host entry is {name, agents}`);let a=o.name;if(typeof a!=="string"||a.trim().length===0)throw Error(`host entry ${i+1} names no machine: every host entry needs a non-empty "name"`);let f=Object.keys(o).filter((l)=>l!=="name"&&l!=="agents");if(f.length>0)throw Error(`host entry ${a}: unknown ${f.length===1?"field":"fields"} ${f.join(", ")} (a host entry is {name, agents})`);if(n.has(a))throw Error(`${a} is named twice in one plan`);n.add(a);let c=o.agents;if(c!==void 0&&(!Array.isArray(c)||!c.every((l)=>typeof l==="string"&&l.length>0&&l.length<=256)))throw Error(`host entry ${a}: agents must be a list of agent member ids`);return c===void 0?{name:a}:{name:a,agents:c}})}function K(e,t){let n=t.hostJoin;if(n!==void 0)return n;let o=e.map((i)=>`host:${i.name}`).join(", ");throw Error(`host entries need a workspace to mint their join links and this apply has none: ${o}. Nothing is sent and no host is created from a plan: run it with the workspace's origin and slug, signed in as a person, or take the hosts out of the plan.`)}async function q(e,t){r(t.source.kind==="agent"?{kind:"agent",id:t.source.id}:{kind:"person",id:t.source.id},"host-join"),K(e,t);let n=e.map((o)=>({name:o.name,agents:[...o.agents??[]]}));if(t.prune!==!0)return{pending:n};return{pending:n,pruneNote:"host links are not pruned; each unconsumed link expires on its own, and its expiry is printed when it is minted"}}var _="x-ahpd-agents://",z=["engine","owner","name","description","tags","model"],p=(e)=>e!==null&&typeof e==="object"&&!Array.isArray(e),B=(e,t)=>{let n=t[w];if(n===void 0)return;if(!p(n))throw Error(`${e}: config.${w} is not a source ({kind, id})`);let{kind:o,id:i}=n;if(o!=="file"&&o!=="program"&&o!=="agent"&&o!=="ci")throw Error(`${e}: config.${w}.kind is not one of file, program, agent, ci`);if(typeof i!=="string"||i==="")throw Error(`${e}: config.${w}.id is empty`);return{kind:o,id:i}},Q=(e)=>{if(!p(e))throw Error("the agents channel answered an entry that is not an object");let t=p(e.record)?e.record:e,n=e.id;if(typeof n!=="string"||n==="")throw Error("the agents channel answered a record that names no id");let o=typeof t.revision==="number"&&Number.isInteger(t.revision)&&t.revision>=0?t.revision:void 0,i=p(t.config)?t.config:{},a=B(n,i);return{id:n,...o===void 0?{}:{revision:o},record:t,...a===void 0?{}:{source:a}}};async function X(e){let t=await e.call("subscribe",{channel:_});await e.call("unsubscribe",{channel:_});let n=t?.snapshot?.state,o=p(n)?n.records:void 0;if(!Array.isArray(o))throw Error("the agents channel answered no records");return o.map(Q)}var I=(e)=>({engine:e.engine,owner:e.owner,name:e.name,...e.description===void 0?{}:{description:e.description},...e.tags===void 0?{}:{tags:e.tags},...e.model===void 0?{}:{model:e.model}}),M=(e)=>Object.fromEntries(Object.entries(e).filter(([t])=>t!==w)),Z=(e,t)=>{let n=I(t),o=z.filter((a)=>h(e.record[a])!==h(n[a])),i=p(e.record.config)?e.record.config:{};if(h(M(i))!==h(M(t.config??{})))o.push("config");return o};async function ee(e,t,n){let o=await X(t),i=new Map(o.map((d)=>[d.id,d])),a=[],f=[],c=[],l=new Set;for(let d of e){if(l.has(d.id))throw Error(`${d.id} is named twice in one plan`);l.add(d.id);let g=i.get(d.id);if(g===void 0)a.push(d);else{let x=Z(g,d);if(x.length===0)c.push(d.id);else if(g.revision===void 0)throw Error(`${d.id} has no revision on this machine; it cannot be edited from here`);else f.push({id:d.id,before:g,after:d,changed:x})}}let s=n.prune===!0?o.filter((d)=>O(d.source,n.source)&&!l.has(d.id)):[];for(let d of s)if(d.revision===void 0)throw Error(`${d.id} has no revision on this machine; it cannot be removed from here`);return{create:a,change:f,unchanged:c,remove:s}}async function b(e,t,n){let o=e.ifVersion??"",i=[],a=[];for(let s of e.hosts?.pending??[]){if(n===void 0)throw Error(`host ${s.name}: host links need a workspace to mint them and this apply has none; nothing was minted`);let d;try{d=await n.mintHostJoin(s.agents)}catch(g){throw Error(`host ${s.name} was not minted: ${g.message}`)}a.push({name:s.name,link:d})}for(let s of e.create)o=(await v(t,"put",{input:{service:s,ifVersion:"absent"}})).ifVersion??o,i.push(s.name);for(let s of e.change)o=(await v(t,"put",{input:{service:s.after,ifVersion:o}})).ifVersion??o,i.push(s.name);let f=[];for(let s of e.keep??[])o=(await v(t,"put",{input:{service:{name:s.name,source:null},ifVersion:o}})).ifVersion??o,f.push(s.name);let c=[];for(let s of e.remove??[]){if(s.state?.status.toLowerCase()==="running")await v(t,"stop",{target:{id:s.name},input:{}});o=(await v(t,"remove",{target:{id:s.name},input:{ifVersion:o}})).ifVersion??o,c.push(s.name)}if(e.agents!==void 0){for(let s of e.agents.create)await D(t,s,0),i.push(`agent:${s.id}`);for(let s of e.agents.change){if(s.before.revision===void 0)throw Error(`${s.id} has no revision on this machine; it cannot be edited from here`);await D(t,s.after,s.before.revision),i.push(`agent:${s.id}`)}for(let s of e.agents.remove){if(s.revision===void 0)throw Error(`${s.id} has no revision on this machine; it cannot be removed from here`);await ne(t,s.id,s.revision),c.push(`agent:${s.id}`)}}let l=e.hosts?.pruneNote===void 0?void 0:a.length===0?"host links are not pruned; this apply minted none, so nothing of its own is outstanding":`host links are not pruned; unconsumed ones expire at ${a.map((s)=>s.link.expiresAt).sort()[0]}`;return{preview:e,written:i,removed:c,kept:f,...e.hosts===void 0?{}:{hostLinks:a},...l===void 0?{}:{hostNote:l}}}var D=(e,t,n)=>e.call("x-ahpd/agents/put",{id:t.id,...I(t),config:{...t.config,[w]:t.source},ifRevision:n}),ne=(e,t,n)=>e.call("x-ahpd/agents/remove",{id:t,ifRevision:n});function T(e){let t=[];for(let n of e.create)t.push(`+ ${n.name}`);for(let n of e.change)t.push(`~ ${n.name} (${n.changed.join(", ")})`);for(let n of e.remove??[]){let o=n.state?.status.toLowerCase()==="running";t.push(`- ${n.name} (${o?"stop, then remove":"remove"}; source ${A(n.source)})`)}for(let n of e.keep??[])t.push(`= ${n.name} (kept: left running here, source cleared)`);for(let n of e.unmanaged??[]){let o=n.source===void 0?"no source":`source ${A(n.source)}`;t.push(`? ${n.name} (not managed by this apply: ${o})`)}for(let n of e.unchanged)t.push(`= ${n}`);for(let n of e.readOnly)t.push(`! ${n.name} read-only: ${n.reason}`);if(e.hosts!==void 0){for(let n of e.hosts.pending){let o=n.agents.length===0?"no agents":`agents ${n.agents.join(",")}`;t.push(`+ host:${n.name} (pending link: the machine must join; ${o})`)}if(e.hosts.pruneNote!==void 0)t.push(`note: ${e.hosts.pruneNote}`)}if(e.agents!==void 0){for(let n of e.agents.create)t.push(`+ agent:${n.id}`);for(let n of e.agents.change)t.push(`~ agent:${n.id} (${n.changed.join(", ")})`);for(let n of e.agents.remove)t.push(`- agent:${n.id} (source ${n.source===void 0?"unknown":A(n.source)})`);for(let n of e.agents.unchanged)t.push(`= agent:${n}`)}return t}
2
+ export{y,r,S,E,k,b,T};
@@ -1,2 +1,2 @@
1
- import w from"ws";async function a(i,s){let u=s.token===void 0?i:`${i}${i.includes("?")?"&":"?"}tkn=${encodeURIComponent(s.token)}`,o=new w(u),d=new Map,t,f=0;o.on("message",(n)=>{let e=JSON.parse(String(n));if(e.id!==void 0&&e.method===void 0)d.get(e.id)?.(e)}),o.on("close",(n,e)=>{t=`${String(n)} ${e.toString()}`;for(let r of d.values())r({error:{code:0,message:`closed: ${t}`}})}),await new Promise((n,e)=>{o.once("open",()=>n()),o.once("error",(r)=>e(r))});let l=(n,e)=>new Promise((r,m)=>{if(t!==void 0)return m(Error(`the machine's connection closed: ${t}`));let g=++f;d.set(g,(c)=>{if(c.error!==void 0)m(Error(c.error.message));else r(c.result)}),o.send(JSON.stringify({jsonrpc:"2.0",id:g,method:n,params:e}))});return await l("initialize",{channel:"ahp-root://",protocolVersions:["1.1.0"],clientId:s.clientId}),{call:l,close:()=>o.close()}}
2
- export{a};
1
+ import w from"ws";async function c(i,s){let u=s.token===void 0?i:`${i}${i.includes("?")?"&":"?"}tkn=${encodeURIComponent(s.token)}`,o=new w(u),d=new Map,t,f=0;o.on("message",(n)=>{let e=JSON.parse(String(n));if(e.id!==void 0&&e.method===void 0)d.get(e.id)?.(e)}),o.on("close",(n,e)=>{t=`${String(n)} ${e.toString()}`;for(let r of d.values())r({error:{code:0,message:`closed: ${t}`}})}),await new Promise((n,e)=>{o.once("open",()=>n()),o.once("error",(r)=>e(r))});let l=(n,e)=>new Promise((r,m)=>{if(t!==void 0)return m(Error(`the machine's connection closed: ${t}`));let g=++f;d.set(g,(a)=>{if(a.error!==void 0)m(Error(a.error.message));else r(a.result)}),o.send(JSON.stringify({jsonrpc:"2.0",id:g,method:n,params:e}))});return await l("initialize",{channel:"ahp-root://",protocolVersions:["1.1.0"],clientId:s.clientId}),{call:l,close:()=>o.close()}}
2
+ export{c};
@@ -1,5 +1,5 @@
1
- import{chmod as j,mkdir as J,readFile as M,rename as V,rm as B,stat as G,writeFile as W}from"node:fs/promises";import{spawn as X}from"node:child_process";import{randomUUID as z}from"node:crypto";import{homedir as Z}from"node:os";import{join as C}from"node:path";function R(r){return r.replace(/\brt_[A-Za-z0-9_-]+/g,"[redacted-refresh-token]").replace(/\bht_session=[^;\s]+/g,"ht_session=[redacted]").replace(/\b[A-Za-z0-9_-]{40,}\b/g,"[redacted-token]")}function x(){return{readFile:(r)=>M(r,"utf8"),stat:(r)=>G(r),writeFile:(r,e,n)=>W(r,e,n),mkdir:async(r,e)=>{await J(r,e)},chmod:(r,e)=>j(r,e),rename:(r,e)=>V(r,e),rm:(r,e)=>B(r,e),env:process.env,home:Z(),nowMs:()=>Date.now(),fetch:(r,e)=>globalThis.fetch(r,e),out:(r)=>{process.stdout.write(`${r}
1
+ import{chmod as j,mkdir as J,readFile as M,rename as V,rm as B,stat as G,writeFile as W}from"node:fs/promises";import{spawn as X}from"node:child_process";import{randomUUID as z}from"node:crypto";import{homedir as Z}from"node:os";import{join as _}from"node:path";function U(r){return r.replace(/\brt_[A-Za-z0-9_-]+/g,"[redacted-refresh-token]").replace(/\bht_session=[^;\s]+/g,"ht_session=[redacted]").replace(/\b[A-Za-z0-9_-]{40,}\b/g,"[redacted-token]")}function C(){return{readFile:(r)=>M(r,"utf8"),stat:(r)=>G(r),writeFile:(r,e,n)=>W(r,e,n),mkdir:async(r,e)=>{await J(r,e)},chmod:(r,e)=>j(r,e),rename:(r,e)=>V(r,e),rm:(r,e)=>B(r,e),env:process.env,home:Z(),nowMs:()=>Date.now(),fetch:(r,e)=>globalThis.fetch(r,e),out:(r)=>{process.stdout.write(`${r}
2
2
  `)},err:(r)=>{process.stderr.write(`${r}
3
- `)},sleep:(r)=>new Promise((e)=>setTimeout(e,r)),openBrowser:async(r)=>{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",r]:[r];try{X(e,n,{stdio:"ignore",detached:!0}).unref()}catch{}}}}function s(r,e){let n;try{n=new URL(r)}catch{return{error:`${e}_ORIGIN_INVALID: --origin must be the https deployment origin, e.g. https://hightea.dev (got ${JSON.stringify(r)}).`}}let t=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]"||n.hostname==="::1";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t)||n.pathname!=="/"||n.search!==""||n.hash!=="")return{error:`${e}_ORIGIN_INVALID: --origin must be the https deployment origin (http is allowed only on localhost), e.g. https://hightea.dev (got ${JSON.stringify(r)}).`};return{origin:n.origin}}function D(r){return r.env.XDG_CONFIG_HOME?.trim()||C(r.home,".config")}function y(r,e){return C(D(e),"hightea","credentials.json")}function l(r){return`run \`hightea auth login --origin ${r}\``}function q(r){return`0${(r&511).toString(8).padStart(3,"0")}`}async function b(r,e,n){let t=`${r}.${process.pid}.${z()}.tmp`;try{await n.writeFile(t,`${JSON.stringify(e,null,2)}
4
- `,{mode:384,flag:"wx"}),await n.chmod(t,384),await n.rename(t,r)}catch(o){try{await n.rm?.(t,{force:!0})}catch{}throw o}}async function Y(r,e){let n,t;try{n=await e.readFile(r),t=(await e.stat(r)).mode}catch(o){if(o.code==="ENOENT")return{error:"AUTH_NOT_SIGNED_IN"};return{error:`AUTH_CREDENTIALS_UNREADABLE: ${r} (${o.message})`}}if((t&63)!==0)return{error:`AUTH_CREDENTIALS_EXPOSED: ${r} is mode ${q(t)}; run chmod 600 ${r}.`};try{let o=JSON.parse(n);if(typeof o!=="object"||o===null||Array.isArray(o))throw SyntaxError("not an object");let i=o;if(i.version!==1||typeof i.origins!=="object"||i.origins===null||Array.isArray(i.origins))throw SyntaxError("not a version 1 credential file");return{file:i}}catch(o){return{error:`AUTH_CREDENTIALS_INVALID: ${r} (${o.message})`}}}function K(r){let e=r;return e!==null&&typeof e==="object"&&typeof e.sessionToken==="string"&&e.sessionToken.length>0&&typeof e.sessionExpiresAt==="string"&&Number.isFinite(Date.parse(e.sessionExpiresAt))&&(e.refreshToken===void 0||typeof e.refreshToken==="string")&&(e.account===void 0||typeof e.account==="object"&&e.account!==null)}async function w(r,e){let n=y(r,e),t=await Y(n,e);if("error"in t){if(t.error==="AUTH_NOT_SIGNED_IN")return{error:`${t.error}: no sign-in for ${r}; ${l(r)}.`};if(t.error.startsWith("AUTH_CREDENTIALS_INVALID"))return{error:`${t.error}; ${l(r)}.`};return{error:t.error}}let o=t.file.origins[r];if(!K(o))return{error:`AUTH_NOT_SIGNED_IN: no sign-in for ${r}; ${l(r)}.`};return{credential:o}}async function O(r,e,n){if(n.writeFile===void 0||n.mkdir===void 0||n.chmod===void 0||n.rename===void 0)return{error:"AUTH_FILESYSTEM_UNAVAILABLE: this command had no filesystem to store the credential."};let t=y(r,n),o=C(D(n),"hightea"),i={};try{let a=JSON.parse(await n.readFile(t));if(typeof a.origins==="object"&&a.origins!==null&&!Array.isArray(a.origins))i=a.origins}catch{}try{await n.mkdir(o,{recursive:!0,mode:448});let a={version:1,origins:{...i,[r]:e}};return await b(t,a,n),{ok:!0}}catch(a){return{error:`AUTH_CREDENTIALS_UNWRITABLE: ${t} (${a.message})`}}}async function Q(r,e){if(e.writeFile===void 0||e.chmod===void 0||e.rename===void 0||e.rm===void 0)return{error:"AUTH_FILESYSTEM_UNAVAILABLE: this command had no filesystem to forget the credential."};let n=y(r,e),t;try{t=JSON.parse(await e.readFile(n))}catch(i){if(i.code==="ENOENT")return{ok:!0};return{error:`AUTH_CREDENTIALS_INVALID: ${n} (${i.message}).`}}let o={...t.origins};delete o[r];try{if(Object.keys(o).length===0)await e.rm(n,{force:!0});else await b(n,{version:1,origins:o},e);return{ok:!0}}catch(i){return{error:`AUTH_CREDENTIALS_UNWRITABLE: ${n} (${i.message})`}}}async function k(r,e,n,t){let o;try{o=await r.fetch(e,{method:"POST",headers:{origin:n,"content-type":"application/json",accept:"application/json","cache-control":"no-store"},body:JSON.stringify(t)})}catch(d){return{error:`AUTH_UNREACHABLE: ${e} did not answer: ${d.message}`}}let i=await o.text(),a={};if(i.length>0)try{let d=JSON.parse(i);if(typeof d!=="object"||d===null||Array.isArray(d))throw SyntaxError("not an object");a=d}catch{return{error:`AUTH_ANSWER_INVALID: ${e} answered HTTP ${o.status} with non-JSON: ${R(i.slice(0,200))}`}}return{status:o.status,answer:a}}function _(r){let e=r.error;return{code:typeof e?.code==="string"?e.code:"HTTP_ERROR",message:R(typeof e?.message==="string"?e.message:"the deployment refused the request")}}function L(r){let{sessionToken:e,sessionExpiresAt:n,refreshToken:t,account:o}=r;if(typeof e!=="string"||e.length===0||typeof n!=="string"||!Number.isFinite(Date.parse(n))||typeof t!=="string"||t.length===0)return null;return{sessionToken:e,sessionExpiresAt:n,refreshToken:t,...o===void 0?{}:{account:o}}}async function H(r,e,n,t=!1){if(e.refreshToken===void 0||e.refreshToken.length===0)return{error:`AUTH_SESSION_EXPIRED: no refresh token for ${r}; ${l(r)}.`};let o=await k(n,`${r}/auth/cli/refresh`,r,{refreshToken:e.refreshToken,sessionToken:e.sessionToken});if("error"in o)return{error:o.error};if(o.status!==200){let d=_(o.answer);if(!t&&(o.status===401||d.code==="REFRESH_INVALID")){let c=await w(r,n);if("credential"in c&&c.credential.refreshToken!==e.refreshToken){if(Date.parse(c.credential.sessionExpiresAt)-(n.nowMs?.()??Date.now())>60000)return c;return await H(r,c.credential,n,!0)}}return{error:`AUTH_${d.code}: ${d.message} ${l(r)}`}}let i=L(o.answer);if(i===null)return{error:"AUTH_ANSWER_INVALID: the refresh answer lacked a session or refresh token."};let a=await O(r,{...i,...e.account===void 0?{}:{account:e.account}},n);if("error"in a)return a;return{credential:i}}async function f(r,e){let n=await w(r,e);if("error"in n)return n;if(Date.parse(n.credential.sessionExpiresAt)-(e.nowMs?.()??Date.now())>60000)return n;return await H(r,n.credential,e)}async function I(r,e=x()){let n=s(r.origin,"AUTH");if("error"in n)return e.err(n.error),1;let t=n.origin,o=await k(e,`${t}/auth/cli/device`,t,{});if("error"in o)return e.err(o.error),1;if(o.status!==200){let u=_(o.answer);return e.err(`AUTH_${u.code}: ${u.message}`),1}let i=o.answer.deviceCode,a=o.answer.userCode,d=o.answer.verificationUri,c=o.answer.verificationUriComplete,h=o.answer.expiresIn,A=o.answer.interval;if(typeof i!=="string"||typeof a!=="string"||typeof d!=="string"||typeof c!=="string"||typeof h!=="number"||typeof A!=="number")return e.err("AUTH_ANSWER_INVALID: the device authorization answer was malformed."),1;let T=r.json?e.err:e.out;if(T(`To sign in to ${t}, open ${d}`),T(`and confirm the code ${a}.`),r.noBrowser!==!0)T(`Opening ${c}`),await e.openBrowser(c);let S=A*1000,P=(e.nowMs?.()??Date.now())+h*1000,F=Math.max(1,Math.ceil(h/A)+1);for(let u=0;u<F;u+=1){if((e.nowMs?.()??Date.now())>=P)break;await e.sleep(S);let g=await k(e,`${t}/auth/cli/token`,t,{deviceCode:i});if("error"in g)return e.err(g.error),1;if(g.status===200){let m=L(g.answer);if(m===null)return e.err("AUTH_ANSWER_INVALID: the sign-in answer lacked a session or refresh token."),1;let U=await O(t,m,e);if("error"in U)return e.err(U.error),1;if(r.json)return e.out(JSON.stringify({origin:t,sessionExpiresAt:m.sessionExpiresAt,account:m.account??null})),0;let E=m.account?.email;return e.out(`Signed in to ${t}${typeof E==="string"&&E.length>0?` as ${E}`:""}.`),e.out(`Credential stored at ${y(t,e)} (mode 0600).`),0}let p=_(g.answer);if(p.code==="AUTHORIZATION_PENDING")continue;if(p.code==="SLOW_DOWN"){S+=5000;continue}return e.err(`AUTH_${p.code}: ${p.message}`),1}return e.err(`AUTH_EXPIRED_TOKEN: the sign-in code expired; ${l(t)}.`),1}async function v(r,e=x()){let n=s(r.origin,"AUTH");if("error"in n)return e.err(n.error),1;let t=await w(n.origin,e);if("error"in t)return e.err(t.error),1;let o=t.credential,i=Date.parse(o.sessionExpiresAt)<=(e.nowMs?.()??Date.now()),a=o.account;if(r.json)return e.out(JSON.stringify({origin:n.origin,account:a??null,sessionExpiresAt:o.sessionExpiresAt,expired:i})),0;let d=a?.email;return e.out(`Signed in to ${n.origin}${typeof d==="string"&&d.length>0?` as ${d}`:""}.`),e.out(`Session ${i?"expired":"expires"} ${o.sessionExpiresAt}${i?`; ${l(n.origin)}.`:"."}`),0}async function N(r,e=x()){let n=s(r.origin,"AUTH");if("error"in n)return e.err(n.error),1;let t=n.origin,o=await w(t,e);if("error"in o){if(o.error.startsWith("AUTH_NOT_SIGNED_IN"))return e.out(`Not signed in to ${t}; nothing to do.`),0;return e.err(o.error),1}let i=!0;try{let d=await e.fetch(`${t}/auth/logout`,{method:"POST",headers:{origin:t,cookie:`ht_session=${o.credential.sessionToken}`,accept:"application/json","cache-control":"no-store"}});i=d.ok||d.status===302}catch{i=!1}if(!i)return e.err(`AUTH_LOGOUT_FAILED: ${t} could not be told to revoke the session; the local credential was kept. Try again.`),1;let a=await Q(t,e);if("error"in a)return e.err(a.error),1;if(r.json)e.out(JSON.stringify({origin:t,signedOut:!0,revoked:i}));else e.out(`Signed out of ${t}.`);return 0}
5
- export{s,f,I,v,N};
3
+ `)},sleep:(r)=>new Promise((e)=>setTimeout(e,r)),openBrowser:async(r)=>{let e=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",r]:[r];try{X(e,n,{stdio:"ignore",detached:!0}).unref()}catch{}}}}function s(r,e){let n;try{n=new URL(r)}catch{return{error:`${e}_ORIGIN_INVALID: --origin must be the https deployment origin, e.g. https://hightea.dev (got ${JSON.stringify(r)}).`}}let t=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]"||n.hostname==="::1";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&t)||n.pathname!=="/"||n.search!==""||n.hash!=="")return{error:`${e}_ORIGIN_INVALID: --origin must be the https deployment origin (http is allowed only on localhost), e.g. https://hightea.dev (got ${JSON.stringify(r)}).`};return{origin:n.origin}}function R(r){return r.env.XDG_CONFIG_HOME?.trim()||_(r.home,".config")}function y(r,e){return _(R(e),"hightea","credentials.json")}function l(r){return`run \`hightea auth login --origin ${r}\``}function q(r){return`0${(r&511).toString(8).padStart(3,"0")}`}async function D(r,e,n){let t=`${r}.${process.pid}.${z()}.tmp`;try{await n.writeFile(t,`${JSON.stringify(e,null,2)}
4
+ `,{mode:384,flag:"wx"}),await n.chmod(t,384),await n.rename(t,r)}catch(o){try{await n.rm?.(t,{force:!0})}catch{}throw o}}async function Y(r,e){let n,t;try{n=await e.readFile(r),t=(await e.stat(r)).mode}catch(o){if(o.code==="ENOENT")return{error:"AUTH_NOT_SIGNED_IN"};return{error:`AUTH_CREDENTIALS_UNREADABLE: ${r} (${o.message})`}}if((t&63)!==0)return{error:`AUTH_CREDENTIALS_EXPOSED: ${r} is mode ${q(t)}; run chmod 600 ${r}.`};try{let o=JSON.parse(n);if(typeof o!=="object"||o===null||Array.isArray(o))throw SyntaxError("not an object");let i=o;if(i.version!==1||typeof i.origins!=="object"||i.origins===null||Array.isArray(i.origins))throw SyntaxError("not a version 1 credential file");return{file:i}}catch(o){return{error:`AUTH_CREDENTIALS_INVALID: ${r} (${o.message})`}}}function K(r){let e=r;return e!==null&&typeof e==="object"&&typeof e.sessionToken==="string"&&e.sessionToken.length>0&&typeof e.sessionExpiresAt==="string"&&Number.isFinite(Date.parse(e.sessionExpiresAt))&&(e.refreshToken===void 0||typeof e.refreshToken==="string")&&(e.account===void 0||typeof e.account==="object"&&e.account!==null)}async function w(r,e){let n=y(r,e),t=await Y(n,e);if("error"in t){if(t.error==="AUTH_NOT_SIGNED_IN")return{error:`${t.error}: no sign-in for ${r}; ${l(r)}.`};if(t.error.startsWith("AUTH_CREDENTIALS_INVALID"))return{error:`${t.error}; ${l(r)}.`};return{error:t.error}}let o=t.file.origins[r];if(!K(o))return{error:`AUTH_NOT_SIGNED_IN: no sign-in for ${r}; ${l(r)}.`};return{credential:o}}async function b(r,e,n){if(n.writeFile===void 0||n.mkdir===void 0||n.chmod===void 0||n.rename===void 0)return{error:"AUTH_FILESYSTEM_UNAVAILABLE: this command had no filesystem to store the credential."};let t=y(r,n),o=_(R(n),"hightea"),i={};try{let a=JSON.parse(await n.readFile(t));if(typeof a.origins==="object"&&a.origins!==null&&!Array.isArray(a.origins))i=a.origins}catch{}try{await n.mkdir(o,{recursive:!0,mode:448});let a={version:1,origins:{...i,[r]:e}};return await D(t,a,n),{ok:!0}}catch(a){return{error:`AUTH_CREDENTIALS_UNWRITABLE: ${t} (${a.message})`}}}async function Q(r,e){if(e.writeFile===void 0||e.chmod===void 0||e.rename===void 0||e.rm===void 0)return{error:"AUTH_FILESYSTEM_UNAVAILABLE: this command had no filesystem to forget the credential."};let n=y(r,e),t;try{t=JSON.parse(await e.readFile(n))}catch(i){if(i.code==="ENOENT")return{ok:!0};return{error:`AUTH_CREDENTIALS_INVALID: ${n} (${i.message}).`}}let o={...t.origins};delete o[r];try{if(Object.keys(o).length===0)await e.rm(n,{force:!0});else await D(n,{version:1,origins:o},e);return{ok:!0}}catch(i){return{error:`AUTH_CREDENTIALS_UNWRITABLE: ${n} (${i.message})`}}}async function k(r,e,n,t){let o;try{o=await r.fetch(e,{method:"POST",headers:{origin:n,"content-type":"application/json",accept:"application/json","cache-control":"no-store"},body:JSON.stringify(t)})}catch(d){return{error:`AUTH_UNREACHABLE: ${e} did not answer: ${d.message}`}}let i=await o.text(),a={};if(i.length>0)try{let d=JSON.parse(i);if(typeof d!=="object"||d===null||Array.isArray(d))throw SyntaxError("not an object");a=d}catch{return{error:`AUTH_ANSWER_INVALID: ${e} answered HTTP ${o.status} with non-JSON: ${U(i.slice(0,200))}`}}return{status:o.status,answer:a}}function N(r){let e=r.error;return{code:typeof e?.code==="string"?e.code:"HTTP_ERROR",message:U(typeof e?.message==="string"?e.message:"the deployment refused the request")}}function L(r){let{sessionToken:e,sessionExpiresAt:n,refreshToken:t,account:o}=r;if(typeof e!=="string"||e.length===0||typeof n!=="string"||!Number.isFinite(Date.parse(n))||typeof t!=="string"||t.length===0)return null;return{sessionToken:e,sessionExpiresAt:n,refreshToken:t,...o===void 0?{}:{account:o}}}async function H(r,e,n,t=!1){if(e.refreshToken===void 0||e.refreshToken.length===0)return{error:`AUTH_SESSION_EXPIRED: no refresh token for ${r}; ${l(r)}.`};let o=await k(n,`${r}/auth/cli/refresh`,r,{refreshToken:e.refreshToken,sessionToken:e.sessionToken});if("error"in o)return{error:o.error};if(o.status!==200){let d=N(o.answer);if(!t&&(o.status===401||d.code==="REFRESH_INVALID")){let c=await w(r,n);if("credential"in c&&c.credential.refreshToken!==e.refreshToken){if(Date.parse(c.credential.sessionExpiresAt)-(n.nowMs?.()??Date.now())>60000)return c;return await H(r,c.credential,n,!0)}}return{error:`AUTH_${d.code}: ${d.message} ${l(r)}`}}let i=L(o.answer);if(i===null)return{error:"AUTH_ANSWER_INVALID: the refresh answer lacked a session or refresh token."};let a=await b(r,{...i,...e.account===void 0?{}:{account:e.account}},n);if("error"in a)return a;return{credential:i}}async function f(r,e){let n=await w(r,e);if("error"in n)return n;if(Date.parse(n.credential.sessionExpiresAt)-(e.nowMs?.()??Date.now())>60000)return n;return await H(r,n.credential,e)}async function I(r,e=C()){let n=s(r.origin,"AUTH");if("error"in n)return e.err(n.error),1;let t=n.origin,o=await k(e,`${t}/auth/cli/device`,t,{});if("error"in o)return e.err(o.error),1;if(o.status!==200){let u=N(o.answer);return e.err(`AUTH_${u.code}: ${u.message}`),1}let i=o.answer.deviceCode,a=o.answer.userCode,d=o.answer.verificationUri,c=o.answer.verificationUriComplete,h=o.answer.expiresIn,A=o.answer.interval;if(typeof i!=="string"||typeof a!=="string"||typeof d!=="string"||typeof c!=="string"||typeof h!=="number"||typeof A!=="number")return e.err("AUTH_ANSWER_INVALID: the device authorization answer was malformed."),1;let T=r.json?e.err:e.out;if(T(`To sign in to ${t}, open ${d}`),T(`and confirm the code ${a}.`),r.noBrowser!==!0)T(`Opening ${c}`),await e.openBrowser(c);let x=A*1000,P=(e.nowMs?.()??Date.now())+h*1000,F=Math.max(1,Math.ceil(h/A)+1);for(let u=0;u<F;u+=1){if((e.nowMs?.()??Date.now())>=P)break;await e.sleep(x);let g=await k(e,`${t}/auth/cli/token`,t,{deviceCode:i});if("error"in g)return e.err(g.error),1;if(g.status===200){let m=L(g.answer);if(m===null)return e.err("AUTH_ANSWER_INVALID: the sign-in answer lacked a session or refresh token."),1;let S=await b(t,m,e);if("error"in S)return e.err(S.error),1;if(r.json)return e.out(JSON.stringify({origin:t,sessionExpiresAt:m.sessionExpiresAt,account:m.account??null})),0;let E=m.account?.email;return e.out(`Signed in to ${t}${typeof E==="string"&&E.length>0?` as ${E}`:""}.`),e.out(`Credential stored at ${y(t,e)} (mode 0600).`),0}let p=N(g.answer);if(p.code==="AUTHORIZATION_PENDING")continue;if(p.code==="SLOW_DOWN"){x+=5000;continue}return e.err(`AUTH_${p.code}: ${p.message}`),1}return e.err(`AUTH_EXPIRED_TOKEN: the sign-in code expired; ${l(t)}.`),1}async function v(r,e=C()){let n=s(r.origin,"AUTH");if("error"in n)return e.err(n.error),1;let t=await w(n.origin,e);if("error"in t)return e.err(t.error),1;let o=t.credential,i=Date.parse(o.sessionExpiresAt)<=(e.nowMs?.()??Date.now()),a=o.account;if(r.json)return e.out(JSON.stringify({origin:n.origin,account:a??null,sessionExpiresAt:o.sessionExpiresAt,expired:i})),0;let d=a?.email;return e.out(`Signed in to ${n.origin}${typeof d==="string"&&d.length>0?` as ${d}`:""}.`),e.out(`Session ${i?"expired":"expires"} ${o.sessionExpiresAt}${i?`; ${l(n.origin)}.`:"."}`),0}async function O(r,e=C()){let n=s(r.origin,"AUTH");if("error"in n)return e.err(n.error),1;let t=n.origin,o=await w(t,e);if("error"in o){if(o.error.startsWith("AUTH_NOT_SIGNED_IN"))return e.out(`Not signed in to ${t}; nothing to do.`),0;return e.err(o.error),1}let i=!0;try{let d=await e.fetch(`${t}/auth/logout`,{method:"POST",headers:{origin:t,cookie:`ht_session=${o.credential.sessionToken}`,accept:"application/json","cache-control":"no-store"}});i=d.ok||d.status===302}catch{i=!1}if(!i)return e.err(`AUTH_LOGOUT_FAILED: ${t} could not be told to revoke the session; the local credential was kept. Try again.`),1;let a=await Q(t,e);if("error"in a)return e.err(a.error),1;if(r.json)e.out(JSON.stringify({origin:t,signedOut:!0,revoked:i}));else e.out(`Signed out of ${t}.`);return 0}
5
+ export{s,f,I,v,O};
@@ -0,0 +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}
5
+ export{m,o,g,N,R,n,i,x,C};
@@ -1 +1 @@
1
- import{L,u,p,w,D,P}from"./chunk-ah99zytf.js";export{L as agentAppsOnPath,w as appInstalled,p as describedApp,u as installLineOf,D as isShippedApp,P as noAgentAppsLine};
1
+ import{L,u,p,w,D,P}from"./chunk-tay0pyz4.js";export{L as agentAppsOnPath,w as appInstalled,p as describedApp,u as installLineOf,D as isShippedApp,P as noAgentAppsLine};
@@ -1 +1 @@
1
- import"./chunk-ah99zytf.js";import{o,n}from"./chunk-c7atktnb.js";import{h}from"./chunk-nfmmht3j.js";import{r}from"./chunk-v221hgba.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-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};
@@ -0,0 +1,13 @@
1
+ import"./chunk-kjkww5cr.js";import{t,e}from"./chunk-vzkbknwq.js";import{existsSync as M,mkdirSync as C,readFileSync as x}from"node:fs";import{userInfo as B}from"node:os";import{dirname as D,isAbsolute as P,join as L,resolve as q}from"node:path";var T=`hightea service list (--host HOST --origin URL --workspace SLUG | --local [--host HOST] [--config-dir DIR]) [--json]
2
+ `+`hightea service add|change NAME [--command CMD] [--cwd DIR] [--patch JSON] (--host … | --local [--host HOST] [--config-dir DIR])
3
+ `+`hightea service remove|start|stop|restart NAME (--host … | --local [--host HOST] [--config-dir DIR])
4
+ `+`hightea service logs NAME [--limit N] [--end N] (--host … | --local [--host HOST] [--config-dir DIR])
5
+ `+`hightea service acknowledge (--host … | --local [--host HOST] [--config-dir DIR])
6
+ `+`hightea service backup --host HOST --origin URL --workspace SLUG [--json]
7
+ hightea service restore [NAME...] --from OLD_HOST (--host NEW_HOST | --local [--host HOST] [--config-dir DIR]) --origin URL --workspace SLUG [--yes] [--json]
8
+ hightea service enable|disable [--host HOST] (run on the machine)`,_=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n)&&typeof n.ok==="boolean"?n:void 0;function U(n,o){let r=encodeURIComponent((n.host??"").trim()),l=async(c,i,s,f)=>{let u=await e(n,o,{method:c,path:`/hosts/${r}/services${i}`,what:s,label:"SERVICE",...f===void 0?{}:{body:f}});if("error"in u){let m=_(u.body?.answer);return m===void 0?u:{answer:m}}let h=_(u.answer.answer);return h===void 0?{exit:1,error:`SERVICE_ANSWER_INVALID: ${s} answered without the host's answer: ${JSON.stringify(u.answer).slice(0,300)}`}:{answer:h}},a=(c)=>`/${encodeURIComponent(c)}`;return{machine:(n.host??"").trim(),list:()=>l("GET","","list"),put:(c)=>l("PUT",a(String(c.service.name)),"put",c),remove:(c)=>l("DELETE",a(c.name),"remove",{ifVersion:c.ifVersion}),control:(c,i)=>l("POST",`${a(c)}/${i}`,i),logs:(c)=>{let i=new URLSearchParams;if(c.end!==void 0)i.set("end",String(c.end));if(c.limit!==void 0)i.set("limit",String(c.limit));let s=i.size===0?"":`?${i}`;return l("GET",`${a(c.name)}/logs${s}`,"logs")},acknowledge:(c)=>l("POST","/acknowledge","acknowledge",c)}}var W=/(^|[\\/])(@ahpd[\\/]deploy|packages[\\/]deploy|(services|deploy)[\\/]plugin)([\\/]|$)/u;function V(n){if(!P(n)||!n.endsWith("/plugin.json"))return;try{let o=JSON.parse(x(n,"utf8"));return typeof o?.id==="string"?o.id:void 0}catch{return}}async function X(n,o=B().username){let r=L(n,"config.json"),l;try{l=JSON.parse(x(r,"utf8"))}catch{return}let a=l?.plugins,c=(Array.isArray(a)?a:[]).filter((g)=>g!==null&&typeof g==="object"&&typeof g.source==="string"),i=c.filter((g)=>V(g.source)==="services"),s=c.filter((g)=>{if(V(g.source)!=="deploy"&&!W.test(g.source))return!1;let y=g.options;return y!==null&&typeof y==="object"&&(("files"in y)||("socket"in y))}),f=i.length>0?i:s;if(f.length===0)return;if(f.length>1)return`${r} has ${f.length} services plugin entries; keep one`;let{acknowledge:u,acknowledgeFiles:h,changesAt:m,controlService:v,listServices:w,machineOf:S,putService:d,removeService:k,serviceLogs:I}=await import("@hallohuman/hightea-services"),O=f[0].options,A=S(n,O!==null&&typeof O==="object"?O:{});if(typeof A==="string")return A;let{machine:p,stateFile:E}=A;try{C(D(E),{recursive:!0,mode:448}),C(D(p.changeLog),{recursive:!0,mode:448})}catch(g){return`cannot make the services directory for ${p.changeLog}: ${g.message}`}let R={principal:`local:${o}`,remote:!1},N=(g)=>{let y=g;if(y.ok&&(!("changed"in y)||y.changed===!0)&&typeof y.file==="string"&&typeof y.ifVersion==="string")u(E,y.file,y.ifVersion);return g};return{machine:p,caller:R,list:()=>w(p),put:async(g)=>N(await d(p,R,g)),remove:async(g)=>N(await k(p,R,g)),control:(g,y)=>v(p,R,{name:g,verb:y}),logs:(g)=>I(p,R,g),acknowledge:(g)=>h(p,R,g,(y,F)=>u(E,y,F)),changes:(g={},y)=>m(p,g,y)}}async function H(n,o={}){let r;if(n.configDir!==void 0&&n.configDir.trim()!==""){if(!P(n.configDir))return{error:`SERVICE_CONFIG_DIR_INVALID: --config-dir needs an absolute path; ${JSON.stringify(n.configDir)} is not one`};let s=q(n.configDir);if(!M(L(s,"config.json")))return{error:`SERVICE_CONFIG_DIR_INVALID: ${s} holds no config.json; name the directory holding this host's ahpd configuration (in a hab-managed host that is its xdg-config/ahpd)`};r=s}else{let{localHost:s,runningAhpds:f}=await import("./chunk-axj8ef03.js"),h=await(o.localHost??((m)=>s(m,{runningAhpds:o.runningAhpds??f})))(n.host);if("error"in h)return h;r=h.configDir}let{localServices:l,LOG_LINES_MAX:a}=await import("@hallohuman/hightea-services"),c=l(r);if(typeof c==="string"&&c.includes("has no services plugin entry")){let s=await X(r);if(s!==void 0)c=s}if(typeof c==="string")return{error:`SERVICE_NOT_CONFIGURED: ${c}`};let i=(s)=>({answer:s});return{machine:c.machine.name,list:async()=>i(c.list()),put:async(s)=>i(await c.put(s)),remove:async(s)=>i(await c.remove(s)),control:async(s,f)=>i(await c.control(s,f)),logs:async(s)=>i(await c.logs({name:s.name,endOffset:s.end??0,limit:Math.min(s.limit??100,a)})),acknowledge:async(s)=>i(await c.acknowledge(s))}}async function oe(n,o,r=t(),l={}){let a=!n.local;if(a&&((n.host??"").trim()===""||n.workspace.trim()===""))return r.err(`SERVICE_INPUT: name the host with --host and --workspace, or act on this machine with --local.
9
+ ${T}`),1;let c=o.command!=="list"&&o.command!=="acknowledge",i=o.name?.trim()??"";if(c&&i==="")return r.err(`SERVICE_INPUT: ${o.command} names one service.
10
+ ${T}`),1;let s=a?U(n,r):await(l.local??H)(n);if("error"in s)return r.err(s.error),1;let f=(u,h)=>{if("error"in u)return r.err(u.error),u.exit;let m=u.answer;if(!m.ok){if(r.err(`${String(m.code??"SERVICE_REFUSED")}: ${String(m.message??"the machine refused")}`),typeof m.diff==="string"&&m.diff!=="")r.err(m.diff);if(n.json)r.out(JSON.stringify(m));return 1}if(n.json)r.out(JSON.stringify(m));else h(m);return 0};switch(o.command){case"list":return f(await s.list(),(u)=>r.out(G(u,s.machine)));case"start":case"stop":case"restart":return f(await s.control(i,o.command),()=>r.out(`${o.command}: ${i} on ${s.machine}`));case"logs":{let u=j(o.end,0),h=j(o.limit,1);if(u===null||h===null)return r.err("SERVICE_INPUT: --end and --limit are whole numbers of lines; --limit is at least 1"),1;let m=await s.logs({name:i,...u===void 0?{}:{end:u},...h===void 0?{}:{limit:h}});return f(m,(v)=>{r.out(`raw output from ${i} on ${s.machine}:`);for(let w of Array.isArray(v.lines)?v.lines:[])r.out(String(w))})}case"acknowledge":case"add":case"change":case"remove":{let u=await s.list();if("error"in u)return r.err(u.error),u.exit;if(!u.answer.ok)return f(u,()=>{});let h=String(u.answer.ifVersion??""),v=(Array.isArray(u.answer.services)?u.answer.services:[]).some((d)=>d.name===i);if(o.command==="acknowledge"){let d=u.answer.hashes??{};return f(await s.acknowledge({hashes:d}),()=>r.out(`acknowledged ${Object.keys(d).join(", ")||"no files"} on ${s.machine} as they are now`))}if(o.command==="remove")return f(await s.remove({name:i,ifVersion:h}),()=>r.out(`removed ${i} on ${s.machine}`));if(o.command==="add"&&v)return r.err(`SERVICE_EXISTS: ${i} is already a service on ${s.machine}; use \`hightea service change\``),1;if(o.command==="change"&&!v)return r.err(`SERVICE_NOT_FOUND: ${i} is not a service on ${s.machine}; use \`hightea service add\``),1;let w=z(i,o.fields??{});if(typeof w==="string")return r.err(`SERVICE_INPUT: ${w}`),1;let S=K(u.answer.capabilities,w,s.machine);if(S!==void 0)return r.err(`SERVICE_UNSUPPORTED: ${S} Nothing was sent.`),1;if(o.command==="add"&&w.command===void 0)return r.err("SERVICE_INPUT: a new service needs --command"),1;return f(await s.put({service:w,ifVersion:h}),(d)=>r.out(d.changed===!1?`${i} on ${s.machine} already reads so; nothing was written`:`${o.command==="add"?"added":"changed"} ${i} on ${s.machine}`))}}}function z(n,o){let r={};if(o.patch!==void 0){try{r=JSON.parse(o.patch)}catch{return"--patch is a JSON object of service fields"}if(typeof r!=="object"||r===null||Array.isArray(r))return"--patch is a JSON object of service fields";if(r.name!==void 0&&r.name!==n)return"--patch names another service"}return{...r,name:n,...o.command===void 0?{}:{command:o.command},...o.cwd===void 0?{}:{cwd:o.cwd}}}function K(n,o,r){if(typeof n!=="object"||n===null)return;let{fields:l,schedule:a}=n;if(Array.isArray(l)){let i=Object.keys(o).filter((s)=>!l.includes(s));if(i.length>0)return`${r}'s driver does not take ${i.join(", ")}; it takes ${l.join(", ")}.`}let c=o.schedule;if(Array.isArray(a)&&typeof c==="object"&&c!==null){let s=Object.keys(c).filter((f)=>f==="cron"||f==="interval").filter((f)=>!a.includes(f));if(s.length>0)return`${r}'s driver does not take ${s.map((f)=>`schedule.${f}`).join(", ")}; it takes ${a.map((f)=>`schedule.${String(f)}`).join(", ")}.`}return}function j(n,o){if(n===void 0)return;return/^\d{1,7}$/u.test(n.trim())&&Number(n)>=o?Number(n):null}function G(n,o){let r=Array.isArray(n.services)?n.services:[],l=Array.isArray(n.readOnly)?n.readOnly:[],a=r.map((i)=>{let s=Array.isArray(i.plainEnv)&&i.plainEnv.length>0?` (plain env: ${i.plainEnv.join("; ")})`:"";return`${String(i.name)} ${String(i.command??"")}${s}`});for(let i of l)a.push(`${String(i.name)} read-only: ${String(i.reason)}`);if(a.length===0)a.push(`no services on ${o} (${String(n.file??"its file")})`);let c=Y(n);if(c.length>0){a.push(`drift on ${o} (${c.length}), shown only; nothing was repaired:`);for(let i of c)a.push(` ${i.level}: ${i.text}`)}return a.join(`
11
+ `)}function Y(n){let o=(l)=>(Array.isArray(l)?l:[]).filter((a)=>b(a)&&typeof a.text==="string").map((a)=>({level:typeof a.level==="string"?a.level:"warning",text:String(a.text)})),r=Array.isArray(n.rows)?n.rows:[];return[...o(n.alerts),...r.flatMap((l)=>b(l)?o(l.alerts):[])]}var b=(n)=>typeof n==="object"&&n!==null&&!Array.isArray(n);async function J(n,o,r){let l=await e(n,o,{method:"GET",path:`/hosts/${encodeURIComponent(r)}/services/backup`,what:"backup",label:"SERVICE"});if("error"in l)return l;let a=l.answer.backup;if(!b(a)||typeof a.label!=="string"||!b(a.listing)||!Array.isArray(a.lines))return{exit:1,error:`SERVICE_ANSWER_INVALID: backup answered without a backup: ${JSON.stringify(l.answer).slice(0,300)}`};return{backup:a}}function Q(n){if(n.unreadable===!0)return`unreadable line at ${String(n.offset)} (${String(n.bytes)} bytes)`;if(n.boundary===!0)return`--- ${String(n.message)} ---`;let o=b(n.refused)?` refused ${String(n.refused.code)}`:"",r=typeof n.name==="string"&&n.name!==""?` ${n.name}`:"";return`${String(n.at??"")} ${String(n.principal??"")} ${String(n.op??"")}${r}${o}`}async function se(n,o=t()){let r=(n.host??"").trim();if(r===""||n.workspace.trim()===""||n.local)return o.err(`SERVICE_INPUT: name the host with --host and --workspace; a backup is read from Hightea, never --local.
12
+ ${T}`),1;let l=await J(n,o,r);if("error"in l)return o.err(l.error),l.exit;let{backup:a}=l;if(n.json)return o.out(JSON.stringify(a)),0;let c=a.hostStatus==="revoked"?`revoked ${a.revokedAt??""}`.trim():a.connected?"connected":"offline";if(o.out(`${r} (${c}): ${a.label}`),typeof a.reason==="string")o.out(`last pull: ${a.reason}`);o.out(G({ok:!0,...a.listing},r)),o.out(a.lines.length===0?"no changes backed up":`changes, oldest first (${a.lines.length}):`);for(let{line:i}of a.lines)o.out(` ${Q(i)}`);return 0}function Z(){return{...t(),confirm:async(n)=>{let{createInterface:o}=await import("node:readline/promises"),r=o({input:process.stdin,output:process.stderr});try{return/^y(es)?$/iu.test((await r.question(n)).trim())}finally{r.close()}}}}async function ie(n,o,r=Z(),l={}){let a=o.from.trim(),c=(n.host??"").trim();if(a===""||n.workspace.trim()===""||!n.local&&c==="")return r.err(`SERVICE_INPUT: restore names the old host with --from, the workspace with --workspace, and the new host with --host or --local.
13
+ ${T}`),1;let i=await J(n,r,a);if("error"in i)return r.err(i.error),i.exit;let{backup:s}=i,f=Array.isArray(s.listing.services)?s.listing.services.filter(b):[],u=o.names.filter((d)=>!f.some((k)=>k.name===d));if(u.length>0)return r.err(`SERVICE_NOT_IN_BACKUP: ${u.join(", ")} ${u.length===1?"is":"are"} not in ${a}'s backup (${s.label}); it holds ${f.map((d)=>String(d.name)).join(", ")||"no services"}`),1;let h=o.names.length===0?f:f.filter((d)=>o.names.includes(String(d.name)));if(h.length===0)return r.err(`SERVICE_NOTHING_TO_RESTORE: ${a}'s backup (${s.label}) holds no services`),1;let m=n.local?await(l.local??H)(n):U(n,r);if("error"in m)return r.err(m.error),1;let v=(d)=>b(d.env)?Object.entries(d.env).map(([k,I])=>`${k} (${String(b(I)?I.$secret:I)})`):[],w=(d)=>Array.isArray(d.plainEnv)?d.plainEnv.map(String):[];r.err(`restore from ${a} (${s.label}) to ${m.machine}, create only:`);for(let d of h){r.err(` ${String(d.name)} ${String(d.command??"")}`);let k=v(d);if(k.length>0)r.err(` secrets to enter again on ${m.machine}: ${k.join(", ")}`)}if(!o.yes&&!await r.confirm(`create ${h.length} service${h.length===1?"":"s"} on ${m.machine}? [y/N] `))return r.err("SERVICE_RESTORE_DECLINED: nothing was sent"),1;let S=[];for(let d of h){let{plainEnv:k,...I}=d,O=String(d.name),A=v(d),p=w(d),E=await m.put({service:I,ifVersion:"absent"});if("error"in E){let[R="SERVICE_FAILED",...N]=E.error.split(": ");S.push({name:O,outcome:"failed",code:R,message:N.join(": "),secrets:A,plainEnv:p})}else if(!E.answer.ok)S.push({name:O,outcome:"refused",code:String(E.answer.code??"SERVICE_REFUSED"),message:String(E.answer.message??""),secrets:A,plainEnv:p});else S.push({name:O,outcome:"created",secrets:A,plainEnv:p})}if(n.json)r.out(JSON.stringify({from:a,to:m.machine,label:s.label,results:S}));else for(let d of S){if(r.out(d.outcome==="created"?`created ${d.name}`:`${d.outcome} ${d.name}: ${d.code}: ${d.message}`),d.outcome==="created"&&d.secrets.length>0)r.out(` secrets to enter again: ${d.secrets.join(", ")}`);if(d.outcome==="created"&&d.plainEnv.length>0)r.out(` plain values never backed up: ${d.plainEnv.join("; ")}`)}return S.every((d)=>d.outcome==="created")?0:1}export{se as serviceBackupCommand,oe as serviceCommand,ie as serviceRestore};