@north-light/cli 0.3.736 → 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.
Files changed (36) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/clients/attach/viewer.js +1 -1
  4. package/dist/commands/sys/doctor.js +1 -1
  5. package/dist/commands/sys/old-package.d.ts +9 -0
  6. package/dist/commands/sys/old-package.js +1 -0
  7. package/dist/commands/sys/signin.d.ts +5 -0
  8. package/dist/commands/sys/signin.js +3 -2
  9. package/dist/core/grants/mirror.d.ts +2 -0
  10. package/dist/core/grants/mirror.js +4 -4
  11. package/dist/core/grants/shadow.d.ts +15 -0
  12. package/dist/core/grants/shadow.js +1 -0
  13. package/dist/core/human/page-schema.d.ts +1 -1
  14. package/dist/core/import/export/cloud.d.ts +3 -0
  15. package/dist/core/import/export/cloud.js +1 -1
  16. package/dist/core/runtime/front-door.js +9 -7
  17. package/dist/daemon/api/handlers/machines.js +1 -1
  18. package/dist/daemon/api/operations.js +1 -1
  19. package/dist/daemon/machine-daemon.js +1 -1
  20. package/dist/daemon/machine-link/config.d.ts +7 -2
  21. package/dist/daemon/machine-link/config.js +4 -3
  22. package/package.json +3 -3
  23. package/packages/crouter-api/dist/api/contract.js +1 -1
  24. package/packages/crouter-api/dist/commands/sys/doctor.js +9 -0
  25. package/packages/crouter-api/dist/commands/sys/old-package.js +20 -0
  26. package/packages/crouter-api/dist/commands/sys/signin.js +70 -8
  27. package/packages/crouter-api/dist/core/grants/mirror.js +6 -2
  28. package/packages/crouter-api/dist/core/grants/shadow.js +102 -0
  29. package/packages/crouter-api/dist/core/import/export/cloud.js +10 -0
  30. package/packages/crouter-api/dist/daemon/api/operations.js +1 -0
  31. package/packages/crouter-api/dist/daemon/machine-link/config.js +17 -3
  32. package/packages/crouter-api/package.json +1 -1
  33. package/packages/crouter-identity/package.json +1 -1
  34. package/packages/crouter-plugin/package.json +3 -3
  35. package/runtime.lock.json +14 -14
  36. package/scripts/sandbox-start.mjs +3 -4
@@ -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};
@@ -3,5 +3,10 @@ import { type SignInPrompt } from '../../core/directory/person-credential.js';
3
3
  export declare function showSignIn(prompt: SignInPrompt & {
4
4
  complete: string;
5
5
  }): void;
