@north-light/cli 0.3.782 → 0.3.784

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 (60) 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/builtin-pi-packages/pi-crtr-extensions/README.md +3 -3
  9. package/dist/cli.js +2 -8
  10. package/dist/clients/attach/viewer.js +1 -1
  11. package/dist/commands/pkg/account-installs.d.ts +10 -0
  12. package/dist/commands/pkg/account-installs.js +1 -0
  13. package/dist/commands/pkg/plugin-manage.d.ts +4 -0
  14. package/dist/commands/pkg/plugin-manage.js +1 -1
  15. package/dist/commands/sys/doctor.js +1 -1
  16. package/dist/commands/sys/provider-login.js +5 -5
  17. package/dist/commands/sys/setup-core.d.ts +1 -52
  18. package/dist/commands/sys/setup-core.js +6 -6
  19. package/dist/commands/sys/setup-wizard.d.ts +4 -9
  20. package/dist/commands/sys/setup-wizard.js +3 -1
  21. package/dist/commands/sys/setup.js +1 -1
  22. package/dist/commands/sys/signin.js +7 -3
  23. package/dist/core/grants/shadow.js +1 -1
  24. package/dist/core/grants/sync.js +1 -1
  25. package/dist/core/ledger/check.d.ts +6 -2
  26. package/dist/core/ledger/check.js +1 -1
  27. package/dist/core/llm/run.js +2 -2
  28. package/dist/core/runtime/first-run-offer.d.ts +2 -6
  29. package/dist/core/runtime/first-run-offer.js +2 -10
  30. package/dist/core/runtime/front-door.js +8 -9
  31. package/dist/core/runtime/package-health.d.ts +1 -1
  32. package/dist/core/runtime/package-health.js +5 -4
  33. package/dist/core/runtime/provider-credential-gate.d.ts +1 -1
  34. package/dist/core/runtime/provider-credential-gate.js +1 -1
  35. package/dist/core/runtime/runner/machine/executor.d.ts +3 -0
  36. package/dist/core/runtime/runner/machine/executor.js +2 -1
  37. package/dist/core/runtime/start-refusal-notice.d.ts +5 -0
  38. package/dist/core/runtime/start-refusal-notice.js +1 -0
  39. package/dist/core/scoped-state/seed-terminal-defaults.d.ts +2 -0
  40. package/dist/core/scoped-state/seed-terminal-defaults.js +1 -0
  41. package/dist/daemon/cron-run.js +2 -2
  42. package/dist/daemon/fleet.js +5 -5
  43. package/dist/daemon/machine-daemon.js +1 -1
  44. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  45. package/docs/cli/first-session.md +2 -2
  46. package/docs/cli/official-marketplace.md +1 -1
  47. package/docs/sdk/release-notes.md +6 -0
  48. package/package.json +3 -3
  49. package/packages/crouter-api/dist/api/contract.js +1 -1
  50. package/packages/crouter-api/dist/api/dto/charges.js +1 -1
  51. package/packages/crouter-api/package.json +1 -1
  52. package/packages/crouter-identity/package.json +1 -1
  53. package/packages/crouter-plugin/package.json +3 -3
  54. package/runtime.lock.json +14 -14
  55. package/dist/commands/sys/panels/plugin-env-panel.d.ts +0 -19
  56. package/dist/commands/sys/panels/plugin-env-panel.js +0 -2
  57. package/dist/commands/sys/panels/plugins-panel.d.ts +0 -16
  58. package/dist/commands/sys/panels/plugins-panel.js +0 -1
  59. package/dist/core/runtime/front-door-login.d.ts +0 -2
  60. package/dist/core/runtime/front-door-login.js +0 -1
