@north-light/cli 0.3.783 → 0.3.785
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin-pi-packages/pi-crtr-extensions/README.md +3 -3
- package/dist/clients/attach/viewer.js +526 -526
- package/dist/commands/pkg/account-installs.d.ts +1 -0
- package/dist/commands/pkg/account-installs.js +1 -1
- package/dist/commands/pkg/plugin-manage.d.ts +4 -0
- package/dist/commands/pkg/plugin-manage.js +1 -1
- package/dist/commands/sys/doctor.js +1 -1
- package/dist/commands/sys/provider-login.js +5 -5
- package/dist/commands/sys/setup-core.js +6 -6
- package/dist/commands/sys/setup-wizard.js +3 -2
- package/dist/commands/sys/signin.js +5 -4
- package/dist/core/grants/shadow.js +1 -1
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/runtime/package-health.d.ts +1 -1
- package/dist/core/runtime/package-health.js +5 -4
- package/dist/core/runtime/provider-credential-gate.d.ts +1 -1
- package/dist/core/runtime/provider-credential-gate.js +1 -1
- package/dist/core/runtime/runner/machine/executor.d.ts +3 -0
- package/dist/core/runtime/runner/machine/executor.js +2 -1
- package/dist/core/scoped-state/seed-terminal-defaults.js +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/machine-daemon.js +1 -1
- package/docs/cli/first-session.md +2 -2
- package/docs/cli/official-marketplace.md +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/core/profiles/manifest.js +8 -4
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=Object.defineProperty;var a=(e,n)=>q(e,"name",{value:n,configurable:!0});import{randomUUID as H}from"node:crypto";import{realpathSync as W,rmSync as S}from"node:fs";import{isAbsolute as Z,resolve as G}from"node:path";import{resolveExistingProjectDir as V}from"./project-dir.js";import{SCHEMA_VERSION as M}from"../../types.js";import{profileSpace as P}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as k}from"../../api/dto/profiles.js";import{ensureDir as Y,nowIso as y}from"../fs-utils.js";import{cachedPausedProfileIds as B,cachedProfilePaused as Q,getCachedProfile as m,listCachedProfiles as X,writeSettings as w}from"../scoped-state/person-store.js";import{usage as l,notFound as p,ambiguous as C,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as j,personId as te}from"../canvas/person-state.js";import{readMachineConfig as ne}from"../../daemon/machine-link/config.js";const $=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,v="root-00000000",g="root";function d(e){return e.grantee??"app:terminal"}a(d,"profileApp");function x(e,n){Y(P(d(n),e).dir)}a(x,"scaffoldProfile");function _(e){if(!$.test(e))throw l(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}a(_,"assertSafeProfileId");function Ae(e){_(e);const n=m(e);if(n===null)throw p(`profile not found: ${e}`,{received:e});return P(d(n.manifest),e).dir}a(Ae,"profileDir");function b(e){if(!Array.isArray(e))throw l("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const n of e){if(typeof n!="object"||n===null||Array.isArray(n))throw l(`invalid project entry: ${JSON.stringify(n)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:t,repo:r}=n;for(const[i,o]of[["path",t],["repo",r]])if(o!==void 0&&(typeof o!="string"||o.trim()===""))throw l(`project entry has an invalid ${i}: ${JSON.stringify(n)}`,{field:"projects",next:`Give ${i} a non-empty string, or leave it out.`});if(t===void 0&&r===void 0)throw l(`project entry has neither path nor repo: ${JSON.stringify(n)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(b,"assertProfileProjects");function re(e){const n=k.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw l("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${n}.`});for(const[t,r]of Object.entries(e)){if(t.trim()==="")throw l("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof r!="string"||!k.includes(r))throw l(`invalid delivery limit for ${t}: ${JSON.stringify(r)}`,{received:String(r),field:"delivery_limits",next:`Set ${t} to one of: ${n}.`})}}a(re,"assertDeliveryLimits");function ie(){return{entries:X(),unreadableIds:[]}}a(ie,"enumerateProfiles");function h(){return ie().entries}a(h,"listProfiles");function oe(e){const n=h(),t=D(n,e,A);return t?{kind:"resolved",entry:t}:{kind:"absent"}}a(oe,"lookupProfile");function N(e){_(e);const n=m(e);if(n!==null)return n;throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(N,"loadExactProfileManifest");const A=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function D(e,n,t){if($.test(n)){const i=e.find(o=>t(o).profileId===n);if(i!==void 0)return i}const r=e.filter(i=>t(i).name===n);if(r.length===1)return r[0];if(r.length>1){const i=r.map(o=>t(o).profileId);throw C(`profile name "${n}" matches ${i.length} profiles: ${i.join(", ")}`,{received:n,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}a(D,"findExactProfile");function L(e,n,t){const r=e.map(i=>`${t(i).profileId} (${t(i).name})`);return p(`profile not found: ${n}`,{received:n,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(L,"profileNotFound");function ae(e){const n=oe(e);if(n.kind==="resolved")return n.entry;throw L(h(),e,A)}a(ae,"loadProfileManifest");function Ee(e){return se(h(),e,A)}a(Ee,"resolveProfileOperand");function se(e,n,t){const r=D(e,n,t);if(r!==null)return r;const{match:i,tied:o}=ee(n,e.map(t));if(i!==null){const s=e.find(f=>t(f).profileId===i.profileId);return console.error(`crtr: no profile named "${n}" \u2014 using the closest match: ${t(s).name} (${t(s).profileId})`),s}if(o.length>1){const s=o.map(f=>`${f.profileId} (${f.name})`);throw C(`"${n}" is equally close to ${o.length} profiles: ${s.join(", ")}`,{received:n,candidates:o.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw L(e,n,t)}a(se,"matchProfileOperand");function z(e){if(!j())return V(e);if(!Z(e))throw l(`project directory must be an absolute path: ${e}`,{received:e});return e}a(z,"storedProjectDir");function E(e){const n=new Set,t=new Map,r=[];for(const i of e)if(i.path!==void 0){if(n.has(i.path))continue;n.add(i.path);const o=i.repo===void 0?void 0:t.get(i.repo);if(o!==void 0&&r[o].path===void 0){r[o]={...r[o],path:i.path};continue}r.push(i)}else if(i.repo!==void 0){if(t.has(i.repo))continue;t.set(i.repo,r.length),r.push(i)}else r.push(i);return r}a(E,"dedupeProjects");function fe(e){let n=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return n.length>40&&(n=n.slice(0,40).replace(/-+$/g,"")),n.length>0?n:"profile"}a(fe,"slugify");function le(e){const n=fe(e);for(let t=0;t<20;t++){const r=H().replace(/-/g,"").slice(0,8),i=`${n}-${r}`;if(m(i)===null)return i}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(le,"generateProfileId");let O=null;function Oe(e){O=e}a(Oe,"setCloudProfileWriter");async function Re(){if(j()){const t=h().find(r=>r.manifest.name===g&&d(r.manifest)==="app:terminal");return t!==void 0?(x(t.profileId,t.manifest),t):await F(g,[],{grantee:"app:terminal"})}const e=m(v)??h().find(t=>t.manifest.name===g&&d(t.manifest)==="app:terminal")??null;if(e!==null)return x(e.profileId,e.manifest),e;const n={schema_version:M,name:g,projects:[],grantee:"app:terminal",paused_at:null,created_at:y(),last_used_at:y()};return x(v,n),await w(t=>t.profiles.some(r=>r.profileId===v)?[]:[{op:"profile.insert",profile:{profileId:v,manifest:n}}]),m(v)}a(Re,"ensureRootProfile");const J=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function T(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(T,"metadataEnvName");function R(e){if(typeof e!="object"||e===null||Array.isArray(e))throw l("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const n=new Map;for(const[t,r]of Object.entries(e)){if(!J.test(t))throw l(`invalid metadata key: ${JSON.stringify(t)}`,{received:t,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof r!="string")throw l(`metadata value for ${t} must be a string`,{received:typeof r,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(r.includes("\0"))throw l(`metadata value for ${t} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=T(t),o=n.get(i);if(o!==void 0)throw l(`metadata keys ${JSON.stringify(o)} and ${JSON.stringify(t)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});n.set(i,t)}}a(R,"assertProfileMetadata");function U(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const n={},t=new Set;for(const[r,i]of Object.entries(e)){if(typeof i!="string"||!J.test(r)||i.includes("\0"))continue;const o=T(r);t.has(o)||(t.add(o),n[r]=i)}return n}a(U,"sanitizeProfileMetadata");async function F(e,n=[],t={}){const r=e.trim();if(r==="")throw l("profile name must not be empty");t.metadata!==void 0&&R(t.metadata),b(n);const i=E(n.map(c=>({...c.repo===void 0?{}:{repo:c.repo},...c.path===void 0?{}:{path:z(c.path)}}))),o=le(r),s={schema_version:M,name:r,projects:i,paused_at:null,...t.grantee===void 0?{}:{grantee:t.grantee},...t.defaultKind!==void 0?{default_kind:t.defaultKind}:{},...t.metadata!==void 0&&Object.keys(t.metadata).length>0?{metadata:{...t.metadata}}:{},created_at:y(),last_used_at:null};x(o,s);const f=a(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:o,manifest:s}}])},"insert");if(j()){if(O===null)throw new Error("a cloud role has no profile environment writer registered");await O({profileId:o,grantee:d(s),person:t.appEnvironment===!0?d(s):te(),...t.appEnvironment===!0?{payer:t.payer??d(s)}:{},...t.memoryMb===void 0?{}:{memoryMb:t.memoryMb},...t.recipe===void 0?{}:{recipe:t.recipe}},async c=>{s.environment_id=c,await f()})}else{const c=ne();c!==void 0&&(s.environment_id=c.environmentId),await f()}return{profileId:o,manifest:s}}a(F,"createProfile");async function Se(e){if(!e.startsWith("app:")||e.length<=4)throw l("an app grantee is required");const n=`app-${e.slice(4)}`,t=h().filter(r=>r.manifest.name===n&&r.manifest.grantee===e);if(t.length>1)throw new Error(`duplicate default profile for ${e}`);return t[0]?t[0]:await F(n,[],{grantee:e})}a(Se,"ensureAppProfile");function K(e){if(_(e),m(e)===null)throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(K,"requireExistingProfile");async function u(e,n){K(e);let t;return await w(r=>{const i=r.profiles.find(o=>o.profileId===e);if(i===void 0)throw p(`profile not found: ${e}`,{received:e});return t={profileId:e,manifest:n(structuredClone(i.manifest))},[{op:"profile.update",profile:t}]}),t}a(u,"mutateManifest");async function Me(e){return await u(e,n=>({...n,last_used_at:y()}))}a(Me,"updateProfileLastUsed");function ce(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}a(ce,"loadProfileManifestOrNull");function ke(e){return e==null||e===""||!$.test(e)?!1:Q(e)}a(ke,"isProfilePaused");function Ce(){return B()}a(Ce,"pausedCanvasProfiles");function ue(e){if(e.manifest.paused_at!==null)throw l(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}a(ue,"assertProfileEntryActive");function Ne(e){const n=ce(e);return n===null?null:(ue(n),n)}a(Ne,"assertProfileActive");async function De(e){return await u(e,n=>({...n,paused_at:n.paused_at??y()}))}a(De,"pauseProfile");async function Le(e){let n=null;return{...await u(e,r=>(n=r.paused_at,{...r,paused_at:null})),pausedAt:n}}a(Le,"resumeProfile");async function ze(e,n){return await u(e,t=>({...t,default_kind:n}))}a(ze,"setProfileDefaultKind");async function Je(e,n,t=[]){return R(n),await u(e,r=>{const i={...U(r.metadata),...n};for(const f of t)delete i[f];R(i);const{metadata:o,...s}=r;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}a(Je,"updateProfileMetadata");function Te(e){if(e===null||e==="")return{};try{return U(N(e).manifest.metadata)}catch{return{}}}a(Te,"readProfileMetadata");async function Ue(e,n){const t=n.trim();if(t==="")throw l("profile name must not be empty");return await u(e,i=>({...i,name:t}))}a(Ue,"renameProfile");async function Fe(e,n,t){b([{path:n,...t===void 0?{}:{repo:t}}]);const r=z(n);return await u(e,i=>({...i,projects:E(i.projects.some(o=>o.path===r)?i.projects.map(o=>o.path===r&&o.repo===void 0&&t!==void 0?{...o,repo:t}:o):[...i.projects,{path:r,...t===void 0?{}:{repo:t}}])}))}a(Fe,"addProfileProject");async function Ke(e,n){return b([{repo:n}]),await u(e,t=>({...t,projects:t.projects.some(r=>r.repo===n)?t.projects:E([...t.projects,{repo:n}])}))}a(Ke,"addProfileRepo");async function qe(e,n,t){let r=!1;return await u(e,i=>{if(i.projects.some(s=>s.repo===t))return i;const o=i.projects.map(s=>s.path!==n||s.repo!==void 0?s:(r=!0,{...s,repo:t}));return r?{...i,projects:o}:i}),r}a(qe,"fillProfileProjectRepo");async function He(e,n,t){return re({[n]:t}),await u(e,r=>{const{[n]:i,...o}=r.delivery_limits??{},s=t==="content"?o:{...o,[n]:t},{delivery_limits:f,...c}=r;return Object.keys(s).length===0?c:{...c,delivery_limits:s}})}a(He,"setProfileDeliveryLimit");async function We(e,n){const t=G(n);let r=t;try{r=W(t)}catch{}return await u(e,o=>{const s=o.projects.filter(f=>f.path===void 0||f.path!==r&&f.path!==t);if(s.length===o.projects.length)throw p(`project not found on profile: ${n}`,{received:n,next:`Current projects: ${o.projects.length>0?o.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...o,projects:s}})}a(We,"removeProfileProject");async function Ze(e){K(e);const n=P(d(N(e).manifest),e);await w(t=>{if(!t.profiles.some(r=>r.profileId===e))throw p(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),S(n.dir,{recursive:!0,force:!0}),S(n.env,{force:!0})}a(Ze,"deleteProfile");export{v as ROOT_PROFILE_ID,Fe as addProfileProject,Ke as addProfileRepo,re as assertDeliveryLimits,Ne as assertProfileActive,ue as assertProfileEntryActive,R as assertProfileMetadata,b as assertProfileProjects,F as createProfile,Ze as deleteProfile,Se as ensureAppProfile,Re as ensureRootProfile,qe as fillProfileProjectRepo,ke as isProfilePaused,h as listProfiles,N as loadExactProfileManifest,ae as loadProfileManifest,oe as lookupProfile,se as matchProfileOperand,T as metadataEnvName,De as pauseProfile,Ce as pausedCanvasProfiles,Ae as profileDir,Te as readProfileMetadata,We as removeProfileProject,Ue as renameProfile,Ee as resolveProfileOperand,Le as resumeProfile,U as sanitizeProfileMetadata,Oe as setCloudProfileWriter,ze as setProfileDefaultKind,He as setProfileDeliveryLimit,Me as updateProfileLastUsed,Je as updateProfileMetadata};
|
|
1
|
+
var H=Object.defineProperty;var a=(e,t)=>H(e,"name",{value:t,configurable:!0});import{randomUUID as W}from"node:crypto";import{realpathSync as Z,rmSync as M}from"node:fs";import{isAbsolute as G,resolve as V}from"node:path";import{resolveExistingProjectDir as Y}from"./project-dir.js";import{SCHEMA_VERSION as k}from"../../types.js";import{profileSpace as P}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as C}from"../../api/dto/profiles.js";import{ensureDir as B,nowIso as y}from"../fs-utils.js";import{cachedPausedProfileIds as I,cachedProfilePaused as Q,getCachedProfile as m,listCachedProfiles as X,writeSettings as g}from"../scoped-state/person-store.js";import{usage as l,notFound as p,ambiguous as N,general as ee}from"../errors.js";import{fuzzyMatchProfile as te}from"./fuzzy-match.js";import{isCloudRole as j,personId as ne}from"../canvas/person-state.js";import{readMachineConfig as D}from"../../daemon/machine-link/config.js";const $=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,v="root-00000000",w="root";function d(e){return e.grantee??"app:terminal"}a(d,"profileApp");function x(e,t){B(P(d(t),e).dir)}a(x,"scaffoldProfile");function _(e){if(!$.test(e))throw l(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}a(_,"assertSafeProfileId");function Ae(e){_(e);const t=m(e);if(t===null)throw p(`profile not found: ${e}`,{received:e});return P(d(t.manifest),e).dir}a(Ae,"profileDir");function b(e){if(!Array.isArray(e))throw l("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:n,repo:i}=t;for(const[r,o]of[["path",n],["repo",i]])if(o!==void 0&&(typeof o!="string"||o.trim()===""))throw l(`project entry has an invalid ${r}: ${JSON.stringify(t)}`,{field:"projects",next:`Give ${r} a non-empty string, or leave it out.`});if(n===void 0&&i===void 0)throw l(`project entry has neither path nor repo: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(b,"assertProfileProjects");function re(e){const t=C.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw l("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[n,i]of Object.entries(e)){if(n.trim()==="")throw l("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof i!="string"||!C.includes(i))throw l(`invalid delivery limit for ${n}: ${JSON.stringify(i)}`,{received:String(i),field:"delivery_limits",next:`Set ${n} to one of: ${t}.`})}}a(re,"assertDeliveryLimits");function ie(){return{entries:X(),unreadableIds:[]}}a(ie,"enumerateProfiles");function h(){return ie().entries}a(h,"listProfiles");function oe(e){const t=h(),n=z(t,e,A);return n?{kind:"resolved",entry:n}:{kind:"absent"}}a(oe,"lookupProfile");function L(e){_(e);const t=m(e);if(t!==null)return t;throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(L,"loadExactProfileManifest");const A=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function z(e,t,n){if($.test(t)){const r=e.find(o=>n(o).profileId===t);if(r!==void 0)return r}const i=e.filter(r=>n(r).name===t);if(i.length===1)return i[0];if(i.length>1){const r=i.map(o=>n(o).profileId);throw N(`profile name "${t}" matches ${r.length} profiles: ${r.join(", ")}`,{received:t,candidates:r,next:`Re-run with one exact profile id: ${r.join(", ")}.`})}return null}a(z,"findExactProfile");function J(e,t,n){const i=e.map(r=>`${n(r).profileId} (${n(r).name})`);return p(`profile not found: ${t}`,{received:t,available:i,next:i.length>0?`Re-run with one of the profiles on this host: ${i.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(J,"profileNotFound");function ae(e){const t=oe(e);if(t.kind==="resolved")return t.entry;throw J(h(),e,A)}a(ae,"loadProfileManifest");function Ee(e){return se(h(),e,A)}a(Ee,"resolveProfileOperand");function se(e,t,n){const i=z(e,t,n);if(i!==null)return i;const{match:r,tied:o}=te(t,e.map(n));if(r!==null){const s=e.find(f=>n(f).profileId===r.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${n(s).name} (${n(s).profileId})`),s}if(o.length>1){const s=o.map(f=>`${f.profileId} (${f.name})`);throw N(`"${t}" is equally close to ${o.length} profiles: ${s.join(", ")}`,{received:t,candidates:o.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw J(e,t,n)}a(se,"matchProfileOperand");function T(e){if(!j())return Y(e);if(!G(e))throw l(`project directory must be an absolute path: ${e}`,{received:e});return e}a(T,"storedProjectDir");function E(e){const t=new Set,n=new Map,i=[];for(const r of e)if(r.path!==void 0){if(t.has(r.path))continue;t.add(r.path);const o=r.repo===void 0?void 0:n.get(r.repo);if(o!==void 0&&i[o].path===void 0){i[o]={...i[o],path:r.path};continue}i.push(r)}else if(r.repo!==void 0){if(n.has(r.repo))continue;n.set(r.repo,i.length),i.push(r)}else i.push(r);return i}a(E,"dedupeProjects");function fe(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}a(fe,"slugify");function le(e){const t=fe(e);for(let n=0;n<20;n++){const i=W().replace(/-/g,"").slice(0,8),r=`${t}-${i}`;if(m(r)===null)return r}throw ee(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(le,"generateProfileId");let R=null;function Re(e){R=e}a(Re,"setCloudProfileWriter");async function Oe(){if(j()){const r=h().find(o=>o.manifest.name===w&&d(o.manifest)==="app:terminal");return r!==void 0?(x(r.profileId,r.manifest),r):await S(w,[],{grantee:"app:terminal"})}const e=D(),t=a(r=>r.manifest.environment_id===e?.environmentId,"ownRoot"),n=[m(v),...h().filter(r=>r.manifest.name===w&&d(r.manifest)==="app:terminal")].find(r=>r!==null&&t(r))??null;if(n!==null)return x(n.profileId,n.manifest),n;if(e!==void 0)return await S(w,[],{grantee:"app:terminal"});const i={schema_version:k,name:w,projects:[],grantee:"app:terminal",paused_at:null,created_at:y(),last_used_at:y()};return x(v,i),await g(r=>r.profiles.some(o=>o.profileId===v)?[]:[{op:"profile.insert",profile:{profileId:v,manifest:i}}]),m(v)}a(Oe,"ensureRootProfile");const U=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function F(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(F,"metadataEnvName");function O(e){if(typeof e!="object"||e===null||Array.isArray(e))throw l("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[n,i]of Object.entries(e)){if(!U.test(n))throw l(`invalid metadata key: ${JSON.stringify(n)}`,{received:n,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof i!="string")throw l(`metadata value for ${n} must be a string`,{received:typeof i,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(i.includes("\0"))throw l(`metadata value for ${n} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const r=F(n),o=t.get(r);if(o!==void 0)throw l(`metadata keys ${JSON.stringify(o)} and ${JSON.stringify(n)} both surface as ${r}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(r,n)}}a(O,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},n=new Set;for(const[i,r]of Object.entries(e)){if(typeof r!="string"||!U.test(i)||r.includes("\0"))continue;const o=F(i);n.has(o)||(n.add(o),t[i]=r)}return t}a(K,"sanitizeProfileMetadata");async function S(e,t=[],n={}){const i=e.trim();if(i==="")throw l("profile name must not be empty");n.metadata!==void 0&&O(n.metadata),b(t);const r=E(t.map(c=>({...c.repo===void 0?{}:{repo:c.repo},...c.path===void 0?{}:{path:T(c.path)}}))),o=le(i),s={schema_version:k,name:i,projects:r,paused_at:null,...n.grantee===void 0?{}:{grantee:n.grantee},...n.defaultKind!==void 0?{default_kind:n.defaultKind}:{},...n.metadata!==void 0&&Object.keys(n.metadata).length>0?{metadata:{...n.metadata}}:{},created_at:y(),last_used_at:null};x(o,s);const f=a(async()=>{await g(()=>[{op:"profile.insert",profile:{profileId:o,manifest:s}}])},"insert");if(j()){if(R===null)throw new Error("a cloud role has no profile environment writer registered");await R({profileId:o,grantee:d(s),person:n.appEnvironment===!0?d(s):ne(),...n.appEnvironment===!0?{payer:n.payer??d(s)}:{},...n.memoryMb===void 0?{}:{memoryMb:n.memoryMb},...n.recipe===void 0?{}:{recipe:n.recipe}},async c=>{s.environment_id=c,await f()})}else{const c=D();c!==void 0&&(s.environment_id=c.environmentId),await f()}return{profileId:o,manifest:s}}a(S,"createProfile");async function Se(e){if(!e.startsWith("app:")||e.length<=4)throw l("an app grantee is required");const t=`app-${e.slice(4)}`,n=h().filter(i=>i.manifest.name===t&&i.manifest.grantee===e);if(n.length>1)throw new Error(`duplicate default profile for ${e}`);return n[0]?n[0]:await S(t,[],{grantee:e})}a(Se,"ensureAppProfile");function q(e){if(_(e),m(e)===null)throw p(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(q,"requireExistingProfile");async function u(e,t){q(e);let n;return await g(i=>{const r=i.profiles.find(o=>o.profileId===e);if(r===void 0)throw p(`profile not found: ${e}`,{received:e});return n={profileId:e,manifest:t(structuredClone(r.manifest))},[{op:"profile.update",profile:n}]}),n}a(u,"mutateManifest");async function Me(e){return await u(e,t=>({...t,last_used_at:y()}))}a(Me,"updateProfileLastUsed");function ce(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}a(ce,"loadProfileManifestOrNull");function ke(e){return e==null||e===""||!$.test(e)?!1:Q(e)}a(ke,"isProfilePaused");function Ce(){return I()}a(Ce,"pausedCanvasProfiles");function ue(e){if(e.manifest.paused_at!==null)throw l(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}a(ue,"assertProfileEntryActive");function Ne(e){const t=ce(e);return t===null?null:(ue(t),t)}a(Ne,"assertProfileActive");async function De(e){return await u(e,t=>({...t,paused_at:t.paused_at??y()}))}a(De,"pauseProfile");async function Le(e){let t=null;return{...await u(e,i=>(t=i.paused_at,{...i,paused_at:null})),pausedAt:t}}a(Le,"resumeProfile");async function ze(e,t){return await u(e,n=>({...n,default_kind:t}))}a(ze,"setProfileDefaultKind");async function Je(e,t,n=[]){return O(t),await u(e,i=>{const r={...K(i.metadata),...t};for(const f of n)delete r[f];O(r);const{metadata:o,...s}=i;return{...s,...Object.keys(r).length>0?{metadata:r}:{}}})}a(Je,"updateProfileMetadata");function Te(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}a(Te,"readProfileMetadata");async function Ue(e,t){const n=t.trim();if(n==="")throw l("profile name must not be empty");return await u(e,r=>({...r,name:n}))}a(Ue,"renameProfile");async function Fe(e,t,n){b([{path:t,...n===void 0?{}:{repo:n}}]);const i=T(t);return await u(e,r=>({...r,projects:E(r.projects.some(o=>o.path===i)?r.projects.map(o=>o.path===i&&o.repo===void 0&&n!==void 0?{...o,repo:n}:o):[...r.projects,{path:i,...n===void 0?{}:{repo:n}}])}))}a(Fe,"addProfileProject");async function Ke(e,t){return b([{repo:t}]),await u(e,n=>({...n,projects:n.projects.some(i=>i.repo===t)?n.projects:E([...n.projects,{repo:t}])}))}a(Ke,"addProfileRepo");async function qe(e,t,n){let i=!1;return await u(e,r=>{if(r.projects.some(s=>s.repo===n))return r;const o=r.projects.map(s=>s.path!==t||s.repo!==void 0?s:(i=!0,{...s,repo:n}));return i?{...r,projects:o}:r}),i}a(qe,"fillProfileProjectRepo");async function He(e,t,n){return re({[t]:n}),await u(e,i=>{const{[t]:r,...o}=i.delivery_limits??{},s=n==="content"?o:{...o,[t]:n},{delivery_limits:f,...c}=i;return Object.keys(s).length===0?c:{...c,delivery_limits:s}})}a(He,"setProfileDeliveryLimit");async function We(e,t){const n=V(t);let i=n;try{i=Z(n)}catch{}return await u(e,o=>{const s=o.projects.filter(f=>f.path===void 0||f.path!==i&&f.path!==n);if(s.length===o.projects.length)throw p(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${o.projects.length>0?o.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...o,projects:s}})}a(We,"removeProfileProject");async function Ze(e){q(e);const t=P(d(L(e).manifest),e);await g(n=>{if(!n.profiles.some(i=>i.profileId===e))throw p(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),M(t.dir,{recursive:!0,force:!0}),M(t.env,{force:!0})}a(Ze,"deleteProfile");export{v as ROOT_PROFILE_ID,Fe as addProfileProject,Ke as addProfileRepo,re as assertDeliveryLimits,Ne as assertProfileActive,ue as assertProfileEntryActive,O as assertProfileMetadata,b as assertProfileProjects,S as createProfile,Ze as deleteProfile,Se as ensureAppProfile,Oe as ensureRootProfile,qe as fillProfileProjectRepo,ke as isProfilePaused,h as listProfiles,L as loadExactProfileManifest,ae as loadProfileManifest,oe as lookupProfile,se as matchProfileOperand,F as metadataEnvName,De as pauseProfile,Ce as pausedCanvasProfiles,Ae as profileDir,Te as readProfileMetadata,We as removeProfileProject,Ue as renameProfile,Ee as resolveProfileOperand,Le as resumeProfile,K as sanitizeProfileMetadata,Re as setCloudProfileWriter,ze as setProfileDefaultKind,He as setProfileDeliveryLimit,Me as updateProfileLastUsed,Je as updateProfileMetadata};
|
|
@@ -30,5 +30,5 @@ export declare function piAgentDir(homeDir?: string): string;
|
|
|
30
30
|
*/
|
|
31
31
|
export declare function findMissingPackagePaths(agentDir: string, homeDir?: string): MissingPackage[];
|
|
32
32
|
/** A human-readable, actionable warning for a set of missing packages, or
|
|
33
|
-
* `null` when nothing is missing.
|
|
33
|
+
* `null` when nothing is missing. */
|
|
34
34
|
export declare function missingPackageWarning(agentDir: string, homeDir?: string): string | null;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
var u=Object.defineProperty;var
|
|
2
|
-
\u2192 ${
|
|
3
|
-
`+
|
|
4
|
-
`)
|
|
1
|
+
var u=Object.defineProperty;var r=(e,t)=>u(e,"name",{value:t,configurable:!0});import{existsSync as d,readFileSync as f}from"node:fs";import{homedir as a}from"node:os";import{appSpace as h}from"../layout.js";import{join as l,resolve as m}from"node:path";import{isRendererReady as g}from"../termrender/termrender.js";import{expandTilde as c}from"../fs-utils.js";function j(){return g()?null:"crtr: the pinned termrender renderer is not provisioned \u2014 pages, reviews, and inline diagrams render as plaintext.\n Fix: install `uv` (curl -LsSf https://astral.sh/uv/install.sh | sh); the next render provisions the renderer."}r(j,"rendererWarning");function A(e=a()){const t=process.env.PI_CODING_AGENT_DIR;return t!==void 0&&t!==""?c(t,e):l(e===a()?h("terminal").home:e,".pi","agent")}r(A,"piAgentDir");function x(e){return e.startsWith("npm:")?!1:e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}r(x,"isLocalPathSource");function v(e,t=a()){let n;try{n=f(l(e,"settings.json"),"utf8")}catch{return[]}let i;try{i=JSON.parse(n).packages}catch{return[]}if(!Array.isArray(i))return[];const s=[];for(const o of i){if(typeof o!="string"||!x(o))continue;const p=m(e,c(o,t));d(p)||s.push({source:o,resolved:p})}return s}r(v,"findMissingPackagePaths");function F(e,t=a()){const n=v(e,t);if(n.length===0)return null;const i=n.map(s=>` \u2022 ${s.source}
|
|
2
|
+
\u2192 ${s.resolved} (missing)`);return`crtr: ${n.length} configured pi package path${n.length===1?"":"s"} no longer exist${n.length===1?"s":""} \u2014 pi silently skips these, so their slash commands (e.g. ~/.claude commands & marketplace plugins) will not load.
|
|
3
|
+
`+i.join(`
|
|
4
|
+
`)+`
|
|
5
|
+
Fix: correct or remove the path in ${l(e,"settings.json")} (crtr does not write this file; its own extensions load without it).`}r(F,"missingPackageWarning");export{v as findMissingPackagePaths,F as missingPackageWarning,A as piAgentDir,j as rendererWarning};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { CredentialStore } from '@earendil-works/pi-ai';
|
|
2
2
|
/** The daemon, which owns the rows, registers a builder of its row-backed read-only view (one read per table); every other process asks the daemon over /v1/model-auth. */
|
|
3
3
|
export declare function registerGateCredentialStore(snapshot: () => Promise<CredentialStore>): void;
|
|
4
|
-
export declare const NO_PROVIDER_CREDENTIAL_MESSAGE = "crtr: no provider credential;
|
|
4
|
+
export declare const NO_PROVIDER_CREDENTIAL_MESSAGE = "crtr: no provider credential; log in under Providers in `crtr sys settings`.";
|
|
5
5
|
/** Check the setup catalog before a path creates a broker-backed node. `profileEnvNames` are the names stored on the
|
|
6
6
|
* launching profile (values are never needed: a stored value is never empty). */
|
|
7
7
|
export declare function hasConfiguredProviderCredential(profileEnvNames: readonly string[]): Promise<boolean>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var a=Object.defineProperty;var t=(e,i)=>a(e,"name",{value:i,configurable:!0});import{ModelRegistry as c,ModelRuntime as l}from"@earendil-works/pi-coding-agent";import{join as m}from"node:path";import{ApiCredentialStore as f}from"../model-auth/api-credential-store.js";import{cliClient as p}from"../../commands/api-client.js";import{hasProviderCredential as u}from"../provider-credential.js";import{piAgentDir as E}from"./package-health.js";import{PROVIDER_ENV_KEYS as g}from"./spawn-env.js";let d;function D(e){d=e}t(D,"registerGateCredentialStore");function w(e){const i=new Map;let n;const o=t(()=>{throw new Error("the provider credential check is read-only")},"refuse");return{read:t(r=>{let s=i.get(r);return s===void 0&&i.set(r,s=e.read(r)),s},"read"),list:t(()=>n??=e.list(),"list"),modify:o,delete:o}}t(w,"readOnceStore");const h="crtr: no provider credential; log in under Providers in `crtr sys settings`.";async function M(e){const i=Object.fromEntries(e.map(r=>[r,"stored"]));if(Object.values(g).some(r=>(i[r]??process.env[r])?.trim()))return!0;const n=E(),o=await l.create({credentials:d===void 0?w(new f(()=>p(),!0)):await d(),modelsPath:m(n,"models.json")});return await u(o,new c(o))}t(M,"hasConfiguredProviderCredential");function _(){process.stderr.write(`${h}
|
|
2
2
|
`),process.exit(1)}t(_,"exitForMissingProviderCredential");export{h as NO_PROVIDER_CREDENTIAL_MESSAGE,_ as exitForMissingProviderCredential,M as hasConfiguredProviderCredential,D as registerGateCredentialStore};
|
|
@@ -15,6 +15,9 @@ export interface MachineExecutorDeps {
|
|
|
15
15
|
signal: string | null;
|
|
16
16
|
}) => void;
|
|
17
17
|
}
|
|
18
|
+
/** The app's pi settings with this install's bundled `pi-crtr-extensions` as the only crtr package entry: the same absolute path a sandbox broker gets (host.ts),
|
|
19
|
+
* so the broker loads the package of the generation that launches it. Other settings and packages the person set are kept. */
|
|
20
|
+
export declare function withBundledExtensions(settingsJson: string | undefined): string;
|
|
18
21
|
/** Broker processes: `{pid, execution, node}` for each `broker-cli.js ... --epoch <execution> <node>` command line. Throws when the process table cannot
|
|
19
22
|
* be read: an unreadable table is not an empty one, and a caller that read it as "no brokers" would start a second broker or report a stop that did not happen. */
|
|
20
23
|
export declare function findBrokers(): Promise<Array<{
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
var
|
|
1
|
+
var g=Object.defineProperty;var c=(n,r)=>g(n,"name",{value:r,configurable:!0});import{spawn as j}from"node:child_process";import{closeSync as J,existsSync as m,mkdirSync as v,openSync as K,readFileSync as V,statSync as X}from"node:fs";import{rm as W}from"node:fs/promises";import{basename as D,dirname as y,join as h}from"node:path";import{fileURLToPath as Y}from"node:url";import{emitEvent as q}from"../../../events/emit.js";import{contextDir as z,jobDir as Q,nodeRunDir as M,crtrHome as L,viewSocketPath as Z}from"../../../canvas/paths.js";import{captureTeardownSnapshot as ee,isAnyPidAlive as ne,killProcessTreePids as A,listProcessTableAsync as oe}from"../../../canvas/pid.js";import{scopesFilePath as G}from"../../../canvas/paths.js";import{writeFileBeneath as b}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as te}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as re}from"../../broker-ownership.js";import{isShippedCanvasExtension as ie}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as ce,mergeCanvasExtensions as se}from"../../canvas-extensions.js";import{layoutRoot as ae,runtimeRoot as de}from"../../../layout.js";import{composeAppProcessEnv as ue,overlayBrokerEnv as fe}from"../../spawn-env.js";const R=c(()=>h(y(Y(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry");function le(n){const r=n===void 0?{}:JSON.parse(n),t=h(y(R()),"..","..","builtin-pi-packages","pi-crtr-extensions"),e=(r.packages??[]).filter(o=>!/pi-crtr-extensions/.test(typeof o=="string"?o:String(o.source)));return`${JSON.stringify({...r,packages:[t,...e]},null,2)}
|
|
2
|
+
`}c(le,"withBundledExtensions");const H=c(n=>{if(n!==void 0)try{process.kill(-n,"SIGKILL")}catch{}},"killGroup"),pe=c(n=>new Promise(r=>setTimeout(r,n)),"sleep");async function U(){const n=[],r=await oe();if(r===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:t,command:e}of r){const o=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);o!==null&&n.push({pid:t,execution:o[1],node:o[2],command:e})}return n}c(U,"findBrokers");const me=["CRTR_HOME","CRTR_RUNTIME_HOME"];function F(n,r){const t={...n};for(const e of me)delete t[e];return t.CRTR_CONTEXT_DIR!==void 0&&(t.CRTR_CONTEXT_DIR=z(r.id,t.CRTR_GRANTEE??r.app)),t.CRTR_SCOPES_FILE!==void 0&&(t.CRTR_SCOPES_FILE=G(r.id)),t}c(F,"localLaunchEnv");function he(n){const r=c(i=>D(i).replace(/\.[jt]s$/,""),"stem"),t=new Set(ce.map(r)),e=c(i=>ie(i)||D(y(i))==="pi-extensions"&&(t.has(r(i))||r(i).startsWith("canvas-")&&!m(i)),"shipped"),o=[],s=[];for(let i=0;i<n.length;i++)if(n[i]==="-e"&&n[i+1]!==void 0){const d=n[++i];if(e(d))continue;if(!m(d))throw new Error(`extension ${d} does not exist on this machine`);s.push(d)}else o.push(n[i]);return[...se(s).flatMap(i=>["-e",i]),...o]}c(he,"localExtensionArgv");function we(n,r,t){const e=JSON.parse(n);return JSON.stringify({...e,argv:he(e.argv),env:F(e.env??{},r),...t===void 0?{}:{start:t}})}c(we,"machineLaunchRecipe");function Ee(n,r,t){const e=n.launch,o=fe({argv:[],env:F(e.env??{},n.node)},ue(n.node.cwd,null,n.node.app,n.machine_env??{},{}));return Object.assign(o,{CRTR_HOME:ae(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??de(),CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t,CRTR_ENVIRONMENT_ID:r.environmentId,CRTR_VIEW_WSS:"0",[te]:"1"})}c(Ee,"machineBrokerEnv");async function $(n,r,t){const{tree:e,identities:o}=ee(n,null,t);if(o===null)return{confirmed:!1,error:`the process tree of broker ${n} could not be read, so shutdown cannot be confirmed`};const s=c(async(i,d)=>{for(let l=0;ne(i);l+=100){if(l>=d)return!1;await pe(100)}return!0},"waitUntilDead");try{process.kill(n,"SIGTERM")}catch{}return await s([n],r),A(e,"SIGTERM",o),await s(e,2e3)?{confirmed:!0}:(A(e,"SIGKILL",o),await s(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${n} survived SIGKILL`})}c($,"stopBroker");async function Ae(n=1e4){const t=(await Promise.all((await U()).filter(e=>re(e.command,L())).map(e=>$(e.pid,n)))).filter(e=>!e.confirmed);if(t.length>0)throw new Error(t.map(e=>e.error??"a broker did not stop").join("; "))}c(Ae,"stopAllBrokers");function Ge(n){const r=(n.stopGraceS??10)*1e3,t=c(async e=>(await U()).find(o=>o.execution===e),"brokerOf");return{async start(e,o){const s={};let i=performance.now();const d=c(a=>{const u=performance.now();s[a]=Math.round((u-i)*10)/10,i=u},"stepDone"),l=await t(e.executionId);if(d("process_lookup"),l!==void 0)return{pid:l.pid,timings:s};if(o?.throwIfAborted(),!m(e.cwd)||!X(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!m(R()))throw new Error(`the broker entry ${R()} does not exist`);if(e.bundle===void 0)throw new Error("the control plane carried no start bundle: it runs an older release than this Mac");const{bundle:_}=e,C=_.launch,w=M(e.nodeId);v(w,{recursive:!0}),b(w,h(w,"broker-launch.json"),we(e.launchJson,_.node,e.start),{atomic:!0,mode:384}),C.env?.CRTR_SCOPES_FILE!==void 0&&b(w,G(e.nodeId),JSON.stringify(C.scopes??[]),{atomic:!0});const O=Q(e.nodeId);v(O,{recursive:!0});const I=K(h(O,"broker.log"),"a"),k=Ee(_,n,e.executionId),S=k.PI_CODING_AGENT_DIR,x=h(S,"settings.json");v(S,{recursive:!0}),b(S,x,le(m(x)?V(x,"utf8"):void 0),{atomic:!0}),delete k.CRTR_NODE_TOKEN,d("file_writes");try{o?.throwIfAborted();const a=j(process.execPath,[R(),"--canvas-home",L(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",I,I,"pipe"],env:k});let u,N=!1;const P=c(()=>{u!==void 0&&n.onExit?.({execution:e.executionId,node:e.nodeId,...u})},"report");a.once("exit",(T,f)=>{u={code:T,signal:f},N&&P()});const p=a.stdio[3];if(p==null||!("end"in p))throw H(a.pid),new Error("broker token pipe did not open");const B=await new Promise((T,f)=>{a.once("error",f),a.once("spawn",()=>{a.off("error",f),p.once("error",E=>{H(a.pid),f(E)}),p.end(e.nodeToken,E=>{E?f(E):T(a.pid)})})});return N=!0,P(),a.unref(),d("spawn_and_token_pipe"),q({level:"info",event:"machine.start.timing",node_id:e.nodeId,fields:{execution:e.executionId,...s}}),{pid:B,timings:s}}finally{J(I)}},async wake({execution:e}){const o=await t(e.executionId);if(o===void 0)return"no_broker";try{return process.kill(o.pid,"SIGUSR1"),"signalled"}catch(s){if(s.code==="ESRCH")return"no_broker";throw s}},async stop({execution:e,options:o}){const s=await t(e.executionId);return s===void 0?{confirmed:!0}:await $(s.pid,r,o.excludePid)},async status({execution:e}){const o=await t(e.executionId);return o===void 0?{state:"gone"}:{state:"running",pid:o.pid}},async delete({nodeId:e}){return await W(M(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:Z(e.nodeId)}}}}c(Ge,"createMachineExecutor");export{Ge as createMachineExecutor,U as findBrokers,he as localExtensionArgv,Ee as machineBrokerEnv,we as machineLaunchRecipe,Ae as stopAllBrokers,le as withBundledExtensions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var s=(a,t)=>d(a,"name",{value:t,configurable:!0});import{withCanvasWrite as l}from"../canvas/db.js";import{applyOpsToRows as w,readSnapshotFromRows as O}from"./person-rows.js";import{emitEvent as E}from"../events/emit.js";import{appRevisionOf as g}from"./person-store.js";import{TERMINAL_APP as c}from"./imported-mac-installs.js";const o={name:"crouter-official-marketplace",url:"https://github.com/crouton-labs/crouter-official-marketplace.git"},S=["capture"],m=s(a=>`terminal_defaults_seeded:${a}`,"seededKey");async function R(){const a=(await l(async e=>await e.prepare("SELECT DISTINCT sub FROM grants WHERE grantee = 'app:terminal' AND status = 'active'").all())).map(e=>e.sub),t=[];for(const e of a)try{await l(async r=>{if(await r.prepare("SELECT 1 FROM canvas_meta WHERE key = ?").get(m(e))!==void 0)return!1;const n=(await O(r,e)).apps[c],p=n===void 0||Object.keys(n.plugins).length===0&&Object.keys(n.marketplaces).length===0;if(p){const u=Object.fromEntries(S.map(f=>[f,{enabled:!0,source_marketplace:o.name}]));await w(r,e,[{op:"app-plugins.replace",app:c,plugins:u,marketplaces:{[o.name]:{url:o.url,ref:"main",installed_at:new Date().toISOString()}},ifRevision:g(n)}])}return await r.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING").run(m(e),new Date().toISOString()),p})&&t.push(e)}catch(i){E({level:"warn",event:"daemon.settings.terminal_defaults_failed",fields:{person:e},error:i})}return t}s(R,"seedTerminalDefaults");export{R as seedTerminalDefaults,m as seededKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var L=Object.defineProperty;var d=(e,t)=>L(e,"name",{value:t,configurable:!0});import{toErrorBody as H}from"./map.js";import{emitEvent as I}from"../../core/events/emit.js";import{scopeAllowed as m,ScopeDeniedError as F}from"../../core/scopes.js";import{coveredByAny as J}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{isCloudRole as M}from"../../core/canvas/person.js";import{activeGrant as Y,activeGrantsOfPerson as p,grantFor as O}from"../../core/grants/mirror.js";import{getNode as w}from"../../core/canvas/canvas.js";import{ownedRun as Z,RunError as E}from"../../core/runs/operations.js";import{openDb as y}from"../../core/canvas/db.js";import{check as V,permits as S}from"../../core/permissions/evaluator.js";import{readerFor as b}from"./reader.js";import{checkCronFire as X}from"../cron/authority.js";import{operationFor as K}from"./operations.js";import{CONTROL_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{getRequest as N,getRequestByInboxTicket as C}from"../../core/human/requests.js";import{requireVisibleReview as v}from"../../core/review/store.js";import{getComment as q}from"../../core/review/comments.js";import{getStructuredRequest as ee}from"../../core/canvas/structured-requests.js";async function te(e,t,o,n,s){const r=e.path,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(e.method==="POST"&&(r==="/v1/human/requests"||r==="/v1/human/reviews")){if((r.endsWith("/reviews")?a.origin_node_id:a.requester_node_id)!==t.node)throw new u(403,"other_app_run","a broker may create a human request only for its own node");const c=a.source;if(c&&typeof c=="object"&&"nodeId"in c&&c.nodeId!==t.node)throw new u(403,"other_app_run","request source must name the calling node")}if(r==="/v1/human/reviews/self/comments"&&e.method==="GET"&&n.get("actor_node_id")!==t.node)throw new u(403,"other_app_run","self review requires the calling node");if(r.includes("/comments")&&e.method!=="GET"&&a.actor_node_id!==t.node)throw new u(403,"other_app_run","comment author must be the calling node");if(o.comment_id&&!await q(o.comment_id))throw new u(404,"not_found","comment not found")}d(te,"authorizeHumanBody");function $(e){return e.class==="broker"||e.class==="cron"}d($,"boundedByStoredScopes");function k(e){return e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import"?null:e.class==="forwarded"?e.actor.kind==="app"?e.actor.app:null:e.app}d(k,"appOf");function l(e){return e.class==="person"&&e.sub===void 0||e.class==="forwarded"&&e.actor.kind==="person"}d(l,"actsAsPerson");async function T(e){const t=await O(e.actor.app,e.sub);if(!t)throw new u(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);return t}d(T,"forwardedGrant");async function U(e){if(e.class==="person"&&e.sub!==void 0)return(await p(e.sub)).flatMap(o=>o.resolved);if(e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import")return[];if(e.class==="forwarded"){if(e.actor.kind==="person")return[];const{resolved:o}=await T(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>J(o,s))}if(e.class==="app")return e.scopes;if(e.class==="cron"){const o=await X({grantee:e.app,sub:e.sub,grant_id:e.grant,scopes:e.scopes});if(o.allowed)return o.effectiveScopes;throw o.reason==="grant_missing"||o.reason==="grant_revoked"?new u(401,"grant_revoked",o.message):new u(403,"scope_missing",o.message)}const t=e.grant?await Y(e.grant):await O(e.app,e.sub);if(t&&t.grantee===e.app&&t.sub===e.sub)return t.resolved;throw new u(401,"grant_revoked","the node grant is not active")}d(U,"resolvedScopes");function x(e){return"class"in e?k(e):e.grantee}d(x,"runCallerApp");function W(e){return"class"in e?e:{class:"app",app:e.grantee,scopes:e.resolved,sub:e.sub}}d(W,"asRequestPrincipal");async function f(e,t,o){const n=W(e);if(l(n))return!0;if(n.class==="anonymous"||n.class==="machine"||n.class==="import")return!1;const s=await y();return await V(s,await b(s,{principal:n}),t,o)}d(f,"mayOnNode");async function Pe(e){if(l(e))return null;if(e.class==="anonymous"||e.class==="machine"||e.class==="import")return new Set;const t=await y(),o=await S(t,await b(t,{principal:e}),"read"),n=await t.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND ${o.sql}`).all(...o.params);return new Set(n.map(s=>s.id))}d(Pe,"readableNodeIds");async function ze(e,t){if(l(e))return new Set(t);if(e.class==="anonymous"||e.class==="machine"||e.class==="import"||t.length===0)return new Set;const o=await y(),n=await S(o,await b(o,{principal:e}),"read"),s=await o.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND o.id = ANY(?::text[]) AND ${n.sql}`).all([...t],...n.params);return new Set(s.map(r=>r.id))}d(ze,"readableAmong");async function De(e,t){if(l(e))return new Set(t);if(e.class==="anonymous"||e.class==="machine"||e.class==="import"||t.length===0)return new Set;const o=await y(),n=await S(o,await b(o,{principal:e}),"read"),s=new Set;for(let r=0;r<t.length;r+=500){const a=t.slice(r,r+500),i=await o.prepareUncached(`SELECT r.inbox_ticket_id AS id FROM human_requests r JOIN node_rows n ON n.node_id = r.requester_node_id JOIN objects o ON o.id = n.node_id WHERE r.inbox_ticket_id IN (${a.map(()=>"?").join(",")}) AND ${n.sql}`).all(...a,...n.params);for(const c of i)s.add(c.id)}return s}d(De,"readableTicketIds");async function j(e,t,o){const n=W(e);return l(n)?!0:n.class==="anonymous"||n.class==="machine"||n.class==="import"?!1:k(n)===t?!0:m(await U(n),o)&&(!$(n)||m(n.scopes,o))}d(j,"mayReadApp");async function Ge(e,t,o){return o===void 0?await j(e,t,`crtr:conversations:read:${t}`):await f(e,"read",o)}d(Ge,"canReadRun");async function Le(e,t,o=!1,n=!1){const s=await w(t);if(!s||s.parent!==null||s.run_id!==t||!s.grantee||s.deleting_at&&!n)throw new E(404,"not_found","run not found");if(!((!("class"in e)||e.class==="app"||e.class==="forwarded"&&e.actor.kind==="app")&&x(e)===s.grantee&&e.sub===s.sub)&&!await f(e,"read",t))throw new E(404,"not_found","run not found");if(o&&x(e)!==null&&x(e)!==s.grantee)throw new E(403,"other_app_run","cannot change another app's run");return await Z(t,s.grantee,n)}d(Le,"requireRun");async function oe(e,t,o){return o===void 0?await j(e,t,`crtr:objects:read:${t}`):await f(e,"read",o)}d(oe,"canReadNode");const P=new Set(["messages.post.58","messages.post.59"]);async function ne(e,t,o){if(!e.classes.includes(t.class)&&!(t.class!=="anonymous"&&t.class!=="machine"&&t.class!=="import"&&t.class!=="forwarded"&&e.classes.includes("anonymous")))throw new u(403,"permission_error","this operation is not available to the caller");if(e.resource==="daemon-control"&&M())throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available on a shared cloud role");if(t.class==="forwarded"&&t.actor.kind==="app"&&await T(t),t.class==="anonymous"||t.class==="machine"||t.class==="import"||l(t))return;if(t.class==="person")return await re(e,t,o);const n=await U(t);if(e.scope&&(!m(n,e.scope)||$(t)&&!m(t.scopes,e.scope)))throw new u(403,"scope_missing",`missing scope ${e.scope}`);if(t.class==="app")return;const s=k(t);t.class==="broker"&&await ue(e,t,o,n);const r=o.id;if((e.resource==="node-read"||e.resource==="node-write")&&r!==void 0){const a=await w(r);if(!a)return;if(e.resource==="node-write"){const i=P.has(e.name);if(a.grantee!==s&&!i)throw new u(403,"other_app_run","cannot change another app's node");if(!await f(t,i&&a.grantee!==s?"message":"read",r))throw a.grantee!==s?new u(403,"other_app_run","cannot change another app's node"):new u(404,"not_found","node not found")}if(e.resource==="node-read"&&!await f(t,"read",r))throw new u(404,"not_found","node not found")}}d(ne,"authorizeOperation");async function re(e,t,o){if(e.resource==="daemon-bash")throw new u(403,"permission_error","a shell on the daemon host is not available to a person bearer");if(e.resource==="daemon-control")throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available to a person bearer");if(e.resource==="human")return await se(e,t,o);if(o.request_id!==void 0&&e.path.startsWith("/v1/structured-requests/"))return await ae(e,t,o.request_id);const n=o.id;if(!(e.resource!=="node-read"&&e.resource!=="node-write"||n===void 0||!await w(n))&&!await f(t,P.has(e.name)?"message":"read",n))throw new u(404,"not_found","node not found")}d(re,"authorizePersonNode");async function se(e,t,o){const n=o.ticket_id!==void 0?new u(404,"ticket_not_found","no matching ticket"):new u(404,"not_found","no request with that id"),s=o.request_id?await N(o.request_id):o.ticket_id?await C(o.ticket_id):null,r=o.comment_id?await q(o.comment_id):null,a=o.review_id?await v(o.review_id).catch(()=>null):r?await v(r.review_id).catch(()=>null):null;if((o.request_id??o.ticket_id??o.review_id??o.comment_id)===void 0)return;const c=s?.requester_node_id??a?.origin_node_id;if(!c||!await w(c)||!await f(t,e.method==="GET"?"read":"edit",c))throw n}d(se,"authorizePersonHuman");async function ae(e,t,o){const n=await ee(o);if(n!==null&&(n.node_id===null||!await w(n.node_id)||!await f(t,e.method==="GET"?"read":"edit",n.node_id)))throw new u(404,"structured_request_not_found",`unknown structured request: ${o}`)}d(ae,"authorizePersonStructuredRequest");async function de(e,t,o){const n=o&&typeof o=="object"&&!Array.isArray(o)?o:{},s=e.path;if(e.method==="POST"&&(s==="/v1/human/requests"||s==="/v1/human/reviews")){const r=n.source,a=s.endsWith("/reviews")?n.origin_node_id:n.requester_node_id;if(typeof a!="string")throw new u(403,"permission_error","a request must name a node the person acts on");const i=s.endsWith("/requests")&&r&&typeof r=="object"&&"nodeId"in r?r.nodeId:void 0;for(const c of[a,i])if(c!==void 0&&(typeof c!="string"||!await w(c)||!await f(t,"edit",c)))throw new u(404,"not_found","node not found")}if(s==="/v1/structured-requests"){const r=n.target,a=r&&typeof r=="object"&&"kind"in r&&r.kind==="node"&&"node_id"in r?r.node_id:void 0;if(typeof a=="string"&&await w(a)&&!await f(t,"message",a))throw new u(404,"node_not_found",`unknown node: ${a}`)}}d(de,"authorizePersonBody");async function ue(e,t,o,n){if(e.resource==="daemon-bash"&&(!m(n,"crtr:files:rw:user:.")||!m(t.scopes,"crtr:files:rw:user:.")))throw new u(403,"scope_missing","missing scope crtr:files:rw:user:.");if(e.resource==="human"){const r=e.path,a=e.method==="GET";if(!a&&(r.endsWith("/respond")||r.endsWith("/submit")||r.endsWith("/dismiss")||r.endsWith("/progress")||r.endsWith("/comment-ranges")||r.includes("/feedback-comments")))throw new u(403,"permission_error","only the person may answer or edit the human inbox");const i=o.request_id?await N(o.request_id):o.ticket_id?await C(o.ticket_id):null,c=o.comment_id?await q(o.comment_id):null,g=o.review_id?await v(o.review_id):c?await v(c.review_id):null,h=i?.requester_node_id??g?.origin_node_id;if(h!=null){const _=await w(h);if(_&&(a?!await oe(t,_.grantee??"app:terminal",h):_.grantee!==t.app))throw new u(a?404:403,a?"not_found":"other_app_run","human request belongs to another app");if(_&&!a&&!await f(t,"read",h))throw new u(404,"not_found","human request not found")}else if(i||g)throw new u(403,"permission_error","only the person may access a request without a node")}const s=o.id;if(e.resource==="node-own"&&s!==void 0&&s!==t.node)throw new u(403,"other_app_run","the operation requires the calling node")}d(ue,"authorizeBrokerOnly");function ie(e,t){if(!m(e,t))throw new F("the bearer token",t)}d(ie,"assertCeiling");function ce(){return new u(403,"owner_only","this operation is owner-only; a scoped token does not reach it")}d(ce,"ownerOnlyError");const fe="Crtr-Caused-By",we=/^(?:message|request|cron_run):[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function he(e){const t=e[fe.toLowerCase()];return typeof t=="string"&&we.test(t)?t:void 0}d(he,"causedByOf");function He(e){return e.map(t=>({...t,ownerOnly:!0}))}d(He,"ownerOnly");class Ie{static{d(this,"Router")}routes=[];register(t){const o=K(t.method,t.pattern);if(!o)throw new Error(`route has no operation row: ${t.method} ${t.pattern}`);if(this.routes.some(n=>n.method===t.method.toUpperCase()&&n.operation.path===t.pattern))throw new Error(`duplicate route: ${t.method} ${t.pattern}`);return this.routes.push({operation:o,method:t.method.toUpperCase(),segments:z(t.pattern),handler:t.handler,maxBodyBytes:t.maxBodyBytes??Q}),this}registerAll(t){for(const o of t)this.register(o);return this}match(t,o){const n=t.toUpperCase(),s=z(o);for(const r of this.routes){if(r.method!==n)continue;const a=me(r.segments,s);if(a!==null)return{handler:r.handler,params:a,operation:r.operation,maxBodyBytes:r.maxBodyBytes}}return null}async handle(t,o,n,s={class:"person"}){try{const r=new URL(t.url??"/","http://127.0.0.1"),a=(t.method??"GET").toUpperCase(),i=this.match(a,r.pathname);if(i===null){G(o,404,"not_found",`no route for ${a} ${r.pathname}`);return}if(await ne(i.operation,s,i.params),n!==null){if(i.operation.classes.length===1&&i.operation.classes[0]==="person")throw ce();i.operation.scope&&ie(n,i.operation.scope)}let c;try{c=await _e(t,i.maxBodyBytes)}catch(B){const R=B instanceof D?"payload_too_large":"invalid_request";G(o,R==="payload_too_large"?413:400,R,B.message);return}s.class==="person"&&s.sub!==void 0&&await de(i.operation,s,c),s.class==="broker"&&i.operation.resource==="human"&&await te(i.operation,s,i.params,r.searchParams,c);const g=he(t.headers),h={...g===void 0?{}:{causedBy:g},method:a,path:r.pathname,params:i.params,query:r.searchParams,body:c,ceiling:n,principal:s,...s.class==="anonymous"&&typeof t.headers.authorization=="string"?{publishToken:t.headers.authorization.slice(7)}:{},req:t,res:o},_=await i.handler(h);o.writableEnded||le(o,_)}catch(r){if(r instanceof Error&&r.code==="person_unresolved"){A(o,503,{error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}});return}const{status:a,body:i}=H(r);a>=500&&I({event:"api.request.failed",level:"error",error:r instanceof Error?r:new Error(String(r)),...s.class==="broker"?{node_id:s.node}:{},fields:{method:(t.method??"GET").toUpperCase(),path:t.url??""}}),A(o,a,i)}}}function z(e){return e.split("/").filter(t=>t.length>0)}d(z,"splitPath");function me(e,t){if(e.length!==t.length)return null;const o={};for(let n=0;n<e.length;n++){const s=e[n],r=t[n];if(s.startsWith(":"))o[s.slice(1)]=decodeURIComponent(r);else if(s!==r)return null}return o}d(me,"matchSegments");class D extends Error{static{d(this,"BodyTooLargeError")}}async function _e(e,t){const o=[];let n=0;for await(const r of e){const a=r;if(n+=a.length,n>t)throw new D(`request body exceeds ${t} bytes`);o.push(a)}if(n===0)return;const s=Buffer.concat(o).toString("utf8").trim();if(s!=="")try{return JSON.parse(s)}catch{throw new Error("request body is not valid JSON")}}d(_e,"readJsonBody");function le(e,t){if(e.headersSent)return;const o={...t.headers??{}};if(t.rawBody!==void 0){e.writeHead(t.status,o),e.end(t.rawBody);return}if(t.status===204||t.body===void 0){e.writeHead(t.status,o),e.end();return}o["content-type"]===void 0&&(o["content-type"]="application/json; charset=utf-8"),e.writeHead(t.status,o),e.end(JSON.stringify(t.body))}d(le,"writeResult");function A(e,t,o){if(e.headersSent){e.end();return}e.writeHead(t,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}d(A,"writeJson");function G(e,t,o,n){A(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(G,"writeError");export{fe as CAUSED_BY_HEADER,Ie as Router,l as actsAsPerson,k as appOf,ie as assertCeiling,$ as boundedByStoredScopes,oe as canReadNode,Ge as canReadRun,he as causedByOf,f as mayOnNode,He as ownerOnly,ce as ownerOnlyError,ze as readableAmong,Pe as readableNodeIds,De as readableTicketIds,Le as requireRun,U as resolvedScopes,x as runCallerApp};
|
|
1
|
+
var L=Object.defineProperty;var d=(e,t)=>L(e,"name",{value:t,configurable:!0});import{toErrorBody as H}from"./map.js";import{emitEvent as I}from"../../core/events/emit.js";import{scopeAllowed as m,ScopeDeniedError as F}from"../../core/scopes.js";import{coveredByAny as J}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{isCloudRole as M}from"../../core/canvas/person.js";import{activeGrant as Y,activeGrantsOfPerson as Z,grantFor as O}from"../../core/grants/mirror.js";import{ownerScopes as p,ownsWithoutRow as V}from"../../core/grants/owner.js";import{getNode as w}from"../../core/canvas/canvas.js";import{ownedRun as X,RunError as E}from"../../core/runs/operations.js";import{openDb as y}from"../../core/canvas/db.js";import{check as K,permits as S}from"../../core/permissions/evaluator.js";import{readerFor as b}from"./reader.js";import{checkCronFire as Q}from"../cron/authority.js";import{operationFor as ee}from"./operations.js";import{CONTROL_BODY_MAX_BYTES as te}from"../../core/llm/body-limits.js";import{getRequest as N,getRequestByInboxTicket as C}from"../../core/human/requests.js";import{requireVisibleReview as v}from"../../core/review/store.js";import{getComment as q}from"../../core/review/comments.js";import{getStructuredRequest as oe}from"../../core/canvas/structured-requests.js";async function ne(e,t,o,n,s){const r=e.path,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(e.method==="POST"&&(r==="/v1/human/requests"||r==="/v1/human/reviews")){if((r.endsWith("/reviews")?a.origin_node_id:a.requester_node_id)!==t.node)throw new u(403,"other_app_run","a broker may create a human request only for its own node");const c=a.source;if(c&&typeof c=="object"&&"nodeId"in c&&c.nodeId!==t.node)throw new u(403,"other_app_run","request source must name the calling node")}if(r==="/v1/human/reviews/self/comments"&&e.method==="GET"&&n.get("actor_node_id")!==t.node)throw new u(403,"other_app_run","self review requires the calling node");if(r.includes("/comments")&&e.method!=="GET"&&a.actor_node_id!==t.node)throw new u(403,"other_app_run","comment author must be the calling node");if(o.comment_id&&!await q(o.comment_id))throw new u(404,"not_found","comment not found")}d(ne,"authorizeHumanBody");function $(e){return e.class==="broker"||e.class==="cron"}d($,"boundedByStoredScopes");function k(e){return e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import"?null:e.class==="forwarded"?e.actor.kind==="app"?e.actor.app:null:e.app}d(k,"appOf");function l(e){return e.class==="person"&&e.sub===void 0||e.class==="forwarded"&&e.actor.kind==="person"}d(l,"actsAsPerson");async function T(e){const t=await O(e.actor.app,e.sub);if(!t)throw new u(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);return t}d(T,"forwardedGrant");async function W(e){if(e.class==="person"&&e.sub!==void 0)return(await Z(e.sub)).flatMap(o=>o.resolved);if(e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import")return[];if(e.class==="forwarded"){if(e.actor.kind==="person")return[];const{resolved:o}=await T(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>J(o,s))}if(e.class==="app")return e.scopes;if(e.class==="cron"){const o=await Q({grantee:e.app,sub:e.sub,grant_id:e.grant,scopes:e.scopes});if(o.allowed)return o.effectiveScopes;throw o.reason==="grant_missing"||o.reason==="grant_revoked"?new u(401,"grant_revoked",o.message):new u(403,"scope_missing",o.message)}const t=e.grant?await Y(e.grant):await O(e.app,e.sub);if(t&&t.grantee===e.app&&t.sub===e.sub)return t.resolved;if(!t&&V(e.app,e.sub,e.grant))return p(e.app);throw new u(401,"grant_revoked","the node grant is not active")}d(W,"resolvedScopes");function x(e){return"class"in e?k(e):e.grantee}d(x,"runCallerApp");function U(e){return"class"in e?e:{class:"app",app:e.grantee,scopes:e.resolved,sub:e.sub}}d(U,"asRequestPrincipal");async function f(e,t,o){const n=U(e);if(l(n))return!0;if(n.class==="anonymous"||n.class==="machine"||n.class==="import")return!1;const s=await y();return await K(s,await b(s,{principal:n}),t,o)}d(f,"mayOnNode");async function Ge(e){if(l(e))return null;if(e.class==="anonymous"||e.class==="machine"||e.class==="import")return new Set;const t=await y(),o=await S(t,await b(t,{principal:e}),"read"),n=await t.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND ${o.sql}`).all(...o.params);return new Set(n.map(s=>s.id))}d(Ge,"readableNodeIds");async function Le(e,t){if(l(e))return new Set(t);if(e.class==="anonymous"||e.class==="machine"||e.class==="import"||t.length===0)return new Set;const o=await y(),n=await S(o,await b(o,{principal:e}),"read"),s=await o.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND o.id = ANY(?::text[]) AND ${n.sql}`).all([...t],...n.params);return new Set(s.map(r=>r.id))}d(Le,"readableAmong");async function He(e,t){if(l(e))return new Set(t);if(e.class==="anonymous"||e.class==="machine"||e.class==="import"||t.length===0)return new Set;const o=await y(),n=await S(o,await b(o,{principal:e}),"read"),s=new Set;for(let r=0;r<t.length;r+=500){const a=t.slice(r,r+500),i=await o.prepareUncached(`SELECT r.inbox_ticket_id AS id FROM human_requests r JOIN node_rows n ON n.node_id = r.requester_node_id JOIN objects o ON o.id = n.node_id WHERE r.inbox_ticket_id IN (${a.map(()=>"?").join(",")}) AND ${n.sql}`).all(...a,...n.params);for(const c of i)s.add(c.id)}return s}d(He,"readableTicketIds");async function j(e,t,o){const n=U(e);return l(n)?!0:n.class==="anonymous"||n.class==="machine"||n.class==="import"?!1:k(n)===t?!0:m(await W(n),o)&&(!$(n)||m(n.scopes,o))}d(j,"mayReadApp");async function Ie(e,t,o){return o===void 0?await j(e,t,`crtr:conversations:read:${t}`):await f(e,"read",o)}d(Ie,"canReadRun");async function Fe(e,t,o=!1,n=!1){const s=await w(t);if(!s||s.parent!==null||s.run_id!==t||!s.grantee||s.deleting_at&&!n)throw new E(404,"not_found","run not found");if(!((!("class"in e)||e.class==="app"||e.class==="forwarded"&&e.actor.kind==="app")&&x(e)===s.grantee&&e.sub===s.sub)&&!await f(e,"read",t))throw new E(404,"not_found","run not found");if(o&&x(e)!==null&&x(e)!==s.grantee)throw new E(403,"other_app_run","cannot change another app's run");return await X(t,s.grantee,n)}d(Fe,"requireRun");async function re(e,t,o){return o===void 0?await j(e,t,`crtr:objects:read:${t}`):await f(e,"read",o)}d(re,"canReadNode");const P=new Set(["messages.post.58","messages.post.59"]);async function se(e,t,o){if(!e.classes.includes(t.class)&&!(t.class!=="anonymous"&&t.class!=="machine"&&t.class!=="import"&&t.class!=="forwarded"&&e.classes.includes("anonymous")))throw new u(403,"permission_error","this operation is not available to the caller");if(e.resource==="daemon-control"&&M())throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available on a shared cloud role");if(t.class==="forwarded"&&t.actor.kind==="app"&&await T(t),t.class==="anonymous"||t.class==="machine"||t.class==="import"||l(t))return;if(t.class==="person")return await ae(e,t,o);const n=await W(t);if(e.scope&&(!m(n,e.scope)||$(t)&&!m(t.scopes,e.scope)))throw new u(403,"scope_missing",`missing scope ${e.scope}`);if(t.class==="app")return;const s=k(t);t.class==="broker"&&await ce(e,t,o,n);const r=o.id;if((e.resource==="node-read"||e.resource==="node-write")&&r!==void 0){const a=await w(r);if(!a)return;if(e.resource==="node-write"){const i=P.has(e.name);if(a.grantee!==s&&!i)throw new u(403,"other_app_run","cannot change another app's node");if(!await f(t,i&&a.grantee!==s?"message":"read",r))throw a.grantee!==s?new u(403,"other_app_run","cannot change another app's node"):new u(404,"not_found","node not found")}if(e.resource==="node-read"&&!await f(t,"read",r))throw new u(404,"not_found","node not found")}}d(se,"authorizeOperation");async function ae(e,t,o){if(e.resource==="daemon-bash")throw new u(403,"permission_error","a shell on the daemon host is not available to a person bearer");if(e.resource==="daemon-control")throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available to a person bearer");if(e.resource==="human")return await de(e,t,o);if(o.request_id!==void 0&&e.path.startsWith("/v1/structured-requests/"))return await ue(e,t,o.request_id);const n=o.id;if(!(e.resource!=="node-read"&&e.resource!=="node-write"||n===void 0||!await w(n))&&!await f(t,P.has(e.name)?"message":"read",n))throw new u(404,"not_found","node not found")}d(ae,"authorizePersonNode");async function de(e,t,o){const n=o.ticket_id!==void 0?new u(404,"ticket_not_found","no matching ticket"):new u(404,"not_found","no request with that id"),s=o.request_id?await N(o.request_id):o.ticket_id?await C(o.ticket_id):null,r=o.comment_id?await q(o.comment_id):null,a=o.review_id?await v(o.review_id).catch(()=>null):r?await v(r.review_id).catch(()=>null):null;if((o.request_id??o.ticket_id??o.review_id??o.comment_id)===void 0)return;const c=s?.requester_node_id??a?.origin_node_id;if(!c||!await w(c)||!await f(t,e.method==="GET"?"read":"edit",c))throw n}d(de,"authorizePersonHuman");async function ue(e,t,o){const n=await oe(o);if(n!==null&&(n.node_id===null||!await w(n.node_id)||!await f(t,e.method==="GET"?"read":"edit",n.node_id)))throw new u(404,"structured_request_not_found",`unknown structured request: ${o}`)}d(ue,"authorizePersonStructuredRequest");async function ie(e,t,o){const n=o&&typeof o=="object"&&!Array.isArray(o)?o:{},s=e.path;if(e.method==="POST"&&(s==="/v1/human/requests"||s==="/v1/human/reviews")){const r=n.source,a=s.endsWith("/reviews")?n.origin_node_id:n.requester_node_id;if(typeof a!="string")throw new u(403,"permission_error","a request must name a node the person acts on");const i=s.endsWith("/requests")&&r&&typeof r=="object"&&"nodeId"in r?r.nodeId:void 0;for(const c of[a,i])if(c!==void 0&&(typeof c!="string"||!await w(c)||!await f(t,"edit",c)))throw new u(404,"not_found","node not found")}if(s==="/v1/structured-requests"){const r=n.target,a=r&&typeof r=="object"&&"kind"in r&&r.kind==="node"&&"node_id"in r?r.node_id:void 0;if(typeof a=="string"&&await w(a)&&!await f(t,"message",a))throw new u(404,"node_not_found",`unknown node: ${a}`)}}d(ie,"authorizePersonBody");async function ce(e,t,o,n){if(e.resource==="daemon-bash"&&(!m(n,"crtr:files:rw:user:.")||!m(t.scopes,"crtr:files:rw:user:.")))throw new u(403,"scope_missing","missing scope crtr:files:rw:user:.");if(e.resource==="human"){const r=e.path,a=e.method==="GET";if(!a&&(r.endsWith("/respond")||r.endsWith("/submit")||r.endsWith("/dismiss")||r.endsWith("/progress")||r.endsWith("/comment-ranges")||r.includes("/feedback-comments")))throw new u(403,"permission_error","only the person may answer or edit the human inbox");const i=o.request_id?await N(o.request_id):o.ticket_id?await C(o.ticket_id):null,c=o.comment_id?await q(o.comment_id):null,g=o.review_id?await v(o.review_id):c?await v(c.review_id):null,h=i?.requester_node_id??g?.origin_node_id;if(h!=null){const _=await w(h);if(_&&(a?!await re(t,_.grantee??"app:terminal",h):_.grantee!==t.app))throw new u(a?404:403,a?"not_found":"other_app_run","human request belongs to another app");if(_&&!a&&!await f(t,"read",h))throw new u(404,"not_found","human request not found")}else if(i||g)throw new u(403,"permission_error","only the person may access a request without a node")}const s=o.id;if(e.resource==="node-own"&&s!==void 0&&s!==t.node)throw new u(403,"other_app_run","the operation requires the calling node")}d(ce,"authorizeBrokerOnly");function fe(e,t){if(!m(e,t))throw new F("the bearer token",t)}d(fe,"assertCeiling");function we(){return new u(403,"owner_only","this operation is owner-only; a scoped token does not reach it")}d(we,"ownerOnlyError");const he="Crtr-Caused-By",me=/^(?:message|request|cron_run):[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function _e(e){const t=e[he.toLowerCase()];return typeof t=="string"&&me.test(t)?t:void 0}d(_e,"causedByOf");function Je(e){return e.map(t=>({...t,ownerOnly:!0}))}d(Je,"ownerOnly");class Me{static{d(this,"Router")}routes=[];register(t){const o=ee(t.method,t.pattern);if(!o)throw new Error(`route has no operation row: ${t.method} ${t.pattern}`);if(this.routes.some(n=>n.method===t.method.toUpperCase()&&n.operation.path===t.pattern))throw new Error(`duplicate route: ${t.method} ${t.pattern}`);return this.routes.push({operation:o,method:t.method.toUpperCase(),segments:z(t.pattern),handler:t.handler,maxBodyBytes:t.maxBodyBytes??te}),this}registerAll(t){for(const o of t)this.register(o);return this}match(t,o){const n=t.toUpperCase(),s=z(o);for(const r of this.routes){if(r.method!==n)continue;const a=le(r.segments,s);if(a!==null)return{handler:r.handler,params:a,operation:r.operation,maxBodyBytes:r.maxBodyBytes}}return null}async handle(t,o,n,s={class:"person"}){try{const r=new URL(t.url??"/","http://127.0.0.1"),a=(t.method??"GET").toUpperCase(),i=this.match(a,r.pathname);if(i===null){G(o,404,"not_found",`no route for ${a} ${r.pathname}`);return}if(await se(i.operation,s,i.params),n!==null){if(i.operation.classes.length===1&&i.operation.classes[0]==="person")throw we();i.operation.scope&&fe(n,i.operation.scope)}let c;try{c=await ge(t,i.maxBodyBytes)}catch(B){const R=B instanceof D?"payload_too_large":"invalid_request";G(o,R==="payload_too_large"?413:400,R,B.message);return}s.class==="person"&&s.sub!==void 0&&await ie(i.operation,s,c),s.class==="broker"&&i.operation.resource==="human"&&await ne(i.operation,s,i.params,r.searchParams,c);const g=_e(t.headers),h={...g===void 0?{}:{causedBy:g},method:a,path:r.pathname,params:i.params,query:r.searchParams,body:c,ceiling:n,principal:s,...s.class==="anonymous"&&typeof t.headers.authorization=="string"?{publishToken:t.headers.authorization.slice(7)}:{},req:t,res:o},_=await i.handler(h);o.writableEnded||ye(o,_)}catch(r){if(r instanceof Error&&r.code==="person_unresolved"){A(o,503,{error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}});return}const{status:a,body:i}=H(r);a>=500&&I({event:"api.request.failed",level:"error",error:r instanceof Error?r:new Error(String(r)),...s.class==="broker"?{node_id:s.node}:{},fields:{method:(t.method??"GET").toUpperCase(),path:t.url??""}}),A(o,a,i)}}}function z(e){return e.split("/").filter(t=>t.length>0)}d(z,"splitPath");function le(e,t){if(e.length!==t.length)return null;const o={};for(let n=0;n<e.length;n++){const s=e[n],r=t[n];if(s.startsWith(":"))o[s.slice(1)]=decodeURIComponent(r);else if(s!==r)return null}return o}d(le,"matchSegments");class D extends Error{static{d(this,"BodyTooLargeError")}}async function ge(e,t){const o=[];let n=0;for await(const r of e){const a=r;if(n+=a.length,n>t)throw new D(`request body exceeds ${t} bytes`);o.push(a)}if(n===0)return;const s=Buffer.concat(o).toString("utf8").trim();if(s!=="")try{return JSON.parse(s)}catch{throw new Error("request body is not valid JSON")}}d(ge,"readJsonBody");function ye(e,t){if(e.headersSent)return;const o={...t.headers??{}};if(t.rawBody!==void 0){e.writeHead(t.status,o),e.end(t.rawBody);return}if(t.status===204||t.body===void 0){e.writeHead(t.status,o),e.end();return}o["content-type"]===void 0&&(o["content-type"]="application/json; charset=utf-8"),e.writeHead(t.status,o),e.end(JSON.stringify(t.body))}d(ye,"writeResult");function A(e,t,o){if(e.headersSent){e.end();return}e.writeHead(t,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}d(A,"writeJson");function G(e,t,o,n){A(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(G,"writeError");export{he as CAUSED_BY_HEADER,Me as Router,l as actsAsPerson,k as appOf,fe as assertCeiling,$ as boundedByStoredScopes,re as canReadNode,Ie as canReadRun,_e as causedByOf,f as mayOnNode,Je as ownerOnly,we as ownerOnlyError,Le as readableAmong,Ge as readableNodeIds,He as readableTicketIds,Fe as requireRun,W as resolvedScopes,x as runCallerApp};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var H=Object.defineProperty;var o=(t,r)=>H(t,"name",{value:r,configurable:!0});import{chmodSync as U,closeSync as G,existsSync as L,mkdirSync as b,openSync as N,unlinkSync as J,writeFileSync as Y,rmSync as M}from"node:fs";import{createServer as K}from"node:http";import{dirname as X,join as z}from"node:path";import{spawn as F}from"node:child_process";import{SELF_UPDATE_SCRIPT as V}from"../core/self-update.js";import{apiSocketPath as W,crtrHome as P}from"../core/canvas/paths.js";import{bindDaemonEventSource as $}from"../core/events/source.js";import{emitEvent as a}from"../core/events/emit.js";import{brokerCommandDeclaresCanvasHome as Q}from"../core/runtime/broker-ownership.js";import{createMachineExecutor as Z,findBrokers as q,stopAllBrokers as ee}from"../core/runtime/runner/machine/executor.js";import{machineCheckoutHandlers as ne}from"../core/checkout-identities.js";import{machineWorktreeHandlers as te}from"../core/worktree-machine.js";import{readPersonCredential as oe}from"../core/directory/person-credential.js";import{socketDir as re}from"../core/layout.js";import{isDaemonRunning as ie,pidfilePath as y,readPidfile as ae}from"./pidfile.js";import{spawnDaemon as se}from"./manage.js";import{processGeneration as ce}from"../commands/sys/shared.js";import{cancelMachineCron as de,runMachineCron as le,stopOrphanedMachineCrons as me}from"./cron/machine-exec.js";import{startMachineLink as fe}from"./machine-link/client.js";import{readMachineConfig as pe,readMachineCredential as C}from"./machine-link/config.js";import{jobExitReporting as ue,stopMachineJob as he}from"./machine-link/job-sweep.js";import{machineSupervision as ve,SUPERVISION_TICK_MS as we}from"./machine-supervision.js";import{startBrokerMemoryCap as _e}from"./broker-memory-cap.js";const D=10*6e4,Se=3e4,ye=75;let g=0;function ge(t,r){if(Date.now()-g<D||!/^\d+\.\d+\.\d+$/.test(t))return;g=Date.now(),a({level:"warn",event:"daemon.machine.updating",fields:{release:t}});const s=N(z(P(),"crtrd.err"),"a"),i=F(process.execPath,[V,"--version",t],{stdio:["ignore",s,s]});G(s),i.on("error",c=>a({level:"error",event:"daemon.machine.update_failed",fields:{release:t},error:c})),i.on("exit",c=>{if(c===ye){g=Date.now()-D+Se;return}if(c!==0){a({level:"error",event:"daemon.machine.update_failed",fields:{release:t,exit_code:c}});return}r()})}o(ge,"updateToRelease");const R=1024;function Ie(t,r){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:t,signed_in:r,generation_id:ce()?.id??null,startup_phase:t?"ready":"recovering"}}o(Ie,"machineHealth");async function Ve(){const t=pe();if(t===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const r=oe()!==void 0;if(r&&C(),ie())throw new Error("a crtrd is already running for this home");$(),r||(await ee(),await me(),a({level:"info",event:"daemon.machine.signed_out",fields:{environment:t.environmentId}})),b(re(),{recursive:!0,mode:493});const s=W();L(s)&&J(s);let i;const c=ue(()=>i),f=K((e,n)=>{const d=(e.url??"").split("?")[0];if(e.method==="POST"&&(d==="/job-exit"||d==="/job-activity")){const k=[];let S=0;e.on("data",l=>{S+=l.length,S<=R&&k.push(l)}),e.on("end",()=>{if(S>R){n.writeHead(413),n.end();return}let l={};try{l=JSON.parse(Buffer.concat(k).toString("utf8"))}catch{}const T=typeof l.node=="string"&&typeof l.job=="string";n.writeHead(T?202:400,{"content-type":"application/json; charset=utf-8"}),n.end("{}"),T&&(d==="/job-exit"?c.notice:c.activity)(l.node,l.job)});return}const x=(e.method??"GET")==="GET"&&(e.url??"/").split("?")[0]==="/healthz";n.writeHead(x?200:404,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify(x?Ie(i?.connected()===!0,r):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((e,n)=>{f.once("error",n),f.listen(s,()=>{f.off("error",n),U(s,384),e()})}),b(X(y()),{recursive:!0}),Y(y(),String(process.pid),"utf8");let I;const u=new Set,h=new Set;let v=!1;const m=Z({apiUrl:t.apiUrl,environmentId:t.environmentId,onExit:o(e=>i?.reportExit(e),"onExit")}),O=o(async(e,n)=>{u.add(e.executionId);for(const d of h)d.add(e.executionId);try{return await m.start(e,n)}finally{u.delete(e.executionId)}},"start");i=r?fe({apiUrl:t.apiUrl,environmentId:t.environmentId,credential:C,onOpen:o(()=>{c.onOpen(),v=!0},"onOpen"),onBehind:o(e=>ge(e,B),"onBehind"),handlers:{start:O,wake:m.wake,stop:m.stop,status:m.status,delete:m.delete,viewer:m.viewer,"cron.run":le,"cron.cancel":de,"job.stop":o(e=>he(e),"job.stop"),...te,...ne}}):void 0;const E=i===void 0?void 0:ve({link:i,brokers:o(async()=>{const e=new Set(u);h.add(e);const n=await q().finally(()=>h.delete(e));return v&&(v=!1,i?.reportRunning([...new Set([...e,...n.filter(d=>Q(d.command,P())).map(d=>d.execution)])])),n},"brokers"),stop:o((e,n)=>m.stop({execution:{executionId:e,nodeId:n,attempt:0},options:{reason:"yield_stall"}}),"stop")});let w=!1;const j=E===void 0?void 0:setInterval(()=>{w||(w=!0,E(Date.now()).catch(e=>a({level:"error",event:"daemon.machine.supervision_failed",error:e})).finally(()=>{w=!1}))},we),A=_e();a({level:"info",event:"daemon.machine.started",fields:{environment:t.environmentId}}),r&&(async()=>{await(await import("../commands/person-settings.js")).loadPersonSettingsViaApi();const{installed:e,failed:n}=await(await import("../commands/pkg/account-installs.js")).installAccountPlugins();a({level:n.length>0?"warn":"info",event:"daemon.machine.account_plugins",fields:{installed:e,failed:n}})})().catch(e=>a({level:"warn",event:"daemon.machine.account_plugins_failed",error:e}));const _=o(()=>I??=(async()=>{i?.stop(),clearInterval(j),A(),await new Promise(e=>{f.close(()=>e()),f.closeAllConnections()}),ae()===process.pid&&(M(s,{force:!0}),M(y(),{force:!0})),process.off("SIGINT",p),process.off("SIGTERM",p)})(),"teardown"),B=o(async()=>{if(I===void 0){await _();try{const e=await se();a({level:"info",event:"daemon.machine.replaced",fields:{successor_pid:e.pid??e.existing_pid??null}}),process.exit(0)}catch(e){a({level:"error",event:"daemon.machine.successor_failed",error:e}),process.exit(1)}}},"replaceSelf"),p=o(()=>{_().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",p),process.on("SIGTERM",p),_}o(Ve,"runMachineDaemon");export{Ie as machineHealth,Ve as runMachineDaemon};
|
|
@@ -16,11 +16,11 @@ npm install -g @north-light/cli
|
|
|
16
16
|
crtr
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
The first time you run `crtr` on a machine, it opens the setup installer. Sign in to your Northlight account first (`crtr sys signin`, see [Sign in a machine to your Northlight account](/docs/cli/join-northlight)).
|
|
19
|
+
The first time you run `crtr` on a machine, it opens the setup installer. Sign in to your Northlight account first (`crtr sys signin`, see [Sign in a machine to your Northlight account](/docs/cli/join-northlight)). Signing in installs the plugins your account lists (a new account lists the official plugin marketplace and `capture`). The installer then offers system dependencies such as tmux. On a Mac, a last step explains how to make Option act as Alt in your terminal (crouter's menu is Alt+C), and can write the setting for you in Ghostty or VS Code after you confirm; until it is set, `/menu` opens the same menu. Next it asks which profile this directory belongs to, then opens a conversation with an agent in the same terminal. That first agent offers a short tour; say yes to learn the viewer, the inbox and document review, or just tell it what you're working on.
|
|
20
20
|
|
|
21
21
|
The conversation viewer is a tmux pane. If you ran `crtr` outside tmux, it starts tmux for you: after setup, the profile choice and sign-in, it opens a tmux session named `crouter` (or adds a window to it, if it already exists) and runs your same command there. Your other tmux sessions are left alone. If tmux is not installed, `crtr` tells you how to install it. The first conversation in a session that `crtr` started shows how to leave and come back: `Ctrl+B d` leaves tmux while the agent keeps running, and `Ctrl+B n` / `Ctrl+B p` switch windows. Run without a terminal (piped or in a script), `crtr` never starts tmux.
|
|
22
22
|
|
|
23
|
-
To reopen the installer later, for example to
|
|
23
|
+
To reopen the installer later, for example to install a missing dependency, run `crtr sys setup`. To add a plugin, run `crtr pkg plugin install <marketplace>/<plugin>`.
|
|
24
24
|
|
|
25
25
|
## Start a conversation
|
|
26
26
|
|
|
@@ -9,7 +9,7 @@ The official marketplace is a git repository, [`crouton-labs/crouter-official-ma
|
|
|
9
9
|
|
|
10
10
|
## Add the marketplace
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
A new Northlight account lists the official marketplace and the `capture` plugin, and a signed-in Mac installs whatever its account lists (after `crtr sys signin`, and when its daemon starts). To add the marketplace by hand:
|
|
13
13
|
|
|
14
14
|
```sh
|
|
15
15
|
crtr pkg market add https://github.com/crouton-labs/crouter-official-marketplace.git
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.785",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -157,8 +157,8 @@
|
|
|
157
157
|
},
|
|
158
158
|
"license": "UNLICENSED",
|
|
159
159
|
"dependencies": {
|
|
160
|
-
"@north-light/identity": "0.3.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
160
|
+
"@north-light/identity": "0.3.785",
|
|
161
|
+
"@north-light/plugin": "0.3.785",
|
|
162
162
|
"@earendil-works/chord": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -231,14 +231,18 @@ export async function ensureRootProfile() {
|
|
|
231
231
|
}
|
|
232
232
|
return await createProfile(ROOT_PROFILE_NAME, [], { grantee: 'app:terminal' });
|
|
233
233
|
}
|
|
234
|
-
// A
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
234
|
+
// A profile runs on the machine its `environment_id` names, so a signed-in computer reuses only a root made for this machine. The account's
|
|
235
|
+
// root of another computer would start every root node there, and that computer refuses the cwd it does not have.
|
|
236
|
+
const machine = readMachineConfig();
|
|
237
|
+
const ownRoot = (p) => p.manifest.environment_id === machine?.environmentId;
|
|
238
|
+
const existing = [getStoredProfile(ROOT_PROFILE_ID), ...listProfiles().filter((p) => p.manifest.name === ROOT_PROFILE_NAME && profileApp(p.manifest) === 'app:terminal')]
|
|
239
|
+
.find((p) => p !== null && ownRoot(p)) ?? null;
|
|
238
240
|
if (existing !== null) {
|
|
239
241
|
scaffoldProfile(existing.profileId, existing.manifest);
|
|
240
242
|
return existing;
|
|
241
243
|
}
|
|
244
|
+
if (machine !== undefined)
|
|
245
|
+
return await createProfile(ROOT_PROFILE_NAME, [], { grantee: 'app:terminal' });
|
|
242
246
|
const next = {
|
|
243
247
|
schema_version: SCHEMA_VERSION,
|
|
244
248
|
name: ROOT_PROFILE_NAME,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.785",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.785",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.785",
|
|
31
|
+
"@north-light/identity": "0.3.785"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.785",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.785",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.785",
|
|
32
|
+
"@north-light/plugin": "0.3.785",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -11902,17 +11902,17 @@
|
|
|
11902
11902
|
},
|
|
11903
11903
|
"packages/crouter-api": {
|
|
11904
11904
|
"name": "@north-light/api",
|
|
11905
|
-
"version": "0.3.
|
|
11905
|
+
"version": "0.3.785",
|
|
11906
11906
|
"license": "UNLICENSED"
|
|
11907
11907
|
},
|
|
11908
11908
|
"packages/crouter-env-docker": {
|
|
11909
11909
|
"name": "@north-light/env-docker",
|
|
11910
|
-
"version": "0.3.
|
|
11910
|
+
"version": "0.3.785",
|
|
11911
11911
|
"license": "UNLICENSED"
|
|
11912
11912
|
},
|
|
11913
11913
|
"packages/crouter-identity": {
|
|
11914
11914
|
"name": "@north-light/identity",
|
|
11915
|
-
"version": "0.3.
|
|
11915
|
+
"version": "0.3.785",
|
|
11916
11916
|
"license": "UNLICENSED",
|
|
11917
11917
|
"dependencies": {
|
|
11918
11918
|
"jose": "^6.2.1"
|
|
@@ -11920,21 +11920,21 @@
|
|
|
11920
11920
|
},
|
|
11921
11921
|
"packages/crouter-plugin": {
|
|
11922
11922
|
"name": "@north-light/plugin",
|
|
11923
|
-
"version": "0.3.
|
|
11923
|
+
"version": "0.3.785",
|
|
11924
11924
|
"license": "UNLICENSED",
|
|
11925
11925
|
"dependencies": {
|
|
11926
|
-
"@north-light/api": "0.3.
|
|
11927
|
-
"@north-light/identity": "0.3.
|
|
11926
|
+
"@north-light/api": "0.3.785",
|
|
11927
|
+
"@north-light/identity": "0.3.785"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.785",
|
|
11933
11933
|
"license": "UNLICENSED",
|
|
11934
11934
|
"dependencies": {
|
|
11935
|
-
"@north-light/api": "0.3.
|
|
11936
|
-
"@north-light/identity": "0.3.
|
|
11937
|
-
"@north-light/plugin": "0.3.
|
|
11935
|
+
"@north-light/api": "0.3.785",
|
|
11936
|
+
"@north-light/identity": "0.3.785",
|
|
11937
|
+
"@north-light/plugin": "0.3.785",
|
|
11938
11938
|
"jose": "^6.2.1"
|
|
11939
11939
|
},
|
|
11940
11940
|
"bin": {
|