6
+ /** A computer with no `machine.json` and no local canvas becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
7
+ * The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
8
+ export declare function registerFreshComputer(directoryUrl: string): Promise<{
9
+ account: string;
10
+ }>;
6
11
  export declare const sysSigninLeaf: import("../../core/command.js").LeafDef;
7
12
  export declare const sysSignoutLeaf: import("../../core/command.js").LeafDef;
@@ -1,2 +1,3 @@
1
- var y=Object.defineProperty;var r=(e,n)=>y(e,"name",{value:n,configurable:!0});import{spawn as c}from"node:child_process";import{mkdirSync as k,openSync as _}from"node:fs";import{dirname as d,join as b}from"node:path";import{defineLeaf as h}from"../../core/command.js";import{CrtrError as u}from"../../core/errors.js";import{signIn as m,signOut as T}from"../../core/directory/person-credential.js";import{moveRecordPath as N,readMachineConfig as l}from"../../daemon/machine-link/config.js";import{sanitizedDaemonEnv as U,spawnDaemon as p,stopAllDaemons as g}from"../../daemon/manage.js";import{northlightUnreachable as S}from"../../core/directory/reach.js";import{envNodeId as A}from"../../shared/env.js";import{ExitCode as f}from"../../types.js";import{insideBroker as v}from"./join.js";import{cliClient as C}from"../api-client.js";import{defaultDirectoryUrl as O,finishMove as $,registerThisMac as P,runMove as R,settleEarlierMove as E}from"./import/move.js";import{WAIT_FOR_PID_ENV as I}from"./import/start.js";function x(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{c(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}r(x,"openBrowser");function a(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
- `),x(e.complete)}r(a,"showSignIn");function D(e){return async n=>{let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(o){return S(o,e.apiUrl)}if(!t.ok)return t.status===404?new u("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,f.USAGE):new u("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,f.GENERAL,{next:"Retry `crtr sys signin`."})}}r(D,"sameAccountOnly");function w(e){const n=b(d(N()),"move.log");k(d(n),{recursive:!0});const t=_(n,"a",384),o=U();for(const s of["CRTR_API_SOCKET","CRTR_API_TOKEN","CRTR_API_URL"])delete o[s];o[I]=String(process.pid);const i=[...process.execArgv,process.argv[1],"sys","import","start","--kind","machine",...e===void 0?[]:["--notify",e]];c(process.execPath,i,{detached:!0,stdio:["ignore",t,t],env:o}).unref()}r(w,"startDetachedMove");const M=r(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"),te=h({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 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:r(async e=>{const n=e.directoryUrl===void 0?O():String(e.directoryUrl),t=await E(a);if(t!==void 0)return v()?(w(void 0),{account:t.account.display,moving:!0}):(await $(t),{account:t.account.display,moved:!0});const o=l();if(o!==void 0){const{account:s}=await m(n,a,{accept:D(o)});return await P(n),await g(),await p(),{account:s}}const{account:i}=await m(n,a);return v()?(w(A()),{account:i,moving:!0}):(await R({directoryUrl:n,notify:null}),{account:i,moved:!0})},"run"),render:r(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${M(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function q(){return await g(),await p(),(await C({local:!0}).healthz()).signed_in===!1}r(q,"stopMovedComputer");const ne=h({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:["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:r(async()=>{const{signedOut:e,revoked:n}=await T(),t=l()===void 0?!1:await q();return{signed_out:e,revoked:n,stopped:t}},"run"),render:r(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{a as showSignIn,te as sysSigninLeaf,ne as sysSignoutLeaf};
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};
@@ -111,6 +111,8 @@ export declare function grantsOfPerson(person: string): Promise<Array<Pick<Grant
111
111
  export declare function grantExpired(grant: Pick<GrantRecord, 'expires_at'>): boolean;
112
112
  /** The active form of a grant record read earlier, or null when it is not active, is past `expires_at`, or is unparsable. */
113
113
  export declare function activeRecord(grant: GrantRecord): ActiveGrant | null;
