@north-light/cli 0.3.737 → 0.3.738
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/sys/doctor.js +1 -1
- package/dist/commands/sys/old-package.d.ts +9 -0
- package/dist/commands/sys/old-package.js +1 -0
- package/dist/commands/sys/signin.js +3 -2
- package/dist/core/import/export/cloud.d.ts +3 -0
- package/dist/core/import/export/cloud.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/commands/sys/doctor.js +9 -0
- package/packages/crouter-api/dist/commands/sys/old-package.js +20 -0
- package/packages/crouter-api/dist/commands/sys/signin.js +7 -0
- package/packages/crouter-api/dist/core/import/export/cloud.js +10 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
var 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,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
|
|
2
|
-
`),
|
|
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 P}from"node:fs";import{dirname as w,join as R}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 l,signOut as C}from"../../core/directory/person-credential.js";import{hasLocalCanvas as I,moveRecordPath as x,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 u,stopAllDaemons as g}from"../../daemon/manage.js";import{hostname as G}from"node:os";import{northlightUnreachable as p}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{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{f(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 p(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 E(e){const n=R(w(x()),"move.log");O(w(n),{recursive:!0});const t=P(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]];f(process.execPath,s,{detached:!0,stdio:["ignore",t,t],env:r}).unref()}i(E,"startDetachedMove");async function X(e){const n=_()===void 0?(await l(e,m),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 p($,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 N(e),await g(),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=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.","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=>{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 T()?(E(void 0),{account:r.account.display,moving:!0}):(await z(r),{account:r.account.display,moved:!0});const s=b();if(s!==void 0){const{account:d}=await l(t,m,{accept:Q(s)});return await N(t),await g(),await u(),{account:d}}if(!I())return await X(t);const{account:o}=await l(t,m);return T()?(E(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 g(),await u(),(await j()).signed_in===!1}i(Z,"stopMovedComputer");async function ee(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 p(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=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 ee(e);const{signedOut:n,revoked:t}=await C(),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
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.738",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.738",
|
|
162
|
+
"@north-light/plugin": "0.3.738",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -12,6 +12,7 @@ import { pathExists, listDirs, removePath } from '../../core/fs-utils.js';
|
|
|
12
12
|
import { lsRemote } from '../../core/git.js';
|
|
13
13
|
import { cliClient } from '../api-client.js';
|
|
14
14
|
import { detectNerdFont, nerdFontInstallCommand, NERD_FONT_SELECT_HINT } from '../../core/runtime/nerd-font.js';
|
|
15
|
+
import { oldPackageInstalled } from './old-package.js';
|
|
15
16
|
import { detectPackageManager } from './setup-core.js';
|
|
16
17
|
import { validateEffectiveCommandPlugins } from '../../core/command-plugins/discovery.js';
|
|
17
18
|
import { adaptPluginContributions } from '../../core/command-plugins/compose.js';
|
|
@@ -386,6 +387,13 @@ function runNerdFontCheck() {
|
|
|
386
387
|
...(plan.command ? { command: plan.command } : {}),
|
|
387
388
|
});
|
|
388
389
|
}
|
|
390
|
+
/** `@crouton-kit/crouter` installed beside this package fights it for the `crtr` bin, and npm refuses to install over it; only uninstalling it first works. */
|
|
391
|
+
function oldPackageCheck() {
|
|
392
|
+
const old = oldPackageInstalled();
|
|
393
|
+
if (old === undefined)
|
|
394
|
+
return pass('canvas', 'package:old-crouter', 'the old @crouton-kit/crouter package is not installed');
|
|
395
|
+
return failCheck('canvas', 'package:old-crouter', old.message, { kind: 'human_action', description: 'Remove the old package, then reinstall this one', command: `${old.uninstall} && npm i -g @north-light/cli@latest` });
|
|
396
|
+
}
|
|
389
397
|
/** Where the generation was installed from (`<id>.source.json` beside it, written by install-runtime). */
|
|
390
398
|
function installSourceCheck(label, generation) {
|
|
391
399
|
const name = `runtime:${label}:source`;
|
|
@@ -630,6 +638,7 @@ export const sysDoctorLeaf = defineLeaf({
|
|
|
630
638
|
allResults.push(...runBinContributionChecks(scopes));
|
|
631
639
|
allResults.push(...runHumanActionChecks(scopes));
|
|
632
640
|
allResults.push(...await runRequiresChecks(scopes));
|
|
641
|
+
allResults.push(oldPackageCheck());
|
|
633
642
|
allResults.push(...await runFaultChecks());
|
|
634
643
|
const processLocation = processGeneration();
|
|
635
644
|
allResults.push(...await generationChecks('selected', selectedGeneration(), processLocation === null));
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// The old `@crouton-kit/crouter` package declares the same `crtr` bin as `@north-light/cli`. npm checks bin ownership before any install script runs,
|
|
2
|
+
// so `npm i -g @north-light/cli` over it fails with EEXIST and no script of ours can prevent that; the old package has to be uninstalled first.
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { dirname, join, sep } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
export const OLD_PACKAGE = '@crouton-kit/crouter';
|
|
7
|
+
export const OLD_PACKAGE_UNINSTALL = `npm uninstall -g ${OLD_PACKAGE}`;
|
|
8
|
+
/** Where a global install of this package sits beside the old one: `<lib>/node_modules/@north-light/cli` → `<lib>/node_modules/@crouton-kit/crouter`. */
|
|
9
|
+
export function oldPackageDir(packageRoot) {
|
|
10
|
+
const marker = `${sep}node_modules${sep}@north-light${sep}cli`;
|
|
11
|
+
const at = packageRoot.lastIndexOf(marker);
|
|
12
|
+
return at < 0 ? undefined : join(packageRoot.slice(0, at), 'node_modules', OLD_PACKAGE);
|
|
13
|
+
}
|
|
14
|
+
/** The old package installed next to this one, with the message that names the command that removes it; undefined when it is absent. */
|
|
15
|
+
export function oldPackageInstalled(packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')) {
|
|
16
|
+
const dir = oldPackageDir(packageRoot);
|
|
17
|
+
if (dir === undefined || !existsSync(join(dir, 'package.json')))
|
|
18
|
+
return undefined;
|
|
19
|
+
return { uninstall: OLD_PACKAGE_UNINSTALL, message: `The old ${OLD_PACKAGE} package is still installed at ${dir} and owns the \`crtr\` command. Run \`${OLD_PACKAGE_UNINSTALL}\`, then \`npm i -g @north-light/cli@latest\`.` };
|
|
20
|
+
}
|
|
@@ -13,6 +13,7 @@ import { envNodeId } from '../../shared/env.js';
|
|
|
13
13
|
import { ExitCode } from '../../types.js';
|
|
14
14
|
import { insideBroker } from './join.js';
|
|
15
15
|
import { defaultDirectoryUrl, finishMove, registerThisMac, runMove, settleEarlierMove } from './import/move.js';
|
|
16
|
+
import { oldPackageInstalled } from './old-package.js';
|
|
16
17
|
import { WAIT_FOR_PID_ENV } from './import/start.js';
|
|
17
18
|
/** Open the confirm page in the person's browser; a failure to open it is harmless because the code and address are printed too. */
|
|
18
19
|
function openBrowser(url) {
|
|
@@ -114,6 +115,7 @@ export const sysSigninLeaf = defineLeaf({
|
|
|
114
115
|
outputKind: 'object',
|
|
115
116
|
effects: [
|
|
116
117
|
'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.',
|
|
118
|
+
'Starts the local daemon first when it is not running, and waits until it serves.',
|
|
117
119
|
'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`.',
|
|
118
120
|
'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.',
|
|
119
121
|
'On a moved computer: restarts the daemon so it reconnects to Northlight.',
|
|
@@ -121,6 +123,11 @@ export const sysSigninLeaf = defineLeaf({
|
|
|
121
123
|
],
|
|
122
124
|
},
|
|
123
125
|
run: async (input) => {
|
|
126
|
+
// A fresh home has no daemon yet, and the move reads the canvas through it: start it (a no-op when it already serves) before anything else.
|
|
127
|
+
await spawnDaemon();
|
|
128
|
+
const oldPackage = oldPackageInstalled();
|
|
129
|
+
if (oldPackage !== undefined)
|
|
130
|
+
process.stderr.write(`${oldPackage.message}\n`);
|
|
124
131
|
const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
|
|
125
132
|
const unfinished = await settleEarlierMove(showSignIn);
|
|
126
133
|
if (unfinished !== undefined) {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// The exporter's HTTP side: `/v1/imports` on the control plane with the person's (or the operator's) bearer token, and signed R2 PUTs.
|
|
2
2
|
// Imports Node built-ins only, so a CLI leaf can use it.
|
|
3
3
|
import { CrtrError, general } from '../../errors.js';
|
|
4
|
+
import { ExitCode } from '../../../types.js';
|
|
5
|
+
import { crtrVersion } from '../../../shared/crtr-version.js';
|
|
4
6
|
import { NORTHLIGHT_UNREACHABLE } from '../../directory/reach.js';
|
|
5
7
|
/** The dump directory's file holding the opened file stores, and the order they are uploaded in. */
|
|
6
8
|
export const STORE_FILE = 'stores.json';
|
|
@@ -17,6 +19,11 @@ function failureText(error) {
|
|
|
17
19
|
const cause = error.cause;
|
|
18
20
|
return `failed: ${error instanceof Error ? error.message : String(error)}${typeof cause?.code === 'string' ? ` (${cause.code})` : ''}`;
|
|
19
21
|
}
|
|
22
|
+
/** The control plane refuses a source that runs another release than its own: name the release it accepts and the command that installs it. */
|
|
23
|
+
export function releaseMismatch(accepted, status) {
|
|
24
|
+
const command = `npm i -g @north-light/cli@${accepted}`;
|
|
25
|
+
return new CrtrError('release_mismatch', `Northlight accepts only crtr ${accepted} for this step, and this computer runs ${crtrVersion()}. Install it with \`${command}\`, then run \`crtr sys signin\` again.`, ExitCode.GENERAL, { status, code: 'release_mismatch', accepted, next: `Run \`${command}\`, then \`crtr sys signin\`.` });
|
|
26
|
+
}
|
|
20
27
|
export class ImportCloud {
|
|
21
28
|
apiUrl;
|
|
22
29
|
token;
|
|
@@ -83,6 +90,9 @@ export class ImportCloud {
|
|
|
83
90
|
catch {
|
|
84
91
|
code = undefined;
|
|
85
92
|
}
|
|
93
|
+
const accepted = code === 'release_mismatch' ? /control plane accepts (\S+)/.exec(text)?.[1]?.replace(/[^0-9A-Za-z.+-]+$/, '') : undefined;
|
|
94
|
+
if (accepted !== undefined)
|
|
95
|
+
throw releaseMismatch(accepted, response.status);
|
|
86
96
|
throw general(`${method} ${path} answered ${response.status}: ${text.slice(0, 500)}`, { status: response.status, ...(typeof code === 'string' ? { code } : {}) });
|
|
87
97
|
}
|
|
88
98
|
return (text === '' ? undefined : JSON.parse(text));
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.738",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.738",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@north-light/api": "0.3.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.738",
|
|
31
|
+
"@north-light/identity": "0.3.738"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.738",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.738",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
32
|
-
"@north-light/plugin": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.738",
|
|
32
|
+
"@north-light/plugin": "0.3.738",
|
|
33
33
|
"cron-parser": "^5.6.0",
|
|
34
34
|
"esbuild": "0.28.2",
|
|
35
35
|
"jose": "^6.2.12",
|
|
@@ -11902,17 +11902,17 @@
|
|
|
11902
11902
|
},
|
|
11903
11903
|
"packages/crouter-api": {
|
|
11904
11904
|
"name": "@north-light/api",
|
|
11905
|
-
"version": "0.3.
|
|
11905
|
+
"version": "0.3.738",
|
|
11906
11906
|
"license": "UNLICENSED"
|
|
11907
11907
|
},
|
|
11908
11908
|
"packages/crouter-env-docker": {
|
|
11909
11909
|
"name": "@north-light/env-docker",
|
|
11910
|
-
"version": "0.3.
|
|
11910
|
+
"version": "0.3.738",
|
|
11911
11911
|
"license": "UNLICENSED"
|
|
11912
11912
|
},
|
|
11913
11913
|
"packages/crouter-identity": {
|
|
11914
11914
|
"name": "@north-light/identity",
|
|
11915
|
-
"version": "0.3.
|
|
11915
|
+
"version": "0.3.738",
|
|
11916
11916
|
"license": "UNLICENSED",
|
|
11917
11917
|
"dependencies": {
|
|
11918
11918
|
"jose": "^6.2.1"
|
|
@@ -11920,21 +11920,21 @@
|
|
|
11920
11920
|
},
|
|
11921
11921
|
"packages/crouter-plugin": {
|
|
11922
11922
|
"name": "@north-light/plugin",
|
|
11923
|
-
"version": "0.3.
|
|
11923
|
+
"version": "0.3.738",
|
|
11924
11924
|
"license": "UNLICENSED",
|
|
11925
11925
|
"dependencies": {
|
|
11926
|
-
"@north-light/api": "0.3.
|
|
11927
|
-
"@north-light/identity": "0.3.
|
|
11926
|
+
"@north-light/api": "0.3.738",
|
|
11927
|
+
"@north-light/identity": "0.3.738"
|
|
11928
11928
|
}
|
|
11929
11929
|
},
|
|
11930
11930
|
"packages/crouter-sdk": {
|
|
11931
11931
|
"name": "@north-light/sdk",
|
|
11932
|
-
"version": "0.3.
|
|
11932
|
+
"version": "0.3.738",
|
|
11933
11933
|
"license": "UNLICENSED",
|
|
11934
11934
|
"dependencies": {
|
|
11935
|
-
"@north-light/api": "0.3.
|
|
11936
|
-
"@north-light/identity": "0.3.
|
|
11937
|
-
"@north-light/plugin": "0.3.
|
|
11935
|
+
"@north-light/api": "0.3.738",
|
|
11936
|
+
"@north-light/identity": "0.3.738",
|
|
11937
|
+
"@north-light/plugin": "0.3.738",
|
|
11938
11938
|
"jose": "^6.2.1"
|
|
11939
11939
|
},
|
|
11940
11940
|
"bin": {
|