@north-light/cli 0.3.781 → 0.3.783

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 (112) hide show
  1. package/README.md +9 -19
  2. package/dist/api/client.d.ts +3 -1
  3. package/dist/api/client.js +1 -1
  4. package/dist/api/contract.d.ts +1 -1
  5. package/dist/api/contract.js +1 -1
  6. package/dist/api/dto/charges.d.ts +3 -3
  7. package/dist/api/dto/charges.js +1 -1
  8. package/dist/api/dto/inbox.d.ts +2 -0
  9. package/dist/build-root.js +1 -1
  10. package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
  11. package/dist/builtin-memory/crouter-sdk/README.md +3 -2
  12. package/dist/builtin-memory/crouter-sdk/client.md +3 -3
  13. package/dist/builtin-memory/crouter-sdk/docker.md +6 -10
  14. package/dist/builtin-memory/crouter-sdk/release-notes.md +25 -3
  15. package/dist/builtin-memory/crouter-sdk/sourcing.md +94 -0
  16. package/dist/builtin-memory/insights/capture.md +2 -2
  17. package/dist/builtin-memory/internal/marketplaces.md +1 -1
  18. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  19. package/dist/builtin-memory/northlight-apps/cli.md +1 -1
  20. package/dist/builtin-memory/northlight-apps/coding-agents.md +1 -1
  21. package/dist/builtin-memory/northlight-apps/get-started.md +2 -2
  22. package/dist/builtin-memory/northlight-apps/guides/watchable-objects.md +1 -1
  23. package/dist/builtin-memory/northlight-apps/how-it-fits.md +1 -1
  24. package/dist/builtin-memory/northlight-apps/let-their-ai-use-your-app.md +1 -4
  25. package/dist/builtin-memory/northlight-apps/quickstart.md +1 -1
  26. package/dist/cli.js +2 -8
  27. package/dist/clients/attach/command.js +1 -1
  28. package/dist/clients/attach/input/capabilities.js +1 -1
  29. package/dist/clients/attach/viewer.js +524 -524
  30. package/dist/clients/inbox/controller.d.ts +34 -11
  31. package/dist/clients/inbox/controller.js +1 -1
  32. package/dist/clients/inbox/dto-adapt.d.ts +1 -0
  33. package/dist/clients/inbox/dto-adapt.js +1 -1
  34. package/dist/clients/inbox/surface.js +1 -1
  35. package/dist/commands/canvas-config.js +2 -2
  36. package/dist/commands/canvas-use.js +1 -1
  37. package/dist/commands/node/inspect.js +6 -6
  38. package/dist/commands/pkg/account-installs.d.ts +9 -0
  39. package/dist/commands/pkg/account-installs.js +1 -0
  40. package/dist/commands/profile/default.js +1 -1
  41. package/dist/commands/sys/setup-core.d.ts +1 -52
  42. package/dist/commands/sys/setup-core.js +6 -6
  43. package/dist/commands/sys/setup-wizard.d.ts +4 -9
  44. package/dist/commands/sys/setup-wizard.js +2 -1
  45. package/dist/commands/sys/setup.js +1 -1
  46. package/dist/commands/sys/signin.d.ts +1 -1
  47. package/dist/commands/sys/signin.js +6 -3
  48. package/dist/core/command.d.ts +1 -2
  49. package/dist/core/command.js +6 -6
  50. package/dist/core/grants/sync.js +1 -1
  51. package/dist/core/human/requests.d.ts +2 -0
  52. package/dist/core/human/requests.js +18 -18
  53. package/dist/core/ledger/check.d.ts +6 -2
  54. package/dist/core/ledger/check.js +1 -1
  55. package/dist/core/llm/run.js +2 -2
  56. package/dist/core/providers/call.js +1 -1
  57. package/dist/core/runtime/broker/cli-relay.d.ts +0 -2
  58. package/dist/core/runtime/broker/cli-relay.js +1 -1
  59. package/dist/core/runtime/broker/run-turn-queue.js +1 -1
  60. package/dist/core/runtime/broker/turn-cause.d.ts +2 -0
  61. package/dist/core/runtime/broker/turn-cause.js +1 -1
  62. package/dist/core/runtime/first-run-offer.d.ts +2 -6
  63. package/dist/core/runtime/first-run-offer.js +2 -10
  64. package/dist/core/runtime/front-door.js +8 -9
  65. package/dist/core/runtime/start-refusal-notice.d.ts +5 -0
  66. package/dist/core/runtime/start-refusal-notice.js +1 -0
  67. package/dist/core/scoped-state/seed-terminal-defaults.d.ts +2 -0
  68. package/dist/core/scoped-state/seed-terminal-defaults.js +1 -0
  69. package/dist/daemon/api/handlers/inbox.js +1 -1
  70. package/dist/daemon/api/router.js +1 -1
  71. package/dist/daemon/cron-run.js +2 -2
  72. package/dist/daemon/fleet.js +5 -5
  73. package/dist/daemon/machine-link/config.d.ts +2 -4
  74. package/dist/daemon/machine-link/config.js +4 -4
  75. package/dist/daemon/manage.js +2 -2
  76. package/dist/daemon/postgres/cluster.d.ts +3 -3
  77. package/dist/daemon/postgres/cluster.js +5 -5
  78. package/dist/daemon/postgres/supervisor.js +1 -1
  79. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  80. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  81. package/docs/apps/cli.md +1 -1
  82. package/docs/apps/coding-agents.md +1 -1
  83. package/docs/apps/get-started.md +2 -2
  84. package/docs/apps/guides/watchable-objects.md +1 -1
  85. package/docs/apps/how-it-fits.md +1 -1
  86. package/docs/apps/let-their-ai-use-your-app.md +1 -4
  87. package/docs/apps/quickstart.md +1 -1
  88. package/docs/concepts/why-a-daemon.md +1 -1
  89. package/docs/sdk/README.md +3 -2
  90. package/docs/sdk/client.md +3 -3
  91. package/docs/sdk/docker.md +5 -9
  92. package/docs/sdk/release-notes.md +25 -3
  93. package/docs/sdk/sourcing.md +91 -0
  94. package/package.json +3 -3
  95. package/packages/crouter-api/dist/api/client.js +2 -2
  96. package/packages/crouter-api/dist/api/contract.js +1 -1
  97. package/packages/crouter-api/dist/api/dto/charges.js +1 -1
  98. package/packages/crouter-api/dist/daemon/machine-link/config.js +3 -5
  99. package/packages/crouter-api/dist/daemon/manage.js +3 -3
  100. package/packages/crouter-api/package.json +1 -1
  101. package/packages/crouter-identity/package.json +1 -1
  102. package/packages/crouter-plugin/package.json +3 -3
  103. package/runtime.lock.json +14 -14
  104. package/scripts/install-runtime.mjs +1 -1
  105. package/dist/commands/sys/panels/plugin-env-panel.d.ts +0 -19
  106. package/dist/commands/sys/panels/plugin-env-panel.js +0 -2
  107. package/dist/commands/sys/panels/plugins-panel.d.ts +0 -16
  108. package/dist/commands/sys/panels/plugins-panel.js +0 -1
  109. package/dist/core/northlight/previews.d.ts +0 -22
  110. package/dist/core/northlight/previews.js +0 -1
  111. package/dist/core/runtime/front-door-login.d.ts +0 -2
  112. package/dist/core/runtime/front-door-login.js +0 -1
