@north-light/cli 0.3.720 → 0.3.721

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 (35) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  4. package/dist/cli.js +8 -8
  5. package/dist/clients/attach/viewer.js +122 -122
  6. package/dist/commands/api-client.d.ts +2 -0
  7. package/dist/commands/api-client.js +2 -2
  8. package/dist/commands/profile/environment.js +2 -2
  9. package/dist/core/canvas/schema-pg/031-environment-pull-request-write-default.sql +2 -0
  10. package/dist/core/canvas/schema-version.d.ts +1 -1
  11. package/dist/core/canvas/schema-version.js +1 -1
  12. package/dist/core/environments.js +1 -1
  13. package/dist/core/graph/reader.js +1 -1
  14. package/dist/core/import/load/open-grants.d.ts +1 -0
  15. package/dist/core/import/load/open-grants.js +1 -0
  16. package/dist/core/import/load/run.d.ts +3 -1
  17. package/dist/core/import/load/run.js +2 -2
  18. package/dist/daemon/api/handlers/profiles.js +1 -1
  19. package/dist/daemon/api/operations.js +1 -1
  20. package/dist/daemon/api/router.d.ts +4 -0
  21. package/dist/daemon/api/router.js +1 -1
  22. package/docs/sdk/release-notes.md +6 -0
  23. package/package.json +3 -3
  24. package/packages/crouter-api/dist/api/contract.js +1 -1
  25. package/packages/crouter-api/dist/commands/api-client.js +3 -1
  26. package/packages/crouter-api/dist/commands/profile/environment.js +2 -2
  27. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  28. package/packages/crouter-api/dist/core/environments.js +1 -1
  29. package/packages/crouter-api/dist/core/graph/reader.js +3 -3
  30. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  31. package/packages/crouter-api/dist/daemon/api/router.js +1 -1
  32. package/packages/crouter-api/package.json +1 -1
  33. package/packages/crouter-identity/package.json +1 -1
  34. package/packages/crouter-plugin/package.json +3 -3
  35. package/runtime.lock.json +14 -14
@@ -34,6 +34,8 @@ export declare const COLD_START_DIAGNOSTIC_TAIL_BYTES = 4096;
34
34
  * contract — a missing/unreadable/empty log yields `undefined` so the base
35
35
  * message is used unchanged. */
36
36
  export declare function readColdStartDiagnostic(): string | undefined;
37
+ /** True when this CLI calls the control plane with a cron's run token; such a process never holds the person's settings. */
38
+ export declare const usesRunToken: () => boolean;
37
39
  /** Where a `crtr` process outside a node reaches the control plane instead of a local daemon: a machine cron's run token goes to
38
40
  * `CRTR_API_URL`; an imported Mac (`runtime/machine.json`) goes to its `apiUrl` with the signed-in person's bearer. Neither: undefined,
39
41
  * and the local socket is used. `CRTR_API_SOCKET` (inside a node) is checked by the caller first and is never remote. */
