@north-light/cli 0.3.674 → 0.3.676

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.
Files changed (44) hide show
  1. package/dist/clients/attach/session/connection.d.ts +2 -1
  2. package/dist/clients/attach/session/connection.js +1 -1
  3. package/dist/clients/attach/viewer.d.ts +11 -1
  4. package/dist/clients/attach/viewer.js +524 -524
  5. package/dist/commands/person-settings.d.ts +5 -0
  6. package/dist/commands/person-settings.js +1 -1
  7. package/dist/core/graph/reader.d.ts +2 -1
  8. package/dist/core/graph/reader.js +3 -3
  9. package/dist/core/graph/repo-sync/repos.d.ts +24 -3
  10. package/dist/core/graph/repo-sync/repos.js +4 -4
  11. package/dist/core/profiles/select.d.ts +3 -1
  12. package/dist/core/profiles/select.js +25 -25
  13. package/dist/core/runtime/bearings.d.ts +3 -3
  14. package/dist/core/runtime/bearings.js +6 -6
  15. package/dist/core/runtime/boot-root.d.ts +3 -3
  16. package/dist/core/runtime/boot-root.js +6 -4
  17. package/dist/core/runtime/deliver-live.js +1 -1
  18. package/dist/core/runtime/front-door.js +1 -1
  19. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  20. package/dist/core/runtime/starting-screen.d.ts +12 -0
  21. package/dist/core/runtime/starting-screen.js +9 -0
  22. package/dist/core/substrate/delivery/deliver.d.ts +1 -1
  23. package/dist/core/substrate/delivery/deliver.js +3 -3
  24. package/dist/core/substrate/subject.d.ts +3 -1
  25. package/dist/core/substrate/subject.js +1 -1
  26. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  27. package/dist/daemon/api/handlers/delivery.js +1 -1
  28. package/package.json +3 -3
  29. package/packages/crouter-api/dist/clients/attach/session/connection.js +3 -2
  30. package/packages/crouter-api/dist/clients/attach/viewer.js +16 -7
  31. package/packages/crouter-api/dist/commands/person-settings.js +10 -3
  32. package/packages/crouter-api/dist/core/graph/reader.js +9 -4
  33. package/packages/crouter-api/dist/core/graph/repo-sync/repos.js +56 -13
  34. package/packages/crouter-api/dist/core/profiles/select.js +17 -7
  35. package/packages/crouter-api/dist/core/runtime/bearings.js +11 -12
  36. package/packages/crouter-api/dist/core/runtime/deliver-live.js +1 -1
  37. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +13 -5
  38. package/packages/crouter-api/dist/core/substrate/delivery/deliver.js +3 -3
  39. package/packages/crouter-api/dist/core/substrate/subject.js +4 -4
  40. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +6 -4
  41. package/packages/crouter-api/package.json +1 -1
  42. package/packages/crouter-identity/package.json +1 -1
  43. package/packages/crouter-plugin/package.json +3 -3
  44. package/runtime.lock.json +14 -14
@@ -1 +1,6 @@
1
+ import type { PersonSettingsDTO } from '../api/index.js';
2
+ /** This process's live settings (every write it has made included), for handing to a viewer bundle that holds its own cache. */
3
+ export declare function loadedPersonSettings(): PersonSettingsDTO;
1
4
  export declare function loadPersonSettingsViaApi(): Promise<void>;
5
+ /** Install a settings answer already in hand (no request) and wire this process's reload and write transports. */
6
+ export declare function installPersonSettingsDto(loaded: PersonSettingsDTO): void;
@@ -1 +1 @@
1
- var a=Object.defineProperty;var r=(t,e)=>a(t,"name",{value:e,configurable:!0});import{ApiError as p}from"../api/index.js";import{setPersonId as c}from"../core/canvas/person-state.js";import{installPersonSnapshot as f,setSettingsReloader as g,setSettingsTransport as m,SettingsRevisionConflictError as l}from"../core/scoped-state/person-store.js";import{cliClient as n}from"./api-client.js";const s=r(t=>t.snapshot,"fromDto");async function y(){const t=await n().getSettings();c(t.person),f(t.person,s(t)),g(async()=>s(await n().getSettings())),m(async(e,i)=>{try{return s(await n().putSettings({ops:i}))}catch(o){throw o instanceof p&&o.status===409?new l:o}})}r(y,"loadPersonSettingsViaApi");export{y as loadPersonSettingsViaApi};
1
+ var a=Object.defineProperty;var n=(t,e)=>a(t,"name",{value:e,configurable:!0});import{ApiError as p}from"../api/index.js";import{personId as c,setPersonId as f}from"../core/canvas/person-state.js";import{currentSnapshot as g,installPersonSnapshot as S,setSettingsReloader as m,setSettingsTransport as l,SettingsRevisionConflictError as u}from"../core/scoped-state/person-store.js";import{cliClient as r}from"./api-client.js";const s=n(t=>t.snapshot,"fromDto");function A(){return{person:c(),snapshot:g()}}n(A,"loadedPersonSettings");async function C(){h(await r().getSettings())}n(C,"loadPersonSettingsViaApi");function h(t){f(t.person),S(t.person,s(t)),m(async()=>s(await r().getSettings())),l(async(e,i)=>{try{return s(await r().putSettings({ops:i}))}catch(o){throw o instanceof p&&o.status===409?new u:o}})}n(h,"installPersonSettingsDto");export{h as installPersonSettingsDto,C as loadPersonSettingsViaApi,A as loadedPersonSettings};
@@ -2,9 +2,10 @@ import type { RequestPrincipal } from '../../daemon/api/router.js';
2
2
  import { type ActiveGrant } from '../grants/mirror.js';
3
3
  import { type CanvasDb } from '../canvas/db.js';
4
4
  import type { Checkout, ObjectRow, Reader } from './types.js';
5
+ import { type ReadAccess } from './repo-sync/repos.js';
5
6
  import type { ProfileProject } from '../../api/dto/profiles.js';
6
7
  /** The repos enclosing a directory, with their checkout roots, nearest first. `person` is whose read permission filters them (default: the request's person). */
7
- export type ReposFn = (cwd: string, person?: string) => Promise<Checkout[]>;
8
+ export type ReposFn = (cwd: string, person?: string, access?: ReadAccess) => Promise<Checkout[]>;
8
9
  /** A node's view of repos: for the checkouts enclosing its cwd, every repo object of their remotes the person may read (own first, then oldest), then
9
10
  * the repos its profile names (an entry's `repo`, and the checkouts of its `path`), in manifest order, each repo once. A repo entry needs no folder or
10
11
  * git; one the person may not read adds nothing. A project path that no longer exists, is not in a repo, or has no work tree contributes nothing. */
