@north-light/cli 0.3.737 → 0.3.739

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var D=Object.defineProperty;var p=(e,o)=>D(e,"name",{value:o,configurable:!0});import{envGrantee as q,envProfileId as x}from"../../shared/env.js";import{requiredPluginEnv as I}from"../../core/plugin-env.js";import{createHash as _}from"node:crypto";import{lstat as w,readFile as T,readdir as E,readlink as C}from"node:fs/promises";import{readFileSync as H}from"node:fs";import{dirname as b,isAbsolute as S,join as h,relative as L,resolve as j,sep as M}from"node:path";import{defineLeaf as B}from"../../core/command.js";import{normalizeRequires as G,readConfig as K,updateConfig as z}from"../../core/config.js";import{scopeRoot as A,listScopes as J,marketplacesDir as W,pluginsDir as V}from"../../core/scope.js";import{readMarketplaceManifest as U,readPluginManifest as Z}from"../../core/manifest.js";import{pathExists as $,listDirs as O,removePath as Q}from"../../core/fs-utils.js";import{lsRemote as X}from"../../core/git.js";import{cliClient as P}from"../api-client.js";import{detectNerdFont as Y,nerdFontInstallCommand as ee,NERD_FONT_SELECT_HINT as R}from"../../core/runtime/nerd-font.js";import{detectPackageManager as ne}from"./setup-core.js";import{validateEffectiveCommandPlugins as te}from"../../core/command-plugins/discovery.js";import{adaptPluginContributions as ie}from"../../core/command-plugins/compose.js";import{resolveCommandRegistry as oe}from"../../core/command-manifests/registry.js";import{applyCommandExtensions as ae,orphanCommandExtensionValidations as se}from"../../core/command-plugins/extensions.js";import{discoverHookRegistry as re}from"../../core/command-hooks/discovery.js";import{resolveBinContributions as ce}from"../../core/runtime/bin-contributions.js";import{inspectHumanActions as le}from"../../core/human-actions.js";import{composeAppProcessEnv as de,overlayBrokerEnv as ue,resolvePathExecutable as me}from"../../core/runtime/spawn-env.js";import{listAllPlugins as pe}from"../../core/resolver.js";import{SUBTREE_NAMES as fe,coreCommandPaths as he,coreHookCatalog as ge,extensibleCoreBranches as $e}from"../../build-root.js";import{processGeneration as ye,processLocatedGeneration as ve,runtimeManifest as y,selectedGeneration as ke}from"./shared.js";import{CONFIG_FILE as we}from"../../types.js";function f(e,o,i){return{scope:e,name:o,status:"pass",message:i}}p(f,"pass");function m(e,o,i,a){return{scope:e,name:o,status:"fail",message:i,...a?{remediation:a}:{}}}p(m,"failCheck");async function k(e){try{switch(e.kind){case"remove_config_key":{if(!e.scope||!e.configKey)return!1;const o=e.configKey.split(".");return await z(e.scope,i=>{let a=i;for(let r=0;r<o.length-1;r++){const n=a[o[r]];if(typeof n!="object"||n===null)return;a=n}delete a[o[o.length-1]]}),!0}case"rm_path":return e.path?(Q(e.path),!0):!1;case"human_action":return!1;default:return!1}}catch{return!1}}p(k,"applyRemediation");function be(e){return[`${e.link} ${e.kind}`,`disposition=${e.retry.disposition}`,typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`attempt=${e.retry.attempt}/${e.retry.max}`:void 0,typeof e.retry.nextAt=="string"?`nextAt=${e.retry.nextAt}`:void 0].filter(i=>i!==void 0).join(" \xB7 ")}p(be,"faultMessage");function N(e){return/^[A-Za-z0-9._:/@%+=,-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}p(N,"shellArgument");function xe(e,o){const i={connection:"restore connectivity","rate-limit":"wait for the rate limit to clear",overloaded:"wait for load to drop",auth:"re-authenticate",protocol:"fix the protocol mismatch","context-overflow":"shrink the task or loaded context, or choose a larger-context model before spawning the node again",other:"fix the underlying issue",wedged:"read `crtr canvas read wedged-child-on-runaway-bash` \u2014 if a runaway subprocess is to blame, kill it (not the node); if the broker had no subprocess, the daemon SIGTERM-kicks it and starts a fresh recovery cycle automatically","model-not-found":"pass a valid `--model provider/id` or configure credentials for an authenticated provider, then revive the node (`crtr node lifecycle revive <id>`)"},a=e.retry.disposition==="auto"?e.retry.by==="client"?"client redialing":typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`auto-retrying, attempt ${e.retry.attempt}/${e.retry.max}`:"auto-retrying":e.retry.disposition==="fatal"?"parked fatal":"manual",r=`crtr sys logs --node ${N(o)} --operation ${N(e.operation_id)}`;return{kind:"human_action",description:`${i[e.kind]}; ${a}; inspect the correlated operation with ${r}`,command:r}}p(xe,"faultRemediation");async function _e(e){const o=[],i=new Set(e),a=new Set(fe),[r,n]=await Promise.all([he(),$e()]),d=te(a,void 0,void 0,r,n);for(const l of d){const t=l.plugin;if(!i.has(t.scope))continue;const c=l.issues.filter(s=>s.code!=="command_collision");if(c.length===0){const s=l.contributions.map(u=>u.node.name).join(", ");o.push(f(t.scope,`plugin:${t.name}:commands`,s.length>0?`contributes top-level command(s): ${s}`:"command manifest valid"));continue}c.forEach((s,u)=>{const g={kind:"human_action",description:`${s.next} Inspect with \`pkg plugin show ${t.name}\`; then update (\`pkg plugin update --name ${t.name}\`) or remove (\`pkg plugin remove ${t.name}\`) the plugin.`},v=s.path!==void 0?` at ${s.path}`:"";o.push(m(t.scope,`plugin:${t.name}:commands[${u}]`,`${s.code}${v}: ${s.message} (received ${s.received}, expected ${s.expected})`,g))})}if(i.has("project")){const l=oe(ie(d.flatMap(s=>s.contributions)).contributions,a),c=[...ae(l.contributions).validations,...se(l.contributions)];for(const s of c){if(s.issue===void 0){o.push(f("project",`extension:${s.branch}`,`repository fragment valid: ${s.fragmentPath}`));continue}const u=s.issue;o.push(m("project",`extension:${s.branch}`,`${u.code} at ${u.path??s.fragmentPath}: ${u.message} (received ${u.received}, expected ${u.expected})`,{kind:"human_action",description:u.next}))}}return o}p(_e,"runCommandPluginChecks");async function Ee(e){const o=new Set(e),i=re(await ge()),a=[];for(const r of i.validations){const n=r.plugin;if(!o.has(n.scope))continue;const d=i.issues.filter(l=>l.plugin===n.name&&l.scope===n.scope);if(d.length===0){const l=r.hooks.map(c=>`${c.target} [${c.phase} ${c.op}]`),t=(r.manifest?.schemaVersion===2?r.manifest.lifecycle:[]).map(c=>`${c.event} [${c.phase} ${c.op}; effects: ${c.effects.join(", ")}]`);a.push(f(n.scope,`plugin:${n.name}:hooks`,`effective hook declaration(s): ${[...l,...t].join("; ")}`));continue}d.forEach((l,t)=>{const c=r.manifestPath??h(n.root,".crouter-plugin","plugin.json"),s=l.path!==void 0?`${c}:${l.path}`:c;a.push(m(n.scope,`plugin:${n.name}:hooks[${t}]`,`${l.code} at ${s}: ${l.message} (received ${l.received}, expected ${l.expected})`,{kind:"human_action",description:`${l.next} Inspect with \`crtr pkg plugin show ${n.name}\`; then disable (\`crtr pkg plugin disable ${n.name} --scope ${n.scope}\`), update (\`crtr pkg plugin update --name ${n.name}\`), or remove (\`crtr pkg plugin remove ${n.name}\`) the plugin.`}))})}return a}p(Ee,"runHookPluginChecks");function Ce(e){const o=new Set(e),{bins:i,issues:a}=ce(process.cwd(),x()||null),r=[];for(const n of a)o.has(n.scope)&&r.push(m(n.scope,`bin:${n.name}`,`${n.origin}: ${n.message}`,{kind:"human_action",description:`Fix the \`bin.${n.name}\` declaration in ${n.origin} \u2014 point it at an executable regular file inside that contributor's own root, or remove it. A same-precedence collision is resolved by renaming one of the claimants.`}));for(const n of i.values())o.has(n.scope)&&r.push(f(n.scope,`bin:${n.name}`,`${n.origin} \u2192 ${n.target}`));return r}p(Ce,"runBinContributionChecks");function Se(e){const o=new Set(e),i=h(A("user"),we),a=[],r=new Map;for(const n of le(process.cwd())){if("kind"in n){if(n.kind==="unknown_action")continue;const c=n.configOrigin===i?"user":"project",s=n.block===!0,u=s?void 0:r.get(n.name);if(!s&&u===void 0&&r.set(n.name,n.configOrigin),!o.has(c))continue;const g=s?`humanActions:block@${n.configOrigin}`:`humanActions:${n.name}@${n.configOrigin}`,v={kind:"human_action",description:s?`Fix or remove the \`humanActions\` block in ${n.configOrigin}. Actions run argv directly without a shell.`:`Fix or remove the \`humanActions.${n.name}\` declaration in ${n.configOrigin}. Actions run argv directly without a shell.`};u!==void 0?a.push({scope:c,name:g,status:"pass",message:`warning: shadowed by ${u}; ${n.configOrigin}: ${n.reason}`,remediation:v}):a.push(m(c,g,`${n.configOrigin}: ${n.reason}`,v));continue}const d=n.configOrigin===i?"user":"project",l=r.get(n.name);if(l===void 0&&r.set(n.name,n.configOrigin),!o.has(d))continue;const t=l===void 0?"":`shadowed by ${l}; `;a.push(f(d,`humanActions:${n.name}@${n.configOrigin}`,`${t}${n.configOrigin} \u2192 ${n.argv[0]} (cwd ${n.cwd})`))}return a}p(Se,"runHumanActionChecks");async function je(e){const o=new Set(e),i=x()??null,a=q()??"app:terminal",r=P(),n=p(t=>Object.fromEntries(t.map(c=>[c,""])),"present"),d=ue({argv:[],env:{CRTR_NODE_CWD:process.cwd(),CRTR_PROFILE_ID:i??"",CRTR_GRANTEE:a}},de(process.cwd(),i,a,n((await r.listAppEnv()).names),i===null?{}:n((await r.listProfileEnv(i)).names))),l=[];for(const t of pe())if(!(!o.has(t.scope)||!t.enabled)){for(const c of I(t.manifest.env))d[c]!==void 0?l.push(f(t.scope,`env:${c}`,`plugin "${t.name}" has ${c}`)):l.push(m(t.scope,`env:${c}`,`plugin "${t.name}" needs ${c}`,{kind:"human_action",description:`crtr sys env set --name ${c}`}));if(t.manifest.requires!==void 0)for(const[c,s]of Object.entries(G(t.manifest.requires))){const u=me(c,d,process.cwd());u!==null?l.push(f(t.scope,`requires:${c}`,`plugin "${t.name}" \u2192 ${u}`)):l.push(m(t.scope,`requires:${c}`,`plugin "${t.name}" requires executable "${c}" on PATH`,{kind:"human_action",description:s}))}}return l}p(je,"runRequiresChecks");async function Ae(e){const o=[];async function i(a){for(const r of await E(a)){const n=h(a,r),d=L(e,n).replaceAll(M,"/");if(d==="generation.json")continue;const l=await w(n);if(l.isDirectory())await i(n);else if(l.isFile()){const t=await T(n);o.push({path:d,size:l.size,sha256:_("sha256").update(t).digest("hex")})}else if(l.isSymbolicLink()){const t=await C(n);if(S(t)||!y.contained(e,j(b(n),t)))throw new Error(`generation symlink escapes root: ${d}`);o.push({path:d,size:Buffer.byteLength(t),sha256:_("sha256").update(t).digest("hex"),symlink:!0})}else throw new Error(`unsupported generation file: ${d}`)}}return p(i,"walk"),await i(e),y.sortInventory(o)}p(Ae,"inventory");async function Oe(e){async function o(i){const a=await w(i);if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`generation directory is invalid: ${i}`);if((a.mode&146)!==0)throw new Error(`generation path is writable: ${i}`);for(const r of await E(i)){const n=h(i,r),d=await w(n);if(d.isDirectory())await o(n);else if(d.isFile()){if((d.mode&146)!==0)throw new Error(`generation path is writable: ${n}`)}else if(d.isSymbolicLink()){const l=await C(n);if(S(l)||!y.contained(e,j(b(n),l)))throw new Error(`generation symlink escapes root: ${n}`)}else throw new Error(`unsupported generation file: ${n}`)}}p(o,"walk"),await o(e)}p(Oe,"verifySealed");function Pe(){const e=Y();if(e.installed)return f("user","terminal:nerd-font",`installed (${e.evidence}) \u2014 if icons still render as boxes, ${R}`);const o=ee(ne());return m("user","terminal:nerd-font","no Nerd Font installed \u2014 viewer tool/command icons will render as tofu boxes",{kind:"human_action",description:`Install a Nerd Font (${o.hint}), ${R}`,...o.command?{command:o.command}:{}})}p(Pe,"runNerdFontCheck");function Re(e,o){const i=`runtime:${e}:source`;let a;try{a=JSON.parse(H(h(b(o.root),`${o.id}.source.json`),"utf8"))}catch{return f("canvas",i,"not recorded (installed from a package, or before install sources were recorded)")}const r=`${a.branch??"?"} @ ${a.commit?.slice(0,9)??"?"} from ${a.checkout??"?"}${a.node?` by node ${a.node}`:""}, ${a.installedAt??""}`;return a.unlanded===void 0||a.unlanded.length===0?f("canvas",i,`origin/main: ${r}`):m("canvas",i,`unlanded code is installed (${a.unlanded.join("; ")}): ${r}. Land it and reinstall from origin/main.`)}p(Re,"installSourceCheck");async function F(e,o,i){if(o.generation===null){const d=o.error??"no runtime generation";return[i?f("canvas",`runtime:${e}`,d):m("canvas",`runtime:${e}`,d)]}const a=o.generation,r=[],n=y.validateManifestShape(a.manifest,{id:a.id,entryName:"cli"});if(!n.ok)return[m("canvas",`runtime:${e}:manifest`,n.error)];r.push(f("canvas",`runtime:${e}:manifest`,`${a.id} ${a.manifest.packageVersion}`)),r.push(Re(e,a));try{await Oe(a.root),r.push(f("canvas",`runtime:${e}:sealing`,"generation tree is sealed and contained"))}catch(d){r.push(m("canvas",`runtime:${e}:sealing`,d instanceof Error?d.message:String(d)))}try{const d=await Ae(a.root),l=y.sortInventory(a.manifest.files);JSON.stringify(a.manifest.files)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"manifest inventory is not in canonical runtime-generation-manifest order")):JSON.stringify(d)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"full generation inventory hash does not match generation.json")):r.push(f("canvas",`runtime:${e}:inventory`,`${d.length} files hash-verified`))}catch(d){r.push(m("canvas",`runtime:${e}:inventory`,d instanceof Error?d.message:String(d)))}return r}p(F,"generationChecks");async function Ne(){const e=[];for(const o of await P().listNodes()){const i=o.fault??null;if(i===null)continue;const a=`fault:${o.node_id}:${i.link}`,r=xe(i,o.node_id);e.push(m("canvas",a,be(i),r))}return e}p(Ne,"runFaultChecks");async function Fe(e,o){const i=[];if(!A(e))return i;const r=K(e),n=W(e);for(const t of Object.keys(r.marketplaces)){if(!n){i.push(m(e,`marketplace:${t}:dir`,"marketplaces directory unavailable"));continue}const c=h(n,t);if($(c))i.push(f(e,`marketplace:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.marketplaces.${t}`,scope:e,configKey:`marketplaces.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`marketplace:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`marketplace:${t}:dir`,`directory missing: ${c}`,s))}}const d=V(e);for(const t of Object.keys(r.plugins)){if(!d){i.push(m(e,`plugin:${t}:dir`,"plugins directory unavailable"));continue}const c=h(d,t);if($(c))i.push(f(e,`plugin:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.plugins.${t}`,scope:e,configKey:`plugins.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`plugin:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`plugin:${t}:dir`,`directory missing: ${c}`,s))}}if(n&&$(n))for(const t of O(n)){const c=h(n,t),s=U(c);if(s){i.push(f(e,`marketplace:${t}:manifest`,"manifest valid"));for(const u of s.plugins){if(u.source.startsWith("http://")||u.source.startsWith("https://")||u.source.startsWith("git@"))continue;const g=h(c,u.source);$(g)?i.push(f(e,`marketplace:${t}:plugin-source:${u.name}`,"source resolves")):i.push(m(e,`marketplace:${t}:plugin-source:${u.name}`,`source path does not resolve: ${g}`))}}else{const u={kind:"rm_path",description:"Remove dangling marketplace directory (no valid .crouter-marketplace/marketplace.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`marketplace:${t}:manifest`,status:"fail",message:"no valid marketplace.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`marketplace:${t}:manifest`,`no valid marketplace.json in ${c}`,u))}}const l=new Map;if(d&&$(d))for(const t of O(d)){const c=h(d,t),s=Z(c);if(!s){const u={kind:"rm_path",description:"Remove dangling plugin directory (no valid .crouter-plugin/plugin.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`plugin:${t}:manifest`,status:"fail",message:"no valid plugin.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`plugin:${t}:manifest`,`no valid plugin.json in ${c}`,u));continue}i.push(f(e,`plugin:${t}:manifest`,"manifest valid")),l.has(t)?i.push(m(e,`plugin:${t}:duplicate`,`duplicate plugin name within scope (also at ${l.get(t)})`)):l.set(t,c),o.remote&&s.source&&(X(s.source).status!==0?i.push(m(e,`plugin:${t}:remote`,`git remote unreachable: ${s.source}`)):i.push(f(e,`plugin:${t}:remote`,"git remote reachable")))}return i}p(Fe,"runChecksForScope");const dn=B({name:"doctor",description:"diagnose installation health",whenToUse:"something in your crtr install looks off and you want it diagnosed \u2014 a plugin or marketplace manifest is missing, a config entry points at a directory that no longer exists, or a plugin command/hook declaration is malformed. Reports each problem with a structured remediation, and can apply the safe repairs for you.",help:{name:"sys doctor",summary:"diagnose runtime integrity, missing manifests, and broken config entries",params:[{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Scope to check. Default: all scopes."},{kind:"flag",name:"fix",type:"bool",required:!1,constraint:"Apply each non-pass check's remediation and report what was fixed."},{kind:"flag",name:"remote",type:"bool",required:!1,constraint:"Check git remotes with ls-remote (slow \u2014 makes network calls)."}],output:[{name:"checks",type:"object[]",required:!0,constraint:"Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. humanActions:<name>@<config-origin> checks validate each user/project scope completion-action declaration: action-name and argv shape, cwd directory, argv[0] regular-file existence, and execute permission; they never execute an action. A malformed effective declaration fails; a malformed shadowed declaration is a pass-level warning that names the winning and shadowed origins. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer's icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/event/collision problems and carry disable/update/remove/show remediation; healthy command hooks list effective target, phase, and op, while lifecycle hooks list event, phase, op, and effects. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name."},{name:"ok",type:"boolean",required:!0,constraint:"True when no unresolved fail checks remain."}],outputKind:"object",effects:["Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, humanActions declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.","With --fix: applies each non-pass check's `remediation` \u2014 removes stale config entries and deletes dangling plugin/marketplace directories; canvas fault findings and plugin command/hook findings stay read-only (--fix never chmods or rewrites third-party plugin content).","Each non-pass result carries a structured `remediation` describing the fix action (absolute paths, exact config keys, or a human_action with its command) so callers can apply it directly without --fix."]},run:p(async e=>{const o=e.scope,i=e.fix,a=e.remote,r=J(o),n=[];for(const s of r){const u=await Fe(s,{fix:i,remote:a});n.push(...u)}r.includes("user")&&n.push(Pe()),n.push(...await _e(r)),n.push(...await Ee(r)),n.push(...Ce(r)),n.push(...Se(r)),n.push(...await je(r)),n.push(...await Ne());const d=ye();n.push(...await F("selected",ke(),d===null)),n.push(...await F("process",ve(),!0));const l={user:0,project:1,builtin:2,canvas:3};n.sort((s,u)=>s.scope!==u.scope?l[s.scope]-l[u.scope]:s.name.localeCompare(u.name));const t=!n.some(s=>s.status==="fail"&&s.fixed!==!0),c=n.filter(s=>s.status==="fail"&&s.fixed!==!0).length;return{checks:n,ok:t,failed:c}},"run")});export{_e as runCommandPluginChecks,dn as sysDoctorLeaf};
1
+ var D=Object.defineProperty;var p=(e,o)=>D(e,"name",{value:o,configurable:!0});import{envGrantee as q,envProfileId as x}from"../../shared/env.js";import{requiredPluginEnv as I}from"../../core/plugin-env.js";import{createHash as _}from"node:crypto";import{lstat as w,readFile as T,readdir as C,readlink as E}from"node:fs/promises";import{readFileSync as H}from"node:fs";import{dirname as b,isAbsolute as S,join as h,relative as L,resolve as j,sep as M}from"node:path";import{defineLeaf as B}from"../../core/command.js";import{normalizeRequires as G,readConfig as K,updateConfig as z}from"../../core/config.js";import{scopeRoot as A,listScopes as J,marketplacesDir as W,pluginsDir as V}from"../../core/scope.js";import{readMarketplaceManifest as U,readPluginManifest as Z}from"../../core/manifest.js";import{pathExists as $,listDirs as O,removePath as Q}from"../../core/fs-utils.js";import{lsRemote as X}from"../../core/git.js";import{cliClient as P}from"../api-client.js";import{detectNerdFont as Y,nerdFontInstallCommand as ee,NERD_FONT_SELECT_HINT as R}from"../../core/runtime/nerd-font.js";import{oldPackageInstalled as ne}from"./old-package.js";import{detectPackageManager as te}from"./setup-core.js";import{validateEffectiveCommandPlugins as ie}from"../../core/command-plugins/discovery.js";import{adaptPluginContributions as oe}from"../../core/command-plugins/compose.js";import{resolveCommandRegistry as ae}from"../../core/command-manifests/registry.js";import{applyCommandExtensions as se,orphanCommandExtensionValidations as re}from"../../core/command-plugins/extensions.js";import{discoverHookRegistry as ce}from"../../core/command-hooks/discovery.js";import{resolveBinContributions as le}from"../../core/runtime/bin-contributions.js";import{inspectHumanActions as de}from"../../core/human-actions.js";import{composeAppProcessEnv as ue,overlayBrokerEnv as me,resolvePathExecutable as pe}from"../../core/runtime/spawn-env.js";import{listAllPlugins as fe}from"../../core/resolver.js";import{SUBTREE_NAMES as he,coreCommandPaths as ge,coreHookCatalog as $e,extensibleCoreBranches as ye}from"../../build-root.js";import{processGeneration as ve,processLocatedGeneration as ke,runtimeManifest as y,selectedGeneration as we}from"./shared.js";import{CONFIG_FILE as be}from"../../types.js";function f(e,o,i){return{scope:e,name:o,status:"pass",message:i}}p(f,"pass");function m(e,o,i,a){return{scope:e,name:o,status:"fail",message:i,...a?{remediation:a}:{}}}p(m,"failCheck");async function k(e){try{switch(e.kind){case"remove_config_key":{if(!e.scope||!e.configKey)return!1;const o=e.configKey.split(".");return await z(e.scope,i=>{let a=i;for(let r=0;r<o.length-1;r++){const n=a[o[r]];if(typeof n!="object"||n===null)return;a=n}delete a[o[o.length-1]]}),!0}case"rm_path":return e.path?(Q(e.path),!0):!1;case"human_action":return!1;default:return!1}}catch{return!1}}p(k,"applyRemediation");function xe(e){return[`${e.link} ${e.kind}`,`disposition=${e.retry.disposition}`,typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`attempt=${e.retry.attempt}/${e.retry.max}`:void 0,typeof e.retry.nextAt=="string"?`nextAt=${e.retry.nextAt}`:void 0].filter(i=>i!==void 0).join(" \xB7 ")}p(xe,"faultMessage");function N(e){return/^[A-Za-z0-9._:/@%+=,-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}p(N,"shellArgument");function _e(e,o){const i={connection:"restore connectivity","rate-limit":"wait for the rate limit to clear",overloaded:"wait for load to drop",auth:"re-authenticate",protocol:"fix the protocol mismatch","context-overflow":"shrink the task or loaded context, or choose a larger-context model before spawning the node again",other:"fix the underlying issue",wedged:"read `crtr canvas read wedged-child-on-runaway-bash` \u2014 if a runaway subprocess is to blame, kill it (not the node); if the broker had no subprocess, the daemon SIGTERM-kicks it and starts a fresh recovery cycle automatically","model-not-found":"pass a valid `--model provider/id` or configure credentials for an authenticated provider, then revive the node (`crtr node lifecycle revive <id>`)"},a=e.retry.disposition==="auto"?e.retry.by==="client"?"client redialing":typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`auto-retrying, attempt ${e.retry.attempt}/${e.retry.max}`:"auto-retrying":e.retry.disposition==="fatal"?"parked fatal":"manual",r=`crtr sys logs --node ${N(o)} --operation ${N(e.operation_id)}`;return{kind:"human_action",description:`${i[e.kind]}; ${a}; inspect the correlated operation with ${r}`,command:r}}p(_e,"faultRemediation");async function Ce(e){const o=[],i=new Set(e),a=new Set(he),[r,n]=await Promise.all([ge(),ye()]),d=ie(a,void 0,void 0,r,n);for(const l of d){const t=l.plugin;if(!i.has(t.scope))continue;const c=l.issues.filter(s=>s.code!=="command_collision");if(c.length===0){const s=l.contributions.map(u=>u.node.name).join(", ");o.push(f(t.scope,`plugin:${t.name}:commands`,s.length>0?`contributes top-level command(s): ${s}`:"command manifest valid"));continue}c.forEach((s,u)=>{const g={kind:"human_action",description:`${s.next} Inspect with \`pkg plugin show ${t.name}\`; then update (\`pkg plugin update --name ${t.name}\`) or remove (\`pkg plugin remove ${t.name}\`) the plugin.`},v=s.path!==void 0?` at ${s.path}`:"";o.push(m(t.scope,`plugin:${t.name}:commands[${u}]`,`${s.code}${v}: ${s.message} (received ${s.received}, expected ${s.expected})`,g))})}if(i.has("project")){const l=ae(oe(d.flatMap(s=>s.contributions)).contributions,a),c=[...se(l.contributions).validations,...re(l.contributions)];for(const s of c){if(s.issue===void 0){o.push(f("project",`extension:${s.branch}`,`repository fragment valid: ${s.fragmentPath}`));continue}const u=s.issue;o.push(m("project",`extension:${s.branch}`,`${u.code} at ${u.path??s.fragmentPath}: ${u.message} (received ${u.received}, expected ${u.expected})`,{kind:"human_action",description:u.next}))}}return o}p(Ce,"runCommandPluginChecks");async function Ee(e){const o=new Set(e),i=ce(await $e()),a=[];for(const r of i.validations){const n=r.plugin;if(!o.has(n.scope))continue;const d=i.issues.filter(l=>l.plugin===n.name&&l.scope===n.scope);if(d.length===0){const l=r.hooks.map(c=>`${c.target} [${c.phase} ${c.op}]`),t=(r.manifest?.schemaVersion===2?r.manifest.lifecycle:[]).map(c=>`${c.event} [${c.phase} ${c.op}; effects: ${c.effects.join(", ")}]`);a.push(f(n.scope,`plugin:${n.name}:hooks`,`effective hook declaration(s): ${[...l,...t].join("; ")}`));continue}d.forEach((l,t)=>{const c=r.manifestPath??h(n.root,".crouter-plugin","plugin.json"),s=l.path!==void 0?`${c}:${l.path}`:c;a.push(m(n.scope,`plugin:${n.name}:hooks[${t}]`,`${l.code} at ${s}: ${l.message} (received ${l.received}, expected ${l.expected})`,{kind:"human_action",description:`${l.next} Inspect with \`crtr pkg plugin show ${n.name}\`; then disable (\`crtr pkg plugin disable ${n.name} --scope ${n.scope}\`), update (\`crtr pkg plugin update --name ${n.name}\`), or remove (\`crtr pkg plugin remove ${n.name}\`) the plugin.`}))})}return a}p(Ee,"runHookPluginChecks");function Se(e){const o=new Set(e),{bins:i,issues:a}=le(process.cwd(),x()||null),r=[];for(const n of a)o.has(n.scope)&&r.push(m(n.scope,`bin:${n.name}`,`${n.origin}: ${n.message}`,{kind:"human_action",description:`Fix the \`bin.${n.name}\` declaration in ${n.origin} \u2014 point it at an executable regular file inside that contributor's own root, or remove it. A same-precedence collision is resolved by renaming one of the claimants.`}));for(const n of i.values())o.has(n.scope)&&r.push(f(n.scope,`bin:${n.name}`,`${n.origin} \u2192 ${n.target}`));return r}p(Se,"runBinContributionChecks");function je(e){const o=new Set(e),i=h(A("user"),be),a=[],r=new Map;for(const n of de(process.cwd())){if("kind"in n){if(n.kind==="unknown_action")continue;const c=n.configOrigin===i?"user":"project",s=n.block===!0,u=s?void 0:r.get(n.name);if(!s&&u===void 0&&r.set(n.name,n.configOrigin),!o.has(c))continue;const g=s?`humanActions:block@${n.configOrigin}`:`humanActions:${n.name}@${n.configOrigin}`,v={kind:"human_action",description:s?`Fix or remove the \`humanActions\` block in ${n.configOrigin}. Actions run argv directly without a shell.`:`Fix or remove the \`humanActions.${n.name}\` declaration in ${n.configOrigin}. Actions run argv directly without a shell.`};u!==void 0?a.push({scope:c,name:g,status:"pass",message:`warning: shadowed by ${u}; ${n.configOrigin}: ${n.reason}`,remediation:v}):a.push(m(c,g,`${n.configOrigin}: ${n.reason}`,v));continue}const d=n.configOrigin===i?"user":"project",l=r.get(n.name);if(l===void 0&&r.set(n.name,n.configOrigin),!o.has(d))continue;const t=l===void 0?"":`shadowed by ${l}; `;a.push(f(d,`humanActions:${n.name}@${n.configOrigin}`,`${t}${n.configOrigin} \u2192 ${n.argv[0]} (cwd ${n.cwd})`))}return a}p(je,"runHumanActionChecks");async function Ae(e){const o=new Set(e),i=x()??null,a=q()??"app:terminal",r=P(),n=p(t=>Object.fromEntries(t.map(c=>[c,""])),"present"),d=me({argv:[],env:{CRTR_NODE_CWD:process.cwd(),CRTR_PROFILE_ID:i??"",CRTR_GRANTEE:a}},ue(process.cwd(),i,a,n((await r.listAppEnv()).names),i===null?{}:n((await r.listProfileEnv(i)).names))),l=[];for(const t of fe())if(!(!o.has(t.scope)||!t.enabled)){for(const c of I(t.manifest.env))d[c]!==void 0?l.push(f(t.scope,`env:${c}`,`plugin "${t.name}" has ${c}`)):l.push(m(t.scope,`env:${c}`,`plugin "${t.name}" needs ${c}`,{kind:"human_action",description:`crtr sys env set --name ${c}`}));if(t.manifest.requires!==void 0)for(const[c,s]of Object.entries(G(t.manifest.requires))){const u=pe(c,d,process.cwd());u!==null?l.push(f(t.scope,`requires:${c}`,`plugin "${t.name}" \u2192 ${u}`)):l.push(m(t.scope,`requires:${c}`,`plugin "${t.name}" requires executable "${c}" on PATH`,{kind:"human_action",description:s}))}}return l}p(Ae,"runRequiresChecks");async function Oe(e){const o=[];async function i(a){for(const r of await C(a)){const n=h(a,r),d=L(e,n).replaceAll(M,"/");if(d==="generation.json")continue;const l=await w(n);if(l.isDirectory())await i(n);else if(l.isFile()){const t=await T(n);o.push({path:d,size:l.size,sha256:_("sha256").update(t).digest("hex")})}else if(l.isSymbolicLink()){const t=await E(n);if(S(t)||!y.contained(e,j(b(n),t)))throw new Error(`generation symlink escapes root: ${d}`);o.push({path:d,size:Buffer.byteLength(t),sha256:_("sha256").update(t).digest("hex"),symlink:!0})}else throw new Error(`unsupported generation file: ${d}`)}}return p(i,"walk"),await i(e),y.sortInventory(o)}p(Oe,"inventory");async function Pe(e){async function o(i){const a=await w(i);if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`generation directory is invalid: ${i}`);if((a.mode&146)!==0)throw new Error(`generation path is writable: ${i}`);for(const r of await C(i)){const n=h(i,r),d=await w(n);if(d.isDirectory())await o(n);else if(d.isFile()){if((d.mode&146)!==0)throw new Error(`generation path is writable: ${n}`)}else if(d.isSymbolicLink()){const l=await E(n);if(S(l)||!y.contained(e,j(b(n),l)))throw new Error(`generation symlink escapes root: ${n}`)}else throw new Error(`unsupported generation file: ${n}`)}}p(o,"walk"),await o(e)}p(Pe,"verifySealed");function Re(){const e=Y();if(e.installed)return f("user","terminal:nerd-font",`installed (${e.evidence}) \u2014 if icons still render as boxes, ${R}`);const o=ee(te());return m("user","terminal:nerd-font","no Nerd Font installed \u2014 viewer tool/command icons will render as tofu boxes",{kind:"human_action",description:`Install a Nerd Font (${o.hint}), ${R}`,...o.command?{command:o.command}:{}})}p(Re,"runNerdFontCheck");function Ne(){const e=ne();return e===void 0?f("canvas","package:old-crouter","the old @crouton-kit/crouter package is not installed"):m("canvas","package:old-crouter",e.message,{kind:"human_action",description:"Remove the old package, then reinstall this one",command:`${e.uninstall} && npm i -g @north-light/cli@latest`})}p(Ne,"oldPackageCheck");function Fe(e,o){const i=`runtime:${e}:source`;let a;try{a=JSON.parse(H(h(b(o.root),`${o.id}.source.json`),"utf8"))}catch{return f("canvas",i,"not recorded (installed from a package, or before install sources were recorded)")}const r=`${a.branch??"?"} @ ${a.commit?.slice(0,9)??"?"} from ${a.checkout??"?"}${a.node?` by node ${a.node}`:""}, ${a.installedAt??""}`;return a.unlanded===void 0||a.unlanded.length===0?f("canvas",i,`origin/main: ${r}`):m("canvas",i,`unlanded code is installed (${a.unlanded.join("; ")}): ${r}. Land it and reinstall from origin/main.`)}p(Fe,"installSourceCheck");async function F(e,o,i){if(o.generation===null){const d=o.error??"no runtime generation";return[i?f("canvas",`runtime:${e}`,d):m("canvas",`runtime:${e}`,d)]}const a=o.generation,r=[],n=y.validateManifestShape(a.manifest,{id:a.id,entryName:"cli"});if(!n.ok)return[m("canvas",`runtime:${e}:manifest`,n.error)];r.push(f("canvas",`runtime:${e}:manifest`,`${a.id} ${a.manifest.packageVersion}`)),r.push(Fe(e,a));try{await Pe(a.root),r.push(f("canvas",`runtime:${e}:sealing`,"generation tree is sealed and contained"))}catch(d){r.push(m("canvas",`runtime:${e}:sealing`,d instanceof Error?d.message:String(d)))}try{const d=await Oe(a.root),l=y.sortInventory(a.manifest.files);JSON.stringify(a.manifest.files)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"manifest inventory is not in canonical runtime-generation-manifest order")):JSON.stringify(d)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"full generation inventory hash does not match generation.json")):r.push(f("canvas",`runtime:${e}:inventory`,`${d.length} files hash-verified`))}catch(d){r.push(m("canvas",`runtime:${e}:inventory`,d instanceof Error?d.message:String(d)))}return r}p(F,"generationChecks");async function De(){const e=[];for(const o of await P().listNodes()){const i=o.fault??null;if(i===null)continue;const a=`fault:${o.node_id}:${i.link}`,r=_e(i,o.node_id);e.push(m("canvas",a,xe(i),r))}return e}p(De,"runFaultChecks");async function qe(e,o){const i=[];if(!A(e))return i;const r=K(e),n=W(e);for(const t of Object.keys(r.marketplaces)){if(!n){i.push(m(e,`marketplace:${t}:dir`,"marketplaces directory unavailable"));continue}const c=h(n,t);if($(c))i.push(f(e,`marketplace:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.marketplaces.${t}`,scope:e,configKey:`marketplaces.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`marketplace:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`marketplace:${t}:dir`,`directory missing: ${c}`,s))}}const d=V(e);for(const t of Object.keys(r.plugins)){if(!d){i.push(m(e,`plugin:${t}:dir`,"plugins directory unavailable"));continue}const c=h(d,t);if($(c))i.push(f(e,`plugin:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.plugins.${t}`,scope:e,configKey:`plugins.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`plugin:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`plugin:${t}:dir`,`directory missing: ${c}`,s))}}if(n&&$(n))for(const t of O(n)){const c=h(n,t),s=U(c);if(s){i.push(f(e,`marketplace:${t}:manifest`,"manifest valid"));for(const u of s.plugins){if(u.source.startsWith("http://")||u.source.startsWith("https://")||u.source.startsWith("git@"))continue;const g=h(c,u.source);$(g)?i.push(f(e,`marketplace:${t}:plugin-source:${u.name}`,"source resolves")):i.push(m(e,`marketplace:${t}:plugin-source:${u.name}`,`source path does not resolve: ${g}`))}}else{const u={kind:"rm_path",description:"Remove dangling marketplace directory (no valid .crouter-marketplace/marketplace.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`marketplace:${t}:manifest`,status:"fail",message:"no valid marketplace.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`marketplace:${t}:manifest`,`no valid marketplace.json in ${c}`,u))}}const l=new Map;if(d&&$(d))for(const t of O(d)){const c=h(d,t),s=Z(c);if(!s){const u={kind:"rm_path",description:"Remove dangling plugin directory (no valid .crouter-plugin/plugin.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`plugin:${t}:manifest`,status:"fail",message:"no valid plugin.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`plugin:${t}:manifest`,`no valid plugin.json in ${c}`,u));continue}i.push(f(e,`plugin:${t}:manifest`,"manifest valid")),l.has(t)?i.push(m(e,`plugin:${t}:duplicate`,`duplicate plugin name within scope (also at ${l.get(t)})`)):l.set(t,c),o.remote&&s.source&&(X(s.source).status!==0?i.push(m(e,`plugin:${t}:remote`,`git remote unreachable: ${s.source}`)):i.push(f(e,`plugin:${t}:remote`,"git remote reachable")))}return i}p(qe,"runChecksForScope");const pn=B({name:"doctor",description:"diagnose installation health",whenToUse:"something in your crtr install looks off and you want it diagnosed \u2014 a plugin or marketplace manifest is missing, a config entry points at a directory that no longer exists, or a plugin command/hook declaration is malformed. Reports each problem with a structured remediation, and can apply the safe repairs for you.",help:{name:"sys doctor",summary:"diagnose runtime integrity, missing manifests, and broken config entries",params:[{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Scope to check. Default: all scopes."},{kind:"flag",name:"fix",type:"bool",required:!1,constraint:"Apply each non-pass check's remediation and report what was fixed."},{kind:"flag",name:"remote",type:"bool",required:!1,constraint:"Check git remotes with ls-remote (slow \u2014 makes network calls)."}],output:[{name:"checks",type:"object[]",required:!0,constraint:"Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. humanActions:<name>@<config-origin> checks validate each user/project scope completion-action declaration: action-name and argv shape, cwd directory, argv[0] regular-file existence, and execute permission; they never execute an action. A malformed effective declaration fails; a malformed shadowed declaration is a pass-level warning that names the winning and shadowed origins. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer's icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/event/collision problems and carry disable/update/remove/show remediation; healthy command hooks list effective target, phase, and op, while lifecycle hooks list event, phase, op, and effects. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name."},{name:"ok",type:"boolean",required:!0,constraint:"True when no unresolved fail checks remain."}],outputKind:"object",effects:["Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, humanActions declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.","With --fix: applies each non-pass check's `remediation` \u2014 removes stale config entries and deletes dangling plugin/marketplace directories; canvas fault findings and plugin command/hook findings stay read-only (--fix never chmods or rewrites third-party plugin content).","Each non-pass result carries a structured `remediation` describing the fix action (absolute paths, exact config keys, or a human_action with its command) so callers can apply it directly without --fix."]},run:p(async e=>{const o=e.scope,i=e.fix,a=e.remote,r=J(o),n=[];for(const s of r){const u=await qe(s,{fix:i,remote:a});n.push(...u)}r.includes("user")&&n.push(Re()),n.push(...await Ce(r)),n.push(...await Ee(r)),n.push(...Se(r)),n.push(...je(r)),n.push(...await Ae(r)),n.push(Ne()),n.push(...await De());const d=ve();n.push(...await F("selected",we(),d===null)),n.push(...await F("process",ke(),!0));const l={user:0,project:1,builtin:2,canvas:3};n.sort((s,u)=>s.scope!==u.scope?l[s.scope]-l[u.scope]:s.name.localeCompare(u.name));const t=!n.some(s=>s.status==="fail"&&s.fixed!==!0),c=n.filter(s=>s.status==="fail"&&s.fixed!==!0).length;return{checks:n,ok:t,failed:c}},"run")});export{Ce as runCommandPluginChecks,pn as sysDoctorLeaf};
@@ -0,0 +1,9 @@
1
+ export declare const OLD_PACKAGE = "@crouton-kit/crouter";
2
+ export declare const OLD_PACKAGE_UNINSTALL = "npm uninstall -g @crouton-kit/crouter";
3
+ /** Where a global install of this package sits beside the old one: `<lib>/node_modules/@north-light/cli` → `<lib>/node_modules/@crouton-kit/crouter`. */
4
+ export declare function oldPackageDir(packageRoot: string): string | undefined;
5
+ /** The old package installed next to this one, with the message that names the command that removes it; undefined when it is absent. */
6
+ export declare function oldPackageInstalled(packageRoot?: string): {
7
+ uninstall: string;
8
+ message: string;
9
+ } | undefined;
@@ -0,0 +1 @@
1
+ var a=Object.defineProperty;var e=(t,n)=>a(t,"name",{value:n,configurable:!0});import{existsSync as d}from"node:fs";import{dirname as c,join as o,sep as r}from"node:path";import{fileURLToPath as m}from"node:url";const i="@crouton-kit/crouter",s=`npm uninstall -g ${i}`;function u(t){const n=`${r}node_modules${r}@north-light${r}cli`,l=t.lastIndexOf(n);return l<0?void 0:o(t.slice(0,l),"node_modules",i)}e(u,"oldPackageDir");function $(t=o(c(m(import.meta.url)),"..","..","..")){const n=u(t);if(!(n===void 0||!d(o(n,"package.json"))))return{uninstall:s,message:`The old ${i} package is still installed at ${n} and owns the \`crtr\` command. Run \`${s}\`, then \`npm i -g @north-light/cli@latest\`.`}}e($,"oldPackageInstalled");export{i as OLD_PACKAGE,s as OLD_PACKAGE_UNINSTALL,u as oldPackageDir,$ as oldPackageInstalled};
@@ -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 T(e,t){return q("sh",["-lc",e],t)}a(T,"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 T("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(`
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=M(),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(M()),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(m){e(d.name,m)}}}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 T(p);const te=Se();return T(p,ne=>{const O=te(ne);O!==null&&N.setFraction(O/100)})}),o.push(i.tool)}const d=[];let m=!1,f;try{f=J(()=>{m=!0,c.start("termrender renderer")},i=>d.push(i))}catch(i){throw m&&await c.fail("termrender renderer",i),i}switch(f){case"provisioned":m&&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(""));m&&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,M as resolveSettingsPath,Pt as setupPluginEnvFields};
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,2 +1,3 @@
1
- var A=Object.defineProperty;var i=(e,n)=>A(e,"name",{value:n,configurable:!0});import{spawn as f}from"node:child_process";import{mkdirSync as O,openSync as R}from"node:fs";import{dirname as w,join as P}from"node:path";import{defineLeaf as v}from"../../core/command.js";import{CrtrError as a}from"../../core/errors.js";import{controlPlaneUrl as U,personAccount as y,personBearer as k,readPersonCredential as _,signIn as u,signOut as C}from"../../core/directory/person-credential.js";import{hasLocalCanvas as x,moveRecordPath as I,readMachineConfig as b,readOrCreateInstallId as L,writeMachineConfig as D,writeMachineCredential as M}from"../../daemon/machine-link/config.js";import{probeDaemonHealth as j,sanitizedDaemonEnv as q,spawnDaemon as m,stopAllDaemons as l}from"../../daemon/manage.js";import{hostname as G}from"node:os";import{northlightUnreachable as g}from"../../core/directory/reach.js";import{envNodeId as B}from"../../shared/env.js";import{ExitCode as c}from"../../types.js";import{insideBroker as T}from"./join.js";import{defaultDirectoryUrl as F,finishMove as z,registerThisMac as N,runMove as H,settleEarlierMove as K}from"./import/move.js";import{WAIT_FOR_PID_ENV as J}from"./import/start.js";function V(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{f(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}i(V,"openBrowser");function h(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
- `),V(e.complete)}i(h,"showSignIn");function W(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 g(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(W,"sameAccountOnly");function E(e){const n=P(w(I()),"move.log");O(w(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[J]=String(process.pid);const s=[...process.execArgv,process.argv[1],"sys","import","start","--kind","machine",...e===void 0?[]:["--notify",e]];f(process.execPath,s,{detached:!0,stdio:["ignore",t,t],env:r}).unref()}i(E,"startDetachedMove");async function Q(e){const n=_()===void 0?(await u(e,h),await y(e)):await y(e),t=await U(e),r=await k(e),s=i(async S=>{try{return await fetch(new URL(`/v1/machines${S?"?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($){throw g($,t)}},"post");let o=await s(!1);o.status===409&&(await o.clone().text()).includes("credential_exists")&&(o=await s(!0));const p=await o.text();if(!o.ok)throw new a("machine_registration_failed",`Northlight refused to register this computer (HTTP ${o.status}): ${p.slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signin` again."});const d=JSON.parse(p);if(typeof d.credential!="string"||typeof d.environment_id!="string")throw new a("machine_registration_failed","Northlight answered without a credential",c.GENERAL);return M(d.credential),D({apiUrl:t,environmentId:d.environment_id,directoryUrl:e,account:n}),await N(e),await l(),await m(),{account:n.display}}i(Q,"registerFreshComputer");const X=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"),fe=v({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.","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=>{const n=e.directoryUrl===void 0?F():String(e.directoryUrl),t=await K(h);if(t!==void 0)return T()?(E(void 0),{account:t.account.display,moving:!0}):(await z(t),{account:t.account.display,moved:!0});const r=b();if(r!==void 0){const{account:o}=await u(n,h,{accept:W(r)});return await N(n),await l(),await m(),{account:o}}if(!x())return await Q(n);const{account:s}=await u(n,h);return T()?(E(B()),{account:s,moving:!0}):(await H({directoryUrl:n,notify:null}),{account:s,moved:!0})},"run"),render:i(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${X(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function Y(){return await l(),await m(),(await j()).signed_in===!1}i(Y,"stopMovedComputer");async function Z(e){if(_()===void 0)return;const n=await k(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 g(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(Z,"revokeMachine");const we=v({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=b();e!==void 0&&await Z(e);const{signedOut:n,revoked:t}=await C(),r=e===void 0?!1:await Y();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{Q as registerFreshComputer,h as showSignIn,fe as sysSigninLeaf,we as sysSignoutLeaf};
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};
@@ -1,7 +1,10 @@
1
+ import { CrtrError } from '../../errors.js';
1
2
  import type { ImportRunDTO, ImportStartRequest, ImportStartedDTO, ImportStoreNameDTO, ImportUploadUrlsDTO } from '../../../api/dto/imports.js';
2
3
  /** The dump directory's file holding the opened file stores, and the order they are uploaded in. */
3
4
  export declare const STORE_FILE = "stores.json";
4
5
  export declare const STORE_ORDER: readonly ImportStoreNameDTO[];
6
+ /** The control plane refuses a source that runs another release than its own: name the release it accepts and the command that installs it. */
7
+ export declare function releaseMismatch(accepted: string, status: number): CrtrError;
5
8
  export declare class ImportCloud {
6
9
  private readonly apiUrl;
7
10
  private readonly token;
@@ -1 +1 @@
1
- var _=Object.defineProperty;var f=(o,t)=>_(o,"name",{value:t,configurable:!0});import{CrtrError as T,general as d}from"../../errors.js";import{NORTHLIGHT_UNREACHABLE as O}from"../../directory/reach.js";const x="stores.json",I=["auth","credentials","env","settings","plugins"],B=10*6e4,R=3e4,U=6e4,y=64*1024,S=f(o=>o===408||o===429||o>=500,"isTransientStatus");function M(o){const t=o.cause;return`failed: ${o instanceof Error?o.message:String(o)}${typeof t?.code=="string"?` (${t.code})`:""}`}f(M,"failureText");class C{static{f(this,"ImportCloud")}apiUrl;token;retryBaseMs;putIdleMs;retryBudgetMs;constructor(t,e,r=500,l=U,a=B){this.apiUrl=t,this.token=e,this.retryBaseMs=r,this.putIdleMs=l,this.retryBudgetMs=a}async backoff(t,e){return Date.now()-e>=this.retryBudgetMs?!1:(await new Promise(r=>setTimeout(r,Math.min(this.retryBaseMs*2**(t-1),R)*(.5+Math.random()/2))),!0)}async call(t,e,r,l=!1){let a;for(let i=1;;i+=1)try{return await this.callOnce(t,e,r,l)}catch(n){const s=n instanceof T?n.details?.status:void 0,u=n instanceof T&&(n.code===O||n.details?.network===!0||typeof s=="number"&&S(s));if(!l||!u||(a??=Date.now(),!await this.backoff(i,a)))throw n}}async callOnce(t,e,r,l){let a,i;const n=`Bearer ${typeof this.token=="string"?this.token:await this.token()}`;try{i=await fetch(new URL(e,this.apiUrl),{method:t,headers:{authorization:n,...r===void 0?{}:{"content-type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},...l?{signal:AbortSignal.timeout(this.putIdleMs)}:{}}),a=await i.text()}catch(s){throw d(`${t} ${e} ${M(s)}`,{network:!0})}if(!i.ok){let s;try{s=JSON.parse(a).error?.code}catch{s=void 0}throw d(`${t} ${e} answered ${i.status}: ${a.slice(0,500)}`,{status:i.status,...typeof s=="string"?{code:s}:{}})}return a===""?void 0:JSON.parse(a)}start(t){return this.call("POST","/v1/imports",t)}uploadUrls(t,e){return this.call("POST",`/v1/imports/${t}/upload-urls`,{keys:e},!0)}putStore(t,e,r){return this.call("PUT",`/v1/imports/${t}/stores/${e}`,r,!0)}load(t){return this.call("POST",`/v1/imports/${t}/load`,{})}get(t){return this.call("GET",`/v1/imports/${t}`)}machineCredential(t,e=!1){return this.call("POST",`/v1/imports/${t}/machine-credential${e?"?rotate=1":""}`,{})}async put(t,e,r,l){let a=!1,i;for(let n=1;;n+=1){let s,u;const $=new AbortController;let p;const w=f(()=>{clearTimeout(p),p=setTimeout(()=>$.abort(new Error(`no progress for ${Math.round(this.putIdleMs/1e3)}s`)),this.putIdleMs)},"arm");let h=0;const E=new ReadableStream({pull(c){if(w(),h>=e.length){c.close();return}c.enqueue(e.subarray(h,h+y)),h+=y}},{highWaterMark:0});try{w();const c=await fetch(t,{method:"PUT",headers:{"content-length":String(e.length)},body:E,duplex:"half",signal:$.signal});if(w(),c.ok){await c.arrayBuffer();return}const m=c.status;let g="";try{g=(await c.text()).slice(0,300)}catch{}if(s=`answered ${m}: ${g}`,m===403&&l!==void 0&&!a){a=!0,t=await l();continue}u=S(m)}catch(c){s=M(c),u=!0}finally{clearTimeout(p)}if(!u)throw d(`upload of ${r} ${s}`,{key:r});if(i??=Date.now(),!await this.backoff(n,i))throw d(`upload of ${r} ${s} after ${n} tries`,{key:r})}}}export{C as ImportCloud,x as STORE_FILE,I as STORE_ORDER};
1
+ var _=Object.defineProperty;var h=(s,t)=>_(s,"name",{value:t,configurable:!0});import{CrtrError as $,general as d}from"../../errors.js";import{ExitCode as O}from"../../../types.js";import{crtrVersion as R}from"../../../shared/crtr-version.js";import{NORTHLIGHT_UNREACHABLE as x}from"../../directory/reach.js";const v="stores.json",D=["auth","credentials","env","settings","plugins"],B=10*6e4,U=3e4,b=6e4,T=64*1024,S=h(s=>s===408||s===429||s>=500,"isTransientStatus");function M(s){const t=s.cause;return`failed: ${s instanceof Error?s.message:String(s)}${typeof t?.code=="string"?` (${t.code})`:""}`}h(M,"failureText");function k(s,t){const e=`npm i -g @north-light/cli@${s}`;return new $("release_mismatch",`Northlight accepts only crtr ${s} for this step, and this computer runs ${R()}. Install it with \`${e}\`, then run \`crtr sys signin\` again.`,O.GENERAL,{status:t,code:"release_mismatch",accepted:s,next:`Run \`${e}\`, then \`crtr sys signin\`.`})}h(k,"releaseMismatch");class L{static{h(this,"ImportCloud")}apiUrl;token;retryBaseMs;putIdleMs;retryBudgetMs;constructor(t,e,r=500,c=b,a=B){this.apiUrl=t,this.token=e,this.retryBaseMs=r,this.putIdleMs=c,this.retryBudgetMs=a}async backoff(t,e){return Date.now()-e>=this.retryBudgetMs?!1:(await new Promise(r=>setTimeout(r,Math.min(this.retryBaseMs*2**(t-1),U)*(.5+Math.random()/2))),!0)}async call(t,e,r,c=!1){let a;for(let o=1;;o+=1)try{return await this.callOnce(t,e,r,c)}catch(i){const n=i instanceof $?i.details?.status:void 0,u=i instanceof $&&(i.code===x||i.details?.network===!0||typeof n=="number"&&S(n));if(!c||!u||(a??=Date.now(),!await this.backoff(o,a)))throw i}}async callOnce(t,e,r,c){let a,o;const i=`Bearer ${typeof this.token=="string"?this.token:await this.token()}`;try{o=await fetch(new URL(e,this.apiUrl),{method:t,headers:{authorization:i,...r===void 0?{}:{"content-type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},...c?{signal:AbortSignal.timeout(this.putIdleMs)}:{}}),a=await o.text()}catch(n){throw d(`${t} ${e} ${M(n)}`,{network:!0})}if(!o.ok){let n;try{n=JSON.parse(a).error?.code}catch{n=void 0}const u=n==="release_mismatch"?/control plane accepts (\S+)/.exec(a)?.[1]?.replace(/[^0-9A-Za-z.+-]+$/,""):void 0;throw u!==void 0?k(u,o.status):d(`${t} ${e} answered ${o.status}: ${a.slice(0,500)}`,{status:o.status,...typeof n=="string"?{code:n}:{}})}return a===""?void 0:JSON.parse(a)}start(t){return this.call("POST","/v1/imports",t)}uploadUrls(t,e){return this.call("POST",`/v1/imports/${t}/upload-urls`,{keys:e},!0)}putStore(t,e,r){return this.call("PUT",`/v1/imports/${t}/stores/${e}`,r,!0)}load(t){return this.call("POST",`/v1/imports/${t}/load`,{})}get(t){return this.call("GET",`/v1/imports/${t}`)}machineCredential(t,e=!1){return this.call("POST",`/v1/imports/${t}/machine-credential${e?"?rotate=1":""}`,{})}async put(t,e,r,c){let a=!1,o;for(let i=1;;i+=1){let n,u;const g=new AbortController;let p;const m=h(()=>{clearTimeout(p),p=setTimeout(()=>g.abort(new Error(`no progress for ${Math.round(this.putIdleMs/1e3)}s`)),this.putIdleMs)},"arm");let f=0;const E=new ReadableStream({pull(l){if(m(),f>=e.length){l.close();return}l.enqueue(e.subarray(f,f+T)),f+=T}},{highWaterMark:0});try{m();const l=await fetch(t,{method:"PUT",headers:{"content-length":String(e.length)},body:E,duplex:"half",signal:g.signal});if(m(),l.ok){await l.arrayBuffer();return}const w=l.status;let y="";try{y=(await l.text()).slice(0,300)}catch{}if(n=`answered ${w}: ${y}`,w===403&&c!==void 0&&!a){a=!0,t=await c();continue}u=S(w)}catch(l){n=M(l),u=!0}finally{clearTimeout(p)}if(!u)throw d(`upload of ${r} ${n}`,{key:r});if(o??=Date.now(),!await this.backoff(i,o))throw d(`upload of ${r} ${n} after ${i} tries`,{key:r})}}}export{L as ImportCloud,v as STORE_FILE,D as STORE_ORDER,k as releaseMismatch};
@@ -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 u=(i,d)=>A(i,"name",{value:d,configurable:!0});import{existsSync as b,statSync as M}from"node:fs";import{resolve as g}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 R}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as G}from"./node-id-token.js";import{markTourOffered as V,recordSetupCompleted as U,setupCompleted as P,tourOfferPending as Y}from"./setup-marker.js";function T(i){try{return b(i)&&M(i).isDirectory()}catch{return!1}}u(T,"isDir");const j=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function J(){let i=!1;const d=u(()=>{i=!0},"onSigint");process.once("SIGINT",d);try{const{runSetup:t}=await import("../../commands/sys/setup-wizard.js"),e=await t();if(i){const l=new Error("Interrupted");throw l.name="AbortError",l}await U(e)}finally{process.removeListener("SIGINT",d)}}u(J,"runFirstSetup");function X(i){let d=process.cwd(),t,e,l,f=!1,p,h;const o=[];for(let c=0;c<i.length;c++){const n=i[c];if(n==="--name")t=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")p="continue";else if(n==="--resume"||n==="-r"){p="pick";const w=i[c+1];w!==void 0&&G(w)&&!T(g(w))&&(h=w,c++)}else n.startsWith("--")||o.push(n)}o.length>0&&T(g(o[0]))&&(d=g(o.shift()));const m=o.length>0?o.join(" "):void 0;return{cwd:d,prompt:m,name:t,kind:e,profile:l,pickProfile:f,resume:p,resumeId:h}}u(X,"parseRootArgs");import{FRONT_DOOR_ENV as ae}from"./front-door-env.js";async function oe(i){const d=i.slice(2),t=d[0];if(process.env[W]||t==="-h"||t==="--help"||t==="--version"||t==="-v"||t!==void 0&&$.includes(t))return!1;if(t!==void 0){const r=/\s/.test(t),s=!t.startsWith("-")&&T(g(t)),a=j.has(t);if(!r&&!s&&!a)return!1;if(s){const{buildRoot:D}=await import("../../build-root.js");if((await D()).subtrees.some(L=>L.name===t))return!1}}const e=X(d),l=u(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:r}=await import("../profiles/manifest.js");e.profile=r(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await l();const f=process.stdin.isTTY&&process.stdout.isTTY;if(R()===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:r}=await import("../../daemon/machine-link/config.js");r()&&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({},{})}catch(a){process.stderr.write(`${a instanceof Error?a.message:String(a)}
3
- `),process.exit(1)}}let p=!1;const h=f&&!P()&&(await(await import("../../commands/api-client.js")).cliClient().getModelAuthReadiness({cwd:e.cwd})).hosted_endpoint;f&&!P()&&!h&&(await J(),p=!0);let o=null,m,c=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:r,noResumeTargetMessage:s}=await import("./resume-root.js"),a=await r(e.resumeId);"error"in a&&(process.stderr.write(`${a.error}
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:r,selectProfileForCwdReadOnly:s}=await import("../profiles/select.js");p&&e.profile===void 0&&process.stdout.write(`
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 r(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(r=>r.names)]),N=u(async()=>{const r=await n().getModelAuthReadiness({cwd:e.cwd,...o===null?{}:{profile:o}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await k(v)&&!await N()){f||w();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||w()}const{inTmux:y}=await import("./placement-tmux.js");if(f&&!y()){const{TMUX_STARTED_ENV:r,handoffToTmux:s}=await import("./tmux-handoff.js");process.env[r]===void 0&&s(d,m!==void 0?null:o,c)}const[{bootRoot:S},{resumeRoot:C},{rendererWarning:O,missingPackageWarning:_,piAgentDir:x}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=_(x());r!==null&&process.stderr.write(`
8
- ${r}
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:r}=await import("./resume-root.js");await r(m)}if(e.resume!==void 0&&await C(e.cwd,e.resume==="pick")==="aborted")return!0;const I=f&&(p||await Y()),{prompt:E,initialWhip:F}=B({offerTour:I,signedIn:I&&R()!==void 0,userPrompt:e.prompt});return I&&y()&&await V(),await S({...e,prompt:E,initialWhip:F,selectedProfileId:o??void 0}),!0}u(oe,"maybeBootRoot");export{ae as FRONT_DOOR_ENV,oe as maybeBootRoot,X as parseRootArgs};
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 n=(r,t)=>l(r,"name",{value:t,configurable:!0});import{chmodSync as y,existsSync as e,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{CrtrError as x}from"../../core/errors.js";import{atomicWriteJson as U}from"../../core/fs-utils.js";import{ExitCode as w}from"../../types.js";const p=n(()=>o(d(),"machine.json"),"machineConfigPath"),m=n(()=>o(g(),"machine-credential"),"machineCredentialPath");function N(){const r=p();if(!e(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}}}n(N,"readMachineConfig");function O(r){a(u(p()),{recursive:!0}),s(p(),`${JSON.stringify(r,null,2)}
2
- `)}n(O,"writeMachineConfig");function P(){const r=m();if(!e(r))throw new Error(`no machine credential at ${r}`);return c(r,"utf8").trim()}n(P,"readMachineCredential");function k(r){const t=m();a(u(t),{recursive:!0}),s(t,`${r}
3
- `,{mode:384}),y(t,384)}n(k,"writeMachineCredential");const f=n(()=>o(d(),"import","move.json"),"moveRecordPath");function I(){const r=f();if(!e(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}}n(I,"readMoveRecord");function A(r){U(f(),r,{mode:384})}n(A,"writeMoveRecord");function F(){h(f(),{force:!0})}n(F,"deleteMoveRecord");const q=n(()=>I()?.state==="committed","isMoveCommitted"),z=n(r=>new x("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"),C=n(()=>o(d(),"install-id"),"installIdPath");function B(){const r=C();if(e(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}n(B,"readOrCreateInstallId");const D=n(()=>["pg","canvas.db","canvas.db.imported"].some(r=>e(o(d(),r))),"hasLocalCanvas");export{F as deleteMoveRecord,D as hasLocalCanvas,C as installIdPath,q as isMoveCommitted,p as machineConfigPath,m as machineCredentialPath,f as moveRecordPath,z as moveUnfinishedError,N as readMachineConfig,P as readMachineCredential,I as readMoveRecord,B as readOrCreateInstallId,O as writeMachineConfig,k as writeMachineCredential,A as writeMoveRecord};
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};