@@ -1 +1,3 @@
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 u=(h,t)=>b(h,"name",{value:t,configurable:!0});import{matchesKey as m,truncateToWidth as l,visibleWidth as p}from"@earendil-works/pi-tui";import{formatGesture as d,formatMovePair as S,matchesPiTuiInput as f}from"../../core/keybindings/index.js";import{buildSetupInitialState as $,executeSetupSubmission as v,formatSetupExecutionSummary as y,reconcileInboxFrontDoor as w,renderSetupStaticInstructions as E}from"./setup-core.js";import{runSetupSettingsProcess as P}from"./setup-settings-runner.js";import{DependenciesPanel as I}from"./panels/dependencies-panel.js";import{PAGE_CHROME_ROWS as k,pageFrame as C,theme as r}from"../../core/tui/panel.js";import{TerminalPanel as T}from"./panels/terminal-panel.js";import{describeEdit as W,planOptionAsAlt as A}from"./terminal-option.js";import{homedir as D}from"node:os";import{createInterface as L}from"node:readline/promises";import{readMachineConfig as x}from"../../daemon/machine-link/config.js";import{defaultDirectoryUrl as H,registerFreshComputer as _}from"./signin.js";import{loadPersonSettingsViaApi as O}from"../person-settings.js";import{installAccountPlugins as R}from"../pkg/account-installs.js";const g=["Dependencies"],q="Option key";class z{static{u(this,"SetupWizard")}bindings;terminalRows;dependencies;terminal;steps;step=0;confirming=!1;cachedWidth;cachedHeight;cachedLines;_focused=!1;onSubmit;onCancel;constructor(t,i,n,s=null){this.bindings=i,this.terminalRows=n;const e=u(()=>this.invalidate(),"invalidate");this.dependencies=new I(t,e),this.terminal=s===null?void 0:new T(s,e),this.steps=this.terminal===void 0?g:[...g,q]}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,i){return f(this.bindings,t,i,(n,s)=>m(n,s))}label(t){const i=this.bindings.gestures(t);return i.length===0?"disabled":d(i[0].split(" > ").pop())}fieldSafeLabel(t){const i=this.bindings.gestures(t).filter(n=>{if(n.includes(" > "))return!0;const s=n.split("+").pop();return!(s==="up"||s==="down"||s==="left"||s==="right")&&(s.length>1||n.includes("+"))});return i.length===0?"Disabled":i.map(d).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 i=this.currentPanel(),n=u((s,e)=>this.matches(s,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(i.handleInput(t,n)){this.invalidate();return}this.matches("crtr.setup.advance",t)&&this.advance()}renderTrail(t){const n=this.steps.map((s,e)=>{if(e===this.step)return r.bg("selectedBg",` ${e+1} ${s} `);const c=e<this.step?r.fg("success","\u2713"):`${e+1}`;return r.fg("dim",` ${c} ${s} `)}).join(r.fg("dim","\u203A"));return p(n)<=t?[l(n,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 i=`${this.fieldSafeLabel("crtr.setup.tab-next")}/${this.fieldSafeLabel("crtr.setup.tab-previous")} step \xB7 ${this.label("crtr.setup.cancel")} cancel`,n=S(this.bindings,"crtr.setup.list-down","crtr.setup.list-up");let s;this.confirming?s=`${this.label("crtr.setup.confirm.accept")} confirm \xB7 ${this.label("crtr.setup.confirm.back")} go back`:this.step===0?s=`${n} move \xB7 ${this.label("crtr.setup.toggle")} toggle \xB7 ${this.label("crtr.setup.advance")} ${this.steps.length>1?"next":"finish"}`:s=`${this.terminal?.canApply?`${this.label("crtr.setup.toggle")} apply for me \xB7 `:""}${this.label("crtr.setup.advance")} finish`;const e=t-p(s)-p(i);return e>=2?`${r.fg("dim",s)}${" ".repeat(e)}${r.fg("dim",i)}`:r.fg("dim",s)}renderConfirm(t){const i=this.buildSubmission(),n=[l(r.fg("warning",r.bold("Confirm installs")),t),""];if(i.systemDeps.length===0&&i.terminalEdit===void 0)return[...n,l(r.fg("success",`Nothing to install; ${this.label("crtr.setup.confirm.accept")} finish.`),t)];if(i.systemDeps.length){n.push(l(r.fg("accent","System deps"),t));for(const s of i.systemDeps)n.push(l(` \u2022 ${s.tool} ${r.fg("dim","\u2192")} ${r.fg("muted",s.command??s.hint)}`,t))}if(i.terminalEdit!==void 0){n.push(l(r.fg("accent","Terminal config"),t));for(const s of W(i.terminalEdit))n.push(l(r.fg("muted",` ${s}`),t))}return n}render(t){const n=this.terminalRows();if(this.cachedLines&&this.cachedWidth===t&&this.cachedHeight===n)return this.cachedLines;const s=this.currentPanel(),e=Math.max(1,n-k),c=this.confirming||e<=2?[]:this.renderTrail(t),o=Math.max(1,e-c.length),a=C({width:t,height:n,title:"crouter setup",meta:this.confirming?"review":`step ${this.step+1} of ${this.steps.length}`,body:[...c,...this.confirming?this.renderConfirm(t):s.render(t,o)],footer:this.footer(t)});return this.cachedWidth=t,this.cachedHeight=n,this.cachedLines=a,a}}function M(){process.stdout.write("\x1B[2J\x1B[H")}u(M,"clearWizardFrame");async function st(){const h=$();let t=!1;if(await w(),!process.stdout.isTTY)return process.stdout.write(E(h)),"skipped";if(x()===void 0)for(;;)try{const{account:e}=await _(H());process.stdout.write(`Signed in to Northlight as ${e}.
2
+ `);break}catch(e){process.stderr.write(`Sign-in failed: ${e instanceof Error?e.message:String(e)}
3
+ `);const c=L({input:process.stdin,output:process.stderr}),o=await c.question("Press Enter to retry, or q to quit: ").catch(()=>"q");c.close(),o.trim().toLowerCase().startsWith("q")&&(process.stderr.write("Setup stopped: this computer is not signed in. Run `crtr sys signin` when ready.\n"),process.exit(1))}let i;try{await O(),i=await R()}catch(e){i={installed:[],warnings:[],failed:[{item:"account plugins",message:e instanceof Error?e.message:String(e)}]}}const n=await P(({terminal:e,bindings:c},o)=>{const a=new z(h.systemPlans,c,()=>e.rows,A({env:process.env,platform:process.platform,home:D()}));return a.onCancel=o.cancel,a.onSubmit=o.submit,a},(e,c)=>e===""?(t=!0,!0):e.length>0&&e.charCodeAt(0)<32&&f(c,"crtr.setup.cancel",e,(o,a)=>m(o,a)));if(M(),t){const e=new Error("Interrupted");throw e.name="AbortError",e}if(n===void 0)return"skipped";const s=await v(n);return s.installed.push(...i.installed.map(e=>`${e} (from your account)`)),s.skipped.push(...i.warnings),s.skipped.push(...i.failed.map(e=>`${e.item} (${e.message})`)),process.stdout.write(y(s)),"completed"}u(st,"runSetup");export{z as SetupWizard,st 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,8 @@
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,t)=>A(e,"name",{value:t,configurable:!0});import{spawn as S}from"node:child_process";import{defineLeaf as f}from"../../core/command.js";import{CrtrError as a}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[t,n]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{S(t,n,{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 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.`,o.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 m(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.`,o.USAGE):new a("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${n.status}); nothing was written.`,o.GENERAL,{next:"Retry `crtr sys signin`."})}}r(j,"sameAccountOnly");async function D(e){const t=g()===void 0?(await v(e,k),await y(e)):await y(e),n=await E(e),i=await l(e),c=r(async T=>{try{return await fetch(new URL(`/v1/machines${T?"?rotate=1":""}`,n),{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($,n)}},"post");let s=await c(!1);s.status===409&&(await s.clone().text()).includes("credential_exists")&&(s=await c(!0));const w=await s.text();if(!s.ok)throw new a("machine_registration_failed",`Northlight refused to register this computer (HTTP ${s.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 a("machine_registration_failed","Northlight answered without a credential",o.GENERAL);return x(d.credential),R({apiUrl:n,environmentId:d.environment_id,directoryUrl:e,account:t}),await _(e),await p(),await u(),{account:t.display}}r(D,"registerFreshComputer");async function b(){try{await(await import("../person-settings.js")).loadPersonSettingsViaApi();const{installed:e,failed:t,warnings:n}=await(await import("../pkg/account-installs.js")).installAccountPlugins();e.length>0&&process.stderr.write(`Installed from your account: ${e.join(", ")}
3
+ `);for(const i of n)process.stderr.write(`${i}
4
+ `);for(const i of t)process.stderr.write(`Could not install ${i.item}: ${i.message}
5
+ `)}catch(e){process.stderr.write(`Could not read your account's plugins: ${e instanceof Error?e.message:String(e)}
6
+ `)}}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 t=e.directoryUrl===void 0?H():String(e.directoryUrl),n=h();if(n!==void 0){const{account:c}=await v(t,k,{accept:j(n)});return await _(t),await p(),await u(),await b(),{account:c}}const i=await D(t);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 t=await l(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 m(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)}`,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:t,revoked:n}=await N(),i=e===void 0?!1:await G();return{signed_out:t,revoked:n,stopped:i}},"run"),render:r(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});function H(){return h()?.directoryUrl??g()?.directoryUrl??I}r(H,"defaultDirectoryUrl");async function _(e){try{await L(e,await l(e))}catch(t){process.stderr.write(`this computer was not registered with the directory: ${t instanceof Error?t.message:String(t)}
3
7
  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};
8
+ `)}}r(_,"registerThisMac");export{H as defaultDirectoryUrl,D as registerFreshComputer,k as showSignIn,ee as sysSigninLeaf,te as sysSignoutLeaf};
@@ -1 +1 @@
1
- var $=Object.defineProperty;var o=(e,r)=>$(e,"name",{value:r,configurable:!0});import{directoryIssuer as h}from"../directory/issuer.js";import{outboundFetch as k}from"../events/outbound.js";import{warn as f}from"../output.js";import{canonicalJson as w,dependenciesOf as E,inferenceEndpointOf as M,endpointPays as T,principalPayer as S}from"./mirror.js";let x=5e3;function F(e){x=e}o(F,"setShadowTtl");const b=512,N=["status","scopes","resolved_scopes","spend_cap","payer","dependencies","run_notice_url","inference_endpoint"];function L(){g.clear()}o(L,"resetShadowCache");const g=new Map,d=new Map,_=new Map;function j(e){const r=e===null?[...new Set([...g.keys(),...d.keys()])]:[e];for(const n of r)g.delete(n),d.delete(n),_.set(n,(_.get(n)??0)+1)}o(j,"forgetShadowAnswer");const c={agree:0,disagree:0,lagging:0,error:0};async function O(e,r,n){const{mintDirectoryToken:s}=await import("./sync.js"),a=await s(e),p=n?`&epochs=${n.epochs.global},${n.epochs.sub}`:"",t=`${e}/v1/runtime/grant-answers?sub=${encodeURIComponent(r)}${p}`,i=await k("grant_shadow",t,{headers:{Authorization:`Bearer ${a.access_token}`},signal:AbortSignal.timeout(1e4)});if(!i.ok)throw new Error(`grant-answers ${i.status}`);const l=await i.json();if(l.unchanged){if(!n)throw new Error("grant-answers said unchanged to a caller holding nothing");return{...n,epochs:l.epochs,checkedAt:Date.now()}}return{epochs:l.epochs,grants:new Map((l.grants??[]).map(y=>[String(y.id),y])),checkedAt:Date.now()}}o(O,"fetchAnswer");async function A(e,r){const n=g.get(r);if(n&&Date.now()-n.checkedAt<x)return n;const s=d.get(r);if(s)return s;const a=_.get(r)??0,p=O(e,r,n).then(t=>((_.get(r)??0)!==a||(g.delete(r),g.set(r,t),g.size>b&&g.delete(g.keys().next().value)),t)).finally(()=>{d.get(r)===p&&d.delete(r)});return d.set(r,p),p}o(A,"answerFor");const m=new Set;async function G(){await Promise.all([...m])}o(G,"shadowIdle");async function C(e){const r=h();if(r===null)return;const n=(await A(r,e.sub)).grants.get(e.id);if(!n){c.disagree++,f(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,fields:["missing"]})}`);return}if(n.rev!==e.rev){c.lagging++;return}const s={...n,payer:S(n.payer,e.sub,e.grantee)},a={...e,resolved_scopes:I(e.resolved_scopes,n.resolved_scopes)},p=N.filter(t=>t==="resolved_scopes"?R(s[t])!==R(a[t]):w(s[t]??null)!==w(a[t]??null));if(p.length===0){c.agree++;return}c.disagree++,f(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,rev:e.rev,fields:p})}`)}o(C,"compare");function R(e){return Array.isArray(e)?JSON.stringify([...new Set(e.map(r=>`${r.scope}|${r.mode}`))].sort()):w(e??null)}o(R,"scopeSet");function I(e,r){if(!Array.isArray(r))return e;const n=new Set(r.flatMap(t=>{const i=t?.scope;return typeof i=="string"?[i]:[]})),s=new Set([...n].filter(t=>t.endsWith(":*")).map(t=>t.slice(0,-2)));if(s.size===0)return e;const a=new Set;return e.flatMap(t=>{const i=t.scope.slice(0,t.scope.indexOf(":"));if(i==="crtr"||!s.has(i))return[t];const l=a.has(i)?[]:[{...t,scope:`${i}:*`}];return a.add(i),n.has(t.scope)?[t,...l]:l})}o(I,"compactLike");let v,u={agree:0,disagree:0,lagging:0,error:0};function D(){v||(v=setInterval(()=>{const e={agree:c.agree-u.agree,disagree:c.disagree-u.disagree,lagging:c.lagging-u.lagging,error:c.error-u.error};u={...c},e.agree+e.disagree+e.lagging+e.error>0&&f(`grant_shadow_summary ${JSON.stringify({window_s:60,...e})}`)},6e4),v.unref())}o(D,"startSummary");function V(e){if(!process.env.CRTR_RUNTIME)return;D();const r=C(e).catch(n=>{c.error++,f(`grant_shadow error ${JSON.stringify({grant:e.id,message:n instanceof Error?n.message:String(n)})}`)}).finally(()=>m.delete(r));m.add(r)}o(V,"shadowCheck");function W(){return!!process.env.CRTR_RUNTIME&&process.env.CRTR_GRANT_LIVE_READS==="1"&&h()!==null}o(W,"liveReads");async function X(e,r){if(e.grantee_prefix)return r();const n=(await A(h(),e.sub)).grants.get(e.id);if(!n)return null;const s=n.status;if(s!=="active"&&s!=="revoked"&&s!=="removed")throw new TypeError("invalid live grant status");if(!Number.isInteger(n.rev))throw new TypeError("invalid live grant rev");const a=S(n.payer,e.sub,e.grantee);return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:null,rev:n.rev,scopes:n.scopes,resolved_scopes:n.resolved_scopes,spend_cap:typeof n.spend_cap=="number"?n.spend_cap:null,expires_at:typeof n.expires_at=="string"?n.expires_at:null,status:s,revoked_at:typeof n.revoked_at=="string"?n.revoked_at:null,approved_at:e.approved_at??null,payer:a,dependencies:E(n.dependencies),run_notice_url:typeof n.run_notice_url=="string"&&n.run_notice_url!==""?n.run_notice_url:null,inference_endpoint:T({payer:a})?M(n.inference_endpoint):null,synced_at:typeof n.synced_at=="string"?n.synced_at:""}}o(X,"liveRecord");export{j as forgetShadowAnswer,W as liveReads,X as liveRecord,L as resetShadowCache,F as setShadowTtl,V as shadowCheck,c as shadowCounts,G as shadowIdle};
1
+ var $=Object.defineProperty;var a=(e,t)=>$(e,"name",{value:t,configurable:!0});import{directoryIssuer as w}from"../directory/issuer.js";import{outboundFetch as E}from"../events/outbound.js";import{warn as _}from"../output.js";import{canonicalJson as m,dependenciesOf as M,inferenceEndpointOf as T,endpointPays as b,principalPayer as x}from"./mirror.js";let A=5e3;function L(e){A=e}a(L,"setShadowTtl");const N=512,O=["status","scopes","resolved_scopes","spend_cap","payer","dependencies","run_notice_url","inference_endpoint"];function j(){g.clear()}a(j,"resetShadowCache");const g=new Map,d=new Map,h=new Map;function G(e){const t=e===null?[...new Set([...g.keys(),...d.keys()])]:[e];for(const n of t)g.delete(n),d.delete(n),h.set(n,(h.get(n)??0)+1)}a(G,"forgetShadowAnswer");const c={agree:0,disagree:0,lagging:0,error:0};async function C(e,t,n){const{mintDirectoryToken:s}=await import("./sync.js"),i=await s(e),l=n?`&epochs=${n.epochs.global},${n.epochs.sub}`:"",r=`${e}/v1/runtime/grant-answers?sub=${encodeURIComponent(t)}${l}`,o=a(()=>E("grant_shadow",r,{headers:{Authorization:`Bearer ${i.access_token}`},signal:AbortSignal.timeout(3e3)}),"ask");let p=await o().catch(()=>null);if((p===null||p.status>=500)&&(p=await o()),!p.ok)throw new Error(`grant-answers ${p.status}`);const f=await p.json();if(f.unchanged){if(!n)throw new Error("grant-answers said unchanged to a caller holding nothing");return{...n,epochs:f.epochs,checkedAt:Date.now()}}return{epochs:f.epochs,grants:new Map((f.grants??[]).map(S=>[String(S.id),S])),checkedAt:Date.now()}}a(C,"fetchAnswer");async function k(e,t){const n=g.get(t);if(n&&Date.now()-n.checkedAt<A)return n;const s=d.get(t);if(s)return s;const i=h.get(t)??0,l=C(e,t,n).then(r=>((h.get(t)??0)!==i||(g.delete(t),g.set(t,r),g.size>N&&g.delete(g.keys().next().value)),r)).finally(()=>{d.get(t)===l&&d.delete(t)});return d.set(t,l),l}a(k,"answerFor");const v=new Set;async function V(){await Promise.all([...v])}a(V,"shadowIdle");async function I(e){const t=w();if(t===null)return;const n=(await k(t,e.sub)).grants.get(e.id);if(!n){c.disagree++,_(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,fields:["missing"]})}`);return}if(n.rev!==e.rev){c.lagging++;return}const s={...n,payer:x(n.payer,e.sub,e.grantee)},i={...e,resolved_scopes:D(e.resolved_scopes,n.resolved_scopes)},l=O.filter(r=>r==="resolved_scopes"?R(s[r])!==R(i[r]):m(s[r]??null)!==m(i[r]??null));if(l.length===0){c.agree++;return}c.disagree++,_(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,rev:e.rev,fields:l})}`)}a(I,"compare");function R(e){return Array.isArray(e)?JSON.stringify([...new Set(e.map(t=>`${t.scope}|${t.mode}`))].sort()):m(e??null)}a(R,"scopeSet");function D(e,t){if(!Array.isArray(t))return e;const n=new Set(t.flatMap(r=>{const o=r?.scope;return typeof o=="string"?[o]:[]})),s=new Set([...n].filter(r=>r.endsWith(":*")).map(r=>r.slice(0,-2)));if(s.size===0)return e;const i=new Set;return e.flatMap(r=>{const o=r.scope.slice(0,r.scope.indexOf(":"));if(o==="crtr"||!s.has(o))return[r];const p=i.has(o)?[]:[{...r,scope:`${o}:*`}];return i.add(o),n.has(r.scope)?[r,...p]:p})}a(D,"compactLike");let y,u={agree:0,disagree:0,lagging:0,error:0};function J(){y||(y=setInterval(()=>{const e={agree:c.agree-u.agree,disagree:c.disagree-u.disagree,lagging:c.lagging-u.lagging,error:c.error-u.error};u={...c},e.agree+e.disagree+e.lagging+e.error>0&&_(`grant_shadow_summary ${JSON.stringify({window_s:60,...e})}`)},6e4),y.unref())}a(J,"startSummary");function W(e){if(!process.env.CRTR_RUNTIME)return;J();const t=I(e).catch(n=>{c.error++,_(`grant_shadow error ${JSON.stringify({grant:e.id,message:n instanceof Error?n.message:String(n)})}`)}).finally(()=>v.delete(t));v.add(t)}a(W,"shadowCheck");function X(){return!!process.env.CRTR_RUNTIME&&process.env.CRTR_GRANT_LIVE_READS==="1"&&w()!==null}a(X,"liveReads");async function q(e,t){if(e.grantee_prefix)return t();const n=(await k(w(),e.sub)).grants.get(e.id);if(!n)return null;const s=n.status;if(s!=="active"&&s!=="revoked"&&s!=="removed")throw new TypeError("invalid live grant status");if(!Number.isInteger(n.rev))throw new TypeError("invalid live grant rev");const i=x(n.payer,e.sub,e.grantee);return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:null,rev:n.rev,scopes:n.scopes,resolved_scopes:n.resolved_scopes,spend_cap:typeof n.spend_cap=="number"?n.spend_cap:null,expires_at:typeof n.expires_at=="string"?n.expires_at:null,status:s,revoked_at:typeof n.revoked_at=="string"?n.revoked_at:null,approved_at:e.approved_at??null,payer:i,dependencies:M(n.dependencies),run_notice_url:typeof n.run_notice_url=="string"&&n.run_notice_url!==""?n.run_notice_url:null,inference_endpoint:b({payer:i})?T(n.inference_endpoint):null,synced_at:typeof n.synced_at=="string"?n.synced_at:""}}a(q,"liveRecord");export{G as forgetShadowAnswer,X as liveReads,q as liveRecord,j as resetShadowCache,L as setShadowTtl,W as shadowCheck,c as shadowCounts,V as shadowIdle};
@@ -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};
@@ -1,3 +1,3 @@
1
- var Je=Object.defineProperty;var l=(e,t)=>Je(e,"name",{value:t,configurable:!0});import{randomUUID as He}from"node:crypto";import{streamSimple as ze}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as Xe,probeRouteAvailability as Ge}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as Me,parseModelSpec as Ve}from"../model-routes.js";import{openModelRegistry as Ye}from"../runtime/model-registry.js";import{getProviderLabel as Ze,isInvalidRefreshTokenError as Qe}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Se,coolingUntilFor as $e,isManagedProvider as N,markSubscriptionRateLimited as et,markSubscriptionSuccess as tt,readSubscriptionPool as Ce,retryAfterMsFromHeaders as ge,retryAfterMsFromError as nt,refreshSubscriptionCredential as ot,subscriptionNeedsSuccessWrite as rt,vendorRateLimit as it,RefreshBusyError as at,RefreshTimeoutError as st}from"../subscription-state.js";import{describeRateLimitScope as Ee,modelCooldownFamily as dt,rateLimitHeaders as lt}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as we}from"../provider-error-recognition.js";import{isSafetyRefusal as ut}from"./refusal.js";import{findRefusal as ct,payerOf as Ie,refusalError as ft,refusedMark as mt,writeCharge as be}from"../ledger/index.js";import{storedApiKey as Oe}from"../auth-file.js";import{eligibleHostedEndpoint as pt,readHostedEndpoint as De}from"../grants/hosted-endpoint.js";import{parseProviderPayment as ht}from"../provider-failure.js";import{personIdAsync as _t}from"../canvas/person.js";import{getNode as Ne}from"../canvas/canvas.js";import{endpointPays as yt}from"../grants/mirror.js";import{outboundToken as Pe}from"../providers/mint.js";import{discardFile as Fe}from"../providers/token-cache.js";import{ProviderError as gt}from"../providers/errors.js";import{appCandidates as wt}from"./app-rungs.js";import{hostedRoute as bt,matchesFeatures as vt,ownerCandidates as kt}from"./owner-candidates.js";function xt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(xt,"validContent");function Le(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,s]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:s}}):e??""}l(Le,"imageContent");function Rt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],s=we({message:o}).kind;return s!=="connection"&&s!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(Rt,"refreshFailure");async function qt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const x=e.getProvider(t)?.auth.oauth;if(!x)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:s});return(await ot(t,o.label,async(r,_)=>{const w=await x.refresh({type:"oauth",refresh:r,access:"",expires:0,..._?{clientId:_}:{}},d??new AbortController().signal).catch(q=>{throw Rt(q,s)}),R=w.clientId;return{refresh:w.refresh,access:w.access,expires:w.expires,...typeof R=="string"&&R?{clientId:R}:{}}}).catch(r=>{throw r instanceof at||r instanceof st?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:s}):r})).access}l(qt,"freshSubscriptionAccess");function an(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&xt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(s=>s&&typeof s.id=="string"&&typeof s.function?.name=="string"&&typeof s.function.arguments=="string"&&At(s.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,s]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||o==="temperature"&&(s<0||s>2)||o==="top_p"&&(s<0||s>1)||o==="max_tokens"&&(!Number.isSafeInteger(s)||s<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(an,"parseLlmRequest");function At(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(At,"isJsonObject");function jt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Le(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(_=>({type:"toolCall",id:_.id,name:_.function.name,arguments:JSON.parse(_.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Le(r.content),timestamp:t}),s=o.findIndex(r=>r.role!=="system"),d=o.slice(0,s<0?o.length:s).map(r=>r.content),x=d.join(`
1
+ var Je=Object.defineProperty;var l=(e,t)=>Je(e,"name",{value:t,configurable:!0});import{randomUUID as He}from"node:crypto";import{streamSimple as ze}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as Xe,probeRouteAvailability as Ge}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as $e,parseModelSpec as Ve}from"../model-routes.js";import{openModelRegistry as Ye}from"../runtime/model-registry.js";import{getProviderLabel as Ze,isInvalidRefreshTokenError as Qe}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Se,coolingUntilFor as Ce,isManagedProvider as N,markSubscriptionRateLimited as et,markSubscriptionSuccess as tt,readSubscriptionPool as Ie,retryAfterMsFromHeaders as we,retryAfterMsFromError as nt,refreshSubscriptionCredential as ot,subscriptionNeedsSuccessWrite as rt,vendorRateLimit as it,RefreshBusyError as at,RefreshTimeoutError as st}from"../subscription-state.js";import{describeRateLimitScope as Ee,modelCooldownFamily as dt,rateLimitHeaders as lt}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as be}from"../provider-error-recognition.js";import{isSafetyRefusal as ut}from"./refusal.js";import{findRefusal as ct,payerOf as Oe,refusalError as ft,refusedMark as mt,writeCharge as ve}from"../ledger/index.js";import{storedApiKey as De}from"../auth-file.js";import{directoryIssuer as ie}from"../directory/issuer.js";import{eligibleHostedEndpoint as pt}from"../grants/hosted-endpoint.js";import{parseProviderPayment as ht}from"../provider-failure.js";import{personIdAsync as _t}from"../canvas/person.js";import{getNode as Ne}from"../canvas/canvas.js";import{endpointPays as yt}from"../grants/mirror.js";import{outboundToken as Pe}from"../providers/mint.js";import{discardFile as Fe}from"../providers/token-cache.js";import{ProviderError as gt}from"../providers/errors.js";import{appCandidates as wt}from"./app-rungs.js";import{hostedRoute as bt,matchesFeatures as vt,ownerCandidates as kt}from"./owner-candidates.js";function xt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(xt,"validContent");function Le(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,s]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:s}}):e??""}l(Le,"imageContent");function Rt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],s=be({message:o}).kind;return s!=="connection"&&s!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(Rt,"refreshFailure");async function qt(e,t,o,s,d){if(o.expires>Date.now())return o.access;const x=e.getProvider(t)?.auth.oauth;if(!x)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:s});return(await ot(t,o.label,async(r,_)=>{const w=await x.refresh({type:"oauth",refresh:r,access:"",expires:0,..._?{clientId:_}:{}},d??new AbortController().signal).catch(q=>{throw Rt(q,s)}),R=w.clientId;return{refresh:w.refresh,access:w.access,expires:w.expires,...typeof R=="string"&&R?{clientId:R}:{}}}).catch(r=>{throw r instanceof at||r instanceof st?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:s}):r})).access}l(qt,"freshSubscriptionAccess");function sn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&xt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(s=>s&&typeof s.id=="string"&&typeof s.function?.name=="string"&&typeof s.function.arguments=="string"&&At(s.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,s]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)||o==="temperature"&&(s<0||s>2)||o==="top_p"&&(s<0||s>1)||o==="max_tokens"&&(!Number.isSafeInteger(s)||s<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(sn,"parseLlmRequest");function At(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(At,"isJsonObject");function jt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Le(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(_=>({type:"toolCall",id:_.id,name:_.function.name,arguments:JSON.parse(_.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Le(r.content),timestamp:t}),s=o.findIndex(r=>r.role!=="system"),d=o.slice(0,s<0?o.length:s).map(r=>r.content),x=d.join(`
2
2
 
3
- `),J=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...x?{systemPrompt:x}:{},messages:o.slice(d.length),...J?{tools:J}:{}}}l(jt,"contextOf");function Mt(e){return ht(e?.payment)}l(Mt,"paymentOf");function St(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l(St,"hostedModel");function $t(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:x}=e.cost;return o===0&&s===0&&d===0&&x===0?null:Number.isFinite(t)&&t>=0?t:null}l($t,"usdEquivalent");function Ct(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(Ct,"allowedFallback");function sn(e){return e?{payer:e.payer,sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(sn,"llmCallerOf");function Te(e){return e instanceof gt?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Te,"mintFailure");const Et=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function It(e,t,o){if(!(e!=="openai-codex"||t===void 0||!Et.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(It,"codexAccountModelRejection");function Ot(e){return e.get("request-id")??e.get("x-request-id")}l(Ot,"vendorRequestId");async function dn(e,t,o,s,d,x,J){const r=x&&yt(x)?x:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const _=r?.inference_endpoint??void 0,w=d===void 0?null:r?.sub??d.sub??await _t(),R=await Ye();let q;_?(q=wt(_,e.model,e.model_policy==="exact").flatMap((y,b)=>{const $=Ve(y.model);return $?[{routeId:"app",credentialSource:"app",family:"app",strength:y.strength,...$,rank:b}]:[]}),q=q.filter(y=>vt(R,e,y))):q=await kt(R,e,s);const ie=!_&&d!==void 0&&w!==null?await pt():null,ae=ie===null?void 0:bt(e,q,ie),Ue=ae?ie:null;ae&&(q=[...q,ae]);const Ke=_?new Set:Xe(),ve=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await De())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(q.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):_?new i(404,"model_unavailable","no eligible model route is configured"):await ve();const H=`chatcmpl-${He()}`;let P=1/0,F=1/0,se,v,de,le;const G=new Set,ue=l(async()=>J??(d?.node?(await Ne(d.node))?.caused_by??null:null)??(d?.run?(await Ne(d.run))?.caused_by??null:null),"causeOf");for(const y of q){const b=y.credentialSource==="hosted";if(!r&&!b&&!(await Ge(y,R)).authenticated){if(y.credentialSource!==Me&&N(y.providerId)){const k=await Ce(y.providerId);k.length>0&&k.every(A=>A.authFailure)&&G.add(y.providerId)}continue}const $=b?St(R,y.modelId):R.find(y.providerId,y.modelId);if(!$)continue;const z=b?Ue.base_url:void 0,u=_?{...$,baseUrl:`${_.base_url}/${$.provider}`}:z?{...$,baseUrl:`${z}/anthropic`,compat:{...$.compat,allowedFallbackModels:void 0}}:$,h=y.providerId,V=y.credentialSource===Me&&N(h),ce=!r&&!b&&!V&&N(h)?await Ce(h):[],L=ce.filter(k=>!k.authFailure),ke=L.filter(k=>$e(k,u.id)<=Date.now()),T=V?await Oe(h):Ke.has(h)?void 0:ce.length?await Oe(h):void 0;if(V&&T===void 0)continue;if(ce.length>0&&L.length===0&&T===void 0){N(h)&&G.add(h);continue}if(L.length&&!ke.length&&T===void 0){const k=Math.min(...L.map(c=>$e(c,u.id)));k<P&&(P=k,de=`${u.provider}/${u.id}`);const A=dt(u.id);for(const c of L){const C=A!==void 0&&(c.modelCooldowns?.[A]??0)>Date.now()?c.vendorLimits?.[A]:c.rateLimitedUntil>Date.now()?c.vendorLimits?.account:void 0;C!==void 0&&(C.vendorReset!==void 0&&C.vendorReset>Date.now()&&(F=Math.min(F,C.vendorReset)),v??={provider:h,model:C.model,account:c.label,observation:C.observation})}continue}const xe=r||b?[void 0,void 0]:V?["key"]:L.length||T!==void 0?[...ke,...T!==void 0?["key"]:[]]:[void 0];let Re=!1;for(const[k,A]of xe.entries()){if(Re&&A!=="key")continue;const c=A==="key"?void 0:A,C=A==="key",Y=Date.now();let qe=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{qe=await qt(R,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Qe(n))throw n;se??=n;continue}const We=jt(e),U=c||r||b||C?void 0:await R.getApiKeyAndHeaders(u);if(U&&!U.ok)continue;const f=`${u.provider}/${u.id}`,K=e.model??f,fe=d?.environmentPayer,j=b?w===null?null:{payer:fe??w,funding:"endpoint"}:r?Ie({call:"model",route:"endpoint",grantee:r.grantee,environmentPayer:fe}):w===null?null:Ie({call:"model",route:c?"subscription":"key",sub:w,environmentPayer:fe});if(d!==void 0&&j!==null){const n=await ct({scope:"call",payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,provider:h});if(n!==null){if(await be({request:d.request??H,kind:"model",what:f,usd:null,payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),refused:mt(n)}),le??=n,A!=="key"&&xe.includes("key")){Re=!0;continue}break}}let O;if(r&&_)try{O=await Pe({audience:_.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}if(z)try{O=await Pe({audience:z,sub:w,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}let W=null,Ae=!1,g,X,Z,E=!1,M,Q=null,S=3e4,B;const me=[],pe=[],ee=[];let a,D;const te=l((n,m=null)=>({id:H,object:"chat.completion.chunk",created:Math.floor(Y/1e3),model:f,served_model:f,requested_model:K,substituted:K!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),ne=l(n=>{me.push(n),o?.(n)},"emit"),Be=ze(u,We,{apiKey:O?.access_token??qe??(C?T:void 0)??(U?.ok?U.apiKey:void 0),...U?.ok?{headers:U.headers}:{},signal:t,reasoning:e.reasoning_effort??y.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,p=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...p?{tool_choice:p}:{},...e.stop!==void 0?{[u.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,m)=>{const p=await fetch(n,m);if(M=p.status,Q=Ot(p.headers)??Q,b){if(W=p.headers.get("crtr-charge-id")?.trim()||null,p.ok&&!W)throw Ae=!0,await p.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return p.status===402&&(Z=Mt(await p.clone().json().catch(()=>{}))),p}return p.status===429&&(E=!0,B=p.headers,S=ge(p.headers)??15e3),p},"fetch"),onProviderStreamEvent:l(n=>{b&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(g=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!b&&n.status===429&&(E=!0,B=n.headers,S=ge(n.headers)??15e3)},"onResponse")});try{for await(const n of Be)n.type==="text_delta"&&(pe.push(n.delta),ne(te({content:n.delta}))),n.type==="thinking_delta"&&(ee.push(n.delta),ne(te({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const m=nt(n);B===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(lt(n.headers)).length&&(B=n.headers);const p=we({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||b)D=n;else{if(!E&&p.kind!=="rate-limit")throw me.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;E=!0,S=m??S}}if(b){if(Ae)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:f});if(M===402&&Z)throw new i(402,"payment_refused",Z.message,void 0,{payment:Z,served_model:f});if(M===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${z} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||M!==void 0&&M>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${M??"with an error"}`;throw M===403?new i(502,"upstream_refused",m,void 0,{served_model:f}):new i(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(g===null||typeof g!="object"||!("id"in g)||g.id!==W||!("served_model"in g)||typeof g.served_model!="string"||!g.served_model.trim()||!("list_usd"in g)||typeof g.list_usd!="number"||!Number.isFinite(g.list_usd)||g.list_usd<0||Number(g.list_usd.toFixed(6))!==g.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:f,charge_id:W});X={id:W,served_model:g.served_model,list_usd:g.list_usd}}if(r){if(M===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(E&&ge(B)===void 0)throw new i(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!E&&(D!==void 0||M!==void 0&&M>=500))throw new i(503,"upstream_model_unavailable",D instanceof Error?D.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!E&&a?.stopReason==="error"&&we({message:a.errorMessage}).kind==="rate-limit"&&(E=!0,S=15e3),E){const n=it(B,u.id,S),{observation:m,vendorReset:p}=n;if(S=n.retryMs,v={provider:h,model:u.id,...c?{account:c.label}:{},observation:m},console.error(`[llm] 429 from ${f}${c?` account "${c.label}"`:""}: scope=${Ee(m.scope)} retry_after_ms=${S} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await et(h,c.label,S,Y,Date.now(),m.scope,{model:u.id,...p!==void 0?{vendorReset:p}:{},observation:m}),p!==void 0&&(F=Math.min(F,p)),Date.now()+Math.min(S,Se)<P&&(P=Date.now()+Math.min(S,Se),de=f),pe.length||ee.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(r)break;continue}const oe=ut(a);if(M===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:f});if(a?.stopReason==="error"){const n=It(u.provider,a.errorMessage,f);if(n)throw n}if(!a||a.stopReason==="error"&&!oe||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:f});c&&N(h)&&rt(c,u.id)&&await tt(h,c.label,Y,u.id);const he=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),_e=oe?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",ye=a.responseModel?Ct(u,a.responseModel):void 0,I=X?`${u.provider}/${X.served_model}`:ye?`${u.provider}/${ye.model}`:f,re={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:X?X.list_usd:$t(ye??u,a.usage.cost.total),served_model:I};b?d!==void 0&&j!==null&&await be({id:W,request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q}):d!==void 0&&j!==null&&await be({request:d.request??H,kind:"model",what:I,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ue(),vendorRef:Q});const je={id:H,object:"chat.completion",created:Math.floor(Y/1e3),model:I,served_model:I,requested_model:K,substituted:K!==I&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,message:{role:"assistant",content:pe.join("")||null,...ee.length?{reasoning_content:ee.join("")}:{},...he.length?{tool_calls:he}:{},...oe?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:_e}],usage:re,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of he.entries())ne(te({tool_calls:[{index:n,...m}]}));return ne({...te({},_e),model:I,served_model:I,substituted:je.substituted,...oe?{choices:[{index:0,delta:{},finish_reason:_e,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:re}),{completion:je,chunks:me}}}throw le!==void 0?ft(le):P!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await De())?.payment_setup_url??null,reset_at:F===1/0?null:new Date(F).toISOString()},retry_after_s:Math.max(1,Math.ceil((P-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:de,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ee(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):se!==void 0?se:e.model_policy==="exact"?new i(400,"substitution_refused",G.size>0?`your ${[...G].map(Ze).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):_?new i(404,"model_unavailable","no usable model route is available"):await ve()}l(dn,"runLlm");export{qt as freshSubscriptionAccess,sn as llmCallerOf,an as parseLlmRequest,dn as runLlm,$t as usdEquivalent};
3
+ `),J=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...x?{systemPrompt:x}:{},messages:o.slice(d.length),...J?{tools:J}:{}}}l(jt,"contextOf");function Mt(e){return ht(e?.payment)}l(Mt,"paymentOf");function $t(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}l($t,"hostedModel");function St(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:x}=e.cost;return o===0&&s===0&&d===0&&x===0?null:Number.isFinite(t)&&t>=0?t:null}l(St,"usdEquivalent");function Ct(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(Ct,"allowedFallback");function dn(e){return e?{payer:e.payer,sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(dn,"llmCallerOf");function Te(e){return e instanceof gt?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Te,"mintFailure");const It=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Et(e,t,o){if(!(e!=="openai-codex"||t===void 0||!It.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Et,"codexAccountModelRejection");function Ot(e){return e.get("request-id")??e.get("x-request-id")}l(Ot,"vendorRequestId");async function ln(e,t,o,s,d,x,J){const r=x&&yt(x)?x:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const _=r?.inference_endpoint??void 0,w=d===void 0?null:r?.sub??d.sub??await _t(),R=await Ye();let q;_?(q=wt(_,e.model,e.model_policy==="exact").flatMap((y,b)=>{const S=Ve(y.model);return S?[{routeId:"app",credentialSource:"app",family:"app",strength:y.strength,...S,rank:b}]:[]}),q=q.filter(y=>vt(R,e,y))):q=await kt(R,e,s);const ae=!_&&d!==void 0&&w!==null?await pt():null,se=ae===null?void 0:bt(e,q,ae),Ue=se?ae:null;se&&(q=[...q,se]);const Ke=_?new Set:Xe(),ke=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:ie()===null?null:`${ie()}/account/pay`,reset_at:null}}),"nothingLeft");if(q.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):_?new i(404,"model_unavailable","no eligible model route is configured"):await ke();const H=`chatcmpl-${He()}`;let P=1/0,F=1/0,de,v,le,ue;const G=new Set,ce=l(async()=>J??(d?.node?(await Ne(d.node))?.caused_by??null:null)??(d?.run?(await Ne(d.run))?.caused_by??null:null),"causeOf");for(const y of q){const b=y.credentialSource==="hosted";if(!r&&!b&&!(await Ge(y,R)).authenticated){if(y.credentialSource!==$e&&N(y.providerId)){const k=await Ie(y.providerId);k.length>0&&k.every(A=>A.authFailure)&&G.add(y.providerId)}continue}const S=b?$t(R,y.modelId):R.find(y.providerId,y.modelId);if(!S)continue;const z=b?Ue.base_url:void 0,u=_?{...S,baseUrl:`${_.base_url}/${S.provider}`}:z?{...S,baseUrl:`${z}/anthropic`,compat:{...S.compat,allowedFallbackModels:void 0}}:S,h=y.providerId,V=y.credentialSource===$e&&N(h),fe=!r&&!b&&!V&&N(h)?await Ie(h):[],L=fe.filter(k=>!k.authFailure),xe=L.filter(k=>Ce(k,u.id)<=Date.now()),T=V?await De(h):Ke.has(h)?void 0:fe.length?await De(h):void 0;if(V&&T===void 0)continue;if(fe.length>0&&L.length===0&&T===void 0){N(h)&&G.add(h);continue}if(L.length&&!xe.length&&T===void 0){const k=Math.min(...L.map(c=>Ce(c,u.id)));k<P&&(P=k,le=`${u.provider}/${u.id}`);const A=dt(u.id);for(const c of L){const C=A!==void 0&&(c.modelCooldowns?.[A]??0)>Date.now()?c.vendorLimits?.[A]:c.rateLimitedUntil>Date.now()?c.vendorLimits?.account:void 0;C!==void 0&&(C.vendorReset!==void 0&&C.vendorReset>Date.now()&&(F=Math.min(F,C.vendorReset)),v??={provider:h,model:C.model,account:c.label,observation:C.observation})}continue}const Re=r||b?[void 0,void 0]:V?["key"]:L.length||T!==void 0?[...xe,...T!==void 0?["key"]:[]]:[void 0];let qe=!1;for(const[k,A]of Re.entries()){if(qe&&A!=="key")continue;const c=A==="key"?void 0:A,C=A==="key",Y=Date.now();let Ae=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{Ae=await qt(R,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Qe(n))throw n;de??=n;continue}const We=jt(e),U=c||r||b||C?void 0:await R.getApiKeyAndHeaders(u);if(U&&!U.ok)continue;const f=`${u.provider}/${u.id}`,K=e.model??f,me=d?.environmentPayer,j=b?w===null?null:{payer:me??w,funding:"endpoint"}:r?Oe({call:"model",route:"endpoint",grantee:r.grantee,environmentPayer:me}):w===null?null:Oe({call:"model",route:c?"subscription":"key",sub:w,environmentPayer:me});if(d!==void 0&&j!==null){const n=await ct({scope:"call",payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,provider:h});if(n!==null){if(await ve({request:d.request??H,kind:"model",what:f,usd:null,payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ce(),refused:mt(n)}),ue??=n,A!=="key"&&Re.includes("key")){qe=!0;continue}break}}let O;if(r&&_)try{O=await Pe({audience:_.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}if(z)try{O=await Pe({audience:z,sub:w,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Te(n)}let W=null,je=!1,g,X,Z,I=!1,M,Q=null,$=3e4,B;const pe=[],he=[],ee=[];let a,D;const te=l((n,m=null)=>({id:H,object:"chat.completion.chunk",created:Math.floor(Y/1e3),model:f,served_model:f,requested_model:K,substituted:K!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),ne=l(n=>{pe.push(n),o?.(n)},"emit"),Be=ze(u,We,{apiKey:O?.access_token??Ae??(C?T:void 0)??(U?.ok?U.apiKey:void 0),...U?.ok?{headers:U.headers}:{},signal:t,reasoning:e.reasoning_effort??y.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,p=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...p?{tool_choice:p}:{},...e.stop!==void 0?{[u.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,m)=>{const p=await fetch(n,m);if(M=p.status,Q=Ot(p.headers)??Q,b){if(W=p.headers.get("crtr-charge-id")?.trim()||null,p.ok&&!W)throw je=!0,await p.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return p.status===402&&(Z=Mt(await p.clone().json().catch(()=>{}))),p}return p.status===429&&(I=!0,B=p.headers,$=we(p.headers)??15e3),p},"fetch"),onProviderStreamEvent:l(n=>{b&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(g=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!b&&n.status===429&&(I=!0,B=n.headers,$=we(n.headers)??15e3)},"onResponse")});try{for await(const n of Be)n.type==="text_delta"&&(he.push(n.delta),ne(te({content:n.delta}))),n.type==="thinking_delta"&&(ee.push(n.delta),ne(te({reasoning_content:n.delta}))),n.type==="done"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const m=nt(n);B===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(lt(n.headers)).length&&(B=n.headers);const p=be({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||b)D=n;else{if(!I&&p.kind!=="rate-limit")throw pe.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;I=!0,$=m??$}}if(b){if(je)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:f});if(M===402&&Z)throw new i(402,"payment_refused",Z.message,void 0,{payment:Z,served_model:f});if(M===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${z} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||M!==void 0&&M>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${M??"with an error"}`;throw M===403?new i(502,"upstream_refused",m,void 0,{served_model:f}):new i(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(g===null||typeof g!="object"||!("id"in g)||g.id!==W||!("served_model"in g)||typeof g.served_model!="string"||!g.served_model.trim()||!("list_usd"in g)||typeof g.list_usd!="number"||!Number.isFinite(g.list_usd)||g.list_usd<0||Number(g.list_usd.toFixed(6))!==g.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:f,charge_id:W});X={id:W,served_model:g.served_model,list_usd:g.list_usd}}if(r){if(M===401){if(O&&Fe(O.key),k===0)continue;throw new i(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(I&&we(B)===void 0)throw new i(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!I&&(D!==void 0||M!==void 0&&M>=500))throw new i(503,"upstream_model_unavailable",D instanceof Error?D.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!I&&a?.stopReason==="error"&&be({message:a.errorMessage}).kind==="rate-limit"&&(I=!0,$=15e3),I){const n=it(B,u.id,$),{observation:m,vendorReset:p}=n;if($=n.retryMs,v={provider:h,model:u.id,...c?{account:c.label}:{},observation:m},console.error(`[llm] 429 from ${f}${c?` account "${c.label}"`:""}: scope=${Ee(m.scope)} retry_after_ms=${$} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await et(h,c.label,$,Y,Date.now(),m.scope,{model:u.id,...p!==void 0?{vendorReset:p}:{},observation:m}),p!==void 0&&(F=Math.min(F,p)),Date.now()+Math.min($,Se)<P&&(P=Date.now()+Math.min($,Se),le=f),he.length||ee.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(r)break;continue}const oe=ut(a);if(M===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new i(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:f});if(a?.stopReason==="error"){const n=Et(u.provider,a.errorMessage,f);if(n)throw n}if(!a||a.stopReason==="error"&&!oe||a.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:f});c&&N(h)&&rt(c,u.id)&&await tt(h,c.label,Y,u.id);const _e=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),ye=oe?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",ge=a.responseModel?Ct(u,a.responseModel):void 0,E=X?`${u.provider}/${X.served_model}`:ge?`${u.provider}/${ge.model}`:f,re={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:X?X.list_usd:St(ge??u,a.usage.cost.total),served_model:E};b?d!==void 0&&j!==null&&await ve({id:W,request:d.request??H,kind:"model",what:E,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ce(),vendorRef:Q}):d!==void 0&&j!==null&&await ve({request:d.request??H,kind:"model",what:E,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:re.usd_equivalent,payer:j.payer,funding:j.funding,sub:w,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:h,causedBy:await ce(),vendorRef:Q});const Me={id:H,object:"chat.completion",created:Math.floor(Y/1e3),model:E,served_model:E,requested_model:K,substituted:K!==E&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,message:{role:"assistant",content:he.join("")||null,...ee.length?{reasoning_content:ee.join("")}:{},..._e.length?{tool_calls:_e}:{},...oe?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:ye}],usage:re,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of _e.entries())ne(te({tool_calls:[{index:n,...m}]}));return ne({...te({},ye),model:E,served_model:E,substituted:Me.substituted,...oe?{choices:[{index:0,delta:{},finish_reason:ye,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:re}),{completion:Me,chunks:pe}}}throw ue!==void 0?ft(ue):P!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:ie()===null?null:`${ie()}/account/pay`,reset_at:F===1/0?null:new Date(F).toISOString()},retry_after_s:Math.max(1,Math.ceil((P-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:le,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ee(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):de!==void 0?de:e.model_policy==="exact"?new i(400,"substitution_refused",G.size>0?`your ${[...G].map(Ze).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):_?new i(404,"model_unavailable","no usable model route is available"):await ke()}l(ln,"runLlm");export{qt as freshSubscriptionAccess,dn as llmCallerOf,sn as parseLlmRequest,ln as runLlm,St as usdEquivalent};
@@ -1,14 +1,10 @@
1
- /** The first message on a computer not yet signed in to Northlight: the tour and sign-in offered together. */
2
- export declare const FIRST_RUN_OFFER_SENTENCE = "Want a quick tour of how this works? I can also sign you in to Northlight, so I can use your apps like Gmail and Slack, search the web and text you. Say which, or just tell me what you're working on.";
3
- /** The first message on a computer already signed in: the tour alone. */
1
+ /** The first message after setup: the tour offer. */
4
2
  export declare const FIRST_RUN_TOUR_SENTENCE = "Want a quick tour of how this works? Say yes, or just tell me what you're working on.";
5
3
  /** The prompt the front door gives a freshly booted root, and whether the
6
4
  * viewer should play the initial-whip animation (only for a prompt the user
7
- * typed). `signedIn` is whether this computer's records already live in a
8
- * Northlight account. */
5
+ * typed). */
9
6
  export declare function frontDoorBootPrompt(facts: {
10
7
  offerTour: boolean;
11
- signedIn: boolean;
12
8
  userPrompt: string | undefined;
13
9
  }): {
14
10
  prompt: string | undefined;
@@ -1,13 +1,5 @@
1
- var r=Object.defineProperty;var n=(t,o)=>r(t,"name",{value:o,configurable:!0});import{formatCard as e}from"../../shared/generated-context.js";const i="Want a quick tour of how this works? I can also sign you in to Northlight, so I can use your apps like Gmail and Slack, search the web and text you. Say which, or just tell me what you're working on.",s="Want a quick tour of how this works? Say yes, or just tell me what you're working on.",a=e("first-run",{},`Open this conversation with exactly this sentence and nothing else:
1
+ var o=Object.defineProperty;var e=(t,r)=>o(t,"name",{value:r,configurable:!0});import{formatCard as n}from"../../shared/generated-context.js";const i="Want a quick tour of how this works? Say yes, or just tell me what you're working on.",s=n("first-run",{},`Open this conversation with exactly this sentence and nothing else:
2
2
 
3
3
  ${i}
4
4
 
5
- Read the user's answer:
6
- - Sign in (or yes to signing in): run \`crtr sys signin\` and follow what it prints.
7
- - Tour (or yes to the tour): run \`crtr sys tutorial basic\` and teach it one lesson per invocation \u2014 in your own words, letting them try each thing before moving on.
8
- - Both: sign in first. When this conversation resumes after the sign-in, start the tour.
9
- - Anything else: drop both offers and do what they asked. Do not mention the tour or signing in again in this conversation. A command that later answers that it needs a Northlight account still gets its one ask; that answer says how.`),h=e("first-run",{},`Open this conversation with exactly this sentence and nothing else:
10
-
11
- ${s}
12
-
13
- If the user says yes, run \`crtr sys tutorial -h\`, pick the track it names, and teach it one lesson per invocation \u2014 in your own words, letting them try each thing before moving on. If the user says anything else, drop the tour entirely and do what they asked.`);function c(t){return t.userPrompt!==void 0&&t.userPrompt.trim()!==""?{prompt:t.userPrompt,initialWhip:!0}:t.offerTour?{prompt:t.signedIn?h:a,initialWhip:!1}:{prompt:void 0,initialWhip:!1}}n(c,"frontDoorBootPrompt");export{i as FIRST_RUN_OFFER_SENTENCE,s as FIRST_RUN_TOUR_SENTENCE,c as frontDoorBootPrompt};
5
+ If the user says yes, run \`crtr sys tutorial -h\`, pick the track it names, and teach it one lesson per invocation \u2014 in your own words, letting them try each thing before moving on. If the user says anything else, drop the tour entirely and do what they asked.`);function u(t){return t.userPrompt!==void 0&&t.userPrompt.trim()!==""?{prompt:t.userPrompt,initialWhip:!0}:t.offerTour?{prompt:s,initialWhip:!1}:{prompt:void 0,initialWhip:!1}}e(u,"frontDoorBootPrompt");export{i as FIRST_RUN_TOUR_SENTENCE,u as frontDoorBootPrompt};
@@ -1,12 +1,11 @@
1
- var L=Object.defineProperty;var p=(i,a)=>L(i,"name",{value:a,configurable:!0});import{existsSync as b,statSync as M}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as $}from"../../build-root.js";import{FRONT_DOOR_ENV as W}from"./front-door-env.js";import{frontDoorBootPrompt as B}from"./first-run-offer.js";import{readMachineConfig as R}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as V}from"./node-id-token.js";import{markTourOffered as G,recordSetupCompleted as U,setupCompleted as y,tourOfferPending as Y}from"./setup-marker.js";function I(i){try{return b(i)&&M(i).isDirectory()}catch{return!1}}p(I,"isDir");const j=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function J(){let i=!1;const a=p(()=>{i=!0},"onSigint");process.once("SIGINT",a);try{const{runSetup:t}=await import("../../commands/sys/setup-wizard.js"),e=await t();if(i){const l=new Error("Interrupted");throw l.name="AbortError",l}await U(e)}finally{process.removeListener("SIGINT",a)}}p(J,"runFirstSetup");function X(i){let a=process.cwd(),t,e,l,f=!1,u,g;const o=[];for(let d=0;d<i.length;d++){const s=i[d];if(s==="--name")t=i[++d];else if(s==="--kind")e=i[++d];else if(s==="--profile")l=i[++d];else if(s==="--pick-profile")f=!0;else if(s==="--continue"||s==="-c")u="continue";else if(s==="--resume"||s==="-r"){u="pick";const w=i[d+1];w!==void 0&&V(w)&&!I(h(w))&&(g=w,d++)}else s.startsWith("--")||o.push(s)}o.length>0&&I(h(o[0]))&&(a=h(o.shift()));const m=o.length>0?o.join(" "):void 0;return{cwd:a,prompt:m,name:t,kind:e,profile:l,pickProfile:f,resume:u,resumeId:g}}p(X,"parseRootArgs");import{FRONT_DOOR_ENV as ae}from"./front-door-env.js";async function oe(i){const a=i.slice(2),t=a[0];if(process.env[W]||t==="-h"||t==="--help"||t==="--version"||t==="-v"||t!==void 0&&$.includes(t))return!1;if(t!==void 0){const r=/\s/.test(t),n=!t.startsWith("-")&&I(h(t)),c=j.has(t);if(!r&&!n&&!c)return!1;if(n){const{buildRoot:D}=await import("../../build-root.js");if((await D()).subtrees.some(A=>A.name===t))return!1}}const e=X(a),l=p(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:r}=await import("../profiles/manifest.js");e.profile=r(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await l();const f=process.stdin.isTTY&&process.stdout.isTTY;if(R()===void 0){f||(process.stderr.write("crtr: this computer is not signed in to Northlight; run `crtr sys signin`.\n"),process.exit(1));const{sysSigninLeaf:r}=await import("../../commands/sys/signin.js");try{await r.run({},{}),await(await import("../../commands/person-settings.js")).loadPersonSettingsViaApi()}catch(n){process.stderr.write(`${n instanceof Error?n.message:String(n)}
2
- `),process.exit(1)}}let u=!1;const g=f&&!y()&&(await(await import("../../commands/api-client.js")).cliClient().getModelAuthReadiness({cwd:e.cwd})).hosted_endpoint;f&&!y()&&!g&&(await J(),u=!0);let o=null,m,d=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:r,noResumeTargetMessage:n}=await import("./resume-root.js"),c=await r(e.resumeId);"error"in c&&(process.stderr.write(`${c.error}
3
- `),process.exit(1)),"none"in c?(e.resumeId.includes("-")&&(process.stderr.write(`${n(e.resumeId)}
4
- `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await l()):(o=c.node.profile_id,m=c.node.node_id,I(c.node.cwd)&&(d=c.node.cwd))}if(m===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:n}=await import("../profiles/select.js");u&&e.profile===void 0&&process.stdout.write(`
1
+ var v=Object.defineProperty;var m=(t,s)=>v(t,"name",{value:s,configurable:!0});import{existsSync as _,statSync as x}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as D}from"../../build-root.js";import{FRONT_DOOR_ENV as F}from"./front-door-env.js";import{frontDoorBootPrompt as E}from"./first-run-offer.js";import{readMachineConfig as C}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as b}from"./node-id-token.js";import{markTourOffered as A,recordSetupCompleted as L,setupCompleted as W,tourOfferPending as $}from"./setup-marker.js";function T(t){try{return _(t)&&x(t).isDirectory()}catch{return!1}}m(T,"isDir");const B=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function M(){let t=!1;const s=m(()=>{t=!0},"onSigint");process.once("SIGINT",s);try{const{runSetup:r}=await import("../../commands/sys/setup-wizard.js"),e=await r();if(t){const c=new Error("Interrupted");throw c.name="AbortError",c}await L(e)}finally{process.removeListener("SIGINT",s)}}m(M,"runFirstSetup");function G(t){let s=process.cwd(),r,e,c,l=!1,u,p;const i=[];for(let f=0;f<t.length;f++){const n=t[f];if(n==="--name")r=t[++f];else if(n==="--kind")e=t[++f];else if(n==="--profile")c=t[++f];else if(n==="--pick-profile")l=!0;else if(n==="--continue"||n==="-c")u="continue";else if(n==="--resume"||n==="-r"){u="pick";const w=t[f+1];w!==void 0&&b(w)&&!T(h(w))&&(p=w,f++)}else n.startsWith("--")||i.push(n)}i.length>0&&T(h(i[0]))&&(s=h(i.shift()));const g=i.length>0?i.join(" "):void 0;return{cwd:s,prompt:g,name:r,kind:e,profile:c,pickProfile:l,resume:u,resumeId:p}}m(G,"parseRootArgs");import{FRONT_DOOR_ENV as re}from"./front-door-env.js";async function Q(t){const s=t.slice(2),r=s[0];if(process.env[F]||r==="-h"||r==="--help"||r==="--version"||r==="-v"||r!==void 0&&D.includes(r))return!1;if(r!==void 0){const o=/\s/.test(r),d=!r.startsWith("-")&&T(h(r)),a=B.has(r);if(!o&&!d&&!a)return!1;if(d){const{buildRoot:O}=await import("../../build-root.js");if((await O()).subtrees.some(S=>S.name===r))return!1}}const e=G(s),c=m(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:o}=await import("../profiles/manifest.js");e.profile=o(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await c();const l=process.stdin.isTTY&&process.stdout.isTTY;C()===void 0&&!l&&(process.stderr.write("crtr: this computer is not signed in to Northlight; run `crtr sys signin`.\n"),process.exit(1));let u=!1;l&&!W()&&(await M(),u=!0);let p=null,i,g=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:o,noResumeTargetMessage:d}=await import("./resume-root.js"),a=await o(e.resumeId);"error"in a&&(process.stderr.write(`${a.error}
2
+ `),process.exit(1)),"none"in a?(e.resumeId.includes("-")&&(process.stderr.write(`${d(e.resumeId)}
3
+ `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await c()):(p=a.node.profile_id,i=a.node.node_id,T(a.node.cwd)&&(g=a.node.cwd))}if(i===void 0){const{selectProfileForCwd:o,selectProfileForCwdReadOnly:d}=await import("../profiles/select.js");u&&e.profile===void 0&&process.stdout.write(`
5
4
  Choose a profile
6
- `),o=e.profile??(f?await r(e.cwd,void 0,e.pickProfile,!1):n(e.cwd))}const{cliClient:s}=await import("../../commands/api-client.js"),[{exitForMissingProviderCredential:w,hasConfiguredProviderCredential:k},S]=await Promise.all([import("./provider-credential-gate.js"),o===null?[]:s().listProfileEnv(o).then(r=>r.names)]),v=p(async()=>{const r=await s().getModelAuthReadiness({cwd:e.cwd,...o===null?{}:{profile:o}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await k(S)&&!await v()){f||w();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||w()}const{inTmux:P}=await import("./placement-tmux.js");if(f&&!P()){const{TMUX_STARTED_ENV:r,handoffToTmux:n}=await import("./tmux-handoff.js");process.env[r]===void 0&&n(a,m!==void 0?null:o,d)}const[{bootRoot:N},{resumeRoot:O},{rendererWarning:_,missingPackageWarning:x,piAgentDir:C}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=x(C());r!==null&&process.stderr.write(`
7
- ${r}
5
+ `),p=e.profile??(l?await o(e.cwd,void 0,e.pickProfile,!1):d(e.cwd))}const{inTmux:f}=await import("./placement-tmux.js");if(l&&!f()){const{TMUX_STARTED_ENV:o,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[o]===void 0&&d(s,i!==void 0?null:p,g)}const[{bootRoot:n},{resumeRoot:w},{rendererWarning:R,missingPackageWarning:k,piAgentDir:y}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const o=k(y());o!==null&&process.stderr.write(`
6
+ ${o}
8
7
 
9
- `);const n=_();n!==null&&process.stderr.write(`
10
- ${n}
8
+ `);const d=R();d!==null&&process.stderr.write(`
9
+ ${d}
11
10
 
12
- `)}catch{}if(m!==void 0){const{resumeNodeById:r}=await import("./resume-root.js");await r(m)}if(e.resume!==void 0&&await O(e.cwd,e.resume==="pick")==="aborted")return!0;const T=f&&(u||await Y()),{prompt:E,initialWhip:F}=B({offerTour:T,signedIn:T&&R()!==void 0,userPrompt:e.prompt});return T&&P()&&await G(),await N({...e,prompt:E,initialWhip:F,selectedProfileId:o??void 0}),!0}p(oe,"maybeBootRoot");export{ae as FRONT_DOOR_ENV,oe as maybeBootRoot,X as parseRootArgs};
11
+ `)}catch{}if(i!==void 0){const{resumeNodeById:o}=await import("./resume-root.js");await o(i)}if(e.resume!==void 0&&await w(e.cwd,e.resume==="pick")==="aborted")return!0;const I=l&&(u||await $()),{prompt:P,initialWhip:N}=E({offerTour:I,userPrompt:e.prompt});return I&&f()&&await A(),await n({...e,prompt:P,initialWhip:N,selectedProfileId:p??void 0}),!0}m(Q,"maybeBootRoot");export{re as FRONT_DOOR_ENV,Q as maybeBootRoot,G as parseRootArgs};
@@ -30,5 +30,5 @@ export declare function piAgentDir(homeDir?: string): string;
30
30
  */
31
31
  export declare function findMissingPackagePaths(agentDir: string, homeDir?: string): MissingPackage[];
32
32
  /** A human-readable, actionable warning for a set of missing packages, or
33
- * `null` when nothing is missing. Names `crtr sys setup` as the fix. */
33
+ * `null` when nothing is missing. */
34
34
  export declare function missingPackageWarning(agentDir: string, homeDir?: string): string | null;
@@ -1,4 +1,5 @@
1
- var u=Object.defineProperty;var t=(r,e)=>u(r,"name",{value:e,configurable:!0});import{existsSync as f,readFileSync as g}from"node:fs";import{homedir as a}from"node:os";import{appSpace as m}from"../layout.js";import{join as c,resolve as d}from"node:path";import{isRendererReady as h}from"../termrender/termrender.js";import{expandTilde as l}from"../fs-utils.js";function j(){return h()?null:"crtr: the pinned termrender renderer is not provisioned \u2014 pages, reviews, and inline diagrams render as plaintext.\n Fix: run `crtr sys setup` (requires `uv`: curl -LsSf https://astral.sh/uv/install.sh | sh)."}t(j,"rendererWarning");function w(r=a()){const e=process.env.PI_CODING_AGENT_DIR;return e!==void 0&&e!==""?l(e,r):c(r===a()?m("terminal").home:r,".pi","agent")}t(w,"piAgentDir");function y(r){return r.startsWith("npm:")?!1:r.startsWith(".")||r.startsWith("/")||r.startsWith("~")}t(y,"isLocalPathSource");function v(r,e=a()){let n;try{n=g(c(r,"settings.json"),"utf8")}catch{return[]}let s;try{s=JSON.parse(n).packages}catch{return[]}if(!Array.isArray(s))return[];const i=[];for(const o of s){if(typeof o!="string"||!y(o))continue;const p=d(r,l(o,e));f(p)||i.push({source:o,resolved:p})}return i}t(v,"findMissingPackagePaths");function F(r,e=a()){const n=v(r,e);if(n.length===0)return null;const s=n.map(i=>` \u2022 ${i.source}
2
- \u2192 ${i.resolved} (missing)`);return`crtr: ${n.length} configured pi package path${n.length===1?"":"s"} no longer exist${n.length===1?"s":""} \u2014 pi silently skips these, so their slash commands (e.g. ~/.claude commands & marketplace plugins) will not load.
3
- `+s.join(`
4
- `)+"\n Fix: re-run `crtr sys setup` (re-resolves package paths to this repo's current location)."}t(F,"missingPackageWarning");export{v as findMissingPackagePaths,F as missingPackageWarning,w as piAgentDir,j as rendererWarning};
1
+ var u=Object.defineProperty;var r=(e,t)=>u(e,"name",{value:t,configurable:!0});import{existsSync as d,readFileSync as f}from"node:fs";import{homedir as a}from"node:os";import{appSpace as h}from"../layout.js";import{join as l,resolve as m}from"node:path";import{isRendererReady as g}from"../termrender/termrender.js";import{expandTilde as c}from"../fs-utils.js";function j(){return g()?null:"crtr: the pinned termrender renderer is not provisioned \u2014 pages, reviews, and inline diagrams render as plaintext.\n Fix: install `uv` (curl -LsSf https://astral.sh/uv/install.sh | sh); the next render provisions the renderer."}r(j,"rendererWarning");function A(e=a()){const t=process.env.PI_CODING_AGENT_DIR;return t!==void 0&&t!==""?c(t,e):l(e===a()?h("terminal").home:e,".pi","agent")}r(A,"piAgentDir");function x(e){return e.startsWith("npm:")?!1:e.startsWith(".")||e.startsWith("/")||e.startsWith("~")}r(x,"isLocalPathSource");function v(e,t=a()){let n;try{n=f(l(e,"settings.json"),"utf8")}catch{return[]}let i;try{i=JSON.parse(n).packages}catch{return[]}if(!Array.isArray(i))return[];const s=[];for(const o of i){if(typeof o!="string"||!x(o))continue;const p=m(e,c(o,t));d(p)||s.push({source:o,resolved:p})}return s}r(v,"findMissingPackagePaths");function F(e,t=a()){const n=v(e,t);if(n.length===0)return null;const i=n.map(s=>` \u2022 ${s.source}
2
+ \u2192 ${s.resolved} (missing)`);return`crtr: ${n.length} configured pi package path${n.length===1?"":"s"} no longer exist${n.length===1?"s":""} \u2014 pi silently skips these, so their slash commands (e.g. ~/.claude commands & marketplace plugins) will not load.
3
+ `+i.join(`
4
+ `)+`
5
+ Fix: correct or remove the path in ${l(e,"settings.json")} (crtr does not write this file; its own extensions load without it).`}r(F,"missingPackageWarning");export{v as findMissingPackagePaths,F as missingPackageWarning,A as piAgentDir,j as rendererWarning};
@@ -1,7 +1,7 @@
1
1
  import type { CredentialStore } from '@earendil-works/pi-ai';
2
2
  /** The daemon, which owns the rows, registers a builder of its row-backed read-only view (one read per table); every other process asks the daemon over /v1/model-auth. */
3
3
  export declare function registerGateCredentialStore(snapshot: () => Promise<CredentialStore>): void;
4
- export declare const NO_PROVIDER_CREDENTIAL_MESSAGE = "crtr: no provider credential; run `crtr sys setup` to log in.";
4
+ export declare const NO_PROVIDER_CREDENTIAL_MESSAGE = "crtr: no provider credential; log in under Providers in `crtr sys settings`.";
5
5
  /** Check the setup catalog before a path creates a broker-backed node. `profileEnvNames` are the names stored on the
6
6
  * launching profile (values are never needed: a stored value is never empty). */
7
7
  export declare function hasConfiguredProviderCredential(profileEnvNames: readonly string[]): Promise<boolean>;
@@ -1,2 +1,2 @@
1
- var d=Object.defineProperty;var t=(e,o)=>d(e,"name",{value:o,configurable:!0});import{ModelRegistry as c,ModelRuntime as l}from"@earendil-works/pi-coding-agent";import{join as m}from"node:path";import{ApiCredentialStore as p}from"../model-auth/api-credential-store.js";import{cliClient as f}from"../../commands/api-client.js";import{hasProviderCredential as u}from"../provider-credential.js";import{piAgentDir as E}from"./package-health.js";import{PROVIDER_ENV_KEYS as w}from"./spawn-env.js";let a;function D(e){a=e}t(D,"registerGateCredentialStore");function g(e){const o=new Map;let n;const i=t(()=>{throw new Error("the provider credential check is read-only")},"refuse");return{read:t(r=>{let s=o.get(r);return s===void 0&&o.set(r,s=e.read(r)),s},"read"),list:t(()=>n??=e.list(),"list"),modify:i,delete:i}}t(g,"readOnceStore");const h="crtr: no provider credential; run `crtr sys setup` to log in.";async function M(e){const o=Object.fromEntries(e.map(r=>[r,"stored"]));if(Object.values(w).some(r=>(o[r]??process.env[r])?.trim()))return!0;const n=E(),i=await l.create({credentials:a===void 0?g(new p(()=>f(),!0)):await a(),modelsPath:m(n,"models.json")});return await u(i,new c(i))}t(M,"hasConfiguredProviderCredential");function _(){process.stderr.write(`${h}
1
+ var a=Object.defineProperty;var t=(e,i)=>a(e,"name",{value:i,configurable:!0});import{ModelRegistry as c,ModelRuntime as l}from"@earendil-works/pi-coding-agent";import{join as m}from"node:path";import{ApiCredentialStore as f}from"../model-auth/api-credential-store.js";import{cliClient as p}from"../../commands/api-client.js";import{hasProviderCredential as u}from"../provider-credential.js";import{piAgentDir as E}from"./package-health.js";import{PROVIDER_ENV_KEYS as g}from"./spawn-env.js";let d;function D(e){d=e}t(D,"registerGateCredentialStore");function w(e){const i=new Map;let n;const o=t(()=>{throw new Error("the provider credential check is read-only")},"refuse");return{read:t(r=>{let s=i.get(r);return s===void 0&&i.set(r,s=e.read(r)),s},"read"),list:t(()=>n??=e.list(),"list"),modify:o,delete:o}}t(w,"readOnceStore");const h="crtr: no provider credential; log in under Providers in `crtr sys settings`.";async function M(e){const i=Object.fromEntries(e.map(r=>[r,"stored"]));if(Object.values(g).some(r=>(i[r]??process.env[r])?.trim()))return!0;const n=E(),o=await l.create({credentials:d===void 0?w(new f(()=>p(),!0)):await d(),modelsPath:m(n,"models.json")});return await u(o,new c(o))}t(M,"hasConfiguredProviderCredential");function _(){process.stderr.write(`${h}
2
2
  `),process.exit(1)}t(_,"exitForMissingProviderCredential");export{h as NO_PROVIDER_CREDENTIAL_MESSAGE,_ as exitForMissingProviderCredential,M as hasConfiguredProviderCredential,D as registerGateCredentialStore};
@@ -15,6 +15,9 @@ export interface MachineExecutorDeps {
15
15
  signal: string | null;
16
16
  }) => void;
17
17
  }
18
+ /** The app's pi settings with this install's bundled `pi-crtr-extensions` as the only crtr package entry: the same absolute path a sandbox broker gets (host.ts),
19
+ * so the broker loads the package of the generation that launches it. Other settings and packages the person set are kept. */
20
+ export declare function withBundledExtensions(settingsJson: string | undefined): string;
18
21
  /** Broker processes: `{pid, execution, node}` for each `broker-cli.js ... --epoch <execution> <node>` command line. Throws when the process table cannot
19
22
  * be read: an unreadable table is not an empty one, and a caller that read it as "no brokers" would start a second broker or report a stop that did not happen. */
20
23
  export declare function findBrokers(): Promise<Array<{