@north-light/cli 0.3.782 → 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 (45) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/charges.d.ts +3 -3
  4. package/dist/api/dto/charges.js +1 -1
  5. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  6. package/dist/builtin-memory/internal/marketplaces.md +1 -1
  7. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  8. package/dist/cli.js +2 -8
  9. package/dist/clients/attach/viewer.js +526 -526
  10. package/dist/commands/pkg/account-installs.d.ts +9 -0
  11. package/dist/commands/pkg/account-installs.js +1 -0
  12. package/dist/commands/sys/setup-core.d.ts +1 -52
  13. package/dist/commands/sys/setup-core.js +6 -6
  14. package/dist/commands/sys/setup-wizard.d.ts +4 -9
  15. package/dist/commands/sys/setup-wizard.js +2 -1
  16. package/dist/commands/sys/setup.js +1 -1
  17. package/dist/commands/sys/signin.js +6 -3
  18. package/dist/core/grants/sync.js +1 -1
  19. package/dist/core/ledger/check.d.ts +6 -2
  20. package/dist/core/ledger/check.js +1 -1
  21. package/dist/core/llm/run.js +2 -2
  22. package/dist/core/runtime/first-run-offer.d.ts +2 -6
  23. package/dist/core/runtime/first-run-offer.js +2 -10
  24. package/dist/core/runtime/front-door.js +8 -9
  25. package/dist/core/runtime/start-refusal-notice.d.ts +5 -0
  26. package/dist/core/runtime/start-refusal-notice.js +1 -0
  27. package/dist/core/scoped-state/seed-terminal-defaults.d.ts +2 -0
  28. package/dist/core/scoped-state/seed-terminal-defaults.js +1 -0
  29. package/dist/daemon/cron-run.js +2 -2
  30. package/dist/daemon/fleet.js +5 -5
  31. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  32. package/docs/sdk/release-notes.md +6 -0
  33. package/package.json +3 -3
  34. package/packages/crouter-api/dist/api/contract.js +1 -1
  35. package/packages/crouter-api/dist/api/dto/charges.js +1 -1
  36. package/packages/crouter-api/package.json +1 -1
  37. package/packages/crouter-identity/package.json +1 -1
  38. package/packages/crouter-plugin/package.json +3 -3
  39. package/runtime.lock.json +14 -14
  40. package/dist/commands/sys/panels/plugin-env-panel.d.ts +0 -19
  41. package/dist/commands/sys/panels/plugin-env-panel.js +0 -2
  42. package/dist/commands/sys/panels/plugins-panel.d.ts +0 -16
  43. package/dist/commands/sys/panels/plugins-panel.js +0 -1
  44. package/dist/core/runtime/front-door-login.d.ts +0 -2
  45. package/dist/core/runtime/front-door-login.js +0 -1
@@ -0,0 +1,9 @@
1
+ export interface AccountInstallResult {
2
+ installed: string[];
3
+ failed: {
4
+ item: string;
5
+ message: string;
6
+ }[];
7
+ }
8
+ /** Install what the account lists and this Mac lacks. Never throws: a failure is returned so sign-in and daemon start are not blocked. */
9
+ export declare function installAccountPlugins(): Promise<AccountInstallResult>;
@@ -0,0 +1 @@
1
+ var s=Object.defineProperty;var i=(n,t)=>s(n,"name",{value:t,configurable:!0});import{currentSnapshot as l}from"../../core/scoped-state/person-store.js";import{TERMINAL_APP as c}from"../../core/scoped-state/imported-mac-installs.js";import{findMarketplaceByName as u,findPluginByName as f}from"../../core/resolver.js";import{addMarketplace as p}from"./market-manage.js";import{installFromMarketplace as m}from"./plugin-manage.js";async function P(){const n={installed:[],failed:[]},t=l().apps[c];if(t===void 0)return n;const o=i(async(e,r)=>{try{await r(),n.installed.push(e)}catch(a){n.failed.push({item:e,message:a instanceof Error?a.message:String(a)})}},"attempt");for(const[e,r]of Object.entries(t.marketplaces))r.url===void 0||u(e,"user")!==null||await o(e,()=>p({url:r.url,...r.ref===void 0?{}:{ref:r.ref},scope:"user"}));for(const[e,r]of Object.entries(t.plugins))r.source_marketplace===void 0||f(e,"user")!==null||await o(e,()=>m({marketplace:r.source_marketplace,plugin:e},"user"));return n}i(P,"installAccountPlugins");export{P as installAccountPlugins};
@@ -1,32 +1,7 @@
1
1
  import { type BindingId, type BindingResolution, type KeybindingDiagnostic, type SparseKeybindingOverrides } from '../../core/keybindings/index.js';
