@north-light/cli 0.3.738 → 0.3.740
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +9 -9
- package/dist/clients/attach/viewer.js +546 -546
- package/dist/commands/sys/setup-core.js +3 -3
- package/dist/commands/sys/signin.js +3 -3
- package/dist/core/import/load/prepare.d.ts +6 -0
- package/dist/core/import/load/prepare.js +10 -10
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/runtime/front-door.js +7 -7
- package/dist/daemon/machine-link/config.d.ts +2 -0
- package/dist/daemon/machine-link/config.js +4 -4
- package/dist/daemon/manage.js +3 -3
- package/package.json +3 -3
- package/packages/crouter-api/dist/commands/sys/setup-core.js +2 -2
- package/packages/crouter-api/dist/commands/sys/signin.js +3 -2
- package/packages/crouter-api/dist/core/import/load/prepare.js +8 -0
- package/packages/crouter-api/dist/core/profiles/manifest.js +5 -2
- package/packages/crouter-api/dist/daemon/machine-link/config.js +3 -0
- package/packages/crouter-api/dist/daemon/manage.js +4 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var re=Object.defineProperty;var a=(e,t)=>re(e,"name",{value:t,configurable:!0});import{spawn as ie,spawnSync as se}from"node:child_process";import{homedir as w,tmpdir as ae}from"node:os";import{mkdtempSync as oe,rmSync as ce}from"node:fs";import{piAgentDir as I}from"../../core/runtime/package-health.js";import{basename as ue,dirname as _,join as h,relative as le,resolve as de}from"node:path";import{isDeepStrictEqual as b}from"node:util";import{BINDING_CATALOG as pe,normalizeGesture as fe,splitGestureExpression as me,inboxShortcut as he,resolveKeybindings as S}from"../../core/keybindings/index.js";import{runtimeManifest as ge}from"./shared.js";import{atomicWriteJson as ke,readJsonIfExists as ve,readJsonOrNull as L}from"../../core/fs-utils.js";import{resolveBundledPiCliPath as be}from"../../core/runtime/pi-cli.js";import{crtrVersion as we}from"../../shared/crtr-version.js";import{installTmuxBindings as ye}from"../../core/runtime/tmux-chrome.js";import{normalizeTmuxPassthrough as xe}from"../../core/config.js";import{detectNerdFont as Pe,nerdFontInstallCommand as Ie,createCurlPercentReader as Se,NERD_FONT_MANUAL_LINUX_COMMAND as Ce,NERD_FONT_SELECT_HINT as Ee}from"../../core/runtime/nerd-font.js";import{startProgressBar as $e}from"../../core/runtime/progress-bar.js";import{ensureRenderer as Ae,isRendererReady as K}from"../../core/termrender/termrender.js";import{installFromMarketplace as Re,isMarketplaceRelativeSource as De}from"../pkg/plugin-manage.js";import{requiredPluginEnv as Me}from"../../core/plugin-env.js";import{readPluginManifest as Te}from"../../core/manifest.js";import{addMarketplace as j}from"../pkg/market-manage.js";import{clone as Ne}from"../../core/git.js";import{readMarketplaceManifest as Oe}from"../../core/manifest.js";import{findPluginByName as F,findMarketplaceByName as C}from"../../core/resolver.js";import{expandTilde as _e}from"../../core/fs-utils.js";import{applyTerminalEdit as Le}from"./terminal-option.js";const E="crouter-official-marketplace",$="https://github.com/crouton-labs/crouter-official-marketplace.git",A="main";function Pt(e){const t=[],n=new Set,r=new Map;try{for(const o of e){if(o.sourceKind!=="marketplace-plugin")continue;const[u,c]=o.installSource.split("/");if(!u||!c)continue;const l=F(c,"user")?.manifest;let d=C(u,"user");if(!d&&!l&&u===E)try{let i=r.get(u);i||(i=oe(h(ae(),"crtr-setup-market-")),r.set(u,i),Ne($,h(i,"checkout"),{ref:A,depth:1}));const p=h(i,"checkout"),v=Oe(p);v&&(d={root:p,manifest:v})}catch{}const m=d?.manifest.plugins.find(i=>i.name===c)?.source,f=m&&De(m)?Te(h(d.root,m))??l:l;if(f)for(const i of Me(f.env))n.has(i)||(n.add(i),t.push({name:i,plugin:c,declaration:f.env[i]}))}}finally{for(const o of r.values())ce(o,{recursive:!0,force:!0})}return t}a(Pt,"setupPluginEnvFields");function G(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(G,"isKeybindingsObject");function g(e){return G(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?[...n]:n])):{}}a(g,"cloneKeybindings");class It{static{a(this,"SetupKeybindingsDraft")}expected;baseline;current;baselineInvalidRoot;invalidRoot;resolutionCache;expectedPassthrough;baselinePassthrough;currentPassthrough;constructor(t,n=void 0){this.expected=t,this.baseline=g(t),this.current=g(t),this.baselineInvalidRoot=t!==void 0&&!G(t)?t:void 0,this.invalidRoot=this.baselineInvalidRoot,this.expectedPassthrough=n,this.baselinePassthrough=xe(n),this.currentPassthrough=[...this.baselinePassthrough]}get dirty(){return!b(this.current,this.baseline)||!b(this.invalidRoot,this.baselineInvalidRoot)||!b(this.currentPassthrough,this.baselinePassthrough)}overrides(){return g(this.current)}expectedKeybindings(){return this.expected}tmuxPassthrough(){return[...this.currentPassthrough]}expectedTmuxPassthrough(){return this.expectedPassthrough}usesTmuxPassthrough(t){return this.currentPassthrough.includes(t)}toggleTmuxPassthrough(t){this.currentPassthrough=this.currentPassthrough.includes(t)?this.currentPassthrough.filter(n=>n!==t):[...this.currentPassthrough,t]}resolution(){return this.resolutionCache===void 0&&(this.resolutionCache=S(this.invalidRoot===void 0?this.current:this.invalidRoot)),this.resolutionCache}hasInvalidRoot(){return this.invalidRoot!==void 0}expression(t){return this.resolution().gestures(t).join(", ")}edit(t,n){if(this.invalidRoot!==void 0)return{ok:!1,diagnostics:[{severity:"error",code:"invalid-keybindings",offendingValue:this.invalidRoot,message:"Reset all before editing: the saved keybindings root is invalid."}]};const r=pe.find(f=>f.id===t);let o;try{o=n.trim()===""?[]:me(n).map(f=>fe(f.trim(),r))}catch(f){return{ok:!1,diagnostics:[{severity:"error",code:"invalid-override",bindingId:t,offendingValue:n,message:f instanceof Error?f.message:String(f)}]}}const u=[...new Set(o)],c={...this.current};delete c[t];const l=[...S(c).gestures(t)],s=b(u,l)?c:{...this.current,[t]:u},d=S(s),m=d.diagnostics.filter(f=>f.bindingId===t||f.relatedBindingIds?.includes(t));return m.length>0?{ok:!1,diagnostics:m}:(this.current=s,this.resolutionCache=void 0,{ok:!0,diagnostics:d.diagnostics})}unbind(t){return this.edit(t,"")}resetRow(t){delete this.current[t],this.resolutionCache=void 0}resetAll(){this.current={},this.currentPassthrough=[],this.invalidRoot=void 0,this.resolutionCache=void 0}discard(){this.current=g(this.baseline),this.currentPassthrough=[...this.baselinePassthrough],this.invalidRoot=this.baselineInvalidRoot,this.resolutionCache=void 0}markSaved(t,n=[]){this.expected=Object.keys(t).length===0?void 0:g(t),this.baseline=g(t),this.current=g(t),this.expectedPassthrough=[...n],this.baselinePassthrough=[...n],this.currentPassthrough=[...n],this.baselineInvalidRoot=void 0,this.invalidRoot=void 0,this.resolutionCache=void 0}}const Ke={"official-marketplace":{name:E,shortDescription:"the official crtr plugin catalog \u2014 registered as a source so its plugins are installable by ref.",longDescription:"Shallow-clones github.com/crouton-labs/crouter-official-marketplace into the user scope and registers it, which is what makes `crtr pkg plugin install crouter-official-marketplace/<name>` resolve and what fills `crtr pkg market browse`. Registering the source installs no plugin by itself. Uncheck it on a machine that should reach no external catalog \u2014 a plugin selected below still registers the marketplace it comes from, because its ref cannot resolve otherwise."},"crtr-extensions":{name:"pi-crtr-extensions",shortDescription:"crtr companion extensions \u2014 command palette, help gating, subscription/OAuth rotation, nested context.",longDescription:"Bundles the extensions built for crtr: a crtr slash-command palette, crtr/crouter help gating, surfacing of Claude Code marketplace plugin commands, nested AGENTS.md/CLAUDE.md loading, OAuth login + rotation across multiple Claude subscriptions (provider-rotation), and system-prompt trimming. The OAuth/rotation piece is what lets crtr authenticate your Claude account."},"oauth-adapter":{name:"pi-claude-oauth-adapter",shortDescription:"Anthropic OAuth / Claude Code credential compatibility for pi.",longDescription:"Third-party adapter (minzique/dotfiles-agents) letting pi authenticate with Claude using Claude Code OAuth credentials. Installed from npm, pinned to 0.2.2."},"capture-plugin":{name:"capture",shortDescription:"crtr plugin mounting `crtr capture` \u2014 browser automation and UI measurement over CDP.",longDescription:"Installs the `capture` plugin from the official crtr marketplace. It mounts `crtr capture` as a transparent passthrough to the external Capture CLI (`npm install -g @crouton-kit/capture`) for CDP screenshots, rendered-geometry measurement, HAR, accessibility trees, and JS execution against a live page. Uncheck it on a machine where agents never drive a browser \u2014 the command then costs nothing in their root prompt."},"dev-plugin":{name:"dev",shortDescription:"crtr plugin mounting the development workflow \u2014 repository setup, worktrees, pull requests, and a dev track in the tutorial.",longDescription:"Installs the dev plugin from the official crtr marketplace. It adds the /dev: workflow commands (init, spec, design, plan, pr-loop), mounts crtr dev for a repository's own lifecycle commands and Grove instances, and contributes the crtr sys tutorial dev track. Uncheck it on a machine whose agents do not work in source repositories."}},R={"official-marketplace":{kind:"marketplace-source",source:$},"crtr-extensions":{kind:"local-path",source:U("pi-crtr-extensions")},"oauth-adapter":{kind:"npm",source:"npm:pi-claude-oauth-adapter@0.2.2"},"capture-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/capture"},"dev-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/dev"}},B=["extensions/*.ts","extensions/*/index.ts","!extensions/**/*.d.ts"],je={"official-marketplace":[],"crtr-extensions":["pi-crtr-extensions"],"oauth-adapter":[],"capture-plugin":[],"dev-plugin":[]};function U(e){return h(ge.runtimeHome(),"selected","dist","builtin-pi-packages",e)}a(U,"selectedPiPackageDir");function D(e=U){return["official-marketplace","crtr-extensions","oauth-adapter","capture-plugin","dev-plugin"].map(t=>{const n=Ke[t],r=R[t].kind==="local-path"?e(n.name):R[t].source;return{id:t,name:n.name,sourceKind:R[t].kind,installSource:r,shortDescription:n.shortDescription,longDescription:n.longDescription}})}a(D,"buildSetupManifest");function St(e){switch(e.sourceKind){case"marketplace-source":return`clone + register ${e.installSource}`;case"marketplace-plugin":return`crtr pkg plugin install ${e.installSource}`;default:return`pi install ${e.installSource}`}}a(St,"packagePlanAction");function Fe(e){if(!e.startsWith("npm:"))return null;const t=e.slice(4),n=t.startsWith("@")?t.indexOf("@",1):t.lastIndexOf("@");return n>0?t.slice(0,n):t}a(Fe,"npmPackageName");function y(e,t,n){const r=Fe(e);if(r!==null)return`npm:${r}`;const o=_e(e,n);return de(t,o)}a(y,"normalizePackageIdentity");function x(e){return`package:${e}`}a(x,"packageNameIdentity");function z(e){return e.startsWith("npm:")?[]:[x(ue(e))]}a(z,"localPackageNameIdentities");function Ge(e,t,n){const r=[y(e.installSource,t,n)];if(e.sourceKind==="local-path"){r.push(x(e.name));for(const o of je[e.id])r.push(x(o))}return r}a(Ge,"manifestIdentities");function Y(e,t=D(),n=h(I(),"settings.json"),r=w()){const o=_(n),u=new Set,c=new Map;for(const s of t)for(const d of Ge(s,o,r))c.set(d,s.id);const l=e&&typeof e=="object"?e.packages:void 0;if(!Array.isArray(l))return u;for(const s of l){const d=typeof s=="string"?s:s&&typeof s=="object"&&typeof s.source=="string"?s.source:null;if(d===null)continue;const m=[y(d,o,r),...z(d)];for(const f of m){const i=c.get(f);if(i==="crtr-extensions"){const p=t.find(v=>v.id===i);if(y(d,o,r)!==y(p.installSource,o,r)||!s||typeof s!="object"||!b(s.extensions,B))continue}i!==void 0&&u.add(i)}}return u}a(Y,"detectInstalledSetupPackageIds");function k(e){return se("sh",["-lc",`command -v ${e} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}a(k,"detectCommandOnPath");function Be(e=process.platform,t=k){switch(e){case"darwin":return t("brew")?"brew":"manual";case"linux":return t("apt-get")?"apt-get":t("dnf")?"dnf":t("pacman")?"pacman":"manual";default:return"manual"}}a(Be,"detectPackageManager");function Ue(e,t,n=k){if(e==="nerd-font"?Pe().installed:n(e))return{tool:e,installed:!0,command:null,hint:"already installed",autoInstall:!1};if(e==="nerd-font"){const u=Ie(t);return{tool:e,installed:!1,command:u.command,hint:`${u.hint} \u2014 ${Ee}`,autoInstall:u.autoInstall}}const o=e==="nvim"?"neovim":"tmux";switch(t){case"brew":return{tool:e,installed:!1,command:`brew install ${o}`,hint:"Homebrew install",autoInstall:!0};case"apt-get":return{tool:e,installed:!1,command:`sudo apt-get update && sudo apt-get install -y ${o}`,hint:"apt-get install",autoInstall:!0};case"dnf":return{tool:e,installed:!1,command:`sudo dnf install -y ${o}`,hint:"dnf install",autoInstall:!0};case"pacman":return{tool:e,installed:!1,command:`sudo pacman -S --noconfirm ${o}`,hint:"pacman install",autoInstall:!0};default:return{tool:e,installed:!1,command:null,hint:`manual install required for ${e}`,autoInstall:!1}}}a(Ue,"buildSystemInstallPlan");function M(e=w()){return h(e===w()?I():h(e,".pi","agent"),"settings.json")}a(M,"resolveSettingsPath");function Ct(e={}){const t=e.homeDir??w(),n=e.settingsPath??M(t),r=e.manifest??D(),o=ve(n),u=Y(o,r,n,t);for(const d of X(r))u.add(d);const c=e.commandExists??k,l=e.packageManager??Be(process.platform,c),s=["tmux","nvim","nerd-font"].map(d=>Ue(d,l,c));return{manifest:r,installedPackageIds:u,systemPlans:s}}a(Ct,"buildSetupInitialState");function Et(e){const t=e.manifest.map(r=>{const o=e.installedPackageIds.has(r.id)?"installed":"not installed";return`- ${r.name} \u2014 ${r.shortDescription} (${o})`}),n=e.systemPlans.map(r=>r.installed?`- ${r.tool}: \u2713 installed`:r.command?`- ${r.tool}: ${r.command}`:`- ${r.tool}: ${r.hint}`);return["crtr sys setup (non-interactive)","","Provider login: open the wizard in a TTY and use the Providers tab (same flow as /login) to authenticate a model provider.","","Packages:",...t,"","System deps:",...n,"",`Inbox: the inbox-toggle key (${he()??"disabled"}) is a crouter keybinding \u2014 view or rebind it in \`crtr sys settings\`; it is installed on the same tmux server as every other crouter binding.`,"Run `crtr sys setup` in a TTY to open the wizard."].join(`
|
|
1
|
+
var re=Object.defineProperty;var a=(e,t)=>re(e,"name",{value:t,configurable:!0});import{spawn as ie,spawnSync as se}from"node:child_process";import{homedir as w,tmpdir as ae}from"node:os";import{mkdtempSync as oe,rmSync as ce}from"node:fs";import{piAgentDir as I}from"../../core/runtime/package-health.js";import{basename as ue,dirname as _,join as m,relative as le,resolve as de}from"node:path";import{isDeepStrictEqual as b}from"node:util";import{BINDING_CATALOG as pe,normalizeGesture as fe,splitGestureExpression as he,inboxShortcut as me,resolveKeybindings as S}from"../../core/keybindings/index.js";import{builtinPiPackageDir as ge}from"../../core/scope.js";import{atomicWriteJson as ke,readJsonIfExists as ve,readJsonOrNull as L}from"../../core/fs-utils.js";import{resolveBundledPiCliPath as be}from"../../core/runtime/pi-cli.js";import{crtrVersion as we}from"../../shared/crtr-version.js";import{installTmuxBindings as ye}from"../../core/runtime/tmux-chrome.js";import{normalizeTmuxPassthrough as xe}from"../../core/config.js";import{detectNerdFont as Pe,nerdFontInstallCommand as Ie,createCurlPercentReader as Se,NERD_FONT_MANUAL_LINUX_COMMAND as Ce,NERD_FONT_SELECT_HINT as Ee}from"../../core/runtime/nerd-font.js";import{startProgressBar as $e}from"../../core/runtime/progress-bar.js";import{ensureRenderer as Ae,isRendererReady as K}from"../../core/termrender/termrender.js";import{installFromMarketplace as Re,isMarketplaceRelativeSource as De}from"../pkg/plugin-manage.js";import{requiredPluginEnv as Te}from"../../core/plugin-env.js";import{readPluginManifest as Me}from"../../core/manifest.js";import{addMarketplace as j}from"../pkg/market-manage.js";import{clone as Ne}from"../../core/git.js";import{readMarketplaceManifest as Oe}from"../../core/manifest.js";import{findPluginByName as F,findMarketplaceByName as C}from"../../core/resolver.js";import{expandTilde as _e}from"../../core/fs-utils.js";import{applyTerminalEdit as Le}from"./terminal-option.js";const E="crouter-official-marketplace",$="https://github.com/crouton-labs/crouter-official-marketplace.git",A="main";function Pt(e){const t=[],n=new Set,r=new Map;try{for(const o of e){if(o.sourceKind!=="marketplace-plugin")continue;const[u,c]=o.installSource.split("/");if(!u||!c)continue;const l=F(c,"user")?.manifest;let d=C(u,"user");if(!d&&!l&&u===E)try{let i=r.get(u);i||(i=oe(m(ae(),"crtr-setup-market-")),r.set(u,i),Ne($,m(i,"checkout"),{ref:A,depth:1}));const p=m(i,"checkout"),v=Oe(p);v&&(d={root:p,manifest:v})}catch{}const h=d?.manifest.plugins.find(i=>i.name===c)?.source,f=h&&De(h)?Me(m(d.root,h))??l:l;if(f)for(const i of Te(f.env))n.has(i)||(n.add(i),t.push({name:i,plugin:c,declaration:f.env[i]}))}}finally{for(const o of r.values())ce(o,{recursive:!0,force:!0})}return t}a(Pt,"setupPluginEnvFields");function G(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(G,"isKeybindingsObject");function g(e){return G(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?[...n]:n])):{}}a(g,"cloneKeybindings");class It{static{a(this,"SetupKeybindingsDraft")}expected;baseline;current;baselineInvalidRoot;invalidRoot;resolutionCache;expectedPassthrough;baselinePassthrough;currentPassthrough;constructor(t,n=void 0){this.expected=t,this.baseline=g(t),this.current=g(t),this.baselineInvalidRoot=t!==void 0&&!G(t)?t:void 0,this.invalidRoot=this.baselineInvalidRoot,this.expectedPassthrough=n,this.baselinePassthrough=xe(n),this.currentPassthrough=[...this.baselinePassthrough]}get dirty(){return!b(this.current,this.baseline)||!b(this.invalidRoot,this.baselineInvalidRoot)||!b(this.currentPassthrough,this.baselinePassthrough)}overrides(){return g(this.current)}expectedKeybindings(){return this.expected}tmuxPassthrough(){return[...this.currentPassthrough]}expectedTmuxPassthrough(){return this.expectedPassthrough}usesTmuxPassthrough(t){return this.currentPassthrough.includes(t)}toggleTmuxPassthrough(t){this.currentPassthrough=this.currentPassthrough.includes(t)?this.currentPassthrough.filter(n=>n!==t):[...this.currentPassthrough,t]}resolution(){return this.resolutionCache===void 0&&(this.resolutionCache=S(this.invalidRoot===void 0?this.current:this.invalidRoot)),this.resolutionCache}hasInvalidRoot(){return this.invalidRoot!==void 0}expression(t){return this.resolution().gestures(t).join(", ")}edit(t,n){if(this.invalidRoot!==void 0)return{ok:!1,diagnostics:[{severity:"error",code:"invalid-keybindings",offendingValue:this.invalidRoot,message:"Reset all before editing: the saved keybindings root is invalid."}]};const r=pe.find(f=>f.id===t);let o;try{o=n.trim()===""?[]:he(n).map(f=>fe(f.trim(),r))}catch(f){return{ok:!1,diagnostics:[{severity:"error",code:"invalid-override",bindingId:t,offendingValue:n,message:f instanceof Error?f.message:String(f)}]}}const u=[...new Set(o)],c={...this.current};delete c[t];const l=[...S(c).gestures(t)],s=b(u,l)?c:{...this.current,[t]:u},d=S(s),h=d.diagnostics.filter(f=>f.bindingId===t||f.relatedBindingIds?.includes(t));return h.length>0?{ok:!1,diagnostics:h}:(this.current=s,this.resolutionCache=void 0,{ok:!0,diagnostics:d.diagnostics})}unbind(t){return this.edit(t,"")}resetRow(t){delete this.current[t],this.resolutionCache=void 0}resetAll(){this.current={},this.currentPassthrough=[],this.invalidRoot=void 0,this.resolutionCache=void 0}discard(){this.current=g(this.baseline),this.currentPassthrough=[...this.baselinePassthrough],this.invalidRoot=this.baselineInvalidRoot,this.resolutionCache=void 0}markSaved(t,n=[]){this.expected=Object.keys(t).length===0?void 0:g(t),this.baseline=g(t),this.current=g(t),this.expectedPassthrough=[...n],this.baselinePassthrough=[...n],this.currentPassthrough=[...n],this.baselineInvalidRoot=void 0,this.invalidRoot=void 0,this.resolutionCache=void 0}}const Ke={"official-marketplace":{name:E,shortDescription:"the official crtr plugin catalog \u2014 registered as a source so its plugins are installable by ref.",longDescription:"Shallow-clones github.com/crouton-labs/crouter-official-marketplace into the user scope and registers it, which is what makes `crtr pkg plugin install crouter-official-marketplace/<name>` resolve and what fills `crtr pkg market browse`. Registering the source installs no plugin by itself. Uncheck it on a machine that should reach no external catalog \u2014 a plugin selected below still registers the marketplace it comes from, because its ref cannot resolve otherwise."},"crtr-extensions":{name:"pi-crtr-extensions",shortDescription:"crtr companion extensions \u2014 command palette, help gating, subscription/OAuth rotation, nested context.",longDescription:"Bundles the extensions built for crtr: a crtr slash-command palette, crtr/crouter help gating, surfacing of Claude Code marketplace plugin commands, nested AGENTS.md/CLAUDE.md loading, OAuth login + rotation across multiple Claude subscriptions (provider-rotation), and system-prompt trimming. The OAuth/rotation piece is what lets crtr authenticate your Claude account."},"oauth-adapter":{name:"pi-claude-oauth-adapter",shortDescription:"Anthropic OAuth / Claude Code credential compatibility for pi.",longDescription:"Third-party adapter (minzique/dotfiles-agents) letting pi authenticate with Claude using Claude Code OAuth credentials. Installed from npm, pinned to 0.2.2."},"capture-plugin":{name:"capture",shortDescription:"crtr plugin mounting `crtr capture` \u2014 browser automation and UI measurement over CDP.",longDescription:"Installs the `capture` plugin from the official crtr marketplace. It mounts `crtr capture` as a transparent passthrough to the external Capture CLI (`npm install -g @crouton-kit/capture`) for CDP screenshots, rendered-geometry measurement, HAR, accessibility trees, and JS execution against a live page. Uncheck it on a machine where agents never drive a browser \u2014 the command then costs nothing in their root prompt."},"dev-plugin":{name:"dev",shortDescription:"crtr plugin mounting the development workflow \u2014 repository setup, worktrees, pull requests, and a dev track in the tutorial.",longDescription:"Installs the dev plugin from the official crtr marketplace. It adds the /dev: workflow commands (init, spec, design, plan, pr-loop), mounts crtr dev for a repository's own lifecycle commands and Grove instances, and contributes the crtr sys tutorial dev track. Uncheck it on a machine whose agents do not work in source repositories."}},R={"official-marketplace":{kind:"marketplace-source",source:$},"crtr-extensions":{kind:"local-path",source:U("pi-crtr-extensions")},"oauth-adapter":{kind:"npm",source:"npm:pi-claude-oauth-adapter@0.2.2"},"capture-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/capture"},"dev-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/dev"}},B=["extensions/*.ts","extensions/*/index.ts","!extensions/**/*.d.ts"],je={"official-marketplace":[],"crtr-extensions":["pi-crtr-extensions"],"oauth-adapter":[],"capture-plugin":[],"dev-plugin":[]};function U(e){return ge(e)}a(U,"selectedPiPackageDir");function D(e=U){return["official-marketplace","crtr-extensions","oauth-adapter","capture-plugin","dev-plugin"].map(t=>{const n=Ke[t],r=R[t].kind==="local-path"?e(n.name):R[t].source;return{id:t,name:n.name,sourceKind:R[t].kind,installSource:r,shortDescription:n.shortDescription,longDescription:n.longDescription}})}a(D,"buildSetupManifest");function St(e){switch(e.sourceKind){case"marketplace-source":return`clone + register ${e.installSource}`;case"marketplace-plugin":return`crtr pkg plugin install ${e.installSource}`;default:return`pi install ${e.installSource}`}}a(St,"packagePlanAction");function Fe(e){if(!e.startsWith("npm:"))return null;const t=e.slice(4),n=t.startsWith("@")?t.indexOf("@",1):t.lastIndexOf("@");return n>0?t.slice(0,n):t}a(Fe,"npmPackageName");function y(e,t,n){const r=Fe(e);if(r!==null)return`npm:${r}`;const o=_e(e,n);return de(t,o)}a(y,"normalizePackageIdentity");function x(e){return`package:${e}`}a(x,"packageNameIdentity");function z(e){return e.startsWith("npm:")?[]:[x(ue(e))]}a(z,"localPackageNameIdentities");function Ge(e,t,n){const r=[y(e.installSource,t,n)];if(e.sourceKind==="local-path"){r.push(x(e.name));for(const o of je[e.id])r.push(x(o))}return r}a(Ge,"manifestIdentities");function Y(e,t=D(),n=m(I(),"settings.json"),r=w()){const o=_(n),u=new Set,c=new Map;for(const s of t)for(const d of Ge(s,o,r))c.set(d,s.id);const l=e&&typeof e=="object"?e.packages:void 0;if(!Array.isArray(l))return u;for(const s of l){const d=typeof s=="string"?s:s&&typeof s=="object"&&typeof s.source=="string"?s.source:null;if(d===null)continue;const h=[y(d,o,r),...z(d)];for(const f of h){const i=c.get(f);if(i==="crtr-extensions"){const p=t.find(v=>v.id===i);if(y(d,o,r)!==y(p.installSource,o,r)||!s||typeof s!="object"||!b(s.extensions,B))continue}i!==void 0&&u.add(i)}}return u}a(Y,"detectInstalledSetupPackageIds");function k(e){return se("sh",["-lc",`command -v ${e} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}a(k,"detectCommandOnPath");function Be(e=process.platform,t=k){switch(e){case"darwin":return t("brew")?"brew":"manual";case"linux":return t("apt-get")?"apt-get":t("dnf")?"dnf":t("pacman")?"pacman":"manual";default:return"manual"}}a(Be,"detectPackageManager");function Ue(e,t,n=k){if(e==="nerd-font"?Pe().installed:n(e))return{tool:e,installed:!0,command:null,hint:"already installed",autoInstall:!1};if(e==="nerd-font"){const u=Ie(t);return{tool:e,installed:!1,command:u.command,hint:`${u.hint} \u2014 ${Ee}`,autoInstall:u.autoInstall}}const o=e==="nvim"?"neovim":"tmux";switch(t){case"brew":return{tool:e,installed:!1,command:`brew install ${o}`,hint:"Homebrew install",autoInstall:!0};case"apt-get":return{tool:e,installed:!1,command:`sudo apt-get update && sudo apt-get install -y ${o}`,hint:"apt-get install",autoInstall:!0};case"dnf":return{tool:e,installed:!1,command:`sudo dnf install -y ${o}`,hint:"dnf install",autoInstall:!0};case"pacman":return{tool:e,installed:!1,command:`sudo pacman -S --noconfirm ${o}`,hint:"pacman install",autoInstall:!0};default:return{tool:e,installed:!1,command:null,hint:`manual install required for ${e}`,autoInstall:!1}}}a(Ue,"buildSystemInstallPlan");function T(e=w()){return m(e===w()?I():m(e,".pi","agent"),"settings.json")}a(T,"resolveSettingsPath");function Ct(e={}){const t=e.homeDir??w(),n=e.settingsPath??T(t),r=e.manifest??D(),o=ve(n),u=Y(o,r,n,t);for(const d of X(r))u.add(d);const c=e.commandExists??k,l=e.packageManager??Be(process.platform,c),s=["tmux","nvim","nerd-font"].map(d=>Ue(d,l,c));return{manifest:r,installedPackageIds:u,systemPlans:s}}a(Ct,"buildSetupInitialState");function Et(e){const t=e.manifest.map(r=>{const o=e.installedPackageIds.has(r.id)?"installed":"not installed";return`- ${r.name} \u2014 ${r.shortDescription} (${o})`}),n=e.systemPlans.map(r=>r.installed?`- ${r.tool}: \u2713 installed`:r.command?`- ${r.tool}: ${r.command}`:`- ${r.tool}: ${r.hint}`);return["crtr sys setup (non-interactive)","","Provider login: open the wizard in a TTY and use the Providers tab (same flow as /login) to authenticate a model provider.","","Packages:",...t,"","System deps:",...n,"",`Inbox: the inbox-toggle key (${me()??"disabled"}) is a crouter keybinding \u2014 view or rebind it in \`crtr sys settings\`; it is installed on the same tmux server as every other crouter binding.`,"Run `crtr sys setup` in a TTY to open the wizard."].join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`}a(Et,"renderSetupStaticInstructions");class P extends Error{static{a(this,"SetupCommandError")}output;constructor(t,n){super(t),this.output=n}}function $t(e){return`${e.stdout?.toString()??""}${e.stderr?.toString()??""}`}a($t,"commandOutput");function q(e,t,n,r=process.env){return new Promise((o,u)=>{const c=ie(e,t,{stdio:["ignore","pipe","pipe"],env:r});let l="";c.stdout.setEncoding("utf8"),c.stderr.setEncoding("utf8"),c.stdout.on("data",s=>{l+=s}),c.stderr.on("data",s=>{l+=s,n?.(s)}),c.on("error",s=>u(new P(`${e} failed: ${s.message}`,l))),c.on("close",s=>{s===0?o():u(new P(`${e} failed with status ${s??"unknown"}`,l))})})}a(q,"runCapturedCommand");function
|
|
3
|
+
`}a(Et,"renderSetupStaticInstructions");class P extends Error{static{a(this,"SetupCommandError")}output;constructor(t,n){super(t),this.output=n}}function $t(e){return`${e.stdout?.toString()??""}${e.stderr?.toString()??""}`}a($t,"commandOutput");function q(e,t,n,r=process.env){return new Promise((o,u)=>{const c=ie(e,t,{stdio:["ignore","pipe","pipe"],env:r});let l="";c.stdout.setEncoding("utf8"),c.stderr.setEncoding("utf8"),c.stdout.on("data",s=>{l+=s}),c.stderr.on("data",s=>{l+=s,n?.(s)}),c.on("error",s=>u(new P(`${e} failed: ${s.message}`,l))),c.on("close",s=>{s===0?o():u(new P(`${e} failed with status ${s??"unknown"}`,l))})})}a(q,"runCapturedCommand");function M(e,t){return q("sh",["-lc",e],t)}a(M,"runShellCommand");function ze(e,t=be()){return q(process.execPath,[t,"install",e],void 0,{...process.env,PI_CODING_AGENT_DIR:I()})}a(ze,"installPiPackage");async function W(){k("capture")||await M("npm install -g @crouton-kit/capture")}a(W,"installCaptureCliIfMissing");function H(e){return e instanceof P?e.output:void 0}a(H,"capturedFailureOutput");function Ye(e){const n=H(e)?.split(/\r?\n/).find(r=>r.trim()!=="");return n!==void 0?n.trim():e instanceof Error?e.message:String(e)}a(Ye,"firstFailureLine");function qe(e){const t=H(e);t===void 0||t.length===0||process.stderr.write(t.endsWith(`
|
|
4
4
|
`)?t:`${t}
|
|
5
5
|
`)}a(qe,"printCapturedFailure");class We{static{a(this,"SetupProgress")}interactive;bar=null;constructor(t=!!process.stdout.isTTY){this.interactive=t}start(t){return this.interactive?(this.bar=$e(`Installing ${t}\u2026`),this.bar):null}async clear(){await this.bar?.stop(),this.bar=null}async succeed(t){await this.clear(),this.interactive&&process.stdout.write(`\r\x1B[2K\u2713 ${t}
|
|
6
6
|
`)}async fail(t,n){await this.clear(),this.interactive&&process.stdout.write(`\r\x1B[2K\u2717 ${t} \u2014 ${Ye(n)}
|
|
7
7
|
`),qe(n)}async run(t,n){const r=this.start(t);try{const o=await n(r);return await this.succeed(t),o}catch(o){throw await this.fail(t,o),o}}}function J(e,t){return K()?"current":(e?.(),Ae(t),K()?"provisioned":"unavailable")}a(J,"ensureManagedRenderer");async function He(){try{ye()}catch{}}a(He,"reconcileInboxFrontDoor");function V(e,t){return t.length===0?[`${e}: none`]:[`${e}:`,...t.map(n=>` - ${n}`)]}a(V,"summarySection");function At(e){return["crtr sys setup complete",...V("installed",e.installed),...V("skipped",e.skipped),"New to crouter? Ask for the tutorial in your first conversation, or run /tutorial any time."].join(`
|
|
8
8
|
`)+`
|
|
9
|
-
`}a(At,"formatSetupExecutionSummary");function X(e,t){const n=[];for(const r of e)try{r.sourceKind==="marketplace-source"?C(r.name,t)!==null&&n.push(r.id):r.sourceKind==="marketplace-plugin"&&F(r.name,t)!==null&&n.push(r.id)}catch{}return n}a(X,"detectInstalledMarketplaceEntries");async function Je(e,t="user"){if(C(e,t)!==null)return null;if(e!==E)throw new Error(`marketplace not registered: ${e}`);return await j({url:$,ref:A,scope:t}),e}a(Je,"ensureMarketplaceRegistered");function Ve(e){const t=
|
|
9
|
+
`}a(At,"formatSetupExecutionSummary");function X(e,t){const n=[];for(const r of e)try{r.sourceKind==="marketplace-source"?C(r.name,t)!==null&&n.push(r.id):r.sourceKind==="marketplace-plugin"&&F(r.name,t)!==null&&n.push(r.id)}catch{}return n}a(X,"detectInstalledMarketplaceEntries");async function Je(e,t="user"){if(C(e,t)!==null)return null;if(e!==E)throw new Error(`marketplace not registered: ${e}`);return await j({url:$,ref:A,scope:t}),e}a(Je,"ensureMarketplaceRegistered");function Ve(e){const t=T(),n=L(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`invalid pi settings: ${t}`);const r=n.packages;if(!Array.isArray(r))throw new Error(`invalid pi packages: ${t}`);const o=a(l=>{const s=typeof l=="string"?l:l&&typeof l=="object"?l.source:void 0;return typeof s=="string"&&z(s).includes(x("pi-crtr-extensions"))},"isCrtrExtensions"),u=r.findIndex(o),c=r.filter(l=>!o(l));c.splice(u<0?c.length:u,0,{source:le(_(t),e),extensions:B}),ke(t,{...n,packages:c})}a(Ve,"configureCrtrExtensions");const Q="git is not installed \u2014 install it (Debian/Ubuntu: apt-get install git), then run `crtr sys setup`";function Z(e){return e.sourceKind==="marketplace-source"||e.sourceKind==="marketplace-plugin"}a(Z,"isMarketplaceEntry");async function ee(e){if(e.sourceKind==="marketplace-source")return await j({url:e.installSource,ref:A,scope:"user"}),[e.name];if(e.sourceKind==="marketplace-plugin"){const[t,n]=e.installSource.split("/"),r=await Je(t);return await Re({marketplace:t,plugin:n},"user"),e.id==="capture-plugin"&&await W(),r===null?[e.name]:[r,e.name]}return await ze(e.installSource),e.id==="crtr-extensions"&&Ve(e.installSource),[e.name]}a(ee,"installSetupPackage");async function Rt(e,t=k){const n=D(),r=Y(L(T()),n);for(const s of X(n,"user"))r.add(s);const o=new Map(n.map(s=>[s.id,s])),u=process.stdin.isTTY&&process.stdout.isTTY?["crtr-extensions","official-marketplace","oauth-adapter","capture-plugin"]:["crtr-extensions","official-marketplace","capture-plugin"];let c,l=!1;for(const s of u){const d=o.get(s);if(!r.has(s)){if(Z(d)&&(c??=!t("git"),c)){l||e("marketplace packages",new Error(Q)),l=!0;continue}try{await ee(d)}catch(h){e(d.name,h)}}}try{J(void 0,()=>{})==="unavailable"&&e("termrender renderer",new Error("unavailable \u2014 install uv"))}catch(s){e("termrender renderer",s)}return we()}a(Rt,"reconcileFirstRun");async function Dt(e,t=k){const n=[],r=[],o=[],u=[],c=new We;let l,s=!1;for(const i of e.packages){if(e.installedPackageIds.has(i.id)){if(r.push(`${i.name} (already installed)`),i.id==="capture-plugin"&&!k("capture"))try{await c.run("Capture CLI",()=>W()),n.push("Capture CLI")}catch(p){r.push(`Capture CLI (${p instanceof Error?p.message:String(p)})`)}continue}if(Z(i)&&(l??=!t("git"),l)){s||r.push(`marketplace packages (${Q})`),s=!0;continue}try{n.push(...await c.run(i.name,()=>ee(i)))}catch(p){if(i.sourceKind!=="marketplace-source"&&i.sourceKind!=="marketplace-plugin")throw p;r.push(`${i.name} (${p instanceof Error?p.message:String(p)})`)}}for(const i of e.systemDeps){if(i.installed){u.push(`${i.tool} (already installed)`);continue}if(!i.autoInstall||!i.command){u.push(`${i.tool} (${i.hint})`);continue}const p=i.command,v=p===Ce;await c.run(i.tool,N=>{if(!v||N===null)return M(p);const te=Se();return M(p,ne=>{const O=te(ne);O!==null&&N.setFraction(O/100)})}),o.push(i.tool)}const d=[];let h=!1,f;try{f=J(()=>{h=!0,c.start("termrender renderer")},i=>d.push(i))}catch(i){throw h&&await c.fail("termrender renderer",i),i}switch(f){case"provisioned":h&&await c.succeed("termrender renderer"),n.push("termrender renderer");break;case"current":r.push("termrender renderer (current)");break;case"unavailable":{const i=new P("unavailable \u2014 install uv",d.join(""));h&&await c.fail("termrender renderer",i),r.push("termrender renderer (unavailable \u2014 install uv)");break}}if(e.terminalEdit!==void 0){const i=`Option as Alt (${e.terminalEdit.path})`,p=Le(e.terminalEdit);p.ok?n.push(`${i} \u2014 ${e.terminalEdit.reload}`):r.push(`${i} (${p.message})`)}return await He(),{installed:[...n,...o],skipped:[...r,...u]}}a(Dt,"executeSetupSubmission");export{E as OFFICIAL_MARKETPLACE_NAME,A as OFFICIAL_MARKETPLACE_REF,$ as OFFICIAL_MARKETPLACE_URL,It as SetupKeybindingsDraft,Ct as buildSetupInitialState,D as buildSetupManifest,Ue as buildSystemInstallPlan,k as detectCommandOnPath,Y as detectInstalledSetupPackageIds,Be as detectPackageManager,Dt as executeSetupSubmission,At as formatSetupExecutionSummary,y as normalizePackageIdentity,St as packagePlanAction,Rt as reconcileFirstRun,He as reconcileInboxFrontDoor,Et as renderSetupStaticInstructions,T as resolveSettingsPath,Pt as setupPluginEnvFields};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),W(e.complete)}i(m,"showSignIn");function Q(e){return async n=>{if(e.runId===void 0)return e.account===void 0||e.account.id===n.account.id?void 0:new a("signin_other_account",`This computer belongs to the Northlight account ${e.account.display}. Sign in to that account.`,c.USAGE);let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(r){return
|
|
3
|
-
`);const t=e.directoryUrl===void 0?F():String(e.directoryUrl),r=await K(m);if(r!==void 0)return
|
|
1
|
+
var O=Object.defineProperty;var i=(e,n)=>O(e,"name",{value:n,configurable:!0});import{spawn as w}from"node:child_process";import{mkdirSync as P,openSync as R}from"node:fs";import{dirname as v,join as U}from"node:path";import{defineLeaf as y}from"../../core/command.js";import{CrtrError as a}from"../../core/errors.js";import{controlPlaneUrl as C,personAccount as k,personBearer as _,readPersonCredential as b,signIn as l,signOut as I}from"../../core/directory/person-credential.js";import{hasLocalCanvas as T,moveRecordPath as x,readMachineConfig as g,readOrCreateInstallId as L,writeMachineConfig as D,writeMachineCredential as M}from"../../daemon/machine-link/config.js";import{probeDaemonHealth as j,sanitizedDaemonEnv as q,spawnDaemon as u,stopAllDaemons as p}from"../../daemon/manage.js";import{hostname as G}from"node:os";import{northlightUnreachable as f}from"../../core/directory/reach.js";import{envNodeId as B}from"../../shared/env.js";import{ExitCode as c}from"../../types.js";import{insideBroker as N}from"./join.js";import{defaultDirectoryUrl as F,finishMove as z,registerThisMac as E,runMove as H,settleEarlierMove as K}from"./import/move.js";import{oldPackageInstalled as J}from"./old-package.js";import{WAIT_FOR_PID_ENV as V}from"./import/start.js";function W(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{w(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}i(W,"openBrowser");function m(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
|
|
2
|
+
`),W(e.complete)}i(m,"showSignIn");function Q(e){return async n=>{if(e.runId===void 0)return e.account===void 0||e.account.id===n.account.id?void 0:new a("signin_other_account",`This computer belongs to the Northlight account ${e.account.display}. Sign in to that account.`,c.USAGE);let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(r){return f(r,e.apiUrl)}if(!t.ok)return t.status===404?new a("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,c.USAGE):new a("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,c.GENERAL,{next:"Retry `crtr sys signin`."})}}i(Q,"sameAccountOnly");function S(e){const n=U(v(x()),"move.log");P(v(n),{recursive:!0});const t=R(n,"a",384),r=q();for(const o of["CRTR_API_SOCKET","CRTR_API_TOKEN","CRTR_API_URL"])delete r[o];r[V]=String(process.pid);const s=[...process.execArgv,process.argv[1],"sys","import","start","--kind","machine",...e===void 0?[]:["--notify",e]];w(process.execPath,s,{detached:!0,stdio:["ignore",t,t],env:r}).unref()}i(S,"startDetachedMove");async function X(e){const n=b()===void 0?(await l(e,m),await k(e)):await k(e),t=await C(e),r=await _(e),s=i(async $=>{try{return await fetch(new URL(`/v1/machines${$?"?rotate=1":""}`,t),{method:"POST",headers:{authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({install_id:L(),name:G().slice(0,64)}),signal:AbortSignal.timeout(3e4)})}catch(A){throw f(A,t)}},"post");let o=await s(!1);o.status===409&&(await o.clone().text()).includes("credential_exists")&&(o=await s(!0));const d=await o.text();if(!o.ok)throw new a("machine_registration_failed",`Northlight refused to register this computer (HTTP ${o.status}): ${d.slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signin` again."});const h=JSON.parse(d);if(typeof h.credential!="string"||typeof h.environment_id!="string")throw new a("machine_registration_failed","Northlight answered without a credential",c.GENERAL);return M(h.credential),D({apiUrl:t,environmentId:h.environment_id,directoryUrl:e,account:n}),await E(e),await p(),await u(),{account:n.display}}i(X,"registerFreshComputer");const Y=i(e=>`Signed in as ${e}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`,"MOVING"),ve=y({name:"signin",description:"sign this computer's crtr in to the person's Northlight account and register it as one of their machines",whenToUse:"the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`",help:{name:"sys signin",summary:"pair this computer with the person's Northlight account in the browser, move this computer's records into it, and register it with the directory",guide:"Prints a code and opens the directory's confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account's move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. Once the records are in the account the computer is also registered as one of the account's machines: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.",params:[{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."}],output:[{name:"account",type:"string",required:!0,constraint:"The account this computer is now signed in as."},{name:"moved",type:"boolean",required:!1,constraint:"Present when this command moved the records, or finished an earlier move's switch-over."},{name:"moving",type:"boolean",required:!1,constraint:"Present when the move runs on in its own process (run from inside a node): end the turn; the node is messaged when it finishes or fails."}],outputKind:"object",effects:["Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.","Starts the local daemon first when it is not running, and waits until it serves.","On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account's result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.","On a computer with no local records: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.","On a moved computer: restarts the daemon so it reconnects to Northlight.","Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity."]},run:i(async e=>{(g()!==void 0||T())&&await u();const n=J();n!==void 0&&process.stderr.write(`${n.message}
|
|
3
|
+
`);const t=e.directoryUrl===void 0?F():String(e.directoryUrl),r=await K(m);if(r!==void 0)return N()?(S(void 0),{account:r.account.display,moving:!0}):(await z(r),{account:r.account.display,moved:!0});const s=g();if(s!==void 0){const{account:d}=await l(t,m,{accept:Q(s)});return await E(t),await p(),await u(),{account:d}}if(!T())return await X(t);const{account:o}=await l(t,m);return N()?(S(B()),{account:o,moving:!0}):(await H({directoryUrl:t,notify:null}),{account:o,moved:!0})},"run"),render:i(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${Y(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function Z(){return await p(),await u(),(await j()).signed_in===!1}i(Z,"stopMovedComputer");async function ee(e){if(b()===void 0)return;const n=await _(e.directoryUrl);let t;try{t=await fetch(new URL(`/v1/machines/${e.environmentId}`,e.apiUrl),{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(3e4)})}catch(r){throw f(r,e.apiUrl)}if(!t.ok&&t.status!==404)throw new a("machine_revoke_failed",`Northlight refused to revoke this computer's machine credential (HTTP ${t.status}): ${(await t.text()).slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signout` again."})}i(ee,"revokeMachine");const ye=y({name:"signout",description:"sign this computer's crtr out, revoke its credential, and stop its agents",whenToUse:"this computer should stop acting as the person on Northlight, or its stored sign-in may have leaked",help:{name:"sys signout",summary:"revoke the stored credential, delete it from this computer, and on a moved computer stop every agent and cron here",params:[],output:[{name:"signed_out",type:"boolean",required:!0,constraint:"False when no sign-in was stored."},{name:"revoked",type:"boolean",required:!0,constraint:"True when the directory ended the credential now; false when it was already ended or none was stored."},{name:"stopped",type:"boolean",required:!0,constraint:"True when this computer's records are in Northlight and its agents and running crons have stopped; false on a computer whose records are local, where nothing else is tied to the sign-in."}],outputKind:"object",effects:["On a fleet machine first calls `DELETE /v1/machines/<environment>` with the stored sign-in, which ends the machine credential (no running daemon needed). Then calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.","On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`."]},run:i(async()=>{const e=g();e!==void 0&&await ee(e);const{signedOut:n,revoked:t}=await I(),r=e===void 0?!1:await Z();return{signed_out:n,revoked:t,stopped:r}},"run"),render:i(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{X as registerFreshComputer,m as showSignIn,ve as sysSigninLeaf,ye as sysSignoutLeaf};
|
|
@@ -30,6 +30,12 @@ export declare function renameClashingProfiles(db: CanvasDb, schema: string, tar
|
|
|
30
30
|
* different amounts. A staged one whose id the target holds with a different payer, units or usd is renamed `<id>:install-<install id>`; one the target holds unchanged keeps its
|
|
31
31
|
* id and is skipped by the copy. A second load of the same bundle derives the same id. Runs before the pre-check. */
|
|
32
32
|
export declare function renameClashingLegacyCharges(db: CanvasDb, schema: string, target: string, installId: string): Promise<number>;
|
|
33
|
+
/** A staged watch whose (watcher, object) the target already holds is already imported (a hosted person's nodes watching shared objects): it and its subscriptions are
|
|
34
|
+
* dropped, the target's rows stand. Only this key is skipped; any other unique conflict still fails the pre-check. Returns the dropped watches and subscriptions. Runs before the pre-check. */
|
|
35
|
+
export declare function dropExistingWatches(db: CanvasDb, schema: string, target: string): Promise<{
|
|
36
|
+
watches: number;
|
|
37
|
+
watch_subscriptions: number;
|
|
38
|
+
}>;
|
|
33
39
|
/** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
|
|
34
40
|
* absent). Runs in the copy transaction: it writes target objects. */
|
|
35
41
|
export declare function fillEnvironments(tx: CanvasDb, schema: string, target: string, source: SourceJson, person: string): Promise<number>;
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var D=Object.defineProperty;var
|
|
2
|
-
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let
|
|
1
|
+
var D=Object.defineProperty;var E=(n,s)=>D(n,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as v,mapPath as N}from"../bundle/layout.js";import{ImportLaneError as _}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as H}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const p=E((n,s)=>`${l(n)}.${l(s)}`,"sq");async function K(n,s,o){if(o.length===0)return 0;const e=E(c=>p(s,c),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const d=E(async(c,r,t,$=!1)=>{const m=await n.prepareUncached(`SELECT ${l(r)}::text AS value FROM ${e(c)} WHERE ${t} AND ${l(r)} IS NOT NULL`).all();for(const{value:f}of m){const S=$?M(f,o):N(o,f);S!==f&&(await n.prepareUncached(`UPDATE ${e(c)} SET ${l(r)} = ? WHERE ${l(r)}::text = ? AND ${t}`).run(S,f),a+=1)}},"apply");return await d("nodes","cwd",`node_id IN ${i}`),await d("worktrees","path",`node_id IN ${i}`),await d("worktrees","repo_root",`node_id IN ${i}`),await d("crons","cwd",`anchor_node IN ${i}`),await d("provider_approvals","prepared_files","TRUE",!0),await d("upload_uses","path",`run_id IN ${i}`),a}E(K,"rewritePaths");async function B(n,s,o,e,i){if(o.length===0)return 0;const a=E(r=>p(s,r),"S"),d=await n.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
|
|
2
|
+
AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let c=0;for(const{conversation_id:r,blob_key:t}of d){const $=H(i,t),m=await e.get($);if(m===null)throw new _("rewrite-paths","bundle_invalid",`${$} is missing: the header of conversation ${r} cannot be rewritten`);const f=C(m,r,S=>N(o,S));f!==null&&(await e.put($,f),c+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ?, cycle_offset = NULL WHERE conversation_id = ? AND seq = 0`).run((f??m).length,r)}return c}E(B,"rewriteConversationHeaders");async function J(n,s){const o=p(s,"human_requests"),e=E(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
|
|
3
3
|
WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
|
|
4
4
|
WHEN ${a} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${a}, length(rtrim(request_dir, '/')) + 2)
|
|
5
|
-
ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await n.prepareUncached(`UPDATE ${
|
|
6
|
-
request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}
|
|
7
|
-
WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name)
|
|
8
|
-
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(e);return Number(i.changes)}
|
|
5
|
+
ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await n.prepareUncached(`UPDATE ${o} SET file = ${e("file")}, presentation_dir = ${e("presentation_dir")},
|
|
6
|
+
request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}E(J,"rewriteRequestPaths");function M(n,s){const o=E(e=>typeof e=="string"?N(s,e):Array.isArray(e)?e.map(o):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,o(a)])):e,"walk");try{return JSON.stringify(o(JSON.parse(n)))}catch{return N(s,n)}}E(M,"rewriteJsonPaths");async function Y(n,s,o,e,i){const a=E(r=>p(s,r),"S"),d=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let c=0;for(const r of d){const t=await n.prepareUncached(`SELECT o.id FROM ${a("objects")} o JOIN ${a("identities")} i ON i.object = o.id AND i.scheme = 'profile' AND i.external_id = ?
|
|
7
|
+
WHERE o.type = 'profile' AND o.name = ?`).get(r.id,r.name),$=await n.prepareUncached(`SELECT 1 AS found FROM ${p(o,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,r.name,r.id),m=t===void 0?void 0:await n.prepareUncached(`SELECT 1 AS found FROM ${p(o,"objects")} WHERE type = 'profile' AND home_machine IS NULL AND name = ? AND id <> ?`).get(r.name,t.id);if($===void 0&&m===void 0)continue;const f=`${r.name}-${e}`;await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(f,r.id),t!==void 0&&await n.prepareUncached(`UPDATE ${a("objects")} SET name = ? WHERE id = ?`).run(f,t.id),c+=1}return c}E(Y,"renameClashingProfiles");async function X(n,s,o,e){const i=await n.prepareUncached(`UPDATE ${p(s,"charges")} s SET id = s.id || ':install-' || ?::text FROM ${p(o,"charges")} t
|
|
8
|
+
WHERE s.id LIKE 'legacy:%' AND t.id = s.id AND (s.payer IS DISTINCT FROM t.payer OR s.units IS DISTINCT FROM t.units OR s.usd IS DISTINCT FROM t.usd)`).run(e);return Number(i.changes)}E(X,"renameClashingLegacyCharges");async function G(n,s,o){const e=`FROM ${p(o,"watches")} t WHERE t.watcher = s.watcher AND t.object = s.object`,i=await n.prepareUncached(`DELETE FROM ${p(s,"watch_subscriptions")} u USING ${p(s,"watches")} s WHERE u.watch = s.watch_id AND EXISTS (SELECT 1 ${e})`).run(),a=await n.prepareUncached(`DELETE FROM ${p(s,"watches")} s WHERE EXISTS (SELECT 1 ${e})`).run();return{watches:Number(a.changes),watch_subscriptions:Number(i.changes)}}E(G,"dropExistingWatches");async function z(n,s,o,e,i){const a=E(r=>p(s,r),"S");let d=0;const c=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const r of c){let t=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(t=(await n.prepareUncached(`SELECT environment_id FROM ${p(o,"profiles")} WHERE id = ?`).get(r.id))?.environment_id??await U(n,{profileId:r.id,grantee:r.grantee??"app:terminal",person:i})),t===null)throw new _("fill","bundle_invalid",`profile ${r.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(t,r.id),d+=1}return d}E(z,"fillEnvironments");async function Q(n,s,o,e){const i=E(c=>p(s,c),"S"),a={},d=E(async(c,r,...t)=>{const $=Number((await n.prepareUncached(r).run(...t)).changes);$>0&&(a[c]=(a[c]??0)+$)},"del");await d("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await n.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await n.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[c,r]of Object.entries(v))await d(c,`DELETE FROM ${i(c)} WHERE ${l(r)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,c);for(const c of o.tables.values())c.columns.includes("claimed_by")&&c.columns.includes("lease_expires_at")&&await n.prepareUncached(`UPDATE ${i(c.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}E(Q,"pruneStaged");async function V(n,s,o){const e=E(d=>p(s,d),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${p(o,"documents")} t WHERE t.object = d.object))`;await n.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
|
|
9
9
|
CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await n.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
|
|
10
10
|
COALESCE((SELECT array_agg(p.parent) FROM ${e("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
|
|
11
|
-
FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(
|
|
12
|
-
FROM (SELECT * FROM ${
|
|
13
|
-
FROM (SELECT ctid AS row_id, * FROM ${
|
|
14
|
-
FROM ${
|
|
11
|
+
FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(d=>({...d}))}E(V,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]},F={charges:["payer","units","usd"]};async function Z(n,s,o,e,i,a,d){const c=E(t=>[...d.get(t)??[],...t==="profiles"?["environment_id"]:[],...g[t]??[],"claimed_by","lease_expires_at"],"ignored"),r=[];for(const t of i){const $=e.tables.get(t);if($===void 0||a.has(t)||$.primaryKey.length===0)continue;const m=$.primaryKey,f=m.some(u=>$.identity.includes(u)),S=m.map(u=>`s.${l(u)} = t.${l(u)}`).join(" AND "),I=f?"TRUE":m.map(u=>`s.${l(u)} IS DISTINCT FROM t.${l(u)}`).join(" OR "),A=new Set([...$.identity,...d.get(t)??[]]);for(const u of e.uniqueKeys.filter(h=>h.table===t&&!h.columns.every(T=>A.has(T)))){const h=u.predicate===null?"":` WHERE ${u.predicate}`,T=u.columns.map(R=>`s.${l(R)} = t.${l(R)}`).join(" AND "),O=await n.prepareUncached(`SELECT ${u.columns.map(R=>`s.${l(R)}::text`).join(" || ',' || ")} AS value
|
|
12
|
+
FROM (SELECT * FROM ${p(s,t)}${h}) s JOIN (SELECT * FROM ${p(o,t)}${h}) t ON ${T} AND (${I}) LIMIT 10`).all();O.length>0&&r.push({table:t,key:u.name,values:O.map(R=>R.value)});const y=f?"TRUE":m.map(R=>`a.${l(R)} IS DISTINCT FROM b.${l(R)}`).join(" OR "),L=await n.prepareUncached(`SELECT DISTINCT ${u.columns.map(R=>`a.${l(R)}::text`).join(" || ',' || ")} AS value
|
|
13
|
+
FROM (SELECT ctid AS row_id, * FROM ${p(s,t)}${h}) a JOIN (SELECT ctid AS row_id, * FROM ${p(s,t)}${h}) b ON ${u.columns.map(R=>`a.${l(R)} = b.${l(R)}`).join(" AND ")} AND a.row_id < b.row_id AND (${y}) LIMIT 10`).all();L.length>0&&r.push({table:t,key:u.name,values:L.map(R=>R.value),staged:!0})}const w=$.columns.filter(u=>!$.identity.includes(u)&&!c(t).includes(u)&&(F[t]?.includes(u)??!0));if(w.length>0&&!f){const u=w.map(T=>`s.${l(T)} IS DISTINCT FROM t.${l(T)}`).join(" OR "),h=await n.prepareUncached(`SELECT ${m.map(T=>`s.${l(T)}::text`).join(" || ',' || ")} AS value
|
|
14
|
+
FROM ${p(s,t)} s JOIN ${p(o,t)} t ON ${S} WHERE ${u} LIMIT 10`).all();h.length>0&&r.push({table:t,key:"primary key payload",values:h.map(T=>T.value)})}}if(r.length>0){const t=r[0];throw new _("pre-check","unique_conflict",`${t.table} ${t.key} collides ${t.staged===!0?"within the bundle":"with the target"}: ${t.values.join(", ")}`,{collisions:r})}}E(Z,"precheck");export{G as dropExistingWatches,z as fillEnvironments,Z as precheck,Q as pruneStaged,X as renameClashingLegacyCharges,Y as renameClashingProfiles,B as rewriteConversationHeaders,K as rewritePaths,J as rewriteRequestPaths,V as takeRepoSyncedDocuments};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var X=Object.defineProperty;var
|
|
1
|
+
var X=Object.defineProperty;var f=(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 D}from"../../canvas/db.js";import{runAsPerson as M}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ae}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{copyRows as se,decodeKeys as W,encodeKeys as B}from"./copy.js";import{pruneStaged as re,precheck as oe,dropExistingWatches as de,renameClashingLegacyCharges as pe,renameClashingProfiles as ce,rewriteConversationHeaders as ue,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 Ee,checkStagedRequestKeys as ye}from"./bind.js";import{deleteBlobs as Se,deleteRunBlobs as ve,deleteRunPrefix as Re,moveRunBlobs as Ie}from"./blobs.js";import{dropStubRows as Oe,findFleetGrant as Pe,grantMissing as je,mapProfileIds as Te,renameClashingRepos as ke,rewriteIds as Ce,rewritePerson as Ae,scopeRepoIdentities as De}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 We}from"./verify.js";import{sandboxPathMap as Be,writeNodeFiles as He}from"./path-map.js";import{allStoreKeys as Ke,readPluginsStore as Ue,recordImportedActivations as Fe,writeStores as Je}from"./stores.js";import{openImportGrants as Ge}from"./open-grants.js";import{publishImportedPlugins as qe}from"./publish-plugins.js";import{COPIED_TABLES as $e}from"../bundle/layout.js";import{emitEvent as Ye}from"../../events/emit.js";import{ClaimLostError as ze}from"../../../daemon/reconcilers/row-claim.js";const Qe=10*6e4,Ve=30*6e4,R=f(()=>new Date().toISOString(),"now"),K=f(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Xe(e,s){const a=await e.get(N.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}f(Xe,"readSource");async function Ze(e,s,a,n,i,p,d){const o=[];for(const t of L(a.run_id,"grants",n)){const c=await e.get(t);if(c===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ne(c))}if(o.length===0)return;const w=o.map(t=>({sub:_e(t.sub,n.person,a.person,"grants.sub"),grantee:t.grantee}));await d(a.run_id);const m=[];for(const t of w)await Pe(s,i,p,t.sub,t.grantee)===void 0&&m.push(t.grantee);if(m.length>0)throw je(m)}f(Ze,"ensureGrants");async function Ot(e,s,a={}){const n=a.blobs??await x(),i=await v(),p=Ne(e.run_id);let d="start";const o=f(async t=>{d=t,await s.assertOwned(),await K(e.run_id,t),await a.atStep?.(t)},"at");let w=e.state==="committed";const m=[];try{const t=await Xe(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 c=await Le(i),I=[...$e],h=await ie(i,c,[...I,"grants"]);if(!w){const l={},P=[],j=[],T=a.fleetRuntime??process.env.CRTR_RUNTIME??null;await ge(i,c,t.person,e.person),await o("open-grants"),await Ze(n,i,e,t,c,T,a.openGrants??Ge),await o("publish-plugins");const F=await Ue(n,e.run_id),y=await M(e.person,()=>qe(F));if(y.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)>=Qe)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${y.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:y.unavailable});await s.assertOwned(),await K(e.run_id,"waiting_for_directory");return}j.push(...y.refused),await o("stage");const J=await Me(i,e.run_id,t.counts,r=>L(e.run_id,r,t),r=>n.get(r));for(const[r,u]of Object.entries(J))l[r]={staged:u,inserted:0,mapped:0,dropped:0};const _={db:i,schema:p,target:c,catalog:h,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:T,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[r,u]of Object.entries(await he(_)))b(l,r,u);for(const[r,u]of Object.entries(await be(_)))b(l,r,u);await o("rewrite-person"),await Ae(_),await De(_),await o("prune");const G=await re(i,p,h,t),S=t.kind==="hosted"?Be(t.pathPrefixes??[]):[];await o("rewrite-paths"),await le(i,p,S),await ue(i,p,S,n,e.run_id),await fe(i,p),await ye(_);const q=await Te(_);await ce(i,p,c,t.installId,e.person),await o("rewrite-ids");const k=await Ce(_,q);await o("drop");const $=await me(i,p,c),Y=await Oe(_);for(const[r,u]of Object.entries({...G}))b(l,r,u);for(const[r,u]of Object.entries(Y))b(l,r,u);for(const[r,u]of Object.entries(await we(_,{installId:t.installId,person:e.person,runId:e.run_id})))b(l,r,u);await Ee(_,{installId:t.installId,person:e.person,runId:e.run_id}),await ke(_),await pe(i,p,c,t.installId);for(const[r,u]of Object.entries(await de(i,p,c)))b(l,r,u);await o("pre-check");const z=new Map([["messages",["seq"]],...ae.map(r=>[r,["seq"]])]);await oe(i,p,c,h,I,new Set,z),await o("blobs"),await Ie(i,p,c,e.person,n,e.run_id,m),await o("copy"),await M(e.person,()=>D(async r=>{await s.assertOwned({extendLeaseMs:Ve});const u=await se({db:r,runId:e.run_id,schema:p,target:c,catalog:h,source:t,person:e.person,idMap:k,pathMap:S}),C=await tt(r,e.run_id,$);C>0&&(u.inserted.revisions=(u.inserted.revisions??0)+C),await He(r,p,e.run_id,t);const A=await Je({db:r,blobs:n,runId:e.run_id,person:e.person,objectMap:k.object});for(const[Q,V]of Object.entries(A.inserted))u.inserted[Q]=V.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({...et(l,u),unresolved_plugins:P,refused_plugins:j}),R(),e.run_id),u})),w=!0,await a.atStep?.("committed")}await o("verify");const E=await We(i,e.run_id,p,c,h,t.installId);if(await i.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(E),e.run_id),!E.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:E.differences,invariants:E.invariants});await o("manifest");const O=N.manifest(e.run_id);await n.put(O,await nt(e.run_id)),await H(i,e.run_id);for(const l of Ke(e.run_id))await n.delete(l);await ve(n,e.run_id),await D(async l=>{await Fe(l,e.run_id,e.person),await l.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 ze)throw t;const c=xe(t,d);Ye({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:c.step,code:c.code}}),await H(i,e.run_id).catch(()=>{}),w||await Se(n,m,!0),await i.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(c),R(),e.run_id),await Re(n,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}f(Ot,"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 a=e.code;return{step:s,code:typeof a=="string"?a:"import_failed",message:e instanceof Error?e.message:String(e)}}f(xe,"failureOf");function b(e,s,a){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=a}f(b,"addDropped");function et(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}f(et,"withInserted");async function tt(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(m=>({rev_id:m.rev_id,parents:m.parents,body_hash:m.body_hash,rationale:m.rationale,created_at:m.created_at})))}return await U(e,s,"revisions",i.map(d=>[d.rev_id])),await U(e,s,"revision_parents",i.flatMap(d=>d.parents.map(o=>[d.rev_id,o]))),i.length}f(tt,"arrive");async function U(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([...W(i.inserted_keys),...n]),s,a)}f(U,"appendManifest");async function nt(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 Z(Buffer.from(a.map(n=>JSON.stringify({table:n.table_name,keys:W(n.inserted_keys)})).join(`
|
|
2
2
|
`)+`
|
|
3
|
-
`))}
|
|
3
|
+
`))}f(nt,"manifestFile");export{Ve as COPY_LEASE_MS,Qe as GRANT_WAIT_MS,Ot as processRun};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var W=Object.defineProperty;var a=(e,t)=>W(e,"name",{value:t,configurable:!0});import{randomUUID as Z}from"node:crypto";import{existsSync as G,realpathSync as O,rmSync as R,statSync as V}from"node:fs";import{resolve as M}from"node:path";import{SCHEMA_VERSION as k}from"../../types.js";import{profileSpace as g}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as C}from"../../api/dto/profiles.js";import{ensureDir as Y,nowIso as h}from"../fs-utils.js";import{cachedPausedProfileIds as B,cachedProfilePaused as Q,getCachedProfile as p,listCachedProfiles as X,writeSettings as w}from"../scoped-state/person-store.js";import{usage as c,notFound as d,ambiguous as N,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as D,personId as te}from"../canvas/person-state.js";import{readMachineConfig as ne}from"../../daemon/machine-link/config.js";const P=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,m="root-00000000",j="root";function y(e){return e.grantee??"app:terminal"}a(y,"profileApp");function x(e,t){Y(g(y(t),e).dir)}a(x,"scaffoldProfile");function $(e){if(!P.test(e))throw c(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}a($,"assertSafeProfileId");function be(e){$(e);const t=p(e);if(t===null)throw d(`profile not found: ${e}`,{received:e});return g(y(t.manifest),e).dir}a(be,"profileDir");function _(e){if(!Array.isArray(e))throw c("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:n,repo:r}=t;for(const[i,o]of[["path",n],["repo",r]])if(o!==void 0&&(typeof o!="string"||o.trim()===""))throw c(`project entry has an invalid ${i}: ${JSON.stringify(t)}`,{field:"projects",next:`Give ${i} a non-empty string, or leave it out.`});if(n===void 0&&r===void 0)throw c(`project entry has neither path nor repo: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(_,"assertProfileProjects");function re(e){const t=C.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw c("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[n,r]of Object.entries(e)){if(n.trim()==="")throw c("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof r!="string"||!C.includes(r))throw c(`invalid delivery limit for ${n}: ${JSON.stringify(r)}`,{received:String(r),field:"delivery_limits",next:`Set ${n} to one of: ${t}.`})}}a(re,"assertDeliveryLimits");function ie(){return{entries:X(),unreadableIds:[]}}a(ie,"enumerateProfiles");function v(){return ie().entries}a(v,"listProfiles");function oe(e){const t=v(),n=z(t,e,b);return n?{kind:"resolved",entry:n}:{kind:"absent"}}a(oe,"lookupProfile");function L(e){$(e);const t=p(e);if(t!==null)return t;throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(L,"loadExactProfileManifest");const b=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function z(e,t,n){if(P.test(t)){const i=e.find(o=>n(o).profileId===t);if(i!==void 0)return i}const r=e.filter(i=>n(i).name===t);if(r.length===1)return r[0];if(r.length>1){const i=r.map(o=>n(o).profileId);throw N(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}a(z,"findExactProfile");function J(e,t,n){const r=e.map(i=>`${n(i).profileId} (${n(i).name})`);return d(`profile not found: ${t}`,{received:t,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(J,"profileNotFound");function ae(e){const t=oe(e);if(t.kind==="resolved")return t.entry;throw J(v(),e,b)}a(ae,"loadProfileManifest");function Ae(e){return se(v(),e,b)}a(Ae,"resolveProfileOperand");function se(e,t,n){const r=z(e,t,n);if(r!==null)return r;const{match:i,tied:o}=ee(t,e.map(n));if(i!==null){const s=e.find(f=>n(f).profileId===i.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${n(s).name} (${n(s).profileId})`),s}if(o.length>1){const s=o.map(f=>`${f.profileId} (${f.name})`);throw N(`"${t}" is equally close to ${o.length} profiles: ${s.join(", ")}`,{received:t,candidates:o.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw J(e,t,n)}a(se,"matchProfileOperand");function T(e){const t=M(e);if(!G(t)||!V(t).isDirectory())throw c(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return O(t)}catch{return t}}a(T,"resolveExistingProjectDir");function A(e){const t=new Set,n=new Map,r=[];for(const i of e)if(i.path!==void 0){if(t.has(i.path))continue;t.add(i.path);const o=i.repo===void 0?void 0:n.get(i.repo);if(o!==void 0&&r[o].path===void 0){r[o]={...r[o],path:i.path};continue}r.push(i)}else if(i.repo!==void 0){if(n.has(i.repo))continue;n.set(i.repo,r.length),r.push(i)}else r.push(i);return r}a(A,"dedupeProjects");function fe(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}a(fe,"slugify");function ce(e){const t=fe(e);for(let n=0;n<20;n++){const r=Z().replace(/-/g,"").slice(0,8),i=`${t}-${r}`;if(p(i)===null)return i}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(ce,"generateProfileId");let E=null;function Ee(e){E=e}a(Ee,"setCloudProfileWriter");async function Se(){if(D()){const n=v().find(r=>r.manifest.name===j&&y(r.manifest)==="app:terminal");return n!==void 0?(x(n.profileId,n.manifest),n):await q(j,[],{grantee:"app:terminal"})}const e=p(m);if(e!==null)return x(m,e.manifest),e;const t={schema_version:k,name:j,projects:[],grantee:"app:terminal",paused_at:null,created_at:h(),last_used_at:h()};return x(m,t),await w(n=>n.profiles.some(r=>r.profileId===m)?[]:[{op:"profile.insert",profile:{profileId:m,manifest:t}}]),p(m)}a(Se,"ensureRootProfile");const U=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function F(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(F,"metadataEnvName");function S(e){if(typeof e!="object"||e===null||Array.isArray(e))throw c("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[n,r]of Object.entries(e)){if(!U.test(n))throw c(`invalid metadata key: ${JSON.stringify(n)}`,{received:n,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof r!="string")throw c(`metadata value for ${n} must be a string`,{received:typeof r,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(r.includes("\0"))throw c(`metadata value for ${n} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=F(n),o=t.get(i);if(o!==void 0)throw c(`metadata keys ${JSON.stringify(o)} and ${JSON.stringify(n)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,n)}}a(S,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},n=new Set;for(const[r,i]of Object.entries(e)){if(typeof i!="string"||!U.test(r)||i.includes("\0"))continue;const o=F(r);n.has(o)||(n.add(o),t[r]=i)}return t}a(K,"sanitizeProfileMetadata");async function q(e,t=[],n={}){const r=e.trim();if(r==="")throw c("profile name must not be empty");n.metadata!==void 0&&S(n.metadata),_(t);const i=A(t.map(l=>({...l.repo===void 0?{}:{repo:l.repo},...l.path===void 0?{}:{path:T(l.path)}}))),o=ce(r),s={schema_version:k,name:r,projects:i,paused_at:null,...n.grantee===void 0?{}:{grantee:n.grantee},...n.defaultKind!==void 0?{default_kind:n.defaultKind}:{},...n.metadata!==void 0&&Object.keys(n.metadata).length>0?{metadata:{...n.metadata}}:{},created_at:h(),last_used_at:null};x(o,s);const f=a(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:o,manifest:s}}])},"insert");if(D()){if(E===null)throw new Error("a cloud role has no profile environment writer registered");await E({profileId:o,grantee:y(s),person:te(),...n.memoryMb===void 0?{}:{memoryMb:n.memoryMb},...n.recipe===void 0?{}:{recipe:n.recipe}},async l=>{s.environment_id=l,await f()})}else{const l=ne();l!==void 0&&(s.environment_id=l.environmentId),await f()}return{profileId:o,manifest:s}}a(q,"createProfile");async function Oe(e){if(!e.startsWith("app:")||e.length<=4)throw c("an app grantee is required");const t=`app-${e.slice(4)}`,n=v().filter(r=>r.manifest.name===t&&r.manifest.grantee===e);if(n.length>1)throw new Error(`duplicate default profile for ${e}`);return n[0]?n[0]:await q(t,[],{grantee:e})}a(Oe,"ensureAppProfile");function H(e){if($(e),p(e)===null)throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(H,"requireExistingProfile");async function u(e,t){H(e);let n;return await w(r=>{const i=r.profiles.find(o=>o.profileId===e);if(i===void 0)throw d(`profile not found: ${e}`,{received:e});return n={profileId:e,manifest:t(structuredClone(i.manifest))},[{op:"profile.update",profile:n}]}),n}a(u,"mutateManifest");async function Re(e){return await u(e,t=>({...t,last_used_at:h()}))}a(Re,"updateProfileLastUsed");function le(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}a(le,"loadProfileManifestOrNull");function Me(e){return e==null||e===""||!P.test(e)?!1:Q(e)}a(Me,"isProfilePaused");function ke(){return B()}a(ke,"pausedCanvasProfiles");function ue(e){if(e.manifest.paused_at!==null)throw c(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}a(ue,"assertProfileEntryActive");function Ce(e){const t=le(e);return t===null?null:(ue(t),t)}a(Ce,"assertProfileActive");async function Ne(e){return await u(e,t=>({...t,paused_at:t.paused_at??h()}))}a(Ne,"pauseProfile");async function De(e){let t=null;return{...await u(e,r=>(t=r.paused_at,{...r,paused_at:null})),pausedAt:t}}a(De,"resumeProfile");async function Le(e,t){return await u(e,n=>({...n,default_kind:t}))}a(Le,"setProfileDefaultKind");async function ze(e,t,n=[]){return S(t),await u(e,r=>{const i={...K(r.metadata),...t};for(const f of n)delete i[f];S(i);const{metadata:o,...s}=r;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}a(ze,"updateProfileMetadata");function Je(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}a(Je,"readProfileMetadata");async function Te(e,t){const n=t.trim();if(n==="")throw c("profile name must not be empty");return await u(e,i=>({...i,name:n}))}a(Te,"renameProfile");async function Ue(e,t,n){_([{path:t,...n===void 0?{}:{repo:n}}]);const r=T(t);return await u(e,i=>({...i,projects:A(i.projects.some(o=>o.path===r)?i.projects.map(o=>o.path===r&&o.repo===void 0&&n!==void 0?{...o,repo:n}:o):[...i.projects,{path:r,...n===void 0?{}:{repo:n}}])}))}a(Ue,"addProfileProject");async function Fe(e,t){return _([{repo:t}]),await u(e,n=>({...n,projects:n.projects.some(r=>r.repo===t)?n.projects:A([...n.projects,{repo:t}])}))}a(Fe,"addProfileRepo");async function Ke(e,t,n){let r=!1;return await u(e,i=>{if(i.projects.some(s=>s.repo===n))return i;const o=i.projects.map(s=>s.path!==t||s.repo!==void 0?s:(r=!0,{...s,repo:n}));return r?{...i,projects:o}:i}),r}a(Ke,"fillProfileProjectRepo");async function qe(e,t,n){return re({[t]:n}),await u(e,r=>{const{[t]:i,...o}=r.delivery_limits??{},s=n==="content"?o:{...o,[t]:n},{delivery_limits:f,...l}=r;return Object.keys(s).length===0?l:{...l,delivery_limits:s}})}a(qe,"setProfileDeliveryLimit");async function He(e,t){const n=M(t);let r=n;try{r=O(n)}catch{}return await u(e,o=>{const s=o.projects.filter(f=>f.path===void 0||f.path!==r&&f.path!==n);if(s.length===o.projects.length)throw d(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${o.projects.length>0?o.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...o,projects:s}})}a(He,"removeProfileProject");async function We(e){H(e);const t=g(y(L(e).manifest),e);await w(n=>{if(!n.profiles.some(r=>r.profileId===e))throw d(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),R(t.dir,{recursive:!0,force:!0}),R(t.env,{force:!0})}a(We,"deleteProfile");export{m as ROOT_PROFILE_ID,Ue as addProfileProject,Fe as addProfileRepo,re as assertDeliveryLimits,Ce as assertProfileActive,ue as assertProfileEntryActive,S as assertProfileMetadata,_ as assertProfileProjects,q as createProfile,We as deleteProfile,Oe as ensureAppProfile,Se as ensureRootProfile,Ke as fillProfileProjectRepo,Me as isProfilePaused,v as listProfiles,L as loadExactProfileManifest,ae as loadProfileManifest,oe as lookupProfile,se as matchProfileOperand,F as metadataEnvName,Ne as pauseProfile,ke as pausedCanvasProfiles,be as profileDir,Je as readProfileMetadata,He as removeProfileProject,Te as renameProfile,Ae as resolveProfileOperand,De as resumeProfile,K as sanitizeProfileMetadata,Ee as setCloudProfileWriter,Le as setProfileDefaultKind,qe as setProfileDeliveryLimit,Re as updateProfileLastUsed,ze as updateProfileMetadata};
|
|
1
|
+
var W=Object.defineProperty;var a=(e,t)=>W(e,"name",{value:t,configurable:!0});import{randomUUID as Z}from"node:crypto";import{existsSync as G,realpathSync as O,rmSync as R,statSync as V}from"node:fs";import{resolve as M}from"node:path";import{SCHEMA_VERSION as k}from"../../types.js";import{profileSpace as P}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as C}from"../../api/dto/profiles.js";import{ensureDir as Y,nowIso as y}from"../fs-utils.js";import{cachedPausedProfileIds as B,cachedProfilePaused as Q,getCachedProfile as p,listCachedProfiles as X,writeSettings as w}from"../scoped-state/person-store.js";import{usage as c,notFound as d,ambiguous as N,general as I}from"../errors.js";import{fuzzyMatchProfile as ee}from"./fuzzy-match.js";import{isCloudRole as D,personId as te}from"../canvas/person-state.js";import{readMachineConfig as ne}from"../../daemon/machine-link/config.js";const j=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,v="root-00000000",x="root";function m(e){return e.grantee??"app:terminal"}a(m,"profileApp");function g(e,t){Y(P(m(t),e).dir)}a(g,"scaffoldProfile");function $(e){if(!j.test(e))throw c(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}a($,"assertSafeProfileId");function be(e){$(e);const t=p(e);if(t===null)throw d(`profile not found: ${e}`,{received:e});return P(m(t.manifest),e).dir}a(be,"profileDir");function _(e){if(!Array.isArray(e))throw c("projects must be an array of {repo?, path?} objects",{received:typeof e,field:"projects",next:'Pass entries like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});for(const t of e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`invalid project entry: ${JSON.stringify(t)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir"} or {"repo": "<repo object id>"}.'});const{path:n,repo:r}=t;for(const[i,o]of[["path",n],["repo",r]])if(o!==void 0&&(typeof o!="string"||o.trim()===""))throw c(`project entry has an invalid ${i}: ${JSON.stringify(t)}`,{field:"projects",next:`Give ${i} a non-empty string, or leave it out.`});if(n===void 0&&r===void 0)throw c(`project entry has neither path nor repo: ${JSON.stringify(t)}`,{field:"projects",next:"Give every project entry a directory path, a repo, or both."})}}a(_,"assertProfileProjects");function re(e){const t=C.join(", ");if(typeof e!="object"||e===null||Array.isArray(e))throw c("delivery_limits must be an object mapping owner handles to a level",{received:typeof e,field:"delivery_limits",next:`Pass e.g. {"crouter": "preview"} \u2014 each level is one of: ${t}.`});for(const[n,r]of Object.entries(e)){if(n.trim()==="")throw c("delivery_limits has an empty owner handle",{field:"delivery_limits",next:"Key each limit by an owner handle such as a repo handle or `user`, or exactly by `<type>:<handle>` such as `repo:crouter`."});if(typeof r!="string"||!C.includes(r))throw c(`invalid delivery limit for ${n}: ${JSON.stringify(r)}`,{received:String(r),field:"delivery_limits",next:`Set ${n} to one of: ${t}.`})}}a(re,"assertDeliveryLimits");function ie(){return{entries:X(),unreadableIds:[]}}a(ie,"enumerateProfiles");function h(){return ie().entries}a(h,"listProfiles");function oe(e){const t=h(),n=z(t,e,b);return n?{kind:"resolved",entry:n}:{kind:"absent"}}a(oe,"lookupProfile");function L(e){$(e);const t=p(e);if(t!==null)return t;throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(L,"loadExactProfileManifest");const b=a(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function z(e,t,n){if(j.test(t)){const i=e.find(o=>n(o).profileId===t);if(i!==void 0)return i}const r=e.filter(i=>n(i).name===t);if(r.length===1)return r[0];if(r.length>1){const i=r.map(o=>n(o).profileId);throw N(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}a(z,"findExactProfile");function J(e,t,n){const r=e.map(i=>`${n(i).profileId} (${n(i).name})`);return d(`profile not found: ${t}`,{received:t,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}a(J,"profileNotFound");function ae(e){const t=oe(e);if(t.kind==="resolved")return t.entry;throw J(h(),e,b)}a(ae,"loadProfileManifest");function Ae(e){return se(h(),e,b)}a(Ae,"resolveProfileOperand");function se(e,t,n){const r=z(e,t,n);if(r!==null)return r;const{match:i,tied:o}=ee(t,e.map(n));if(i!==null){const s=e.find(f=>n(f).profileId===i.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${n(s).name} (${n(s).profileId})`),s}if(o.length>1){const s=o.map(f=>`${f.profileId} (${f.name})`);throw N(`"${t}" is equally close to ${o.length} profiles: ${s.join(", ")}`,{received:t,candidates:o.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw J(e,t,n)}a(se,"matchProfileOperand");function T(e){const t=M(e);if(!G(t)||!V(t).isDirectory())throw c(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return O(t)}catch{return t}}a(T,"resolveExistingProjectDir");function A(e){const t=new Set,n=new Map,r=[];for(const i of e)if(i.path!==void 0){if(t.has(i.path))continue;t.add(i.path);const o=i.repo===void 0?void 0:n.get(i.repo);if(o!==void 0&&r[o].path===void 0){r[o]={...r[o],path:i.path};continue}r.push(i)}else if(i.repo!==void 0){if(n.has(i.repo))continue;n.set(i.repo,r.length),r.push(i)}else r.push(i);return r}a(A,"dedupeProjects");function fe(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}a(fe,"slugify");function ce(e){const t=fe(e);for(let n=0;n<20;n++){const r=Z().replace(/-/g,"").slice(0,8),i=`${t}-${r}`;if(p(i)===null)return i}throw I(`failed to generate a unique profile id for "${e}" after 20 attempts`)}a(ce,"generateProfileId");let E=null;function Ee(e){E=e}a(Ee,"setCloudProfileWriter");async function Se(){if(D()){const n=h().find(r=>r.manifest.name===x&&m(r.manifest)==="app:terminal");return n!==void 0?(g(n.profileId,n.manifest),n):await q(x,[],{grantee:"app:terminal"})}const e=p(v)??h().find(n=>n.manifest.name===x&&m(n.manifest)==="app:terminal")??null;if(e!==null)return g(e.profileId,e.manifest),e;const t={schema_version:k,name:x,projects:[],grantee:"app:terminal",paused_at:null,created_at:y(),last_used_at:y()};return g(v,t),await w(n=>n.profiles.some(r=>r.profileId===v)?[]:[{op:"profile.insert",profile:{profileId:v,manifest:t}}]),p(v)}a(Se,"ensureRootProfile");const U=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function F(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}a(F,"metadataEnvName");function S(e){if(typeof e!="object"||e===null||Array.isArray(e))throw c("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[n,r]of Object.entries(e)){if(!U.test(n))throw c(`invalid metadata key: ${JSON.stringify(n)}`,{received:n,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof r!="string")throw c(`metadata value for ${n} must be a string`,{received:typeof r,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(r.includes("\0"))throw c(`metadata value for ${n} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=F(n),o=t.get(i);if(o!==void 0)throw c(`metadata keys ${JSON.stringify(o)} and ${JSON.stringify(n)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,n)}}a(S,"assertProfileMetadata");function K(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},n=new Set;for(const[r,i]of Object.entries(e)){if(typeof i!="string"||!U.test(r)||i.includes("\0"))continue;const o=F(r);n.has(o)||(n.add(o),t[r]=i)}return t}a(K,"sanitizeProfileMetadata");async function q(e,t=[],n={}){const r=e.trim();if(r==="")throw c("profile name must not be empty");n.metadata!==void 0&&S(n.metadata),_(t);const i=A(t.map(l=>({...l.repo===void 0?{}:{repo:l.repo},...l.path===void 0?{}:{path:T(l.path)}}))),o=ce(r),s={schema_version:k,name:r,projects:i,paused_at:null,...n.grantee===void 0?{}:{grantee:n.grantee},...n.defaultKind!==void 0?{default_kind:n.defaultKind}:{},...n.metadata!==void 0&&Object.keys(n.metadata).length>0?{metadata:{...n.metadata}}:{},created_at:y(),last_used_at:null};g(o,s);const f=a(async()=>{await w(()=>[{op:"profile.insert",profile:{profileId:o,manifest:s}}])},"insert");if(D()){if(E===null)throw new Error("a cloud role has no profile environment writer registered");await E({profileId:o,grantee:m(s),person:te(),...n.memoryMb===void 0?{}:{memoryMb:n.memoryMb},...n.recipe===void 0?{}:{recipe:n.recipe}},async l=>{s.environment_id=l,await f()})}else{const l=ne();l!==void 0&&(s.environment_id=l.environmentId),await f()}return{profileId:o,manifest:s}}a(q,"createProfile");async function Oe(e){if(!e.startsWith("app:")||e.length<=4)throw c("an app grantee is required");const t=`app-${e.slice(4)}`,n=h().filter(r=>r.manifest.name===t&&r.manifest.grantee===e);if(n.length>1)throw new Error(`duplicate default profile for ${e}`);return n[0]?n[0]:await q(t,[],{grantee:e})}a(Oe,"ensureAppProfile");function H(e){if($(e),p(e)===null)throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}a(H,"requireExistingProfile");async function u(e,t){H(e);let n;return await w(r=>{const i=r.profiles.find(o=>o.profileId===e);if(i===void 0)throw d(`profile not found: ${e}`,{received:e});return n={profileId:e,manifest:t(structuredClone(i.manifest))},[{op:"profile.update",profile:n}]}),n}a(u,"mutateManifest");async function Re(e){return await u(e,t=>({...t,last_used_at:y()}))}a(Re,"updateProfileLastUsed");function le(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}a(le,"loadProfileManifestOrNull");function Me(e){return e==null||e===""||!j.test(e)?!1:Q(e)}a(Me,"isProfilePaused");function ke(){return B()}a(ke,"pausedCanvasProfiles");function ue(e){if(e.manifest.paused_at!==null)throw c(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}a(ue,"assertProfileEntryActive");function Ce(e){const t=le(e);return t===null?null:(ue(t),t)}a(Ce,"assertProfileActive");async function Ne(e){return await u(e,t=>({...t,paused_at:t.paused_at??y()}))}a(Ne,"pauseProfile");async function De(e){let t=null;return{...await u(e,r=>(t=r.paused_at,{...r,paused_at:null})),pausedAt:t}}a(De,"resumeProfile");async function Le(e,t){return await u(e,n=>({...n,default_kind:t}))}a(Le,"setProfileDefaultKind");async function ze(e,t,n=[]){return S(t),await u(e,r=>{const i={...K(r.metadata),...t};for(const f of n)delete i[f];S(i);const{metadata:o,...s}=r;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}a(ze,"updateProfileMetadata");function Je(e){if(e===null||e==="")return{};try{return K(L(e).manifest.metadata)}catch{return{}}}a(Je,"readProfileMetadata");async function Te(e,t){const n=t.trim();if(n==="")throw c("profile name must not be empty");return await u(e,i=>({...i,name:n}))}a(Te,"renameProfile");async function Ue(e,t,n){_([{path:t,...n===void 0?{}:{repo:n}}]);const r=T(t);return await u(e,i=>({...i,projects:A(i.projects.some(o=>o.path===r)?i.projects.map(o=>o.path===r&&o.repo===void 0&&n!==void 0?{...o,repo:n}:o):[...i.projects,{path:r,...n===void 0?{}:{repo:n}}])}))}a(Ue,"addProfileProject");async function Fe(e,t){return _([{repo:t}]),await u(e,n=>({...n,projects:n.projects.some(r=>r.repo===t)?n.projects:A([...n.projects,{repo:t}])}))}a(Fe,"addProfileRepo");async function Ke(e,t,n){let r=!1;return await u(e,i=>{if(i.projects.some(s=>s.repo===n))return i;const o=i.projects.map(s=>s.path!==t||s.repo!==void 0?s:(r=!0,{...s,repo:n}));return r?{...i,projects:o}:i}),r}a(Ke,"fillProfileProjectRepo");async function qe(e,t,n){return re({[t]:n}),await u(e,r=>{const{[t]:i,...o}=r.delivery_limits??{},s=n==="content"?o:{...o,[t]:n},{delivery_limits:f,...l}=r;return Object.keys(s).length===0?l:{...l,delivery_limits:s}})}a(qe,"setProfileDeliveryLimit");async function He(e,t){const n=M(t);let r=n;try{r=O(n)}catch{}return await u(e,o=>{const s=o.projects.filter(f=>f.path===void 0||f.path!==r&&f.path!==n);if(s.length===o.projects.length)throw d(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${o.projects.length>0?o.projects.map(f=>f.path??`repo ${f.repo}`).join(", "):"(none)"}.`});return{...o,projects:s}})}a(He,"removeProfileProject");async function We(e){H(e);const t=P(m(L(e).manifest),e);await w(n=>{if(!n.profiles.some(r=>r.profileId===e))throw d(`profile not found: ${e}`,{received:e});return[{op:"profile.delete",profileId:e}]}),R(t.dir,{recursive:!0,force:!0}),R(t.env,{force:!0})}a(We,"deleteProfile");export{v as ROOT_PROFILE_ID,Ue as addProfileProject,Fe as addProfileRepo,re as assertDeliveryLimits,Ce as assertProfileActive,ue as assertProfileEntryActive,S as assertProfileMetadata,_ as assertProfileProjects,q as createProfile,We as deleteProfile,Oe as ensureAppProfile,Se as ensureRootProfile,Ke as fillProfileProjectRepo,Me as isProfilePaused,h as listProfiles,L as loadExactProfileManifest,ae as loadProfileManifest,oe as lookupProfile,se as matchProfileOperand,F as metadataEnvName,Ne as pauseProfile,ke as pausedCanvasProfiles,be as profileDir,Je as readProfileMetadata,He as removeProfileProject,Te as renameProfile,Ae as resolveProfileOperand,De as resumeProfile,K as sanitizeProfileMetadata,Ee as setCloudProfileWriter,Le as setProfileDefaultKind,qe as setProfileDeliveryLimit,Re as updateProfileLastUsed,ze as updateProfileMetadata};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var A=Object.defineProperty;var
|
|
2
|
-
`);const{sysSigninLeaf:s}=await import("../../commands/sys/signin.js");try{await s.run({},{})}catch(a){process.stderr.write(`${a instanceof Error?a.message:String(a)}
|
|
3
|
-
`),process.exit(1)}}let
|
|
1
|
+
var A=Object.defineProperty;var p=(i,d)=>A(i,"name",{value:d,configurable:!0});import{existsSync as b,statSync as M}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as $}from"../../build-root.js";import{FRONT_DOOR_ENV as W}from"./front-door-env.js";import{frontDoorBootPrompt as B}from"./first-run-offer.js";import{readMachineConfig as P}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as V}from"./node-id-token.js";import{markTourOffered as G,recordSetupCompleted as U,setupCompleted as R,tourOfferPending as Y}from"./setup-marker.js";function T(i){try{return b(i)&&M(i).isDirectory()}catch{return!1}}p(T,"isDir");const j=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function J(){let i=!1;const d=p(()=>{i=!0},"onSigint");process.once("SIGINT",d);try{const{runSetup:r}=await import("../../commands/sys/setup-wizard.js"),e=await r();if(i){const l=new Error("Interrupted");throw l.name="AbortError",l}await U(e)}finally{process.removeListener("SIGINT",d)}}p(J,"runFirstSetup");function X(i){let d=process.cwd(),r,e,l,f=!1,u,g;const o=[];for(let c=0;c<i.length;c++){const n=i[c];if(n==="--name")r=i[++c];else if(n==="--kind")e=i[++c];else if(n==="--profile")l=i[++c];else if(n==="--pick-profile")f=!0;else if(n==="--continue"||n==="-c")u="continue";else if(n==="--resume"||n==="-r"){u="pick";const w=i[c+1];w!==void 0&&V(w)&&!T(h(w))&&(g=w,c++)}else n.startsWith("--")||o.push(n)}o.length>0&&T(h(o[0]))&&(d=h(o.shift()));const m=o.length>0?o.join(" "):void 0;return{cwd:d,prompt:m,name:r,kind:e,profile:l,pickProfile:f,resume:u,resumeId:g}}p(X,"parseRootArgs");import{FRONT_DOOR_ENV as ae}from"./front-door-env.js";async function oe(i){const d=i.slice(2),r=d[0];if(process.env[W]||r==="-h"||r==="--help"||r==="--version"||r==="-v"||r!==void 0&&$.includes(r))return!1;if(r!==void 0){const t=/\s/.test(r),s=!r.startsWith("-")&&T(h(r)),a=j.has(r);if(!t&&!s&&!a)return!1;if(s){const{buildRoot:D}=await import("../../build-root.js");if((await D()).subtrees.some(L=>L.name===r))return!1}}const e=X(d),l=p(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:t}=await import("../profiles/manifest.js");e.profile=t(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await l();const f=process.stdin.isTTY&&process.stdout.isTTY;if(P()===void 0){f||(process.stderr.write("crtr: this computer is not signed in to Northlight; run `crtr sys signin`.\n"),process.exit(1));const{hasLocalCanvas:t}=await import("../../daemon/machine-link/config.js");t()&&process.stderr.write(`This computer's crtr keeps its records locally. Local installs are ending; sign in to Northlight to move them into your account.
|
|
2
|
+
`);const{sysSigninLeaf:s}=await import("../../commands/sys/signin.js");try{await s.run({},{}),await(await import("../../commands/person-settings.js")).loadPersonSettingsViaApi()}catch(a){process.stderr.write(`${a instanceof Error?a.message:String(a)}
|
|
3
|
+
`),process.exit(1)}}let u=!1;const g=f&&!R()&&(await(await import("../../commands/api-client.js")).cliClient().getModelAuthReadiness({cwd:e.cwd})).hosted_endpoint;f&&!R()&&!g&&(await J(),u=!0);let o=null,m,c=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:t,noResumeTargetMessage:s}=await import("./resume-root.js"),a=await t(e.resumeId);"error"in a&&(process.stderr.write(`${a.error}
|
|
4
4
|
`),process.exit(1)),"none"in a?(e.resumeId.includes("-")&&(process.stderr.write(`${s(e.resumeId)}
|
|
5
|
-
`),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await l()):(o=a.node.profile_id,m=a.node.node_id,T(a.node.cwd)&&(c=a.node.cwd))}if(m===void 0){const{selectProfileForCwd:
|
|
5
|
+
`),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await l()):(o=a.node.profile_id,m=a.node.node_id,T(a.node.cwd)&&(c=a.node.cwd))}if(m===void 0){const{selectProfileForCwd:t,selectProfileForCwdReadOnly:s}=await import("../profiles/select.js");u&&e.profile===void 0&&process.stdout.write(`
|
|
6
6
|
Choose a profile
|
|
7
|
-
`),o=e.profile??(f?await
|
|
8
|
-
${
|
|
7
|
+
`),o=e.profile??(f?await t(e.cwd,void 0,e.pickProfile,!1):s(e.cwd))}const{cliClient:n}=await import("../../commands/api-client.js"),[{exitForMissingProviderCredential:w,hasConfiguredProviderCredential:k},v]=await Promise.all([import("./provider-credential-gate.js"),o===null?[]:n().listProfileEnv(o).then(t=>t.names)]),S=p(async()=>{const t=await n().getModelAuthReadiness({cwd:e.cwd,...o===null?{}:{profile:o}});return t.credential==="ready"||t.hosted_endpoint},"startable");if(!await k(v)&&!await S()){f||w();const{runFrontDoorLogin:t}=await import("./front-door-login.js");await t()||w()}const{inTmux:y}=await import("./placement-tmux.js");if(f&&!y()){const{TMUX_STARTED_ENV:t,handoffToTmux:s}=await import("./tmux-handoff.js");process.env[t]===void 0&&s(d,m!==void 0?null:o,c)}const[{bootRoot:N},{resumeRoot:C},{rendererWarning:O,missingPackageWarning:_,piAgentDir:x}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const t=_(x());t!==null&&process.stderr.write(`
|
|
8
|
+
${t}
|
|
9
9
|
|
|
10
10
|
`);const s=O();s!==null&&process.stderr.write(`
|
|
11
11
|
${s}
|
|
12
12
|
|
|
13
|
-
`)}catch{}if(m!==void 0){const{resumeNodeById:
|
|
13
|
+
`)}catch{}if(m!==void 0){const{resumeNodeById:t}=await import("./resume-root.js");await t(m)}if(e.resume!==void 0&&await C(e.cwd,e.resume==="pick")==="aborted")return!0;const I=f&&(u||await Y()),{prompt:E,initialWhip:F}=B({offerTour:I,signedIn:I&&P()!==void 0,userPrompt:e.prompt});return I&&y()&&await G(),await N({...e,prompt:E,initialWhip:F,selectedProfileId:o??void 0}),!0}p(oe,"maybeBootRoot");export{ae as FRONT_DOOR_ENV,oe as maybeBootRoot,X as parseRootArgs};
|
|
@@ -48,3 +48,5 @@ export declare const installIdPath: () => string;
|
|
|
48
48
|
export declare function readOrCreateInstallId(): string;
|
|
49
49
|
/** Whether this computer still holds a local canvas from before crtr was fleet-only (a supervised Postgres or a SQLite file). */
|
|
50
50
|
export declare const hasLocalCanvas: () => boolean;
|
|
51
|
+
/** A computer with no `machine.json`, no local records and no join registration has not been set up: it has no control plane to reach until `crtr sys signin`. */
|
|
52
|
+
export declare const computerIsUnset: () => boolean;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var l=Object.defineProperty;var
|
|
2
|
-
`)}
|
|
3
|
-
`,{mode:384}),y(t,384)}
|
|
4
|
-
`),t}
|
|
1
|
+
var l=Object.defineProperty;var e=(r,t)=>l(r,"name",{value:t,configurable:!0});import{chmodSync as y,existsSync as n,mkdirSync as a,readFileSync as c,rmSync as h,writeFileSync as s}from"node:fs";import{randomBytes as v}from"node:crypto";import{dirname as u,join as o}from"node:path";import{runtimeRoot as d,secretsDir as g}from"../../core/layout.js";import{joinedIssuer as x}from"../../core/directory/join.js";import{CrtrError as I}from"../../core/errors.js";import{atomicWriteJson as U}from"../../core/fs-utils.js";import{ExitCode as w}from"../../types.js";const p=e(()=>o(d(),"machine.json"),"machineConfigPath"),m=e(()=>o(g(),"machine-credential"),"machineCredentialPath");function C(){const r=p();if(!n(r))return;const t=JSON.parse(c(r,"utf8"));if(typeof t.apiUrl!="string"||typeof t.environmentId!="string"||t.runId!==void 0&&typeof t.runId!="string"||typeof t.directoryUrl!="string")throw new Error(`${r} must hold {apiUrl, environmentId, directoryUrl}`);const i=t.account!==void 0&&typeof t.account?.id=="string"&&typeof t.account.display=="string"?{id:t.account.id,display:t.account.display}:void 0;return{apiUrl:t.apiUrl,environmentId:t.environmentId,...t.runId===void 0?{}:{runId:t.runId},directoryUrl:t.directoryUrl,...i===void 0?{}:{account:i}}}e(C,"readMachineConfig");function A(r){a(u(p()),{recursive:!0}),s(p(),`${JSON.stringify(r,null,2)}
|
|
2
|
+
`)}e(A,"writeMachineConfig");function F(){const r=m();if(!n(r))throw new Error(`no machine credential at ${r}`);return c(r,"utf8").trim()}e(F,"readMachineCredential");function q(r){const t=m();a(u(t),{recursive:!0}),s(t,`${r}
|
|
3
|
+
`,{mode:384}),y(t,384)}e(q,"writeMachineCredential");const f=e(()=>o(d(),"import","move.json"),"moveRecordPath");function S(){const r=f();if(!n(r))return;const t=JSON.parse(c(r,"utf8"));if(typeof t.runId!="string"||typeof t.apiUrl!="string"||typeof t.directoryUrl!="string"||t.state!=="running"&&t.state!=="committed"&&t.state!=="activated"||typeof t.account?.id!="string"||typeof t.account.display!="string")throw new Error(`${r} is not a move record`);return{runId:t.runId,apiUrl:t.apiUrl,directoryUrl:t.directoryUrl,account:{id:t.account.id,display:t.account.display},notify:typeof t.notify=="string"?t.notify:null,state:t.state,notified:t.notified===!0,pid:typeof t.pid=="number"?t.pid:0}}e(S,"readMoveRecord");function z(r){U(f(),r,{mode:384})}e(z,"writeMoveRecord");function B(){h(f(),{force:!0})}e(B,"deleteMoveRecord");const D=e(()=>S()?.state==="committed","isMoveCommitted"),G=e(r=>new I("move_unfinished",`crtr's records are already in your Northlight account, but this computer has not switched over${r===void 0?".":`: ${r}`}`,w.USAGE,{next:"Run `crtr sys signin` to finish."}),"moveUnfinishedError"),M=e(()=>o(d(),"install-id"),"installIdPath");function L(){const r=M();if(n(r))return c(r,"utf8").trim();const t=Array.from(v(8),i=>"abcdefghijklmnopqrstuvwxyz0123456789"[i%36]).join("");return a(u(r),{recursive:!0}),s(r,`${t}
|
|
4
|
+
`),t}e(L,"readOrCreateInstallId");const $=e(()=>["pg","canvas.db","canvas.db.imported"].some(r=>n(o(d(),r))),"hasLocalCanvas"),W=e(()=>C()===void 0&&!$()&&x()===null,"computerIsUnset");export{W as computerIsUnset,B as deleteMoveRecord,$ as hasLocalCanvas,M as installIdPath,D as isMoveCommitted,p as machineConfigPath,m as machineCredentialPath,f as moveRecordPath,G as moveUnfinishedError,C as readMachineConfig,F as readMachineCredential,S as readMoveRecord,L as readOrCreateInstallId,A as writeMachineConfig,q as writeMachineCredential,z as writeMoveRecord};
|