@@ -1,9 +1,9 @@
1
- var re=Object.defineProperty;var a=(e,t)=>re(e,"name",{value:t,configurable:!0});import{spawn as ie,spawnSync as se}from"node:child_process";import{homedir as w,tmpdir as ae}from"node:os";import{mkdtempSync as oe,rmSync as ce}from"node:fs";import{piAgentDir as I}from"../../core/runtime/package-health.js";import{basename as ue,dirname as _,join as m,relative as le,resolve as de}from"node:path";import{isDeepStrictEqual as b}from"node:util";import{BINDING_CATALOG as pe,normalizeGesture as fe,splitGestureExpression as he,inboxShortcut as me,resolveKeybindings as S}from"../../core/keybindings/index.js";import{builtinPiPackageDir as ge}from"../../core/scope.js";import{atomicWriteJson as ke,readJsonIfExists as ve,readJsonOrNull as L}from"../../core/fs-utils.js";import{resolveBundledPiCliPath as be}from"../../core/runtime/pi-cli.js";import{crtrVersion as we}from"../../shared/crtr-version.js";import{installTmuxBindings as ye}from"../../core/runtime/tmux-chrome.js";import{normalizeTmuxPassthrough as xe}from"../../core/config.js";import{detectNerdFont as Pe,nerdFontInstallCommand as Ie,createCurlPercentReader as Se,NERD_FONT_MANUAL_LINUX_COMMAND as Ce,NERD_FONT_SELECT_HINT as Ee}from"../../core/runtime/nerd-font.js";import{startProgressBar as $e}from"../../core/runtime/progress-bar.js";import{ensureRenderer as Ae,isRendererReady as K}from"../../core/termrender/termrender.js";import{installFromMarketplace as Re,isMarketplaceRelativeSource as De}from"../pkg/plugin-manage.js";import{requiredPluginEnv as Te}from"../../core/plugin-env.js";import{readPluginManifest as Me}from"../../core/manifest.js";import{addMarketplace as j}from"../pkg/market-manage.js";import{clone as Ne}from"../../core/git.js";import{readMarketplaceManifest as Oe}from"../../core/manifest.js";import{findPluginByName as F,findMarketplaceByName as C}from"../../core/resolver.js";import{expandTilde as _e}from"../../core/fs-utils.js";import{applyTerminalEdit as Le}from"./terminal-option.js";const E="crouter-official-marketplace",$="https://github.com/crouton-labs/crouter-official-marketplace.git",A="main";function Pt(e){const t=[],n=new Set,r=new Map;try{for(const o of e){if(o.sourceKind!=="marketplace-plugin")continue;const[u,c]=o.installSource.split("/");if(!u||!c)continue;const l=F(c,"user")?.manifest;let d=C(u,"user");if(!d&&!l&&u===E)try{let i=r.get(u);i||(i=oe(m(ae(),"crtr-setup-market-")),r.set(u,i),Ne($,m(i,"checkout"),{ref:A,depth:1}));const p=m(i,"checkout"),v=Oe(p);v&&(d={root:p,manifest:v})}catch{}const h=d?.manifest.plugins.find(i=>i.name===c)?.source,f=h&&De(h)?Me(m(d.root,h))??l:l;if(f)for(const i of Te(f.env))n.has(i)||(n.add(i),t.push({name:i,plugin:c,declaration:f.env[i]}))}}finally{for(const o of r.values())ce(o,{recursive:!0,force:!0})}return t}a(Pt,"setupPluginEnvFields");function G(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}a(G,"isKeybindingsObject");function g(e){return G(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?[...n]:n])):{}}a(g,"cloneKeybindings");class It{static{a(this,"SetupKeybindingsDraft")}expected;baseline;current;baselineInvalidRoot;invalidRoot;resolutionCache;expectedPassthrough;baselinePassthrough;currentPassthrough;constructor(t,n=void 0){this.expected=t,this.baseline=g(t),this.current=g(t),this.baselineInvalidRoot=t!==void 0&&!G(t)?t:void 0,this.invalidRoot=this.baselineInvalidRoot,this.expectedPassthrough=n,this.baselinePassthrough=xe(n),this.currentPassthrough=[...this.baselinePassthrough]}get dirty(){return!b(this.current,this.baseline)||!b(this.invalidRoot,this.baselineInvalidRoot)||!b(this.currentPassthrough,this.baselinePassthrough)}overrides(){return g(this.current)}expectedKeybindings(){return this.expected}tmuxPassthrough(){return[...this.currentPassthrough]}expectedTmuxPassthrough(){return this.expectedPassthrough}usesTmuxPassthrough(t){return this.currentPassthrough.includes(t)}toggleTmuxPassthrough(t){this.currentPassthrough=this.currentPassthrough.includes(t)?this.currentPassthrough.filter(n=>n!==t):[...this.currentPassthrough,t]}resolution(){return this.resolutionCache===void 0&&(this.resolutionCache=S(this.invalidRoot===void 0?this.current:this.invalidRoot)),this.resolutionCache}hasInvalidRoot(){return this.invalidRoot!==void 0}expression(t){return this.resolution().gestures(t).join(", ")}edit(t,n){if(this.invalidRoot!==void 0)return{ok:!1,diagnostics:[{severity:"error",code:"invalid-keybindings",offendingValue:this.invalidRoot,message:"Reset all before editing: the saved keybindings root is invalid."}]};const r=pe.find(f=>f.id===t);let o;try{o=n.trim()===""?[]:he(n).map(f=>fe(f.trim(),r))}catch(f){return{ok:!1,diagnostics:[{severity:"error",code:"invalid-override",bindingId:t,offendingValue:n,message:f instanceof Error?f.message:String(f)}]}}const u=[...new Set(o)],c={...this.current};delete c[t];const l=[...S(c).gestures(t)],s=b(u,l)?c:{...this.current,[t]:u},d=S(s),h=d.diagnostics.filter(f=>f.bindingId===t||f.relatedBindingIds?.includes(t));return h.length>0?{ok:!1,diagnostics:h}:(this.current=s,this.resolutionCache=void 0,{ok:!0,diagnostics:d.diagnostics})}unbind(t){return this.edit(t,"")}resetRow(t){delete this.current[t],this.resolutionCache=void 0}resetAll(){this.current={},this.currentPassthrough=[],this.invalidRoot=void 0,this.resolutionCache=void 0}discard(){this.current=g(this.baseline),this.currentPassthrough=[...this.baselinePassthrough],this.invalidRoot=this.baselineInvalidRoot,this.resolutionCache=void 0}markSaved(t,n=[]){this.expected=Object.keys(t).length===0?void 0:g(t),this.baseline=g(t),this.current=g(t),this.expectedPassthrough=[...n],this.baselinePassthrough=[...n],this.currentPassthrough=[...n],this.baselineInvalidRoot=void 0,this.invalidRoot=void 0,this.resolutionCache=void 0}}const Ke={"official-marketplace":{name:E,shortDescription:"the official crtr plugin catalog \u2014 registered as a source so its plugins are installable by ref.",longDescription:"Shallow-clones github.com/crouton-labs/crouter-official-marketplace into the user scope and registers it, which is what makes `crtr pkg plugin install crouter-official-marketplace/<name>` resolve and what fills `crtr pkg market browse`. Registering the source installs no plugin by itself. Uncheck it on a machine that should reach no external catalog \u2014 a plugin selected below still registers the marketplace it comes from, because its ref cannot resolve otherwise."},"crtr-extensions":{name:"pi-crtr-extensions",shortDescription:"crtr companion extensions \u2014 command palette, help gating, subscription/OAuth rotation, nested context.",longDescription:"Bundles the extensions built for crtr: a crtr slash-command palette, crtr/crouter help gating, surfacing of Claude Code marketplace plugin commands, nested AGENTS.md/CLAUDE.md loading, OAuth login + rotation across multiple Claude subscriptions (provider-rotation), and system-prompt trimming. The OAuth/rotation piece is what lets crtr authenticate your Claude account."},"oauth-adapter":{name:"pi-claude-oauth-adapter",shortDescription:"Anthropic OAuth / Claude Code credential compatibility for pi.",longDescription:"Third-party adapter (minzique/dotfiles-agents) letting pi authenticate with Claude using Claude Code OAuth credentials. Installed from npm, pinned to 0.2.2."},"capture-plugin":{name:"capture",shortDescription:"crtr plugin mounting `crtr capture` \u2014 browser automation and UI measurement over CDP.",longDescription:"Installs the `capture` plugin from the official crtr marketplace. It mounts `crtr capture` as a transparent passthrough to the external Capture CLI (`npm install -g @crouton-kit/capture`) for CDP screenshots, rendered-geometry measurement, HAR, accessibility trees, and JS execution against a live page. Uncheck it on a machine where agents never drive a browser \u2014 the command then costs nothing in their root prompt."},"dev-plugin":{name:"dev",shortDescription:"crtr plugin mounting the development workflow \u2014 repository setup, worktrees, pull requests, and a dev track in the tutorial.",longDescription:"Installs the dev plugin from the official crtr marketplace. It adds the /dev: workflow commands (init, spec, design, plan, pr-loop), mounts crtr dev for a repository's own lifecycle commands and Grove instances, and contributes the crtr sys tutorial dev track. Uncheck it on a machine whose agents do not work in source repositories."}},R={"official-marketplace":{kind:"marketplace-source",source:$},"crtr-extensions":{kind:"local-path",source:U("pi-crtr-extensions")},"oauth-adapter":{kind:"npm",source:"npm:pi-claude-oauth-adapter@0.2.2"},"capture-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/capture"},"dev-plugin":{kind:"marketplace-plugin",source:"crouter-official-marketplace/dev"}},B=["extensions/*.ts","extensions/*/index.ts","!extensions/**/*.d.ts"],je={"official-marketplace":[],"crtr-extensions":["pi-crtr-extensions"],"oauth-adapter":[],"capture-plugin":[],"dev-plugin":[]};function U(e){return ge(e)}a(U,"selectedPiPackageDir");function D(e=U){return["official-marketplace","crtr-extensions","oauth-adapter","capture-plugin","dev-plugin"].map(t=>{const n=Ke[t],r=R[t].kind==="local-path"?e(n.name):R[t].source;return{id:t,name:n.name,sourceKind:R[t].kind,installSource:r,shortDescription:n.shortDescription,longDescription:n.longDescription}})}a(D,"buildSetupManifest");function St(e){switch(e.sourceKind){case"marketplace-source":return`clone + register ${e.installSource}`;case"marketplace-plugin":return`crtr pkg plugin install ${e.installSource}`;default:return`pi install ${e.installSource}`}}a(St,"packagePlanAction");function Fe(e){if(!e.startsWith("npm:"))return null;const t=e.slice(4),n=t.startsWith("@")?t.indexOf("@",1):t.lastIndexOf("@");return n>0?t.slice(0,n):t}a(Fe,"npmPackageName");function y(e,t,n){const r=Fe(e);if(r!==null)return`npm:${r}`;const o=_e(e,n);return de(t,o)}a(y,"normalizePackageIdentity");function x(e){return`package:${e}`}a(x,"packageNameIdentity");function z(e){return e.startsWith("npm:")?[]:[x(ue(e))]}a(z,"localPackageNameIdentities");function Ge(e,t,n){const r=[y(e.installSource,t,n)];if(e.sourceKind==="local-path"){r.push(x(e.name));for(const o of je[e.id])r.push(x(o))}return r}a(Ge,"manifestIdentities");function Y(e,t=D(),n=m(I(),"settings.json"),r=w()){const o=_(n),u=new Set,c=new Map;for(const s of t)for(const d of Ge(s,o,r))c.set(d,s.id);const l=e&&typeof e=="object"?e.packages:void 0;if(!Array.isArray(l))return u;for(const s of l){const d=typeof s=="string"?s:s&&typeof s=="object"&&typeof s.source=="string"?s.source:null;if(d===null)continue;const h=[y(d,o,r),...z(d)];for(const f of h){const i=c.get(f);if(i==="crtr-extensions"){const p=t.find(v=>v.id===i);if(y(d,o,r)!==y(p.installSource,o,r)||!s||typeof s!="object"||!b(s.extensions,B))continue}i!==void 0&&u.add(i)}}return u}a(Y,"detectInstalledSetupPackageIds");function k(e){return se("sh",["-lc",`command -v ${e} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}a(k,"detectCommandOnPath");function Be(e=process.platform,t=k){switch(e){case"darwin":return t("brew")?"brew":"manual";case"linux":return t("apt-get")?"apt-get":t("dnf")?"dnf":t("pacman")?"pacman":"manual";default:return"manual"}}a(Be,"detectPackageManager");function Ue(e,t,n=k){if(e==="nerd-font"?Pe().installed:n(e))return{tool:e,installed:!0,command:null,hint:"already installed",autoInstall:!1};if(e==="nerd-font"){const u=Ie(t);return{tool:e,installed:!1,command:u.command,hint:`${u.hint} \u2014 ${Ee}`,autoInstall:u.autoInstall}}const o=e==="nvim"?"neovim":"tmux";switch(t){case"brew":return{tool:e,installed:!1,command:`brew install ${o}`,hint:"Homebrew install",autoInstall:!0};case"apt-get":return{tool:e,installed:!1,command:`sudo apt-get update && sudo apt-get install -y ${o}`,hint:"apt-get install",autoInstall:!0};case"dnf":return{tool:e,installed:!1,command:`sudo dnf install -y ${o}`,hint:"dnf install",autoInstall:!0};case"pacman":return{tool:e,installed:!1,command:`sudo pacman -S --noconfirm ${o}`,hint:"pacman install",autoInstall:!0};default:return{tool:e,installed:!1,command:null,hint:`manual install required for ${e}`,autoInstall:!1}}}a(Ue,"buildSystemInstallPlan");function T(e=w()){return m(e===w()?I():m(e,".pi","agent"),"settings.json")}a(T,"resolveSettingsPath");function Ct(e={}){const t=e.homeDir??w(),n=e.settingsPath??T(t),r=e.manifest??D(),o=ve(n),u=Y(o,r,n,t);for(const d of X(r))u.add(d);const c=e.commandExists??k,l=e.packageManager??Be(process.platform,c),s=["tmux","nvim","nerd-font"].map(d=>Ue(d,l,c));return{manifest:r,installedPackageIds:u,systemPlans:s}}a(Ct,"buildSetupInitialState");function Et(e){const t=e.manifest.map(r=>{const o=e.installedPackageIds.has(r.id)?"installed":"not installed";return`- ${r.name} \u2014 ${r.shortDescription} (${o})`}),n=e.systemPlans.map(r=>r.installed?`- ${r.tool}: \u2713 installed`:r.command?`- ${r.tool}: ${r.command}`:`- ${r.tool}: ${r.hint}`);return["crtr sys setup (non-interactive)","","Provider login: open the wizard in a TTY and use the Providers tab (same flow as /login) to authenticate a model provider.","","Packages:",...t,"","System deps:",...n,"",`Inbox: the inbox-toggle key (${me()??"disabled"}) is a crouter keybinding \u2014 view or rebind it in \`crtr sys settings\`; it is installed on the same tmux server as every other crouter binding.`,"Run `crtr sys setup` in a TTY to open the wizard."].join(`
1
+ var T=Object.defineProperty;var r=(e,t)=>T(e,"name",{value:t,configurable:!0});import{spawn as N,spawnSync as O}from"node:child_process";import{isDeepStrictEqual as g}from"node:util";import{BINDING_CATALOG as A,normalizeGesture as D,splitGestureExpression as F,inboxShortcut as j,resolveKeybindings as y}from"../../core/keybindings/index.js";import{installTmuxBindings as _}from"../../core/runtime/tmux-chrome.js";import{normalizeTmuxPassthrough as L}from"../../core/config.js";import{detectNerdFont as M,nerdFontInstallCommand as B,createCurlPercentReader as G,NERD_FONT_MANUAL_LINUX_COMMAND as z,NERD_FONT_SELECT_HINT as Y}from"../../core/runtime/nerd-font.js";import{startProgressBar as q}from"../../core/runtime/progress-bar.js";import{ensureRenderer as H,isRendererReady as w}from"../../core/termrender/termrender.js";import{applyTerminalEdit as K}from"./terminal-option.js";function x(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}r(x,"isKeybindingsObject");function f(e){return x(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Array.isArray(n)?[...n]:n])):{}}r(f,"cloneKeybindings");class ct{static{r(this,"SetupKeybindingsDraft")}expected;baseline;current;baselineInvalidRoot;invalidRoot;resolutionCache;expectedPassthrough;baselinePassthrough;currentPassthrough;constructor(t,n=void 0){this.expected=t,this.baseline=f(t),this.current=f(t),this.baselineInvalidRoot=t!==void 0&&!x(t)?t:void 0,this.invalidRoot=this.baselineInvalidRoot,this.expectedPassthrough=n,this.baselinePassthrough=L(n),this.currentPassthrough=[...this.baselinePassthrough]}get dirty(){return!g(this.current,this.baseline)||!g(this.invalidRoot,this.baselineInvalidRoot)||!g(this.currentPassthrough,this.baselinePassthrough)}overrides(){return f(this.current)}expectedKeybindings(){return this.expected}tmuxPassthrough(){return[...this.currentPassthrough]}expectedTmuxPassthrough(){return this.expectedPassthrough}usesTmuxPassthrough(t){return this.currentPassthrough.includes(t)}toggleTmuxPassthrough(t){this.currentPassthrough=this.currentPassthrough.includes(t)?this.currentPassthrough.filter(n=>n!==t):[...this.currentPassthrough,t]}resolution(){return this.resolutionCache===void 0&&(this.resolutionCache=y(this.invalidRoot===void 0?this.current:this.invalidRoot)),this.resolutionCache}hasInvalidRoot(){return this.invalidRoot!==void 0}expression(t){return this.resolution().gestures(t).join(", ")}edit(t,n){if(this.invalidRoot!==void 0)return{ok:!1,diagnostics:[{severity:"error",code:"invalid-keybindings",offendingValue:this.invalidRoot,message:"Reset all before editing: the saved keybindings root is invalid."}]};const o=A.find(d=>d.id===t);let s;try{s=n.trim()===""?[]:F(n).map(d=>D(d.trim(),o))}catch(d){return{ok:!1,diagnostics:[{severity:"error",code:"invalid-override",bindingId:t,offendingValue:n,message:d instanceof Error?d.message:String(d)}]}}const u=[...new Set(s)],a={...this.current};delete a[t];const c=[...y(a).gestures(t)],l=g(u,c)?a:{...this.current,[t]:u},m=y(l),h=m.diagnostics.filter(d=>d.bindingId===t||d.relatedBindingIds?.includes(t));return h.length>0?{ok:!1,diagnostics:h}:(this.current=l,this.resolutionCache=void 0,{ok:!0,diagnostics:m.diagnostics})}unbind(t){return this.edit(t,"")}resetRow(t){delete this.current[t],this.resolutionCache=void 0}resetAll(){this.current={},this.currentPassthrough=[],this.invalidRoot=void 0,this.resolutionCache=void 0}discard(){this.current=f(this.baseline),this.currentPassthrough=[...this.baselinePassthrough],this.invalidRoot=this.baselineInvalidRoot,this.resolutionCache=void 0}markSaved(t,n=[]){this.expected=Object.keys(t).length===0?void 0:f(t),this.baseline=f(t),this.current=f(t),this.expectedPassthrough=[...n],this.baselinePassthrough=[...n],this.currentPassthrough=[...n],this.baselineInvalidRoot=void 0,this.invalidRoot=void 0,this.resolutionCache=void 0}}function b(e){return O("sh",["-lc",`command -v ${e} >/dev/null 2>&1`],{stdio:"ignore"}).status===0}r(b,"detectCommandOnPath");function U(e=process.platform,t=b){switch(e){case"darwin":return t("brew")?"brew":"manual";case"linux":return t("apt-get")?"apt-get":t("dnf")?"dnf":t("pacman")?"pacman":"manual";default:return"manual"}}r(U,"detectPackageManager");function V(e,t,n=b){if(e==="nerd-font"?M().installed:n(e))return{tool:e,installed:!0,command:null,hint:"already installed",autoInstall:!1};if(e==="nerd-font"){const u=B(t);return{tool:e,installed:!1,command:u.command,hint:`${u.hint} \u2014 ${Y}`,autoInstall:u.autoInstall}}const s=e==="nvim"?"neovim":e;switch(t){case"brew":return{tool:e,installed:!1,command:`brew install ${s}`,hint:"Homebrew install",autoInstall:!0};case"apt-get":return{tool:e,installed:!1,command:`sudo apt-get update && sudo apt-get install -y ${s}`,hint:"apt-get install",autoInstall:!0};case"dnf":return{tool:e,installed:!1,command:`sudo dnf install -y ${s}`,hint:"dnf install",autoInstall:!0};case"pacman":return{tool:e,installed:!1,command:`sudo pacman -S --noconfirm ${s}`,hint:"pacman install",autoInstall:!0};default:return{tool:e,installed:!1,command:null,hint:`manual install required for ${e}`,autoInstall:!1}}}r(V,"buildSystemInstallPlan");function ht(e={}){const t=e.commandExists??b,n=e.packageManager??U(process.platform,t);return{systemPlans:["tmux","nvim","nerd-font","uv"].map(s=>V(s,n,t))}}r(ht,"buildSetupInitialState");function ft(e){return["crtr sys setup (non-interactive)","","Sign in: run `crtr sys signin` (or open the wizard in a TTY) to sign this computer in to Northlight. Your account holds the model access, agents and plugins; this computer runs their commands.","","System deps:",...e.systemPlans.map(n=>n.installed?`- ${n.tool}: \u2713 installed`:n.command?`- ${n.tool}: ${n.command}`:`- ${n.tool}: ${n.hint}`),"",`Inbox: the inbox-toggle key (${j()??"disabled"}) is a crouter keybinding \u2014 view or rebind it in \`crtr sys settings\`; it is installed on the same tmux server as every other crouter binding.`,"Run `crtr sys setup` in a TTY to open the wizard."].join(`
2
2
  `)+`
3
- `}a(Et,"renderSetupStaticInstructions");class P extends Error{static{a(this,"SetupCommandError")}output;constructor(t,n){super(t),this.output=n}}function $t(e){return`${e.stdout?.toString()??""}${e.stderr?.toString()??""}`}a($t,"commandOutput");function q(e,t,n,r=process.env){return new Promise((o,u)=>{const c=ie(e,t,{stdio:["ignore","pipe","pipe"],env:r});let l="";c.stdout.setEncoding("utf8"),c.stderr.setEncoding("utf8"),c.stdout.on("data",s=>{l+=s}),c.stderr.on("data",s=>{l+=s,n?.(s)}),c.on("error",s=>u(new P(`${e} failed: ${s.message}`,l))),c.on("close",s=>{s===0?o():u(new P(`${e} failed with status ${s??"unknown"}`,l))})})}a(q,"runCapturedCommand");function M(e,t){return q("sh",["-lc",e],t)}a(M,"runShellCommand");function ze(e,t=be()){return q(process.execPath,[t,"install",e],void 0,{...process.env,PI_CODING_AGENT_DIR:I()})}a(ze,"installPiPackage");async function W(){k("capture")||await M("npm install -g @crouton-kit/capture")}a(W,"installCaptureCliIfMissing");function H(e){return e instanceof P?e.output:void 0}a(H,"capturedFailureOutput");function Ye(e){const n=H(e)?.split(/\r?\n/).find(r=>r.trim()!=="");return n!==void 0?n.trim():e instanceof Error?e.message:String(e)}a(Ye,"firstFailureLine");function qe(e){const t=H(e);t===void 0||t.length===0||process.stderr.write(t.endsWith(`
3
+ `}r(ft,"renderSetupStaticInstructions");class v extends Error{static{r(this,"SetupCommandError")}output;constructor(t,n){super(t),this.output=n}}function pt(e){return`${e.stdout?.toString()??""}${e.stderr?.toString()??""}`}r(pt,"commandOutput");function W(e,t,n,o=process.env){return new Promise((s,u)=>{const a=N(e,t,{stdio:["ignore","pipe","pipe"],env:o});let c="";a.stdout.setEncoding("utf8"),a.stderr.setEncoding("utf8"),a.stdout.on("data",l=>{c+=l}),a.stderr.on("data",l=>{c+=l,n?.(l)}),a.on("error",l=>u(new v(`${e} failed: ${l.message}`,c))),a.on("close",l=>{l===0?s():u(new v(`${e} failed with status ${l??"unknown"}`,c))})})}r(W,"runCapturedCommand");function I(e,t){return W("sh",["-lc",e],t)}r(I,"runShellCommand");function R(e){return e instanceof v?e.output:void 0}r(R,"capturedFailureOutput");function X(e){const n=R(e)?.split(/\r?\n/).find(o=>o.trim()!=="");return n!==void 0?n.trim():e instanceof Error?e.message:String(e)}r(X,"firstFailureLine");function J(e){const t=R(e);t===void 0||t.length===0||process.stderr.write(t.endsWith(`
4
4
  `)?t:`${t}
5
- `)}a(qe,"printCapturedFailure");class We{static{a(this,"SetupProgress")}interactive;bar=null;constructor(t=!!process.stdout.isTTY){this.interactive=t}start(t){return this.interactive?(this.bar=$e(`Installing ${t}\u2026`),this.bar):null}async clear(){await this.bar?.stop(),this.bar=null}async succeed(t){await this.clear(),this.interactive&&process.stdout.write(`\r\x1B[2K\u2713 ${t}
6
- `)}async fail(t,n){await this.clear(),this.interactive&&process.stdout.write(`\r\x1B[2K\u2717 ${t} \u2014 ${Ye(n)}
7
- `),qe(n)}async run(t,n){const r=this.start(t);try{const o=await n(r);return await this.succeed(t),o}catch(o){throw await this.fail(t,o),o}}}function J(e,t){return K()?"current":(e?.(),Ae(t),K()?"provisioned":"unavailable")}a(J,"ensureManagedRenderer");async function He(){try{ye()}catch{}}a(He,"reconcileInboxFrontDoor");function V(e,t){return t.length===0?[`${e}: none`]:[`${e}:`,...t.map(n=>` - ${n}`)]}a(V,"summarySection");function At(e){return["crtr sys setup complete",...V("installed",e.installed),...V("skipped",e.skipped),"New to crouter? Ask for the tutorial in your first conversation, or run /tutorial any time."].join(`
5
+ `)}r(J,"printCapturedFailure");class Q{static{r(this,"SetupProgress")}interactive;bar=null;constructor(t=!!process.stdout.isTTY){this.interactive=t}start(t){return this.interactive?(this.bar=q(`Installing ${t}\u2026`),this.bar):null}async clear(){await this.bar?.stop(),this.bar=null}async succeed(t){await this.clear(),this.interactive&&process.stdout.write(`\r\x1B[2K\u2713 ${t}
6
+ `)}async fail(t,n){await this.clear(),this.interactive&&process.stdout.write(`\r\x1B[2K\u2717 ${t} \u2014 ${X(n)}
7
+ `),J(n)}async run(t,n){const o=this.start(t);try{const s=await n(o);return await this.succeed(t),s}catch(s){throw await this.fail(t,s),s}}}function Z(e,t){return w()?"current":(e?.(),H(t),w()?"provisioned":"unavailable")}r(Z,"ensureManagedRenderer");async function tt(){try{_()}catch{}}r(tt,"reconcileInboxFrontDoor");function S(e,t){return t.length===0?[`${e}: none`]:[`${e}:`,...t.map(n=>` - ${n}`)]}r(S,"summarySection");function mt(e){return["crtr sys setup complete",...S("installed",e.installed),...S("skipped",e.skipped),"New to crouter? Ask for the tutorial in your first conversation, or run /tutorial any time."].join(`
8
8
  `)+`
9
- `}a(At,"formatSetupExecutionSummary");function X(e,t){const n=[];for(const r of e)try{r.sourceKind==="marketplace-source"?C(r.name,t)!==null&&n.push(r.id):r.sourceKind==="marketplace-plugin"&&F(r.name,t)!==null&&n.push(r.id)}catch{}return n}a(X,"detectInstalledMarketplaceEntries");async function Je(e,t="user"){if(C(e,t)!==null)return null;if(e!==E)throw new Error(`marketplace not registered: ${e}`);return await j({url:$,ref:A,scope:t}),e}a(Je,"ensureMarketplaceRegistered");function Ve(e){const t=T(),n=L(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`invalid pi settings: ${t}`);const r=n.packages;if(!Array.isArray(r))throw new Error(`invalid pi packages: ${t}`);const o=a(l=>{const s=typeof l=="string"?l:l&&typeof l=="object"?l.source:void 0;return typeof s=="string"&&z(s).includes(x("pi-crtr-extensions"))},"isCrtrExtensions"),u=r.findIndex(o),c=r.filter(l=>!o(l));c.splice(u<0?c.length:u,0,{source:le(_(t),e),extensions:B}),ke(t,{...n,packages:c})}a(Ve,"configureCrtrExtensions");const Q="git is not installed \u2014 install it (Debian/Ubuntu: apt-get install git), then run `crtr sys setup`";function Z(e){return e.sourceKind==="marketplace-source"||e.sourceKind==="marketplace-plugin"}a(Z,"isMarketplaceEntry");async function ee(e){if(e.sourceKind==="marketplace-source")return await j({url:e.installSource,ref:A,scope:"user"}),[e.name];if(e.sourceKind==="marketplace-plugin"){const[t,n]=e.installSource.split("/"),r=await Je(t);return await Re({marketplace:t,plugin:n},"user"),e.id==="capture-plugin"&&await W(),r===null?[e.name]:[r,e.name]}return await ze(e.installSource),e.id==="crtr-extensions"&&Ve(e.installSource),[e.name]}a(ee,"installSetupPackage");async function Rt(e,t=k){const n=D(),r=Y(L(T()),n);for(const s of X(n,"user"))r.add(s);const o=new Map(n.map(s=>[s.id,s])),u=process.stdin.isTTY&&process.stdout.isTTY?["crtr-extensions","official-marketplace","oauth-adapter","capture-plugin"]:["crtr-extensions","official-marketplace","capture-plugin"];let c,l=!1;for(const s of u){const d=o.get(s);if(!r.has(s)){if(Z(d)&&(c??=!t("git"),c)){l||e("marketplace packages",new Error(Q)),l=!0;continue}try{await ee(d)}catch(h){e(d.name,h)}}}try{J(void 0,()=>{})==="unavailable"&&e("termrender renderer",new Error("unavailable \u2014 install uv"))}catch(s){e("termrender renderer",s)}return we()}a(Rt,"reconcileFirstRun");async function Dt(e,t=k){const n=[],r=[],o=[],u=[],c=new We;let l,s=!1;for(const i of e.packages){if(e.installedPackageIds.has(i.id)){if(r.push(`${i.name} (already installed)`),i.id==="capture-plugin"&&!k("capture"))try{await c.run("Capture CLI",()=>W()),n.push("Capture CLI")}catch(p){r.push(`Capture CLI (${p instanceof Error?p.message:String(p)})`)}continue}if(Z(i)&&(l??=!t("git"),l)){s||r.push(`marketplace packages (${Q})`),s=!0;continue}try{n.push(...await c.run(i.name,()=>ee(i)))}catch(p){if(i.sourceKind!=="marketplace-source"&&i.sourceKind!=="marketplace-plugin")throw p;r.push(`${i.name} (${p instanceof Error?p.message:String(p)})`)}}for(const i of e.systemDeps){if(i.installed){u.push(`${i.tool} (already installed)`);continue}if(!i.autoInstall||!i.command){u.push(`${i.tool} (${i.hint})`);continue}const p=i.command,v=p===Ce;await c.run(i.tool,N=>{if(!v||N===null)return M(p);const te=Se();return M(p,ne=>{const O=te(ne);O!==null&&N.setFraction(O/100)})}),o.push(i.tool)}const d=[];let h=!1,f;try{f=J(()=>{h=!0,c.start("termrender renderer")},i=>d.push(i))}catch(i){throw h&&await c.fail("termrender renderer",i),i}switch(f){case"provisioned":h&&await c.succeed("termrender renderer"),n.push("termrender renderer");break;case"current":r.push("termrender renderer (current)");break;case"unavailable":{const i=new P("unavailable \u2014 install uv",d.join(""));h&&await c.fail("termrender renderer",i),r.push("termrender renderer (unavailable \u2014 install uv)");break}}if(e.terminalEdit!==void 0){const i=`Option as Alt (${e.terminalEdit.path})`,p=Le(e.terminalEdit);p.ok?n.push(`${i} \u2014 ${e.terminalEdit.reload}`):r.push(`${i} (${p.message})`)}return await He(),{installed:[...n,...o],skipped:[...r,...u]}}a(Dt,"executeSetupSubmission");export{E as OFFICIAL_MARKETPLACE_NAME,A as OFFICIAL_MARKETPLACE_REF,$ as OFFICIAL_MARKETPLACE_URL,It as SetupKeybindingsDraft,Ct as buildSetupInitialState,D as buildSetupManifest,Ue as buildSystemInstallPlan,k as detectCommandOnPath,Y as detectInstalledSetupPackageIds,Be as detectPackageManager,Dt as executeSetupSubmission,At as formatSetupExecutionSummary,y as normalizePackageIdentity,St as packagePlanAction,Rt as reconcileFirstRun,He as reconcileInboxFrontDoor,Et as renderSetupStaticInstructions,T as resolveSettingsPath,Pt as setupPluginEnvFields};
9
+ `}r(mt,"formatSetupExecutionSummary");async function gt(e,t=b){const n=[],o=[],s=[],u=[],a=new Q;let c,l=!1;for(const i of e.systemDeps){if(i.installed){u.push(`${i.tool} (already installed)`);continue}if(!i.autoInstall||!i.command){u.push(`${i.tool} (${i.hint})`);continue}const p=i.command,k=p===z;await a.run(i.tool,P=>{if(!k||P===null)return I(p);const C=G();return I(p,E=>{const $=C(E);$!==null&&P.setFraction($/100)})}),s.push(i.tool)}const m=[];let h=!1,d;try{d=Z(()=>{h=!0,a.start("termrender renderer")},i=>m.push(i))}catch(i){throw h&&await a.fail("termrender renderer",i),i}switch(d){case"provisioned":h&&await a.succeed("termrender renderer"),n.push("termrender renderer");break;case"current":o.push("termrender renderer (current)");break;case"unavailable":{const i=new v("unavailable \u2014 install uv",m.join(""));h&&await a.fail("termrender renderer",i),o.push("termrender renderer (unavailable \u2014 install uv)");break}}if(e.terminalEdit!==void 0){const i=`Option as Alt (${e.terminalEdit.path})`,p=K(e.terminalEdit);p.ok?n.push(`${i} \u2014 ${e.terminalEdit.reload}`):o.push(`${i} (${p.message})`)}return await tt(),{installed:[...n,...s],skipped:[...o,...u]}}r(gt,"executeSetupSubmission");export{ct as SetupKeybindingsDraft,ht as buildSetupInitialState,V as buildSystemInstallPlan,b as detectCommandOnPath,U as detectPackageManager,gt as executeSetupSubmission,mt as formatSetupExecutionSummary,tt as reconcileInboxFrontDoor,ft as renderSetupStaticInstructions};
@@ -1,16 +1,12 @@
1
- import { ModelRegistry, ModelRuntime } from '@earendil-works/pi-coding-agent';
2
- import { TUI, type Component, type Focusable } from '@earendil-works/pi-tui';
1
+ import { type Component, type Focusable } from '@earendil-works/pi-tui';
3
2
  import { type BindingId, type BindingResolution } from '../../core/keybindings/index.js';
4
- import { type SetupPackageId, type SetupPackageManifestEntry, type SetupSubmission, type SetupSystemInstallPlan } from './setup-core.js';
3
+ import { type SetupSubmission, type SetupSystemInstallPlan } from './setup-core.js';
5
4
  import { type OptionAsAltPlan } from './terminal-option.js';
6
5
  /** The host owns step navigation, focus, submission and composition. Each step
7
6
  * owns its own mutable UI state. */
8
7
  export declare class SetupWizard implements Component, Focusable {
9
8
  private readonly bindings;
10
9
  private readonly terminalRows;
11
- private readonly providers;
12
- private readonly plugins;
13
- private readonly pluginEnv;
14
10
  private readonly dependencies;
15
11
  private readonly terminal;
16
12
  private readonly steps;
@@ -20,12 +16,12 @@ export declare class SetupWizard implements Component, Focusable {
20
16
  private cachedHeight;
21
17
  private cachedLines;
22
18
  private _focused;
23
- private readonly installedPackageIds;
24
19
  onSubmit?: (submission: SetupSubmission) => void;
25
20
  onCancel?: () => void;
26
- constructor(manifest: SetupPackageManifestEntry[], installedPackageIds: Set<SetupPackageId>, systemPlans: SetupSystemInstallPlan[], tui: TUI, agentDir: string, runtime: ModelRuntime, registry: ModelRegistry, bindings: BindingResolution<BindingId>, terminalRows: () => number, existingEnvNames: Set<string>, optionPlan?: OptionAsAltPlan | null);
21
+ constructor(systemPlans: SetupSystemInstallPlan[], bindings: BindingResolution<BindingId>, terminalRows: () => number, optionPlan?: OptionAsAltPlan | null);
27
22
  set focused(value: boolean);
28
23
  get focused(): boolean;
24
+ dispose(): void;
29
25
  invalidate(): void;
30
26
  private matches;
31
27
  private label;
@@ -36,7 +32,6 @@ export declare class SetupWizard implements Component, Focusable {
36
32
  /** Enter on a non-final step walks forward; on the last one it finishes. */
37
33
  private advance;
38
34
  private cancel;
39
- dispose(): void;
40
35
  private hasPendingInstalls;
41
36
  private buildSubmission;
42
37
  private finalize;
@@ -1 +1,2 @@
1
- var P=Object.defineProperty;var p=(h,e)=>P(h,"name",{value:e,configurable:!0});import{matchesKey as b,truncateToWidth as o,visibleWidth as g}from"@earendil-works/pi-tui";import{formatGesture as v,formatMovePair as k,matchesPiTuiInput as $}from"../../core/keybindings/index.js";import{buildSetupInitialState as y,executeSetupSubmission as I,formatSetupExecutionSummary as w,packagePlanAction as A,reconcileInboxFrontDoor as x,renderSetupStaticInstructions as T,setupPluginEnvFields as C}from"./setup-core.js";import{runSetupSettingsProcess as W}from"./setup-settings-runner.js";import{DependenciesPanel as D}from"./panels/dependencies-panel.js";import{PAGE_CHROME_ROWS as F,pageFrame as L,theme as r}from"../../core/tui/panel.js";import{PluginsPanel as H}from"./panels/plugins-panel.js";import{ProviderPanel as O}from"./panels/provider-panel.js";import{PluginEnvPanel as _}from"./panels/plugin-env-panel.js";import{TerminalPanel as N}from"./panels/terminal-panel.js";import{describeEdit as R,planOptionAsAlt as z}from"./terminal-option.js";import{homedir as M}from"node:os";import{cliClient as S}from"../api-client.js";const E=["Providers","Plugins","Plugin env","Dependencies"],j="Option key";class B{static{p(this,"SetupWizard")}bindings;terminalRows;providers;plugins;pluginEnv;dependencies;terminal;steps;step=0;confirming=!1;cachedWidth;cachedHeight;cachedLines;_focused=!1;installedPackageIds;onSubmit;onCancel;constructor(e,i,t,n,s,c,a,l,f,m,d=null){this.bindings=l,this.terminalRows=f,this.installedPackageIds=i;const u=p(()=>this.invalidate(),"invalidate");this.providers=new O(n,s,c,a),this.providers.onChange=u,this.plugins=new H(e,i,u),this.pluginEnv=new _(m,u),this.dependencies=new D(t,u),this.terminal=d===null?void 0:new N(d,u),this.steps=this.terminal===void 0?E:[...E,j]}set focused(e){this._focused=e}get focused(){return this._focused}invalidate(){this.cachedWidth=void 0,this.cachedHeight=void 0,this.cachedLines=void 0}matches(e,i){return $(this.bindings,e,i,(t,n)=>b(t,n))}label(e){const i=this.bindings.gestures(e);return i.length===0?"disabled":v(i[0].split(" > ").pop())}fieldSafeLabel(e){const i=this.bindings.gestures(e).filter(t=>{if(t.includes(" > "))return!0;const n=t.split("+").pop();return!(n==="up"||n==="down"||n==="left"||n==="right")&&(n.length>1||t.includes("+"))});return i.length===0?"Disabled":i.map(v).join(" / ")}setStep(e){e===2&&this.step!==2&&this.pluginEnv.setFields(C(this.plugins.selected)),this.step=e,this.invalidate()}moveStep(e){this.setStep((this.step+e+this.steps.length)%this.steps.length)}advance(){this.step===this.steps.length-1?this.finalize():(this.step!==2||this.pluginEnv.complete)&&this.moveStep(1)}cancel(){if(this.confirming){this.confirming=!1,this.invalidate();return}this.onCancel?.()}dispose(){this.providers.dispose()}hasPendingInstalls(){return this.plugins.selected.some(e=>!this.installedPackageIds.has(e.id))||this.dependencies.selected.length>0||this.terminal?.selectedEdit!==void 0}buildSubmission(){return{packages:[...this.plugins.selected],installedPackageIds:new Set(this.installedPackageIds),systemDeps:[...this.dependencies.selected],pluginEnv:new Map(this.pluginEnv.values),...this.terminal?.selectedEdit===void 0?{}:{terminalEdit:this.terminal.selectedEdit}}}finalize(){if(this.confirming||!this.hasPendingInstalls()){this.onSubmit?.(this.buildSubmission());return}this.confirming=!0,this.invalidate()}currentPanel(){return this.step===0?this.providers:this.step===1?this.plugins:this.step===2?this.pluginEnv:this.step===3?this.dependencies:this.terminal}handleInput(e){const i=this.currentPanel(),t=p((s,c)=>this.matches(s,c),"match");if(this.step===0&&this.providers.isNestedFlowActive()){i.handleInput(e,t)&&this.invalidate();return}if(this.confirming){this.matches("crtr.setup.confirm.accept",e)?this.onSubmit?.(this.buildSubmission()):this.matches("crtr.setup.confirm.back",e)&&(this.confirming=!1,this.invalidate());return}if(this.step===2&&this.pluginEnv.handleInput(e)){this.invalidate();return}if(this.matches("crtr.setup.cancel",e)){this.cancel();return}if(this.matches("crtr.setup.tab-next",e)){if(this.step===2&&!this.pluginEnv.complete)return;this.moveStep(1);return}if(this.matches("crtr.setup.tab-previous",e)){this.moveStep(-1);return}if(i.handleInput(e,t)){this.invalidate();return}this.matches("crtr.setup.advance",e)&&this.advance()}renderTrail(e){const t=this.steps.map((n,s)=>{if(s===this.step)return r.bg("selectedBg",` ${s+1} ${n} `);const c=s<this.step?r.fg("success","\u2713"):`${s+1}`;return r.fg("dim",` ${c} ${n} `)}).join(r.fg("dim","\u203A"));return g(t)<=e?[o(t,e),""]:[o(`${r.fg("dim",`Step ${this.step+1} of ${this.steps.length}`)} ${r.fg("accent",r.bold(this.steps[this.step]))}`,e),""]}footer(e){const i=`${this.fieldSafeLabel("crtr.setup.tab-next")}/${this.fieldSafeLabel("crtr.setup.tab-previous")} step \xB7 ${this.label("crtr.setup.cancel")} cancel`,t=k(this.bindings,"crtr.setup.list-down","crtr.setup.list-up"),n=this.label("crtr.setup.advance");let s,c;if(this.confirming)s=`${this.label("crtr.setup.confirm.accept")} confirm \xB7 ${this.label("crtr.setup.confirm.back")} go back`;else if(this.step===0){const a=this.providers.isAddRowSelected()?`${n} add provider`:`${n} next`;s=this.providers.isNestedFlowActive()?"OAuth in progress \xB7 esc cancel":`${t} select \xB7 ${a} \xB7 a add \xB7 p prefer \xB7 r rename \xB7 l re-login \xB7 x remove`,this.providers.isNestedFlowActive()||(c=`${t} select \xB7 ${a} \xB7 a add \xB7 l re-login`)}else this.step===1?s=`${t} move \xB7 ${this.label("crtr.setup.toggle")} toggle \xB7 ${this.label("crtr.setup.details")} details \xB7 ${this.label("crtr.setup.advance")} next`:this.step===2?s=`type value \xB7 Enter save/skip \xB7 ${this.pluginEnv.complete?`${this.label("crtr.setup.advance")} next`:"complete keys to continue"}`:this.step===3?s=`${t} move \xB7 ${this.label("crtr.setup.toggle")} toggle \xB7 ${this.label("crtr.setup.advance")} ${this.steps.length>4?"next":"finish"}`:s=`${this.terminal?.canApply?`${this.label("crtr.setup.toggle")} apply for me \xB7 `:""}${this.label("crtr.setup.advance")} finish`;for(const a of c===void 0?[s]:[s,c]){const l=e-g(a)-g(i);if(l>=2)return`${r.fg("dim",a)}${" ".repeat(l)}${r.fg("dim",i)}`}return r.fg("dim",c??s)}renderConfirm(e){const i=this.buildSubmission(),t=[o(r.fg("warning",r.bold("Confirm installs")),e),""];if(i.packages.length===0&&i.systemDeps.length===0&&i.terminalEdit===void 0)return[...t,o(r.fg("success",`Nothing to install; ${this.label("crtr.setup.confirm.accept")} finish.`),e)];if(i.packages.length){t.push(o(r.fg("accent","Packages"),e));for(const n of i.packages)t.push(o(` \u2022 ${n.name} ${r.fg("dim","\u2192")} ${this.installedPackageIds.has(n.id)?r.fg("success","skip (already installed)"):r.fg("muted",A(n))}`,e))}if(i.systemDeps.length){t.push(o(r.fg("accent","System deps"),e));for(const n of i.systemDeps)t.push(o(` \u2022 ${n.tool} ${r.fg("dim","\u2192")} ${r.fg("muted",n.command??n.hint)}`,e))}if(i.terminalEdit!==void 0){t.push(o(r.fg("accent","Terminal config"),e));for(const n of R(i.terminalEdit))t.push(o(r.fg("muted",` ${n}`),e))}return t}render(e){const i=this.step===0,t=this.terminalRows();if(!i&&this.cachedLines&&this.cachedWidth===e&&this.cachedHeight===t)return this.cachedLines;const n=this.currentPanel(),s=Math.max(1,t-F),c=this.confirming||s<=2?[]:this.renderTrail(e),a=Math.max(1,s-c.length),l=L({width:e,height:t,title:"crouter setup",meta:this.confirming?"review":`step ${this.step+1} of ${this.steps.length}`,body:[...c,...this.confirming?this.renderConfirm(e):n.render(e,a)],footer:this.footer(e)});return i||(this.cachedWidth=e,this.cachedHeight=t,this.cachedLines=l),l}}function G(){process.stdout.write("\x1B[2J\x1B[H")}p(G,"clearWizardFrame");async function re(){const h=y();let e=!1;if(await x(),!process.stdout.isTTY)return process.stdout.write(T(h)),"skipped";const i=new Set((await S().listAppEnv()).names),t=await W(({tui:s,terminal:c,agentDir:a,runtime:l,registry:f,bindings:m},d)=>{const u=new B(h.manifest,h.installedPackageIds,h.systemPlans,s,a,l,f,m,()=>c.rows,i,z({env:process.env,platform:process.platform,home:M()}));return u.onCancel=d.cancel,u.onSubmit=d.submit,u},(s,c)=>s===""?(e=!0,!0):s.length>0&&s.charCodeAt(0)<32&&$(c,"crtr.setup.cancel",s,(a,l)=>b(a,l)));if(G(),e){const s=new Error("Interrupted");throw s.name="AbortError",s}if(t===void 0)return"skipped";for(const[s,c]of t.pluginEnv)await S().setAppEnv(s,c);const n=await I(t);return process.stdout.write(w(n)),"completed"}p(re,"runSetup");export{B as SetupWizard,re as runSetup};
1
+ var b=Object.defineProperty;var h=(u,t)=>b(u,"name",{value:t,configurable:!0});import{matchesKey as d,truncateToWidth as l,visibleWidth as p}from"@earendil-works/pi-tui";import{formatGesture as m,formatMovePair as S,matchesPiTuiInput as f}from"../../core/keybindings/index.js";import{buildSetupInitialState as $,executeSetupSubmission as v,formatSetupExecutionSummary as y,reconcileInboxFrontDoor as E,renderSetupStaticInstructions as P}from"./setup-core.js";import{runSetupSettingsProcess as w}from"./setup-settings-runner.js";import{DependenciesPanel as I}from"./panels/dependencies-panel.js";import{PAGE_CHROME_ROWS as T,pageFrame as C,theme as r}from"../../core/tui/panel.js";import{TerminalPanel as k}from"./panels/terminal-panel.js";import{describeEdit as A,planOptionAsAlt as D}from"./terminal-option.js";import{homedir as W}from"node:os";import{readMachineConfig as L}from"../../daemon/machine-link/config.js";import{defaultDirectoryUrl as x,registerFreshComputer as H}from"./signin.js";import{loadPersonSettingsViaApi as _}from"../person-settings.js";import{installAccountPlugins as O}from"../pkg/account-installs.js";const g=["Dependencies"],z="Option key";class M{static{h(this,"SetupWizard")}bindings;terminalRows;dependencies;terminal;steps;step=0;confirming=!1;cachedWidth;cachedHeight;cachedLines;_focused=!1;onSubmit;onCancel;constructor(t,n,s,i=null){this.bindings=n,this.terminalRows=s;const e=h(()=>this.invalidate(),"invalidate");this.dependencies=new I(t,e),this.terminal=i===null?void 0:new k(i,e),this.steps=this.terminal===void 0?g:[...g,z]}set focused(t){this._focused=t}get focused(){return this._focused}dispose(){}invalidate(){this.cachedWidth=void 0,this.cachedHeight=void 0,this.cachedLines=void 0}matches(t,n){return f(this.bindings,t,n,(s,i)=>d(s,i))}label(t){const n=this.bindings.gestures(t);return n.length===0?"disabled":m(n[0].split(" > ").pop())}fieldSafeLabel(t){const n=this.bindings.gestures(t).filter(s=>{if(s.includes(" > "))return!0;const i=s.split("+").pop();return!(i==="up"||i==="down"||i==="left"||i==="right")&&(i.length>1||s.includes("+"))});return n.length===0?"Disabled":n.map(m).join(" / ")}setStep(t){this.step=t,this.invalidate()}moveStep(t){this.setStep((this.step+t+this.steps.length)%this.steps.length)}advance(){this.step===this.steps.length-1?this.finalize():this.moveStep(1)}cancel(){if(this.confirming){this.confirming=!1,this.invalidate();return}this.onCancel?.()}hasPendingInstalls(){return this.dependencies.selected.length>0||this.terminal?.selectedEdit!==void 0}buildSubmission(){return{systemDeps:[...this.dependencies.selected],...this.terminal?.selectedEdit===void 0?{}:{terminalEdit:this.terminal.selectedEdit}}}finalize(){if(this.confirming||!this.hasPendingInstalls()){this.onSubmit?.(this.buildSubmission());return}this.confirming=!0,this.invalidate()}currentPanel(){return this.step===0?this.dependencies:this.terminal}handleInput(t){const n=this.currentPanel(),s=h((i,e)=>this.matches(i,e),"match");if(this.confirming){this.matches("crtr.setup.confirm.accept",t)?this.onSubmit?.(this.buildSubmission()):this.matches("crtr.setup.confirm.back",t)&&(this.confirming=!1,this.invalidate());return}if(this.matches("crtr.setup.cancel",t)){this.cancel();return}if(this.matches("crtr.setup.tab-next",t)){this.moveStep(1);return}if(this.matches("crtr.setup.tab-previous",t)){this.moveStep(-1);return}if(n.handleInput(t,s)){this.invalidate();return}this.matches("crtr.setup.advance",t)&&this.advance()}renderTrail(t){const s=this.steps.map((i,e)=>{if(e===this.step)return r.bg("selectedBg",` ${e+1} ${i} `);const c=e<this.step?r.fg("success","\u2713"):`${e+1}`;return r.fg("dim",` ${c} ${i} `)}).join(r.fg("dim","\u203A"));return p(s)<=t?[l(s,t),""]:[l(`${r.fg("dim",`Step ${this.step+1} of ${this.steps.length}`)} ${r.fg("accent",r.bold(this.steps[this.step]))}`,t),""]}footer(t){const n=`${this.fieldSafeLabel("crtr.setup.tab-next")}/${this.fieldSafeLabel("crtr.setup.tab-previous")} step \xB7 ${this.label("crtr.setup.cancel")} cancel`,s=S(this.bindings,"crtr.setup.list-down","crtr.setup.list-up"),i=this.label("crtr.setup.advance");let e;const c=void 0;this.confirming?e=`${this.label("crtr.setup.confirm.accept")} confirm \xB7 ${this.label("crtr.setup.confirm.back")} go back`:this.step===0?e=`${s} move \xB7 ${this.label("crtr.setup.toggle")} toggle \xB7 ${this.label("crtr.setup.advance")} ${this.steps.length>1?"next":"finish"}`:e=`${this.terminal?.canApply?`${this.label("crtr.setup.toggle")} apply for me \xB7 `:""}${this.label("crtr.setup.advance")} finish`;for(const a of c===void 0?[e]:[e,c]){const o=t-p(a)-p(n);if(o>=2)return`${r.fg("dim",a)}${" ".repeat(o)}${r.fg("dim",n)}`}return r.fg("dim",c??e)}renderConfirm(t){const n=this.buildSubmission(),s=[l(r.fg("warning",r.bold("Confirm installs")),t),""];if(n.systemDeps.length===0&&n.terminalEdit===void 0)return[...s,l(r.fg("success",`Nothing to install; ${this.label("crtr.setup.confirm.accept")} finish.`),t)];if(n.systemDeps.length){s.push(l(r.fg("accent","System deps"),t));for(const i of n.systemDeps)s.push(l(` \u2022 ${i.tool} ${r.fg("dim","\u2192")} ${r.fg("muted",i.command??i.hint)}`,t))}if(n.terminalEdit!==void 0){s.push(l(r.fg("accent","Terminal config"),t));for(const i of A(n.terminalEdit))s.push(l(r.fg("muted",` ${i}`),t))}return s}render(t){const s=this.terminalRows();if(this.cachedLines&&this.cachedWidth===t&&this.cachedHeight===s)return this.cachedLines;const i=this.currentPanel(),e=Math.max(1,s-T),c=this.confirming||e<=2?[]:this.renderTrail(t),a=Math.max(1,e-c.length),o=C({width:t,height:s,title:"crouter setup",meta:this.confirming?"review":`step ${this.step+1} of ${this.steps.length}`,body:[...c,...this.confirming?this.renderConfirm(t):i.render(t,a)],footer:this.footer(t)});return this.cachedWidth=t,this.cachedHeight=s,this.cachedLines=o,o}}function R(){process.stdout.write("\x1B[2J\x1B[H")}h(R,"clearWizardFrame");async function tt(){const u=$();let t=!1;if(await E(),!process.stdout.isTTY)return process.stdout.write(P(u)),"skipped";if(L()===void 0){const{account:e}=await H(x());process.stdout.write(`Signed in to Northlight as ${e}.
2
+ `),await _()}const n=await O(),s=await w(({terminal:e,bindings:c},a)=>{const o=new M(u.systemPlans,c,()=>e.rows,D({env:process.env,platform:process.platform,home:W()}));return o.onCancel=a.cancel,o.onSubmit=a.submit,o},(e,c)=>e===""?(t=!0,!0):e.length>0&&e.charCodeAt(0)<32&&f(c,"crtr.setup.cancel",e,(a,o)=>d(a,o)));if(R(),t){const e=new Error("Interrupted");throw e.name="AbortError",e}if(s===void 0)return"skipped";const i=await v(s);return i.installed.push(...n.installed.map(e=>`${e} (from your account)`)),i.skipped.push(...n.failed.map(e=>`${e.item} (${e.message})`)),process.stdout.write(y(i)),"completed"}h(tt,"runSetup");export{M as SetupWizard,tt as runSetup};
@@ -1 +1 @@
1
- var s=Object.defineProperty;var t=(e,n)=>s(e,"name",{value:n,configurable:!0});import{defineLeaf as a}from"../../core/command.js";const o="Valid CRTR_WARN_LIVE_BROKERS and CRTR_MAX_LIVE_BROKERS environment overrides take precedence over their corresponding configured limits.",c=a({name:"setup",description:"bootstrap a fresh machine \u2014 provider login, companion packages, system dependencies",whenToUse:"you need to re-run the first-launch installer \u2014 sign in to another provider, add companion packages or system dependencies, or repair package paths. A person never needs it to get started: the first bare `crtr` in a terminal opens this installer itself. Use sys settings to change configuration on an installed machine, and sys config set for scriptable edits.",help:{name:"sys setup",summary:"reopen the installer bare `crtr` runs on first launch: provider login, companion packages, system dependencies",inputNote:"No input parameters.",output:[],outputKind:"object",effects:["Opens a three-step pi-tui installer. Step one logs in to a model provider (pi's real OAuth/API-key flow, same as in-app /login) so a fresh install has credentials before running any node.","The remaining steps collect companion package installs and system dependency installs, then confirm them all at once.","On macOS, a final step detects the terminal and explains how to make Option act as Alt (crouter's menu is Alt+C). Where the setting is safely scriptable (Ghostty, stock VS Code) it can write the one line for you, but only if you tick it and after showing exactly what will be written.","Runs the bundled pi CLI to install the selected companion packages and prints a summary.","The companion-package list includes the official crtr marketplace and the plugins installed from it (currently `capture`), all checked by default and registered or installed into the user scope when left checked. Nothing else registers a marketplace, so an install that never runs setup fetches no catalog. An unreachable marketplace is reported as skipped rather than failing setup. Vendor credentials belong to the plugin that needs them, never to setup.","In a terminal, records setup as done (the same record the first bare `crtr` writes), so the next bare `crtr` boots a conversation instead of reopening the installer, and offers the tutorial if no conversation has started since setup first ran.","On every invocation (best-effort, idempotent), refreshes crouter-owned tmux bindings and registers known nodes' interaction roots so resolved tickets can call back into the asking node. The inbox popup toggle is a crouter-owned keybinding, editable on the keybindings tab."]},run:t(async()=>{const e=await(await import("./setup-wizard.js")).runSetup();process.stdout.isTTY&&await(await import("../../core/runtime/setup-marker.js")).recordSetupCompleted(e)},"run"),render:t(()=>"","render")});export{o as BROKER_LIMIT_OVERRIDE_PRECEDENCE,c as sysSetupLeaf};
1
+ var s=Object.defineProperty;var t=(e,n)=>s(e,"name",{value:n,configurable:!0});import{defineLeaf as i}from"../../core/command.js";const r="Valid CRTR_WARN_LIVE_BROKERS and CRTR_MAX_LIVE_BROKERS environment overrides take precedence over their corresponding configured limits.",c=i({name:"setup",description:"bootstrap this computer \u2014 sign in to Northlight, install the account's plugins, system dependencies",whenToUse:"you need to re-run the first-launch installer \u2014 sign in, pick up the account's plugins, or add system dependencies. A person never needs it to get started: the first bare `crtr` in a terminal opens this installer itself. Use sys settings to change configuration on an installed machine, and sys config set for scriptable edits.",help:{name:"sys setup",summary:"reopen the installer bare `crtr` runs on first launch: sign in to Northlight, the account's plugins, system dependencies",inputNote:"No input parameters.",output:[],outputKind:"object",effects:["Signs this computer in to the person's Northlight account when it is not yet (prints a code and opens the confirm page, same as `crtr sys signin`). Model access, agents and plugins belong to the account; this computer only runs their commands.","Installs on this computer the marketplaces and plugins in the account's terminal-app install block that are not on disk yet. New accounts start with the official marketplace and `capture`. A failed install is reported in the summary and never fails setup.","Opens a pi-tui page for system dependencies (tmux, nvim, a Nerd Font, uv) and confirms installs before running them.","On macOS, a final step detects the terminal and explains how to make Option act as Alt (crouter's menu is Alt+C). Where the setting is safely scriptable (Ghostty, stock VS Code) it can write the one line for you, but only if you tick it and after showing exactly what will be written.","In a terminal, records setup as done, so the next bare `crtr` boots a conversation instead of reopening the installer, and offers the tutorial if no conversation has started since setup first ran.","On every invocation (best-effort, idempotent), refreshes crouter-owned tmux bindings and registers known nodes' interaction roots so resolved tickets can call back into the asking node. The inbox popup toggle is a crouter-owned keybinding, editable on the keybindings tab."]},run:t(async()=>{const e=await(await import("./setup-wizard.js")).runSetup();process.stdout.isTTY&&await(await import("../../core/runtime/setup-marker.js")).recordSetupCompleted(e)},"run"),render:t(()=>"","render")});export{r as BROKER_LIMIT_OVERRIDE_PRECEDENCE,c as sysSetupLeaf};
@@ -3,7 +3,7 @@ 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.
6
+ /** A computer with no `machine.json` becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
7
7
  * The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
8
8
  export declare function registerFreshComputer(directoryUrl: string): Promise<{
9
9
  account: string;
@@ -1,4 +1,7 @@
1
- var N=Object.defineProperty;var r=(e,t)=>N(e,"name",{value:t,configurable:!0});import{spawn as E}from"node:child_process";import{defineLeaf as f}from"../../core/command.js";import{CrtrError as o}from"../../core/errors.js";import{controlPlaneUrl as S,personAccount as y,personBearer as u,readPersonCredential as l,signIn as v,signOut as A}from"../../core/directory/person-credential.js";import{hasLocalCanvas as U,readMachineConfig as d,readOrCreateInstallId as $,writeMachineConfig as R,writeMachineCredential as x}from"../../daemon/machine-link/config.js";import{probeDaemonHealth as L,spawnDaemon as h,stopAllDaemons as g}from"../../daemon/manage.js";import{hostname as O}from"node:os";import{northlightUnreachable as p}from"../../core/directory/reach.js";import{ExitCode as a}from"../../types.js";import{registerSignedInMac as C}from"../../core/directory/join.js";import{NORTHLIGHT_DIRECTORY_URL as I}from"../../core/directory/issuer.js";function P(e){const[t,n]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{E(t,n,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}r(P,"openBrowser");function _(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
- `),P(e.complete)}r(_,"showSignIn");function j(e){return async t=>{if(e.runId===void 0)return e.account===void 0||e.account.id===t.account.id?void 0:new o("signin_other_account",`This computer belongs to the Northlight account ${e.account.display}. Sign in to that account.`,a.USAGE);let n;try{n=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${t.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(i){return p(i,e.apiUrl)}if(!n.ok)return n.status===404?new o("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,a.USAGE):new o("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${n.status}); nothing was written.`,a.GENERAL,{next:"Retry `crtr sys signin`."})}}r(j,"sameAccountOnly");async function D(e){const t=l()===void 0?(await v(e,_),await y(e)):await y(e),n=await S(e),i=await u(e),m=r(async b=>{try{return await fetch(new URL(`/v1/machines${b?"?rotate=1":""}`,n),{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({install_id:$(),name:O().slice(0,64)}),signal:AbortSignal.timeout(3e4)})}catch(T){throw p(T,n)}},"post");let s=await m(!1);s.status===409&&(await s.clone().text()).includes("credential_exists")&&(s=await m(!0));const w=await s.text();if(!s.ok)throw new o("machine_registration_failed",`Northlight refused to register this computer (HTTP ${s.status}): ${w.slice(0,300)}`,a.GENERAL,{next:"Run `crtr sys signin` again."});const c=JSON.parse(w);if(typeof c.credential!="string"||typeof c.environment_id!="string")throw new o("machine_registration_failed","Northlight answered without a credential",a.GENERAL);return x(c.credential),R({apiUrl:n,environmentId:c.environment_id,directoryUrl:e,account:t}),await k(e),await g(),await h(),{account:t.display}}r(D,"registerFreshComputer");const ee=f({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`",help:{name:"sys signin",summary:"pair this computer with the person's Northlight account in the browser, register it as one of their machines, 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. A computer already registered accepts only the account it was registered under. A computer holding a local canvas and no `runtime/machine.json` is refused with `local_canvas_unsupported`: moving a local canvas into Northlight is no longer supported. A computer is also registered with the directory: 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."}],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 with no `machine.json`: 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 registered 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=>{d()!==void 0&&await h();const t=e.directoryUrl===void 0?H():String(e.directoryUrl),n=d();if(n!==void 0){const{account:i}=await v(t,_,{accept:j(n)});return await k(t),await g(),await h(),{account:i}}if(U())throw new o("local_canvas_unsupported","this computer holds a local crtr canvas, and moving one into Northlight is no longer supported.",a.USAGE,{next:"Remove the local canvas (the `pg`, `canvas.db` and `canvas.db.imported` entries under the runtime folder) to sign this computer in fresh."});return await D(t)},"run"),render:r(e=>`<signin account="${e.account}"/>`,"render")});async function G(){return await g(),await h(),(await L()).signed_in===!1}r(G,"stopMovedComputer");async function M(e){if(l()===void 0)return;const t=await u(e.directoryUrl);let n;try{n=await fetch(new URL(`/v1/machines/${e.environmentId}`,e.apiUrl),{method:"DELETE",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(3e4)})}catch(i){throw p(i,e.apiUrl)}if(!n.ok&&n.status!==404)throw new o("machine_revoke_failed",`Northlight refused to revoke this computer's machine credential (HTTP ${n.status}): ${(await n.text()).slice(0,300)}`,a.GENERAL,{next:"Run `crtr sys signout` again."})}r(M,"revokeMachine");const te=f({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:r(async()=>{const e=d();e!==void 0&&await M(e);const{signedOut:t,revoked:n}=await A(),i=e===void 0?!1:await G();return{signed_out:t,revoked:n,stopped:i}},"run"),render:r(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});function H(){return d()?.directoryUrl??l()?.directoryUrl??I}r(H,"defaultDirectoryUrl");async function k(e){try{await C(e,await u(e))}catch(t){process.stderr.write(`this computer was not registered with the directory: ${t instanceof Error?t.message:String(t)}
1
+ var A=Object.defineProperty;var r=(e,n)=>A(e,"name",{value:n,configurable:!0});import{spawn as S}from"node:child_process";import{defineLeaf as f}from"../../core/command.js";import{CrtrError as s}from"../../core/errors.js";import{controlPlaneUrl as E,personAccount as y,personBearer as l,readPersonCredential as g,signIn as v,signOut as N}from"../../core/directory/person-credential.js";import{readMachineConfig as h,readOrCreateInstallId as U,writeMachineConfig as R,writeMachineCredential as x}from"../../daemon/machine-link/config.js";import{probeDaemonHealth as C,spawnDaemon as u,stopAllDaemons as p}from"../../daemon/manage.js";import{hostname as O}from"node:os";import{northlightUnreachable as m}from"../../core/directory/reach.js";import{ExitCode as o}from"../../types.js";import{registerSignedInMac as L}from"../../core/directory/join.js";import{NORTHLIGHT_DIRECTORY_URL as I}from"../../core/directory/issuer.js";function P(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{S(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}r(P,"openBrowser");function k(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
+ `),P(e.complete)}r(k,"showSignIn");function j(e){return async n=>{if(e.runId===void 0)return e.account===void 0||e.account.id===n.account.id?void 0:new s("signin_other_account",`This computer belongs to the Northlight account ${e.account.display}. Sign in to that account.`,o.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(i){return m(i,e.apiUrl)}if(!t.ok)return t.status===404?new s("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,o.USAGE):new s("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,o.GENERAL,{next:"Retry `crtr sys signin`."})}}r(j,"sameAccountOnly");async function D(e){const n=g()===void 0?(await v(e,k),await y(e)):await y(e),t=await E(e),i=await l(e),c=r(async T=>{try{return await fetch(new URL(`/v1/machines${T?"?rotate=1":""}`,t),{method:"POST",headers:{authorization:`Bearer ${i}`,"content-type":"application/json"},body:JSON.stringify({install_id:U(),name:O().slice(0,64)}),signal:AbortSignal.timeout(3e4)})}catch($){throw m($,t)}},"post");let a=await c(!1);a.status===409&&(await a.clone().text()).includes("credential_exists")&&(a=await c(!0));const w=await a.text();if(!a.ok)throw new s("machine_registration_failed",`Northlight refused to register this computer (HTTP ${a.status}): ${w.slice(0,300)}`,o.GENERAL,{next:"Run `crtr sys signin` again."});const d=JSON.parse(w);if(typeof d.credential!="string"||typeof d.environment_id!="string")throw new s("machine_registration_failed","Northlight answered without a credential",o.GENERAL);return x(d.credential),R({apiUrl:t,environmentId:d.environment_id,directoryUrl:e,account:n}),await _(e),await p(),await u(),{account:n.display}}r(D,"registerFreshComputer");async function b(){try{await(await import("../person-settings.js")).loadPersonSettingsViaApi();const{installed:e,failed:n}=await(await import("../pkg/account-installs.js")).installAccountPlugins();e.length>0&&process.stderr.write(`Installed from your account: ${e.join(", ")}
3
+ `);for(const t of n)process.stderr.write(`Could not install ${t.item}: ${t.message}
4
+ `)}catch(e){process.stderr.write(`Could not read your account's plugins: ${e instanceof Error?e.message:String(e)}
5
+ `)}}r(b,"installAccountPluginsAfterSignIn");const ee=f({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`",help:{name:"sys signin",summary:"pair this computer with the person's Northlight account in the browser, register it as one of their machines, 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. A computer already registered accepts only the account it was registered under. Anything an earlier local crtr left in the runtime folder (`pg`, `canvas.db`) is not read and not moved: the canvas is the account's in Northlight, and this computer starts fresh. A computer is also registered with the directory: 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."}],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 with no `machine.json`: 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 registered computer: restarts the daemon so it reconnects to Northlight.","Installs on this computer the marketplaces and plugins listed in the account's terminal-app install block that are not on disk yet (failures are printed, not fatal).","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=>{h()!==void 0&&await u();const n=e.directoryUrl===void 0?H():String(e.directoryUrl),t=h();if(t!==void 0){const{account:c}=await v(n,k,{accept:j(t)});return await _(n),await p(),await u(),await b(),{account:c}}const i=await D(n);return await b(),i},"run"),render:r(e=>`<signin account="${e.account}"/>`,"render")});async function G(){return await p(),await u(),(await C()).signed_in===!1}r(G,"stopMovedComputer");async function M(e){if(g()===void 0)return;const n=await l(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(i){throw m(i,e.apiUrl)}if(!t.ok&&t.status!==404)throw new s("machine_revoke_failed",`Northlight refused to revoke this computer's machine credential (HTTP ${t.status}): ${(await t.text()).slice(0,300)}`,o.GENERAL,{next:"Run `crtr sys signout` again."})}r(M,"revokeMachine");const te=f({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 agents and running crons have stopped; false when this computer was never signed 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:r(async()=>{const e=h();e!==void 0&&await M(e);const{signedOut:n,revoked:t}=await N(),i=e===void 0?!1:await G();return{signed_out:n,revoked:t,stopped:i}},"run"),render:r(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});function H(){return h()?.directoryUrl??g()?.directoryUrl??I}r(H,"defaultDirectoryUrl");async function _(e){try{await L(e,await l(e))}catch(n){process.stderr.write(`this computer was not registered with the directory: ${n instanceof Error?n.message:String(n)}
3
6
  Run \`crtr sys signin\` again to register it.
4
- `)}}r(k,"registerThisMac");export{H as defaultDirectoryUrl,D as registerFreshComputer,_ as showSignIn,ee as sysSigninLeaf,te as sysSignoutLeaf};
7
+ `)}}r(_,"registerThisMac");export{H as defaultDirectoryUrl,D as registerFreshComputer,k as showSignIn,ee as sysSigninLeaf,te as sysSignoutLeaf};
@@ -206,8 +206,7 @@ export declare function renderNode(node: AnyNode): string;
206
206
  * the full path to the matched node (not just its local name), so the recovery
207
207
  * hint is a command that actually exists. No fuzzy matching. */
208
208
  export declare function unknownPathError(node: AnyNode, path: string[], bad: string): CrtrError;
209
- /** An unknown top-level command on a computer with no Northlight account (no `runtime/machine.json`, no `runtime.issuer`):
210
- * a command that comes from Northlight needs the account. */
209
+ /** An unknown top-level command on a computer that is not signed in to Northlight: crtr runs only through the account, so the answer is to sign in. */
211
210
  export declare function notJoinedError(bad: string): CrtrError;
212
211
  /** Options for parseArgv. */
213
212
  export interface ParseArgvOptions {
@@ -1,10 +1,10 @@
1
- var G=Object.defineProperty;var f=(e,t)=>G(e,"name",{value:t,configurable:!0});import{parsePrincipal as K}from"@north-light/identity";import{renderRoot as V,renderBranch as B,renderLeafArgv as T,withAsyncHelpState as L,collapseWideChildren as D,rootPromotedChildren as J}from"./help.js";import{beginPreview as Q,publishPreviewResult as X,readStdinRaw as M,peekStdinRaw as Y,emit as Z,handle as ee,setJsonOutput as ne,isJsonOutput as te}from"./io.js";import{renderResult as ie}from"./render.js";import{CrtrError as H}from"./errors.js";import{validateValue as re}from"../api/command-manifest/result.js";import{isManifestStaleError as ae}from"./manifest-stale.js";import{operationIdContext as oe}from"./events/operation-id.js";import{ExitCode as j}from"../types.js";import{envNodeId as se,providerProjectionOverBrokerRelay as le}from"../shared/env.js";import{readFileSync as de}from"node:fs";import{spawnSync as fe}from"node:child_process";import{constants as ce}from"node:os";import{resolve as ue}from"node:path";function q(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(const t of Object.values(e))q(t);return Object.freeze(e)}f(q,"freezeCommandMetadata");function Me(e){const t=q(e.help),{helpState:r}=e;if(r!==void 0&&e.effectiveHelp!==void 0)throw new Error(`leaf ${e.name} declares both helpState and effectiveHelp`);return Object.freeze({kind:"leaf",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:t,effectiveHelp:e.effectiveHelp??(r===void 0?void 0:n=>L(t,r,n)),slash:e.slash===void 0?void 0:q(e.slash),hookEligible:e.hookEligible,plugin:e.plugin,machineSelector:e.machineSelector,actingAs:e.actingAs,run:e.run,render:e.render,preview:e.preview,stdoutExact:e.stdoutExact})}f(Me,"defineLeaf");function O(e){return e.kind==="branch"&&e.children.length>0&&I(e)===0?"hidden":e.tier??"normal"}f(O,"effectiveTier");function I(e){return e.kind!=="branch"?0:(e.help.listing??[]).filter(t=>t.tier!=="hidden").length}f(I,"visibleSubCount");function Ie(e){if(e.passthrough!==void 0&&e.children.length>0)throw new Error(`defineBranch("${e.name}"): a passthrough branch must declare no children (found ${e.children.length})`);return e.help.listing=e.children.map(t=>{const r=I(t);return{name:t.name,description:t.description??"",whenToUse:t.whenToUse??"",tier:O(t),kind:t.kind,...t.plugin!==void 0?{plugin:t.plugin}:{},...r>0?{subCount:r}:{}}}),{kind:"branch",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:e.help,effectiveHelp:e.effectiveHelp,rootEntry:e.rootEntry,extensible:e.extensible,plugin:e.plugin,slash:e.slash,passthrough:e.passthrough,refusal:e.refusal,children:e.children}}f(Ie,"defineBranch");function ze(e){const t=[],r=f(n=>{if(n.slash!==void 0&&t.push(n.slash),n.kind==="branch")for(const a of n.children)r(a)},"visit");for(const n of e.subtrees)r(n);return t}f(ze,"collectSlashSpecs");function Ge(e){const t=e.subtrees.filter(n=>n.rootEntry!==void 0&&O(n)!=="hidden").map(n=>{const a=(n.help.listing??[]).filter(o=>o.tier!=="hidden"),d=J(a).map(o=>({path:`${n.name} ${o.name}`,desc:o.tier==="important"?o.description:void 0}));return{name:n.name,concept:n.rootEntry.concept,desc:n.rootEntry.desc,useWhen:n.rootEntry.useWhen,dynamicState:n.rootEntry.dynamicState,subcommands:d.length>0?d:void 0,otherSubcommandCount:a.length-d.length}});return{kind:"root",help:{tagline:e.tagline,commands:t,globals:e.globals},subtrees:e.subtrees}}f(Ge,"defineRoot");function he(e){if(e.kind==="root")return e.subtrees.filter(t=>O(t)!=="hidden").map(t=>t.name);if(e.kind==="branch"){const{listed:t,unlisted:r}=D(e.children.filter(n=>O(n)!=="hidden"));return[...t.map(n=>n.name),...r>0?[`(and ${r} more)`]:[]]}return[]}f(he,"childNames");function pe(e,t){let r=e;const n=[];let a=0;for(;a<t.length;){const d=t[a];if(d==="-h"||d==="--help")break;if(r.kind==="root"){const o=r.subtrees.find(s=>s.name===d);if(o===void 0)break;r=o,n.push(o.name),a++}else if(r.kind==="branch"){const o=r.children.find(s=>s.name===d);if(o===void 0)break;r=o,n.push(o.name),a++}else break}return{node:r,path:n,remaining:t.slice(a)}}f(pe,"walk");function me(e){return e.kind==="root"?V(e.help):e.kind==="branch"?B(e.help):T(e.help)}f(me,"renderNode");async function z(e,t,r){if(r!==void 0&&e.kind==="leaf")return T(e.effectiveHelp!==void 0?await e.effectiveHelp(r):e.help,r);const n=e.kind==="leaf"&&e.effectiveHelp!==void 0?T(await e.effectiveHelp()):e.kind==="branch"&&e.effectiveHelp!==void 0?B(await e.effectiveHelp()):me(e);if(t.length===0)return n;const{hasEffectiveCommandPlugins:a}=await import("./command-plugins/presence.js");if(!a())return n;const[{collectHelpAddenda:d},{SUBTREE_NAMES:o,coreCommandPathsCovering:s,extensibleCoreBranches:x}]=await Promise.all([import("./command-plugins/help-addenda.js"),import("../build-root.js")]),k=await d(t.join(" "),{reservedCoreNames:new Set(o),coreCommandPaths:s,extensibleCoreBranches:x});return n+k.map(E=>`
1
+ var I=Object.defineProperty;var f=(e,t)=>I(e,"name",{value:t,configurable:!0});import{parsePrincipal as K}from"@north-light/identity";import{renderRoot as V,renderBranch as B,renderLeafArgv as W,withAsyncHelpState as L,collapseWideChildren as D,rootPromotedChildren as J}from"./help.js";import{beginPreview as Q,publishPreviewResult as X,readStdinRaw as M,peekStdinRaw as Y,emit as Z,handle as ee,setJsonOutput as ne,isJsonOutput as te}from"./io.js";import{renderResult as ie}from"./render.js";import{CrtrError as H}from"./errors.js";import{validateValue as re}from"../api/command-manifest/result.js";import{isManifestStaleError as ae}from"./manifest-stale.js";import{operationIdContext as oe}from"./events/operation-id.js";import{ExitCode as j}from"../types.js";import{envNodeId as se,providerProjectionOverBrokerRelay as le}from"../shared/env.js";import{readFileSync as de}from"node:fs";import{spawnSync as fe}from"node:child_process";import{constants as ce}from"node:os";import{resolve as ue}from"node:path";function q(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(const t of Object.values(e))q(t);return Object.freeze(e)}f(q,"freezeCommandMetadata");function Me(e){const t=q(e.help),{helpState:r}=e;if(r!==void 0&&e.effectiveHelp!==void 0)throw new Error(`leaf ${e.name} declares both helpState and effectiveHelp`);return Object.freeze({kind:"leaf",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:t,effectiveHelp:e.effectiveHelp??(r===void 0?void 0:n=>L(t,r,n)),slash:e.slash===void 0?void 0:q(e.slash),hookEligible:e.hookEligible,plugin:e.plugin,machineSelector:e.machineSelector,actingAs:e.actingAs,run:e.run,render:e.render,preview:e.preview,stdoutExact:e.stdoutExact})}f(Me,"defineLeaf");function O(e){return e.kind==="branch"&&e.children.length>0&&z(e)===0?"hidden":e.tier??"normal"}f(O,"effectiveTier");function z(e){return e.kind!=="branch"?0:(e.help.listing??[]).filter(t=>t.tier!=="hidden").length}f(z,"visibleSubCount");function ze(e){if(e.passthrough!==void 0&&e.children.length>0)throw new Error(`defineBranch("${e.name}"): a passthrough branch must declare no children (found ${e.children.length})`);return e.help.listing=e.children.map(t=>{const r=z(t);return{name:t.name,description:t.description??"",whenToUse:t.whenToUse??"",tier:O(t),kind:t.kind,...t.plugin!==void 0?{plugin:t.plugin}:{},...r>0?{subCount:r}:{}}}),{kind:"branch",name:e.name,description:e.description,whenToUse:e.whenToUse,tier:e.tier,help:e.help,effectiveHelp:e.effectiveHelp,rootEntry:e.rootEntry,extensible:e.extensible,plugin:e.plugin,slash:e.slash,passthrough:e.passthrough,refusal:e.refusal,children:e.children}}f(ze,"defineBranch");function Ge(e){const t=[],r=f(n=>{if(n.slash!==void 0&&t.push(n.slash),n.kind==="branch")for(const a of n.children)r(a)},"visit");for(const n of e.subtrees)r(n);return t}f(Ge,"collectSlashSpecs");function Ie(e){const t=e.subtrees.filter(n=>n.rootEntry!==void 0&&O(n)!=="hidden").map(n=>{const a=(n.help.listing??[]).filter(o=>o.tier!=="hidden"),d=J(a).map(o=>({path:`${n.name} ${o.name}`,desc:o.tier==="important"?o.description:void 0}));return{name:n.name,concept:n.rootEntry.concept,desc:n.rootEntry.desc,useWhen:n.rootEntry.useWhen,dynamicState:n.rootEntry.dynamicState,subcommands:d.length>0?d:void 0,otherSubcommandCount:a.length-d.length}});return{kind:"root",help:{tagline:e.tagline,commands:t,globals:e.globals},subtrees:e.subtrees}}f(Ie,"defineRoot");function he(e){if(e.kind==="root")return e.subtrees.filter(t=>O(t)!=="hidden").map(t=>t.name);if(e.kind==="branch"){const{listed:t,unlisted:r}=D(e.children.filter(n=>O(n)!=="hidden"));return[...t.map(n=>n.name),...r>0?[`(and ${r} more)`]:[]]}return[]}f(he,"childNames");function pe(e,t){let r=e;const n=[];let a=0;for(;a<t.length;){const d=t[a];if(d==="-h"||d==="--help")break;if(r.kind==="root"){const o=r.subtrees.find(s=>s.name===d);if(o===void 0)break;r=o,n.push(o.name),a++}else if(r.kind==="branch"){const o=r.children.find(s=>s.name===d);if(o===void 0)break;r=o,n.push(o.name),a++}else break}return{node:r,path:n,remaining:t.slice(a)}}f(pe,"walk");function me(e){return e.kind==="root"?V(e.help):e.kind==="branch"?B(e.help):W(e.help)}f(me,"renderNode");async function G(e,t,r){if(r!==void 0&&e.kind==="leaf")return W(e.effectiveHelp!==void 0?await e.effectiveHelp(r):e.help,r);const n=e.kind==="leaf"&&e.effectiveHelp!==void 0?W(await e.effectiveHelp()):e.kind==="branch"&&e.effectiveHelp!==void 0?B(await e.effectiveHelp()):me(e);if(t.length===0)return n;const{hasEffectiveCommandPlugins:a}=await import("./command-plugins/presence.js");if(!a())return n;const[{collectHelpAddenda:d},{SUBTREE_NAMES:o,coreCommandPathsCovering:s,extensibleCoreBranches:x}]=await Promise.all([import("./command-plugins/help-addenda.js"),import("../build-root.js")]),k=await d(t.join(" "),{reservedCoreNames:new Set(o),coreCommandPaths:s,extensibleCoreBranches:x});return n+k.map(E=>`
2
2
 
3
3
  <plugin-help plugin="${E.plugin}">
4
4
  ${E.text}
5
- </plugin-help>`).join("")}f(z,"renderNodeWithAddenda");function ge(e){return e.some(t=>t==="-h"||t==="--help")}f(ge,"helpRequested");function we(e,t){if(e.kind!=="leaf"||t.length!==2)return;const[r,n]=t;if(n!=="-h"&&n!=="--help"||!r.startsWith("--")||r.includes("="))return;const a=r.slice(2);return(e.help.params??[]).find(o=>o.kind==="flag"&&o.name===a)?.focusedHelp!==void 0?a:void 0}f(we,"focusedHelpFlag");function ve(e,t){let r=0;for(let n=0;n<e.length;n++){if(r===t.length)return e.slice(n);e[n]!=="--json"&&e[n]===t[r]&&r++}return[]}f(ve,"rawArgsAfterPath");function be(e,t){const r=fe(e.bin,t,{stdio:"inherit"});if(r.error!==void 0){const n=r.error;throw new H("binary_missing",`${e.bin} could not be run (${n.code??n.message})`,j.USAGE,{received:e.bin,next:e.installHint})}if(r.status!==null&&process.exit(r.status),r.signal!==null){const n=ce.signals[r.signal];n!==void 0&&process.exit(128+n)}process.exit(1)}f(be,"runPassthrough");function xe(e,t,r){const n=he(e),a=n.length>0?n.join(", "):"(none)",d=t.length>0?`crtr ${t.join(" ")} -h`:"crtr -h",o=n.some(s=>s.startsWith("(and "));return new H("unknown_path",`unknown subcommand: ${r}`,j.USAGE,{received:r,next:o?`Valid children include: ${a}. Run \`${d}\` for how to find the rest.`:`Valid children: ${a}. Run \`${d}\` for the full list.`})}f(xe,"unknownPathError");function ke(e){const t="If it comes from Northlight, it needs a Northlight account: `crtr sys signin`.";return new H("not_joined",`\`crtr ${e}\` isn't a command here. ${t}`,j.USAGE,{received:e,next:t})}f(ke,"notJoinedError");async function $e(){if(le())return!1;try{const{readConfig:e}=await import("./config.js"),{readMachineConfig:t}=await import("../daemon/machine-link/config.js");return t()===void 0&&!e("user").runtime?.issuer}catch{return!1}}f($e,"runtimeUnjoined");function h(e,t,r,n,a){return new H(e,t,j.USAGE,{received:r,field:n,next:a!==void 0?a:"Run the command with -h to see the parameter schema."})}f(h,"parseArgvError");function P(e){return e.replace(/-([a-z])/g,(t,r)=>r.toUpperCase())}f(P,"flagNameToKey");async function ye(e,t,r){const n={},a=new Set,d=new Map,o=e.filter(i=>i.kind==="positional"),s=e.find(i=>i.kind==="stdin"),x=e.find(i=>i.kind==="context-file"),k=e.filter(i=>i.kind==="flag"),E=new Map(k.map(i=>[i.name,i])),$=k.some(i=>i.sensitive===!0);for(const i of k)i.type==="bool"?n[P(i.name)]=i.default!==void 0?i.default:!1:i.default!==void 0&&(n[P(i.name)]=i.default);const w=[];let v=0,A=!1,b=0;for(;b<t.length;){const i=t[b];if(i==="--"&&!A){A=!0,b++;continue}if(!A&&i.startsWith("--")){const p=i.indexOf("=");let l,_;if(p!==-1?(l=i.slice(2,p),_=i.slice(p+1)):l=i.slice(2),l==="context-file"){if(x===void 0)throw h("unknown_flag","unknown flag: --context-file","--context-file",void 0,"This leaf does not accept --context-file.");const c=_!==void 0?_:t[++b];if(c===void 0)throw h("missing_parameter","--context-file requires a PATH argument","--context-file","context-file");let S;try{S=de(c,"utf8")}catch{throw h("invalid_type",`--context-file: cannot read file: ${c}`,c,"context-file","Provide a readable file path.")}let F;try{F=JSON.parse(S)}catch{throw h("invalid_type",`--context-file: file is not valid JSON: ${c}`,c,"context-file","Ensure the file contains a valid JSON object.")}const W=P(x.name);n[W]=F,d.set(W,ue(c)),a.add(W),b++;continue}const R=E.has(l)||!l.startsWith("no-")?void 0:E.get(l.slice(3));if(R!==void 0&&R.type==="bool"){if(_!==void 0)throw h("invalid_type",`boolean flag --${l} takes no value`,`--${l}=${_}`,R.name,`Use --${l} (presence = false) with no value.`);const c=P(R.name);a.add(c),n[c]=!1,b++;continue}const y=E.get(l);if(y===void 0)throw h("unknown_flag",`unknown flag: --${l}`,`--${l}`,void 0,"Use --<flag-name> for declared flags only. Run -h for the schema.");const N=P(l);if(a.has(N)&&y.type!=="bool"&&y.repeatable!==!0)throw h("bad_invocation",`--${l} given twice; it takes one value`,`--${l}`,l,`Pass --${l} once.`);if(a.add(N),y.type==="bool"){if(_!==void 0)throw h("invalid_type",`boolean flag --${l} takes no value`,`--${l}=${_}`,l,`Use --${l} (presence = true) or --no-${l} (false), with no value.`);n[N]=!0,b++;continue}const C=_!==void 0?_:t[++b];if(C===void 0||_===void 0&&C.startsWith("--")){const c=y.focusedHelp!==void 0&&(r?.leafPath?.length??0)>0?`Run \`crtr ${r.leafPath.join(" ")} --${l} -h\` and read the focused value contract before retrying.`:void 0;throw h("missing_parameter",`--${l} requires a value`,`--${l}`,l,c)}let U;if(y.type==="int"){const c=Number(C);if(!Number.isInteger(c))throw h("invalid_type",`--${l} must be an integer`,C,l,`Provide an integer value for --${l}.`);U=c}else if(y.type==="enum"){const c=y.choices;if(c!==void 0&&!c.includes(C))throw h("invalid_type",`--${l} must be one of: ${c.join(", ")}`,C,l,`Retry with one of: ${c.join(", ")}.`);U=C}else if(y.type==="json"){let c;try{c=JSON.parse(C)}catch{throw h("invalid_type",`--${l} is not valid JSON`,C,l,`Pass one JSON value for --${l}; run -h for its shape.`)}const S=y.shape===void 0?null:re(y.shape,c,`--${l}`);if(S!==null)throw h("invalid_type",`${S.path} must be ${S.expected}, got ${S.receivedType}`,C,S.path,`Fix ${S.path}; run -h for the shape of --${l}.`);U=c}else U=C;if(y.repeatable===!0){const c=n[N],S=Array.isArray(c)?c:[];S.push(U),n[N]=S}else n[N]=U;b++;continue}const m=o[v];if(m!==void 0){const p=P(m.name);if(m.repeatable===!0){const l=n[p]??[];l.push(i),n[p]=l}else n[p]=i,v++;w.push(i),a.add(p),b++;continue}if(w.length>0){if(s!==void 0&&o.length===0){w.push(i),b++;continue}throw s!==void 0?h("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${s.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument."):h("bad_invocation",$?"unexpected extra positional argument (value withheld: this leaf takes a secret)":`unexpected extra positional argument: ${i}`,$?void 0:t.join(" "),void 0,"Use declared flags or positional parameters. Run -h for the schema.")}if(o.length===0&&(s===void 0||s.allowPositional===!1))throw h("bad_invocation",$?"this leaf takes no positional arguments (value withheld: this leaf takes a secret)":`this leaf takes no positional arguments: ${i}`,$?void 0:i,void 0,"Use --flag for parameters. Run -h for the schema.");w.push(i),b++}let g=!1;if(s!==void 0){if(w.length>1&&o.length===0){const i=s.positionalStdinConflict?.(n);throw i!==void 0?h("bad_invocation",i.message,void 0,i.field,i.next):h("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${s.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument.")}if(w.length>0&&o.length===0&&s.allowPositional!==!1){const i=w[0];if(i==="-"){const m=await M();(m.trim()!==""||!s.required)&&(n[P(s.name)]=m),g=!0}else{if((await Y()).trim()!==""){const p=s.positionalStdinConflict?.(n);throw h("bad_invocation",p?.message??`both a positional argument ("${i}") and piped stdin were provided for ${s.name}`,i,p?.field??s.name,p?.next??"Pass exactly one: either the positional argument or piped stdin, not both.")}n[P(s.name)]=i,g=!0}}else{const i=await M();i!==""&&(i.trim()!==""||!s.required)&&(n[P(s.name)]=i,g=!0)}}g&&s!==void 0&&a.add(P(s.name));for(const i of e){if(i.kind!=="flag"&&i.kind!=="positional"||i.defaultFromEnv===void 0)continue;const m=P(i.name);if(a.has(m))continue;const p=process.env[i.defaultFromEnv];p===void 0||p===""||(n[m]=i.kind==="positional"&&i.repeatable===!0?[p]:p,a.add(m))}const u=[];for(const i of e){const m=P(i.name),p=i.kind==="flag"&&i.type==="bool"&&!a.has(m);if(i.required&&(p||n[m]===void 0||n[m]===null)){const l=i.kind==="positional"?`positional ${i.name.toUpperCase()}`:i.kind==="flag"?`--${i.name}`:i.kind==="context-file"?"--context-file":"stdin";u.push({display:l,name:i.name})}}if(u.length>0){const i=u.map(l=>l.display).join(", "),m=r?.leafPath,p=m!==void 0&&m.length>0?`\`crtr ${m.join(" ")} -h\``:"this command with -h";throw h("missing_parameter",u.length===1?`required parameter is missing: ${i}`:`required parameters are missing: ${i}`,void 0,u.map(l=>l.name).join(", "),`Run ${p} and read the full schema before re-issuing \u2014 do not guess parameters one at a time.`)}return r?.onProvidedParams!==void 0&&r.onProvidedParams(a),r?.onContextFilePaths!==void 0&&r.onContextFilePaths(d),n}f(ye,"parseArgv");function Se(e){const t=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){t.push(...e.slice(n));break}const d=a.startsWith("--machine=")?a.slice(10):void 0;if(a!=="--machine"&&d===void 0){t.push(a);continue}const o=d??e[n+1];if(o===void 0||o===""||d===void 0&&o.startsWith("-"))throw h("missing_parameter","--machine requires a machine id","--machine","machine","Pass the machine_id of one of the candidates a `machine_required` answer lists.");d===void 0&&n++,r=o}return r===void 0?{rest:t}:{rest:t,machine:r}}f(Se,"takeMachineSelector");function Pe(e){const t=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){t.push(...e.slice(n));break}const d=a.startsWith("--as=")?a.slice(5):void 0;if(a!=="--as"&&d===void 0){t.push(a);continue}const o=d??e[n+1];if(o===void 0||K(o)===null)throw h("missing_parameter","--as requires a principal like user:<id> or app:<id>/<path>","--as","as","Name the principal this call acts for, for example `--as user:alice`.");d===void 0&&n++,r=o}return r===void 0?{rest:t}:{rest:t,as:r}}f(Pe,"takeActingAs");const Ce=new Set(["--json","--no-autostart"]);async function Ke(e,t){const r=t.slice(2);r.includes("--json")&&ne(!0);const n=r.filter(s=>!Ce.has(s));if(n.length===0||n.length===1&&(n[0]==="-h"||n[0]==="--help")){const s=se()?{...e.help,commands:await Promise.all(e.help.commands.map(async x=>{const k=e.subtrees.find(v=>v.name===x.name);if(k?.effectiveHelp===void 0)return x;const $=((await k.effectiveHelp()).listing??[]).filter(v=>v.tier!=="hidden"),w=J($).map(v=>({path:`${k.name} ${v.name}`,desc:v.tier==="important"?v.description:void 0}));return{...x,subcommands:w.length?w:void 0,otherSubcommandCount:$.length-w.length}}))}:e.help;process.stdout.write(V(s)+`
5
+ </plugin-help>`).join("")}f(G,"renderNodeWithAddenda");function ge(e){return e.some(t=>t==="-h"||t==="--help")}f(ge,"helpRequested");function we(e,t){if(e.kind!=="leaf"||t.length!==2)return;const[r,n]=t;if(n!=="-h"&&n!=="--help"||!r.startsWith("--")||r.includes("="))return;const a=r.slice(2);return(e.help.params??[]).find(o=>o.kind==="flag"&&o.name===a)?.focusedHelp!==void 0?a:void 0}f(we,"focusedHelpFlag");function ve(e,t){let r=0;for(let n=0;n<e.length;n++){if(r===t.length)return e.slice(n);e[n]!=="--json"&&e[n]===t[r]&&r++}return[]}f(ve,"rawArgsAfterPath");function be(e,t){const r=fe(e.bin,t,{stdio:"inherit"});if(r.error!==void 0){const n=r.error;throw new H("binary_missing",`${e.bin} could not be run (${n.code??n.message})`,j.USAGE,{received:e.bin,next:e.installHint})}if(r.status!==null&&process.exit(r.status),r.signal!==null){const n=ce.signals[r.signal];n!==void 0&&process.exit(128+n)}process.exit(1)}f(be,"runPassthrough");function xe(e,t,r){const n=he(e),a=n.length>0?n.join(", "):"(none)",d=t.length>0?`crtr ${t.join(" ")} -h`:"crtr -h",o=n.some(s=>s.startsWith("(and "));return new H("unknown_path",`unknown subcommand: ${r}`,j.USAGE,{received:r,next:o?`Valid children include: ${a}. Run \`${d}\` for how to find the rest.`:`Valid children: ${a}. Run \`${d}\` for the full list.`})}f(xe,"unknownPathError");function ke(e){const t="This computer is not signed in to Northlight, and most crtr commands come from the account. Run `crtr sys signin`. A computer with an old local crtr canvas starts fresh: the old canvas is not read or moved.";return new H("not_joined",`\`crtr ${e}\` isn't a command here. ${t}`,j.USAGE,{received:e,next:t})}f(ke,"notJoinedError");async function $e(){if(le())return!1;try{const{readConfig:e}=await import("./config.js"),{readMachineConfig:t}=await import("../daemon/machine-link/config.js");return t()===void 0&&!e("user").runtime?.issuer}catch{return!1}}f($e,"runtimeUnjoined");function h(e,t,r,n,a){return new H(e,t,j.USAGE,{received:r,field:n,next:a!==void 0?a:"Run the command with -h to see the parameter schema."})}f(h,"parseArgvError");function P(e){return e.replace(/-([a-z])/g,(t,r)=>r.toUpperCase())}f(P,"flagNameToKey");async function ye(e,t,r){const n={},a=new Set,d=new Map,o=e.filter(i=>i.kind==="positional"),s=e.find(i=>i.kind==="stdin"),x=e.find(i=>i.kind==="context-file"),k=e.filter(i=>i.kind==="flag"),E=new Map(k.map(i=>[i.name,i])),$=k.some(i=>i.sensitive===!0);for(const i of k)i.type==="bool"?n[P(i.name)]=i.default!==void 0?i.default:!1:i.default!==void 0&&(n[P(i.name)]=i.default);const w=[];let v=0,U=!1,b=0;for(;b<t.length;){const i=t[b];if(i==="--"&&!U){U=!0,b++;continue}if(!U&&i.startsWith("--")){const p=i.indexOf("=");let l,_;if(p!==-1?(l=i.slice(2,p),_=i.slice(p+1)):l=i.slice(2),l==="context-file"){if(x===void 0)throw h("unknown_flag","unknown flag: --context-file","--context-file",void 0,"This leaf does not accept --context-file.");const c=_!==void 0?_:t[++b];if(c===void 0)throw h("missing_parameter","--context-file requires a PATH argument","--context-file","context-file");let S;try{S=de(c,"utf8")}catch{throw h("invalid_type",`--context-file: cannot read file: ${c}`,c,"context-file","Provide a readable file path.")}let F;try{F=JSON.parse(S)}catch{throw h("invalid_type",`--context-file: file is not valid JSON: ${c}`,c,"context-file","Ensure the file contains a valid JSON object.")}const T=P(x.name);n[T]=F,d.set(T,ue(c)),a.add(T),b++;continue}const R=E.has(l)||!l.startsWith("no-")?void 0:E.get(l.slice(3));if(R!==void 0&&R.type==="bool"){if(_!==void 0)throw h("invalid_type",`boolean flag --${l} takes no value`,`--${l}=${_}`,R.name,`Use --${l} (presence = false) with no value.`);const c=P(R.name);a.add(c),n[c]=!1,b++;continue}const y=E.get(l);if(y===void 0)throw h("unknown_flag",`unknown flag: --${l}`,`--${l}`,void 0,"Use --<flag-name> for declared flags only. Run -h for the schema.");const N=P(l);if(a.has(N)&&y.type!=="bool"&&y.repeatable!==!0)throw h("bad_invocation",`--${l} given twice; it takes one value`,`--${l}`,l,`Pass --${l} once.`);if(a.add(N),y.type==="bool"){if(_!==void 0)throw h("invalid_type",`boolean flag --${l} takes no value`,`--${l}=${_}`,l,`Use --${l} (presence = true) or --no-${l} (false), with no value.`);n[N]=!0,b++;continue}const C=_!==void 0?_:t[++b];if(C===void 0||_===void 0&&C.startsWith("--")){const c=y.focusedHelp!==void 0&&(r?.leafPath?.length??0)>0?`Run \`crtr ${r.leafPath.join(" ")} --${l} -h\` and read the focused value contract before retrying.`:void 0;throw h("missing_parameter",`--${l} requires a value`,`--${l}`,l,c)}let A;if(y.type==="int"){const c=Number(C);if(!Number.isInteger(c))throw h("invalid_type",`--${l} must be an integer`,C,l,`Provide an integer value for --${l}.`);A=c}else if(y.type==="enum"){const c=y.choices;if(c!==void 0&&!c.includes(C))throw h("invalid_type",`--${l} must be one of: ${c.join(", ")}`,C,l,`Retry with one of: ${c.join(", ")}.`);A=C}else if(y.type==="json"){let c;try{c=JSON.parse(C)}catch{throw h("invalid_type",`--${l} is not valid JSON`,C,l,`Pass one JSON value for --${l}; run -h for its shape.`)}const S=y.shape===void 0?null:re(y.shape,c,`--${l}`);if(S!==null)throw h("invalid_type",`${S.path} must be ${S.expected}, got ${S.receivedType}`,C,S.path,`Fix ${S.path}; run -h for the shape of --${l}.`);A=c}else A=C;if(y.repeatable===!0){const c=n[N],S=Array.isArray(c)?c:[];S.push(A),n[N]=S}else n[N]=A;b++;continue}const m=o[v];if(m!==void 0){const p=P(m.name);if(m.repeatable===!0){const l=n[p]??[];l.push(i),n[p]=l}else n[p]=i,v++;w.push(i),a.add(p),b++;continue}if(w.length>0){if(s!==void 0&&o.length===0){w.push(i),b++;continue}throw s!==void 0?h("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${s.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument."):h("bad_invocation",$?"unexpected extra positional argument (value withheld: this leaf takes a secret)":`unexpected extra positional argument: ${i}`,$?void 0:t.join(" "),void 0,"Use declared flags or positional parameters. Run -h for the schema.")}if(o.length===0&&(s===void 0||s.allowPositional===!1))throw h("bad_invocation",$?"this leaf takes no positional arguments (value withheld: this leaf takes a secret)":`this leaf takes no positional arguments: ${i}`,$?void 0:i,void 0,"Use --flag for parameters. Run -h for the schema.");w.push(i),b++}let g=!1;if(s!==void 0){if(w.length>1&&o.length===0){const i=s.positionalStdinConflict?.(n);throw i!==void 0?h("bad_invocation",i.message,void 0,i.field,i.next):h("bad_invocation",`unexpected extra positional argument (value withheld: this leaf reads "${s.name}" from stdin, never argv)`,void 0,void 0,"Pipe it on stdin instead of passing it as a positional argument.")}if(w.length>0&&o.length===0&&s.allowPositional!==!1){const i=w[0];if(i==="-"){const m=await M();(m.trim()!==""||!s.required)&&(n[P(s.name)]=m),g=!0}else{if((await Y()).trim()!==""){const p=s.positionalStdinConflict?.(n);throw h("bad_invocation",p?.message??`both a positional argument ("${i}") and piped stdin were provided for ${s.name}`,i,p?.field??s.name,p?.next??"Pass exactly one: either the positional argument or piped stdin, not both.")}n[P(s.name)]=i,g=!0}}else{const i=await M();i!==""&&(i.trim()!==""||!s.required)&&(n[P(s.name)]=i,g=!0)}}g&&s!==void 0&&a.add(P(s.name));for(const i of e){if(i.kind!=="flag"&&i.kind!=="positional"||i.defaultFromEnv===void 0)continue;const m=P(i.name);if(a.has(m))continue;const p=process.env[i.defaultFromEnv];p===void 0||p===""||(n[m]=i.kind==="positional"&&i.repeatable===!0?[p]:p,a.add(m))}const u=[];for(const i of e){const m=P(i.name),p=i.kind==="flag"&&i.type==="bool"&&!a.has(m);if(i.required&&(p||n[m]===void 0||n[m]===null)){const l=i.kind==="positional"?`positional ${i.name.toUpperCase()}`:i.kind==="flag"?`--${i.name}`:i.kind==="context-file"?"--context-file":"stdin";u.push({display:l,name:i.name})}}if(u.length>0){const i=u.map(l=>l.display).join(", "),m=r?.leafPath,p=m!==void 0&&m.length>0?`\`crtr ${m.join(" ")} -h\``:"this command with -h";throw h("missing_parameter",u.length===1?`required parameter is missing: ${i}`:`required parameters are missing: ${i}`,void 0,u.map(l=>l.name).join(", "),`Run ${p} and read the full schema before re-issuing \u2014 do not guess parameters one at a time.`)}return r?.onProvidedParams!==void 0&&r.onProvidedParams(a),r?.onContextFilePaths!==void 0&&r.onContextFilePaths(d),n}f(ye,"parseArgv");function Se(e){const t=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){t.push(...e.slice(n));break}const d=a.startsWith("--machine=")?a.slice(10):void 0;if(a!=="--machine"&&d===void 0){t.push(a);continue}const o=d??e[n+1];if(o===void 0||o===""||d===void 0&&o.startsWith("-"))throw h("missing_parameter","--machine requires a machine id","--machine","machine","Pass the machine_id of one of the candidates a `machine_required` answer lists.");d===void 0&&n++,r=o}return r===void 0?{rest:t}:{rest:t,machine:r}}f(Se,"takeMachineSelector");function Pe(e){const t=[];let r;for(let n=0;n<e.length;n++){const a=e[n];if(a==="--"){t.push(...e.slice(n));break}const d=a.startsWith("--as=")?a.slice(5):void 0;if(a!=="--as"&&d===void 0){t.push(a);continue}const o=d??e[n+1];if(o===void 0||K(o)===null)throw h("missing_parameter","--as requires a principal like user:<id> or app:<id>/<path>","--as","as","Name the principal this call acts for, for example `--as user:alice`.");d===void 0&&n++,r=o}return r===void 0?{rest:t}:{rest:t,as:r}}f(Pe,"takeActingAs");const Ce=new Set(["--json","--no-autostart"]);async function Ke(e,t){const r=t.slice(2);r.includes("--json")&&ne(!0);const n=r.filter(s=>!Ce.has(s));if(n.length===0||n.length===1&&(n[0]==="-h"||n[0]==="--help")){const s=se()?{...e.help,commands:await Promise.all(e.help.commands.map(async x=>{const k=e.subtrees.find(v=>v.name===x.name);if(k?.effectiveHelp===void 0)return x;const $=((await k.effectiveHelp()).listing??[]).filter(v=>v.tier!=="hidden"),w=J($).map(v=>({path:`${k.name} ${v.name}`,desc:v.tier==="important"?v.description:void 0}));return{...x,subcommands:w.length?w:void 0,otherSubcommandCount:$.length-w.length}}))}:e.help;process.stdout.write(V(s)+`
6
6
  `),process.exitCode=j.SUCCESS;return}if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){const{readPackageVersion:s}=await import("../commands/sys/shared.js");process.stdout.write(s()+`
7
- `),process.exitCode=j.SUCCESS;return}let{node:a,path:d,remaining:o}=pe(e,n);try{if(a.kind==="branch"&&a.passthrough!==void 0&&be(a.passthrough,ve(r,d)),a.kind==="branch"&&a.refusal!==void 0&&o[0]!=="-h"&&o[0]!=="--help")throw new H(a.refusal.code,a.refusal.message,a.refusal.exit,{next:a.refusal.next});if((a.kind==="root"||a.kind==="branch")&&o.length>0&&o[0]!=="-h"&&o[0]!=="--help")throw a.kind==="root"&&!o[0].startsWith("-")&&a.providerCatalogFailure!==void 0?a.providerCatalogFailure:a.kind==="root"&&!o[0].startsWith("-")&&await $e()?ke(o[0]):xe(a,d,o[0]);if(ge(o)){process.stdout.write(await z(a,d,we(a,o))+`
8
- `),process.exitCode=j.SUCCESS;return}if(a.kind==="root"||a.kind==="branch"){process.stdout.write(await z(a,d)+`
9
- `),process.exitCode=j.SUCCESS;return}const s=a;Q(d.join(" "));const x=s.help.params!==void 0?s.help.params:[];let k=new Set,E=new Map,$=o,w;if(s.machineSelector===!0&&!x.some(u=>u.kind==="flag"&&u.name==="machine")){const u=Se(o);$=u.rest,w=u.machine}let v;if(s.actingAs===!0&&!x.some(u=>u.kind==="flag"&&u.name==="as")){const u=Pe($);$=u.rest,v=u.as}const A=await ye(x,$,{leafPath:d,onProvidedParams:f(u=>{k=u},"onProvidedParams"),onContextFilePaths:f(u=>{E=u},"onContextFilePaths")}),b={providedParams:k,contextFilePaths:E,...w===void 0?{}:{machine:w},...v===void 0?{}:{as:v}},g=await oe.fresh(()=>s.run(A,b));if(X(g==null?g:s.preview?.(g)??g),g!=null)if(te())Z(g);else{const u=s.render!==void 0?s.render(g):ie(g,s.help);process.stdout.write(u+(s.stdoutExact?.(g)?"":`
10
- `))}}catch(s){if(ae(s))throw s;ee(s)}}f(Ke,"runCli");export{Ce as GLOBAL_TOKENS,ze as collectSlashSpecs,Ie as defineBranch,Me as defineLeaf,Ge as defineRoot,ke as notJoinedError,ye as parseArgv,me as renderNode,Ke as runCli,Pe as takeActingAs,Se as takeMachineSelector,xe as unknownPathError,pe as walk};
7
+ `),process.exitCode=j.SUCCESS;return}let{node:a,path:d,remaining:o}=pe(e,n);try{if(a.kind==="branch"&&a.passthrough!==void 0&&be(a.passthrough,ve(r,d)),a.kind==="branch"&&a.refusal!==void 0&&o[0]!=="-h"&&o[0]!=="--help")throw new H(a.refusal.code,a.refusal.message,a.refusal.exit,{next:a.refusal.next});if((a.kind==="root"||a.kind==="branch")&&o.length>0&&o[0]!=="-h"&&o[0]!=="--help")throw a.kind==="root"&&!o[0].startsWith("-")&&a.providerCatalogFailure!==void 0?a.providerCatalogFailure:a.kind==="root"&&!o[0].startsWith("-")&&await $e()?ke(o[0]):xe(a,d,o[0]);if(ge(o)){process.stdout.write(await G(a,d,we(a,o))+`
8
+ `),process.exitCode=j.SUCCESS;return}if(a.kind==="root"||a.kind==="branch"){process.stdout.write(await G(a,d)+`
9
+ `),process.exitCode=j.SUCCESS;return}const s=a;Q(d.join(" "));const x=s.help.params!==void 0?s.help.params:[];let k=new Set,E=new Map,$=o,w;if(s.machineSelector===!0&&!x.some(u=>u.kind==="flag"&&u.name==="machine")){const u=Se(o);$=u.rest,w=u.machine}let v;if(s.actingAs===!0&&!x.some(u=>u.kind==="flag"&&u.name==="as")){const u=Pe($);$=u.rest,v=u.as}const U=await ye(x,$,{leafPath:d,onProvidedParams:f(u=>{k=u},"onProvidedParams"),onContextFilePaths:f(u=>{E=u},"onContextFilePaths")}),b={providedParams:k,contextFilePaths:E,...w===void 0?{}:{machine:w},...v===void 0?{}:{as:v}},g=await oe.fresh(()=>s.run(U,b));if(X(g==null?g:s.preview?.(g)??g),g!=null)if(te())Z(g);else{const u=s.render!==void 0?s.render(g):ie(g,s.help);process.stdout.write(u+(s.stdoutExact?.(g)?"":`
10
+ `))}}catch(s){if(ae(s))throw s;ee(s)}}f(Ke,"runCli");export{Ce as GLOBAL_TOKENS,Ge as collectSlashSpecs,ze as defineBranch,Me as defineLeaf,Ie as defineRoot,ke as notJoinedError,ye as parseArgv,me as renderNode,Ke as runCli,Pe as takeActingAs,Se as takeMachineSelector,xe as unknownPathError,pe as walk};
@@ -1 +1 @@
1
- var j=Object.defineProperty;var r=(e,n)=>j(e,"name",{value:n,configurable:!0});import{createPrivateKey as O,randomUUID as $,sign as A}from"node:crypto";import{readFileSync as T}from"node:fs";import{join as N}from"node:path";import{crtrHome as R}from"../canvas/paths.js";import{withCanvasWrite as v}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as k}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as b,outboundJson as E,outboundRefusal as S}from"../events/outbound.js";import{dependenciesOf as U,endpointPays as B,inferenceEndpointOf as C,principalPayer as D,replaceGrants as F,teamsOf as M}from"./mirror.js";import{loadPersonSettings as W}from"../scoped-state/person-rows.js";import{onGrantSync as q}from"./on-sync.js";import{hostedEndpointOf as I,paymentSetupUrlOf as L,storeHostedEndpoint as H}from"./hosted-endpoint.js";import{PersonOutsideRequestError as z,PersonUnresolvedError as K,personId as V,resolvePerson as Y,retireLocalPerson as Q,setPersonId as X}from"../canvas/person.js";const be=300;function Z(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:$()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:O({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Z,"assertion");function y(){const e=JSON.parse(T(N(R(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function Ee(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(Ee,"runtimeId");function ee(e){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(ee,"machineRevokedMessage");class x extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(ee(n)),this.name="MachineRevokedError"}}async function te(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Z(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await b("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&k()&&await ne(o)?new x(e):S("directory_token",c,`directory token request failed: ${o.status}`);const a=await E("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:re(a.access_token,a.expires_in)}}r(te,"mintDirectoryToken");async function ne(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(ne,"isInvalidClient");function re(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(re,"tokenExpiry");function oe(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||k()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=D(t.payer,t.sub,t.grantee);return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,grantee_prefix:typeof t.grantee_prefix=="string"?t.grantee_prefix:null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:B({payer:a})?C(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(oe,"responseGrant");async function ie(){try{return{id:V(),late:null}}catch(n){if(n instanceof z)return null;if(!(n instanceof K))throw n}const e=await Y();return e===null?null:{id:e.id,late:e}}r(ie,"pullPerson");async function se(e){X(e.id),await W(e.id);const n=await Q();await v(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(se,"bindLatePerson");let _;function Se(e){return _?_(e):Promise.resolve()}r(Se,"requestGrantSync");function xe(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await te(i),m=await b("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw S("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await E("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:I(s.hosted_endpoint??null),payment_setup_url:L(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,P=s.synced_at,h=s.grants.map(l=>oe(l,d)),w=await v(async()=>{await F(h,P,i,M(s.teams));const l=await ie();return g&&l&&await H(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await se(w.late);try{await q(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof x?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:J(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(xe,"createGrantSync");export{be as GRANT_SYNC_INTERVAL_S,x as MachineRevokedError,Z as assertion,xe as createGrantSync,ee as machineRevokedMessage,te as mintDirectoryToken,Se as requestGrantSync,y as runtimeClient,Ee as runtimeId};
1
+ var O=Object.defineProperty;var r=(e,n)=>O(e,"name",{value:n,configurable:!0});import{createPrivateKey as T,randomUUID as $,sign as A}from"node:crypto";import{readFileSync as N}from"node:fs";import{join as R}from"node:path";import{crtrHome as D}from"../canvas/paths.js";import{withCanvasWrite as k}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as b}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as E,outboundJson as S,outboundRefusal as x}from"../events/outbound.js";import{dependenciesOf as U,endpointPays as B,inferenceEndpointOf as C,principalPayer as F,replaceGrants as M,teamsOf as W}from"./mirror.js";import{seedTerminalDefaults as q}from"../scoped-state/seed-terminal-defaults.js";import{loadPersonSettings as I}from"../scoped-state/person-rows.js";import{onGrantSync as L}from"./on-sync.js";import{hostedEndpointOf as H,paymentSetupUrlOf as z,storeHostedEndpoint as K}from"./hosted-endpoint.js";import{PersonOutsideRequestError as V,PersonUnresolvedError as Y,personId as Q,resolvePerson as X,retireLocalPerson as Z,setPersonId as ee}from"../canvas/person.js";const xe=300;function te(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:$()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:T({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(te,"assertion");function y(){const e=JSON.parse(N(R(D(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function Pe(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(Pe,"runtimeId");function ne(e){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(ne,"machineRevokedMessage");class P extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(ne(n)),this.name="MachineRevokedError"}}async function re(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:te(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await E("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&b()&&await oe(o)?new P(e):x("directory_token",c,`directory token request failed: ${o.status}`);const a=await S("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:ie(a.access_token,a.expires_in)}}r(re,"mintDirectoryToken");async function oe(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(oe,"isInvalidClient");function ie(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(ie,"tokenExpiry");function se(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||b()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=F(t.payer,t.sub,t.grantee);return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,grantee_prefix:typeof t.grantee_prefix=="string"?t.grantee_prefix:null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:B({payer:a})?C(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(se,"responseGrant");async function ae(){try{return{id:Q(),late:null}}catch(n){if(n instanceof V)return null;if(!(n instanceof Y))throw n}const e=await X();return e===null?null:{id:e.id,late:e}}r(ae,"pullPerson");async function ce(e){ee(e.id),await I(e.id);const n=await Z();await k(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(ce,"bindLatePerson");let _;function je(e){return _?_(e):Promise.resolve()}r(je,"requestGrantSync");function Oe(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),l=await re(i),m=await E("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${l.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw x("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await S("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:H(s.hosted_endpoint??null),payment_setup_url:z(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,j=s.synced_at,h=s.grants.map(p=>se(p,d)),w=await k(async()=>{await M(h,j,i,W(s.teams));const p=await ae();return g&&p&&await K(g,p.id),p}),v=await q();v.length>0&&f({level:"info",event:"daemon.settings.terminal_defaults_seeded",fields:{people:v.length}}),f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await ce(w.late);try{await L(n)}catch(p){f({level:"error",event:"daemon.grants.on_sync_failed",error:p})}},"run");let u;const o=r(()=>{const d=c().catch(l=>{throw l instanceof P?f({level:"error",event:"daemon.grants.machine_revoked",error:l}):f({level:"error",event:"daemon.grants.sync_failed",error:l,fields:J(l)}),l}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(Oe,"createGrantSync");export{xe as GRANT_SYNC_INTERVAL_S,P as MachineRevokedError,te as assertion,Oe as createGrantSync,ne as machineRevokedMessage,re as mintDirectoryToken,je as requestGrantSync,y as runtimeClient,Pe as runtimeId};
@@ -98,6 +98,8 @@ export declare function commitBindingRequest(input: NewReviewRequest): Promise<{
98
98
  }>;
99
99
  export declare function getRequest(requestId: string): Promise<HumanRequestRecord | null>;
100
100
  export declare function getRequestByInboxTicket(ticketId: string): Promise<HumanRequestRecord | null>;
101
+ /** Every request among `ticketIds`, in one statement: the inbox list's page bodies read them all at once. */
102
+ export declare function getRequestsByInboxTickets(ticketIds: readonly string[]): Promise<HumanRequestRecord[]>;
101
103
  export declare function getRequestByDirectory(dir: string): Promise<HumanRequestRecord | null>;
102
104
  export declare function getRequestByCompanion(nodeId: string): Promise<HumanRequestRecord | null>;
103
105
  export declare function getRequestByIdempotencyKey(key: string): Promise<HumanRequestRecord | null>;