2
- import { type PluginEnvDeclaration } from '../../core/plugin-env.js';
3
2
  import { type TerminalConfigEdit } from './terminal-option.js';
4
- export declare const OFFICIAL_MARKETPLACE_NAME = "crouter-official-marketplace";
5
- export declare const OFFICIAL_MARKETPLACE_URL = "https://github.com/crouton-labs/crouter-official-marketplace.git";
6
- export declare const OFFICIAL_MARKETPLACE_REF = "main";
7
- export type SetupPackageId = 'official-marketplace' | 'crtr-extensions' | 'oauth-adapter' | 'capture-plugin' | 'dev-plugin';
8
- /** `nerd-font` is not a command on PATH like the other two — it is an installed
9
- * font face, detected by fontconfig/font-directory scan. The viewer renders
10
- * every tool and command icon with Nerd Font codepoints, so without it a fresh
11
- * machine shows tofu boxes. */
12
- export type SetupTool = 'tmux' | 'nvim' | 'nerd-font';
13
- /** `marketplace-source` clones and registers a marketplace repo
14
- * (`installSource` is its git URL); `marketplace-plugin` installs one plugin
15
- * from a registered marketplace (`installSource` is a `<marketplace>/<plugin>`
16
- * ref). Neither runs the bundled pi CLI, and neither happens anywhere but
17
- * setup: an install that never runs setup — a Northlight guest image, CI —
18
- * fetches no catalog and carries no command whose external binary it lacks. */
19
- export type SetupPackageSourceKind = 'local-path' | 'npm' | 'marketplace-source' | 'marketplace-plugin';
20
- export type SetupPackageIdentity = string;
3
+ export type SetupTool = 'tmux' | 'nvim' | 'nerd-font' | 'uv';
21
4
  export type PackageManager = 'brew' | 'apt-get' | 'dnf' | 'pacman' | 'manual';