@@ -1,3 +1,3 @@
1
- var M=Object.defineProperty;var s=(o,e)=>M(o,"name",{value:e,configurable:!0});import{coveredByAny as h,isSandboxedNode as $}from"../../shared/env.js";import{projectPaths as H}from"../../api/dto/profiles.js";import{existsSync as N}from"node:fs";import{CrtrError as W}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as F}from"@north-light/identity";import{activeGrant as b,grantFor as C,runtimeScope as D}from"../grants/mirror.js";import{withCanvasWrite as B}from"../canvas/db.js";import{ApiError as J}from"../../api/errors.js";import{pluginAppToken as P}from"../secrets.js";import{loadExactProfileManifest as k}from"../profiles/manifest.js";import{ensureOwner as x,getById as G,nodeObject as q,ownerForGrantee as U,profileHandle as Y}from"./objects.js";import{personId as z,personIdAsync as K}from"../canvas/person.js";import{OBJECT_TYPE as Q}from"../permissions/builtin.js";import{warmCheckoutDirs as A}from"../checkout-identities.js";import{fillProfileProjectRepo as V}from"../profiles/manifest.js";import{emitEvent as X}from"../events/emit.js";import{isCloudRole as y}from"../canvas/person-state.js";import{mayRead as Z,reposForCwd as I,warmCheckoutIdentities as S}from"./repo-sync/repos.js";async function L(o,e,t,r,n,a){const l=t===null?[]:n.projects(t),c=await r(e,a),p=new Set(c.map(u=>u.repo.id)),f=[],d=[];for(const u of l){if(u.repo!==void 0&&!p.has(u.repo)){const i=await n.object(u.repo);i!==null&&i.type==="repo"&&i.deleted_at===null&&await Z(o,a??await K(),i.id)&&(p.add(i.id),f.push(i))}if(u.path===void 0||!y()&&!N(u.path))continue;let w;try{w=await r(u.path,a)}catch(i){if(i instanceof W&&i.code==="git-lookup-failed")continue;throw i}for(const i of w)p.has(i.repo.id)||(p.add(i.repo.id),f.push(i.repo),d.push(i))}return{repos:c.map(u=>u.repo),checkouts:c,projectRepos:f,projectCheckouts:d}}s(L,"viewRepos");async function Ne(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?H(g(o).projects(t.profile_id)):[];if(y()){await ee(t.profile_id,[t.cwd,...r]);return}await S(t.cwd);for(const n of r)N(n)&&await S(n)}s(Ne,"warmNodeRepos");async function ee(o,e){if(await A(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await B(async n=>await I(n,t.path)))[0];r!==void 0&&await V(o,t.path,r.id)}catch(r){X({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(ee,"warmCloudNodeCheckouts");async function ve(o,e,t){if(!y()){for(const n of t)await S(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await A(r?.profile_id,t)}s(ve,"warmNodeDirs");async function Fe(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await O(o)};if(e.class==="app")return{class:"app",app:await _(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await O(o)};const c=await C(e.actor.app,e.sub);if(!c)throw new J(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const p=e.actor.node_scopes;return{class:"app",app:await _(o,e.actor.app),place:e.actor.place,launched:p,scopes:p===null?c.resolved:p.filter(f=>h(c.resolved,f))}}if(e.class==="cron"){const c=e.grant?(await b(e.grant))?.resolved??[]:[],p=e.scopes;return{class:"app",app:await _(o,e.app),scopes:p===null?c:p.filter(f=>h(c,f)),launched:p,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=g(o),n=await q(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),l=a.app===null?null:await r.object(a.app);if(!l)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:l,scopes:await T(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await L(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,l)}}s(Fe,"readerFor");async function oe(o,e,t,r=g(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),l=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
2
- sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!l)throw new Error(`no node ${e}`);const{grantee:c,sub:p,grant_id:f,scopes_json:d,cwd:u,profile_id:w,app:i}=l,E=i===null?null:await r.object(i);if(!E)throw new Error(`node ${e} has no app`);const j=d===null?null:JSON.parse(d);return{class:"node",node:a,app:E,scopes:await T(c,p??"",f,j,r,n),launched:j,cwd:u,...await L(o,u,w,t,r,p||void 0),profile:w===null?null:await r.profile(w,E)}}s(oe,"readerForNode");class te extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function be(o,e,t=async()=>[],r=g(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await ne(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await oe(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const c=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!c)throw new te;const p=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(c.id))?.external_id??"app:terminal",f=D(),d=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${f.sql}`).all(p,...f.args),u=s(m=>JSON.parse(m.resolved_scopes_json).filter(R=>R.mode==="always").map(R=>F(R.scope)),"always"),w=d.length>1&&a.type==="app"?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(Q,e.id)).map(m=>m.subject_id)):null,i=w===null?void 0:d.find(m=>w.has(m.sub.replace(/^user:/,"")))?.sub,E=i===void 0?null:await r.grantFor(p,i),j=a.type==="person"?null:d.length===0?r.pluginScopes(p):d.length===1?u(d[0]):E?.resolved??null;return{class:"object",object:e,node:e,owner:a,app:c,scopes:j,...E===null?{}:{sub:E.sub},repos:a.type==="repo"?[a]:[]}}s(be,"readerForObject");async function Ce(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>F(a.scope))}s(Ce,"appScopesNow");async function ne(o,e,t,r){const n=await O(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await _(o,t.app),l=t?.app==null?null:await r.grantFor(t.app,t.sub),c=t===null||l===null?null:t.node_scopes===null?l.resolved:t.node_scopes.filter(f=>h(l.resolved,f)),p=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:p,app:p,scopes:c,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(ne,"readerForStub");function g(o){return{grantById:b,grantFor:C,pluginScopes:s(e=>P(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await G(o,e),"object"),profile:s(async(e,t)=>await re(o,e,t),"profile"),projects:s(e=>$()?[]:v(e)?.manifest.projects??[],"projects")}}s(g,"liveLookups");function xe(o){const e=g(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(xe,"publishLookups");async function T(o,e,t,r,n,a=!1){const l=t?await n.grantById(t):await n.grantFor(o,e),c=l&&l.grantee===o?l.resolved:null;if(c===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?c:r.filter(p=>h(c,p))}s(T,"nodeScopes");async function O(o){return await U(o,z())}s(O,"personObject");async function _(o,e){return await x(o,"app","app",e,e.replace(/^app:/,""))}s(_,"appObject");async function re(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
- WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await x(o,"profile","profile",e,Y(e,k(e).manifest.name),t)}s(re,"profileObject");export{te as NoOwningAppError,Ce as appScopesNow,g as liveLookups,re as profileObject,xe as publishLookups,Fe as readerFor,oe as readerForNode,be as readerForObject,L as viewRepos,ee as warmCloudNodeCheckouts,ve as warmNodeDirs,Ne as warmNodeRepos};
1
+ var $=Object.defineProperty;var s=(o,e)=>$(o,"name",{value:e,configurable:!0});import{coveredByAny as j,isSandboxedNode as H}from"../../shared/env.js";import{projectPaths as W}from"../../api/dto/profiles.js";import{existsSync as S}from"node:fs";import{CrtrError as D}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as F}from"@north-light/identity";import{activeGrant as C,grantFor as b,runtimeScope as B}from"../grants/mirror.js";import{withCanvasWrite as J}from"../canvas/db.js";import{ApiError as P}from"../../api/errors.js";import{pluginAppToken as k}from"../secrets.js";import{loadExactProfileManifest as G}from"../profiles/manifest.js";import{ensureOwner as x,getById as q,nodeObject as U,ownerForGrantee as Y,profileHandle as z}from"./objects.js";import{personId as K,personIdAsync as A}from"../canvas/person.js";import{OBJECT_TYPE as Q}from"../permissions/builtin.js";import{warmCheckoutDirs as L}from"../checkout-identities.js";import{fillProfileProjectRepo as V}from"../profiles/manifest.js";import{emitEvent as X}from"../events/emit.js";import{isCloudRole as _}from"../canvas/person-state.js";import{loadReadAccess as Z,mayRead as I,prefetchRepoReads as ee,reposForCwd as oe,warmCheckoutIdentities as O}from"./repo-sync/repos.js";async function M(o,e,t,r,n,a){const u=t===null?[]:n.projects(t),c=u.length===0?void 0:a??await A(),p=c===void 0?void 0:await Z(o,c);p!==void 0&&c!==void 0&&await ee(o,c,[e,...u.flatMap(i=>i.path!==void 0&&(_()||S(i.path))?[i.path]:[])],p);const f=await r(e,a,p),d=new Set(f.map(i=>i.repo.id)),m=[],E=[];for(const i of u){if(i.repo!==void 0&&!d.has(i.repo)){const l=await n.object(i.repo);l!==null&&l.type==="repo"&&l.deleted_at===null&&await I(o,c??a??await A(),l.id,p)&&(d.add(l.id),m.push(l))}if(i.path===void 0||!_()&&!S(i.path))continue;let w;try{w=await r(i.path,a,p)}catch(l){if(l instanceof D&&l.code==="git-lookup-failed")continue;throw l}for(const l of w)d.has(l.repo.id)||(d.add(l.repo.id),m.push(l.repo),E.push(l))}return{repos:f.map(i=>i.repo),checkouts:f,projectRepos:m,projectCheckouts:E}}s(M,"viewRepos");async function Fe(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?W(h(o).projects(t.profile_id)):[];if(_()){await te(t.profile_id,[t.cwd,...r]);return}await O(t.cwd);for(const n of r)S(n)&&await O(n)}s(Fe,"warmNodeRepos");async function te(o,e){if(await L(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await J(async n=>await oe(n,t.path)))[0];r!==void 0&&await V(o,t.path,r.id)}catch(r){X({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(te,"warmCloudNodeCheckouts");async function Ce(o,e,t){if(!_()){for(const n of t)await O(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await L(r?.profile_id,t)}s(Ce,"warmNodeDirs");async function be(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await N(o)};if(e.class==="app")return{class:"app",app:await R(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await N(o)};const c=await b(e.actor.app,e.sub);if(!c)throw new P(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const p=e.actor.node_scopes;return{class:"app",app:await R(o,e.actor.app),place:e.actor.place,launched:p,scopes:p===null?c.resolved:p.filter(f=>j(c.resolved,f))}}if(e.class==="cron"){const c=e.grant?(await C(e.grant))?.resolved??[]:[],p=e.scopes;return{class:"app",app:await R(o,e.app),scopes:p===null?c:p.filter(f=>j(c,f)),launched:p,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=h(o),n=await U(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),u=a.app===null?null:await r.object(a.app);if(!u)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:u,scopes:await T(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await M(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,u)}}s(be,"readerFor");async function ne(o,e,t,r=h(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),u=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
2
+ sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!u)throw new Error(`no node ${e}`);const{grantee:c,sub:p,grant_id:f,scopes_json:d,cwd:m,profile_id:E,app:i}=u,w=i===null?null:await r.object(i);if(!w)throw new Error(`node ${e} has no app`);const l=d===null?null:JSON.parse(d);return{class:"node",node:a,app:w,scopes:await T(c,p??"",f,l,r,n),launched:l,cwd:m,...await M(o,m,E,t,r,p||void 0),profile:E===null?null:await r.profile(E,w)}}s(ne,"readerForNode");class re extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function xe(o,e,t=async()=>[],r=h(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await ae(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ne(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const c=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!c)throw new re;const p=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(c.id))?.external_id??"app:terminal",f=B(),d=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${f.sql}`).all(p,...f.args),m=s(g=>JSON.parse(g.resolved_scopes_json).filter(y=>y.mode==="always").map(y=>F(y.scope)),"always"),E=d.length>1&&a.type==="app"?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(Q,e.id)).map(g=>g.subject_id)):null,i=E===null?void 0:d.find(g=>E.has(g.sub.replace(/^user:/,"")))?.sub,w=i===void 0?null:await r.grantFor(p,i),l=a.type==="person"?null:d.length===0?r.pluginScopes(p):d.length===1?m(d[0]):w?.resolved??null;return{class:"object",object:e,node:e,owner:a,app:c,scopes:l,...w===null?{}:{sub:w.sub},repos:a.type==="repo"?[a]:[]}}s(xe,"readerForObject");async function Ae(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>F(a.scope))}s(Ae,"appScopesNow");async function ae(o,e,t,r){const n=await N(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await R(o,t.app),u=t?.app==null?null:await r.grantFor(t.app,t.sub),c=t===null||u===null?null:t.node_scopes===null?u.resolved:t.node_scopes.filter(f=>j(u.resolved,f)),p=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:p,app:p,scopes:c,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(ae,"readerForStub");function h(o){return{grantById:C,grantFor:b,pluginScopes:s(e=>k(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await q(o,e),"object"),profile:s(async(e,t)=>await se(o,e,t),"profile"),projects:s(e=>H()?[]:v(e)?.manifest.projects??[],"projects")}}s(h,"liveLookups");function Le(o){const e=h(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(Le,"publishLookups");async function T(o,e,t,r,n,a=!1){const u=t?await n.grantById(t):await n.grantFor(o,e),c=u&&u.grantee===o?u.resolved:null;if(c===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?c:r.filter(p=>j(c,p))}s(T,"nodeScopes");async function N(o){return await Y(o,K())}s(N,"personObject");async function R(o,e){return await x(o,"app","app",e,e.replace(/^app:/,""))}s(R,"appObject");async function se(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
+ WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await x(o,"profile","profile",e,z(e,G(e).manifest.name),t)}s(se,"profileObject");export{re as NoOwningAppError,Ae as appScopesNow,h as liveLookups,se as profileObject,Le as publishLookups,be as readerFor,ne as readerForNode,xe as readerForObject,M as viewRepos,te as warmCloudNodeCheckouts,Ce as warmNodeDirs,Fe as warmNodeRepos};
@@ -1,6 +1,8 @@
1
1
  import type { Checkout, ObjectRow } from '../types.js';
2
2
  import { handleHint } from './identity.js';
3
3
  import type { CanvasDb } from '../../canvas/db.js';
4
+ import { subjectSet } from '../../permissions/evaluator.js';
5
+ import { loadDefinitions } from '../../permissions/schemas.js';
4
6
  export { handleHint };
5
7
  export interface RepoIdentity {
6
8
  scheme: 'git' | 'local-path';
@@ -10,14 +12,33 @@ export interface RepoIdentity {
10
12
  /** The repo object of the person this request runs as for an identity, created on first sight. A handle already
11
13
  * held by another repo gets `-2`, `-3`, … appended. */
12
14
  export declare function ensureRepo(db: CanvasDb, id: RepoIdentity, handle?: string): Promise<ObjectRow>;
15
+ /** What a permission check on repos needs from the database: the schema definitions and the person's subject set. A caller checking many
16
+ * repos for one person in one request loads it once and passes it down. */
17
+ export interface ReadAccess {
18
+ defs: Awaited<ReturnType<typeof loadDefinitions>>;
19
+ subjects: Awaited<ReturnType<typeof subjectSet>>;
20
+ /** Filled by `prefetchRepoReads`: the answer of `readableRepos` per `scheme\0externalId`, and every local-path repo identity. */
21
+ readable?: Map<string, {
22
+ readable: ObjectRow[];
23
+ heldByPerson: boolean;
24
+ }>;
25
+ localPaths?: Array<ObjectRow & {
26
+ path: string;
27
+ person: string;
28
+ }>;
29
+ }
30
+ export declare function loadReadAccess(db: CanvasDb, person: string): Promise<ReadAccess>;
13
31
  /** Whether `person` may read the object `id` by permission facts alone (no ceiling): the gate for a repo a profile names. */
14
- export declare function mayRead(db: CanvasDb, person: string, id: string): Promise<boolean>;
32
+ export declare function mayRead(db: CanvasDb, person: string, id: string, access?: ReadAccess): Promise<boolean>;
15
33
  /** The repo objects of one remote identity, any person's, that `person` may read (permission facts only, no ceiling), the person's own first and
16
34
  * then by age, oldest first. `heldByPerson` says whether the person has an identity row for it at all, readable or not. */
17
- export declare function readableRepos(db: CanvasDb, person: string, scheme: string, externalId: string): Promise<{
35
+ export declare function readableRepos(db: CanvasDb, person: string, scheme: string, externalId: string, access?: ReadAccess): Promise<{
18
36
  readable: ObjectRow[];
19
37
  heldByPerson: boolean;
20
38
  }>;
39
+ /** For a request that resolves many directories for one person: read once what each `checkoutsForCwd` would read per directory (the readable
40
+ * repos of every git identity in `dirs`, and the local-path repos) and store it on `access`. */
41
+ export declare function prefetchRepoReads(db: CanvasDb, person: string, dirs: readonly string[], access: ReadAccess): Promise<void>;
21
42
  /** Repos enclosing `cwd`, nearest first: every enclosing git checkout (created
22
43
  * on first sight) and every existing local-path repo whose path is `cwd` or
23
44
  * an ancestor of it. A non-git folder is never created here. */
@@ -28,4 +49,4 @@ export declare function warmCheckoutIdentities(cwd: string): Promise<void>;
28
49
  /** `reposForCwd` with the directory each repo is checked out at. Each git checkout yields every repo object of its remote that `person` (default: the
29
50
  * request's person) may read: their own first, then the others oldest first. A personal repo object is created only when the person holds none for the
30
51
  * remote; one they hold but may no longer read (a group they left) contributes nothing. */
31
- export declare function checkoutsForCwd(db: CanvasDb, cwd: string, person?: string): Promise<Checkout[]>;
52
+ export declare function checkoutsForCwd(db: CanvasDb, cwd: string, person?: string, access?: ReadAccess): Promise<Checkout[]>;
@@ -1,4 +1,4 @@
1
- var C=Object.defineProperty;var c=(o,t)=>C(o,"name",{value:t,configurable:!0});import{resolve as f,sep as u}from"node:path";import{CrtrError as k}from"../../errors.js";import{realpathOrSelf as w}from"../../fs-utils.js";import{ExitCode as O}from"../../../types.js";import{personIdAsync as d}from"../../canvas/person.js";import{ensureOwner as R}from"../objects.js";import{checkoutChain as _,handleHint as g}from"./identity.js";import{checkoutChainOf as L}from"../../checkout-identities.js";import{subjectSet as E}from"../../permissions/evaluator.js";import{loadDefinitions as N}from"../../permissions/schemas.js";import{compilePermission as x}from"../../permissions/compile.js";import{f as D,raw as I}from"../../permissions/sql.js";import{OBJECT_TYPE as y}from"../../permissions/builtin.js";async function $(o,t,r,a){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
2
- WHERE o.type = 'repo' AND i.person = ? AND i.scheme = ? AND i.external_id = ?`).get(t,r,a)??null}c($,"existingRepo");async function j(o,t,r){const a=await $(o,await d(),t.scheme,t.externalId);if(a)return a;const n=r??t.handleHint;await o.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`repo-handle:${n}`);const m=o.prepare("SELECT 1 FROM objects WHERE name = ? AND type = 'repo' AND home_machine IS NULL");let s=n;for(let p=2;await m.get(s);p++)s=`${n}-${p}`;return await R(o,"repo",t.scheme,t.externalId,s)}c(j,"ensureRepo");async function Q(o,t,r){const a=x(await N(o),await E(o,t.replace(/^user:/,"")),y,"read",D`${r}::text`);return(await o.prepareUncached(`SELECT ${a.sql} AS ok`).get(...a.params))?.ok===!0}c(Q,"mayRead");async function T(o,t,r,a){const n=x(await N(o),await E(o,t.replace(/^user:/,"")),y,"read",I("o.id")),m=await o.prepareUncached(`SELECT o.*, i.person AS holder, ${n.sql} AS ok FROM identities i JOIN objects o ON o.id = i.object
3
- WHERE o.type = 'repo' AND o.deleted_at IS NULL AND i.scheme = ? AND i.external_id = ?`).all(...n.params,r,a),s=`user:${t.replace(/^user:/,"")}`,p=c(e=>e.holder===s&&e.owner===null,"own");return{readable:m.filter(e=>e.ok).sort((e,i)=>Number(p(i))-Number(p(e))||e.created_at.localeCompare(i.created_at)||e.seq-i.seq).map(({holder:e,ok:i,...l})=>l),heldByPerson:m.some(e=>e.holder===s)}}c(T,"readableRepos");async function V(o,t){return(await F(o,t)).map(r=>r.repo)}c(V,"reposForCwd");async function X(o){await _(w(f(o)))}c(X,"warmCheckoutIdentities");async function F(o,t,r){const a=w(f(t)),n=[];for(const e of await L(o,a,async()=>r??await d())){if(!e.ok)throw new k("git-lookup-failed",`cannot identify the repo at ${e.dir}: ${e.reason}`,O.GENERAL,{dir:e.dir});const i=r??await d(),{readable:l,heldByPerson:A}=await T(o,i,e.scheme,e.externalId);l.length===0&&!A&&l.push(await j(o,e));for(const S of l)n.push({root:e.root,repo:S})}const s=(await o.prepare(`SELECT o.*, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
4
- WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all()).filter(({path:e})=>a===e||a.startsWith(e.endsWith(u)?e:e+u)),p=s.length>0?r??await d():"";for(const{path:e,person:i,...l}of s)i===`user:${p.replace(/^user:/,"")}`&&n.push({root:e,repo:l});n.sort((e,i)=>i.root.length-e.root.length);const h=new Set;return n.filter(({repo:e})=>!h.has(e.id)&&(h.add(e.id),!0))}c(F,"checkoutsForCwd");export{F as checkoutsForCwd,j as ensureRepo,g as handleHint,Q as mayRead,T as readableRepos,V as reposForCwd,X as warmCheckoutIdentities};
1
+ var $=Object.defineProperty;var p=(e,o)=>$(e,"name",{value:o,configurable:!0});import{resolve as E,sep as N}from"node:path";import{CrtrError as R}from"../../errors.js";import{realpathOrSelf as y}from"../../fs-utils.js";import{ExitCode as O}from"../../../types.js";import{personIdAsync as x}from"../../canvas/person.js";import{ensureOwner as L}from"../objects.js";import{checkoutChain as j,handleHint as D}from"./identity.js";import{checkoutChainOf as S}from"../../checkout-identities.js";import{subjectSet as P}from"../../permissions/evaluator.js";import{loadDefinitions as T}from"../../permissions/schemas.js";import{compilePermission as A}from"../../permissions/compile.js";import{f as F,raw as b}from"../../permissions/sql.js";import{OBJECT_TYPE as k}from"../../permissions/builtin.js";async function M(e,o,r,n){return await e.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
2
+ WHERE o.type = 'repo' AND i.person = ? AND i.scheme = ? AND i.external_id = ?`).get(o,r,n)??null}p(M,"existingRepo");async function H(e,o,r){const n=await M(e,await x(),o.scheme,o.externalId);if(n)return n;const i=r??o.handleHint;await e.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`repo-handle:${i}`);const c=e.prepare("SELECT 1 FROM objects WHERE name = ? AND type = 'repo' AND home_machine IS NULL");let a=i;for(let s=2;await c.get(a);s++)a=`${i}-${s}`;return await L(e,"repo",o.scheme,o.externalId,a)}p(H,"ensureRepo");async function _(e,o){return{defs:await T(e),subjects:await P(e,o.replace(/^user:/,""))}}p(_,"loadReadAccess");async function ae(e,o,r,n){const{defs:i,subjects:c}=n??await _(e,o),a=A(i,c,k,"read",F`${r}::text`);return(await e.prepareUncached(`SELECT ${a.sql} AS ok`).get(...a.params))?.ok===!0}p(ae,"mayRead");async function W(e,o,r,n,i){const c=`${r}\0${n}`,a=i?.readable?.get(c);return a!==void 0?{readable:[...a.readable],heldByPerson:a.heldByPerson}:(await g(e,o,[{scheme:r,externalId:n}],i)).get(c)}p(W,"readableRepos");async function g(e,o,r,n){const{defs:i,subjects:c}=n??await _(e,o),a=A(i,c,k,"read",b("o.id")),s=r.length===0?[]:await e.prepareUncached(`SELECT o.*, i.person AS holder, i.scheme AS id_scheme, i.external_id AS id_external, ${a.sql} AS ok FROM identities i JOIN objects o ON o.id = i.object
3
+ WHERE o.type = 'repo' AND o.deleted_at IS NULL AND (i.scheme, i.external_id) IN (SELECT * FROM unnest(?::text[], ?::text[]))`).all(...a.params,r.map(t=>t.scheme),r.map(t=>t.externalId)),m=`user:${o.replace(/^user:/,"")}`,w=p(t=>t.holder===m&&t.owner===null,"own"),u=new Map;for(const t of r){const d=s.filter(l=>l.id_scheme===t.scheme&&l.id_external===t.externalId),h=d.filter(l=>l.ok).sort((l,f)=>Number(w(f))-Number(w(l))||l.created_at.localeCompare(f.created_at)||l.seq-f.seq).map(({holder:l,ok:f,id_scheme:q,id_external:J,...I})=>I);u.set(`${t.scheme}\0${t.externalId}`,{readable:h,heldByPerson:d.some(l=>l.holder===m)})}return u}p(g,"readableReposFor");const C=p(async e=>await e.prepare(`SELECT o.*, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
4
+ WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all(),"localPathRepos");async function ne(e,o,r,n){const i=new Map;for(const c of r){let a;try{a=await S(e,y(E(c)),async()=>o)}catch(s){if(s instanceof R&&s.code==="git-lookup-failed")continue;throw s}for(const s of a)s.ok&&i.set(`${s.scheme}\0${s.externalId}`,{scheme:s.scheme,externalId:s.externalId})}n.readable=await g(e,o,[...i.values()],n),n.localPaths=await C(e)}p(ne,"prefetchRepoReads");async function ie(e,o){return(await B(e,o)).map(r=>r.repo)}p(ie,"reposForCwd");async function se(e){await j(y(E(e)))}p(se,"warmCheckoutIdentities");async function B(e,o,r,n){const i=y(E(o)),c=[];let a=n;for(const t of await S(e,i,async()=>r??await x())){if(!t.ok)throw new R("git-lookup-failed",`cannot identify the repo at ${t.dir}: ${t.reason}`,O.GENERAL,{dir:t.dir});const d=r??await x();a??=await _(e,d);const{readable:h,heldByPerson:l}=await W(e,d,t.scheme,t.externalId,a);h.length===0&&!l&&h.push(await H(e,t));for(const f of h)c.push({root:t.root,repo:f})}const m=(n?.localPaths??await C(e)).filter(({path:t})=>i===t||i.startsWith(t.endsWith(N)?t:t+N)),w=m.length>0?r??await x():"";for(const{path:t,person:d,...h}of m)d===`user:${w.replace(/^user:/,"")}`&&c.push({root:t,repo:h});c.sort((t,d)=>d.root.length-t.root.length);const u=new Set;return c.filter(({repo:t})=>!u.has(t.id)&&(u.add(t.id),!0))}p(B,"checkoutsForCwd");export{B as checkoutsForCwd,H as ensureRepo,D as handleHint,_ as loadReadAccess,ae as mayRead,ne as prefetchRepoReads,W as readableRepos,ie as reposForCwd,se as warmCheckoutIdentities};
@@ -42,5 +42,7 @@ export declare function selectProfileForCwdReadOnly(cwd: string): string;
42
42
  * the root profile. Non-interactive (no TTY):
43
43
  * default to the root profile and print the recovery instruction to STDERR —
44
44
  * never stdout, which the caller may be piping. */
45
- export declare function selectProfileForCwd(cwd: string, explicitProfile?: string | null, forcePicker?: boolean): Promise<string>;
45
+ export declare function selectProfileForCwd(cwd: string, explicitProfile?: string | null, forcePicker?: boolean,
46
+ /** The front door's startup does not hold the start on the last-used write (a timestamp nothing in this start reads back); crtrd's callers wait for it. */
47
+ waitForLastUsed?: boolean): Promise<string>;
46
48
  export {};
@@ -1,35 +1,35 @@
1
- var se=Object.defineProperty;var l=(t,e)=>se(t,"name",{value:e,configurable:!0});import{projectPaths as P}from"../../api/dto/profiles.js";import{spawnSync as le}from"node:child_process";import{existsSync as ae,realpathSync as ce}from"node:fs";import{basename as fe,resolve as ue,sep as A}from"node:path";import{createInterface as T}from"node:readline/promises";import{emitKeypressEvents as D}from"node:readline";import{listProfiles as O,loadProfileManifest as pe,resolveProfileOperand as de,updateProfileLastUsed as b,createProfile as me,addProfileProject as k,ensureRootProfile as L,ROOT_PROFILE_ID as N}from"./manifest.js";import{getDefaultProfileId as he,setDefaultProfileId as $e,clearDefaultProfile as j}from"./default-binding.js";import{tildify as v}from"../fs-utils.js";import{stdoutColor as _}from"../output.js";import{inTmux as we}from"../runtime/placement-tmux.js";import{surfaceTmuxStyleArgs as ge}from"../runtime/surface-bg.js";import{formatBinding as w,matchesTerminalInput as Ie,resolveUserKeybindings as ye}from"../keybindings/index.js";const xe=["crtr.profile.menu.abort","crtr.profile.menu.up","crtr.profile.menu.down","crtr.profile.menu.select","crtr.profile.menu.accept-default","crtr.profile.menu.slot.1","crtr.profile.menu.slot.2","crtr.profile.menu.slot.3","crtr.profile.menu.slot.4","crtr.profile.menu.slot.5","crtr.profile.menu.slot.6","crtr.profile.menu.slot.7","crtr.profile.menu.slot.8","crtr.profile.menu.slot.9","crtr.profile.menu.create","crtr.profile.menu.search-existing","crtr.profile.menu.use-root","crtr.profile.menu.set-default","crtr.profile.menu.add-directory","crtr.profile.menu.unpin","crtr.profile.menu.manage"],Pe=["crtr.profile.search.abort","crtr.profile.search.back","crtr.profile.search.pick","crtr.profile.search.up","crtr.profile.search.down","crtr.profile.search.delete"];function Y(t,e){return{input:e.ctrl===!0||e.meta===!0?e.name??t:t,upArrow:e.name==="up",downArrow:e.name==="down",return:e.name==="return"||e.name==="enter",escape:e.name==="escape",backspace:e.name==="backspace",ctrl:e.ctrl,meta:e.meta,shift:e.shift}}l(Y,"profileRawInput");function B(t,e,r){return e.find(n=>Ie(t,n,r))??null}l(B,"firstProfileMatch");function be(t,e){return B(t,xe,e)}l(be,"resolveProfileMenuAction");function ve(t,e){return B(t,Pe,e)}l(ve,"resolveProfileSearchAction");function W(t){const e=ue(t);if(!ae(e))return e;try{return ce(e)}catch{return e}}l(W,"resolveCwd");function F(t,e){return!!(t===e||t.startsWith(e+A)||e.startsWith(t+A))}l(F,"projectCovers");function U(t,e){return P(t.manifest.projects).some(r=>F(e,r))}l(U,"profileCoversCwd");function C(t,e){return t===null?!1:e===null?!0:t>e}l(C,"isMoreRecent");function H(t){return t.reduce((e,r)=>C(r.manifest.last_used_at,e.manifest.last_used_at)?r:e)}l(H,"pickMostRecent");function K(t){const e=W(t),r=O().filter(o=>U(o,e)),n=r.filter(o=>P(o.manifest.projects).includes(e)),s=he(e),i=s===null?null:r.find(o=>o.profileId===s)??null;return{covering:r,exact:n,pinnedId:s,pinned:i}}l(K,"profileSelectionState");function Je(t){const{covering:e,exact:r,pinned:n}=K(t);if(n!==null)return n.profileId;if(r.length===1)return r[0].profileId;const s=r.length>0?r:e;return s.length>0?H(s).profileId:N}l(Je,"selectProfileForCwdReadOnly");function q(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}l(q,"isInteractive");const $=_.dim,x=_.bold,I=_.cyan;function Me(t){return I(x(t))}l(Me,"key");function G(t){if(t===null)return"never used";const e=Date.parse(t);if(Number.isNaN(e))return"used recently";const r=Math.max(0,Math.floor((Date.now()-e)/1e3));if(r<60)return"used just now";const n=Math.floor(r/60);if(n<60)return`used ${n}m ago`;const s=Math.floor(n/60);if(s<24)return`used ${s}h ago`;const i=Math.floor(s/24);if(i<30)return`used ${i}d ago`;const o=Math.floor(i/30);return o<12?`used ${o}mo ago`:`used ${Math.floor(o/12)}y ago`}l(G,"relativeUsed");function Te(t,e){const r=e!==void 0?` ${$(e)}
1
+ var se=Object.defineProperty;var l=(t,e)=>se(t,"name",{value:e,configurable:!0});import{projectPaths as P}from"../../api/dto/profiles.js";import{spawnSync as le}from"node:child_process";import{existsSync as ae,realpathSync as ce}from"node:fs";import{basename as fe,join as ue,resolve as pe,sep as A}from"node:path";import{appendRotatingRecord as de}from"../log.js";import{crtrHome as me}from"../canvas/paths.js";import{createInterface as M}from"node:readline/promises";import{emitKeypressEvents as E}from"node:readline";import{listProfiles as D,loadProfileManifest as he,resolveProfileOperand as $e,updateProfileLastUsed as O,createProfile as ge,addProfileProject as j,ensureRootProfile as k,ROOT_PROFILE_ID as L}from"./manifest.js";import{getDefaultProfileId as we,setDefaultProfileId as Ie,clearDefaultProfile as N}from"./default-binding.js";import{tildify as b}from"../fs-utils.js";import{stdoutColor as T}from"../output.js";import{inTmux as ye}from"../runtime/placement-tmux.js";import{surfaceTmuxStyleArgs as xe}from"../runtime/surface-bg.js";import{formatBinding as g,matchesTerminalInput as Pe,resolveUserKeybindings as be}from"../keybindings/index.js";const ve=["crtr.profile.menu.abort","crtr.profile.menu.up","crtr.profile.menu.down","crtr.profile.menu.select","crtr.profile.menu.accept-default","crtr.profile.menu.slot.1","crtr.profile.menu.slot.2","crtr.profile.menu.slot.3","crtr.profile.menu.slot.4","crtr.profile.menu.slot.5","crtr.profile.menu.slot.6","crtr.profile.menu.slot.7","crtr.profile.menu.slot.8","crtr.profile.menu.slot.9","crtr.profile.menu.create","crtr.profile.menu.search-existing","crtr.profile.menu.use-root","crtr.profile.menu.set-default","crtr.profile.menu.add-directory","crtr.profile.menu.unpin","crtr.profile.menu.manage"],Me=["crtr.profile.search.abort","crtr.profile.search.back","crtr.profile.search.pick","crtr.profile.search.up","crtr.profile.search.down","crtr.profile.search.delete"];function Y(t,e){return{input:e.ctrl===!0||e.meta===!0?e.name??t:t,upArrow:e.name==="up",downArrow:e.name==="down",return:e.name==="return"||e.name==="enter",escape:e.name==="escape",backspace:e.name==="backspace",ctrl:e.ctrl,meta:e.meta,shift:e.shift}}l(Y,"profileRawInput");function B(t,e,r){return e.find(n=>Pe(t,n,r))??null}l(B,"firstProfileMatch");function Te(t,e){return B(t,ve,e)}l(Te,"resolveProfileMenuAction");function _e(t,e){return B(t,Me,e)}l(_e,"resolveProfileSearchAction");function W(t){const e=pe(t);if(!ae(e))return e;try{return ce(e)}catch{return e}}l(W,"resolveCwd");function F(t,e){return!!(t===e||t.startsWith(e+A)||e.startsWith(t+A))}l(F,"projectCovers");function H(t,e){return P(t.manifest.projects).some(r=>F(e,r))}l(H,"profileCoversCwd");function _(t,e){return t===null?!1:e===null?!0:t>e}l(_,"isMoreRecent");function U(t){return t.reduce((e,r)=>_(r.manifest.last_used_at,e.manifest.last_used_at)?r:e)}l(U,"pickMostRecent");function K(t){const e=W(t),r=D().filter(o=>H(o,e)),n=r.filter(o=>P(o.manifest.projects).includes(e)),i=we(e),s=i===null?null:r.find(o=>o.profileId===i)??null;return{covering:r,exact:n,pinnedId:i,pinned:s}}l(K,"profileSelectionState");function Ze(t){const{covering:e,exact:r,pinned:n}=K(t);if(n!==null)return n.profileId;if(r.length===1)return r[0].profileId;const i=r.length>0?r:e;return i.length>0?U(i).profileId:L}l(Ze,"selectProfileForCwdReadOnly");function q(){return!!process.stdin.isTTY&&!!process.stdout.isTTY}l(q,"isInteractive");const $=T.dim,x=T.bold,y=T.cyan;function Re(t){return y(x(t))}l(Re,"key");function G(t){if(t===null)return"never used";const e=Date.parse(t);if(Number.isNaN(e))return"used recently";const r=Math.max(0,Math.floor((Date.now()-e)/1e3));if(r<60)return"used just now";const n=Math.floor(r/60);if(n<60)return`used ${n}m ago`;const i=Math.floor(n/60);if(i<24)return`used ${i}h ago`;const s=Math.floor(i/24);if(s<30)return`used ${s}d ago`;const o=Math.floor(s/30);return o<12?`used ${o}mo ago`:`used ${Math.floor(o/12)}y ago`}l(G,"relativeUsed");function Ce(t,e){const r=e!==void 0?` ${$(e)}
2
2
  `:"";process.stdout.write(`
3
3
  ${x(t)}
4
4
  ${r}
5
- `)}l(Te,"writeHeader");function _e(t){const e=P(t.manifest.projects),r=e.length,n=e[0];return n===void 0?G(t.manifest.last_used_at):r>1?`${v(n)} \xB7 ${r} dirs total`:v(n)}l(_e,"purviewSummary");const J=I("\u25B8"),z=l(t=>t>0?`\x1B[${t}A\r`:"","cursorUp"),Q="\x1B[0J",Ce=/\u001b\[[0-9;]*m/g;function V(t){const e=process.stdout.columns??80,r=t.split(`
6
- `),n=r.length-1;let s=0;for(let i=0;i<n;i++){const o=r[i].replace(Ce,"").length;e>0&&o>e&&(s+=Math.ceil(o/e)-1)}return n+s}l(V,"blockRows");function Re(t,e,r,n,s,i){let o=`
5
+ `)}l(Ce,"writeHeader");function Se(t){const e=P(t.manifest.projects),r=e.length,n=e[0];return n===void 0?G(t.manifest.last_used_at):r>1?`${b(n)} \xB7 ${r} dirs total`:b(n)}l(Se,"purviewSummary");const J=y("\u25B8"),z=l(t=>t>0?`\x1B[${t}A\r`:"","cursorUp"),Q="\x1B[0J",Ae=/\u001b\[[0-9;]*m/g;function V(t){const e=process.stdout.columns??80,r=t.split(`
6
+ `),n=r.length-1;let i=0;for(let s=0;s<n;s++){const o=r[s].replace(Ae,"").length;e>0&&o>e&&(i+=Math.ceil(o/e)-1)}return n+i}l(V,"blockRows");function Ee(t,e,r,n,i,s){let o=`
7
7
  ${x(e)}
8
8
  `;r!==void 0&&(o+=` ${$(r)}
9
9
  `),o+=`
10
- `;let d=0;for(const[h,m]of n.entries()){const c=m.bindingId===void 0?++d:0,p=m.bindingId!==void 0?w(t,m.bindingId):c<=9?w(t,`crtr.profile.menu.slot.${c}`):"",u=h===s?J:" ",f=m.detail!==""?" "+$(m.detail):"",a=m.isDefault?" "+I("\xB7 "+(m.defaultText??"default")):"";o+=` ${u} ${Me(p)} ${m.label}${f}${a}
11
- `}return i!==void 0&&(o+=`
12
- ${$(i)}
10
+ `;let a=0;for(const[d,h]of n.entries()){const c=h.bindingId===void 0?++a:0,m=h.bindingId!==void 0?g(t,h.bindingId):c<=9?g(t,`crtr.profile.menu.slot.${c}`):"",u=d===i?J:" ",p=h.detail!==""?" "+$(h.detail):"",f=h.isDefault?" "+y("\xB7 "+(h.defaultText??"default")):"";o+=` ${u} ${Re(m)} ${h.label}${p}${f}
11
+ `}return s!==void 0&&(o+=`
12
+ ${$(s)}
13
13
  `),o+=`
14
- ${$(`${w(t,"crtr.profile.menu.up")}/${w(t,"crtr.profile.menu.down")} move ${w(t,"crtr.profile.menu.select")} select ${w(t,"crtr.profile.menu.accept-default")} default ${w(t,"crtr.profile.menu.abort")} quit`)}
15
- `,o}l(Re,"renderMenu");function X(t,e,r,n,s={}){const i=[];n.forEach((d,h)=>{d.bindingId===void 0&&i.push(h)});let o=s.initialIndex??0;return new Promise(d=>{let h=0;const m=l(()=>{const u=Re(t,e,r,n,o,s.hint);process.stdout.write((h>0?z(h)+Q:"")+u),h=V(u)},"draw"),c=l(()=>{process.stdin.off("keypress",p),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),p=l((u,f)=>{const a=be(t,Y(u,f));if(a==="crtr.profile.menu.abort"&&(c(),process.stdout.write(`
16
- `),process.exit(130)),a==="crtr.profile.menu.up"){o=(o-1+n.length)%n.length,m();return}if(a==="crtr.profile.menu.down"){o=(o+1)%n.length,m();return}if(a==="crtr.profile.menu.select"){c(),d({index:o});return}if(a==="crtr.profile.menu.accept-default"){c(),d({index:s.initialIndex??0});return}if(a?.startsWith("crtr.profile.menu.slot.")){const g=Number.parseInt(a.slice(-1),10);g>=1&&g<=i.length&&(o=i[g-1],m());return}const y=n.findIndex(g=>g.bindingId!==void 0&&g.bindingId===a);if(y>=0){c(),d({index:y});return}a!==null&&s.actionBindingIds?.includes(a)===!0&&(c(),d({index:o,action:a}))},"onKey");D(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",p),m()})}l(X,"runMenu");function Z(t){return we()?(le("tmux",["display-popup","-E","-T"," profiles ","-w","90%","-h","85%","-d",t,...ge(),"crtr sys settings --page profiles"],{stdio:"inherit"}),!0):(process.stdout.write(` ${$("the profile manager needs tmux \u2014 run `crtr sys settings` instead")}
17
- `),!1)}l(Z,"openProfileManager");const R=Symbol("profile-manager-ran");function ee(t){return` ${I("\u203A")} ${$(t)} `}l(ee,"caret");function Se(t){return`crtr: no profile covers ${t}, and this session is non-interactive \u2014 using the root profile.
14
+ ${$(`${g(t,"crtr.profile.menu.up")}/${g(t,"crtr.profile.menu.down")} move ${g(t,"crtr.profile.menu.select")} select ${g(t,"crtr.profile.menu.accept-default")} default ${g(t,"crtr.profile.menu.abort")} quit`)}
15
+ `,o}l(Ee,"renderMenu");function X(t,e,r,n,i={}){const s=[];n.forEach((a,d)=>{a.bindingId===void 0&&s.push(d)});let o=i.initialIndex??0;return new Promise(a=>{let d=0;const h=l(()=>{const u=Ee(t,e,r,n,o,i.hint);process.stdout.write((d>0?z(d)+Q:"")+u),d=V(u)},"draw"),c=l(()=>{process.stdin.off("keypress",m),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),m=l((u,p)=>{const f=Te(t,Y(u,p));if(f==="crtr.profile.menu.abort"&&(c(),process.stdout.write(`
16
+ `),process.exit(130)),f==="crtr.profile.menu.up"){o=(o-1+n.length)%n.length,h();return}if(f==="crtr.profile.menu.down"){o=(o+1)%n.length,h();return}if(f==="crtr.profile.menu.select"){c(),a({index:o});return}if(f==="crtr.profile.menu.accept-default"){c(),a({index:i.initialIndex??0});return}if(f?.startsWith("crtr.profile.menu.slot.")){const I=Number.parseInt(f.slice(-1),10);I>=1&&I<=s.length&&(o=s[I-1],h());return}const w=n.findIndex(I=>I.bindingId!==void 0&&I.bindingId===f);if(w>=0){c(),a({index:w});return}f!==null&&i.actionBindingIds?.includes(f)===!0&&(c(),a({index:o,action:f}))},"onKey");E(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",m),h()})}l(X,"runMenu");function Z(t){return ye()?(le("tmux",["display-popup","-E","-T"," profiles ","-w","90%","-h","85%","-d",t,...xe(),"crtr sys settings --page profiles"],{stdio:"inherit"}),!0):(process.stdout.write(` ${$("the profile manager needs tmux \u2014 run `crtr sys settings` instead")}
17
+ `),!1)}l(Z,"openProfileManager");const R=Symbol("profile-manager-ran");function ee(t){return` ${y("\u203A")} ${$(t)} `}l(ee,"caret");function De(t){return`crtr: no profile covers ${t}, and this session is non-interactive \u2014 using the root profile.
18
18
  Run \`crtr profile new --name <name> --project ${t}\` to create a dedicated profile, or pass --profile <id-or-name> next time.
19
- `}l(Se,"rootProfileMessage");async function Ee(t,e){const r=T({input:process.stdin,output:process.stdout});try{Te(`Profile "${t.manifest.name}" doesn't cover this directory`),await te(r,t,e)}finally{r.close()}}l(Ee,"promptAddDirToProfile");async function te(t,e,r){const n=(await t.question(ee(`add this directory to "${e.manifest.name}"? [Y/n]`))).trim().toLowerCase();n==="n"||n==="no"||(await k(e.profileId,r),process.stdout.write(` ${I("\u2713")} ${$(`added this directory to "${e.manifest.name}"`)}
20
- `))}l(te,"offerAddDirToProfile");async function Ae(t){const e=[...O()].filter(i=>i.profileId!==N).sort((i,o)=>C(i.manifest.last_used_at,o.manifest.last_used_at)?-1:1);if(e.length===0)return process.stdout.write(` ${$("no existing profiles to select")}
21
- `),null;let r="",n=0;const s=l(()=>r===""?e:e.filter(i=>i.manifest.name.toLowerCase().includes(r)||P(i.manifest.projects).some(o=>v(o).toLowerCase().includes(r))),"matchesOf");return new Promise(i=>{let o=0;const d=l(()=>{const c=s();n>=c.length&&(n=Math.max(0,c.length-1));let p=`
19
+ `}l(De,"rootProfileMessage");async function Oe(t,e){const r=M({input:process.stdin,output:process.stdout});try{Ce(`Profile "${t.manifest.name}" doesn't cover this directory`),await te(r,t,e)}finally{r.close()}}l(Oe,"promptAddDirToProfile");async function te(t,e,r){const n=(await t.question(ee(`add this directory to "${e.manifest.name}"? [Y/n]`))).trim().toLowerCase();n==="n"||n==="no"||(await j(e.profileId,r),process.stdout.write(` ${y("\u2713")} ${$(`added this directory to "${e.manifest.name}"`)}
20
+ `))}l(te,"offerAddDirToProfile");async function je(t){const e=[...D()].filter(s=>s.profileId!==L).sort((s,o)=>_(s.manifest.last_used_at,o.manifest.last_used_at)?-1:1);if(e.length===0)return process.stdout.write(` ${$("no existing profiles to select")}
21
+ `),null;let r="",n=0;const i=l(()=>r===""?e:e.filter(s=>s.manifest.name.toLowerCase().includes(r)||P(s.manifest.projects).some(o=>b(o).toLowerCase().includes(r))),"matchesOf");return new Promise(s=>{let o=0;const a=l(()=>{const c=i();n>=c.length&&(n=Math.max(0,c.length-1));let m=`
22
22
  ${x("Select an existing profile")}
23
- `;if(p+=` ${$("across every profile, not just this directory")}
23
+ `;if(m+=` ${$("across every profile, not just this directory")}
24
24
 
25
- `,c.length===0)p+=` ${$(`no match for "${r}"`)}
26
- `;else{const u=Math.max(...c.map(f=>f.manifest.name.length));c.forEach((f,a)=>{p+=` ${a===n?J:" "} ${x(f.manifest.name.padEnd(u))} ${$(_e(f))}
27
- `})}p+=`
28
- ${I("\u203A")} ${r}${$("\u2588")}
29
- `,p+=` ${$(`type to filter ${w(t,"crtr.profile.search.up")}/${w(t,"crtr.profile.search.down")} move ${w(t,"crtr.profile.search.pick")} pick ${w(t,"crtr.profile.search.back")} back`)}
30
- `,process.stdout.write((o>0?z(o)+Q:"")+p),o=V(p)},"draw"),h=l(()=>{process.stdin.off("keypress",m),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),m=l((c,p)=>{const u=ve(t,Y(c,p));if(u==="crtr.profile.search.abort"&&(h(),process.stdout.write(`
31
- `),process.exit(130)),u==="crtr.profile.search.back"){h(),i(null);return}const f=s();if(u==="crtr.profile.search.pick"){f.length>0&&(h(),i(f[n].profileId));return}if(u==="crtr.profile.search.up"){f.length>0&&(n=(n-1+f.length)%f.length,d());return}if(u==="crtr.profile.search.down"){f.length>0&&(n=(n+1)%f.length,d());return}if(u==="crtr.profile.search.delete"){r=r.slice(0,-1),n=0,d();return}c!==void 0&&c.length===1&&c>=" "&&p.ctrl!==!0&&(r+=c.toLowerCase(),n=0,d())},"onKey");D(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",m),d()})}l(Ae,"promptSelectExistingProfile");async function re(t,e){const r=fe(e)||"profile",n=(await t.question(ee(`name the new profile [${r}]`))).trim(),s=n!==""?n:r,i=(await me(s,[{path:e}])).profileId;return process.stdout.write(` ${I("\u2713")} ${$(`created profile "${s}"`)}
32
- `),i}l(re,"createProfileHere");async function De(t,e){const r=[{label:"create a profile here",detail:"",bindingId:"crtr.profile.menu.create"},{label:"select an existing profile",detail:"",bindingId:"crtr.profile.menu.search-existing"},{label:$("use the root profile"),detail:"",bindingId:"crtr.profile.menu.use-root",isDefault:!0}];for(;;){const n=await X(e,"No profile covers this directory",void 0,r,{initialIndex:2,actionBindingIds:["crtr.profile.menu.manage"],hint:`${w(e,"crtr.profile.menu.manage")}=manage profiles`});if(n.action==="crtr.profile.menu.manage"){if(Z(t))return R;continue}if(n.index===0){const s=T({input:process.stdin,output:process.stdout});try{return await re(s,t)}finally{s.close()}}if(n.index===1){const s=await Ae(e);if(s===null)continue;const i=pe(s),o=T({input:process.stdin,output:process.stdout});try{await te(o,i,t)}finally{o.close()}return i.profileId}return(await L()).profileId}}l(De,"promptCreateOrRoot");async function S(t,e,r,n,s){const i=[...t].sort((a,y)=>C(a.manifest.last_used_at,y.manifest.last_used_at)?-1:1),o=n!==null?i.find(a=>a.profileId===n)??null:null,d=o!==null?[o,...i.filter(a=>a!==o)]:i,h=Math.max(...d.map(a=>a.manifest.name.length)),m=d.map((a,y)=>{const g=P(a.manifest.projects),M=g.length,ne=r?`${G(a.manifest.last_used_at)}${M>1?` \xB7 ${M} dirs total`:""}`:(()=>{const E=g.find(ie=>F(e,ie))??g[0];return M>1?`matches ${v(E)} \xB7 ${M} dirs total`:`matches ${v(E)}`})(),oe=o!==null&&d[0]===o?"default (pinned)":"default";return{label:x(a.manifest.name.padEnd(h)),detail:ne,isDefault:y===0,defaultText:oe}});m.push({label:$("create a new profile here"),detail:"",bindingId:"crtr.profile.menu.create"});const c=["crtr.profile.menu.set-default","crtr.profile.menu.manage"];r||c.push("crtr.profile.menu.add-directory"),o!==null&&c.push("crtr.profile.menu.unpin");const p=[`${w(s,"crtr.profile.menu.set-default")}=set default`];r||p.push(`${w(s,"crtr.profile.menu.add-directory")}=add dir here`),o!==null&&p.push(`${w(s,"crtr.profile.menu.unpin")}=unpin`),p.push(`${w(s,"crtr.profile.menu.manage")}=manage profiles`);const u=await X(s,r?"Choose a profile":"Select a profile",r?"Several profiles claim this directory as their project":"This directory falls under existing profile(s)",m,{actionBindingIds:c,hint:p.join(" ")});if(u.action==="crtr.profile.menu.manage")return Z(e)?R:await S(t,e,r,n,s);if(u.index>=d.length){const a=T({input:process.stdin,output:process.stdout});try{return await re(a,e)}finally{a.close()}}const f=d[u.index];return u.action==="crtr.profile.menu.unpin"?(await j(e),process.stdout.write(` ${I("\u2713")} ${$("cleared the default for this directory")}
33
- `),f.profileId):(u.action==="crtr.profile.menu.set-default"?(await $e(e,f.profileId),process.stdout.write(` ${I("\u2713")} ${$(`"${f.manifest.name}" is now the default here`)}
34
- `)):u.action==="crtr.profile.menu.add-directory"&&(await k(f.profileId,e),process.stdout.write(` ${I("\u2713")} ${$(`added this directory to "${f.manifest.name}"`)}
35
- `)),f.profileId)}l(S,"promptPickProfileOrCreate");async function ze(t,e,r=!1){const n=W(t),s=ye();if(e!=null&&e!==""){const i=de(e);return!U(i,n)&&q()&&await Ee(i,n),await b(i.profileId),i.profileId}for(;;){const{covering:i,exact:o,pinnedId:d,pinned:h}=K(n);if(d!==null&&h===null&&await j(n),h!==null&&!r)return await b(h.profileId),h.profileId;if(!r&&h===null&&o.length===1)return await b(o[0].profileId),o[0].profileId;if(!q()){const p=o.length>0?o:i;if(p.length>0){const f=H(p);return await b(f.profileId),f.profileId}const u=await L();return process.stderr.write(Se(n)),u.profileId}const m=h!==null?h.profileId:null,c=o.length>1?await S(o,n,!0,m,s):i.length>0?await S(i,n,!1,m,s):await De(n,s);if(c!==R)return await b(c),c}}l(ze,"selectProfileForCwd");export{U as profileCoversCwd,be as resolveProfileMenuAction,ve as resolveProfileSearchAction,ze as selectProfileForCwd,Je as selectProfileForCwdReadOnly};
25
+ `,c.length===0)m+=` ${$(`no match for "${r}"`)}
26
+ `;else{const u=Math.max(...c.map(p=>p.manifest.name.length));c.forEach((p,f)=>{m+=` ${f===n?J:" "} ${x(p.manifest.name.padEnd(u))} ${$(Se(p))}
27
+ `})}m+=`
28
+ ${y("\u203A")} ${r}${$("\u2588")}
29
+ `,m+=` ${$(`type to filter ${g(t,"crtr.profile.search.up")}/${g(t,"crtr.profile.search.down")} move ${g(t,"crtr.profile.search.pick")} pick ${g(t,"crtr.profile.search.back")} back`)}
30
+ `,process.stdout.write((o>0?z(o)+Q:"")+m),o=V(m)},"draw"),d=l(()=>{process.stdin.off("keypress",h),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause()},"cleanup"),h=l((c,m)=>{const u=_e(t,Y(c,m));if(u==="crtr.profile.search.abort"&&(d(),process.stdout.write(`
31
+ `),process.exit(130)),u==="crtr.profile.search.back"){d(),s(null);return}const p=i();if(u==="crtr.profile.search.pick"){p.length>0&&(d(),s(p[n].profileId));return}if(u==="crtr.profile.search.up"){p.length>0&&(n=(n-1+p.length)%p.length,a());return}if(u==="crtr.profile.search.down"){p.length>0&&(n=(n+1)%p.length,a());return}if(u==="crtr.profile.search.delete"){r=r.slice(0,-1),n=0,a();return}c!==void 0&&c.length===1&&c>=" "&&m.ctrl!==!0&&(r+=c.toLowerCase(),n=0,a())},"onKey");E(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("keypress",h),a()})}l(je,"promptSelectExistingProfile");async function re(t,e){const r=fe(e)||"profile",n=(await t.question(ee(`name the new profile [${r}]`))).trim(),i=n!==""?n:r,s=(await ge(i,[{path:e}])).profileId;return process.stdout.write(` ${y("\u2713")} ${$(`created profile "${i}"`)}
32
+ `),s}l(re,"createProfileHere");async function ke(t,e){const r=[{label:"create a profile here",detail:"",bindingId:"crtr.profile.menu.create"},{label:"select an existing profile",detail:"",bindingId:"crtr.profile.menu.search-existing"},{label:$("use the root profile"),detail:"",bindingId:"crtr.profile.menu.use-root",isDefault:!0}];for(;;){const n=await X(e,"No profile covers this directory",void 0,r,{initialIndex:2,actionBindingIds:["crtr.profile.menu.manage"],hint:`${g(e,"crtr.profile.menu.manage")}=manage profiles`});if(n.action==="crtr.profile.menu.manage"){if(Z(t))return R;continue}if(n.index===0){const i=M({input:process.stdin,output:process.stdout});try{return await re(i,t)}finally{i.close()}}if(n.index===1){const i=await je(e);if(i===null)continue;const s=he(i),o=M({input:process.stdin,output:process.stdout});try{await te(o,s,t)}finally{o.close()}return s.profileId}return(await k()).profileId}}l(ke,"promptCreateOrRoot");async function C(t,e,r,n,i){const s=[...t].sort((f,w)=>_(f.manifest.last_used_at,w.manifest.last_used_at)?-1:1),o=n!==null?s.find(f=>f.profileId===n)??null:null,a=o!==null?[o,...s.filter(f=>f!==o)]:s,d=Math.max(...a.map(f=>f.manifest.name.length)),h=a.map((f,w)=>{const I=P(f.manifest.projects),v=I.length,ne=r?`${G(f.manifest.last_used_at)}${v>1?` \xB7 ${v} dirs total`:""}`:(()=>{const S=I.find(ie=>F(e,ie))??I[0];return v>1?`matches ${b(S)} \xB7 ${v} dirs total`:`matches ${b(S)}`})(),oe=o!==null&&a[0]===o?"default (pinned)":"default";return{label:x(f.manifest.name.padEnd(d)),detail:ne,isDefault:w===0,defaultText:oe}});h.push({label:$("create a new profile here"),detail:"",bindingId:"crtr.profile.menu.create"});const c=["crtr.profile.menu.set-default","crtr.profile.menu.manage"];r||c.push("crtr.profile.menu.add-directory"),o!==null&&c.push("crtr.profile.menu.unpin");const m=[`${g(i,"crtr.profile.menu.set-default")}=set default`];r||m.push(`${g(i,"crtr.profile.menu.add-directory")}=add dir here`),o!==null&&m.push(`${g(i,"crtr.profile.menu.unpin")}=unpin`),m.push(`${g(i,"crtr.profile.menu.manage")}=manage profiles`);const u=await X(i,r?"Choose a profile":"Select a profile",r?"Several profiles claim this directory as their project":"This directory falls under existing profile(s)",h,{actionBindingIds:c,hint:m.join(" ")});if(u.action==="crtr.profile.menu.manage")return Z(e)?R:await C(t,e,r,n,i);if(u.index>=a.length){const f=M({input:process.stdin,output:process.stdout});try{return await re(f,e)}finally{f.close()}}const p=a[u.index];return u.action==="crtr.profile.menu.unpin"?(await N(e),process.stdout.write(` ${y("\u2713")} ${$("cleared the default for this directory")}
33
+ `),p.profileId):(u.action==="crtr.profile.menu.set-default"?(await Ie(e,p.profileId),process.stdout.write(` ${y("\u2713")} ${$(`"${p.manifest.name}" is now the default here`)}
34
+ `)):u.action==="crtr.profile.menu.add-directory"&&(await j(p.profileId,e),process.stdout.write(` ${y("\u2713")} ${$(`added this directory to "${p.manifest.name}"`)}
35
+ `)),p.profileId)}l(C,"promptPickProfileOrCreate");async function et(t,e,r=!1,n=!0){const i=l(async a=>{n?await O(a):O(a).catch(d=>de(ue(me(),"attach-invariants.log"),`${new Date().toISOString()} profile.last_used ${a} ${String(d).replaceAll(/[\r\n]/g," ")}`))},"touch"),s=W(t),o=be();if(e!=null&&e!==""){const a=$e(e);return!H(a,s)&&q()&&await Oe(a,s),await i(a.profileId),a.profileId}for(;;){const{covering:a,exact:d,pinnedId:h,pinned:c}=K(s);if(h!==null&&c===null&&await N(s),c!==null&&!r)return await i(c.profileId),c.profileId;if(!r&&c===null&&d.length===1)return await i(d[0].profileId),d[0].profileId;if(!q()){const p=d.length>0?d:a;if(p.length>0){const w=U(p);return await i(w.profileId),w.profileId}const f=await k();return process.stderr.write(De(s)),f.profileId}const m=c!==null?c.profileId:null,u=d.length>1?await C(d,s,!0,m,o):a.length>0?await C(a,s,!1,m,o):await ke(s,o);if(u!==R)return await i(u),u}}l(et,"selectProfileForCwd");export{H as profileCoversCwd,Te as resolveProfileMenuAction,_e as resolveProfileSearchAction,et as selectProfileForCwd,Ze as selectProfileForCwdReadOnly};
@@ -1,4 +1,4 @@
1
- import { type Cron } from '../canvas/index.js';
1
+ import { type Cron, type NodeMeta } from '../canvas/index.js';
2
2
  import type { DeliveredDoc, RenderContext } from '../substrate/delivery/render-event.js';
3
3
  import { buildProjectContextBlock, contextDirNote, orchestratorContextNote } from './bearings-render.js';
4
4
  /** The bearings custom type is shared with every attached renderer. */
@@ -13,11 +13,11 @@ export { buildProjectContextBlock, contextDirNote, orchestratorContextNote };
13
13
  * `assembleNodeSubject`'s profile resolution). This absolute-path disclosure
14
14
  * is intentional (spec-approved): the agent must know its full purview, not a
15
15
  * redacted count. */
16
- export declare function profileNote(nodeId: string): Promise<string>;
16
+ export declare function profileNote(nodeId: string, known?: NodeMeta | null): Promise<string>;
17
17
  /** The graph mini-map: the ancestry trunk (root first), then this node marked
18
18
  * `● you`, then its immediate children. Returns '' for a lone root with no
19
19
  * children (nothing to map). Exported for testing. */
20
- export declare function buildGraphMap(nodeId: string): Promise<string>;
20
+ export declare function buildGraphMap(nodeId: string, known?: NodeMeta | null): Promise<string>;
21
21
  /** Why a node was born or woken, as carried from the fired cron to the
22
22
  * injection seam. `ownerName` is the armer's resolved display name when it
23
23
  * still exists (a reaped cron's armer renders as a bare id, never crashes). */
@@ -1,7 +1,7 @@
1
- var b=Object.defineProperty;var a=(e,n)=>b(e,"name",{value:n,configurable:!0});import{getNode as i,fullName as d,isSafeNodeId as k,subscriptionsOf as g}from"../canvas/index.js";import{cadenceDisplay as N}from"../wake.js";import{renderKnowledge as v,renderWorkspaceOpen as x}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as _}from"./situational-context.js";import{statusRank as l}from"../canvas/node-order.js";import{buildProjectContextBlock as w,contextDirNote as f,orchestratorContextNote as p,profileNote as $,renderGraphMap as C,buildIdentityAssertion as S,worktreeNote as O}from"./bearings-render.js";import{mapAsync as Y}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as V}from"../../shared/generated-context.js";async function A(e){const n=await i(e);return n===null?"":$(n.cwd,n.profile_id)}a(A,"profileNote");async function E(e){const n=[],r=new Set([e]);let t=(await i(e))?.parent??null;for(;t!==null&&t!==""&&!r.has(t);){r.add(t);const o=await i(t);if(o===null)break;n.unshift(o),t=o.parent??null}return n}a(E,"ancestorTrunk");const I=5;async function j(e){return(await Y(await g(e),async n=>await i(n.node_id))).filter(n=>n!==null&&n.kind!=="human").sort((n,r)=>l(n.status)-l(r.status))}a(j,"childNodes");async function B(e){const n=await i(e);if(n===null)return"";const r=await E(e),t=await j(e);return C(e,n.kind,n.mode,r,t)}a(B,"buildGraphMap");async function R(e){const n=await i(e),r=n?.fork_from,t=r!=null&&r!==""&&k(r)?await i(r):null,o=t!==null?`${r} ("${d(t)}")`:r??"";return S(e,n?.kind??"general",n?.mode??"base",r,o)}a(R,"buildIdentityAssertion");function T(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(T,"armerPhrase");async function K(e,n){const r=e.created_by!=null?await i(e.created_by):null;return{kind:n,ownerId:e.created_by,...r!==null?{ownerName:d(r)}:{},armedAt:e.created,recur:e.recur}}a(K,"cronWakeOrigin");function q(e){const n=e.recur!==null&&e.recur!==void 0&&e.recur!=="",r=n?N(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
- ${n?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${r} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
1
+ var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});import{getNode as s,fullName as d,isSafeNodeId as k,subscriptionsOf as g}from"../canvas/index.js";import{cadenceDisplay as N}from"../wake.js";import{renderKnowledge as v,renderWorkspaceOpen as x}from"../substrate/delivery/render-boot.js";import{situationalContextEnvelope as _}from"./situational-context.js";import{statusRank as l}from"../canvas/node-order.js";import{buildProjectContextBlock as f,contextDirNote as w,orchestratorContextNote as p,profileNote as $,renderGraphMap as C,buildIdentityAssertion as S,worktreeNote as O}from"./bearings-render.js";import{mapAsync as Y}from"../async-array.js";import{CONTEXT_INTRO_CUSTOM_TYPE as V}from"../../shared/generated-context.js";async function A(e,r){const n=r!==void 0?r:await s(e);return n===null?"":$(n.cwd,n.profile_id)}a(A,"profileNote");async function E(e,r){const n=[],t=new Set([e]);let o=r.parent??null;for(;o!==null&&o!==""&&!t.has(o);){t.add(o);const i=await s(o);if(i===null)break;n.unshift(i),o=i.parent??null}return n}a(E,"ancestorTrunk");const F=5;async function j(e){return(await Y(await g(e),async r=>await s(r.node_id))).filter(r=>r!==null&&r.kind!=="human").sort((r,n)=>l(r.status)-l(n.status))}a(j,"childNodes");async function B(e,r){const n=r!==void 0?r:await s(e);if(n===null)return"";const t=await E(e,n),o=await j(e);return C(e,n.kind,n.mode,t,o)}a(B,"buildGraphMap");async function R(e,r){const n=r?.fork_from,t=n!=null&&n!==""&&k(n)?await s(n):null,o=t!==null?`${n} ("${d(t)}")`:n??"";return S(e,r?.kind??"general",r?.mode??"base",n,o)}a(R,"buildIdentityAssertion");function T(e){return e.ownerId===null||e.ownerId===""?"an unknown node":e.ownerName!==void 0?`node ${e.ownerId} ("${e.ownerName}")`:`node ${e.ownerId} (now gone)`}a(T,"armerPhrase");async function K(e,r){const n=e.created_by!=null?await s(e.created_by):null;return{kind:r,ownerId:e.created_by,...n!==null?{ownerName:d(n)}:{},armedAt:e.created,recur:e.recur}}a(K,"cronWakeOrigin");function q(e){const r=e.recur!==null&&e.recur!==void 0&&e.recur!=="",n=r?N(e.recur):null;if(e.kind==="schedule_revive")return`<crtr-wake>
2
+ ${r?`A SCHEDULE woke you, not a message \u2014 a recurring cron firing ${n} revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the clock came round. Re-read your bearings below, do this cycle's pass of the standing job, and stop.`:"A SCHEDULE woke you, not a message \u2014 a one-shot cron armed to fire now revived you fresh. Nothing new happened on the canvas and nobody is waiting on a reply: the time you were waiting for arrived. Re-read your bearings below and continue from there."}
3
3
  </crtr-wake>`;const t=T(e);return`<crtr-wake>
4
- ${n?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, firing ${r}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
- </crtr-wake>`}a(q,"buildWakeBearings");function D(e){return O(e?.managed_worktree)}a(D,"managedWorktreeNote");async function W(e,n,r){const t=await i(e),o=["<crtr-bearings>",await R(e)],s=await B(e);s!==""&&o.push("","## Your place in the canvas",s),o.push("","## Your documents and context directory",f(e,t?.grantee));const u=await A(e);u!==""&&o.push("",u);const c=D(t);c!==""&&o.push("","## Your managed worktree",c),t?.mode==="orchestrator"&&o.push("",p()),o.push("</crtr-bearings>");const h=await _(e)??"",m=t?.cwd!==void 0?w(t.cwd):"";return[o.join(`
6
- `),n,r,h,m].filter(y=>y!=="").join(`
7
- `)}a(W,"bearingsShell");async function z(e,n){const r=await v(n),t=await x(n);return{content:await W(e,r.content,t.content),delivered:[...r.delivered,...t.delivered]}}a(z,"buildContextBearings");export{V as CONTEXT_INTRO_CUSTOM_TYPE,z as buildContextBearings,B as buildGraphMap,w as buildProjectContextBlock,q as buildWakeBearings,f as contextDirNote,K as cronWakeOrigin,p as orchestratorContextNote,A as profileNote};
4
+ ${r?`You were BORN by a scheduled wake, not spawned on demand \u2014 a recurring spawn-cron armed by ${t}, firing ${n}. The runtime re-births a fresh node like you on this cadence whether or not earlier runs survived: you are one run of a standing job, not a one-off, and you inherit nothing from prior runs but this task. Your task follows.`:`You were BORN by a scheduled wake, not spawned on demand \u2014 a one-shot deferred birth armed by ${t} to fire now. You are its only run, not a recurring job. Your task follows.`}
5
+ </crtr-wake>`}a(q,"buildWakeBearings");function D(e){return O(e?.managed_worktree)}a(D,"managedWorktreeNote");async function W(e,r,n){const t=await s(e),o=["<crtr-bearings>",await R(e,t)],i=await B(e,t);i!==""&&o.push("","## Your place in the canvas",i),o.push("","## Your documents and context directory",w(e,t?.grantee));const u=await A(e,t);u!==""&&o.push("",u);const c=D(t);c!==""&&o.push("","## Your managed worktree",c),t?.mode==="orchestrator"&&o.push("",p()),o.push("</crtr-bearings>");const h=await _(e)??"",m=t?.cwd!==void 0?f(t.cwd):"";return[o.join(`
6
+ `),r,n,h,m].filter(y=>y!=="").join(`
7
+ `)}a(W,"bearingsShell");async function z(e,r){const n=await v(r),t=await x(r);return{content:await W(e,n.content,t.content),delivered:[...n.delivered,...t.delivered]}}a(z,"buildContextBearings");export{V as CONTEXT_INTRO_CUSTOM_TYPE,z as buildContextBearings,B as buildGraphMap,f as buildProjectContextBlock,q as buildWakeBearings,w as contextDirNote,K as cronWakeOrigin,p as orchestratorContextNote,A as profileNote};
@@ -27,8 +27,8 @@ export interface BootRootOpts {
27
27
  export declare function rootCreateRequest(opts: BootRootOpts, profileId: string): Parameters<ReturnType<typeof cliClient>['createNode']>[0];
28
28
  /** Boot the front-door root: create the resident root through crtrd (broker
29
29
  * launched + view socket ready server-side), register THIS terminal's pane as
30
- * its foreground viewer, then exec `crtr surface attach` inline so this terminal
31
- * becomes a writable viewer. Does not return — it process.exit()s
32
- * when the inline attach exits (detach leaves the resident broker running, to
30
+ * its foreground viewer, then run the attach viewer in this process so this
31
+ * terminal becomes a writable viewer. Does not return — it process.exit()s
32
+ * when the viewer exits (detach leaves the resident broker running, to
33
33
  * be reconnected later). */
34
34
  export declare function bootRoot(opts: BootRootOpts): Promise<never>;
@@ -1,5 +1,7 @@
1
- var w=Object.defineProperty;var d=(e,o)=>w(e,"name",{value:o,configurable:!0});import{spawn as l}from"node:child_process";import{inTmux as u,currentTmux as _,viewerSplitEnv as T}from"./placement-tmux.js";import{selectProfileForCwd as x}from"../profiles/select.js";import{cliClient as p}from"../../commands/api-client.js";import{mark as c}from"../timing.js";import{printComeBackNote as C}from"./come-back-note.js";function h(e,o){const t=e.kind;return{...t!==void 0?{kind:t}:{},mode:"base",prompt:e.prompt,profile:o,cwd:e.cwd,...e.name!==void 0?{name:e.name}:t!==void 0?{name:t}:{},root:!0,prefer_warm:!0}}d(h,"rootCreateRequest");async function E(e){if(!u()){const n=process.stderr.isTTY?i=>`\x1B[1;33m${i}\x1B[0m`:i=>i;process.stderr.write(`
2
- ${n("crtr must be started from inside a tmux session.")}
3
- ${n("Start tmux first, e.g. tmux new -s work \u2014 then run crtr there.")}
1
+ var x=Object.defineProperty;var p=(e,o)=>x(e,"name",{value:o,configurable:!0});import{inTmux as b,currentTmux as w}from"./placement-tmux.js";import{selectProfileForCwd as g}from"../profiles/select.js";import{cliClient as c}from"../../commands/api-client.js";import{mark as s}from"../timing.js";import{handle as T}from"../io.js";import{loadedPersonSettings as k}from"../../commands/person-settings.js";import{showStartingScreen as C}from"./starting-screen.js";import{printComeBackNote as l}from"./come-back-note.js";function h(e,o){const i=e.kind;return{...i!==void 0?{kind:i}:{},mode:"base",prompt:e.prompt,profile:o,cwd:e.cwd,...e.name!==void 0?{name:e.name}:i!==void 0?{name:i}:{},root:!0,start:!0,prefer_warm:!0}}p(h,"rootCreateRequest");async function R(e){if(!b()){const t=process.stderr.isTTY?r=>`\x1B[1;33m${r}\x1B[0m`:r=>r;process.stderr.write(`
2
+ ${t("crtr must be started from inside a tmux session.")}
3
+ ${t("Start tmux first, e.g. tmux new -s work \u2014 then run crtr there.")}
4
4
 
5
- `),process.exit(1)}c("boot_root.start");const o=e.selectedProfileId??await x(e.cwd,e.profile,e.pickProfile??!1);c("boot_root.profile_resolved");const a=(await p().createNode(h(e,o))).node_id;c("boot_root.node_created",{node:a});const r=_();if(r!==null)try{await p().registerFocus({node_id:a,pane:r.pane,session:r.session,window:r.window})}catch{}const s={...process.env,...T(),CRTR_ATTACH_WAIT_MS:"30000",...e.initialWhip??(e.prompt!==void 0&&e.prompt!=="")?{CRTR_ATTACH_INITIAL_WHIP:"1"}:{}};r!==null&&(s.CRTR_ATTACH_BORROWED_PANE=r.pane),c("boot_root.viewer_spawn");const m=l("crtr",["surface","attach","to",a],{stdio:"inherit",env:s}),f=await new Promise(n=>{m.once("exit",i=>n(i??0)),m.once("error",()=>n(1))});await C(a,f),process.exit(f)}d(E,"bootRoot");export{E as bootRoot,h as rootCreateRequest};
5
+ `),process.exit(1)}s("boot_root.start");const o=e.selectedProfileId??await g(e.cwd,e.profile,e.pickProfile??!1,!1);if(s("boot_root.profile_resolved"),!process.stdout.isTTY){const t=await c().createNode(h(e,o)),r=w();r!==null&&await c().registerFocus({node_id:t.node_id,pane:r.pane,session:r.session,window:r.window}).catch(()=>{}),process.stdout.write(`crtr surface attach is an interactive terminal viewer \u2014 run it in a tmux pane (a TTY), not a pipe. Node: ${t.node_id}
6
+ `),await l(t.node_id,0),process.exit(0)}const{buildBannerInfo:i}=await import("../../clients/attach/session/banner.js"),{hint:$,..._}=i({cwd:e.cwd,profile_id:o}),a=C(_);s("boot_root.starting_painted");const f=import("../../clients/attach/viewer.js");f.catch(()=>{});let m;try{m=await c().createNode(h(e,o))}catch(t){throw a.stop(),t}const n=m.node_id;a.setNode(n),s("boot_root.node_created",{node:n});const d=w();d!==null&&c().registerFocus({node_id:n,pane:d.pane,session:d.session,window:d.window}).catch(()=>{});let u=0;try{const{runAttach:t}=await f;s("boot_root.viewer_attach"),await t(n,!1,void 0,!0,{node:m,settings:k(),initialWhip:e.initialWhip??(e.prompt!==void 0&&e.prompt!=="")},()=>a.stop())}catch(t){a.stop(),process.stderr.write(`crtr: the agent ${n} is still running; reopen it with crtr -r ${n}
7
+ `),T(t),process.exit(typeof process.exitCode=="number"?process.exitCode:1)}await l(n,u),process.exit(u)}p(R,"bootRoot");export{R as bootRoot,h as rootCreateRequest};
@@ -1 +1 @@
1
- var n=Object.defineProperty;var o=(e,t)=>n(e,"name",{value:t,configurable:!0});import{getNode as m}from"../canvas/index.js";import{openDb as s,withCanvasWrite as c}from"../canvas/db.js";import{readerForNode as l,warmNodeRepos as u}from"../graph/reader.js";import{checkoutsForCwd as f}from"../graph/repo-sync/repos.js";import{deliver as p}from"../substrate/delivery/deliver.js";import{oneShotControllerRequest as v}from"./broker-request.js";import{isBrokerLive as w}from"./model-swap.js";import{CONTEXT_INTRO_CUSTOM_TYPE as d}from"./bearings.js";import{formatCard as y}from"../../shared/generated-context.js";async function T(e,t){const r=await m(e);if(r===null)throw new Error(`deliverCustomMessageLive: unknown node ${e}`);w(r)&&await v({nodeId:e,what:`the ${t.customType} delivery`,ackFor:"deliver_custom_message",frame:o(()=>({type:"deliver_custom_message",customType:t.customType,content:t.content,...t.deliverAs!==void 0?{deliverAs:t.deliverAs}:{},...t.details!==void 0?{details:t.details}:{}}),"frame"),result:o(()=>{},"result")})}o(T,"deliverCustomMessageLive");async function O(e){await u(await s(),e);const{content:t}=await c(async r=>await p(r,await l(r,e,async(i,a)=>await f(r,i,a)),{activity:"boot"}));await T(e,{customType:d,content:y("bearings",{},t),details:{nodeId:e}})}o(O,"deliverBearingsLive");export{O as deliverBearingsLive,T as deliverCustomMessageLive};
1
+ var m=Object.defineProperty;var o=(e,t)=>m(e,"name",{value:t,configurable:!0});import{getNode as s}from"../canvas/index.js";import{openDb as c,withCanvasWrite as l}from"../canvas/db.js";import{readerForNode as u,warmNodeRepos as f}from"../graph/reader.js";import{checkoutsForCwd as p}from"../graph/repo-sync/repos.js";import{deliver as v}from"../substrate/delivery/deliver.js";import{oneShotControllerRequest as w}from"./broker-request.js";import{isBrokerLive as d}from"./model-swap.js";import{CONTEXT_INTRO_CUSTOM_TYPE as y}from"./bearings.js";import{formatCard as T}from"../../shared/generated-context.js";async function C(e,t){const r=await s(e);if(r===null)throw new Error(`deliverCustomMessageLive: unknown node ${e}`);d(r)&&await w({nodeId:e,what:`the ${t.customType} delivery`,ackFor:"deliver_custom_message",frame:o(()=>({type:"deliver_custom_message",customType:t.customType,content:t.content,...t.deliverAs!==void 0?{deliverAs:t.deliverAs}:{},...t.details!==void 0?{details:t.details}:{}}),"frame"),result:o(()=>{},"result")})}o(C,"deliverCustomMessageLive");async function R(e){await f(await c(),e);const{content:t}=await l(async r=>await v(r,await u(r,e,async(i,a,n)=>await p(r,i,a,n)),{activity:"boot"}));await C(e,{customType:y,content:T("bearings",{},t),details:{nodeId:e}})}o(R,"deliverBearingsLive");export{R as deliverBearingsLive,C as deliverCustomMessageLive};
@@ -2,7 +2,7 @@ var E=Object.defineProperty;var p=(i,s)=>E(i,"name",{value:s,configurable:!0});i
2
2
  `),process.exit(1)),"none"in l?(e.resumeId.includes("-")&&(process.stderr.write(`${d(e.resumeId)}
3
3
  `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await c()):(a=l.node.profile_id,o=l.node.node_id,I(l.node.cwd)&&(g=l.node.cwd))}if(o===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:d}=await import("../profiles/select.js");m&&e.profile===void 0&&process.stdout.write(`
4
4
  Choose a profile
5
- `),a=e.profile??(u?await r(e.cwd,void 0,e.pickProfile):d(e.cwd))}const{exitForMissingProviderCredential:f,hasConfiguredProviderCredential:n}=await import("./provider-credential-gate.js"),{cliClient:w}=await import("../../commands/api-client.js"),P=a===null?[]:(await w().listProfileEnv(a)).names,k=p(async()=>{const r=await w().getModelAuthReadiness({cwd:e.cwd,...a===null?{}:{profile:a}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await n(P)&&!await k()){u||f();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||f()}const{inTmux:R}=await import("./placement-tmux.js");if(u&&!R()){const{TMUX_STARTED_ENV:r,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[r]===void 0&&d(s,o!==void 0?null:a,g)}const[{bootRoot:v},{resumeRoot:y},{rendererWarning:N,missingPackageWarning:O,piAgentDir:S}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=O(S());r!==null&&process.stderr.write(`
5
+ `),a=e.profile??(u?await r(e.cwd,void 0,e.pickProfile,!1):d(e.cwd))}const{exitForMissingProviderCredential:f,hasConfiguredProviderCredential:n}=await import("./provider-credential-gate.js"),{cliClient:w}=await import("../../commands/api-client.js"),P=a===null?[]:(await w().listProfileEnv(a)).names,k=p(async()=>{const r=await w().getModelAuthReadiness({cwd:e.cwd,...a===null?{}:{profile:a}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await n(P)&&!await k()){u||f();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||f()}const{inTmux:R}=await import("./placement-tmux.js");if(u&&!R()){const{TMUX_STARTED_ENV:r,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[r]===void 0&&d(s,o!==void 0?null:a,g)}const[{bootRoot:v},{resumeRoot:y},{rendererWarning:N,missingPackageWarning:O,piAgentDir:S}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=O(S());r!==null&&process.stderr.write(`
6
6
  ${r}
7
7
 
8
8
  `);const d=N();d!==null&&process.stderr.write(`
@@ -1,6 +1,6 @@
1
- var F=Object.defineProperty;var l=(e,t)=>F(e,"name",{value:t,configurable:!0});import{spawn as M}from"node:child_process";import{constants as N,lstatSync as K,mkdirSync as Y,readFileSync as j,readdirSync as z,readlinkSync as q,rmSync as H,writeFileSync as U}from"node:fs";import{join as g,relative as J}from"node:path";import{crc32 as W,deflateRawSync as V}from"node:zlib";import{BlaxelApiError as Z}from"./client.js";const Q="public.ecr.aws/docker/library/node:24-alpine",X="ghcr.io/blaxel-ai/sandbox:latest",m="crtr",S="/var/lib/crtr/recipe-pi-agent",ee="1.1.0",$="recipe-setup.sh",_="repos",v="/work/.crtr/setup.log",A="/work/.crtr/setup-failed",D=l(e=>`'${e.replace(/'/g,"'\\''")}'`,"shellQuote"),te=l(e=>(e??"").split(`
2
- `).map(t=>t.trim()).filter(t=>t!==""),"lines"),I=l((e,t)=>`RUN { ${t}; } >> ${v} 2>&1 || echo ${D(e)} "exited $?" >> ${A}`,"guarded");function re(e,t,a=!1){const o=te(e.pi_packages),i=e.setup_script!==null&&e.setup_script.trim()!=="",n=[`FROM ${Q}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${X} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${m} -s /bin/sh ${m} && mkdir -p /work/.crtr ${S} && chown -R ${m} /work /var/lib/crtr`],r=[`${n[0]} AS build`,...a?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${A} ${v}`,I("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];e.repositories.length>0&&r.push(`COPY --chown=${m} ${_}/ /work/`),o.length>0&&r.push(I("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${ee}`)),i&&r.push(`COPY ${$} /tmp/${$}`),r.push("WORKDIR /work");for(const s of o)r.push(I(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${S} pi install ${D(s)}`));i&&r.push(I("setup script",`bash /tmp/${$}`)),r.push(I("finalize",`echo ${Math.trunc(t)} > /work/.crtr/recipe-revision && chown -R ${m} /work /home/${m} /var/lib/crtr`)),r.push("",...n);for(const s of["/work",`/home/${m}`,"/usr/local","/var/lib/crtr","/usr","/etc","/lib"])r.push(`COPY --from=build ${s} ${s}`);return r.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),a&&r.push(`RUN rm -f /work/.npmrc /home/${m}/.npmrc`),r.push("WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),r.join(`
3
- `)}l(re,"recipeDockerfile");const ne=l((e,t,a)=>new Promise((o,i)=>{const n=M("git",e,{cwd:a,env:{...process.env,...t,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let r="";n.stderr.on("data",s=>{r+=s.toString()}),n.on("error",i),n.on("close",s=>{s===0?o():i(new Error(`git ${e[0]} failed (${s}): ${r.slice(0,300)}`))})}),"runGit");async function ue(e){const t=e.git??ne,a=e.packagesToken??null,o=e.cloneUrl??(n=>`https://github.com/${n}.git`);Y(g(e.dir,_),{recursive:!0});const i=e.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${e.token}`).toString("base64")}`};for(const n of e.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await t(["clone","--quiet","--branch",n.default_branch,o(n.github_full_name),g(_,n.name)],i,e.dir)}U(g(e.dir,"Dockerfile"),re(e.recipe,e.revision,a!==null)),a!==null&&U(g(e.dir,".env.build"),`NODE_AUTH_TOKEN=${a}
4
- `,{mode:384}),e.recipe.setup_script!==null&&e.recipe.setup_script.trim()!==""&&U(g(e.dir,$),e.recipe.setup_script.endsWith(`
5
- `)?e.recipe.setup_script:`${e.recipe.setup_script}
6
- `)}l(ue,"prepareBuildDir");function P(e,t,a){for(const o of z(t).sort()){const i=g(t,o),n=K(i),r=J(e,i).split("\\").join("/");n.isDirectory()?P(e,i,a):n.isSymbolicLink()?a.push({name:r,data:Buffer.from(q(i)),mode:N.S_IFLNK|511}):n.isFile()&&a.push({name:r,data:j(i),mode:N.S_IFREG|n.mode&511})}}l(P,"walk");function se(e){const t=[];P(e,e,t);const a=[],o=[];let i=0;for(const s of t){const u=Buffer.from(s.name),h=V(s.data),b=W(s.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE(b,14),p.writeUInt32LE(h.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(u.length,26),a.push(p,u,h);const c=Buffer.alloc(46);c.writeUInt32LE(33639248,0),c.writeUInt16LE(788,4),c.writeUInt16LE(20,6),c.writeUInt16LE(2048,8),c.writeUInt16LE(8,10),c.writeUInt32LE(33,14),c.writeUInt32LE(b,16),c.writeUInt32LE(h.length,20),c.writeUInt32LE(s.data.length,24),c.writeUInt16LE(u.length,28),c.writeUInt32LE(s.mode<<16>>>0,38),c.writeUInt32LE(i,42),o.push(c,u),i+=p.length+u.length+h.length}const n=Buffer.concat(o),r=Buffer.alloc(22);return r.writeUInt32LE(101010256,0),r.writeUInt16LE(t.length,8),r.writeUInt16LE(t.length,10),r.writeUInt32LE(n.length,12),r.writeUInt32LE(i,16),Buffer.concat([...a,n,r])}l(se,"zipDirectory");async function x(e,t,a,o,i=[]){const n=`${e.controlUrl??"https://api.blaxel.ai/v0"}${a}`,r=await(e.fetch??fetch)(n,{method:t,headers:{authorization:`Bearer ${e.apiKey}`,"x-blaxel-workspace":e.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await r.text();let u=null;if(s!=="")try{u=JSON.parse(s)}catch{u={raw:s}}if(!r.ok&&!i.includes(r.status))throw new Z(r.status,null,`Blaxel ${t} ${n} failed (${r.status}): ${s.slice(0,300)}`);return{status:r.status,headers:r.headers,json:u}}l(x,"api");async function B(e,t){const{status:a,json:o}=await x(e,"GET",`/images/sandbox/${encodeURIComponent(t)}`,void 0,[404]);return a===404?null:o}l(B,"getImage");async function fe(e,t){await x(e,"DELETE",`/images/sandbox/${encodeURIComponent(t)}`,void 0,[404])}l(fe,"deleteImage");async function me(e,t,a,o={}){const i=o.sleep??(f=>new Promise(w=>setTimeout(w,f))),n=o.now??Date.now,r=n(),s=await B(e,t),u=new Set((s?.spec?.tags??[]).map(f=>f.name)),h=s?.metadata?.events?.length??0,p=(await x(e,"POST","/images",{resourceType:"sandbox",name:t})).headers.get("x-blaxel-upload-url");if(p===null)throw new Error(`Blaxel gave no upload URL for image ${t}`);const c=await(e.fetch??fetch)(p,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(se(a))});if(!c.ok)throw new Error(`uploading the build context of image ${t} failed (${c.status}): ${(await c.text()).slice(0,300)}`);const G=r+(o.timeoutMs??20*6e4);let L=null;for(;;){const f=await B(e,t),w=f?.metadata?.status;if(w==="BUILT"&&(f?.metadata?.events?.length??0)>=h+2){L??=n();const E=(f?.spec?.tags??[]).filter(d=>d.name!==void 0),k=(f?.metadata?.events??[]).slice(h).map(d=>d.time??"").filter(d=>d!=="").sort()[0],O=l(d=>k!==void 0&&Date.parse(d??"")>=Date.parse(k),"touchedSince"),R=E.filter(d=>!u.has(d.name)||O(d.createdAt)||O(d.updatedAt)),T=n()-L>=(o.tagGraceMs??6e4),y=(R.length>0?R:T?E:[]).sort((d,C)=>(C.updatedAt??"").localeCompare(d.updatedAt??""))[0]?.name;if(y!==void 0)return{ref:`sandbox/${t}:${y}`,buildMs:n()-r};if(T)throw new Error(`Blaxel built image ${t} but no tag appeared`)}if(w==="FAILED"||w==="TERMINATED"){const E=f?.metadata?.events??[];throw new Error(`building image ${t} ${w.toLowerCase()}: ${E[E.length-1]?.message??"no message"}`)}if(n()>G)throw new Error(`building image ${t} did not finish within ${o.timeoutMs??20*6e4} ms (last status ${w??"none"})`);await i(o.pollMs??3e3)}}l(me,"buildImage");const he=l(e=>`env-${e}`,"environmentImageName");function we(e){H(e,{recursive:!0,force:!0})}l(we,"removeBuildDir");export{Q as NODE_BASE_IMAGE,S as RECIPE_PI_AGENT_DIR,_ as REPOS_DIR,m as RUN_USER,X as SANDBOX_API_IMAGE,A as SETUP_FAILED_FILE,v as SETUP_LOG_FILE,$ as SETUP_SCRIPT_FILE,me as buildImage,fe as deleteImage,he as environmentImageName,B as getImage,ue as prepareBuildDir,re as recipeDockerfile,we as removeBuildDir,se as zipDirectory};
1
+ var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as K}from"node:child_process";import{constants as S,lstatSync as j,mkdirSync as q,readFileSync as z,readdirSync as H,readlinkSync as J,rmSync as W,writeFileSync as _}from"node:fs";import{join as E,relative as V}from"node:path";import{crc32 as Z,deflateRawSync as Q}from"node:zlib";import{BlaxelApiError as X}from"./client.js";const tt="public.ecr.aws/docker/library/node:24-alpine",et="ghcr.io/blaxel-ai/sandbox:latest",h="crtr",A="/var/lib/crtr/recipe-pi-agent",rt="1.1.0",b="recipe-setup.sh",L="repos",D="/work/.crtr/setup.log",P="/work/.crtr/setup-failed",B=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),nt=c(t=>(t??"").split(`
2
+ `).map(r=>r.trim()).filter(r=>r!==""),"lines"),I=c((t,r)=>`RUN { ${r}; } >> ${D} 2>&1 || echo ${B(t)} "exited $?" >> ${P}`,"guarded");function st(t,r,i=!1){const o=nt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${tt}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${et} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${h} -s /bin/sh ${h} && mkdir -p /work/.crtr ${A} && chown -R ${h} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${P} ${D}`,I("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${h} ${L}/ /work/`),o.length>0&&e.push(I("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${rt}`)),a&&e.push(`COPY ${b} /tmp/${b}`),e.push("WORKDIR /work");for(const s of o)e.push(I(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${A} pi install ${B(s)}`));a&&e.push(I("setup script",`bash /tmp/${b}`)),e.push(I("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${h} /work /home/${h} /var/lib/crtr`)),e.push("",...n);for(const s of["/work",`/home/${h}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${h}:${h} ${s} ${s}`);for(const s of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${s} ${s}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push(`RUN rm -f /work/.npmrc /home/${h}/.npmrc`),e.push("WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
3
+ `)}c(st,"recipeDockerfile");const ot=c((t,r,i)=>new Promise((o,a)=>{const n=K("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",s=>{e+=s.toString()}),n.on("error",a),n.on("close",s=>{s===0?o():a(new Error(`git ${t[0]} failed (${s}): ${e.slice(0,300)}`))})}),"runGit");async function ht(t){const r=t.git??ot,i=t.packagesToken??null,o=t.cloneUrl??(n=>`https://github.com/${n}.git`);q(E(t.dir,L),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,o(n.github_full_name),E(L,n.name)],a,t.dir)}_(E(t.dir,"Dockerfile"),st(t.recipe,t.revision,i!==null)),i!==null&&_(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
4
+ `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&_(E(t.dir,b),t.recipe.setup_script.endsWith(`
5
+ `)?t.recipe.setup_script:`${t.recipe.setup_script}
6
+ `)}c(ht,"prepareBuildDir");function C(t,r,i){for(const o of H(r).sort()){const a=E(r,o),n=j(a),e=V(t,a).split("\\").join("/");n.isDirectory()?C(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(J(a)),mode:S.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:z(a),mode:S.S_IFREG|n.mode&511})}}c(C,"walk");function it(t){const r=[];C(t,t,r);const i=[],o=[];let a=0;for(const s of r){const u=Buffer.from(s.name),g=Q(s.data),$=Z(s.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE($,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(u.length,26),i.push(p,u,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE($,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(s.data.length,24),l.writeUInt16LE(u.length,28),l.writeUInt32LE(s.mode<<16>>>0,38),l.writeUInt32LE(a,42),o.push(l,u),a+=p.length+u.length+g.length}const n=Buffer.concat(o),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(it,"zipDirectory");async function N(t,r,i,o,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await e.text();let u=null;if(s!=="")try{u=JSON.parse(s)}catch{u={raw:s}}if(!e.ok&&!a.includes(e.status))throw new X(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${s.slice(0,300)}`);return{status:e.status,headers:e.headers,json:u}}c(N,"api");async function G(t,r){const{status:i,json:o}=await N(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:o}c(G,"getImage");async function mt(t,r){await N(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(mt,"deleteImage");async function wt(t,r,i,o={}){const a=o.sleep??(f=>new Promise(d=>setTimeout(d,f))),n=o.now??Date.now,e=n(),s=await G(t,r),u=new Set((s?.spec?.tags??[]).map(f=>f.name)),g=c(f=>(f?.metadata?.events??[]).map(d=>Date.parse(d.time??"")).filter(d=>!Number.isNaN(d)),"eventTimes"),$=Math.max(-1/0,...g(s)),l=(await N(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(it(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const F=e+(o.timeoutMs??20*6e4);let R=null;for(;;){const f=await G(t,r),d=f?.metadata?.status,k=g(f).filter(m=>m>$).sort((m,x)=>m-x);if(d==="BUILT"&&k.length>=2){R??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],O=c(w=>Date.parse(w??"")>=x,"touchedSince"),T=m.filter(w=>!u.has(w.name)||O(w.createdAt)||O(w.updatedAt)),y=n()-R>=(o.tagGraceMs??6e4),v=(T.length>0?T:y?m:[]).sort((w,M)=>(M.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(v!==void 0)return{ref:`sandbox/${r}:${v}`,buildMs:n()-e};if(y)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(d==="FAILED"||d==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${d.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>F)throw new Error(`building image ${r} did not finish within ${o.timeoutMs??20*6e4} ms (last status ${d??"none"})`);await a(o.pollMs??3e3)}}c(wt,"buildImage");const gt=c(t=>`env-${t}`,"environmentImageName");function Et(t){W(t,{recursive:!0,force:!0})}c(Et,"removeBuildDir");export{tt as NODE_BASE_IMAGE,A as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,h as RUN_USER,et as SANDBOX_API_IMAGE,P as SETUP_FAILED_FILE,D as SETUP_LOG_FILE,b as SETUP_SCRIPT_FILE,wt as buildImage,mt as deleteImage,gt as environmentImageName,G as getImage,ht as prepareBuildDir,st as recipeDockerfile,Et as removeBuildDir,it as zipDirectory};
@@ -0,0 +1,12 @@
1
+ export interface StartingInfo {
2
+ version?: string;
3
+ profile?: string;
4
+ cwd?: string;
5
+ }
6
+ export interface StartingScreen {
7
+ /** Erase the screen and give the terminal back (cursor shown, raw mode off). */
8
+ stop(): void;
9
+ /** Record the created node so an interrupt can say how to reopen it. */
10
+ setNode(nodeId: string): void;
11
+ }
12
+ export declare function showStartingScreen(info: StartingInfo): StartingScreen;
@@ -0,0 +1,9 @@
1
+ var R=Object.defineProperty;var e=(s,t)=>R(s,"name",{value:t,configurable:!0});import{homedir as g}from"node:os";import{croutonBannerLines as A}from"./banner.js";const T="\x1B[2m",x="\x1B[0m",D=100,G="\x1B7",E="\x1B8",S="\x1B[J",L="\x1B[2K";function v(s){const t=process.stdout,h=Date.now();let p=!1,r;const c=g(),u=s.cwd===void 0?void 0:s.cwd===c?"~":s.cwd.startsWith(`${c}/`)?`~${s.cwd.slice(c.length)}`:s.cwd,i=A({...s,...u===void 0?{}:{cwd:u}}).join(`\r
2
+ `),d=e(()=>`${T}starting ${((Date.now()-h)/1e3).toFixed(1)}s${x}`,"seconds"),b=e(()=>{t.write(`\r${L}${d()}`)},"tick"),l=e(()=>{t.write(`${E}${S}${i}\r
3
+ \r
4
+ ${d()}`)},"drawAll"),w=e(()=>r===void 0?"":`crtr: the agent ${r} is still running; reopen it with crtr -r ${r}
5
+ `,"reopenNote"),$=process.stdin.isTTY===!0,f=e(n=>{n.includes(3)&&(a(),process.stderr.write(w()),process.exit(130))},"onData"),o=e(n=>{a(),process.stderr.write(w()),process.kill(process.pid,n)},"onSignal");$&&(process.stdin.setRawMode(!0),process.stdin.on("data",f),process.stdin.resume()),process.once("SIGTERM",o),process.once("SIGHUP",o),t.on("resize",l);const m=i.split(`\r
6
+ `).reduce((n,M)=>n+Math.max(1,Math.ceil(M.replaceAll(/\u001b\[[0-9;]*m/g,"").length/Math.max(1,t.columns??80))),0)+2;t.write(`\x1B[?25l${`
7
+ `.repeat(m)}\x1B[${m}A${G}${i}\r
8
+ \r
9
+ ${d()}`);const I=setInterval(b,D);function a(){p||(p=!0,clearInterval(I),t.off("resize",l),process.off("SIGTERM",o),process.off("SIGHUP",o),t.write(`${E}${S}\x1B[?25h`),$&&(process.stdin.off("data",f),process.stdin.pause(),process.stdin.setRawMode(!1)))}return e(a,"stop"),{stop:a,setNode:e(n=>{r=n},"setNode")}}e(v,"showStartingScreen");export{v as showStartingScreen};
@@ -27,7 +27,7 @@ export declare function recordContentDelivery(db: CanvasDb, reader: Reader, deli
27
27
  * inside its boot, and a document read goes through the read route. */
28
28
  export declare const DRY_RUN_ONLY: readonly DeliveryActivity[];
29
29
  /** One delivery for a live node. Call inside `withCanvasWrite`. */
30
- export declare function deliver(db: CanvasDb, reader: Reader, req: DeliveryRequestInput): Promise<DeliveryResult>;
30
+ export declare function deliver(db: CanvasDb, reader: Reader, req: DeliveryRequestInput, subject?: NodeConfigSubject): Promise<DeliveryResult>;
31
31
  /** A node that does not exist, described by what delivery reads of one:
32
32
  * the directory it would work in, its profile and app, and the fields rule
33
33
  * `if` conditions see. Every field but `cwd` has a default. */