@@ -1,4 +1,4 @@
1
- var T=Object.defineProperty;var a=(r,t)=>T(r,"name",{value:t,configurable:!0});import{closeSync as N,existsSync as E,fstatSync as A,openSync as O,readFileSync as m,readSync as x}from"node:fs";import{dirname as I,join as l}from"node:path";import{gunzipSync as M}from"node:zlib";import{CrtrClient as p,ApiError as u}from"../api/index.js";import{localClient as f}from"../api/node-transport.js";import{northlightFetch as F,notSignedIn as D,readPersonCredential as P}from"../core/directory/person-credential.js";import{isMoveCommitted as U,moveUnfinishedError as k,readMachineConfig as w}from"../daemon/machine-link/config.js";import{northlightUnreachable as L}from"../core/directory/reach.js";import{apiErrorToCliError as _}from"../core/io.js";import{autostartDisabled as b,daemonAutostartStartupFailure as K,ensureDaemon as B}from"../daemon/manage.js";import{DAEMON_STARTUP_WINDOW_MS as g}from"../daemon/startup-policy.js";import{readState as W}from"../core/config.js";import{resolveRemoteCanvasTarget as j}from"../core/remote-canvas-target.js";import{RemoteCanvasSource as G}from"../core/canvas/remote-canvas-source.js";import{BROKER_RELEASED_MARKER as z,BROKER_RELAY_GENERATION as V,crtrHome as q}from"../core/canvas/paths.js";import{envTestNodeSocketWindowMs as H,isSandboxedNode as Y,providerProjectionOverBrokerRelay as $}from"../shared/env.js";import{CrtrError as v,ownerOnly as J}from"../core/errors.js";import{ExitCode as y}from"../types.js";function d(r){return{...r,fault:r.fault??null}}a(d,"withRowFault");function X(r,t){throw r instanceof u?_(r,t):r}a(X,"rethrowAsCliError");async function Nt(r){try{return await S().getNode(r)}catch(t){if(t instanceof u&&t.status===404)return null;X(t)}}a(Nt,"getNodeOrNull");const Q="crtr_run_",Z=4096,tt=20;function et(){let r;try{r=O(l(q(),"crtrd.log"),"r");const{size:t}=A(r),e=Math.max(0,t-Z),s=t-e;if(s<=0)return;const n=Buffer.alloc(s);x(r,n,0,s,e);const o=n.toString("utf8").split(`
1
+ var T=Object.defineProperty;var a=(r,t)=>T(r,"name",{value:t,configurable:!0});import{closeSync as E,existsSync as N,fstatSync as A,openSync as O,readFileSync as m,readSync as x}from"node:fs";import{dirname as I,join as l}from"node:path";import{gunzipSync as M}from"node:zlib";import{CrtrClient as p,ApiError as u}from"../api/index.js";import{localClient as f}from"../api/node-transport.js";import{northlightFetch as P,notSignedIn as F,readPersonCredential as U}from"../core/directory/person-credential.js";import{isMoveCommitted as D,moveUnfinishedError as k,readMachineConfig as w}from"../daemon/machine-link/config.js";import{northlightUnreachable as K}from"../core/directory/reach.js";import{apiErrorToCliError as _}from"../core/io.js";import{autostartDisabled as b,daemonAutostartStartupFailure as L,ensureDaemon as B}from"../daemon/manage.js";import{DAEMON_STARTUP_WINDOW_MS as C}from"../daemon/startup-policy.js";import{readState as W}from"../core/config.js";import{resolveRemoteCanvasTarget as j}from"../core/remote-canvas-target.js";import{RemoteCanvasSource as G}from"../core/canvas/remote-canvas-source.js";import{BROKER_RELEASED_MARKER as z,BROKER_RELAY_GENERATION as V,crtrHome as q}from"../core/canvas/paths.js";import{envTestNodeSocketWindowMs as H,isSandboxedNode as Y,providerProjectionOverBrokerRelay as $}from"../shared/env.js";import{CrtrError as g,ownerOnly as J}from"../core/errors.js";import{ExitCode as v}from"../types.js";function d(r){return{...r,fault:r.fault??null}}a(d,"withRowFault");function X(r,t){throw r instanceof u?_(r,t):r}a(X,"rethrowAsCliError");async function Nt(r){try{return await y().getNode(r)}catch(t){if(t instanceof u&&t.status===404)return null;X(t)}}a(Nt,"getNodeOrNull");const Q="crtr_run_",Z=4096,tt=20;function et(){let r;try{r=O(l(q(),"crtrd.log"),"r");const{size:t}=A(r),e=Math.max(0,t-Z),s=t-e;if(s<=0)return;const n=Buffer.alloc(s);x(r,n,0,s,e);const o=n.toString("utf8").split(`
2
2
  `).filter(c=>c.trim()!=="").slice(-tt).join(`
3
3
  `).trim();return o===""?void 0:`crtrd.log (tail):
4
- ${o}`}catch{return}finally{if(r!==void 0)try{N(r)}catch{}}}a(et,"readColdStartDiagnostic");function nt(){if(process.env.CRTR_API_SOCKET)return;const r=process.env.CRTR_API_TOKEN,t=process.env.CRTR_API_URL;if(r!==void 0&&r.startsWith(Q)&&t)return{client:a(i=>new p({baseUrl:t,headers:{authorization:`Bearer ${r}`},...i!==void 0?{timeoutMs:i}:{}}),"client")};const e=w();if(e===void 0)return;if(P()===void 0)throw D("this computer is imported into Northlight, so crtr needs your sign-in");const s=F(e.directoryUrl,e.apiUrl),n=a((i,o)=>s(i,o).catch(c=>{throw c instanceof v?C(c):c}),"authed");return{client:a(i=>st(new p({baseUrl:e.apiUrl,fetch:n,...i!==void 0?{timeoutMs:i}:{}}),e.apiUrl),"client")}}a(nt,"remoteTarget");function rt(){return!!process.env.CRTR_API_SOCKET&&(w()!==void 0||$())}a(rt,"relayReachesControlPlane");function st(r,t){return new Proxy(r,{get(e,s){const n=Reflect.get(e,s,e);return typeof n!="function"?n:(...i)=>{const o=n.apply(e,i);return o instanceof Promise?o.catch(c=>{throw c instanceof u&&c.code==="request_timeout"?C(L(c,t)):c}):o}}})}a(st,"unreachableOnTimeout");function C(r){const t=typeof r.details?.next=="string"?r.details.next:void 0;return new u(r.exitCode===y.NETWORK?503:401,r.code,r.message,{error:r.code,message:r.message,...t===void 0?{}:{next:t}})}a(C,"asApiError");function it(){return U()?k():void 0}a(it,"moveUnfinished");function S(r){if(r?.local!==!0){const s=it();if(s!==void 0)throw s}if(r?.local===!0&&rt())throw new v("no_local_daemon","this node reaches Northlight's shared control plane, not a daemon on this computer",y.USAGE,{next:"Ask the person to run this in their own terminal on this computer."});const t=r?.local===!0?void 0:nt();if(t!==void 0)return t.client(r?.timeoutMs);const e=process.env.CRTR_API_SOCKET;if(e){const s=a(()=>{if(!E(e))try{const i=I(e),o=m(l(i,z),"utf8"),c=m(l(i,V),"utf8");if(o===c&&o!=="")return new u(503,"broker_released","This node's broker has been released, so crtr commands from its background jobs are not available.")}catch(i){if(i.code!=="ENOENT")throw i}},"availabilityFailure"),n=s();if(n!==void 0)throw _(n,"Run the command from the node's own turn instead.");return f({autostart:!1,availabilityFailure:s,coldStartPollWindowMs:(b()?H():void 0)??g,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}})}return b()?f({autostart:!1,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}}):f({...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{},onColdSocket:a(async()=>{B()},"onColdSocket"),coldStartDiagnostic:et,coldStartFailure:K,coldStartPollWindowMs:g})}a(S,"cliClient");const ot=2e3;class R{static{a(this,"ApiCanvasSource")}client;rosterCache=null;rosterInFlight=null;constructor(t=S()){this.client=t}async roster(){const t=Date.now();return this.rosterCache!==null&&t-this.rosterCache.at<ot?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(e=>{const s={snapshot:e,subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i={node_id:n.to_id,active:n.active,created:n.created},o={node_id:n.from_id,active:n.active,created:n.created},c=s.subscriptions.get(n.from_id);c===void 0?s.subscriptions.set(n.from_id,[i]):c.push(i);const h=s.subscribers.get(n.to_id);h===void 0?s.subscribers.set(n.to_id,[o]):h.push(o)}return this.rosterCache={at:Date.now(),index:s},s}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(t){try{return await t()}catch(e){if(e instanceof u&&e.status===404)return null;throw e}}async getNode(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async getRow(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async listNodes(t){const e=t?.status,s=t?.under===void 0?{}:{under:t.under,under_inclusive:!0};let n;if(Array.isArray(e)){const i=new Set(e);n=(await this.client.listNodes(s)).filter(c=>i.has(c.status))}else n=await this.client.listNodes({...e!==void 0?{status:e}:{},...s});return n.map(i=>d(i))}async browseSnapshot(){const t=await this.client.canvasBrowseCompressed(),e=JSON.parse(M(t).toString("utf8")),s={subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i=s.subscriptions.get(n.from_id)??[];i.push({node_id:n.to_id,active:n.active,created:n.created}),s.subscriptions.set(n.from_id,i);const o=s.subscribers.get(n.to_id)??[];o.push({node_id:n.from_id,active:n.active,created:n.created}),s.subscribers.set(n.to_id,o)}return this.rosterCache={at:Date.now(),index:s},e.nodes.map(n=>d(n))}async panelView(t){return await this.client.canvasView(t)}async panelRoster(){const t=await this.roster();return t.snapshot!==void 0?t.snapshot:(this.rosterCache=null,(await this.roster()).snapshot)}async subscriptionsOf(t){return this.roster().then(e=>e.subscriptions.get(t)??[])}async subscribersOf(t){return this.roster().then(e=>e.subscribers.get(t)??[])}async view(t){const e=new Set([t]),s=[],n=(await this.subscriptionsOf(t)).map(i=>i.node_id);for(;n.length>0;){const i=n.shift();if(!e.has(i)){e.add(i),s.push(i);for(const o of await this.subscriptionsOf(i))e.has(o.node_id)||n.push(o.node_id)}}return s}async ticketCountsForNodes(t){return(await this.client.attentionCounts([...t])).counts}async ticketCountsForView(t){return this.ticketCountsForNodes([t,...await this.view(t)])}async newestReport(t){return(await this.client.getReports(t,{limit:1}))[0]??null}async hasActiveLiveSubscription(t){const e=(await this.subscriptionsOf(t)).filter(s=>s.active);for(const s of e){const n=await this.getRow(s.node_id);if(n&&(n.status==="active"||n.status==="idle"))return!0}return!1}}function Et(r,t=Y()){const e=r?.scope??"user";if(t){if(r?.canvasName!==void 0)throw J("--canvas selects the person's remote canvas targets, which an app's node cannot reach","Omit --canvas; this node reads its own runtime's canvas.");return new R}const s=r?.canvasName??W(e).activeCanvas??null;if(!s)return new R;const{previewEndpoint:n,relayToken:i}=j(s,e);return new G(n,i)}a(Et,"cliCanvasSource");export{R as ApiCanvasSource,Z as COLD_START_DIAGNOSTIC_TAIL_BYTES,Et as cliCanvasSource,S as cliClient,Nt as getNodeOrNull,it as moveUnfinished,et as readColdStartDiagnostic,rt as relayReachesControlPlane,nt as remoteTarget,X as rethrowAsCliError};
4
+ ${o}`}catch{return}finally{if(r!==void 0)try{E(r)}catch{}}}a(et,"readColdStartDiagnostic");const nt=a(()=>!process.env.CRTR_API_SOCKET&&!!process.env.CRTR_API_URL&&!!process.env.CRTR_API_TOKEN?.startsWith(Q),"usesRunToken");function rt(){if(process.env.CRTR_API_SOCKET)return;const r=process.env.CRTR_API_TOKEN,t=process.env.CRTR_API_URL;if(nt()&&r&&t)return{client:a(i=>new p({baseUrl:t,headers:{authorization:`Bearer ${r}`},...i!==void 0?{timeoutMs:i}:{}}),"client")};const e=w();if(e===void 0)return;if(U()===void 0)throw F("this computer is imported into Northlight, so crtr needs your sign-in");const s=P(e.directoryUrl,e.apiUrl),n=a((i,o)=>s(i,o).catch(c=>{throw c instanceof g?R(c):c}),"authed");return{client:a(i=>it(new p({baseUrl:e.apiUrl,fetch:n,...i!==void 0?{timeoutMs:i}:{}}),e.apiUrl),"client")}}a(rt,"remoteTarget");function st(){return!!process.env.CRTR_API_SOCKET&&(w()!==void 0||$())}a(st,"relayReachesControlPlane");function it(r,t){return new Proxy(r,{get(e,s){const n=Reflect.get(e,s,e);return typeof n!="function"?n:(...i)=>{const o=n.apply(e,i);return o instanceof Promise?o.catch(c=>{throw c instanceof u&&c.code==="request_timeout"?R(K(c,t)):c}):o}}})}a(it,"unreachableOnTimeout");function R(r){const t=typeof r.details?.next=="string"?r.details.next:void 0;return new u(r.exitCode===v.NETWORK?503:401,r.code,r.message,{error:r.code,message:r.message,...t===void 0?{}:{next:t}})}a(R,"asApiError");function ot(){return D()?k():void 0}a(ot,"moveUnfinished");function y(r){if(r?.local!==!0){const s=ot();if(s!==void 0)throw s}if(r?.local===!0&&st())throw new g("no_local_daemon","this node reaches Northlight's shared control plane, not a daemon on this computer",v.USAGE,{next:"Ask the person to run this in their own terminal on this computer."});const t=r?.local===!0?void 0:rt();if(t!==void 0)return t.client(r?.timeoutMs);const e=process.env.CRTR_API_SOCKET;if(e){const s=a(()=>{if(!N(e))try{const i=I(e),o=m(l(i,z),"utf8"),c=m(l(i,V),"utf8");if(o===c&&o!=="")return new u(503,"broker_released","This node's broker has been released, so crtr commands from its background jobs are not available.")}catch(i){if(i.code!=="ENOENT")throw i}},"availabilityFailure"),n=s();if(n!==void 0)throw _(n,"Run the command from the node's own turn instead.");return f({autostart:!1,availabilityFailure:s,coldStartPollWindowMs:(b()?H():void 0)??C,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}})}return b()?f({autostart:!1,...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{}}):f({...r?.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{},onColdSocket:a(async()=>{B()},"onColdSocket"),coldStartDiagnostic:et,coldStartFailure:L,coldStartPollWindowMs:C})}a(y,"cliClient");const at=2e3;class S{static{a(this,"ApiCanvasSource")}client;rosterCache=null;rosterInFlight=null;constructor(t=y()){this.client=t}async roster(){const t=Date.now();return this.rosterCache!==null&&t-this.rosterCache.at<at?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(e=>{const s={snapshot:e,subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i={node_id:n.to_id,active:n.active,created:n.created},o={node_id:n.from_id,active:n.active,created:n.created},c=s.subscriptions.get(n.from_id);c===void 0?s.subscriptions.set(n.from_id,[i]):c.push(i);const h=s.subscribers.get(n.to_id);h===void 0?s.subscribers.set(n.to_id,[o]):h.push(o)}return this.rosterCache={at:Date.now(),index:s},s}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(t){try{return await t()}catch(e){if(e instanceof u&&e.status===404)return null;throw e}}async getNode(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async getRow(t){const e=await this.orNull(()=>this.client.getNode(t));return e===null?null:d(e)}async listNodes(t){const e=t?.status,s=t?.under===void 0?{}:{under:t.under,under_inclusive:!0};let n;if(Array.isArray(e)){const i=new Set(e);n=(await this.client.listNodes(s)).filter(c=>i.has(c.status))}else n=await this.client.listNodes({...e!==void 0?{status:e}:{},...s});return n.map(i=>d(i))}async browseSnapshot(){const t=await this.client.canvasBrowseCompressed(),e=JSON.parse(M(t).toString("utf8")),s={subscriptions:new Map,subscribers:new Map};for(const n of e.edges){const i=s.subscriptions.get(n.from_id)??[];i.push({node_id:n.to_id,active:n.active,created:n.created}),s.subscriptions.set(n.from_id,i);const o=s.subscribers.get(n.to_id)??[];o.push({node_id:n.from_id,active:n.active,created:n.created}),s.subscribers.set(n.to_id,o)}return this.rosterCache={at:Date.now(),index:s},e.nodes.map(n=>d(n))}async panelView(t){return await this.client.canvasView(t)}async panelRoster(){const t=await this.roster();return t.snapshot!==void 0?t.snapshot:(this.rosterCache=null,(await this.roster()).snapshot)}async subscriptionsOf(t){return this.roster().then(e=>e.subscriptions.get(t)??[])}async subscribersOf(t){return this.roster().then(e=>e.subscribers.get(t)??[])}async view(t){const e=new Set([t]),s=[],n=(await this.subscriptionsOf(t)).map(i=>i.node_id);for(;n.length>0;){const i=n.shift();if(!e.has(i)){e.add(i),s.push(i);for(const o of await this.subscriptionsOf(i))e.has(o.node_id)||n.push(o.node_id)}}return s}async ticketCountsForNodes(t){return(await this.client.attentionCounts([...t])).counts}async ticketCountsForView(t){return this.ticketCountsForNodes([t,...await this.view(t)])}async newestReport(t){return(await this.client.getReports(t,{limit:1}))[0]??null}async hasActiveLiveSubscription(t){const e=(await this.subscriptionsOf(t)).filter(s=>s.active);for(const s of e){const n=await this.getRow(s.node_id);if(n&&(n.status==="active"||n.status==="idle"))return!0}return!1}}function At(r,t=Y()){const e=r?.scope??"user";if(t){if(r?.canvasName!==void 0)throw J("--canvas selects the person's remote canvas targets, which an app's node cannot reach","Omit --canvas; this node reads its own runtime's canvas.");return new S}const s=r?.canvasName??W(e).activeCanvas??null;if(!s)return new S;const{previewEndpoint:n,relayToken:i}=j(s,e);return new G(n,i)}a(At,"cliCanvasSource");export{S as ApiCanvasSource,Z as COLD_START_DIAGNOSTIC_TAIL_BYTES,At as cliCanvasSource,y as cliClient,Nt as getNodeOrNull,ot as moveUnfinished,et as readColdStartDiagnostic,st as relayReachesControlPlane,rt as remoteTarget,X as rethrowAsCliError,nt as usesRunToken};
@@ -1,2 +1,2 @@
1
- var g=Object.defineProperty;var n=(e,r)=>g(e,"name",{value:r,configurable:!0});import{readFileSync as w}from"node:fs";import{resolve as y}from"node:path";import{defineLeaf as p,defineBranch as b}from"../../core/command.js";import{usage as m}from"../../core/errors.js";import{cliClient as u}from"../api-client.js";import{resolveProfileViaDaemon as c}from"./daemon-profiles.js";const d={kind:"flag",name:"profile",type:"string",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},f=[{name:"profile_id",type:"string",required:!0,constraint:"Stable profile id."},{name:"repositories",type:"string[]",required:!0,constraint:"`owner/name` in checkout order; the first is where nodes start (`/work/<name>`)."},{name:"setup_script",type:"string",required:!1,constraint:"The script the image build runs; null when none."},{name:"pi_packages",type:"string",required:!1,constraint:"pi package sources, one per line; null when none."},{name:"memory_mb",type:"number",required:!0,constraint:"Memory of new sandboxes: 2048, 4096 or 8192."},{name:"allow_pull_request_write",type:"boolean",required:!0,constraint:"Whether sandboxes may merge pull requests: their GitHub credential carries pull_requests write besides contents write."},{name:"recipe_revision",type:"number",required:!0,constraint:"Raised by one each time the recipe changes."},{name:"image_revision",type:"number",required:!1,constraint:"The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build."},{name:"image_error",type:"string",required:!1,constraint:"Why the last image build failed; null when it did not."}];function h(e){const{environment_id:r,...t}=e;return t}n(h,"output");const k=p({name:"show",description:"show a cloud profile's recipe, memory and image state",whenToUse:"checking what a dev profile builds and runs in, or whether the image for its latest recipe is ready (`image_revision` equals `recipe_revision`).",help:{name:"profile environment show",summary:"a cloud profile's environment: repositories, setup script, pi packages, memory and image build state",params:[d],output:[...f],outputKind:"object",effects:["Read-only. Refuses a profile that does not run in a cloud environment."]},run:n(async e=>{const{id:r}=await c(e.profile);return h(await u().getProfileEnvironment(r))},"run")}),v=p({name:"set",description:"change a cloud profile's repositories, setup script, pi packages, memory or pull request merging",whenToUse:"a dev profile needs other repositories, a setup script for its image (run as root in the build, working directory `/work`), pi packages, or more memory. A flag left out keeps its value.",help:{name:"profile environment set",summary:"change a cloud profile's environment recipe or memory",params:[d,{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each."},{kind:"flag",name:"setup-script-file",type:"path",required:!1,constraint:"File holding the setup script the image build runs as root."},{kind:"flag",name:"pi-package",type:"string",required:!1,repeatable:!0,constraint:"pi package source (repeat per package); replaces the whole list."},{kind:"flag",name:"allow-pull-request-write",type:"bool",required:!1,constraint:"Pass it to let the sandboxes merge pull requests (their GitHub credential adds pull_requests write); `--no-allow-pull-request-write` returns to contents write only. Takes effect on the next credential a sandbox fetches; builds no image."},{kind:"flag",name:"memory",type:"int",required:!1,constraint:"Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory."}],output:[...f],outputKind:"object",effects:["A changed recipe raises `recipe_revision`, and the daemon builds a new image for it; check `profile environment show`. A recipe identical to the stored one changes nothing."]},run:n(async e=>{const{id:r}=await c(e.profile),t=e.repo,s=e.setupScriptFile,o=e.piPackage,i=e.memory,a=e.allowPullRequestWrite;if(i!==void 0&&![2,4,8].includes(i))throw m("`--memory` is 2, 4 or 8 (GB).");const l={...t!==void 0&&t.length>0?{repositories:t}:{},...s!==void 0?{setup_script:w(y(s),"utf8")}:{},...o!==void 0&&o.length>0?{pi_packages:o.join(`
2
- `)}:{},...i!==void 0?{memory_mb:i*1024}:{},...a!==void 0?{allow_pull_request_write:a}:{}};if(Object.keys(l).length===0)throw m("pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`, `--allow-pull-request-write`.");return h(await u().setProfileEnvironment(r,l))},"run")}),A=b({name:"environment",description:"a cloud profile's recipe (repositories, setup script, pi packages) and sandbox memory",whenToUse:"viewing or changing what a cloud dev profile's sandboxes are built from and how much memory they get.",help:{name:"profile environment",summary:"a cloud profile's environment recipe and memory",model:"A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from; changing the recipe makes the daemon build a new image, and new sandboxes use it. Memory applies to new sandboxes only."},children:[k,v]});export{A as environmentBranch};
1
+ var g=Object.defineProperty;var i=(e,r)=>g(e,"name",{value:r,configurable:!0});import{readFileSync as y}from"node:fs";import{resolve as w}from"node:path";import{defineLeaf as p,defineBranch as b}from"../../core/command.js";import{usage as u}from"../../core/errors.js";import{cliClient as m}from"../api-client.js";import{resolveProfileViaDaemon as c}from"./daemon-profiles.js";const d={kind:"flag",name:"profile",type:"string",required:!0,constraint:"Profile id or manifest name; a close-enough name resolves to the nearest profile, reported on stderr."},f=[{name:"profile_id",type:"string",required:!0,constraint:"Stable profile id."},{name:"repositories",type:"string[]",required:!0,constraint:"`owner/name` in checkout order; the first is where nodes start (`/work/<name>`)."},{name:"setup_script",type:"string",required:!1,constraint:"The script the image build runs; null when none."},{name:"pi_packages",type:"string",required:!1,constraint:"pi package sources, one per line; null when none."},{name:"memory_mb",type:"number",required:!0,constraint:"Memory of new sandboxes: 2048, 4096 or 8192."},{name:"allow_pull_request_write",type:"boolean",required:!0,constraint:"Whether sandboxes may open and merge pull requests: their GitHub credential carries pull_requests write besides contents write. On by default."},{name:"recipe_revision",type:"number",required:!0,constraint:"Raised by one each time the recipe changes."},{name:"image_revision",type:"number",required:!1,constraint:"The recipe revision the current image was built from; the image is ready when it equals recipe_revision. Null before the first build."},{name:"image_error",type:"string",required:!1,constraint:"Why the last image build failed; null when it did not."}];function h(e){const{environment_id:r,...n}=e;return n}i(h,"output");const k=p({name:"show",description:"show a cloud profile's recipe, memory and image state",whenToUse:"checking what a dev profile builds and runs in, or whether the image for its latest recipe is ready (`image_revision` equals `recipe_revision`).",help:{name:"profile environment show",summary:"a cloud profile's environment: repositories, setup script, pi packages, memory and image build state",params:[d],output:[...f],outputKind:"object",effects:["Read-only. Refuses a profile that does not run in a cloud environment."]},run:i(async e=>{const{id:r}=await c(e.profile);return h(await m().getProfileEnvironment(r))},"run")}),q=p({name:"set",description:"change a cloud profile's repositories, setup script, pi packages, memory or pull request merging",whenToUse:"a dev profile needs other repositories, a setup script for its image (run as root in the build, working directory `/work`), pi packages, or more memory. A flag left out keeps its value.",help:{name:"profile environment set",summary:"change a cloud profile's environment recipe or memory",params:[d,{kind:"flag",name:"repo",type:"string",required:!1,repeatable:!0,constraint:"GitHub repository `owner/name` (repeat per repository); replaces the whole list. The GitHub App must be installed on each."},{kind:"flag",name:"setup-script-file",type:"path",required:!1,constraint:"File holding the setup script the image build runs as root."},{kind:"flag",name:"pi-package",type:"string",required:!1,repeatable:!0,constraint:"pi package source (repeat per package); replaces the whole list."},{kind:"flag",name:"allow-pull-request-write",type:"bool",required:!1,constraint:"On by default: sandboxes may open and merge pull requests (their GitHub credential carries pull_requests write). `--no-allow-pull-request-write` drops to contents write only, so sandboxes can push branches but not open pull requests. Takes effect on the next credential a sandbox fetches; builds no image."},{kind:"flag",name:"memory",type:"int",required:!1,constraint:"Sandbox memory in GB: 2, 4 or 8. Reaches sandboxes created after the change; a running sandbox keeps its memory."}],output:[...f],outputKind:"object",effects:["A changed recipe raises `recipe_revision`, and the daemon builds a new image for it; check `profile environment show`. A recipe identical to the stored one changes nothing."]},run:i(async e=>{const{id:r}=await c(e.profile),n=e.repo,s=e.setupScriptFile,o=e.piPackage,t=e.memory,a=e.allowPullRequestWrite;if(t!==void 0&&![2,4,8].includes(t))throw u("`--memory` is 2, 4 or 8 (GB).");const l={...n!==void 0&&n.length>0?{repositories:n}:{},...s!==void 0?{setup_script:y(w(s),"utf8")}:{},...o!==void 0&&o.length>0?{pi_packages:o.join(`
2
+ `)}:{},...t!==void 0?{memory_mb:t*1024}:{},...a!==void 0?{allow_pull_request_write:a}:{}};if(Object.keys(l).length===0)throw u("pass at least one of `--repo`, `--setup-script-file`, `--pi-package`, `--memory`, `--allow-pull-request-write`.");return h(await m().setProfileEnvironment(r,l))},"run")}),A=b({name:"environment",description:"a cloud profile's recipe (repositories, setup script, pi packages) and sandbox memory",whenToUse:"viewing or changing what a cloud dev profile's sandboxes are built from and how much memory they get.",help:{name:"profile environment",summary:"a cloud profile's environment recipe and memory",model:"A cloud profile runs its nodes in Blaxel sandboxes. Its environment holds the recipe the sandbox image is built from; changing the recipe makes the daemon build a new image, and new sandboxes use it. Memory applies to new sandboxes only."},children:[k,q]});export{A as environmentBranch};
@@ -0,0 +1,2 @@
1
+ -- 031-environment-pull-request-write-default.sql — cloud environments open pull requests by default: every existing environment gets `allow_pull_request_write = true` (030 gave them false only as the column default, never as a choice). The column default stays false, because a delta may not change a default old writers rely on; new cloud environments write true explicitly.
2
+ UPDATE environments SET allow_pull_request_write = true;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 30;
4
+ export declare const CANVAS_SCHEMA_VERSION = 31;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=30;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=31;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -1 +1 @@
1
- var f=Object.defineProperty;var a=(e,n)=>f(e,"name",{value:n,configurable:!0});import{openDb as l,withCanvasWrite as c}from"./canvas/db.js";import{createObject as p,ensureOwner as u,ownerForGrantee as w}from"./graph/objects.js";import{writeActsFor as s}from"./permissions/facts.js";import{isCloudRole as v,personIdAsync as E}from"./canvas/person.js";import{writeEnvironmentRecipe as h}from"./environment-recipe.js";import{setCloudProfileWriter as I}from"./profiles/manifest.js";let o=null;async function O(e){const n=new Date().toISOString(),t=await c(async i=>{const r=await i.prepare("SELECT object FROM environments WHERE machine_id = ?").get(e);if(r!==void 0)return await i.prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(n,e),{environmentId:r.object,created:!1};const d=await w(i,"app:terminal"),m=await p(i,{type:"environment",kind:"machine",owner:d.id,privacy:"public",name:e,preview:"machine"});return v()||await s(i,m.id,await E()),await i.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(m.id,e,n),{environmentId:m.id,created:!0}});return o={environmentId:t.environmentId,machineId:e},t}a(O,"registerMachineEnvironment");async function _(e,n){const t=await w(e,n.grantee),i=await u(e,"profile","profile",n.profileId,n.profileId,t),r=await p(e,{type:"environment",kind:"blaxel",owner:i.id,privacy:"private",name:n.profileId,preview:"blaxel"});return await s(e,r.id,n.person),await e.prepare("INSERT INTO environments (object, kind, machine_id, memory_mb, last_seen_at) VALUES (?, 'blaxel', NULL, ?, ?)").run(r.id,n.memoryMb??2048,new Date().toISOString()),n.recipe!==void 0&&await h(e,r.id,n.recipe),r.id}a(_,"createProfileBlaxelEnvironment");async function A(e){o!==null&&await(await l()).prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(e,o.machineId)}a(A,"touchMachineEnvironment");function D(){if(o===null)throw new Error("the machine environment is not registered yet");return o.environmentId}a(D,"machineEnvironmentId"),I((e,n)=>c(async t=>{await n(await _(t,e))}));export{_ as createProfileBlaxelEnvironment,D as machineEnvironmentId,O as registerMachineEnvironment,A as touchMachineEnvironment};
1
+ var u=Object.defineProperty;var a=(e,n)=>u(e,"name",{value:n,configurable:!0});import{openDb as d,withCanvasWrite as c}from"./canvas/db.js";import{createObject as p,ensureOwner as f,ownerForGrantee as w}from"./graph/objects.js";import{writeActsFor as s}from"./permissions/facts.js";import{isCloudRole as v,personIdAsync as E}from"./canvas/person.js";import{writeEnvironmentRecipe as h}from"./environment-recipe.js";import{setCloudProfileWriter as _}from"./profiles/manifest.js";let o=null;async function O(e){const n=new Date().toISOString(),t=await c(async r=>{const i=await r.prepare("SELECT object FROM environments WHERE machine_id = ?").get(e);if(i!==void 0)return await r.prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(n,e),{environmentId:i.object,created:!1};const l=await w(r,"app:terminal"),m=await p(r,{type:"environment",kind:"machine",owner:l.id,privacy:"public",name:e,preview:"machine"});return v()||await s(r,m.id,await E()),await r.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(m.id,e,n),{environmentId:m.id,created:!0}});return o={environmentId:t.environmentId,machineId:e},t}a(O,"registerMachineEnvironment");async function I(e,n){const t=await w(e,n.grantee),r=await f(e,"profile","profile",n.profileId,n.profileId,t),i=await p(e,{type:"environment",kind:"blaxel",owner:r.id,privacy:"private",name:n.profileId,preview:"blaxel"});return await s(e,i.id,n.person),await e.prepare("INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?)").run(i.id,n.memoryMb??2048,new Date().toISOString()),n.recipe!==void 0&&await h(e,i.id,n.recipe),i.id}a(I,"createProfileBlaxelEnvironment");async function A(e){o!==null&&await(await d()).prepare("UPDATE environments SET last_seen_at = ? WHERE machine_id = ?").run(e,o.machineId)}a(A,"touchMachineEnvironment");function D(){if(o===null)throw new Error("the machine environment is not registered yet");return o.environmentId}a(D,"machineEnvironmentId"),_((e,n)=>c(async t=>{await n(await I(t,e))}));export{I as createProfileBlaxelEnvironment,D as machineEnvironmentId,O as registerMachineEnvironment,A as touchMachineEnvironment};
@@ -1,3 +1,3 @@
1
1
  var W=Object.defineProperty;var s=(o,e)=>W(o,"name",{value:e,configurable:!0});import{coveredByAny as _,isSandboxedNode as $}from"../../shared/env.js";import{projectPaths as D}from"../../api/dto/profiles.js";import{existsSync as N}from"node:fs";import{CrtrError as B}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as C}from"@north-light/identity";import{activeGrant as x,grantFor as A,runtimeScope as J}from"../grants/mirror.js";import{withCanvasWrite as P}from"../canvas/db.js";import{ApiError as k}from"../../api/errors.js";import{pluginAppToken as G}from"../secrets.js";import{loadExactProfileManifest as q}from"../profiles/manifest.js";import{ensureOwner as L,getById as U,nodeObject as Y,ownerForGrantee as z,profileHandle as K}from"./objects.js";import{personId as Q,personIdAsync as V}from"../canvas/person.js";import{OBJECT_TYPE as X}from"../permissions/builtin.js";import{warmCheckoutDirs as M}from"../checkout-identities.js";import{fillProfileProjectRepo as Z}from"../profiles/manifest.js";import{emitEvent as I}from"../events/emit.js";import{isCloudRole as R}from"../canvas/person-state.js";import{loadReadAccess as ee,readableAmong as oe,prefetchRepoReads as te,reposForCwd as ne,warmCheckoutIdentities as b}from"./repo-sync/repos.js";async function T(o,e,t,r,n,a){const l=t===null?[]:n.projects(t),p=l.length===0?void 0:a??await V(),c=p===void 0?void 0:await ee(o,p);c!==void 0&&p!==void 0&&await te(o,p,[e,...l.flatMap(i=>i.path!==void 0&&(R()||N(i.path))?[i.path]:[])],c);const d=l.flatMap(i=>i.repo===void 0?[]:[i.repo]),f=p===void 0?new Set:await oe(o,p,d,c),g=await r(e,a,c),w=new Set(g.map(i=>i.repo.id)),E=[],m=[];for(const i of l){if(i.repo!==void 0&&!w.has(i.repo)){const u=await n.object(i.repo);u!==null&&u.type==="repo"&&u.deleted_at===null&&f.has(u.id)&&(w.add(u.id),E.push(u))}if(i.path===void 0||!R()&&!N(i.path))continue;let y;try{y=await r(i.path,a,c)}catch(u){if(u instanceof B&&u.code==="git-lookup-failed")continue;throw u}for(const u of y)w.has(u.repo.id)||(w.add(u.repo.id),E.push(u.repo),m.push(u))}return{repos:g.map(i=>i.repo),checkouts:g,projectRepos:E,projectCheckouts:m}}s(T,"viewRepos");async function Ce(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?D(j(o).projects(t.profile_id)):[];if(R()){await re(t.profile_id,[t.cwd,...r]);return}await b(t.cwd);for(const n of r)N(n)&&await b(n)}s(Ce,"warmNodeRepos");async function re(o,e){if(await M(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 P(async n=>await ne(n,t.path)))[0];r!==void 0&&await Z(o,t.path,r.id)}catch(r){I({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(re,"warmCloudNodeCheckouts");async function xe(o,e,t){if(!R()){for(const n of t)await b(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await M(r?.profile_id,t)}s(xe,"warmNodeDirs");async function Ae(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 F(o)};if(e.class==="app")return{class:"app",app:await S(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 F(o)};const p=await A(e.actor.app,e.sub);if(!p)throw new k(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const c=e.actor.node_scopes;return{class:"app",app:await S(o,e.actor.app),place:e.actor.place,launched:c,scopes:c===null?p.resolved:c.filter(d=>_(p.resolved,d))}}if(e.class==="cron"){const p=e.grant?(await x(e.grant))?.resolved??[]:[],c=e.scopes;return{class:"app",app:await S(o,e.app),scopes:c===null?p:c.filter(d=>_(p,d)),launched:c,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=j(o),n=await Y(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 H(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await T(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(Ae,"readerFor");async function ae(o,e,t,r=j(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:p,sub:c,grant_id:d,scopes_json:f,cwd:g,profile_id:w,app:E}=l,m=E===null?null:await r.object(E);if(!m)throw new Error(`node ${e} has no app`);const i=f===null?null:JSON.parse(f);return{class:"node",node:a,app:m,scopes:await H(p,c??"",d,i,r,n),launched:i,cwd:g,...await T(o,g,w,t,r,c||void 0),profile:w===null?null:await r.profile(w,m)}}s(ae,"readerForNode");class se extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function Le(o,e,t=async()=>[],r=j(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await pe(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ae(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 p=(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(!p)throw new se;const c=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",d=J(),f=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${d.sql}`).all(c,...d.args),g=s(h=>JSON.parse(h.resolved_scopes_json).filter(O=>O.mode==="always").map(O=>C(O.scope)),"always"),w=f.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(X,e.id)).map(h=>h.subject_id)):null,E=w===null?void 0:f.find(h=>w.has(h.sub.replace(/^user:/,"")))?.sub,m=E===void 0?null:await r.grantFor(c,E),i=a.type==="person"?null:f.length===0?r.pluginScopes(c):f.length===1?g(f[0]):m?.resolved??null,u=(a.type==="person"?(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(a.id))?.external_id:void 0)??(f.length===1?f[0].sub:m?.sub);return{class:"object",object:e,node:e,owner:a,app:p,scopes:i,...u===void 0?{}:{sub:u},repos:a.type==="repo"?[a]:[]}}s(Le,"readerForObject");async function Me(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=>C(a.scope))}s(Me,"appScopesNow");async function pe(o,e,t,r){const n=await F(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 S(o,t.app),l=t?.app==null?null:await r.grantFor(t.app,t.sub),p=t===null||l===null?null:t.node_scopes===null?l.resolved:t.node_scopes.filter(d=>_(l.resolved,d)),c=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:c,app:c,scopes:p,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(pe,"readerForStub");function j(o){return{grantById:x,grantFor:A,pluginScopes:s(e=>G(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await U(o,e),"object"),profile:s(async(e,t)=>await ce(o,e,t),"profile"),projects:s(e=>$()?[]:v(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function Te(o){const e=j(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(Te,"publishLookups");async function H(o,e,t,r,n,a=!1){const l=t?await n.grantById(t):await n.grantFor(o,e),p=l&&l.grantee===o?l.resolved:null;if(p===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?p:r.filter(c=>_(p,c))}s(H,"nodeScopes");async function F(o){return await z(o,Q())}s(F,"personObject");async function S(o,e){return await L(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function ce(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
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:p,sub:c,grant_id:d,scopes_json:f,cwd:g,profile_id:w,app:E}=l,m=E===null?null:await r.object(E);if(!m)throw new Error(`node ${e} has no app`);const i=f===null?null:JSON.parse(f);return{class:"node",node:a,app:m,scopes:await H(p,c??"",d,i,r,n),launched:i,cwd:g,...await T(o,g,w,t,r,c||void 0),profile:w===null?null:await r.profile(w,m)}}s(ae,"readerForNode");class se extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function Le(o,e,t=async()=>[],r=j(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await pe(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ae(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 p=(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(!p)throw new se;const c=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",d=J(),f=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${d.sql}`).all(c,...d.args),g=s(h=>JSON.parse(h.resolved_scopes_json).filter(O=>O.mode==="always").map(O=>C(O.scope)),"always"),w=f.length>1&&(a.type==="app"||a.type==="repo")?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(X,a.type==="repo"?a.id:e.id)).map(h=>h.subject_id)):null,E=w===null?void 0:f.find(h=>w.has(h.sub.replace(/^user:/,"")))?.sub,m=E===void 0?null:await r.grantFor(c,E),i=a.type==="person"?null:f.length===0?r.pluginScopes(c):f.length===1?g(f[0]):m?.resolved??null,u=(a.type==="person"?(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(a.id))?.external_id:void 0)??(f.length===1?f[0].sub:m?.sub);return{class:"object",object:e,node:e,owner:a,app:p,scopes:i,...u===void 0?{}:{sub:u},repos:a.type==="repo"?[a]:[]}}s(Le,"readerForObject");async function Me(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=>C(a.scope))}s(Me,"appScopesNow");async function pe(o,e,t,r){const n=await F(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 S(o,t.app),l=t?.app==null?null:await r.grantFor(t.app,t.sub),p=t===null||l===null?null:t.node_scopes===null?l.resolved:t.node_scopes.filter(d=>_(l.resolved,d)),c=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:c,app:c,scopes:p,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(pe,"readerForStub");function j(o){return{grantById:x,grantFor:A,pluginScopes:s(e=>G(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await U(o,e),"object"),profile:s(async(e,t)=>await ce(o,e,t),"profile"),projects:s(e=>$()?[]:v(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function Te(o){const e=j(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(Te,"publishLookups");async function H(o,e,t,r,n,a=!1){const l=t?await n.grantById(t):await n.grantFor(o,e),p=l&&l.grantee===o?l.resolved:null;if(p===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?p:r.filter(c=>_(p,c))}s(H,"nodeScopes");async function F(o){return await z(o,Q())}s(F,"personObject");async function S(o,e){return await L(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function ce(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
3
  WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await L(o,"profile","profile",e,K(e,q(e).manifest.name),t)}s(ce,"profileObject");export{se as NoOwningAppError,Me as appScopesNow,j as liveLookups,ce as profileObject,Te as publishLookups,Ae as readerFor,ae as readerForNode,Le as readerForObject,T as viewRepos,re as warmCloudNodeCheckouts,xe as warmNodeDirs,Ce as warmNodeRepos};
@@ -0,0 +1 @@
1
+ export declare function openImportGrants(runId: string): Promise<void>;
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var s=(o,t)=>a(o,"name",{value:t,configurable:!0});import{directoryIssuer as c}from"../../directory/issuer.js";import{outboundFetch as p}from"../../events/outbound.js";import{mintDirectoryToken as m}from"../../grants/sync.js";import{ImportLaneError as n}from"./stage.js";async function y(o){const t=c();if(t===null)throw new n("open-grants","directory_refused","the directory is not configured, so the person's grants cannot be copied onto the fleet runtime");const i=`${t}/v1/runtime/imports/${encodeURIComponent(o)}/open`;let r;try{const e=await m(t);r=await p("import_open_grants",i,{method:"POST",headers:{Authorization:`Bearer ${e.access_token}`},signal:AbortSignal.timeout(12e4)})}catch(e){throw new n("open-grants","directory_refused",`the directory could not be asked to copy the grants: ${e instanceof Error?e.message:String(e)}`)}if(!r.ok)throw new n("open-grants","directory_refused",`the directory refused to copy the person's grants onto the fleet runtime: ${r.status}`)}s(y,"openImportGrants");export{y as openImportGrants};
@@ -13,10 +13,12 @@ export interface RunOptions {
13
13
  blobs?: BlobStore;
14
14
  /** The control plane's fleet runtime principal, the key of the directory's grants (`CRTR_RUNTIME`). */
15
15
  fleetRuntime?: string | null;
16
+ /** Asks the directory to copy the person's grants onto the fleet runtime; default is the directory's `POST /v1/runtime/imports/:run/open`. */
17
+ openGrants?: (runId: string) => Promise<void>;
16
18
  /** Test hook: called when a step is reached, before it runs. A throw there is that step failing. */
17
19
  atStep?: (step: string) => void | Promise<void>;
18
20
  }
19
- /** How long a loading run waits for the directory to copy the person's grants onto the fleet runtime before it fails `grant_missing` (design-import-fleet-grants G10). */
21
+ /** How long a loading run waits for an unreachable directory to answer for its plugins before it fails `directory_unavailable`. */
20
22
  export declare const GRANT_WAIT_MS: number;
21
23
  /** How far the copy transaction moves the run's lease ahead: renewals cannot land while it holds the row. Copy is bounded by the pause budget of 10 minutes. */
22
24
  export declare const COPY_LEASE_MS: number;
@@ -1,3 +1,3 @@
1
- var X=Object.defineProperty;var m=(e,s)=>X(e,"name",{value:s,configurable:!0});import{zstdCompressSync as Z}from"node:zlib";import{blobStore as x}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as M}from"../../canvas/db.js";import{runAsPerson as ee}from"../../canvas/person.js";import{insertImportedRevisions as te}from"../../graph/documents.js";import{getById as ae}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ie}from"../bundle/layout.js";import{readCatalog as se}from"./catalog.js";import{copyRows as re,decodeKeys as B,encodeKeys as W}from"./copy.js";import{pruneStaged as oe,precheck as de,renameClashingLegacyCharges as pe,renameClashingProfiles as ue,rewriteConversationHeaders as ce,rewritePaths as le,rewriteRequestPaths as fe,takeRepoSyncedDocuments as me}from"./prepare.js";import{boundSub as _e,dropRefusedMessages as we,checkSourcePerson as ge,checkStagedBlobKeys as be,checkStagedPersons as he,checkStagedReferences as ye,checkStagedRequestKeys as Ee}from"./bind.js";import{deleteBlobs as Se,deleteRunBlobs as ve,deleteRunPrefix as Re,moveRunBlobs as Oe}from"./blobs.js";import{dropStubRows as Ie,findFleetGrant as Pe,grantMissing as Te,mapProfileIds as je,renameClashingRepos as ke,rewriteIds as De,rewritePerson as Ce,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as H,ImportLaneError as g,stage as Me,stagingSchema as Ne,targetSchema as Le}from"./stage.js";import{verifyRun as Be}from"./verify.js";import{sandboxPathMap as We,writeNodeFiles as He}from"./path-map.js";import{allStoreKeys as Ke,readPluginsStore as Ue,recordImportedActivations as Fe,writeStores as Je}from"./stores.js";import{publishImportedPlugins as qe}from"./publish-plugins.js";import{COPIED_TABLES as $e}from"../bundle/layout.js";import{emitEvent as Ge}from"../../events/emit.js";import{ClaimLostError as Ye}from"../../../daemon/reconcilers/row-claim.js";const K=10*6e4,ze=30*6e4,R=m(()=>new Date().toISOString(),"now"),O=m(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Qe(e,s){const t=await e.get(N.source(s));if(t===null)throw new g("stage","bundle_invalid","source.json is missing");const a=JSON.parse(t.toString("utf8"));if(typeof a.rowParts!="object"||a.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return a}m(Qe,"readSource");async function Ve(e,s,t,a,n,p){const o=[];for(const l of L(t.run_id,"grants",a)){const f=await e.get(l);if(f===null)throw new g("stage","bundle_invalid",`row file ${l} is missing`);o.push(...ne(f))}const d=[];for(const l of o){const f=_e(l.sub,a.person,t.person,"grants.sub");await Pe(s,n,p,f,l.grantee)===void 0&&d.push(l.grantee)}if(d.length===0)return!0;if(t.loaded_at===void 0||t.loaded_at===null)throw new g("stage","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(t.loaded_at)>=K)throw Te(d);return!1}m(Ve,"grantsReady");async function vt(e,s,t={}){const a=t.blobs??await x(),n=await v(),p=Ne(e.run_id);let o="start";const d=m(async i=>{o=i,await s.assertOwned(),await O(e.run_id,i),await t.atStep?.(i)},"at");let l=e.state==="committed";const f=[];try{const i=await Qe(a,e.run_id);if(e.source_kind==="machine"&&i.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${i.installId}, the run is for ${e.source_install_id}`);i.installId=e.source_install_id;const c=await Le(n),I=[...$e],b=await se(n,c,[...I,"grants"]);if(!l){const _={},T=[],j=[],k=t.fleetRuntime??process.env.CRTR_RUNTIME??null;if(await ge(n,c,i.person,e.person),!await Ve(a,n,e,i,c,k)){await s.assertOwned(),await O(e.run_id,"waiting_for_grants");return}await d("publish-plugins");const F=await Ue(a,e.run_id),E=await ee(e.person,()=>qe(F));if(E.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=K)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${E.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:E.unavailable});await s.assertOwned(),await O(e.run_id,"waiting_for_directory");return}j.push(...E.refused),await d("stage");const J=await Me(n,e.run_id,i.counts,r=>L(e.run_id,r,i),r=>a.get(r));for(const[r,u]of Object.entries(J))_[r]={staged:u,inserted:0,mapped:0,dropped:0};const w={db:n,schema:p,target:c,catalog:b,sourcePerson:i.person,targetPerson:e.person,fleetRuntime:k,shippedBodies:i.shippedBodies??{}};await d("bind-staged");for(const[r,u]of Object.entries(await he(w)))h(_,r,u);for(const[r,u]of Object.entries(await be(w)))h(_,r,u);await d("rewrite-person"),await Ce(w),await Ae(w),await d("prune");const q=await oe(n,p,b,i),S=i.kind==="hosted"?We(i.pathPrefixes??[]):[];await d("rewrite-paths"),await le(n,p,S),await ce(n,p,S,a,e.run_id),await fe(n,p),await Ee(w);const $=await je(w);await ue(n,p,c,i.installId,e.person),await d("rewrite-ids");const D=await De(w,$);await d("drop");const G=await me(n,p,c),Y=await Ie(w);for(const[r,u]of Object.entries({...q}))h(_,r,u);for(const[r,u]of Object.entries(Y))h(_,r,u);for(const[r,u]of Object.entries(await we(w,{installId:i.installId,person:e.person,runId:e.run_id})))h(_,r,u);await ye(w,{installId:i.installId,person:e.person,runId:e.run_id}),await ke(w),await pe(n,p,c,i.installId),await d("pre-check");const z=new Map([["messages",["seq"]],...ie.map(r=>[r,["seq"]])]);await de(n,p,c,b,I,new Set,z),await d("blobs"),await Oe(n,p,c,e.person,a,e.run_id,f),await d("copy"),await M(async r=>{await s.assertOwned({extendLeaseMs:ze});const u=await re({db:r,runId:e.run_id,schema:p,target:c,catalog:b,source:i,person:e.person,idMap:D,pathMap:S}),C=await xe(r,e.run_id,G);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await He(r,p,e.run_id,i);const A=await Je({db:r,blobs:a,runId:e.run_id,person:e.person,objectMap:D.object});for(const[Q,V]of Object.entries(A.inserted))u.inserted[Q]=V.length;return T.push(...A.unresolvedPlugins),await r.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...Ze(_,u),unresolved_plugins:T,refused_plugins:j}),R(),e.run_id),u}),l=!0,await t.atStep?.("committed")}await d("verify");const y=await Be(n,e.run_id,p,c,b,i.installId);if(await n.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await d("manifest");const P=N.manifest(e.run_id);await a.put(P,await et(e.run_id)),await H(n,e.run_id);for(const _ of Ke(e.run_id))await a.delete(_);await ve(a,e.run_id),await M(async _=>{await Fe(_,e.run_id,e.person),await _.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(P,R(),e.run_id)})}catch(i){if(i instanceof Ye)throw i;const c=Xe(i,o);Ge({level:"error",event:"import.run.failed",error:i,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await H(n,e.run_id).catch(()=>{}),l||await Se(a,f,!0),await n.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(a,e.run_id,{keepNodeFiles:l,bestEffort:!0})}}m(vt,"processRun");function Xe(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const t=e.code;return{step:s,code:typeof t=="string"?t:"import_failed",message:e instanceof Error?e.message:String(e)}}m(Xe,"failureOf");function h(e,s,t){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=t}m(h,"addDropped");function Ze(e,s){for(const[t,a]of Object.entries(s.inserted))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=a;for(const[t,a]of Object.entries(s.mapped))(e[t]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=a;return e}m(Ze,"withInserted");async function xe(e,s,t){const a=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(t.map(o=>o.rev_id)))).map(o=>o.rev_id)),n=t.filter(o=>!a.has(o.rev_id)),p=new Map;for(const o of t)p.set(o.document,[...p.get(o.document)??[],o]);for(const[o,d]of p){const l=await ae(e,o);l!==null&&await te(e,l,d.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await U(e,s,"revisions",n.map(o=>[o.rev_id])),await U(e,s,"revision_parents",n.flatMap(o=>o.parents.map(d=>[o.rev_id,d]))),n.length}m(xe,"arrive");async function U(e,s,t,a){if(a.length===0)return;const n=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,t);n===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,t,W(a)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...B(n.inserted_keys),...a]),s,t)}m(U,"appendManifest");async function et(e){const t=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Z(Buffer.from(t.map(a=>JSON.stringify({table:a.table_name,keys:B(a.inserted_keys)})).join(`
1
+ var V=Object.defineProperty;var l=(e,s)=>V(e,"name",{value:s,configurable:!0});import{zstdCompressSync as X}from"node:zlib";import{blobStore as Z}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as x}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as M,decodeRows as ne,rowKeys as N,SEQ_TABLES as ae}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{copyRows as se,decodeKeys as L,encodeKeys as B}from"./copy.js";import{pruneStaged as re,precheck as oe,renameClashingLegacyCharges as de,renameClashingProfiles as pe,rewriteConversationHeaders as ue,rewritePaths as ce,rewriteRequestPaths as le,takeRepoSyncedDocuments as fe}from"./prepare.js";import{boundSub as me,dropRefusedMessages as _e,checkSourcePerson as we,checkStagedBlobKeys as ge,checkStagedPersons as be,checkStagedReferences as he,checkStagedRequestKeys as ye}from"./bind.js";import{deleteBlobs as Ee,deleteRunBlobs as Se,deleteRunPrefix as ve,moveRunBlobs as Re}from"./blobs.js";import{dropStubRows as Ie,findFleetGrant as Oe,grantMissing as Pe,mapProfileIds as Te,renameClashingRepos as je,rewriteIds as ke,rewritePerson as Ce,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as W,ImportLaneError as g,stage as De,stagingSchema as Me,targetSchema as Ne}from"./stage.js";import{verifyRun as Le}from"./verify.js";import{sandboxPathMap as Be,writeNodeFiles as We}from"./path-map.js";import{allStoreKeys as He,readPluginsStore as Ke,recordImportedActivations as Ue,writeStores as Fe}from"./stores.js";import{openImportGrants as Je}from"./open-grants.js";import{publishImportedPlugins as Ge}from"./publish-plugins.js";import{COPIED_TABLES as qe}from"../bundle/layout.js";import{emitEvent as $e}from"../../events/emit.js";import{ClaimLostError as Ye}from"../../../daemon/reconcilers/row-claim.js";const ze=10*6e4,Qe=30*6e4,R=l(()=>new Date().toISOString(),"now"),H=l(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Ve(e,s){const a=await e.get(M.source(s));if(a===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(a.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}l(Ve,"readSource");async function Xe(e,s,a,n,i,p,d){const o=[];for(const t of N(a.run_id,"grants",n)){const u=await e.get(t);if(u===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ne(u))}if(o.length===0)return;const w=o.map(t=>({sub:me(t.sub,n.person,a.person,"grants.sub"),grantee:t.grantee}));await d(a.run_id);const f=[];for(const t of w)await Oe(s,i,p,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw Pe(f)}l(Xe,"ensureGrants");async function It(e,s,a={}){const n=a.blobs??await Z(),i=await v(),p=Me(e.run_id);let d="start";const o=l(async t=>{d=t,await s.assertOwned(),await H(e.run_id,t),await a.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Ve(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const u=await Ne(i),I=[...qe],b=await ie(i,u,[...I,"grants"]);if(!w){const m={},P=[],T=[],j=a.fleetRuntime??process.env.CRTR_RUNTIME??null;await we(i,u,t.person,e.person),await o("open-grants"),await Xe(n,i,e,t,u,j,a.openGrants??Je),await o("publish-plugins");const U=await Ke(n,e.run_id),E=await x(e.person,()=>Ge(U));if(E.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=ze)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${E.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:E.unavailable});await s.assertOwned(),await H(e.run_id,"waiting_for_directory");return}T.push(...E.refused),await o("stage");const F=await De(i,e.run_id,t.counts,r=>N(e.run_id,r,t),r=>n.get(r));for(const[r,c]of Object.entries(F))m[r]={staged:c,inserted:0,mapped:0,dropped:0};const _={db:i,schema:p,target:u,catalog:b,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[r,c]of Object.entries(await be(_)))h(m,r,c);for(const[r,c]of Object.entries(await ge(_)))h(m,r,c);await o("rewrite-person"),await Ce(_),await Ae(_),await o("prune");const J=await re(i,p,b,t),S=t.kind==="hosted"?Be(t.pathPrefixes??[]):[];await o("rewrite-paths"),await ce(i,p,S),await ue(i,p,S,n,e.run_id),await le(i,p),await ye(_);const G=await Te(_);await pe(i,p,u,t.installId,e.person),await o("rewrite-ids");const k=await ke(_,G);await o("drop");const q=await fe(i,p,u),$=await Ie(_);for(const[r,c]of Object.entries({...J}))h(m,r,c);for(const[r,c]of Object.entries($))h(m,r,c);for(const[r,c]of Object.entries(await _e(_,{installId:t.installId,person:e.person,runId:e.run_id})))h(m,r,c);await he(_,{installId:t.installId,person:e.person,runId:e.run_id}),await je(_),await de(i,p,u,t.installId),await o("pre-check");const Y=new Map([["messages",["seq"]],...ae.map(r=>[r,["seq"]])]);await oe(i,p,u,b,I,new Set,Y),await o("blobs"),await Re(i,p,u,e.person,n,e.run_id,f),await o("copy"),await D(async r=>{await s.assertOwned({extendLeaseMs:Qe});const c=await se({db:r,runId:e.run_id,schema:p,target:u,catalog:b,source:t,person:e.person,idMap:k,pathMap:S}),C=await et(r,e.run_id,q);C>0&&(c.inserted.revisions=(c.inserted.revisions??0)+C),await We(r,p,e.run_id,t);const A=await Fe({db:r,blobs:n,runId:e.run_id,person:e.person,objectMap:k.object});for(const[z,Q]of Object.entries(A.inserted))c.inserted[z]=Q.length;return P.push(...A.unresolvedPlugins),await r.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...xe(m,c),unresolved_plugins:P,refused_plugins:T}),R(),e.run_id),c}),w=!0,await a.atStep?.("committed")}await o("verify");const y=await Le(i,e.run_id,p,u,b,t.installId);if(await i.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await o("manifest");const O=M.manifest(e.run_id);await n.put(O,await tt(e.run_id)),await W(i,e.run_id);for(const m of He(e.run_id))await n.delete(m);await Se(n,e.run_id),await D(async m=>{await Ue(m,e.run_id,e.person),await m.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof Ye)throw t;const u=Ze(t,d);$e({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:u.step,code:u.code}}),await W(i,e.run_id).catch(()=>{}),w||await Ee(n,f,!0),await i.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id),await ve(n,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}l(It,"processRun");function Ze(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const a=e.code;return{step:s,code:typeof a=="string"?a:"import_failed",message:e instanceof Error?e.message:String(e)}}l(Ze,"failureOf");function h(e,s,a){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=a}l(h,"addDropped");function xe(e,s){for(const[a,n]of Object.entries(s.inserted))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[a,n]of Object.entries(s.mapped))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}l(xe,"withInserted");async function et(e,s,a){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(a.map(d=>d.rev_id)))).map(d=>d.rev_id)),i=a.filter(d=>!n.has(d.rev_id)),p=new Map;for(const d of a)p.set(d.document,[...p.get(d.document)??[],d]);for(const[d,o]of p){const w=await te(e,d);w!==null&&await ee(e,w,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await K(e,s,"revisions",i.map(d=>[d.rev_id])),await K(e,s,"revision_parents",i.flatMap(d=>d.parents.map(o=>[d.rev_id,o]))),i.length}l(et,"arrive");async function K(e,s,a,n){if(n.length===0)return;const i=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,a);i===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,a,B(n)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(B([...L(i.inserted_keys),...n]),s,a)}l(K,"appendManifest");async function tt(e){const a=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return X(Buffer.from(a.map(n=>JSON.stringify({table:n.table_name,keys:L(n.inserted_keys)})).join(`
2
2
  `)+`
3
- `))}m(et,"manifestFile");export{ze as COPY_LEASE_MS,K as GRANT_WAIT_MS,vt as processRun};
3
+ `))}l(tt,"manifestFile");export{Qe as COPY_LEASE_MS,ze as GRANT_WAIT_MS,It as processRun};
@@ -1 +1 @@
1
- var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{openDb as N}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as M}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as $}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as F}from"../../../core/graph/jobs.js";import{boundFleet as S}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as V}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as C}from"../reader.js";import{canRead as B}from"../../../core/graph/access.js";import{ownersByHandle as G}from"../../../core/graph/names.js";import{reposForCwd as H,warmCheckoutIdentities as K}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as U}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as p}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as W}from"../../../core/env-name.js";import{listProfileEnvNames as J,removeProfileEnvVar as Y,setProfileEnvVar as z}from"../../../core/profiles/env-store.js";import{isDeploymentName as Q,listAppEnvNames as X,removeAppEnvVar as Z,setAppEnvVar as x}from"../../../core/profiles/app-env-store.js";import{addProfileProject as ee,addProfileRepo as te,assertDeliveryLimits as ae,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as re,listProfiles as u,loadProfileManifest as E,pauseProfile as ie,removeProfileProject as ne,renameProfile as oe,resumeProfile as se,setProfileDefaultKind as de,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as fe}from"../../profile-delete.js";import{brokerSignalBus as le}from"../../broker-signals/bus.js";import{toProfileDTO as me}from"../map.js";import{isCloudRole as ue,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as A}from"../../../core/environment-repos.js";import{actsAsPerson as g,appOf as j,resolvedScopes as ve}from"../router.js";const I="root",he=4096;function v(t,e=[]){return{...me(t),...t.manifest.environment_id===void 0?{}:{environment_id:t.manifest.environment_id},repositories:e}}o(v,"toProfileDTO");async function l(t){return v(t,(await A()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function k(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new p(400,"invalid_request",`${t} already has a profile named ${e}`)}o(k,"assertNameFree");async function m(t,e){const r=await q(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new p(403,"permission_error",`profile ${r.profileId} belongs to ${a}; only that app changes it`);return r}o(m,"requireOwnProfile");async function ye(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const r=c(t),a=e.name.trim();k(r,a),e.default_kind!==void 0&&await h(e.default_kind,process.cwd(),null);const i=e.repositories??[];if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const f=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:v(f)}}if(!ue())throw new p(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new p(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),i),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r,memoryMb:he,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(ye,"handleCreate");async function _e(t,e){const r=e.trim();if(r==="")throw d("profile name must not be empty");return await w(async a=>(await U(a,t,r),await oe(t,r)))}o(_e,"renameProfileAndHandle");async function be(t,e,r){await K(r);const i=(await w(async n=>await H(n,r)))[0];await ee(t,r,i?.id),i!==void 0&&e[i.name]===void 0&&e[`repo:${i.name}`]===void 0&&await _(t,i.name,"preview")}o(be,"addProjectWithDefaultLimit");async function Pe(t,e,r,a){const i=await w(async n=>{const s=await C(n,t);for(const f of await G(n,a,"repo"))if(await B(n,s,f))return f;return null});if(i===null)throw new p(404,"not_found",`no repo you can read is named ${a}`);await te(e,i.id),r[i.name]===void 0&&r[`repo:${i.name}`]===void 0&&await _(e,i.name,"preview")}o(Pe,"addRepoWithDefaultLimit");async function Ee(t){const{profileId:e,manifest:r}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&k(r.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await h(a.default_kind,process.cwd(),e),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&ae({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await _e(e,a.name),a.default_kind!==void 0&&await de(e,a.default_kind),a.add_project?.path!==void 0?await be(e,r.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await Pe(t,e,r.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await ne(e,a.remove_project),{status:200,body:await l(E(e))}}o(Ee,"handleUpdate");async function ge(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await J(e)}}}o(ge,"handleEnvList");function D(t){const e=t.params.var,r=W(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function O(t){const e=D(t);if(Q(e)&&!g(t.principal))throw new p(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(O,"requireSelfEnvVarName");async function je(t){const{profileId:e}=await m(t,t.params.name),r=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await z(e,r,a)}}}o(je,"handleEnvSet");async function De(t){const{profileId:e}=await m(t,t.params.name),r=D(t);return{status:200,body:{profile_id:e,changed:await Y(e,r)}}}o(De,"handleEnvRemove");async function Te(t){const e=t.params.name,r=t.body??{};r.projects!==void 0&&b(r.projects);const a=c(t);if(e===I&&a==="app:terminal")return{status:200,body:await l(await re())};if(e===I)throw new p(403,"permission_error","root belongs to the terminal app");const i=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(i!==void 0)return{status:200,body:await l(i)};r.default_kind!==void 0&&await h(r.default_kind,process.cwd(),null);const n=await P(e,r.projects??[],{defaultKind:r.default_kind,metadata:r.metadata,grantee:a});return{status:200,body:v(n)}}o(Te,"handleEnsure");async function Ae(t){const e=await m(t,t.params.name),r=t.body??{};if(typeof r!="object"||r===null||Array.isArray(r))throw d("profile metadata body must be an object",{field:"body"});const a=r,i=a.unset===void 0?[]:a.unset;if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,i);return{status:200,body:await l(s)}}o(Ae,"handleSetMetadata");async function Ie(t){const e=E(t.params.name),r=await ie(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}};const i=S();for(const n of a){const s=i.get(n.node_id);if(s!==void 0){await i.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&V(n.pi_pid,n.pi_pid_identity)==="alive"&&await i.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(Ie,"handlePause");async function ke(t){const e=E(t.params.name),r=await se(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await $(a.node_id)!==null)&&le.markMail(a.node_id);if(r.pausedAt!==null){const a=Date.parse(r.pausedAt);if(!Number.isNaN(a)){const i=Math.max(0,Date.now()-a);await M(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>F(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(ke,"handleResume");async function R(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await N(),i=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>i.has(n))}const r=await ve(e);return u().filter(({profileId:a,manifest:i})=>{const n=i.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return T(r,s)&&(e.class!=="broker"||T(e.scopes,s))})}o(R,"visibleProfiles");async function q(t,e){const r=await R(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new p(404,"not_found","profile not found");if(i.length>1)throw new p(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(q,"requireUsableProfile");async function Oe(t){const e=await A();return{status:200,body:(await R(t)).map(r=>v(r,e.get(r.profileId)??[]))}}o(Oe,"handleList");async function Re(t){return{status:200,body:await l(await q(t,t.params.name))}}o(Re,"handleGet");async function qe(t){return fe((await m(t,t.params.name)).profileId,t.body)}o(qe,"handleDelete");const ot=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await X(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=O(t),{value:r}=t.body??{};if(typeof r!="string"||!r)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await x(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await Z(c(t),O(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Te},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:Ie},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:ke},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ae},{method:"POST",pattern:"/v1/profiles",handler:ye},{method:"PATCH",pattern:"/v1/profiles/:name",handler:Ee},{method:"GET",pattern:"/v1/profiles/:name/env",handler:ge},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:je},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name",handler:qe},{method:"GET",pattern:"/v1/profiles",handler:Oe},{method:"GET",pattern:"/v1/profiles/:name",handler:Re}];export{be as addProjectWithDefaultLimit,ot as profileRoutes,_e as renameProfileAndHandle,q as requireUsableProfile};
1
+ var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{openDb as N}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as M}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as $}from"../../../core/graph/jobs.js";import{boundFleet as F}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as V}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as C}from"../reader.js";import{canRead as B}from"../../../core/graph/access.js";import{ownersByHandle as G}from"../../../core/graph/names.js";import{reposForCwd as H,warmCheckoutIdentities as K}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as U}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as p}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as W}from"../../../core/env-name.js";import{listProfileEnvNames as J,removeProfileEnvVar as Y,setProfileEnvVar as z}from"../../../core/profiles/env-store.js";import{isDeploymentName as Q,listAppEnvNames as X,removeAppEnvVar as Z,setAppEnvVar as x}from"../../../core/profiles/app-env-store.js";import{addProfileProject as ee,addProfileRepo as te,assertDeliveryLimits as ae,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as re,listProfiles as u,loadProfileManifest as E,pauseProfile as ie,removeProfileProject as ne,renameProfile as oe,resumeProfile as se,setProfileDefaultKind as de,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as fe}from"../../profile-delete.js";import{brokerSignalBus as le}from"../../broker-signals/bus.js";import{toProfileDTO as me}from"../map.js";import{isCloudRole as ue,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as A}from"../../../core/environment-repos.js";import{actsAsPerson as g,appOf as j,boundedByStoredScopes as ve,resolvedScopes as he}from"../router.js";const I="root",ye=4096;function v(t,e=[]){return{...me(t),...t.manifest.environment_id===void 0?{}:{environment_id:t.manifest.environment_id},repositories:e}}o(v,"toProfileDTO");async function l(t){return v(t,(await A()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function k(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new p(400,"invalid_request",`${t} already has a profile named ${e}`)}o(k,"assertNameFree");async function m(t,e){const r=await q(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new p(403,"permission_error",`profile ${r.profileId} belongs to ${a}; only that app changes it`);return r}o(m,"requireOwnProfile");async function _e(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const r=c(t),a=e.name.trim();k(r,a),e.default_kind!==void 0&&await h(e.default_kind,process.cwd(),null);const i=e.repositories??[];if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const f=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:v(f)}}if(!ue())throw new p(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new p(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),i),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r,memoryMb:ye,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(_e,"handleCreate");async function be(t,e){const r=e.trim();if(r==="")throw d("profile name must not be empty");return await w(async a=>(await U(a,t,r),await oe(t,r)))}o(be,"renameProfileAndHandle");async function Pe(t,e,r){await K(r);const i=(await w(async n=>await H(n,r)))[0];await ee(t,r,i?.id),i!==void 0&&e[i.name]===void 0&&e[`repo:${i.name}`]===void 0&&await _(t,i.name,"preview")}o(Pe,"addProjectWithDefaultLimit");async function Ee(t,e,r,a){const i=await w(async n=>{const s=await C(n,t);for(const f of await G(n,a,"repo"))if(await B(n,s,f))return f;return null});if(i===null)throw new p(404,"not_found",`no repo you can read is named ${a}`);await te(e,i.id),r[i.name]===void 0&&r[`repo:${i.name}`]===void 0&&await _(e,i.name,"preview")}o(Ee,"addRepoWithDefaultLimit");async function ge(t){const{profileId:e,manifest:r}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&k(r.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await h(a.default_kind,process.cwd(),e),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&ae({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await be(e,a.name),a.default_kind!==void 0&&await de(e,a.default_kind),a.add_project?.path!==void 0?await Pe(e,r.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await Ee(t,e,r.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await ne(e,a.remove_project),{status:200,body:await l(E(e))}}o(ge,"handleUpdate");async function je(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await J(e)}}}o(je,"handleEnvList");function D(t){const e=t.params.var,r=W(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function O(t){const e=D(t);if(Q(e)&&!g(t.principal))throw new p(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(O,"requireSelfEnvVarName");async function De(t){const{profileId:e}=await m(t,t.params.name),r=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await z(e,r,a)}}}o(De,"handleEnvSet");async function Te(t){const{profileId:e}=await m(t,t.params.name),r=D(t);return{status:200,body:{profile_id:e,changed:await Y(e,r)}}}o(Te,"handleEnvRemove");async function Ae(t){const e=t.params.name,r=t.body??{};r.projects!==void 0&&b(r.projects);const a=c(t);if(e===I&&a==="app:terminal")return{status:200,body:await l(await re())};if(e===I)throw new p(403,"permission_error","root belongs to the terminal app");const i=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(i!==void 0)return{status:200,body:await l(i)};r.default_kind!==void 0&&await h(r.default_kind,process.cwd(),null);const n=await P(e,r.projects??[],{defaultKind:r.default_kind,metadata:r.metadata,grantee:a});return{status:200,body:v(n)}}o(Ae,"handleEnsure");async function Ie(t){const e=await m(t,t.params.name),r=t.body??{};if(typeof r!="object"||r===null||Array.isArray(r))throw d("profile metadata body must be an object",{field:"body"});const a=r,i=a.unset===void 0?[]:a.unset;if(!Array.isArray(i)||i.some(f=>typeof f!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,i);return{status:200,body:await l(s)}}o(Ie,"handleSetMetadata");async function ke(t){const e=E(t.params.name),r=await ie(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}};const i=F();for(const n of a){const s=i.get(n.node_id);if(s!==void 0){await i.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&V(n.pi_pid,n.pi_pid_identity)==="alive"&&await i.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(ke,"handlePause");async function Oe(t){const e=E(t.params.name),r=await se(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await S(a.node_id)!==null)&&le.markMail(a.node_id);if(r.pausedAt!==null){const a=Date.parse(r.pausedAt);if(!Number.isNaN(a)){const i=Math.max(0,Date.now()-a);await M(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>$(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(Oe,"handleResume");async function R(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await N(),i=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>i.has(n))}const r=await he(e);return u().filter(({profileId:a,manifest:i})=>{const n=i.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return T(r,s)&&(!ve(e)||T(e.scopes,s))})}o(R,"visibleProfiles");async function q(t,e){const r=await R(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new p(404,"not_found","profile not found");if(i.length>1)throw new p(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(q,"requireUsableProfile");async function Re(t){const e=await A();return{status:200,body:(await R(t)).map(r=>v(r,e.get(r.profileId)??[]))}}o(Re,"handleList");async function qe(t){return{status:200,body:await l(await q(t,t.params.name))}}o(qe,"handleGet");async function Le(t){return fe((await m(t,t.params.name)).profileId,t.body)}o(Le,"handleDelete");const st=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await X(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=O(t),{value:r}=t.body??{};if(typeof r!="string"||!r)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await x(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await Z(c(t),O(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Ae},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:ke},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:Oe},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ie},{method:"POST",pattern:"/v1/profiles",handler:_e},{method:"PATCH",pattern:"/v1/profiles/:name",handler:ge},{method:"GET",pattern:"/v1/profiles/:name/env",handler:je},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:Te},{method:"DELETE",pattern:"/v1/profiles/:name",handler:Le},{method:"GET",pattern:"/v1/profiles",handler:Re},{method:"GET",pattern:"/v1/profiles/:name",handler:qe}];export{Pe as addProjectWithDefaultLimit,st as profileRoutes,be as renameProfileAndHandle,q as requireUsableProfile};