22
- export interface SetupPackageManifestEntry {
23
- id: SetupPackageId;
24
- name: string;
25
- sourceKind: SetupPackageSourceKind;
26
- installSource: string;
27
- shortDescription: string;
28
- longDescription: string;
29
- }
30
5
  export interface SetupSystemInstallPlan {
31
6
  tool: SetupTool;
32
7
  installed: boolean;
@@ -34,18 +9,8 @@ export interface SetupSystemInstallPlan {
34
9
  hint: string;
35
10
  autoInstall: boolean;
36
11
  }
37
- export interface SetupPluginEnvField {
38
- name: string;
39
- plugin: string;
40
- declaration: PluginEnvDeclaration;
41
- }
42
- /** Read declarations without installing or registering a marketplace until confirmation. */
43
- export declare function setupPluginEnvFields(packages: readonly SetupPackageManifestEntry[]): SetupPluginEnvField[];
44
12
  export interface SetupSubmission {
45
- packages: SetupPackageManifestEntry[];
46
- installedPackageIds: Set<SetupPackageId>;
47
13
  systemDeps: SetupSystemInstallPlan[];
48
- pluginEnv: Map<string, string>;
49
14
  /** A terminal-config write the person explicitly ticked in the Option key step. */
50
15
  terminalEdit?: TerminalConfigEdit;
51
16
  }
@@ -54,8 +19,6 @@ export interface SetupExecutionSummary {
54
19
  skipped: string[];
55
20
  }
56
21
  export interface SetupInitialState {
57
- manifest: SetupPackageManifestEntry[];
58
- installedPackageIds: Set<SetupPackageId>;
59
22
  systemPlans: SetupSystemInstallPlan[];
60
23
  }
61
24
  export interface KeybindingEditResult {
@@ -93,20 +56,10 @@ export declare class SetupKeybindingsDraft {
93
56
  discard(): void;
94
57
  markSaved(overrides: SparseKeybindingOverrides<BindingId>, tmuxPassthrough?: readonly BindingId[]): void;
95
58
  }
96
- export declare function buildSetupManifest(resolveBuiltinPackageDir?: (name: string) => string): SetupPackageManifestEntry[];
97
- /** One-line description of what installing an entry will actually run — the
98
- * wizard's confirm step and the non-TTY dump both show it. */
99
- export declare function packagePlanAction(entry: SetupPackageManifestEntry): string;
100
- export declare function normalizePackageIdentity(source: string, settingsDir: string, homeDir: string): SetupPackageIdentity;
101
- export declare function detectInstalledSetupPackageIds(settingsJson: unknown, manifest?: SetupPackageManifestEntry[], settingsPath?: string, homeDir?: string): Set<SetupPackageId>;
102
59
  export declare function detectCommandOnPath(command: string): boolean;
103
60
  export declare function detectPackageManager(platform?: NodeJS.Platform, commandExists?: (command: string) => boolean): PackageManager;
104
61
  export declare function buildSystemInstallPlan(tool: SetupTool, packageManager: PackageManager, commandExists?: (command: string) => boolean): SetupSystemInstallPlan;
105
- export declare function resolveSettingsPath(homeDir?: string): string;
106
62
  export declare function buildSetupInitialState(opts?: {
107
- manifest?: SetupPackageManifestEntry[];
108
- settingsPath?: string;
109
- homeDir?: string;
110
63
  packageManager?: PackageManager;
111
64
  commandExists?: (command: string) => boolean;
112
65
  }): SetupInitialState;
@@ -114,8 +67,4 @@ export declare function renderSetupStaticInstructions(state: SetupInitialState):
114
67
  /** Refresh crouter-owned tmux bindings. Setup must never fail because tmux is unavailable. */
115
68
  export declare function reconcileInboxFrontDoor(): Promise<void>;
116
69
  export declare function formatSetupExecutionSummary(summary: SetupExecutionSummary): string;
117
- /** The non-interactive first command reconciles only crouter-owned packages.
118
- * Individual failures are reported by the CLI but never prevent later work or
119
- * writing the once-per-machine marker. */
120
- export declare function reconcileFirstRun(onFailure: (item: string, error: unknown) => void, commandExists?: (command: string) => boolean): Promise<string>;
121
70
  export declare function executeSetupSubmission(submission: SetupSubmission, commandExists?: (command: string) => boolean): Promise<SetupExecutionSummary>;
@@ -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};
@@ -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 a}from"../../core/errors.js";import{controlPlaneUrl as S,personAccount as y,personBearer as u,readPersonCredential as l,signIn as v,signOut as $}from"../../core/directory/person-credential.js";import{readMachineConfig as d,readOrCreateInstallId as A,writeMachineConfig as U,writeMachineCredential as R}from"../../daemon/machine-link/config.js";import{probeDaemonHealth as x,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 s}from"../../types.js";import{registerSignedInMac as L}from"../../core/directory/join.js";import{NORTHLIGHT_DIRECTORY_URL as C}from"../../core/directory/issuer.js";function I(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(I,"openBrowser");function k(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
- `),I(e.complete)}r(k,"showSignIn");function P(e){return async t=>{if(e.runId===void 0)return e.account===void 0||e.account.id===t.account.id?void 0:new a("signin_other_account",`This computer belongs to the Northlight account ${e.account.display}. Sign in to that account.`,s.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 a("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,s.USAGE):new a("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${n.status}); nothing was written.`,s.GENERAL,{next:"Retry `crtr sys signin`."})}}r(P,"sameAccountOnly");async function D(e){const t=l()===void 0?(await v(e,k),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:A(),name:O().slice(0,64)}),signal:AbortSignal.timeout(3e4)})}catch(T){throw p(T,n)}},"post");let o=await m(!1);o.status===409&&(await o.clone().text()).includes("credential_exists")&&(o=await m(!0));const w=await o.text();if(!o.ok)throw new a("machine_registration_failed",`Northlight refused to register this computer (HTTP ${o.status}): ${w.slice(0,300)}`,s.GENERAL,{next:"Run `crtr sys signin` again."});const c=JSON.parse(w);if(typeof c.credential!="string"||typeof c.environment_id!="string")throw new a("machine_registration_failed","Northlight answered without a credential",s.GENERAL);return R(c.credential),U({apiUrl:n,environmentId:c.environment_id,directoryUrl:e,account:t}),await _(e),await g(),await h(),{account:t.display}}r(D,"registerFreshComputer");const Z=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.","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?M():String(e.directoryUrl),n=d();if(n!==void 0){const{account:i}=await v(t,k,{accept:P(n)});return await _(t),await g(),await h(),{account:i}}return await D(t)},"run"),render:r(e=>`<signin account="${e.account}"/>`,"render")});async function j(){return await g(),await h(),(await x()).signed_in===!1}r(j,"stopMovedComputer");async function G(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 a("machine_revoke_failed",`Northlight refused to revoke this computer's machine credential (HTTP ${n.status}): ${(await n.text()).slice(0,300)}`,s.GENERAL,{next:"Run `crtr sys signout` again."})}r(G,"revokeMachine");const ee=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=d();e!==void 0&&await G(e);const{signedOut:t,revoked:n}=await $(),i=e===void 0?!1:await j();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 M(){return d()?.directoryUrl??l()?.directoryUrl??C}r(M,"defaultDirectoryUrl");async function _(e){try{await L(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(_,"registerThisMac");export{M as defaultDirectoryUrl,D as registerFreshComputer,k as showSignIn,Z as sysSigninLeaf,ee as sysSignoutLeaf};
7
+ `)}}r(_,"registerThisMac");export{H as defaultDirectoryUrl,D as registerFreshComputer,k as showSignIn,ee as sysSigninLeaf,te as sysSignoutLeaf};
@@ -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};
@@ -1,4 +1,5 @@
1
1
  import { RunError } from '../runs/operations.js';
2
+ import type { PaymentRefusalDTO } from '../../api/dto/charges.js';
2
3
  import type { Funding, Limit } from './types.js';
3
4
  /** A model or tool call, checked before it is sent: everything about it is known. A limit matches when its `payer` equals
4
5
  * the candidate's and each of its non-null filters equals the candidate's value. */
@@ -35,9 +36,12 @@ export interface Refusal {
35
36
  export declare function findRefusal(candidate: Candidate, at?: Date): Promise<Refusal | null>;
36
37
  /** The `user_action` a person can take for a limit of this source; absent for an operator limit. */
37
38
  export declare function userActionOf(source: Limit['source']): 'raise_cap' | 'clear_limit' | undefined;
38
- /** `402 cap_exhausted` for a refusal. Details: `limit` (id, payer, filters, usd_per_month, source), `usd`, `reset_at`, and
39
+ /** The reason, person sentence and fix link of a refusal by this limit (design-limit-refusals, contract 3). Links are built from the
40
+ * directory this runtime is connected to; null when it has none. */
41
+ export declare function paymentOf(refusal: Refusal): PaymentRefusalDTO;
42
+ /** `402 cap_exhausted` for a refusal. Details: `payment` (reason, person sentence, fix link), `limit` (id, payer, filters, usd_per_month, source), `usd`, `reset_at`, and
39
43
  * `user_action` when the person can act; plus the deprecated `spend_cap` (= `limit.usd_per_month`) and `usd_equivalent` (= `usd`)
40
- * that the refusal carried before the ledger, kept so a caller that reads them still gets the numbers. */
44
+ * that the refusal carried before the ledger, kept so a caller that reads them still gets the numbers. The message is the person sentence. */
41
45
  export declare function refusalError(refusal: Refusal): RunError;
42
46
  /** Throw `refusalError` when a limit refuses `candidate`. */
43
47
  export declare function check(candidate: Candidate, at?: Date): Promise<void>;
@@ -1 +1 @@
1
- var o=Object.defineProperty;var r=(e,t)=>o(e,"name",{value:t,configurable:!0});import{openDb as s}from"../canvas/db.js";import{RunError as a}from"../runs/operations.js";import{usageMonth as u}from"./months.js";async function c(e,t=new Date){const n={...e,month:u(t)},i=await(await s()).prepare("SELECT ledger_check(?::jsonb) AS refusal").get(JSON.stringify(n));return typeof i?.refusal=="string"?JSON.parse(i.refusal):i?.refusal??null}r(c,"findRefusal");function p(e){return e==="grant_sync"?"raise_cap":e==="person"?"clear_limit":void 0}r(p,"userActionOf");function d(e){const{limit:t}=e,n=p(t.source);return new a(402,"cap_exhausted",`${t.payer??t.account} reached its monthly limit (${t.id})`,void 0,{limit:{id:t.id,payer:t.payer,account:t.account,filters:{account:t.account,funding:t.funding,grantee:t.grantee,provider:t.provider,sub:t.sub},usd_per_month:t.usd_per_month,source:t.source},usd:e.usd,reset_at:e.reset_at,spend_cap:t.usd_per_month,usd_equivalent:e.usd,...n===void 0?{}:{user_action:n},...t.source==="grant_sync"?{payment:{reason:"app_limit",message:"This app reached its monthly spending limit for your account",pay_url:null,reset_at:e.reset_at}}:{}})}r(d,"refusalError");async function y(e,t){const n=await c(e,t);if(n!==null)throw d(n)}r(y,"check");const g=r(e=>({limit:e.limit.id,reason:`${e.limit.payer??e.limit.account} reached ${e.limit.usd_per_month} USD this month (spent ${e.usd})`}),"refusedMark");export{y as check,c as findRefusal,d as refusalError,g as refusedMark,p as userActionOf};
1
+ var u=Object.defineProperty;var o=(t,e)=>u(t,"name",{value:e,configurable:!0});import{openDb as c}from"../canvas/db.js";import{RunError as p}from"../runs/operations.js";import{usageMonth as l}from"./months.js";import{directoryIssuer as d}from"../directory/issuer.js";async function m(t,e=new Date){const n={...t,month:l(e)},r=await(await c()).prepare("SELECT ledger_check(?::jsonb) AS refusal").get(JSON.stringify(n));return typeof r?.refusal=="string"?JSON.parse(r.refusal):r?.refusal??null}o(m,"findRefusal");function h(t){return t==="grant_sync"?"raise_cap":t==="person"?"clear_limit":void 0}o(h,"userActionOf");function _(t){const{limit:e}=t,n=d(),r=o(a=>n===null?null:`${n}${a}`,"link"),s=Number.isInteger(e.usd_per_month)?String(e.usd_per_month):e.usd_per_month.toFixed(2),i={reset_at:t.reset_at};switch(e.source){case"grant_sync":{const a=e.grantee?.startsWith("app:")?e.grantee.slice(4):null;return{reason:"app_limit",message:`This app reached the $${s} monthly limit set for it on your account. You can raise it.`,pay_url:a===null?null:r(`/account/apps/${encodeURIComponent(a)}#limit`),...i}}case"billing":return{reason:"card_limit",message:e.provider===null?`You have reached your $${s} monthly billing limit.`:`You have reached your $${s} monthly limit for this provider.`,pay_url:r("/account/billing#limit"),...i};case"card":return{reason:"card_required",message:"Add a card to keep going.",pay_url:r("/account/pay"),...i};case"operator":return{reason:"operator_stop",message:"Northlight has paused spending on your account. Contact support to have it lifted.",pay_url:null,...i};case"person":return{reason:"person_limit",message:`You set a $${s} monthly limit that this reached. Change it with \`crtr sys spend\`.`,pay_url:null,...i}}}o(_,"paymentOf");function g(t){const{limit:e}=t,n=h(e.source),r=_(t);return new p(402,"cap_exhausted",r.message,void 0,{limit:{id:e.id,payer:e.payer,account:e.account,filters:{account:e.account,funding:e.funding,grantee:e.grantee,provider:e.provider,sub:e.sub},usd_per_month:e.usd_per_month,source:e.source},usd:t.usd,reset_at:t.reset_at,spend_cap:e.usd_per_month,usd_equivalent:t.usd,...n===void 0?{}:{user_action:n},payment:r})}o(g,"refusalError");async function v(t,e){const n=await m(t,e);if(n!==null)throw g(n)}o(v,"check");const x=o(t=>({limit:t.limit.id,reason:`${t.limit.payer??t.limit.account} reached ${t.limit.usd_per_month} USD this month (spent ${t.usd})`}),"refusedMark");export{v as check,m as findRefusal,_ as paymentOf,g as refusalError,x as refusedMark,h as userActionOf};