114
+ /** JSON with every object's keys sorted, at every depth, and arrays kept in order. */
115
+ export declare function canonicalJson(value: unknown): string;
114
116
  /** `grant.get`'s `version`: an opaque string that changes exactly when what an app
115
117
  * reads from its grant changes — `rev`, `resolved_scopes` (order kept), `spend_cap`,
116
118
  * `payer`, `inference_endpoint`, `dependencies`. `synced_at` and the token's claims are left out, so a
@@ -1,11 +1,11 @@
1
- var R=Object.defineProperty;var t=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";const $=["not_started","pending","ready","failed","unavailable"],F=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(v,"runtimeScope");async function i(e,r,n=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(i,"grantRows");async function u(e,r,n=[]){return(await i(e,r,n))[0]}t(u,"grantRow");function k(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}t(k,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!k(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function U(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:o}=e;return typeof r!="string"||!$.includes(r)||n!==void 0&&typeof n!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...o===void 0?{}:{step:o}}}t(U,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const o=U(s);o&&(r[n]=o)}return r}t(O,"dependenciesOf");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const o of F){const a=n[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(G,"inferenceEndpointOf");function A(e,r,n,s){return r===e&&n&&s}t(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?G(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function d(e){if(!e||e.status!=="active")return null;try{return q(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}t(_,"mirrorOnly");async function ne(){return(await J()).filter(e=>!_(e))}t(ne,"localGrants");async function te(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}t(te,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",H=new RegExp(`^(${y}):(${y})$`);function W(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const o=H.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}t(W,"providerIdsFromGrants");async function se(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
1
+ var R=Object.defineProperty;var n=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";import{shadowCheck as $}from"./shadow.js";const F=["not_started","pending","ready","failed","unavailable"],k=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(v,"runtimeScope");async function i(e,r,t=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(i,"grantRows");async function u(e,r,t=[]){return(await i(e,r,t))[0]}n(u,"grantRow");function U(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(U,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!U(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!F.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(G,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=G(s);o&&(r[t]=o)}return r}n(O,"dependenciesOf");function H(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of k){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(H,"inferenceEndpointOf");function A(e,r,t,s){return r===e&&t&&s}n(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?H(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(f,"record");function d(e){if(!e||e.status!=="active")return null;try{const r=B(f(e));return r!==null&&$(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}n(_,"mirrorOnly");async function se(){return(await V()).filter(e=>!_(e))}n(se,"localGrants");async function ae(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(ae,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",W=new RegExp(`^(${y}):(${y})$`);function P(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=W.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(P,"providerIdsFromGrants");async function oe(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
2
2
  SELECT DISTINCT e->>'scope' AS scope FROM (
3
3
  SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${x()}${e.sql}) d OFFSET 0) p
4
4
  CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
5
5
  CROSS JOIN LATERAL regexp_match(s.scope, '^(${y}):${y}$') m
6
- WHERE m[1] <> 'crtr'`).all(...e.args)).map(n=>n.id).sort()}t(se,"activeProviderIds");async function ae(){const e=v();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${m}${x()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}t(ae,"anyActiveGrant");async function oe(e,r){return await u("1",`sub = ? AND ${m}${x()} AND EXISTS (
6
+ WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(oe,"activeProviderIds");async function ce(){const e=v();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${m}${x()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(ce,"anyActiveGrant");async function ie(e,r){return await u("1",`sub = ? AND ${m}${x()} AND EXISTS (
7
7
  SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
8
- WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}t(oe,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}t(x,"localOnly");async function ce(){return(await i("DISTINCT sub",P)).map(e=>e.sub)}t(ce,"grantSubs");async function ie(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}t(ie,"activeGrants");async function ue(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(W(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(ue,"grantedProviderIds");function pe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(pe,"isProviderBundleRow");async function de(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=d(n);return s===null?[]:[s]})}t(de,"activeGrantsOfPerson");async function J(){return j(await i("*","true"))}t(J,"allGrants");async function le(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(n=>{if(!A(n.rev,n.computed_rev,n.has_scopes,n.resolved_scopes_json!==null))return[];try{return[{sub:n.sub,status:n.status,resolved_scopes:l(JSON.parse(n.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}t(le,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return[];throw n}})}t(j,"records");function V(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(V,"grantExpired");function q(e){if(e.status!=="active"||V(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>L(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(q,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(S,"canonicalJson");function fe(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}t(fe,"grantVersion");async function _e(e){return!!await u("1","id = ?",[e])}t(_e,"hasGrant");async function ye(e){return await u("rev, status","id = ?",[e])??null}t(ye,"grantSyncState");async function Ee(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(Ee,"grantSyncStateFor");async function B(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(B,"grantRecord");async function ge(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=d(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(ge,"grantStanding");async function ve(e){return(await i("id",e)).map(r=>r.id)}t(ve,"grantIdsWhere");async function me(e){return(e?(await B(e))?.payer:null)??"user"}t(me,"payerOfGrant");async function X(e){return d(await u("*","id = ?",[e]))}t(X,"activeGrant");async function xe(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}t(xe,"grantFor");async function Se(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}t(Se,"activeGrantForApp");async function Te(e){const r=await X(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(Te,"runNoticeTarget");async function Ne(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}t(Ne,"terminalGrant");async function Oe(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(Oe,"grantsSource");async function Ae(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(Ae,"hasSyncedGrants");async function je(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(je,"dropLocalGrantMirror");async function we(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(we,"backfillComputedRev");function be(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const n of e){const{team:s,members:o}=n??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}t(be,"teamsOf");async function he(e,r,n,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await T(async a=>{let E=0;const g=[...o];E+=Number((await(g.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):a.prepareUncached("DELETE FROM grants").run())).changes);const w=a.prepare(`INSERT INTO grants
8
+ WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ie,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",J="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}n(x,"localOnly");async function ue(){return(await i("DISTINCT sub",J)).map(e=>e.sub)}n(ue,"grantSubs");async function pe(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}n(pe,"activeGrants");async function de(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(P(r.flatMap(t=>{try{return[f(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(de,"grantedProviderIds");function le(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(le,"isProviderBundleRow");async function fe(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=d(t);return s===null?[]:[s]})}n(fe,"activeGrantsOfPerson");async function V(){return j(await i("*","true"))}n(V,"allGrants");async function _e(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!A(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:l(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(_e,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(j,"records");function q(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(q,"grantExpired");function B(e){if(e.status!=="active"||q(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>L(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(B,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(S,"canonicalJson");function ye(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}n(ye,"grantVersion");async function Ee(e){return!!await u("1","id = ?",[e])}n(Ee,"hasGrant");async function ge(e){return await u("rev, status","id = ?",[e])??null}n(ge,"grantSyncState");async function ve(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(ve,"grantSyncStateFor");async function X(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(X,"grantRecord");async function me(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=d(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(me,"grantStanding");async function xe(e){return(await i("id",e)).map(r=>r.id)}n(xe,"grantIdsWhere");async function Se(e){return(e?(await X(e))?.payer:null)??"user"}n(Se,"payerOfGrant");async function z(e){return d(await u("*","id = ?",[e]))}n(z,"activeGrant");async function Te(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}n(Te,"grantFor");async function Ne(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}n(Ne,"activeGrantForApp");async function Oe(e){const r=await z(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(Oe,"runNoticeTarget");async function Ae(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}n(Ae,"terminalGrant");async function je(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(je,"grantsSource");async function we(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(we,"hasSyncedGrants");async function be(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(be,"dropLocalGrantMirror");async function he(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}n(he,"backfillComputedRev");function Re(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n(Re,"teamsOf");async function De(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await T(async a=>{let E=0;const g=[...o];E+=Number((await(g.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):a.prepareUncached("DELETE FROM grants").run())).changes);const w=a.prepare(`INSERT INTO grants
9
9
  (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
10
10
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
11
11
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -19,4 +19,4 @@ var R=Object.defineProperty;var t=(e,r)=>R(e,"name",{value:r,configurable:!0});i
19
19
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
20
20
  IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
21
21
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
22
- excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(a,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(h=>({resourceId:c,subject:C(h)})))),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(he,"replaceGrants");async function Re(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(Re,"grantsGeneration");export{X as activeGrant,Se as activeGrantForApp,oe as activeGrantNamesApp,ie as activeGrants,de as activeGrantsOfPerson,se as activeProviderIds,q as activeRecord,J as allGrants,ae as anyActiveGrant,we as backfillComputedRev,O as dependenciesOf,je as dropLocalGrantMirror,V as grantExpired,xe as grantFor,ve as grantIdsWhere,B as grantRecord,ge as grantStanding,ce as grantSubs,ye as grantSyncState,Ee as grantSyncStateFor,fe as grantVersion,ue as grantedProviderIds,Re as grantsGeneration,le as grantsOfPerson,Oe as grantsSource,_e as hasGrant,Ae as hasSyncedGrants,G as inferenceEndpointOf,pe as isProviderBundleRow,ne as localGrants,_ as mirrorOnly,te as otherLiveGrantOfApp,me as payerOfGrant,W as providerIdsFromGrants,he as replaceGrants,Te as runNoticeTarget,v as runtimeScope,be as teamsOf,Ne as terminalGrant};
22
+ excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(a,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(h=>({resourceId:c,subject:C(h)})))),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n(De,"replaceGrants");async function Le(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(Le,"grantsGeneration");export{z as activeGrant,Ne as activeGrantForApp,ie as activeGrantNamesApp,pe as activeGrants,fe as activeGrantsOfPerson,oe as activeProviderIds,B as activeRecord,V as allGrants,ce as anyActiveGrant,he as backfillComputedRev,S as canonicalJson,O as dependenciesOf,be as dropLocalGrantMirror,q as grantExpired,Te as grantFor,xe as grantIdsWhere,X as grantRecord,me as grantStanding,ue as grantSubs,ge as grantSyncState,ve as grantSyncStateFor,ye as grantVersion,de as grantedProviderIds,Le as grantsGeneration,_e as grantsOfPerson,je as grantsSource,Ee as hasGrant,we as hasSyncedGrants,H as inferenceEndpointOf,le as isProviderBundleRow,se as localGrants,_ as mirrorOnly,ae as otherLiveGrantOfApp,Se as payerOfGrant,P as providerIdsFromGrants,De as replaceGrants,Oe as runNoticeTarget,v as runtimeScope,Re as teamsOf,Ae as terminalGrant};
@@ -0,0 +1,15 @@
1
+ import { type GrantRecord } from './mirror.js';
2
+ /** Test hook: how long a cached answer is used before its epochs are re-checked. */
3
+ export declare function setShadowTtl(ms: number): void;
4
+ /** Test hook: forget every cached answer. */
5
+ export declare function resetShadowCache(): void;
6
+ /** How many checks agreed, disagreed (live answer differs at the same rev), lagged (live rev differs: a sync has not landed) or failed since this process started. */
7
+ export declare const shadowCounts: {
8
+ agree: number;
9
+ disagree: number;
10
+ lagging: number;
11
+ error: number;
12
+ };
13
+ export declare function shadowIdle(): Promise<void>;
14
+ /** Compare one stored grant with the directory's live answer, in the background, on the fleet only. Never throws and never delays the caller. */
15
+ export declare function shadowCheck(stored: GrantRecord): void;
@@ -0,0 +1 @@
1
+ var S=Object.defineProperty;var a=(e,r)=>S(e,"name",{value:r,configurable:!0});import{directoryIssuer as $}from"../directory/issuer.js";import{outboundFetch as v}from"../events/outbound.js";import{warn as u}from"../output.js";import{canonicalJson as m}from"./mirror.js";let _=5e3;function O(e){_=e}a(O,"setShadowTtl");const k=512,A=["status","scopes","resolved_scopes","spend_cap","payer","dependencies","run_notice_url","inference_endpoint"];function R(){i.clear()}a(R,"resetShadowCache");const i=new Map,f=new Map,t={agree:0,disagree:0,lagging:0,error:0};async function M(e,r,n){const{mintDirectoryToken:s}=await import("./sync.js"),o=await s(e),g=n?`&epochs=${n.epochs.global},${n.epochs.sub}`:"",y=`${e}/v1/runtime/grant-answers?sub=${encodeURIComponent(r)}${g}`,d=await v("grant_shadow",y,{headers:{Authorization:`Bearer ${o.access_token}`},signal:AbortSignal.timeout(1e4)});if(!d.ok)throw new Error(`grant-answers ${d.status}`);const l=await d.json();if(l.unchanged){if(!n)throw new Error("grant-answers said unchanged to a caller holding nothing");return{...n,epochs:l.epochs,checkedAt:Date.now()}}return{epochs:l.epochs,grants:new Map((l.grants??[]).map(w=>[String(w.id),w])),checkedAt:Date.now()}}a(M,"fetchAnswer");async function x(e,r){const n=i.get(r);if(n&&Date.now()-n.checkedAt<_)return n;const s=f.get(r);if(s)return s;const o=M(e,r,n).then(g=>(i.delete(r),i.set(r,g),i.size>k&&i.delete(i.keys().next().value),g)).finally(()=>f.delete(r));return f.set(r,o),o}a(x,"answerFor");const h=new Set;async function T(){await Promise.all([...h])}a(T,"shadowIdle");async function C(e){const r=$();if(r===null)return;const n=(await x(r,e.sub)).grants.get(e.id);if(!n){t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,fields:["missing"]})}`);return}if(n.rev!==e.rev){t.lagging++;return}const s=A.filter(o=>m(n[o]??null)!==m(e[o]??null));if(s.length===0){t.agree++;return}t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,rev:e.rev,fields:s})}`)}a(C,"compare");let p,c={agree:0,disagree:0,lagging:0,error:0};function b(){p||(p=setInterval(()=>{const e={agree:t.agree-c.agree,disagree:t.disagree-c.disagree,lagging:t.lagging-c.lagging,error:t.error-c.error};c={...t},e.agree+e.disagree+e.lagging+e.error>0&&u(`grant_shadow_summary ${JSON.stringify({window_s:60,...e})}`)},6e4),p.unref())}a(b,"startSummary");function U(e){if(!process.env.CRTR_RUNTIME)return;b();const r=C(e).catch(n=>{t.error++,u(`grant_shadow error ${JSON.stringify({grant:e.id,message:n instanceof Error?n.message:String(n)})}`)}).finally(()=>h.delete(r));h.add(r)}a(U,"shadowCheck");export{R as resetShadowCache,O as setShadowTtl,U as shadowCheck,t as shadowCounts,T as shadowIdle};
@@ -186,8 +186,8 @@ export declare const chartDataRowsSchema: z.ZodArray<z.ZodRecord<z.ZodString, z.
186
186
  export declare const chartConfigSchema: z.ZodObject<{
187
187
  kind: z.ZodEnum<{
188
188
  line: "line";
189
- bar: "bar";
190
189
  area: "area";
190
+ bar: "bar";
191
191
  }>;
192
192
  x: z.ZodString;
193
193
  y: z.ZodArray<z.ZodObject<{
@@ -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,11 +1,13 @@
1
- var E=Object.defineProperty;var p=(i,s)=>E(i,"name",{value:s,configurable:!0});import{existsSync as x,statSync as b}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as A}from"../../build-root.js";import{FRONT_DOOR_ENV as L}from"./front-door-env.js";import{frontDoorBootPrompt as M}from"./first-run-offer.js";import{readMachineConfig as W}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as $}from"./node-id-token.js";import{markTourOffered as B,recordSetupCompleted as G,setupCompleted as V,tourOfferPending as U}from"./setup-marker.js";function I(i){try{return x(i)&&b(i).isDirectory()}catch{return!1}}p(I,"isDir");const Y=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function j(){let i=!1;const s=p(()=>{i=!0},"onSigint");process.once("SIGINT",s);try{const{runSetup:t}=await import("../../commands/sys/setup-wizard.js"),e=await t();if(i){const c=new Error("Interrupted");throw c.name="AbortError",c}await G(e)}finally{process.removeListener("SIGINT",s)}}p(j,"runFirstSetup");function J(i){let s=process.cwd(),t,e,c,u=!1,m,a;const n=[];for(let f=0;f<i.length;f++){const o=i[f];if(o==="--name")t=i[++f];else if(o==="--kind")e=i[++f];else if(o==="--profile")c=i[++f];else if(o==="--pick-profile")u=!0;else if(o==="--continue"||o==="-c")m="continue";else if(o==="--resume"||o==="-r"){m="pick";const w=i[f+1];w!==void 0&&$(w)&&!I(h(w))&&(a=w,f++)}else o.startsWith("--")||n.push(o)}n.length>0&&I(h(n[0]))&&(s=h(n.shift()));const g=n.length>0?n.join(" "):void 0;return{cwd:s,prompt:g,name:t,kind:e,profile:c,pickProfile:u,resume:m,resumeId:a}}p(J,"parseRootArgs");import{FRONT_DOOR_ENV as se}from"./front-door-env.js";async function ie(i){const s=i.slice(2),t=s[0];if(process.env[L]||t==="-h"||t==="--help"||t==="--version"||t==="-v"||t!==void 0&&A.includes(t))return!1;if(t!==void 0){const r=/\s/.test(t),d=!t.startsWith("-")&&I(h(t)),l=Y.has(t);if(!r&&!d&&!l)return!1;if(d){const{buildRoot:C}=await import("../../build-root.js");if((await C()).subtrees.some(D=>D.name===t))return!1}}const e=J(s),c=p(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 c();const u=process.stdin.isTTY&&process.stdout.isTTY;let m=!1;u&&!V()&&(await j(),m=!0);let a=null,n,g=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:r,noResumeTargetMessage:d}=await import("./resume-root.js"),l=await r(e.resumeId);"error"in l&&(process.stderr.write(`${l.error}
2
- `),process.exit(1)),"none"in l?(e.resumeId.includes("-")&&(process.stderr.write(`${d(e.resumeId)}
3
- `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await c()):(a=l.node.profile_id,n=l.node.node_id,I(l.node.cwd)&&(g=l.node.cwd))}if(n===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:d}=await import("../profiles/select.js");m&&e.profile===void 0&&process.stdout.write(`
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}
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(`
4
6
  Choose a profile
5
- `),a=e.profile??(u?await r(e.cwd,void 0,e.pickProfile,!1):d(e.cwd))}const{cliClient:f}=await import("../../commands/api-client.js"),[{exitForMissingProviderCredential:o,hasConfiguredProviderCredential:w},R]=await Promise.all([import("./provider-credential-gate.js"),a===null?[]:f().listProfileEnv(a).then(r=>r.names)]),k=p(async()=>{const r=await f().getModelAuthReadiness({cwd:e.cwd,...a===null?{}:{profile:a}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await w(R)&&!await k()){u||o();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||o()}const{inTmux:P}=await import("./placement-tmux.js");if(u&&!P()){const{TMUX_STARTED_ENV:r,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[r]===void 0&&d(s,n!==void 0?null:a,g)}const[{bootRoot:v},{resumeRoot:y},{rendererWarning:N,missingPackageWarning:O,piAgentDir:S}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=O(S());r!==null&&process.stderr.write(`
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(`
6
8
  ${r}
7
9
 
8
- `);const d=N();d!==null&&process.stderr.write(`
9
- ${d}
10
+ `);const s=O();s!==null&&process.stderr.write(`
11
+ ${s}
10
12
 
11
- `)}catch{}if(n!==void 0){const{resumeNodeById:r}=await import("./resume-root.js");await r(n)}if(e.resume!==void 0&&await y(e.cwd,e.resume==="pick")==="aborted")return!0;const T=u&&(m||await U()),{prompt:F,initialWhip:_}=M({offerTour:T,signedIn:T&&W()!==void 0,userPrompt:e.prompt});return T&&P()&&await B(),await v({...e,prompt:F,initialWhip:_,selectedProfileId:a??void 0}),!0}p(ie,"maybeBootRoot");export{se as FRONT_DOOR_ENV,ie as maybeBootRoot,J as parseRootArgs};
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};
@@ -1 +1 @@
1
- var h=Object.defineProperty;var w=(t,o)=>h(t,"name",{value:o,configurable:!0});import{ApiError as a}from"../../../api/errors.js";import{withCanvasWrite as _}from"../../../core/canvas/db.js";import{createObject as v,ownerForGrantee as E}from"../../../core/graph/objects.js";import{OBJECT_TYPE as y}from"../../../core/permissions/builtin.js";import{listFacts as g,userSubject as b,writeActsFor as j}from"../../../core/permissions/facts.js";import{hasMachineCredential as S,mintMachineCredential as T}from"../../machine-link/credential.js";async function R(t){if(t.principal.class!=="person"||t.principal.sub===void 0)throw new a(403,"person_only","a machine is registered by a signed-in person");const o=b(t.principal.sub).id,e=t.body??{},p=t.query.get("rotate")==="1",i=typeof e.environment_id=="string"&&p?e.environment_id:void 0;if(i===void 0&&(typeof e.install_id!="string"||e.install_id.trim()===""))throw new a(400,"invalid_request","install_id is required");const s=typeof e.install_id=="string"?e.install_id.trim():"",u=typeof e.name=="string"&&e.name.trim()!==""?e.name.trim():s,l=new Date().toISOString(),c=await _(async n=>{const r=i===void 0?await n.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(s):await n.prepare("SELECT object FROM environments WHERE object = ? AND kind = 'machine'").get(i);if(r===void 0&&i!==void 0)throw new a(404,"environment_not_found",`no machine environment ${i}`);if(r!==void 0){if(!(await g(n,y,r.object)).some(m=>m.relation==="acts_for"&&m.subject_type==="user"&&m.subject_id===o))throw new a(409,"install_id_taken","this install id is registered to another person");return await n.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(l,r.object),r.object}const f=await E(n,"app:terminal"),d=await v(n,{type:"environment",kind:"machine",owner:f.id,privacy:"public",name:s,preview:u});return await j(n,d.id,o),await n.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(d.id,s,l),d.id});if(!p&&await S(c))throw new a(409,"credential_exists","the machine credential was already issued; rotate it");return{status:200,body:{environment_id:c,credential:await T(c)}}}w(R,"handleRegister");const N=[{method:"POST",pattern:"/v1/machines",handler:R}];export{N as machineRoutes};
1
+ var y=Object.defineProperty;var u=(n,r)=>y(n,"name",{value:r,configurable:!0});import{ApiError as t}from"../../../api/errors.js";import{withCanvasWrite as h}from"../../../core/canvas/db.js";import{createObject as b,ownerForGrantee as g}from"../../../core/graph/objects.js";import{OBJECT_TYPE as _}from"../../../core/permissions/builtin.js";import{listFacts as f,userSubject as v,writeActsFor as j}from"../../../core/permissions/facts.js";import{hasMachineCredential as R,mintMachineCredential as T,revokeMachineCredential as S}from"../../machine-link/credential.js";async function k(n){if(n.principal.class!=="person"||n.principal.sub===void 0)throw new t(403,"person_only","a machine is registered by a signed-in person");const r=v(n.principal.sub).id,e=n.body??{},o=n.query.get("rotate")==="1",a=typeof e.environment_id=="string"&&o?e.environment_id:void 0;if(a===void 0&&(typeof e.install_id!="string"||e.install_id.trim()===""))throw new t(400,"invalid_request","install_id is required");const s=typeof e.install_id=="string"?e.install_id.trim():"",c=typeof e.name=="string"&&e.name.trim()!==""?e.name.trim():s,w=new Date().toISOString(),m=await h(async i=>{const d=a===void 0?await i.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(s):await i.prepare("SELECT object FROM environments WHERE object = ? AND kind = 'machine'").get(a);if(d===void 0&&a!==void 0)throw new t(404,"environment_not_found",`no machine environment ${a}`);if(d!==void 0){if(!(await f(i,_,d.object)).some(l=>l.relation==="acts_for"&&l.subject_type==="user"&&l.subject_id===r))throw new t(409,"install_id_taken","this install id is registered to another person");return await i.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(w,d.object),d.object}const E=await g(i,"app:terminal"),p=await b(i,{type:"environment",kind:"machine",owner:E.id,privacy:"public",name:s,preview:c});return await j(i,p.id,r),await i.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(p.id,s,w),p.id});if(!o&&await R(m))throw new t(409,"credential_exists","the machine credential was already issued; rotate it");return{status:200,body:{environment_id:m,credential:await T(m)}}}u(k,"handleRegister");async function A(n){if(n.principal.class!=="person"||n.principal.sub===void 0)throw new t(403,"person_only","a machine is revoked by a signed-in person");const r=v(n.principal.sub).id,e=n.params.environment_id??"";return await h(async o=>{if(!(await o.prepare("SELECT object FROM environments WHERE object = ? AND kind = 'machine'").get(e)===void 0?[]:await f(o,_,e)).some(c=>c.relation==="acts_for"&&c.subject_type==="user"&&c.subject_id===r))throw new t(404,"environment_not_found",`no machine environment ${e}`)}),await S(e),{status:200,body:{environment_id:e}}}u(A,"handleRevoke");const W=[{method:"POST",pattern:"/v1/machines",handler:k},{method:"DELETE",pattern:"/v1/machines/:environment_id",handler:A}];export{W as machineRoutes};