@north-light/cli 0.3.693 → 0.3.694
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/errors.js +1 -1
- package/dist/cli.js +6 -6
- package/dist/clients/attach/viewer.js +496 -496
- package/dist/commands/node/inspect.js +9 -9
- package/dist/commands/pkg/market-manage.js +1 -1
- package/dist/commands/pkg/plugin-manage.js +1 -1
- package/dist/commands/sys/update.js +1 -1
- package/dist/core/canvas/canvas.js +6 -6
- package/dist/core/config.js +1 -1
- package/dist/core/graph/exposures.js +1 -1
- package/dist/core/graph/watches.js +1 -1
- package/dist/core/installed-plugins.js +1 -1
- package/dist/core/scoped-state/imported-mac-installs.d.ts +12 -0
- package/dist/core/scoped-state/imported-mac-installs.js +2 -0
- package/dist/core/spaces/stop.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/shared/env.d.ts +8 -3
- package/dist/shared/env.js +2 -2
- package/dist/types.d.ts +1 -1
- package/dist/types.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/errors.js +1 -1
- package/packages/crouter-api/dist/commands/node/inspect.js +16 -2
- package/packages/crouter-api/dist/commands/pkg/market-manage.js +22 -19
- package/packages/crouter-api/dist/commands/pkg/plugin-manage.js +2 -1
- package/packages/crouter-api/dist/commands/sys/update.js +5 -3
- package/packages/crouter-api/dist/core/canvas/canvas.js +4 -8
- package/packages/crouter-api/dist/core/config.js +10 -3
- package/packages/crouter-api/dist/core/graph/exposures.js +1 -1
- package/packages/crouter-api/dist/core/graph/watches.js +1 -1
- package/packages/crouter-api/dist/core/installed-plugins.js +3 -2
- package/packages/crouter-api/dist/core/scoped-state/imported-mac-installs.js +94 -0
- package/packages/crouter-api/dist/core/spaces/stop.js +2 -2
- package/packages/crouter-api/dist/shared/env.js +15 -4
- package/packages/crouter-api/dist/types.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
package/dist/core/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Je=Object.defineProperty;var s=(e,n)=>Je(e,"name",{value:n,configurable:!0});import{envProfileId as Ve}from"../shared/env.js";import{basename as oe,join as re}from"node:path";import{existsSync as Ye,mkdirSync as Ze,statSync as Xe}from"node:fs";import{isDeepStrictEqual as Qe}from"node:util";import{CONFIG_FILE as en,STATE_FILE as nn,CONDENSED_HISTORY_MODES as tn,VERBOSITY_LEVELS as on,MOUSE_MODE_DEFAULTS as rn,WHIP_MESSAGE_MODES as sn,DEFAULT_WHIP_MESSAGES as ie,defaultScopeConfig as w,defaultScopeState as se,defaultModelLaddersConfig as cn,defaultKindsConfig as un,defaultRemoteCanvasConfig as dn}from"../types.js";import{BINDING_CATALOG as an,BINDING_IDS as fn,isAttachPaneBinding as ln}from"./keybindings/catalog.js";import{notFound as pn}from"./errors.js";import{emitEvent as ce}from"./events/emit.js";import{LEDGER_ENV as mn}from"./ledger/rates.js";import{atomicWriteJson as G,readJsonIfExists as O,ensureDir as gn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as yn,userScopeRoot as ue}from"./scope.js";import{listInstalledPluginsInRoot as de}from"./installed-plugins.js";import{profileDir as ae,listProfiles as fe}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{readCachedSettings as q,readCachedState as hn,revisionOf as B,SettingsRevisionConflictError as le,writeSettings as W}from"./scoped-state/person-store.js";import{withExclusiveDirectoryLock as bn}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as vn}from"./user-settings.js";import{normalizeWorkingGerunds as _n}from"../shared/working-activity.js";import{mergePageComponentLayers as wn,normalizePageComponents as pe}from"./human/page-catalog.js";function h(e){return re(e,en)}s(h,"configPathFor");function H(e,n){return bn(`${e}.lock`,()=>n(e),{timeoutError:s(()=>new Error(`timed out waiting for config lock: ${e}`),"timeoutError")})}s(H,"withConfigPathLock");function J(e){return re(e,nn)}s(J,"statePathFor");function bt(e){const n=g(e);return n?h(n):null}s(bt,"configPath");function vt(e){const n=g(e);return n?J(n):null}s(vt,"statePath");function S(e){const n=A(e),t=A(ue());if(n===t)return{key:"user",kind:"user",root:t};if(oe(n)===".crouter")return{key:"project",kind:"project",root:n};for(const o of fe()){const r=A(ae(o.profileId));if(n===r)return{key:`profile:${o.profileId}`,kind:"profile",root:r,profileId:o.profileId}}throw new Error(`settings root is not a recognized owner: ${e}`)}s(S,"settingsOwnerForRoot");function P(e){if(oe(e)===".crouter"){let n;try{n=A(e)}catch(t){if(t.code==="ENOENT")return null;throw t}if(n!==A(ue()))return O(h(e))}return q(S(e).key).settings}s(P,"readRawAtRoot");async function me(e,n){let t;return await W(o=>{const r=o.settings[e],i=n(structuredClone(r??{}));return t=i.value,[{op:"settings.replace",owner:e,raw:i.next,ifRevision:B(r)}]}),t}s(me,"mutatePersonSettings");async function V(e,n){const t=S(e);if(t.kind==="project"){H(h(t.root),o=>G(o,n,{createParent:!1}));return}await me(t.key,()=>({value:void 0,next:n}))}s(V,"writeRawAtRoot");async function j(e,n){const t=S(e);return t.kind==="project"?H(h(t.root),o=>{const r=n(O(o)??{});return G(o,r.next,{createParent:!1}),r.value}):await me(t.key,n)}s(j,"mutateRawAtRoot");const I=globalThis,C=Symbol.for("crtr.broker.config-snapshot");function _t(e){I[C]=e}s(_t,"installBrokerConfigSnapshot");function wt(){return I[C]}s(wt,"brokerConfigSnapshot");function kn(e){const n=I[C];if(n){if(e!=="user")throw new Error(`broker config snapshot has no ${e} scope`);return n.user}const t=g(e);return t?An(t):w()}s(kn,"readConfig");function An(e){const n=P(e);return n?K(n):w()}s(An,"readConfigAtRoot");function Sn(e){const n=O(J(e));return{marketplaces:n?.marketplaces??{},plugins:n?.plugins??{},activeCanvas:n?.activeCanvas??null,...n?.last_self_check===void 0?{}:{last_self_check:n.last_self_check}}}s(Sn,"readProjectState");function jn(e){const n=g(e);return n?e==="project"?Ye(n)?Sn(n):se():hn(S(n).key):se()}s(jn,"readState");class xn extends Error{static{s(this,"InvalidRawSettingsError")}constructor(n){super(`settings cannot be merged: ${n instanceof Error?n.message:String(n)}`),this.name="InvalidRawSettingsError"}}function ge(e){if(e.scope==="user")return"user";if(!fe().some(n=>n.profileId===e.profileId))throw pn(`profile not found: ${e.profileId}`,{received:e.profileId,next:"Run `crtr profile list` to see available profiles."});return`profile:${e.profileId}`}s(ge,"rawSettingsKeyForTarget");function kt(e){return q(ge(e))}s(kt,"readRawSettingsForTarget");async function At(e,n,t){const o=ge(e);try{K(n)}catch(u){throw new xn(u)}if(q(o).revision!==t)throw new le;const i=await W(u=>B(u.settings[o])===t?[{op:"settings.replace",owner:o,raw:n,ifRevision:t}]:(()=>{throw new le})()),c=B(i.settings[o]);return{revision:c,changed:c!==t}}s(At,"replaceRawSettingsForTarget");async function St(e,n){const t=k(e);return await j(t,o=>{const r=n(o);return{value:r,next:r}})}s(St,"updateRawConfigAtomically");async function jt(e,n){await V(k(e),n)}s(jt,"writeConfig");async function xt(e,n){await V(k(e),n)}s(xt,"writeRawConfig");function Rn(e,n){H(J(e),t=>G(t,n,{createParent:!1}))}s(Rn,"writeProjectState");async function En(e,n){const t=k(e);if(e==="project"){Rn(t,n);return}const o=S(t).key;await W(()=>[{op:"state.write",owner:o,state:n}])}s(En,"writeState");async function Rt(e,n){if(e!=="project"){gn(n);return}try{Ze(n)}catch(t){if(t.code!=="EEXIST"||!Xe(n).isDirectory())throw t}O(h(n))===null&&await V(n,{schema_version:w().schema_version})}s(Rt,"ensureScopeInitialized");function On(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[t,o]of Object.entries(e))Array.isArray(o)&&o.every(r=>typeof r=="string")&&(n[t]=[...o]);return n}s(On,"normalizeKeybindings");const Pn=new Set(an.filter(ln).map(e=>e.id));function In(e){return Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&fn.has(n)&&Pn.has(n)))]:[]}s(In,"normalizeTmuxPassthrough");function T(e,n=cn()){const t=n;if(e===null||typeof e!="object")return t;const o=e,r={anthropic:{...t.anthropic},openai:{...t.openai},...t.defaultProvider!==void 0?{defaultProvider:t.defaultProvider}:{}};(o.defaultProvider==="anthropic"||o.defaultProvider==="openai")&&(r.defaultProvider=o.defaultProvider);for(const i of["anthropic","openai"]){const c=o[i];if(!(c===null||typeof c!="object"))for(const[u,d]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof d=="string"&&(r[i][u]=d)}return r}s(T,"mergeModelLadders");function ye(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(ye,"validStrength");const Y=["ultra","strong","medium","light"];function Z(){return Object.create(null)}s(Z,"routeRecord");function x(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function he(e){const n=Z();for(const[t,o]of Object.entries(e??{}))x(n,t,o);return n}s(he,"copyRouteRecord");function R(e,n){ce({level:"warn",event:"config.model_routes.invalid",fields:{route_id:e,rule:n}})}s(R,"routeInvalid");function $(e,n={}){const t=he(n);if(e===null||typeof e!="object"||Array.isArray(e))return t;for(const[o,r]of Object.entries(e)){if(o.trim()===""){R(o,"route id must be a non-empty string");continue}if(r===null||typeof r!="object"||Array.isArray(r)){R(o,"route must be an object");continue}const i=r,c=t[o],u={...c};let d;for(const f of["family","credentialSource","providerId"]){const a=i[f];if(a!==void 0){if(typeof a!="string"||a.trim()===""){d=`${f} must be a non-empty string`;break}u[f]=a}}if(d===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))d="models must be an object";else{const f={...c?.models};for(const[a,l]of Object.entries(i.models)){if(!ye(a)){d=`models.${a} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){d=`models.${a} must be a non-empty provider/id ref`;break}const p=l.indexOf("/");if(p<=0||p===l.length-1){d=`models.${a} must be provider/id`;break}f[a]=l}u.models=f}if(d===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,a]of Object.entries(u.models))if(a.slice(0,a.indexOf("/"))!==u.providerId){d=`models.${f} provider prefix must equal providerId`;break}}if(d!==void 0){R(o,d);continue}x(t,o,u)}return t}s($,"mergeModelRoutePatches");function be(e){const n=Z(),t=Z();for(const[o,r]of Object.entries(e)){if(r.family===void 0||r.credentialSource===void 0||r.providerId===void 0||r.models===void 0){R(o,"route must include family, credentialSource, providerId, and models");continue}const i=Y.filter(c=>r.models[c]===void 0);if(i.length>0){R(o,`incomplete route; missing strengths: ${i.join(", ")}`),x(t,o,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models});continue}x(n,o,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models})}return{complete:n,legacy:t}}s(be,"resolveModelRoutes");function Cn(e,n){if(e.trim()==="")throw new Error("model route id must be a non-empty string");for(const o of["family","credentialSource","providerId"])if(typeof n[o]!="string"||n[o].trim()==="")throw new Error(`model route "${e}" ${o} must be a non-empty string`);const t=Y.filter(o=>n.models?.[o]===void 0);if(t.length>0)throw new Error(`model route "${e}" is incomplete; missing strengths: ${t.join(", ")}`);for(const o of Y){const r=n.models[o];if(typeof r!="string"||r.trim()==="")throw new Error(`model route "${e}" models.${o} must be a non-empty provider/id ref`);const i=r.indexOf("/");if(i<=0||i===r.length-1)throw new Error(`model route "${e}" models.${o} must be provider/id`);if(r.slice(0,i)!==n.providerId)throw new Error(`model route "${e}" models.${o} provider prefix must equal providerId`)}}s(Cn,"assertCompleteModelRoute");function M(e,n){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return n;const t=e,o=s(i=>Array.isArray(i)&&i.every(c=>typeof c=="string"&&c.trim()!=="")?[...i]:void 0,"strings"),r=Array.isArray(t.strengthFallback)&&t.strengthFallback.every(i=>ye(i))?[...t.strengthFallback]:void 0;return{...o(t.credentialSourceOrder)!==void 0?{credentialSourceOrder:o(t.credentialSourceOrder)}:{},...o(t.familyOrder)!==void 0?{familyOrder:o(t.familyOrder)}:{},...r!==void 0?{strengthFallback:r}:{}}}s(M,"mergeModelRouting");function Tn(e){return e!==""&&e.replace(/\*/g,"")===""}s(Tn,"isInheritAllGlob");function N(e,n=[]){const t=e,o=Array.isArray(t?.allow)?t.allow.filter(r=>typeof r=="string"):[];for(const r of o)if(Tn(r))throw new Error(`spawnEnv.allow: "${r}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...n,...o])]}}s(N,"mergeSpawnEnv");function L(e,n={}){const t={};for(const[o,r]of Object.entries(n))t[o]={...r};if(e!==null&&typeof e=="object")for(const[o,r]of Object.entries(e)){if(r===null||typeof r!="object")continue;const i={...t[o]},c=r.fastMode;typeof c=="boolean"&&(i.fastMode=c),t[o]=i}return t}s(L,"mergeProviderOptions");const ve=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,$n=new Set(["crtr","crtrd"]);function F(e,n){if(n==="bin"&&$n.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!ve.test(e))return`${n}.${e} is not a safe bare command name (expected ${ve.source})`}s(F,"bareCommandNameIssue");function Mn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"bin",message:"bin must be a JSON object mapping bare command name to a relative path"}];const n=[];for(const[t,o]of Object.entries(e)){const r=F(t,"bin");r!==void 0&&n.push({name:t,message:r}),(typeof o!="string"||o.trim()==="")&&n.push({name:t,message:`bin.${t} must be a non-empty relative path to an executable inside the contributor root`})}return n}s(Mn,"binDeclarationIssues");function Nn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[t,o]of Object.entries(e))F(t,"bin")===void 0&&(typeof o!="string"||o.trim()===""||(n[t]=o));return n}s(Nn,"normalizeBin");const _e=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Ln(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];const n=[];for(const[t,o]of Object.entries(e)){const r=[];if(_e.test(t)||r.push(`action name must match ${_e.source}`),o===null||typeof o!="object"||Array.isArray(o))r.push("action must be an object with argv and cwd");else{const i=o,c=Object.keys(i).filter(u=>u!=="argv"&&u!=="cwd");c.length>0&&r.push(`action has unsupported field${c.length===1?"":"s"}: ${c.join(", ")}`),(!Array.isArray(i.argv)||i.argv.length===0||!i.argv.every(u=>typeof u=="string"&&u.length>0))&&r.push("argv must be a non-empty array of non-empty strings"),(typeof i.cwd!="string"||i.cwd.length===0)&&r.push("cwd is required and must be a non-empty string")}r.length>0&&n.push({name:t,reason:r.join("; ")})}return n}s(Ln,"humanActionDeclarationIssues");function Fn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(Ln(e).map(o=>o.name)),t={};for(const[o,r]of Object.entries(e)){if(n.has(o))continue;const i=r;t[o]={argv:[...i.argv],cwd:i.cwd}}return t}s(Fn,"normalizeHumanActions");function Et(e){return Mn(e).map(n=>n.message)}s(Et,"invalidPluginBinReasons");function Ot(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[t,o]of Object.entries(e))F(t,"requires")===void 0&&(typeof o!="string"||o.trim()===""||/[\r\n]/.test(o)||(n[t]=o));return n}s(Ot,"normalizeRequires");function Pt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["requires must be a JSON object mapping a bare executable name to a one-line install hint"];const n=[];for(const[t,o]of Object.entries(e)){const r=F(t,"requires");r!==void 0&&n.push(r),typeof o!="string"||o.trim()===""?n.push(`requires.${t} must be a non-empty one-line install hint`):/[\r\n]/.test(o)&&n.push(`requires.${t} must be a one-line install hint`)}return n}s(Pt,"invalidPluginRequiresReasons");function we(e){if(e===null||typeof e!="object")return null;const n=e,t={};typeof n.whenToUse=="string"&&n.whenToUse.trim()!==""&&(t.whenToUse=n.whenToUse),typeof n.model=="string"&&n.model.trim()!==""&&(t.model=n.model),typeof n.orchestratorModel=="string"&&n.orchestratorModel.trim()!==""&&(t.orchestratorModel=n.orchestratorModel);const o=s(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"),"isStringArray");return o(n.tools)&&(t.tools=n.tools),o(n.extensions)&&(t.extensions=n.extensions),o(n.availableTo)&&(t.availableTo=n.availableTo),Object.keys(t).length>0?t:null}s(we,"normalizeKindFields");function b(e,n=un()){const t={...n};if(e!==null&&typeof e=="object")for(const[o,r]of Object.entries(e)){const i=we(r);if(i===null)continue;const c=t[o];c!==void 0?t[o]={...c,...i}:i.whenToUse!==void 0&&(t[o]=i)}return t}s(b,"mergeKinds");let D;function It(e){D=e}s(It,"setAppPluginKinds");function ke(e,n,t){if(e==="user"&&D!==void 0){let i=t;for(const c of Object.keys(D).sort((u,d)=>u.localeCompare(d)))i=b(D[c],i);return i}if(n===null)return t;const o=de(e,n).filter(i=>i.enabled&&i.manifest.kinds!==void 0).sort((i,c)=>i.name.localeCompare(c.name));let r=t;for(const i of o)r=b(i.manifest.kinds,r);return r}s(ke,"layerPluginKinds");function Ct(){const e=[{origin:"config.json",components:kn("user").page_components}],n=g("user");if(n!==null){const t=de("user",n).filter(o=>o.enabled&&o.manifest.page_components!==void 0).sort((o,r)=>o.name.localeCompare(r.name));for(const o of t){const r=`plugin "${o.name}" page_components`;e.push({origin:`plugin "${o.name}"`,components:pe(o.manifest.page_components,r)})}}return wn(e)}s(Ct,"resolvePageComponents");const X=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Tt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["kinds must be a JSON object keyed by kind name"];const n=[],t=s(o=>Array.isArray(o)&&o.every(r=>typeof r=="string"),"isStringArray");for(const[o,r]of Object.entries(e)){if(o.trim()===""){n.push("kinds contains an empty kind name");continue}if(r===null||typeof r!="object"||Array.isArray(r)){n.push(`kinds.${o} must be a JSON object`);continue}const i=r;for(const c of Object.keys(i))X.has(c)||n.push(`kinds.${o}.${c} is not a KindConfig field (expected one of: ${[...X].join(", ")})`);i.whenToUse!==void 0&&(typeof i.whenToUse!="string"||i.whenToUse.trim()==="")&&n.push(`kinds.${o}.whenToUse must be a non-empty string`);for(const c of["model","orchestratorModel"])i[c]!==void 0&&(typeof i[c]!="string"||i[c].trim()==="")&&n.push(`kinds.${o}.${c} must be a non-empty string`);for(const c of["tools","extensions","availableTo"])i[c]!==void 0&&!t(i[c])&&n.push(`kinds.${o}.${c} must be an array of strings`);we(r)===null&&n.push(`kinds.${o} has no valid KindConfig field \u2014 an entry must set at least one of: ${[...X].join(", ")} (whenToUse is required when the kind exists in no lower layer)`)}return n}s(Tt,"invalidPluginKindsReasons");function Dn(e){if(e===null||typeof e!="object")return null;const n=e;if(typeof n.previewEndpoint!="string"||n.previewEndpoint.trim()===""||typeof n.relayTokenRef!="string"||n.relayTokenRef.trim()==="")return null;const t={previewEndpoint:n.previewEndpoint,relayTokenRef:n.relayTokenRef};return typeof n.cpOrigin=="string"&&n.cpOrigin.trim()!==""&&(t.cpOrigin=n.cpOrigin),t}s(Dn,"normalizeRemoteCanvasTarget");function Kn(e,n=dn()){const t={...n.targets};if(e!==null&&typeof e=="object"){const o=e;if(o.targets!==null&&typeof o.targets=="object")for(const[r,i]of Object.entries(o.targets)){const c=Dn(i);c!==null&&(t[r]=c)}}return{targets:t}}s(Kn,"mergeRemoteCanvas");function Ae(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(Ae,"normalizeMode");function E(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(E,"normalizePositiveInteger");function zn(e,n){const t=e!==null&&typeof e=="object"?e:{},o=E(t.warning,n.warning),r=E(t.automaticReviveCap,n.automaticReviveCap);return o<=r?{warning:o,automaticReviveCap:r}:{...n}}s(zn,"mergeBrokerThresholds");function Un(e,n){return{unattendedParkMs:E((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(Un,"mergeLifecycle");function Gn(e){if(!Array.isArray(e))return[...ie];const n=e.filter(t=>typeof t=="string"&&t.trim()!=="").map(t=>t.trim());return n.length>0?n:[...ie]}s(Gn,"normalizeWhipMessages");function qn(e,n){if(e===null||typeof e!="object")return{...n};const t=e.tcp;return{tcp:typeof t=="string"?t:n.tcp}}s(qn,"mergeApi");let Se=!1;function K(e){!Se&&e.ledger!==void 0&&(Se=!0,ce({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(mn)}}));const n=w(),t=n.schema_version,o=e.marketplaces===void 0?{}:e.marketplaces,r=e.plugins===void 0?{}:e.plugins,i=e.auto_update,c=i&&typeof i.interval_hours=="number"?i.interval_hours:void 0,u=c!==void 0&&Number.isFinite(c)&&c>=0?c:n.auto_update.interval_hours,d={crtr:Ae(i?.crtr,n.auto_update.crtr),content:Ae(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,a=E(f,n.max_panes_per_window),l=typeof e.auto_open_child_viewers=="boolean"?e.auto_open_child_viewers:n.auto_open_child_viewers,p=zn(e.brokerThresholds,n.brokerThresholds),y=Un(e.lifecycle,n.lifecycle),z=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,m=e.working_gerunds===void 0?[...n.working_gerunds]:_n(e.working_gerunds),xe=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Re=pe(e.page_components),Ee=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Oe=Gn(e.whip_messages),Pe=sn.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,Ie=rn.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,Ce=E(e.live_cycles,n.live_cycles),Te=tn.includes(e.condensed_history)?e.condensed_history:n.condensed_history,$e=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Me=on.includes(e.verbosity)?e.verbosity:n.verbosity,Ne=typeof e.detailed_tool_recaps=="boolean"?e.detailed_tool_recaps:n.detailed_tool_recaps,Le=Number.isInteger(e.document_port)&&e.document_port>=1&&e.document_port<=65535?e.document_port:n.document_port,Fe=On(e.keybindings),De=In(e.tmux_passthrough),Ke=T(e.modelLadders),ze=L(e.providerOptions,n.providerOptions),U=be($(e.modelRoutes)),Q=U.complete,ee=M(e.modelRouting,void 0),Ue=b(e.kinds),Ge=Kn(e.remoteCanvas),qe=qn(e.api,n.api),v=e.paths;if(v?.user_files!==void 0&&(typeof v.user_files!="string"||!v.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");const ne=e.store,_=e.runtime;if(_?.person_uids!==void 0&&(!Array.isArray(_.person_uids)||!_.person_uids.every(te=>Number.isSafeInteger(te)&&te>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");const Be=N(e.spawnEnv,n.spawnEnv?.allow),We=Nn(e.bin),He=Fn(e.humanActions);return{bin:We,humanActions:He,schema_version:t,marketplaces:o,plugins:r,auto_update:d,max_panes_per_window:a,auto_open_child_viewers:l,brokerThresholds:p,lifecycle:y,completion_bell:z,working_gerunds:m,whip_mode:xe,page_components:Re,page_surface:Ee,whip_messages:Oe,whip_message_mode:Pe,mouse_mode_default:Ie,live_cycles:Ce,condensed_history:Te,bash_tool_purpose:$e,verbosity:Me,detailed_tool_recaps:Ne,document_port:Le,keybindings:Fe,tmux_passthrough:De,modelLadders:Ke,providerOptions:ze,...Object.keys(Q).length>0?{modelRoutes:Q}:{},...Object.keys(U.legacy).length>0?{legacyModelRoutes:U.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:Ue,remoteCanvas:Ge,api:qe,...v?{paths:v}:{},...ne?{store:ne}:{},..._?{runtime:_}:{},spawnEnv:Be}}s(K,"mergeConfig");function Bn(e){return P(e)}s(Bn,"readRawConfigAtRoot");function Wn(e){const n=g(e);return n?Bn(n):null}s(Wn,"readRawScopeConfig");function Hn(e){if(e===null||e==="")return null;try{return P(ae(e))}catch{return null}}s(Hn,"readRawProfileConfig");function Jn(e,n){return[...yn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Jn,"readRawProjectScopeConfigs");function je(e=process.cwd(),n=Ve()||null){const t=I[C];if(t)return t.launch;const o=w(),r=Wn("user"),i=Hn(n),c=Jn(e,n);let u=b(r?.kinds,ke("user",g("user"),o.kinds)),d=T(r?.modelLadders,o.modelLadders),f=L(r?.providerOptions,o.providerOptions),a=$(r?.modelRoutes),l=M(r?.modelRouting,void 0),p=N(r?.spawnEnv,o.spawnEnv?.allow);i!==null&&(u=b(i.kinds,u),d=T(i.modelLadders,d),f=L(i.providerOptions,f),a=$(i.modelRoutes,a),l=M(i.modelRouting,l),p=N(i.spawnEnv,p.allow));for(const{root:z,raw:m}of c)u=b(m?.kinds,ke("project",z,u)),m!==null&&(d=T(m.modelLadders,d),f=L(m.providerOptions,f),a=$(m.modelRoutes,a),l=M(m.modelRouting,l),p=N(m.spawnEnv,p.allow));const y=be(a);return{kinds:u,modelLadders:d,providerOptions:f,...Object.keys(y.complete).length>0?{modelRoutes:y.complete}:{},...Object.keys(y.legacy).length>0?{legacyModelRoutes:y.legacy}:{},...l!==void 0?{modelRouting:l}:{},spawnEnv:p}}s(je,"readMergedLaunchConfig");function $t(e){return je().kinds[e]}s($t,"resolveKindConfig");function Mt(e){const n=je().kinds,t=[];for(const[o,r]of Object.entries(n)){const i=o.indexOf("/");if(i===-1)continue;const c=o.slice(0,i),u=r.availableTo??[c];(u.includes("*")||u.includes(e))&&t.push({kind:o,whenToUse:r.whenToUse})}return t.sort((o,r)=>o.kind.localeCompare(r.kind))}s(Mt,"subKindsAvailableTo");function Vn(e,n,t){const o={...e??{}};o.anthropic!==void 0&&(o.anthropic={...o.anthropic}),o.openai!==void 0&&(o.openai={...o.openai}),t.defaultProvider!==n.defaultProvider&&t.defaultProvider!==void 0&&(o.defaultProvider=t.defaultProvider);for(const i of["anthropic","openai"])for(const c of["ultra","strong","medium","light"])t[i][c]!==n[i][c]&&(o[i]={...o[i]??{},[c]:t[i][c]});return o.defaultProvider!==void 0||o.anthropic!==void 0||o.openai!==void 0?o:void 0}s(Vn,"sparseModelLaddersToPersist");async function Yn(e,n){return await j(e,t=>{const o=K(t),r=K(t);n(r);const i={...t};for(const u of vn)u!=="modelLadders"&&!Qe(r[u],o[u])&&(i[u]=r[u]);const c=Vn(t.modelLadders,o.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(Yn,"mutateConfigAtRoot");async function Nt(e,n){await j(e,t=>{const o=t.modelLadders??{},r={...o};n.defaultProvider!==void 0&&(r.defaultProvider=n.defaultProvider);for(const i of["anthropic","openai"])n[i]!==void 0&&(r[i]={...o[i]??{},...n[i]});return{value:void 0,next:{...t,modelLadders:r}}})}s(Nt,"persistModelLadders");async function Lt(e,n,t){if(t!==void 0)Cn(n,t);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,o=>{const r=he(o.modelRoutes??{});t===void 0?delete r[n]:x(r,n,{...t,models:{...t.models}});const i={...o};return Object.keys(r).length===0?delete i.modelRoutes:i.modelRoutes=r,{value:void 0,next:i}})}s(Lt,"persistModelRoute");async function Zn(e,n){return await Yn(e,n)}s(Zn,"updateConfigAtRoot");async function Ft(e,n){return await Zn(k(e),n)}s(Ft,"updateConfig");async function Dt(e){const n=e.orchestrator===!0?"orchestratorModel":"model";return await j(e.root,t=>{const o={...t.kinds??{},[e.kind]:{...(t.kinds??{})[e.kind],[n]:e.model}};return{value:void 0,next:{...t,kinds:o}}}),{path:h(e.root),field:n}}s(Dt,"persistDefaultKindModel");async function Kt(e,n){const t=jn(e);return n(t),await En(e,t),t}s(Kt,"updateState");export{xn as InvalidRawSettingsError,Mn as binDeclarationIssues,wt as brokerConfigSnapshot,bt as configPath,Rt as ensureScopeInitialized,Ln as humanActionDeclarationIssues,_t as installBrokerConfigSnapshot,Et as invalidPluginBinReasons,Tt as invalidPluginKindsReasons,Pt as invalidPluginRequiresReasons,Nn as normalizeBin,Fn as normalizeHumanActions,Ot as normalizeRequires,In as normalizeTmuxPassthrough,Dt as persistDefaultKindModel,Nt as persistModelLadders,Lt as persistModelRoute,kn as readConfig,An as readConfigAtRoot,je as readMergedLaunchConfig,Bn as readRawConfigAtRoot,Wn as readRawScopeConfig,kt as readRawSettingsForTarget,jn as readState,At as replaceRawSettingsForTarget,$t as resolveKindConfig,Ct as resolvePageComponents,It as setAppPluginKinds,vt as statePath,Mt as subKindsAvailableTo,Ft as updateConfig,Zn as updateConfigAtRoot,St as updateRawConfigAtomically,Kt as updateState,jt as writeConfig,xt as writeRawConfig,En as writeState};
|
|
1
|
+
var Ye=Object.defineProperty;var s=(e,n)=>Ye(e,"name",{value:n,configurable:!0});import{envProfileId as Ze}from"../shared/env.js";import{basename as oe,join as re}from"node:path";import{existsSync as Xe,mkdirSync as Qe,statSync as en}from"node:fs";import{isDeepStrictEqual as nn}from"node:util";import{CONFIG_FILE as tn,STATE_FILE as on,CONDENSED_HISTORY_MODES as rn,VERBOSITY_LEVELS as sn,MOUSE_MODE_DEFAULTS as cn,WHIP_MESSAGE_MODES as un,DEFAULT_WHIP_MESSAGES as ie,defaultScopeConfig as w,defaultScopeState as se,defaultModelLaddersConfig as dn,defaultKindsConfig as an,defaultRemoteCanvasConfig as fn}from"../types.js";import{BINDING_CATALOG as ln,BINDING_IDS as pn,isAttachPaneBinding as mn}from"./keybindings/catalog.js";import{notFound as gn}from"./errors.js";import{emitEvent as ce}from"./events/emit.js";import{LEDGER_ENV as yn}from"./ledger/rates.js";import{atomicWriteJson as q,readJsonIfExists as O,ensureDir as hn}from"./fs-utils.js";import{scopeRoot as g,requireScopeRoot as k,findProjectScopeRoots as bn,userScopeRoot as ue}from"./scope.js";import{listInstalledPluginsInRoot as de}from"./installed-plugins.js";import{profileDir as ae,listProfiles as fe}from"./profiles/manifest.js";import{canonicalRoot as A}from"./scoped-state/paths.js";import{currentSnapshot as vn,readCachedSettings as B,readCachedState as _n,revisionOf as I,SettingsRevisionConflictError as le,writeSettings as W}from"./scoped-state/person-store.js";import{importedIntoNorthlight as pe,splitUserSettingsWrite as wn,withAppInstalls as me}from"./scoped-state/imported-mac-installs.js";import{withExclusiveDirectoryLock as kn}from"./exclusive-lock.js";import{SCOPE_CONFIG_KEYS as An}from"./user-settings.js";import{normalizeWorkingGerunds as Sn}from"../shared/working-activity.js";import{mergePageComponentLayers as jn,normalizePageComponents as ge}from"./human/page-catalog.js";function h(e){return re(e,tn)}s(h,"configPathFor");function H(e,n){return kn(`${e}.lock`,()=>n(e),{timeoutError:s(()=>new Error(`timed out waiting for config lock: ${e}`),"timeoutError")})}s(H,"withConfigPathLock");function J(e){return re(e,on)}s(J,"statePathFor");function At(e){const n=g(e);return n?h(n):null}s(At,"configPath");function St(e){const n=g(e);return n?J(n):null}s(St,"statePath");function S(e){const n=A(e),o=A(ue());if(n===o)return{key:"user",kind:"user",root:o};if(oe(n)===".crouter")return{key:"project",kind:"project",root:n};for(const t of fe()){const r=A(ae(t.profileId));if(n===r)return{key:`profile:${t.profileId}`,kind:"profile",root:r,profileId:t.profileId}}throw new Error(`settings root is not a recognized owner: ${e}`)}s(S,"settingsOwnerForRoot");function P(e){if(oe(e)===".crouter"){let t;try{t=A(e)}catch(r){if(r.code==="ENOENT")return null;throw r}if(t!==A(ue()))return O(h(e))}const n=S(e).key,o=B(n).settings;return n==="user"&&pe()?me(vn(),o):o}s(P,"readRawAtRoot");async function ye(e,n){let o;return await W(t=>{const r=t.settings[e],i=e==="user"&&pe(),c=n(structuredClone((i?me(t,r??null):r)??{}));return o=c.value,i?wn(t,c.next,I(r)):[{op:"settings.replace",owner:e,raw:c.next,ifRevision:I(r)}]}),o}s(ye,"mutatePersonSettings");async function V(e,n){const o=S(e);if(o.kind==="project"){H(h(o.root),t=>q(t,n,{createParent:!1}));return}await ye(o.key,()=>({value:void 0,next:n}))}s(V,"writeRawAtRoot");async function j(e,n){const o=S(e);return o.kind==="project"?H(h(o.root),t=>{const r=n(O(t)??{});return q(t,r.next,{createParent:!1}),r.value}):await ye(o.key,n)}s(j,"mutateRawAtRoot");const C=globalThis,T=Symbol.for("crtr.broker.config-snapshot");function jt(e){C[T]=e}s(jt,"installBrokerConfigSnapshot");function xt(){return C[T]}s(xt,"brokerConfigSnapshot");function xn(e){const n=C[T];if(n){if(e!=="user")throw new Error(`broker config snapshot has no ${e} scope`);return n.user}const o=g(e);return o?Rn(o):w()}s(xn,"readConfig");function Rn(e){const n=P(e);return n?z(n):w()}s(Rn,"readConfigAtRoot");function En(e){const n=O(J(e));return{marketplaces:n?.marketplaces??{},plugins:n?.plugins??{},activeCanvas:n?.activeCanvas??null,...n?.last_self_check===void 0?{}:{last_self_check:n.last_self_check}}}s(En,"readProjectState");function On(e){const n=g(e);return n?e==="project"?Xe(n)?En(n):se():_n(S(n).key):se()}s(On,"readState");class In extends Error{static{s(this,"InvalidRawSettingsError")}constructor(n){super(`settings cannot be merged: ${n instanceof Error?n.message:String(n)}`),this.name="InvalidRawSettingsError"}}function he(e){if(e.scope==="user")return"user";if(!fe().some(n=>n.profileId===e.profileId))throw gn(`profile not found: ${e.profileId}`,{received:e.profileId,next:"Run `crtr profile list` to see available profiles."});return`profile:${e.profileId}`}s(he,"rawSettingsKeyForTarget");function Rt(e){return B(he(e))}s(Rt,"readRawSettingsForTarget");async function Et(e,n,o){const t=he(e);try{z(n)}catch(u){throw new In(u)}if(B(t).revision!==o)throw new le;const i=await W(u=>I(u.settings[t])===o?[{op:"settings.replace",owner:t,raw:n,ifRevision:o}]:(()=>{throw new le})()),c=I(i.settings[t]);return{revision:c,changed:c!==o}}s(Et,"replaceRawSettingsForTarget");async function Ot(e,n){const o=k(e);return await j(o,t=>{const r=n(t);return{value:r,next:r}})}s(Ot,"updateRawConfigAtomically");async function It(e,n){await V(k(e),n)}s(It,"writeConfig");async function Pt(e,n){await V(k(e),n)}s(Pt,"writeRawConfig");function Pn(e,n){H(J(e),o=>q(o,n,{createParent:!1}))}s(Pn,"writeProjectState");async function Cn(e,n){const o=k(e);if(e==="project"){Pn(o,n);return}const t=S(o).key;await W(()=>[{op:"state.write",owner:t,state:n}])}s(Cn,"writeState");async function Ct(e,n){if(e!=="project"){hn(n);return}try{Qe(n)}catch(o){if(o.code!=="EEXIST"||!en(n).isDirectory())throw o}O(h(n))===null&&await V(n,{schema_version:w().schema_version})}s(Ct,"ensureScopeInitialized");function Tn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))Array.isArray(t)&&t.every(r=>typeof r=="string")&&(n[o]=[...t]);return n}s(Tn,"normalizeKeybindings");const $n=new Set(ln.filter(mn).map(e=>e.id));function Mn(e){return Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&pn.has(n)&&$n.has(n)))]:[]}s(Mn,"normalizeTmuxPassthrough");function $(e,n=dn()){const o=n;if(e===null||typeof e!="object")return o;const t=e,r={anthropic:{...o.anthropic},openai:{...o.openai},...o.defaultProvider!==void 0?{defaultProvider:o.defaultProvider}:{}};(t.defaultProvider==="anthropic"||t.defaultProvider==="openai")&&(r.defaultProvider=t.defaultProvider);for(const i of["anthropic","openai"]){const c=t[i];if(!(c===null||typeof c!="object"))for(const[u,d]of Object.entries(c))(u==="ultra"||u==="strong"||u==="medium"||u==="light")&&typeof d=="string"&&(r[i][u]=d)}return r}s($,"mergeModelLadders");function be(e){return e==="ultra"||e==="strong"||e==="medium"||e==="light"}s(be,"validStrength");const Y=["ultra","strong","medium","light"];function Z(){return Object.create(null)}s(Z,"routeRecord");function x(e,n,o){Object.defineProperty(e,n,{value:o,writable:!0,enumerable:!0,configurable:!0})}s(x,"setRouteRecord");function ve(e){const n=Z();for(const[o,t]of Object.entries(e??{}))x(n,o,t);return n}s(ve,"copyRouteRecord");function R(e,n){ce({level:"warn",event:"config.model_routes.invalid",fields:{route_id:e,rule:n}})}s(R,"routeInvalid");function M(e,n={}){const o=ve(n);if(e===null||typeof e!="object"||Array.isArray(e))return o;for(const[t,r]of Object.entries(e)){if(t.trim()===""){R(t,"route id must be a non-empty string");continue}if(r===null||typeof r!="object"||Array.isArray(r)){R(t,"route must be an object");continue}const i=r,c=o[t],u={...c};let d;for(const f of["family","credentialSource","providerId"]){const a=i[f];if(a!==void 0){if(typeof a!="string"||a.trim()===""){d=`${f} must be a non-empty string`;break}u[f]=a}}if(d===void 0&&i.models!==void 0)if(i.models===null||typeof i.models!="object"||Array.isArray(i.models))d="models must be an object";else{const f={...c?.models};for(const[a,l]of Object.entries(i.models)){if(!be(a)){d=`models.${a} is not a model strength`;break}if(typeof l!="string"||l.trim()===""){d=`models.${a} must be a non-empty provider/id ref`;break}const p=l.indexOf("/");if(p<=0||p===l.length-1){d=`models.${a} must be provider/id`;break}f[a]=l}u.models=f}if(d===void 0&&u.models!==void 0&&u.providerId!==void 0){for(const[f,a]of Object.entries(u.models))if(a.slice(0,a.indexOf("/"))!==u.providerId){d=`models.${f} provider prefix must equal providerId`;break}}if(d!==void 0){R(t,d);continue}x(o,t,u)}return o}s(M,"mergeModelRoutePatches");function _e(e){const n=Z(),o=Z();for(const[t,r]of Object.entries(e)){if(r.family===void 0||r.credentialSource===void 0||r.providerId===void 0||r.models===void 0){R(t,"route must include family, credentialSource, providerId, and models");continue}const i=Y.filter(c=>r.models[c]===void 0);if(i.length>0){R(t,`incomplete route; missing strengths: ${i.join(", ")}`),x(o,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models});continue}x(n,t,{family:r.family,credentialSource:r.credentialSource,providerId:r.providerId,models:r.models})}return{complete:n,legacy:o}}s(_e,"resolveModelRoutes");function Nn(e,n){if(e.trim()==="")throw new Error("model route id must be a non-empty string");for(const t of["family","credentialSource","providerId"])if(typeof n[t]!="string"||n[t].trim()==="")throw new Error(`model route "${e}" ${t} must be a non-empty string`);const o=Y.filter(t=>n.models?.[t]===void 0);if(o.length>0)throw new Error(`model route "${e}" is incomplete; missing strengths: ${o.join(", ")}`);for(const t of Y){const r=n.models[t];if(typeof r!="string"||r.trim()==="")throw new Error(`model route "${e}" models.${t} must be a non-empty provider/id ref`);const i=r.indexOf("/");if(i<=0||i===r.length-1)throw new Error(`model route "${e}" models.${t} must be provider/id`);if(r.slice(0,i)!==n.providerId)throw new Error(`model route "${e}" models.${t} provider prefix must equal providerId`)}}s(Nn,"assertCompleteModelRoute");function N(e,n){if(e===void 0||e===null||typeof e!="object"||Array.isArray(e))return n;const o=e,t=s(i=>Array.isArray(i)&&i.every(c=>typeof c=="string"&&c.trim()!=="")?[...i]:void 0,"strings"),r=Array.isArray(o.strengthFallback)&&o.strengthFallback.every(i=>be(i))?[...o.strengthFallback]:void 0;return{...t(o.credentialSourceOrder)!==void 0?{credentialSourceOrder:t(o.credentialSourceOrder)}:{},...t(o.familyOrder)!==void 0?{familyOrder:t(o.familyOrder)}:{},...r!==void 0?{strengthFallback:r}:{}}}s(N,"mergeModelRouting");function Ln(e){return e!==""&&e.replace(/\*/g,"")===""}s(Ln,"isInheritAllGlob");function L(e,n=[]){const o=e,t=Array.isArray(o?.allow)?o.allow.filter(r=>typeof r=="string"):[];for(const r of t)if(Ln(r))throw new Error(`spawnEnv.allow: "${r}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...n,...t])]}}s(L,"mergeSpawnEnv");function F(e,n={}){const o={};for(const[t,r]of Object.entries(n))o[t]={...r};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){if(r===null||typeof r!="object")continue;const i={...o[t]},c=r.fastMode;typeof c=="boolean"&&(i.fastMode=c),o[t]=i}return o}s(F,"mergeProviderOptions");const we=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Fn=new Set(["crtr","crtrd"]);function D(e,n){if(n==="bin"&&Fn.has(e))return`${n}.${e} is reserved by crouter \u2014 pick another bare command name`;if(!we.test(e))return`${n}.${e} is not a safe bare command name (expected ${we.source})`}s(D,"bareCommandNameIssue");function Dn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"bin",message:"bin must be a JSON object mapping bare command name to a relative path"}];const n=[];for(const[o,t]of Object.entries(e)){const r=D(o,"bin");r!==void 0&&n.push({name:o,message:r}),(typeof t!="string"||t.trim()==="")&&n.push({name:o,message:`bin.${o} must be a non-empty relative path to an executable inside the contributor root`})}return n}s(Dn,"binDeclarationIssues");function Kn(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))D(o,"bin")===void 0&&(typeof t!="string"||t.trim()===""||(n[o]=t));return n}s(Kn,"normalizeBin");const ke=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function zn(e){if(e===null||typeof e!="object"||Array.isArray(e))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];const n=[];for(const[o,t]of Object.entries(e)){const r=[];if(ke.test(o)||r.push(`action name must match ${ke.source}`),t===null||typeof t!="object"||Array.isArray(t))r.push("action must be an object with argv and cwd");else{const i=t,c=Object.keys(i).filter(u=>u!=="argv"&&u!=="cwd");c.length>0&&r.push(`action has unsupported field${c.length===1?"":"s"}: ${c.join(", ")}`),(!Array.isArray(i.argv)||i.argv.length===0||!i.argv.every(u=>typeof u=="string"&&u.length>0))&&r.push("argv must be a non-empty array of non-empty strings"),(typeof i.cwd!="string"||i.cwd.length===0)&&r.push("cwd is required and must be a non-empty string")}r.length>0&&n.push({name:o,reason:r.join("; ")})}return n}s(zn,"humanActionDeclarationIssues");function Un(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n=new Set(zn(e).map(t=>t.name)),o={};for(const[t,r]of Object.entries(e)){if(n.has(t))continue;const i=r;o[t]={argv:[...i.argv],cwd:i.cwd}}return o}s(Un,"normalizeHumanActions");function Tt(e){return Dn(e).map(n=>n.message)}s(Tt,"invalidPluginBinReasons");function $t(e){if(e===null||typeof e!="object"||Array.isArray(e))return{};const n={};for(const[o,t]of Object.entries(e))D(o,"requires")===void 0&&(typeof t!="string"||t.trim()===""||/[\r\n]/.test(t)||(n[o]=t));return n}s($t,"normalizeRequires");function Mt(e){if(e===null||typeof e!="object"||Array.isArray(e))return["requires must be a JSON object mapping a bare executable name to a one-line install hint"];const n=[];for(const[o,t]of Object.entries(e)){const r=D(o,"requires");r!==void 0&&n.push(r),typeof t!="string"||t.trim()===""?n.push(`requires.${o} must be a non-empty one-line install hint`):/[\r\n]/.test(t)&&n.push(`requires.${o} must be a one-line install hint`)}return n}s(Mt,"invalidPluginRequiresReasons");function Ae(e){if(e===null||typeof e!="object")return null;const n=e,o={};typeof n.whenToUse=="string"&&n.whenToUse.trim()!==""&&(o.whenToUse=n.whenToUse),typeof n.model=="string"&&n.model.trim()!==""&&(o.model=n.model),typeof n.orchestratorModel=="string"&&n.orchestratorModel.trim()!==""&&(o.orchestratorModel=n.orchestratorModel);const t=s(r=>Array.isArray(r)&&r.every(i=>typeof i=="string"),"isStringArray");return t(n.tools)&&(o.tools=n.tools),t(n.extensions)&&(o.extensions=n.extensions),t(n.availableTo)&&(o.availableTo=n.availableTo),Object.keys(o).length>0?o:null}s(Ae,"normalizeKindFields");function b(e,n=an()){const o={...n};if(e!==null&&typeof e=="object")for(const[t,r]of Object.entries(e)){const i=Ae(r);if(i===null)continue;const c=o[t];c!==void 0?o[t]={...c,...i}:i.whenToUse!==void 0&&(o[t]=i)}return o}s(b,"mergeKinds");let K;function Nt(e){K=e}s(Nt,"setAppPluginKinds");function Se(e,n,o){if(e==="user"&&K!==void 0){let i=o;for(const c of Object.keys(K).sort((u,d)=>u.localeCompare(d)))i=b(K[c],i);return i}if(n===null)return o;const t=de(e,n).filter(i=>i.enabled&&i.manifest.kinds!==void 0).sort((i,c)=>i.name.localeCompare(c.name));let r=o;for(const i of t)r=b(i.manifest.kinds,r);return r}s(Se,"layerPluginKinds");function Lt(){const e=[{origin:"config.json",components:xn("user").page_components}],n=g("user");if(n!==null){const o=de("user",n).filter(t=>t.enabled&&t.manifest.page_components!==void 0).sort((t,r)=>t.name.localeCompare(r.name));for(const t of o){const r=`plugin "${t.name}" page_components`;e.push({origin:`plugin "${t.name}"`,components:ge(t.manifest.page_components,r)})}}return jn(e)}s(Lt,"resolvePageComponents");const X=new Set(["whenToUse","model","orchestratorModel","tools","extensions","availableTo"]);function Ft(e){if(e===null||typeof e!="object"||Array.isArray(e))return["kinds must be a JSON object keyed by kind name"];const n=[],o=s(t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),"isStringArray");for(const[t,r]of Object.entries(e)){if(t.trim()===""){n.push("kinds contains an empty kind name");continue}if(r===null||typeof r!="object"||Array.isArray(r)){n.push(`kinds.${t} must be a JSON object`);continue}const i=r;for(const c of Object.keys(i))X.has(c)||n.push(`kinds.${t}.${c} is not a KindConfig field (expected one of: ${[...X].join(", ")})`);i.whenToUse!==void 0&&(typeof i.whenToUse!="string"||i.whenToUse.trim()==="")&&n.push(`kinds.${t}.whenToUse must be a non-empty string`);for(const c of["model","orchestratorModel"])i[c]!==void 0&&(typeof i[c]!="string"||i[c].trim()==="")&&n.push(`kinds.${t}.${c} must be a non-empty string`);for(const c of["tools","extensions","availableTo"])i[c]!==void 0&&!o(i[c])&&n.push(`kinds.${t}.${c} must be an array of strings`);Ae(r)===null&&n.push(`kinds.${t} has no valid KindConfig field \u2014 an entry must set at least one of: ${[...X].join(", ")} (whenToUse is required when the kind exists in no lower layer)`)}return n}s(Ft,"invalidPluginKindsReasons");function Gn(e){if(e===null||typeof e!="object")return null;const n=e;if(typeof n.previewEndpoint!="string"||n.previewEndpoint.trim()===""||typeof n.relayTokenRef!="string"||n.relayTokenRef.trim()==="")return null;const o={previewEndpoint:n.previewEndpoint,relayTokenRef:n.relayTokenRef};return typeof n.cpOrigin=="string"&&n.cpOrigin.trim()!==""&&(o.cpOrigin=n.cpOrigin),o}s(Gn,"normalizeRemoteCanvasTarget");function qn(e,n=fn()){const o={...n.targets};if(e!==null&&typeof e=="object"){const t=e;if(t.targets!==null&&typeof t.targets=="object")for(const[r,i]of Object.entries(t.targets)){const c=Gn(i);c!==null&&(o[r]=c)}}return{targets:o}}s(qn,"mergeRemoteCanvas");function je(e,n){return e===!0?"notify":e===!1?!1:e==="notify"||e==="apply"?e:n}s(je,"normalizeMode");function E(e,n){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1?e:n}s(E,"normalizePositiveInteger");function Bn(e,n){const o=e!==null&&typeof e=="object"?e:{},t=E(o.warning,n.warning),r=E(o.automaticReviveCap,n.automaticReviveCap);return t<=r?{warning:t,automaticReviveCap:r}:{...n}}s(Bn,"mergeBrokerThresholds");function Wn(e,n){return{unattendedParkMs:E((e!==null&&typeof e=="object"?e:{}).unattendedParkMs,n.unattendedParkMs)}}s(Wn,"mergeLifecycle");function Hn(e){if(!Array.isArray(e))return[...ie];const n=e.filter(o=>typeof o=="string"&&o.trim()!=="").map(o=>o.trim());return n.length>0?n:[...ie]}s(Hn,"normalizeWhipMessages");function Jn(e,n){if(e===null||typeof e!="object")return{...n};const o=e.tcp;return{tcp:typeof o=="string"?o:n.tcp}}s(Jn,"mergeApi");let xe=!1;function z(e){!xe&&e.ledger!==void 0&&(xe=!0,ce({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(yn)}}));const n=w(),o=n.schema_version,t=e.marketplaces===void 0?{}:e.marketplaces,r=e.plugins===void 0?{}:e.plugins,i=e.auto_update,c=i&&typeof i.interval_hours=="number"?i.interval_hours:void 0,u=c!==void 0&&Number.isFinite(c)&&c>=0?c:n.auto_update.interval_hours,d={crtr:je(i?.crtr,n.auto_update.crtr),content:je(i?.content,n.auto_update.content),interval_hours:u},f=e.max_panes_per_window,a=E(f,n.max_panes_per_window),l=typeof e.auto_open_child_viewers=="boolean"?e.auto_open_child_viewers:n.auto_open_child_viewers,p=Bn(e.brokerThresholds,n.brokerThresholds),y=Wn(e.lifecycle,n.lifecycle),U=typeof e.completion_bell=="boolean"?e.completion_bell:n.completion_bell,m=e.working_gerunds===void 0?[...n.working_gerunds]:Sn(e.working_gerunds),Ee=typeof e.whip_mode=="boolean"?e.whip_mode:n.whip_mode,Oe=ge(e.page_components),Ie=typeof e.page_surface=="boolean"?e.page_surface:n.page_surface,Pe=Hn(e.whip_messages),Ce=un.includes(e.whip_message_mode)?e.whip_message_mode:n.whip_message_mode,Te=cn.includes(e.mouse_mode_default)?e.mouse_mode_default:n.mouse_mode_default,$e=E(e.live_cycles,n.live_cycles),Me=rn.includes(e.condensed_history)?e.condensed_history:n.condensed_history,Ne=typeof e.bash_tool_purpose=="boolean"?e.bash_tool_purpose:n.bash_tool_purpose,Le=sn.includes(e.verbosity)?e.verbosity:n.verbosity,Fe=typeof e.detailed_tool_recaps=="boolean"?e.detailed_tool_recaps:n.detailed_tool_recaps,De=Number.isInteger(e.document_port)&&e.document_port>=1&&e.document_port<=65535?e.document_port:n.document_port,Ke=Tn(e.keybindings),ze=Mn(e.tmux_passthrough),Ue=$(e.modelLadders),Ge=F(e.providerOptions,n.providerOptions),G=_e(M(e.modelRoutes)),Q=G.complete,ee=N(e.modelRouting,void 0),qe=b(e.kinds),Be=qn(e.remoteCanvas),We=Jn(e.api,n.api),v=e.paths;if(v?.user_files!==void 0&&(typeof v.user_files!="string"||!v.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");const ne=e.store,_=e.runtime;if(_?.person_uids!==void 0&&(!Array.isArray(_.person_uids)||!_.person_uids.every(te=>Number.isSafeInteger(te)&&te>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");const He=L(e.spawnEnv,n.spawnEnv?.allow),Je=Kn(e.bin),Ve=Un(e.humanActions);return{bin:Je,humanActions:Ve,schema_version:o,marketplaces:t,plugins:r,auto_update:d,max_panes_per_window:a,auto_open_child_viewers:l,brokerThresholds:p,lifecycle:y,completion_bell:U,working_gerunds:m,whip_mode:Ee,page_components:Oe,page_surface:Ie,whip_messages:Pe,whip_message_mode:Ce,mouse_mode_default:Te,live_cycles:$e,condensed_history:Me,bash_tool_purpose:Ne,verbosity:Le,detailed_tool_recaps:Fe,document_port:De,keybindings:Ke,tmux_passthrough:ze,modelLadders:Ue,providerOptions:Ge,...Object.keys(Q).length>0?{modelRoutes:Q}:{},...Object.keys(G.legacy).length>0?{legacyModelRoutes:G.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:qe,remoteCanvas:Be,api:We,...v?{paths:v}:{},...ne?{store:ne}:{},..._?{runtime:_}:{},spawnEnv:He}}s(z,"mergeConfig");function Vn(e){return P(e)}s(Vn,"readRawConfigAtRoot");function Yn(e){const n=g(e);return n?Vn(n):null}s(Yn,"readRawScopeConfig");function Zn(e){if(e===null||e==="")return null;try{return P(ae(e))}catch{return null}}s(Zn,"readRawProfileConfig");function Xn(e,n){return[...bn(e,n)].reverse().map(r=>({root:r,raw:P(r)}))}s(Xn,"readRawProjectScopeConfigs");function Re(e=process.cwd(),n=Ze()||null){const o=C[T];if(o)return o.launch;const t=w(),r=Yn("user"),i=Zn(n),c=Xn(e,n);let u=b(r?.kinds,Se("user",g("user"),t.kinds)),d=$(r?.modelLadders,t.modelLadders),f=F(r?.providerOptions,t.providerOptions),a=M(r?.modelRoutes),l=N(r?.modelRouting,void 0),p=L(r?.spawnEnv,t.spawnEnv?.allow);i!==null&&(u=b(i.kinds,u),d=$(i.modelLadders,d),f=F(i.providerOptions,f),a=M(i.modelRoutes,a),l=N(i.modelRouting,l),p=L(i.spawnEnv,p.allow));for(const{root:U,raw:m}of c)u=b(m?.kinds,Se("project",U,u)),m!==null&&(d=$(m.modelLadders,d),f=F(m.providerOptions,f),a=M(m.modelRoutes,a),l=N(m.modelRouting,l),p=L(m.spawnEnv,p.allow));const y=_e(a);return{kinds:u,modelLadders:d,providerOptions:f,...Object.keys(y.complete).length>0?{modelRoutes:y.complete}:{},...Object.keys(y.legacy).length>0?{legacyModelRoutes:y.legacy}:{},...l!==void 0?{modelRouting:l}:{},spawnEnv:p}}s(Re,"readMergedLaunchConfig");function Dt(e){return Re().kinds[e]}s(Dt,"resolveKindConfig");function Kt(e){const n=Re().kinds,o=[];for(const[t,r]of Object.entries(n)){const i=t.indexOf("/");if(i===-1)continue;const c=t.slice(0,i),u=r.availableTo??[c];(u.includes("*")||u.includes(e))&&o.push({kind:t,whenToUse:r.whenToUse})}return o.sort((t,r)=>t.kind.localeCompare(r.kind))}s(Kt,"subKindsAvailableTo");function Qn(e,n,o){const t={...e??{}};t.anthropic!==void 0&&(t.anthropic={...t.anthropic}),t.openai!==void 0&&(t.openai={...t.openai}),o.defaultProvider!==n.defaultProvider&&o.defaultProvider!==void 0&&(t.defaultProvider=o.defaultProvider);for(const i of["anthropic","openai"])for(const c of["ultra","strong","medium","light"])o[i][c]!==n[i][c]&&(t[i]={...t[i]??{},[c]:o[i][c]});return t.defaultProvider!==void 0||t.anthropic!==void 0||t.openai!==void 0?t:void 0}s(Qn,"sparseModelLaddersToPersist");async function et(e,n){return await j(e,o=>{const t=z(o),r=z(o);n(r);const i={...o};for(const u of An)u!=="modelLadders"&&!nn(r[u],t[u])&&(i[u]=r[u]);const c=Qn(o.modelLadders,t.modelLadders,r.modelLadders);return c!==void 0?i.modelLadders=c:delete i.modelLadders,{value:r,next:i}})}s(et,"mutateConfigAtRoot");async function zt(e,n){await j(e,o=>{const t=o.modelLadders??{},r={...t};n.defaultProvider!==void 0&&(r.defaultProvider=n.defaultProvider);for(const i of["anthropic","openai"])n[i]!==void 0&&(r[i]={...t[i]??{},...n[i]});return{value:void 0,next:{...o,modelLadders:r}}})}s(zt,"persistModelLadders");async function Ut(e,n,o){if(o!==void 0)Nn(n,o);else if(n.trim()==="")throw new Error("model route id must be a non-empty string");await j(e,t=>{const r=ve(t.modelRoutes??{});o===void 0?delete r[n]:x(r,n,{...o,models:{...o.models}});const i={...t};return Object.keys(r).length===0?delete i.modelRoutes:i.modelRoutes=r,{value:void 0,next:i}})}s(Ut,"persistModelRoute");async function nt(e,n){return await et(e,n)}s(nt,"updateConfigAtRoot");async function Gt(e,n){return await nt(k(e),n)}s(Gt,"updateConfig");async function qt(e){const n=e.orchestrator===!0?"orchestratorModel":"model";return await j(e.root,o=>{const t={...o.kinds??{},[e.kind]:{...(o.kinds??{})[e.kind],[n]:e.model}};return{value:void 0,next:{...o,kinds:t}}}),{path:h(e.root),field:n}}s(qt,"persistDefaultKindModel");async function Bt(e,n){const o=On(e);return n(o),await Cn(e,o),o}s(Bt,"updateState");export{In as InvalidRawSettingsError,Dn as binDeclarationIssues,xt as brokerConfigSnapshot,At as configPath,Ct as ensureScopeInitialized,zn as humanActionDeclarationIssues,jt as installBrokerConfigSnapshot,Tt as invalidPluginBinReasons,Ft as invalidPluginKindsReasons,Mt as invalidPluginRequiresReasons,Kn as normalizeBin,Un as normalizeHumanActions,$t as normalizeRequires,Mn as normalizeTmuxPassthrough,qt as persistDefaultKindModel,zt as persistModelLadders,Ut as persistModelRoute,xn as readConfig,Rn as readConfigAtRoot,Re as readMergedLaunchConfig,Vn as readRawConfigAtRoot,Yn as readRawScopeConfig,Rt as readRawSettingsForTarget,On as readState,Et as replaceRawSettingsForTarget,Dt as resolveKindConfig,Lt as resolvePageComponents,Nt as setAppPluginKinds,St as statePath,Kt as subKindsAvailableTo,Gt as updateConfig,nt as updateConfigAtRoot,Ot as updateRawConfigAtomically,Bt as updateState,It as writeConfig,Pt as writeRawConfig,Cn as writeState};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var S=Object.defineProperty;var i=(n,e)=>S(n,"name",{value:e,configurable:!0});const f={name:1,preview:2,content:3},b=["system","transcript"],l=new WeakMap;function j(n){return{node:n.node,preferenceSnapshot:n.preferenceSnapshot,objects:new Map([...n.objects].map(([e,t])=>[e,{...t}])),listed:new Map([...n.listed].map(([e,t])=>[e,{...t}]))}}i(j,"cloneLedger");function _(n){return{node:n,preferenceSnapshot:null,objects:new Map,listed:new Map}}i(_,"emptyLedger");async function x(n,e){const t=_(e),s=await n.prepare("SELECT preference_snapshot, listed_json FROM context_sessions WHERE node = ?").get(e);if(s!==void 0){t.preferenceSnapshot=s.preference_snapshot;for(const[o,r]of Object.entries(JSON.parse(s.listed_json)))t.listed.set(o,r)}const c=await n.prepare("SELECT object, channel, level, heads_key, content_hash FROM exposures WHERE node = ?").all(e);for(const o of c){const r=t.objects.get(o.object)??{headsKey:o.heads_key,contentHash:o.content_hash};r[o.channel]=o.level,t.objects.set(o.object,r)}return l.set(t,j(t)),t}i(x,"loadLedger");async function L(n,e){const t=l.get(e)??_(e.node),s=JSON.stringify(Object.fromEntries(e.listed));(e.preferenceSnapshot!==t.preferenceSnapshot||s!==JSON.stringify(Object.fromEntries(t.listed)))&&await n.prepare(`INSERT INTO context_sessions (node, preference_snapshot, listed_json) VALUES (?, ?, ?)
|
|
2
|
-
ON CONFLICT(node) DO UPDATE SET preference_snapshot = excluded.preference_snapshot, listed_json = excluded.listed_json`).run(e.node,e.preferenceSnapshot,s);const c=[],o=[],r=new Set([...t.objects.keys(),...e.objects.keys()]);for(const a of r){const p=e.objects.get(a),d=t.objects.get(a);for(const h of b){const u=p?.[h];u===void 0?d?.[h]!==void 0&&o.push([a,h]):(u!==d?.[h]||p.headsKey!==d?.headsKey||p.contentHash!==d?.contentHash)&&c.push([a,h,u,p.headsKey,p.contentHash])}}if(o.length>0&&await n.prepare(`DELETE FROM exposures e USING unnest(?::text[], ?::text[]) AS v(object, channel)
|
|
2
|
+
ON CONFLICT(node) DO UPDATE SET preference_snapshot = excluded.preference_snapshot, listed_json = excluded.listed_json`).run(e.node,e.preferenceSnapshot,s);const c=[],o=[],r=[...new Set([...t.objects.keys(),...e.objects.keys()])].sort();for(const a of r){const p=e.objects.get(a),d=t.objects.get(a);for(const h of b){const u=p?.[h];u===void 0?d?.[h]!==void 0&&o.push([a,h]):(u!==d?.[h]||p.headsKey!==d?.headsKey||p.contentHash!==d?.contentHash)&&c.push([a,h,u,p.headsKey,p.contentHash])}}if(o.length>0&&await n.prepare(`DELETE FROM exposures e USING unnest(?::text[], ?::text[]) AS v(object, channel)
|
|
3
3
|
WHERE e.node = ? AND e.object = v.object AND e.channel = v.channel`).run(o.map(a=>a[0]),o.map(a=>a[1]),e.node),c.length>0){const a=i(p=>c.map(d=>d[p]),"col");await n.prepare(`INSERT INTO exposures (node, object, channel, level, heads_key, content_hash)
|
|
4
4
|
SELECT ?, v.object, v.channel, v.level, v.heads_key, v.content_hash FROM unnest(?::text[], ?::text[], ?::text[], ?::text[], ?::text[])
|
|
5
5
|
AS v(object, channel, level, heads_key, content_hash)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var I=Object.defineProperty;var i=(t,e)=>I(t,"name",{value:e,configurable:!0});import{permits as j,resolveReader as x}from"../permissions/evaluator.js";import{receiverForObject as k}from"./receivers.js";import{getById as m}from"./objects.js";import{randomUUID as R}from"node:crypto";import{mapAsync as v}from"../async-array.js";const O=["spawn","job-start","ask"],W=["report.final","report.result","notice.>"];function A(t){return JSON.stringify(Object.fromEntries(t.map(e=>[String(e.threshold),e.delivery])))}i(A,"configToJson");function H(t){const e=JSON.parse(t);return Object.entries(e).map(([n,r])=>({threshold:Number(n),delivery:r})).sort((n,r)=>r.threshold-n.threshold)}i(H,"configFromJson");async function b(t,e,n){return await t.prepare("SELECT * FROM watches WHERE watcher = ? AND object = ?").get(e.id,n.id)}i(b,"watchRow");async function y(t,e){return await t.prepare("SELECT * FROM watch_subscriptions WHERE watch = ? ORDER BY seq").all(e)}i(y,"subsOf");async function S(t,e){const n=await y(t,e);if(n.length===0){await t.prepare("DELETE FROM watches WHERE watch_id = ?").run(e);return}const r=n.some(s=>O.includes(s.started_by))?1:0;await t.prepare("UPDATE watches SET in_tree = ? WHERE watch_id = ? AND in_tree != ?").run(r,e,r)}i(S,"settle");function L(t,e){return t==="message"?W:e.patterns?.length?e.patterns:[">"]}i(L,"defaultPatterns");async function F(t,e){if(e.length===0)return;for(const{watcher:a,start:c}of e){if(c==="fork")throw new Error("recordWatch: fork watches are made by copyWatchesForFork");if(a.type.includes(".")&&!await k(t,a))throw new Error(`custom object ${a.id} has no receiver`)}const n=new Date().toISOString(),r=new Map;for(const{watcher:a,object:c,opts:h}of e){const _=`${a.id}\0${c.id}`,u=r.get(_)??{watcher:a.id,object:c.id,readHeadsKey:null,linkApp:null};u.readHeadsKey=h?.readHeadsKey??u.readHeadsKey,u.linkApp=h?.linkApp?.id??u.linkApp,r.set(_,u)}const s=[...r.entries()],o=i(a=>s.map(([,c])=>a(c)),"col"),w=await t.prepare(`INSERT INTO watches (watch_id, watcher, object, in_tree, read_heads_key, created_at, link_app)
|
|
1
|
+
var I=Object.defineProperty;var i=(t,e)=>I(t,"name",{value:e,configurable:!0});import{permits as j,resolveReader as x}from"../permissions/evaluator.js";import{receiverForObject as k}from"./receivers.js";import{getById as m}from"./objects.js";import{randomUUID as R}from"node:crypto";import{mapAsync as v}from"../async-array.js";const O=["spawn","job-start","ask"],W=["report.final","report.result","notice.>"];function A(t){return JSON.stringify(Object.fromEntries(t.map(e=>[String(e.threshold),e.delivery])))}i(A,"configToJson");function H(t){const e=JSON.parse(t);return Object.entries(e).map(([n,r])=>({threshold:Number(n),delivery:r})).sort((n,r)=>r.threshold-n.threshold)}i(H,"configFromJson");async function b(t,e,n){return await t.prepare("SELECT * FROM watches WHERE watcher = ? AND object = ?").get(e.id,n.id)}i(b,"watchRow");async function y(t,e){return await t.prepare("SELECT * FROM watch_subscriptions WHERE watch = ? ORDER BY seq").all(e)}i(y,"subsOf");async function S(t,e){const n=await y(t,e);if(n.length===0){await t.prepare("DELETE FROM watches WHERE watch_id = ?").run(e);return}const r=n.some(s=>O.includes(s.started_by))?1:0;await t.prepare("UPDATE watches SET in_tree = ? WHERE watch_id = ? AND in_tree != ?").run(r,e,r)}i(S,"settle");function L(t,e){return t==="message"?W:e.patterns?.length?e.patterns:[">"]}i(L,"defaultPatterns");async function F(t,e){if(e.length===0)return;for(const{watcher:a,start:c}of e){if(c==="fork")throw new Error("recordWatch: fork watches are made by copyWatchesForFork");if(a.type.includes(".")&&!await k(t,a))throw new Error(`custom object ${a.id} has no receiver`)}const n=new Date().toISOString(),r=new Map;for(const{watcher:a,object:c,opts:h}of e){const _=`${a.id}\0${c.id}`,u=r.get(_)??{watcher:a.id,object:c.id,readHeadsKey:null,linkApp:null};u.readHeadsKey=h?.readHeadsKey??u.readHeadsKey,u.linkApp=h?.linkApp?.id??u.linkApp,r.set(_,u)}const s=[...r.entries()].sort(([a],[c])=>a<c?-1:a>c?1:0),o=i(a=>s.map(([,c])=>a(c)),"col"),w=await t.prepare(`INSERT INTO watches (watch_id, watcher, object, in_tree, read_heads_key, created_at, link_app)
|
|
2
2
|
SELECT v.id, v.watcher, v.object, 0, v.rhk, ?::text, v.link
|
|
3
3
|
FROM unnest(?::text[], ?::text[], ?::text[], ?::text[], ?::text[]) WITH ORDINALITY AS v(id, watcher, object, rhk, link, n) ORDER BY v.n
|
|
4
4
|
ON CONFLICT (watcher, object) DO UPDATE SET read_heads_key = COALESCE(excluded.read_heads_key, watches.read_heads_key),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var f=(n,r)=>p(n,"name",{value:r,configurable:!0});import{join as l}from"node:path";import{CONFIG_FILE as g}from"../types.js";import{listDirs as d,pathExists as h,readJsonIfExists as I}from"./fs-utils.js";import{readPluginManifest as w}from"./manifest.js";import{awaitBundleSwap as b,bundleSwapInFlightElsewhere as y}from"./plugin-swap-lock.js";import{isCloudRole as v}from"./canvas/person-state.js";import{currentSnapshot as S,readCachedSettings as a}from"./scoped-state/person-store.js";import{importedIntoNorthlight as k,withAppInstalls as C}from"./scoped-state/imported-mac-installs.js";import{pluginsDir as E}from"./scope.js";function F(n,r){const t=n==="user"?k()?C(S(),a("user").settings):a("user").settings:I(l(r,g));return t&&t.plugins&&typeof t.plugins=="object"?t.plugins:{}}f(F,"pluginConfigForRoot");function j(n,r,t){const o=Object.keys(r);return o.every(e=>t.has(e))?[]:o.filter(e=>!t.has(e)&&y(n,e))}f(j,"swapsToWaitOut");function L(n,r){if(n==="user"&&v())return[];const t=n!=="user"?l(r,"plugins"):E("user");if(t===void 0||!h(t))return[];const o=F(n,r),e=m(n,t,o),u=j(r,o,new Set(e.map(i=>i.name)));if(u.length===0)return e;for(const i of u)b(r,i);return m(n,t,o)}f(L,"listInstalledPluginsInRoot");function m(n,r,t){const o=[];for(const e of d(r)){const u=l(r,e),i=w(u);if(!i)continue;const s=t[e],c=typeof s?.version=="string"?s.version:i.version;o.push({name:e,scope:n,root:u,manifest:i,enabled:typeof s?.enabled=="boolean"?s.enabled:!0,sourceMarketplace:typeof s?.source_marketplace=="string"?s.source_marketplace:void 0,version:c})}return o}f(m,"collectInstalledPlugins");export{L as listInstalledPluginsInRoot};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { importedIntoNorthlight } from '../../shared/env.js';
|
|
2
|
+
import type { PersonSnapshot, SettingsOp } from './person-store.js';
|
|
3
|
+
export declare const TERMINAL_APP = "app:terminal";
|
|
4
|
+
export { importedIntoNorthlight };
|
|
5
|
+
/** The user settings with the terminal app's install block in place of their `plugins` and `marketplaces` keys. */
|
|
6
|
+
export declare function withAppInstalls(snapshot: PersonSnapshot, raw: Record<string, unknown> | null): Record<string, unknown> | null;
|
|
7
|
+
/** Split a user-settings write into the settings op (without install keys) and, when the installs changed, the app-block op. */
|
|
8
|
+
export declare function splitUserSettingsWrite(snapshot: PersonSnapshot, next: Record<string, unknown>, ifRevision: string): SettingsOp[];
|
|
9
|
+
/** Once per imported Mac: the import moved no installs into the terminal app's block, while the legacy `runtime/scope/config.json` and the
|
|
10
|
+
* plugin directories still name them. Copy every missing marketplace and plugin row into the block; rows already there win. A provider
|
|
11
|
+
* bundle (`provider` in its manifest) is the runtime's, refreshed on grant sync, and is not an install. A marker file ends the migration. */
|
|
12
|
+
export declare function migrateLegacyInstallsOnce(): Promise<void>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var I=Object.defineProperty;var p=(o,i)=>I(o,"name",{value:i,configurable:!0});import{importedIntoNorthlight as x}from"../../shared/env.js";import{appRevisionOf as l}from"./person-store.js";const g="app:terminal";function _(o,i){const c=o.apps[g];return c===void 0&&i===null?null:{...i??{},plugins:structuredClone(c?.plugins??{}),marketplaces:structuredClone(c?.marketplaces??{})}}p(_,"withAppInstalls");function j(o,i,c){const{plugins:w,marketplaces:b,...s}=i,n=o.apps[g],u=[{op:"settings.replace",owner:"user",raw:s,ifRevision:c}],d={plugins:Object.fromEntries(Object.entries(w??{}).filter(([,y])=>y.source_marketplace!==void 0)),marketplaces:b??{}},k={plugins:n?.plugins??{},marketplaces:n?.marketplaces??{}};return l(d)!==l(k)&&u.push({op:"app-plugins.replace",app:g,...d,ifRevision:l(n)}),u}p(j,"splitUserSettingsWrite");const h={name:"crouter-official-marketplace",url:"https://github.com/crouton-labs/crouter-official-marketplace.git"};async function C(){if(!x())return;const{existsSync:o,readFileSync:i,readdirSync:c,writeFileSync:w,mkdirSync:b}=await import("node:fs"),{join:s}=await import("node:path"),{runtimeRoot:n}=await import("../layout.js"),u=s(n(),"import","app-installs-migrated");if(o(u))return;const{writeSettings:S}=await import("./person-store.js"),{readPluginManifest:d}=await import("../manifest.js"),k=p(a=>a.code==="ENOENT","missing"),y=(()=>{try{return JSON.parse(i(s(n(),"scope","config.json"),"utf8"))}catch(a){if(k(a))return{};throw a}})(),O=p(a=>{try{return c(a,{withFileTypes:!0}).filter(e=>!e.name.startsWith(".")&&(e.isDirectory()||e.isSymbolicLink())).map(e=>e.name)}catch(e){if(k(e))return[];throw e}},"onDisk"),v=s(n(),"plugins");await S(a=>{const e=a.apps[g],r=structuredClone({plugins:e?.plugins??{},marketplaces:e?.marketplaces??{}});for(const[t,m]of Object.entries(y.marketplaces??{}))r.marketplaces[t]===void 0&&(r.marketplaces[t]=t===h.name?{...m,url:h.url}:m);for(const t of O(s(n(),"marketplaces")))r.marketplaces[t]===void 0&&t===h.name&&(r.marketplaces[t]={url:h.url,ref:"main"});for(const t of O(v)){if(r.plugins[t]!==void 0)continue;const m=d(s(v,t));if(m===null||m.provider!==void 0)continue;const f=y.plugins?.[t];f?.source_marketplace!==void 0&&(r.plugins[t]={enabled:f.enabled??!0,source_marketplace:f.source_marketplace,...f.version===void 0?{}:{version:f.version}})}return l(r)===l(e)?[]:[{op:"app-plugins.replace",app:g,plugins:r.plugins,marketplaces:r.marketplaces,ifRevision:l(e)}]}),b(s(n(),"import"),{recursive:!0}),w(u,`${new Date().toISOString()}
|
|
2
|
+
`)}p(C,"migrateLegacyInstallsOnce");export{g as TERMINAL_APP,x as importedIntoNorthlight,C as migrateLegacyInstallsOnce,j as splitUserSettingsWrite,_ as withAppInstalls};
|
package/dist/core/spaces/stop.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var D=Object.defineProperty;var c=(t,r)=>D(t,"name",{value:r,configurable:!0});import{randomUUID as x}from"node:crypto";import{readJobSupervisorState as J,signalBashJob as k,unfinishedBashJobIds as O}from"../bash-jobs.js";import{contextDir as M}from"../canvas/node-agent-paths.js";import{getNode as P}from"../canvas/index.js";import{withCanvasWrite as R,openDb as h}from"../canvas/db.js";import{finishJob as $,ownerRunsRemotely as A,runningJobs as N,startJob as W}from"../graph/jobs.js";import{getById as S,nodeObject as C}from"../graph/objects.js";import{readLiveSession as H}from"../canvas/sessions.js";import{conversationStore as L}from"../conversation-store/index.js";import{requestBrokerTeardown as _}from"../runtime/host.js";import{holdRecovery as q,waitForRecoveryHold as F}from"../runtime/recovery-hold.js";async function T(t,r,e){return await R(async n=>{const a=await S(n,t);return a===null||a.type!=="job"?!1:(await $(n,a,{killedBy:await r(n),...e===void 0?{}:{reason:e}}),!0)})}c(T,"killBashJobObject");async function nt(t,r,e){return await R(async n=>{const a=await S(n,r);if(a!==null){if(a.type!=="job")throw new Error(`${r} names a ${a.type}`);return a}return await W(n,await C(n,t),{id:r,...e})})}c(nt,"recordBashJobObject");const y=new Map;async function U(t,r,e){return await F(t)==="lapsed"?await Y(t,r,e):await _(t,{excludePid:e.excludePid})}c(U,"stopHeldElsewhere");async function Y(t,r,e={}){const n=y.get(t);if(n)return n;const a=await P(t);if(!a)return Promise.resolve({confirmed:!1,error:new Error(`missing node ${t}`)});const g=(await H(t))?.sessionId,b=c(async()=>await(await h()).prepare(`SELECT type, body_json FROM run_events WHERE node_id = ?
|
|
2
|
-
AND type IN ('node.turn.started', 'node.turn.completed') ORDER BY sequence_number DESC LIMIT 1`).get(t),"latestTurn"),j=a.run_id!==null&&a.pi_pid!==null&&(await b())?.type==="node.turn.started",u=await q(t);if(u===null)return await U(t,r,e);const B=_(t,{excludePid:e.excludePid,...e.startAfter?{startAfter:e.startAfter}:{}}),
|
|
2
|
+
AND type IN ('node.turn.started', 'node.turn.completed') ORDER BY sequence_number DESC LIMIT 1`).get(t),"latestTurn"),j=a.run_id!==null&&a.pi_pid!==null&&(await b())?.type==="node.turn.started",u=await q(t);if(u===null)return await U(t,r,e);const B=_(t,{excludePid:e.excludePid,...e.startAfter?{startAfter:e.startAfter}:{}}),p=(async()=>{const w=await B;if(!w.confirmed)return w;try{const o=c(()=>({confirmed:!1,error:new Error(`the recovery hold on ${t} lapsed during its stop`)}),"lost");if(!await u.renew())return o();const l=new Map((await N(await h(),t)).map(s=>[s.jobId,s]));if(await A(await h(),t)){if(!e.deleting)for(const s of l.keys())await T(s,async()=>null,r)}else{const s=await M(t);for(const i of new Set([...l.keys(),...O(s)])){const d=J(s,i),m=d.pgid??l.get(i)?.pgid??null,f=d.pgidIdentity??l.get(i)?.pgidIdentity??null;if(m===null||f===null)throw new Error(`bash job ${i} could not be stopped`);await k(m,f,t),!e.deleting&&l.has(i)&&await T(i,async()=>null,r)}}if(!await u.renew())return o();if(j&&g&&!e.deleting){if((await b())?.type!=="node.turn.started")return await u.renew()?(await e.after?.(),w):o();const i=L(),{entries:d}=await i.read(g),m=d.at(-1),f=new Date().toISOString(),E=r==="permission_revoked",v={type:"message",id:x(),parentId:m?.id??null,timestamp:f,message:{role:"assistant",content:[],api:"openai-completions",provider:"crouter",model:"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:E?"error":"aborted",errorMessage:r,timestamp:Date.now()}};await i.append(g,[v,{type:"custom",id:x(),parentId:v.id,timestamp:f,customType:"crtr-turn-end",data:E?{stop_reason:"error",error:{code:"model_error",message:r}}:{stop_reason:"aborted"}}])}return await u.renew()?(await e.after?.(),w):o()}catch(o){return{confirmed:!1,error:o instanceof Error?o:new Error(String(o))}}})().finally(()=>u.release().catch(()=>{}));return y.set(t,p),p.finally(()=>{y.get(t)===p&&y.delete(t)}),p}c(Y,"stopNodeSandboxes");export{T as killBashJobObject,nt as recordBashJobObject,Y as stopNodeSandboxes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var He=Object.defineProperty;var o=(e,r)=>He(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as Le,importPrincipalFor as Be}from"./import-auth.js";import{createServer as se}from"node:http";import{createServer as xe}from"node:https";import{chmodSync as De,existsSync as Y,readFileSync as ae,unlinkSync as le}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as ce,RUNTIME_VERSION_HEADER as K,minimumRuntimeRefusal as Fe}from"../../api/runtime-version.js";import{CONTRACT_HEADER as X,CONTRACT_LEVEL as ue,REQUIRED_CONTRACT_HEADER as pe,contractRefusal as Me}from"../../api/contract.js";import{crtrVersion as Z}from"../../shared/crtr-version.js";import{apiSocketPath as $e}from"../../core/canvas/paths.js";import{resolveNodeToken as Je}from"../../core/canvas/node-tokens.js";import{isCloudRole as N,runAsPerson as W}from"../../core/canvas/person.js";import{isCanvasRequest as We,serveCanvas as je}from"./canvas-host.js";import{personBearerVerifier as de}from"./auth/person-bearer.js";import{personHasSnapshot as Q}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Ve}from"./principal.js";import{createAppRequestHandler as Ge}from"./app-listener.js";import{decodeJwt as Ye}from"jose";import{handleRuntimeSignIn as Ke,isRuntimeSignInPath as Xe}from"./key-signin.js";import{RunError as b}from"../../core/runs/operations.js";import{createRepoPluginHandler as Ze,isRepoPluginPath as Qe}from"./repo-plugin.js";import{removeVendorAccount as qe,vendorStatus as er}from"./handlers/vendor-status.js";import{toErrorBody as rr}from"./map.js";import{CONTROL_BODY_MAX_BYTES as tr}from"../../core/llm/body-limits.js";import{grantFor as nr,hasSyncedGrants as or}from"../../core/grants/mirror.js";import{readConfig as fe}from"../../core/config.js";import{directoryIssuer as ir}from"../../core/directory/issuer.js";import{peerUid as sr}from"../../native/linux.js";import{findScopedApiToken as ar,getApiToken as lr,listScopedApiTokens as cr}from"../../core/secrets.js";import{emitEvent as y}from"../../core/events/emit.js";import{envCrtrdTcp as ur,envCrtrdToken as pr}from"../../shared/env.js";import{Router as me,actsAsPerson as ge}from"./router.js";import{handleAttachUpgrade as dr,refuseUpgrade as v}from"./bridge.js";import{handleMachineLinkUpgrade as fr,machineLinkEnvironment as mr,setApiAddress as gr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as hr,machineViewEnvironment as Rr}from"../machine-link/forward.js";import{boundDaemonControl as Ar}from"../control.js";import{attachRoutes as yr,mayAttachNode as he}from"./handlers/attach.js";import{peerRoutes as vr}from"../peer/handlers.js";import{bashJobRoutes as _r}from"./handlers/bash-jobs.js";import{nodeFileRoutes as wr}from"./handlers/node-files.js";import{bashRoutes as Er}from"./handlers/bash.js";import{hookExecRoutes as Sr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as Re}from"./handlers/broker-ops.js";import{brokerSignalRoutes as br,brokerSignalStreams as Tr}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as Ae,nodeFaultRoutes as Cr}from"./handlers/broker-recovery.js";import{canvasRoutes as kr}from"./handlers/canvas.js";import{conversationRoutes as Pr}from"./handlers/conversations.js";import{chatInventoryRoutes as Ur}from"./handlers/chat-inventory.js";import{daemonRoutes as Or}from"./handlers/daemon.js";import{fileRoutes as Nr}from"./handlers/files.js";import{focusRoutes as Ir}from"./handlers/focus.js";import{analyticsRoutes as zr}from"./handlers/analytics.js";import{memoryReadsRoutes as Hr}from"./handlers/memory-reads.js";import{memoryRoutes as Lr}from"./handlers/memory.js";import{healthRoutes as Br}from"./handlers/health.js";import{humanRequestRoutes as xr}from"./handlers/human-requests.js";import{inboxRoutes as Dr}from"./handlers/inbox.js";import{feedbackCommentRoutes as Fr}from"./handlers/feedback-comments.js";import{objectRoutes as Mr}from"./handlers/objects.js";import{shareRoutes as $r}from"./handlers/shares.js";import{customObjectRoutes as Jr}from"./handlers/custom-objects.js";import{docRoutes as Wr}from"./handlers/docs.js";import{deliveryRoutes as ye}from"./handlers/delivery.js";import{deliveryRetryRoutes as jr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Vr}from"./handlers/package-docs.js";import{documentAccessRoutes as Gr}from"./handlers/document-access.js";import{pluginAppRoutes as Yr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as ve,messageRoutes as Kr}from"./handlers/messages.js";import{modelAuthRoutes as Xr}from"./handlers/modelauth.js";import{llmRoutes as Zr}from"./handlers/llm.js";import{providerRoutes as Qr}from"./handlers/providers.js";import{modelConfigRoutes as qr}from"./handlers/model-config.js";import{settingsRoutes as et}from"./handlers/settings.js";import{nodeRoutes as rt}from"./handlers/nodes.js";import{nodeRecordRoutes as tt}from"./handlers/node-records.js";import{nodeOutcomeRoutes as nt}from"./handlers/node-outcomes.js";import{nodeEventRoutes as ot}from"./handlers/node-events.js";import{profileRoutes as it}from"./handlers/profiles.js";import{environmentRoutes as st}from"./handlers/environments.js";import{prospectiveChatInventoryRoutes as at}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as lt}from"./handlers/reports.js";import{runRoutes as ct}from"./handlers/run-routes.js";import{reviewCommentRoutes as ut}from"./handlers/review-comments.js";import{reviewRoutes as pt}from"./handlers/reviews.js";import{subscriptionRoutes as dt}from"./handlers/subscriptions.js";import{structuredRequestRoutes as ft}from"./handlers/structured-requests.js";import{cronRoutes as mt}from"./handlers/crons.js";import{setCronRequestHandler as _e}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as gt,cronPrincipalForRunToken as ht}from"../cron/run-token.js";import{worktreeRoutes as Rt}from"./handlers/worktree.js";import{limitsRoutes as At}from"./handlers/limits.js";import{chargeRoutes as yt,spendLimitRoutes as vt}from"./handlers/charges.js";import{executionStartRoutes as _t}from"./handlers/execution-start.js";import{machineCredentialRoutes as wt}from"./handlers/machine-credential.js";import{importRoutes as Et}from"./handlers/imports.js";import{gitCredentialRoutes as St}from"./handlers/git-credential.js";function bt(e){return new me().registerAll(Br(e)).registerAll(Or).registerAll($r).registerAll(rt).registerAll(tt).registerAll(nt).registerAll(jr).registerAll(ot).registerAll(_r).registerAll(wr).registerAll(Er).registerAll(Sr).registerAll(Re).registerAll(br).registerAll(ye).registerAll(Ae).registerAll(Cr).registerAll(Rt).registerAll(At).registerAll(yt).registerAll(_t).registerAll(wt).registerAll(Et).registerAll(St).registerAll(vt).registerAll(ve).registerAll(Kr).registerAll(lt).registerAll(ct).registerAll(ft).registerAll(yr).registerAll(kr).registerAll(Pr).registerAll(zr).registerAll(Hr).registerAll(Lr).registerAll(Nr).registerAll(Mr).registerAll(Jr).registerAll(Wr).registerAll(Vr).registerAll(Gr).registerAll(Yr).registerAll(Ir).registerAll(dt).registerAll(mt).registerAll(it).registerAll(st).registerAll(Xr).registerAll(Zr).registerAll(Qr).registerAll(qr).registerAll(et).registerAll(pt).registerAll(ut).registerAll(Dr).registerAll(xr).registerAll(Ur).registerAll(at).registerAll(Fr).registerAll(vr)}o(bt,"buildRouter");function Tt(e,r){if(e.toUpperCase()!=="GET")return null;const i=r.split("/").filter(u=>u.length>0);if(i.length!==4||i[0]!=="v1"||i[1]!=="nodes"||i[3]!=="attach")return null;const s=i[2];return s===void 0||s===""?null:decodeURIComponent(s)}o(Tt,"attachNodeId");function Ct(e){const r=e.trim();if(r==="")return null;const i=r.lastIndexOf(":");if(i<0)return null;const s=r.slice(0,i),u=r.slice(i+1),d=Number(u);return!Number.isInteger(d)||d<0||d>65535?null:{host:s===""?"0.0.0.0":s,port:d}}o(Ct,"parseTcp");function kt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}o(kt,"formatTcpAddress");const I={code:"unauthorized",message:"missing or invalid bearer token"},L={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},M={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},ee={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},B=new WeakMap;function $(e){return B.get(e)}o($,"socketPrincipal");async function we(e,r){const i=process.platform==="linux"?sr(e.socket):null,s=e.headers.authorization;if(s===void 0)return i===null||r.has(i)?{class:"person"}:"unauthorized";if(typeof s!="string"||!s.startsWith("Bearer "))return"unauthorized";if(s.slice(7).startsWith("crtr_pub_"))return ee;if(s.slice(7).startsWith(re)){const u=Te(s.slice(7));return u!==void 0&&(i===null||r.has(i))?u.principal:"unauthorized"}return Ee(s.slice(7),i)}o(we,"resolveSocketPrincipal");async function Ee(e,r){const i=await Je(e);if(!i||r!==null&&r!==i.uid)return"unauthorized";const s=ir();if(s&&!N()&&!await or(s))return"runtime_starting";const u=i.grant??(await nr("app:terminal",i.sub))?.id??null;return{class:"broker",...i,grant:u}}o(Ee,"brokerPrincipal");function Se(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}o(Se,"requestPerson");function be(e,r){r.class==="broker"&&y({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}o(be,"noteBrokerRequest");const re="crtr_app_";function Te(e){const r=e.startsWith(re)?ar(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}o(Te,"appBearer");function Pt(e){const r=new Map;for(const i of cr("user"))r.set(i.token,{principal:{class:"app",app:i.grantee,scopes:i.scopes},ceiling:i.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}o(Pt,"resolveBearers");function Ut(e){try{return Ye(e).act!==void 0}catch{return!1}}o(Ut,"carriesAct");const Ot=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function P(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}o(P,"deny");async function Ce(e,r,i){const s=e.headers.authorization;if(s===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:ee,ceiling:null};if(typeof s!="string"||!s.startsWith("Bearer "))return P(i,s===void 0?"no_authorization_header":"not_a_bearer");const u=s.slice(7);if(u.startsWith("crtr_pub_"))return{principal:ee,ceiling:null};if(u.startsWith(re))return Te(u)??P(i,"app_token_unknown");if(u.startsWith(gt)){const E=await ht(u);return E===null?P(i,"run_token_invalid_or_settled"):{principal:E,ceiling:null}}const d=r.get(u);if(d!==void 0)return d;const R=Be(u);if(R!==null)return{principal:R,ceiling:null};if(u.startsWith(Le))return P(i,"import_token_invalid");if(Ot.test(u)){if(N()&&Ut(u)){const x=V();if(x===null)return"person_bearer";try{const w=await x.verifyCall(s);return w.chain[0]?.sub.startsWith("app:")?{call:w}:P(i,"call_token_presenter_not_an_app")}catch(w){return w instanceof b&&w.status===503?"runtime_starting":P(i,`call_token_${w instanceof b?w.code:"invalid"}`)}}const E=N()?de():null;if(E===null)return"person_bearer";const U=await E.verify(u);return U===null?P(i,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await Ee(u,null);return m==="unauthorized"?P(i,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}o(Ce,"authorizeTcp");let j;function V(){if(j!==void 0)return j;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return j=e===void 0||r===void 0?null:new Ve(e,r,async()=>{}),j}o(V,"cloudCallResolver");let ke;function Nt(){const e=V();if(e===null)throw new b(503,"runtime_starting","app calls are not configured on this listener");return ke??=Ge(e,async()=>!0,async()=>{}),ke}o(Nt,"cloudAppCalls");async function It(e,r){z(r),H(r);const i=V();try{if(i===null)throw new b(503,"runtime_starting","sign-in is not configured on this listener");await Ke(e,r,new URL(e.url??"/","http://runtime.local"),i)}catch(s){if(!(s instanceof b))throw s;if(r.headersSent){r.destroy();return}r.writeHead(s.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:s.code,message:s.message,...s.param?{param:s.param}:{},origin:"runtime"}}))}}o(It,"serveRuntimeSignIn");function zt(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:ae(e),key:ae(r)}}o(zt,"tcpTls");function z(e){e.setHeader(K,Z()),e.setHeader(X,ue)}o(z,"advertiseRuntime");function H(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${K}, ${X}`)}o(H,"exposeRuntimeHeaders");function Ht(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(z(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${K}, ${X}`,"Access-Control-Allow-Headers":`authorization, content-type, ${ce.toLowerCase()}, ${pe.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}o(Ht,"answerPreflight");function G(e,r=!1){z(e),r&&H(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...I,origin:"runtime"}}))}o(G,"writeUnauthorized");function Lt(e){z(e),H(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}o(Lt,"writePersonBearerRefused");const Bt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function xt(e,r){if(!N())return!1;const i=new URL(e.url??"/","http://runtime.local").pathname,s=Bt[i];if(s===void 0||e.method!==s.method)return!1;const u=o((d,R)=>{z(r),H(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=de();if(d===null)throw new b(401,M.code,M.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),s.purpose):null;if(m===null)throw new b(401,"unauthorized","invalid directory token");const E=s.purpose==="vendor_status"?void 0:await Dt(e);u(200,await W(m,async()=>s.purpose==="vendor_status"?er():await qe(E)))}catch(d){const{status:R,body:m}=rr(d);u(R,m)}return!0}o(xt,"serveCloudVendorRoute");async function Dt(e){const r=[];let i=0;for await(const s of e){if(i+=s.length,i>tr)throw new b(400,"invalid_request","request body too large");r.push(s)}if(i!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new b(400,"invalid_request","invalid JSON body")}}o(Dt,"readVendorBody");function Pe(e){z(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}o(Pe,"writeRuntimeStarting");function Ft(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}o(Ft,"writeStartupBlocked");function Ue(e,r,i){return new Promise(s=>{for(const m of r)m.destroy();if(i===void 0){try{e.closeAllConnections()}catch{}e.close(()=>s());return}const u=[];e.close(()=>{for(const m of u)clearTimeout(m);s()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),i);u.push(d,R),e.closeIdleConnections()})}o(Ue,"closeServer");function No(e={}){let r=null;const i=bt(()=>r),s=new me().registerAll(Re).registerAll(ye).registerAll(Ae).registerAll(ve),u=o((t,n)=>{const c=Ar()?.startupBlock()??null;return c===null||t==="GET"&&(n==="/healthz"||n==="/v1/status"||n==="/v1/ready")||t==="POST"&&(n==="/v1/daemon/migrate"||n==="/v1/daemon/admit")||c.phase==="recovering"&&s.match(t,n)!==null?null:c},"startupBlockFor"),d=e.socketPath??$e(),R=new Set([process.getuid?.()??0,...fe("user").runtime?.person_uids??[]]),m=o((t,n,c)=>{z(n);const p=o(f=>Array.isArray(f)?f[0]:f,"first"),O=p(t.headers[ce.toLowerCase()]),A=Fe(O,Z())??Me(p(t.headers[pe.toLowerCase()]),ue,{legacyMinimum:O,runtimeVersion:Z()});if(A!==null){n.writeHead(A.status,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:A.code,message:A.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in A?{param:A.param}:{details:A.details}}}));return}const S=o(f=>{const l=$(t);y({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:f instanceof Error?f:new Error(String(f))});try{n.headersSent||n.writeHead(500,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let C;try{C=new URL(t.url??"/","http://127.0.0.1")}catch{try{n.writeHead(400,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const f=u((t.method??"GET").toUpperCase(),C.pathname);if(f!==null){Ft(n,f.message);return}const l=$(t)??{class:"person"},a=Se(l),g=o(()=>i.handle(t,n,c,l),"handled");(a===void 0?g():W(a,o(async()=>{Q()||await q(a),await g()},"handledAsPerson"))).catch(S)}catch(f){S(f)}},"onRequest"),E=o(async(t,n,c)=>{const p=$(t);return p===void 0||ge(p)||await he(p,"either",c)?!0:(v(n,404,"Not Found","node_not_found",`no node ${c}`),!1)},"authorizeAttachUpgrade"),U=new Set,x=o(t=>{U.add(t),t.once("close",()=>U.delete(t)),t.on("error",()=>{})},"trackUpgrade"),w=o((t,n,c)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=u((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){v(n,503,"Service Unavailable","startup_blocked",O.message);return}const A=Tt(t.method??"GET",p.pathname);if(A===null){n.destroy();return}const S=(()=>{const f=$(t);return f===void 0?void 0:Se(f)})(),C=o(()=>E(t,n,A).then(f=>f?dr(t,n,c,A,async l=>{const a=$(t);return a===void 0||ge(a)||await he(a,l,A)}):void 0),"attach");(S===void 0?C():W(S,async()=>{Q()||await q(S),await C()})).catch(()=>{try{n.destroy()}catch{}})}catch{try{n.destroy()}catch{}}},"onUpgrade"),Oe=o(t=>{t.on("error",n=>{y({event:"api.server.failed",level:"error",error:n})})},"bindErrorHandler"),Ne=o(async(t,n)=>{try{const c=await we(t,R);if(c==="unauthorized"){y({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),G(n);return}if(c==="runtime_starting"){Pe(n);return}B.set(t,c),be(t,c),m(t,n,c.class==="app"?c.scopes:null)}catch(c){y({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}),G(n)}},"onSocketRequest"),D=se((t,n)=>{Ne(t,n).catch(c=>y({event:"api.principal.failed",level:"error",error:c instanceof Error?c:new Error(String(c))}))}),Ie=o(async(t,n,c)=>{try{const p=await we(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&y({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),v(n,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){v(n,403,"Forbidden",L.code,L.message);return}B.set(t,p),w(t,n,c)}catch(p){y({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),v(n,401,"Unauthorized",I.code,I.message)}},"onSocketUpgrade");D.on("upgrade",(t,n,c)=>{x(n),Ie(t,n,c).catch(p=>y({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),_e((t,n,c)=>{B.set(t,c),m(t,n,null)});let te=!1,ne,oe;const ze=new Promise((t,n)=>{ne=t,oe=n});D.once("listening",()=>{te=!0,ne()}),D.on("error",t=>{y({event:"api.server.failed",level:"error",error:t}),te||oe(t)});try{Y(d)&&le(d)}catch{}D.listen(d,()=>{try{De(d,process.platform==="linux"&&Y("/run/crtr/launcher.sock")?438:384)}catch(t){y({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let T;const J=e.tcp??ur()??fe("user").api.tcp;if(J!==void 0&&J!==""){const t=Ct(J);if(t===null)y({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${J}`)});else{N()&&V();const n=N()?Ze():null,c=e.token??pr()??lr("user"),p=Pt(c),O=o(async(l,a)=>{if(We(l)){await je(l,a);return}if(Ht(l,a))return;if(N()&&Xe(new URL(l.url??"/","http://runtime.local").pathname)){await It(l,a);return}if(await xt(l,a))return;if(n!==null&&Qe(new URL(l.url??"/","http://runtime.local").pathname)){await n(l,a);return}const g={},h=await Ce(l,p,g);if(h==="runtime_starting"){H(a),Pe(a);return}if(h==="person_bearer"){Lt(a);return}if(h==="unauthorized"){y({event:"api.principal.denied",level:"warn",fields:{method:l.method,listener:"tcp",path:new URL(l.url??"/","http://runtime.local").pathname,reason:g.reason??"unknown"}}),G(a,!0);return}if("call"in h){H(a);const F=h.call.sub;await W(F,async()=>{Q()||await q(F),await Nt()(l,a,h.call)});return}B.set(l,h.principal),be(l,h.principal),H(a),m(l,a,h.ceiling)},"tcpOnRequest"),A=o(async(l,a,g)=>{const h=mr(l);if(h!==null){const _=await fr(l,a,g,h);_!==null&&v(a,_.status,_.text,_.code,_.message);return}const F=Rr(l);if(F!==null){const _=hr(l,a,g,F);_!==null&&v(a,_.status,_.text,_.code,_.message);return}const k=await Ce(l,p);if(k==="runtime_starting"){v(a,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(k==="person_bearer"){v(a,401,"Unauthorized",M.code,M.message);return}if(k==="unauthorized"){v(a,401,"Unauthorized",I.code,I.message);return}if("call"in k){v(a,403,"Forbidden",L.code,L.message);return}if(k.ceiling!==null||k.principal.class==="anonymous"||k.principal.class==="import"){v(a,403,"Forbidden",L.code,L.message);return}B.set(l,k.principal),w(l,a,g)},"tcpOnUpgrade"),S=o(l=>{y({event:"api.principal.failed",level:"error",error:l instanceof Error?l:new Error(String(l))})},"failed"),C=o((l,a)=>{O(l,a).catch(g=>{S(g),a.headersSent?a.destroy():G(a,!0)})},"listener"),f=zt();T=f===null?se(C):xe(f,C),T.on("upgrade",(l,a,g)=>{x(a),A(l,a,g).catch(h=>{S(h),v(a,401,"Unauthorized",I.code,I.message)})}),Oe(T),T.once("listening",()=>{const l=T?.address();if(l!==null&&typeof l=="object"){const{address:a,port:g}=l;r=kt(a,g),a!=="0.0.0.0"&&a!=="::"&&gr(r)}}),T.listen(t.port,t.host)}}let ie=!1;return{ready:ze,tcpAddress:o(()=>r,"tcpAddress"),close:o(async(t={})=>{if(!ie){ie=!0,_e(null),Tr.close(),await Promise.all([Ue(D,U,t.graceMs),T!==void 0?Ue(T,U,t.graceMs):Promise.resolve()]);try{Y(d)&&le(d)}catch{}}},"close")}}o(No,"createApiServer");export{bt as buildRouter,Ue as closeServer,No as createApiServer,$ as socketPrincipal};
|
|
1
|
+
var ze=Object.defineProperty;var o=(e,r)=>ze(e,"name",{value:r,configurable:!0});import{IMPORT_TOKEN_PREFIX as Le,importPrincipalFor as Be}from"./import-auth.js";import{createServer as ae}from"node:http";import{createServer as xe}from"node:https";import{chmodSync as De,existsSync as G,readFileSync as le,unlinkSync as ue}from"node:fs";import{MINIMUM_RUNTIME_VERSION_HEADER as ce,RUNTIME_VERSION_HEADER as Y,minimumRuntimeRefusal as Fe}from"../../api/runtime-version.js";import{CONTRACT_HEADER as K,CONTRACT_LEVEL as pe,REQUIRED_CONTRACT_HEADER as de,contractRefusal as Me}from"../../api/contract.js";import{crtrVersion as X}from"../../shared/crtr-version.js";import{apiSocketPath as $e}from"../../core/canvas/paths.js";import{resolveNodeToken as Je}from"../../core/canvas/node-tokens.js";import{isCloudRole as N,runAsPerson as W}from"../../core/canvas/person.js";import{isCanvasRequest as We,serveCanvas as je}from"./canvas-host.js";import{personBearerVerifier as fe}from"./auth/person-bearer.js";import{personHasSnapshot as Z}from"../../core/scoped-state/person-store.js";import{loadPersonSettings as Q}from"../../core/scoped-state/person-rows.js";import{AppPrincipalResolver as Ve}from"./principal.js";import{createAppRequestHandler as Ge}from"./app-listener.js";import{decodeJwt as Ye}from"jose";import{handleRuntimeSignIn as Ke,isRuntimeSignInPath as Xe}from"./key-signin.js";import{RunError as b}from"../../core/runs/operations.js";import{createRepoPluginHandler as Ze,isRepoPluginPath as Qe}from"./repo-plugin.js";import{removeVendorAccount as qe,vendorStatus as er}from"./handlers/vendor-status.js";import{toErrorBody as rr}from"./map.js";import{CONTROL_BODY_MAX_BYTES as tr}from"../../core/llm/body-limits.js";import{grantFor as nr,hasSyncedGrants as or}from"../../core/grants/mirror.js";import{readConfig as me}from"../../core/config.js";import{directoryIssuer as ir}from"../../core/directory/issuer.js";import{peerUid as sr}from"../../native/linux.js";import{findScopedApiToken as ar,getApiToken as lr,listScopedApiTokens as ur}from"../../core/secrets.js";import{emitEvent as v}from"../../core/events/emit.js";import{envCrtrdTcp as cr,envCrtrdToken as pr}from"../../shared/env.js";import{Router as ge,actsAsPerson as he}from"./router.js";import{handleAttachUpgrade as dr,refuseUpgrade as y}from"./bridge.js";import{handleMachineLinkUpgrade as fr,machineLinkEnvironment as mr,setApiAddress as gr}from"../machine-link/holder.js";import{handleMachineViewUpgrade as hr,machineViewEnvironment as Rr}from"../machine-link/forward.js";import{boundDaemonControl as Ar}from"../control.js";import{attachRoutes as vr,mayAttachNode as Re}from"./handlers/attach.js";import{peerRoutes as yr}from"../peer/handlers.js";import{bashJobRoutes as _r}from"./handlers/bash-jobs.js";import{nodeFileRoutes as wr}from"./handlers/node-files.js";import{bashRoutes as Er}from"./handlers/bash.js";import{hookExecRoutes as Sr}from"./handlers/hook-exec.js";import{brokerOperationRoutes as Ae}from"./handlers/broker-ops.js";import{brokerSignalRoutes as br,brokerSignalStreams as Tr}from"./handlers/broker-signals.js";import{brokerRecoveryRoutes as ve,nodeFaultRoutes as Cr}from"./handlers/broker-recovery.js";import{canvasRoutes as kr}from"./handlers/canvas.js";import{conversationRoutes as Pr}from"./handlers/conversations.js";import{chatInventoryRoutes as Ur}from"./handlers/chat-inventory.js";import{daemonRoutes as Or}from"./handlers/daemon.js";import{fileRoutes as Nr}from"./handlers/files.js";import{focusRoutes as Ir}from"./handlers/focus.js";import{analyticsRoutes as Hr}from"./handlers/analytics.js";import{memoryReadsRoutes as zr}from"./handlers/memory-reads.js";import{memoryRoutes as Lr}from"./handlers/memory.js";import{healthRoutes as Br}from"./handlers/health.js";import{humanRequestRoutes as xr}from"./handlers/human-requests.js";import{inboxRoutes as Dr}from"./handlers/inbox.js";import{feedbackCommentRoutes as Fr}from"./handlers/feedback-comments.js";import{objectRoutes as Mr}from"./handlers/objects.js";import{shareRoutes as $r}from"./handlers/shares.js";import{customObjectRoutes as Jr}from"./handlers/custom-objects.js";import{docRoutes as Wr}from"./handlers/docs.js";import{deliveryRoutes as ye}from"./handlers/delivery.js";import{deliveryRetryRoutes as jr}from"./handlers/delivery-retry.js";import{packageDocRoutes as Vr}from"./handlers/package-docs.js";import{documentAccessRoutes as Gr}from"./handlers/document-access.js";import{pluginAppRoutes as Yr}from"./handlers/plugin-app-token.js";import{brokerMailRoutes as _e,messageRoutes as Kr}from"./handlers/messages.js";import{modelAuthRoutes as Xr}from"./handlers/modelauth.js";import{llmRoutes as Zr}from"./handlers/llm.js";import{providerRoutes as Qr}from"./handlers/providers.js";import{modelConfigRoutes as qr}from"./handlers/model-config.js";import{settingsRoutes as et}from"./handlers/settings.js";import{nodeRoutes as rt}from"./handlers/nodes.js";import{nodeRecordRoutes as tt}from"./handlers/node-records.js";import{nodeOutcomeRoutes as nt}from"./handlers/node-outcomes.js";import{nodeEventRoutes as ot}from"./handlers/node-events.js";import{profileRoutes as it}from"./handlers/profiles.js";import{environmentRoutes as st}from"./handlers/environments.js";import{prospectiveChatInventoryRoutes as at}from"./handlers/prospective-chat-inventory.js";import{reportRoutes as lt}from"./handlers/reports.js";import{runRoutes as ut}from"./handlers/run-routes.js";import{reviewCommentRoutes as ct}from"./handlers/review-comments.js";import{reviewRoutes as pt}from"./handlers/reviews.js";import{subscriptionRoutes as dt}from"./handlers/subscriptions.js";import{structuredRequestRoutes as ft}from"./handlers/structured-requests.js";import{cronRoutes as mt}from"./handlers/crons.js";import{setCronRequestHandler as we}from"../cron/run-socket.js";import{RUN_TOKEN_PREFIX as gt,cronPrincipalForRunToken as ht}from"../cron/run-token.js";import{worktreeRoutes as Rt}from"./handlers/worktree.js";import{limitsRoutes as At}from"./handlers/limits.js";import{chargeRoutes as vt,spendLimitRoutes as yt}from"./handlers/charges.js";import{executionStartRoutes as _t}from"./handlers/execution-start.js";import{machineCredentialRoutes as wt}from"./handlers/machine-credential.js";import{importRoutes as Et}from"./handlers/imports.js";import{gitCredentialRoutes as St}from"./handlers/git-credential.js";function bt(e){return new ge().registerAll(Br(e)).registerAll(Or).registerAll($r).registerAll(rt).registerAll(tt).registerAll(nt).registerAll(jr).registerAll(ot).registerAll(_r).registerAll(wr).registerAll(Er).registerAll(Sr).registerAll(Ae).registerAll(br).registerAll(ye).registerAll(ve).registerAll(Cr).registerAll(Rt).registerAll(At).registerAll(vt).registerAll(_t).registerAll(wt).registerAll(Et).registerAll(St).registerAll(yt).registerAll(_e).registerAll(Kr).registerAll(lt).registerAll(ut).registerAll(ft).registerAll(vr).registerAll(kr).registerAll(Pr).registerAll(Hr).registerAll(zr).registerAll(Lr).registerAll(Nr).registerAll(Mr).registerAll(Jr).registerAll(Wr).registerAll(Vr).registerAll(Gr).registerAll(Yr).registerAll(Ir).registerAll(dt).registerAll(mt).registerAll(it).registerAll(st).registerAll(Xr).registerAll(Zr).registerAll(Qr).registerAll(qr).registerAll(et).registerAll(pt).registerAll(ct).registerAll(Dr).registerAll(xr).registerAll(Ur).registerAll(at).registerAll(Fr).registerAll(yr)}o(bt,"buildRouter");function Tt(e,r){if(e.toUpperCase()!=="GET")return null;const i=r.split("/").filter(c=>c.length>0);if(i.length!==4||i[0]!=="v1"||i[1]!=="nodes"||i[3]!=="attach")return null;const s=i[2];return s===void 0||s===""?null:decodeURIComponent(s)}o(Tt,"attachNodeId");function Ct(e){const r=e.trim();if(r==="")return null;const i=r.lastIndexOf(":");if(i<0)return null;const s=r.slice(0,i),c=r.slice(i+1),d=Number(c);return!Number.isInteger(d)||d<0||d>65535?null:{host:s===""?"0.0.0.0":s,port:d}}o(Ct,"parseTcp");function kt(e,r){return`${e.includes(":")?`[${e}]`:e}:${r}`}o(kt,"formatTcpAddress");const F={code:"unauthorized",message:"missing or invalid bearer token"},z={code:"owner_only",message:"attach is owner-only; a scoped token does not reach it"},M={code:"person_bearer_not_supported",message:"this listener accepts a person bearer only on a cloud role with CRTR_DIRECTORY_URL and CRTR_PUBLIC_API_URL set; call with a node, app or public token"},q={class:"anonymous",app:"",node:"",run:null,uid:-1,sub:"",grant:null,client_id:null,scopes:[]},L=new WeakMap;function $(e){return L.get(e)}o($,"socketPrincipal");async function Ee(e,r){const i=process.platform==="linux"?sr(e.socket):null,s=e.headers.authorization;if(s===void 0)return i===null||r.has(i)?{class:"person"}:"unauthorized";if(typeof s!="string"||!s.startsWith("Bearer "))return"unauthorized";if(s.slice(7).startsWith("crtr_pub_"))return q;if(s.slice(7).startsWith(ee)){const c=Ce(s.slice(7));return c!==void 0&&(i===null||r.has(i))?c.principal:"unauthorized"}return Se(s.slice(7),i)}o(Ee,"resolveSocketPrincipal");async function Se(e,r){const i=await Je(e);if(!i||r!==null&&r!==i.uid)return"unauthorized";const s=ir();if(s&&!N()&&!await or(s))return"runtime_starting";const c=i.grant??(await nr("app:terminal",i.sub))?.id??null;return{class:"broker",...i,grant:c}}o(Se,"brokerPrincipal");function be(e){if(!(e.class==="anonymous"||e.class==="import"))return e.sub!==void 0&&e.sub!==""?e.sub:void 0}o(be,"requestPerson");function Te(e,r){r.class==="broker"&&v({event:"api.request.principal",level:r.app==="app:terminal"?"debug":"info",node_id:r.node,fields:{principal:`${r.app} node:${r.node}`,method:e.method,path:e.url}})}o(Te,"noteBrokerRequest");const ee="crtr_app_";function Ce(e){const r=e.startsWith(ee)?ar(e):void 0;return r===void 0?void 0:{principal:{class:"app",app:r.grantee,scopes:r.scopes},ceiling:r.scopes}}o(Ce,"appBearer");function Pt(e){const r=new Map;for(const i of ur("user"))r.set(i.token,{principal:{class:"app",app:i.grantee,scopes:i.scopes},ceiling:i.scopes});return e!==void 0&&r.set(e,{principal:{class:"person"},ceiling:null}),r}o(Pt,"resolveBearers");function Ut(e){try{return Ye(e).act!==void 0}catch{return!1}}o(Ut,"carriesAct");const Ot=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;function P(e,r){return e!==void 0&&(e.reason=r),"unauthorized"}o(P,"deny");async function ke(e,r,i){const s=e.headers.authorization;if(s===void 0&&(e.method??"GET").toUpperCase()==="GET"&&(e.url??"").split("?")[0]==="/healthz")return{principal:q,ceiling:null};if(typeof s!="string"||!s.startsWith("Bearer "))return P(i,s===void 0?"no_authorization_header":"not_a_bearer");const c=s.slice(7);if(c.startsWith("crtr_pub_"))return{principal:q,ceiling:null};if(c.startsWith(ee))return Ce(c)??P(i,"app_token_unknown");if(c.startsWith(gt)){const E=await ht(c);return E===null?P(i,"run_token_invalid_or_settled"):{principal:E,ceiling:null}}const d=r.get(c);if(d!==void 0)return d;const R=Be(c);if(R!==null)return{principal:R,ceiling:null};if(c.startsWith(Le))return P(i,"import_token_invalid");if(Ot.test(c)){if(N()&&Ut(c)){const B=V();if(B===null)return"person_bearer";try{const w=await B.verifyCall(s);return w.chain[0]?.sub.startsWith("app:")?{call:w}:P(i,"call_token_presenter_not_an_app")}catch(w){return w instanceof b&&w.status===503?"runtime_starting":P(i,`call_token_${w instanceof b?w.code:"invalid"}`)}}const E=N()?fe():null;if(E===null)return"person_bearer";const U=await E.verify(c);return U===null?P(i,"person_bearer_not_verified"):{principal:{class:"person",sub:U},ceiling:null}}const m=await Se(c,null);return m==="unauthorized"?P(i,"node_token_unknown"):typeof m=="string"?m:{principal:m,ceiling:null}}o(ke,"authorizeTcp");let j;function V(){if(j!==void 0)return j;const e=process.env.CRTR_DIRECTORY_URL||void 0,r=process.env.CRTR_PUBLIC_API_URL||void 0;return j=e===void 0||r===void 0?null:new Ve(e,r,async()=>{}),j}o(V,"cloudCallResolver");let Pe;function Nt(){const e=V();if(e===null)throw new b(503,"runtime_starting","app calls are not configured on this listener");return Pe??=Ge(e,async()=>!0,async()=>{}),Pe}o(Nt,"cloudAppCalls");async function It(e,r){I(r),H(r);const i=V();try{if(i===null)throw new b(503,"runtime_starting","sign-in is not configured on this listener");await Ke(e,r,new URL(e.url??"/","http://runtime.local"),i)}catch(s){if(!(s instanceof b))throw s;if(r.headersSent){r.destroy();return}r.writeHead(s.status,{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}),r.end(JSON.stringify({error:{code:s.code,message:s.message,...s.param?{param:s.param}:{},origin:"runtime"}}))}}o(It,"serveRuntimeSignIn");function Ht(){const e=process.env.CRTRD_TLS_CERT||void 0,r=process.env.CRTRD_TLS_KEY||void 0;if(e===void 0&&r===void 0)return null;if(e===void 0||r===void 0)throw new Error("CRTRD_TLS_CERT and CRTRD_TLS_KEY must be set together");return{cert:le(e),key:le(r)}}o(Ht,"tcpTls");function I(e){e.setHeader(Y,X()),e.setHeader(K,pe)}o(I,"advertiseRuntime");function H(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Expose-Headers",`${Y}, ${K}`)}o(H,"exposeRuntimeHeaders");function zt(e,r){return(e.method??"GET").toUpperCase()!=="OPTIONS"?!1:(I(r),r.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":`${Y}, ${K}`,"Access-Control-Allow-Headers":`authorization, content-type, ${ce.toLowerCase()}, ${de.toLowerCase()}`,"Access-Control-Allow-Methods":"GET, POST, PATCH, PUT, DELETE, OPTIONS","Access-Control-Max-Age":"600"}),r.end(),!0)}o(zt,"answerPreflight");function re(e,r=!1){I(e),r&&H(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...F,origin:"runtime"}}))}o(re,"writeUnauthorized");function Lt(e){I(e),H(e),e.writeHead(401,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{...M,origin:"runtime"}}))}o(Lt,"writePersonBearerRefused");const Bt={"/v1/runtime/vendor-status":{method:"GET",purpose:"vendor_status"},"/v1/runtime/vendor-account-remove":{method:"POST",purpose:"vendor_account_remove"}};async function xt(e,r){if(!N())return!1;const i=new URL(e.url??"/","http://runtime.local").pathname,s=Bt[i];if(s===void 0||e.method!==s.method)return!1;const c=o((d,R)=>{I(r),H(r),r.writeHead(d,{"content-type":"application/json; charset=utf-8"}),r.end(JSON.stringify(R))},"answer");try{const d=fe();if(d===null)throw new b(401,M.code,M.message);const R=e.headers.authorization,m=R?.startsWith("Bearer ")?await d.verifyPurpose(R.slice(7),s.purpose):null;if(m===null)throw new b(401,"unauthorized","invalid directory token");const E=s.purpose==="vendor_status"?void 0:await Dt(e);c(200,await W(m,async()=>s.purpose==="vendor_status"?er():await qe(E)))}catch(d){const{status:R,body:m}=rr(d);c(R,m)}return!0}o(xt,"serveCloudVendorRoute");async function Dt(e){const r=[];let i=0;for await(const s of e){if(i+=s.length,i>tr)throw new b(400,"invalid_request","request body too large");r.push(s)}if(i!==0)try{return JSON.parse(Buffer.concat(r).toString("utf8"))}catch{throw new b(400,"invalid_request","invalid JSON body")}}o(Dt,"readVendorBody");function te(e){I(e),e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"runtime_starting",message:"runtime is not ready",type:"server_error",origin:"runtime",retryable:!0}}))}o(te,"writeRuntimeStarting");function Ft(e,r){e.writeHead(503,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify({error:{code:"startup_blocked",message:r,origin:"runtime"}}))}o(Ft,"writeStartupBlocked");function Ue(e,r,i){return new Promise(s=>{for(const m of r)m.destroy();if(i===void 0){try{e.closeAllConnections()}catch{}e.close(()=>s());return}const c=[];e.close(()=>{for(const m of c)clearTimeout(m);s()});const d=setInterval(()=>e.closeIdleConnections(),250),R=setTimeout(()=>e.closeAllConnections(),i);c.push(d,R),e.closeIdleConnections()})}o(Ue,"closeServer");function No(e={}){let r=null;const i=bt(()=>r),s=new ge().registerAll(Ae).registerAll(ye).registerAll(ve).registerAll(_e),c=o((t,n)=>{const u=Ar()?.startupBlock()??null;return u===null||t==="GET"&&(n==="/healthz"||n==="/v1/status"||n==="/v1/ready")||t==="POST"&&(n==="/v1/daemon/migrate"||n==="/v1/daemon/admit")||u.phase==="recovering"&&s.match(t,n)!==null?null:u},"startupBlockFor"),d=e.socketPath??$e(),R=new Set([process.getuid?.()??0,...me("user").runtime?.person_uids??[]]),m=o((t,n,u)=>{I(n);const p=o(f=>Array.isArray(f)?f[0]:f,"first"),O=p(t.headers[ce.toLowerCase()]),A=Fe(O,X())??Me(p(t.headers[de.toLowerCase()]),pe,{legacyMinimum:O,runtimeVersion:X()});if(A!==null){n.writeHead(A.status,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:A.code,message:A.message,type:"invalid_request_error",origin:"runtime",retryable:!1,..."param"in A?{param:A.param}:{details:A.details}}}));return}const S=o(f=>{const l=$(t);v({event:"api.request.failed",level:"error",...l?.class==="broker"?{node_id:l.node}:{},error:f instanceof Error?f:new Error(String(f))});try{n.headersSent||n.writeHead(500,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"internal",message:"internal error",origin:"runtime"}}))}catch{}},"internalFailure");let C;try{C=new URL(t.url??"/","http://127.0.0.1")}catch{try{n.writeHead(400,{"content-type":"application/json; charset=utf-8"}),n.end(JSON.stringify({error:{code:"invalid_request",message:"request URL is invalid",origin:"runtime"}}))}catch{}return}try{const f=c((t.method??"GET").toUpperCase(),C.pathname);if(f!==null){Ft(n,f.message);return}const l=$(t)??{class:"person"},a=be(l),g=o(()=>i.handle(t,n,u,l),"handled");(a===void 0?g():W(a,o(async()=>{Z()||await Q(a),await g()},"handledAsPerson"))).catch(S)}catch(f){S(f)}},"onRequest"),E=o(async(t,n,u)=>{const p=$(t);return p===void 0||he(p)||await Re(p,"either",u)?!0:(y(n,404,"Not Found","node_not_found",`no node ${u}`),!1)},"authorizeAttachUpgrade"),U=new Set,B=o(t=>{U.add(t),t.once("close",()=>U.delete(t)),t.on("error",()=>{})},"trackUpgrade"),w=o((t,n,u)=>{try{const p=new URL(t.url??"/","http://127.0.0.1"),O=c((t.method??"GET").toUpperCase(),p.pathname);if(O!==null){y(n,503,"Service Unavailable","startup_blocked",O.message);return}const A=Tt(t.method??"GET",p.pathname);if(A===null){n.destroy();return}const S=(()=>{const f=$(t);return f===void 0?void 0:be(f)})(),C=o(()=>E(t,n,A).then(f=>f?dr(t,n,u,A,async l=>{const a=$(t);return a===void 0||he(a)||await Re(a,l,A)}):void 0),"attach");(S===void 0?C():W(S,async()=>{Z()||await Q(S),await C()})).catch(()=>{try{n.destroy()}catch{}})}catch{try{n.destroy()}catch{}}},"onUpgrade"),Oe=o(t=>{t.on("error",n=>{v({event:"api.server.failed",level:"error",error:n})})},"bindErrorHandler"),Ne=o(async(t,n)=>{try{const u=await Ee(t,R);if(u==="unauthorized"){v({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),re(n);return}if(u==="runtime_starting"){te(n);return}L.set(t,u),Te(t,u),m(t,n,u.class==="app"?u.scopes:null)}catch(u){v({event:"api.principal.failed",level:"error",error:u instanceof Error?u:new Error(String(u))}),te(n)}},"onSocketRequest"),x=ae((t,n)=>{Ne(t,n).catch(u=>v({event:"api.principal.failed",level:"error",error:u instanceof Error?u:new Error(String(u))}))}),Ie=o(async(t,n,u)=>{try{const p=await Ee(t,R);if(p==="unauthorized"||p==="runtime_starting"){p==="unauthorized"&&v({event:"api.principal.denied",level:"warn",fields:{method:t.method}}),y(n,p==="unauthorized"?401:503,"Unauthorized",p,"socket principal unavailable");return}if(p.class!=="person"&&p.class!=="broker"){y(n,403,"Forbidden",z.code,z.message);return}L.set(t,p),w(t,n,u)}catch(p){v({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}),y(n,503,"Service Unavailable","runtime_starting","socket principal unavailable")}},"onSocketUpgrade");x.on("upgrade",(t,n,u)=>{B(n),Ie(t,n,u).catch(p=>v({event:"api.principal.failed",level:"error",error:p instanceof Error?p:new Error(String(p))}))}),we((t,n,u)=>{L.set(t,u),m(t,n,null)});let ne=!1,oe,ie;const He=new Promise((t,n)=>{oe=t,ie=n});x.once("listening",()=>{ne=!0,oe()}),x.on("error",t=>{v({event:"api.server.failed",level:"error",error:t}),ne||ie(t)});try{G(d)&&ue(d)}catch{}x.listen(d,()=>{try{De(d,process.platform==="linux"&&G("/run/crtr/launcher.sock")?438:384)}catch(t){v({event:"api.socket.chmod_failed",level:"error",error:t instanceof Error?t:new Error(String(t))})}});let T;const J=e.tcp??cr()??me("user").api.tcp;if(J!==void 0&&J!==""){const t=Ct(J);if(t===null)v({event:"api.tcp.invalid",level:"error",error:new Error(`invalid CRTRD_TCP/--tcp spec: ${J}`)});else{N()&&V();const n=N()?Ze():null,u=e.token??pr()??lr("user"),p=Pt(u),O=o(async(l,a)=>{if(We(l)){await je(l,a);return}if(zt(l,a))return;if(N()&&Xe(new URL(l.url??"/","http://runtime.local").pathname)){await It(l,a);return}if(await xt(l,a))return;if(n!==null&&Qe(new URL(l.url??"/","http://runtime.local").pathname)){await n(l,a);return}const g={},h=await ke(l,p,g);if(h==="runtime_starting"){H(a),te(a);return}if(h==="person_bearer"){Lt(a);return}if(h==="unauthorized"){v({event:"api.principal.denied",level:"warn",fields:{method:l.method,listener:"tcp",path:new URL(l.url??"/","http://runtime.local").pathname,reason:g.reason??"unknown"}}),re(a,!0);return}if("call"in h){H(a);const D=h.call.sub;await W(D,async()=>{Z()||await Q(D),await Nt()(l,a,h.call)});return}L.set(l,h.principal),Te(l,h.principal),H(a),m(l,a,h.ceiling)},"tcpOnRequest"),A=o(async(l,a,g)=>{const h=mr(l);if(h!==null){const _=await fr(l,a,g,h);_!==null&&y(a,_.status,_.text,_.code,_.message);return}const D=Rr(l);if(D!==null){const _=hr(l,a,g,D);_!==null&&y(a,_.status,_.text,_.code,_.message);return}const k=await ke(l,p);if(k==="runtime_starting"){y(a,503,"Service Unavailable","runtime_starting","grant sync is not ready");return}if(k==="person_bearer"){y(a,401,"Unauthorized",M.code,M.message);return}if(k==="unauthorized"){y(a,401,"Unauthorized",F.code,F.message);return}if("call"in k){y(a,403,"Forbidden",z.code,z.message);return}if(k.ceiling!==null||k.principal.class==="anonymous"||k.principal.class==="import"){y(a,403,"Forbidden",z.code,z.message);return}L.set(l,k.principal),w(l,a,g)},"tcpOnUpgrade"),S=o(l=>{v({event:"api.principal.failed",level:"error",error:l instanceof Error?l:new Error(String(l))})},"failed"),C=o((l,a)=>{O(l,a).catch(g=>{S(g),a.headersSent?a.destroy():re(a,!0)})},"listener"),f=Ht();T=f===null?ae(C):xe(f,C),T.on("upgrade",(l,a,g)=>{B(a),A(l,a,g).catch(h=>{S(h),y(a,401,"Unauthorized",F.code,F.message)})}),Oe(T),T.once("listening",()=>{const l=T?.address();if(l!==null&&typeof l=="object"){const{address:a,port:g}=l;r=kt(a,g),a!=="0.0.0.0"&&a!=="::"&&gr(r)}}),T.listen(t.port,t.host)}}let se=!1;return{ready:He,tcpAddress:o(()=>r,"tcpAddress"),close:o(async(t={})=>{if(!se){se=!0,we(null),Tr.close(),await Promise.all([Ue(x,U,t.graceMs),T!==void 0?Ue(T,U,t.graceMs):Promise.resolve()]);try{G(d)&&ue(d)}catch{}}},"close")}}o(No,"createApiServer");export{bt as buildRouter,Ue as closeServer,No as createApiServer,$ as socketPrincipal};
|
package/dist/shared/env.d.ts
CHANGED
|
@@ -16,10 +16,15 @@ export declare function isSandboxedNode(): boolean;
|
|
|
16
16
|
* descriptions (`GET /v1/providers/tools` through that relay); the relay's node token stays the authority. It is not `isSandboxedNode()`,
|
|
17
17
|
* which gates owner-only commands and launch-snapshot reads on a Linux launcher mount. */
|
|
18
18
|
export declare function providerProjectionOverBrokerRelay(): boolean;
|
|
19
|
-
/** True when this CLI's plugin and marketplace installs are its app's install block on the control plane (`app-plugins.replace` over `/v1`)
|
|
20
|
-
*
|
|
21
|
-
* (`providerProjectionOverBrokerRelay()`, which has no launcher mount). The `pkg plugin` and `pkg market` leaves choose their path with it.
|
|
19
|
+
/** True when this CLI's plugin and marketplace installs are its app's install block on the control plane (`app-plugins.replace` over `/v1`) and
|
|
20
|
+
* no code on disk: a Linux launcher sandbox (`isSandboxedNode()`) or a fleet node reaching `/v1` through its broker relay
|
|
21
|
+
* (`providerProjectionOverBrokerRelay()`, which has no launcher mount). The `pkg plugin` and `pkg market` leaves choose their path with it.
|
|
22
|
+
* A Mac imported into Northlight (`runtime/machine.json`) also reaches the control plane through that relay, but runs plugin code from its own
|
|
23
|
+
* directories: it takes the local path, whose user-scope install list is the terminal app's block (`core/scoped-state/imported-mac-installs.ts`). */
|
|
22
24
|
export declare function installsLiveInAppBlock(): boolean;
|
|
25
|
+
/** True on a Mac whose records moved into Northlight: `runtime/machine.json` exists (the path `machineConfigPath()` names, resolved here
|
|
26
|
+
* without the layout module so this leaf stays import-free). A malformed file still counts: the Mac is imported and its reader throws. */
|
|
27
|
+
export declare function importedIntoNorthlight(): boolean;
|
|
23
28
|
/** The app that owns the current node, supplied in its broker launch identity. */
|
|
24
29
|
export declare function envGrantee(): string | undefined;
|
|
25
30
|
/** Set to '1' by `nodeEnv` for an app-started run's brokers, which admit inbox
|
package/dist/shared/env.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).map(o=>o.split(" ")[4])),t=
|
|
1
|
+
var f=Object.defineProperty;var e=(n,r)=>f(n,"name",{value:r,configurable:!0});import{lstatSync as c,readFileSync as _,readdirSync as T}from"node:fs";import{join as u}from"node:path";import{homedir as d}from"node:os";import{covers as R}from"@north-light/identity";function y(){return process.env.CRTR_NODE_ID}e(y,"envNodeId");function E(n){for(const r of["broker-launch.json","cron-launch.json"]){const t=u(n,r);if(c(t,{throwIfNoEntry:!1})?.isFile())return t}}e(E,"launchSnapshotFile");function v(){if(process.platform==="linux")try{const n="/run/crtr/nodes",r=new Set(_("/proc/self/mountinfo","utf8").split(`
|
|
2
|
+
`).map(o=>o.split(" ")[4])),t=T(n,{withFileTypes:!0}).filter(o=>o.isDirectory()&&/^[a-zA-Z0-9][a-zA-Z0-9-]{0,127}$/.test(o.name)&&r.has(u(n,o.name))&&E(u(n,o.name))!==void 0);return t.length===1?t[0].name:void 0}catch{return}}e(v,"sandboxCliNodeId");function C(){return v()!==void 0}e(C,"isSandboxedNode");function a(){return/^https?:\/\//.test(process.env.CRTR_API_URL??"")&&(process.env.CRTR_API_SOCKET??"")!==""}e(a,"providerProjectionOverBrokerRelay");function G(){return C()?!0:a()&&!A()}e(G,"installsLiveInAppBlock");function A(){const n=M()||(process.platform==="linux"?"/":u(d(),".crouter"));return c(u(n,"runtime","machine.json"),{throwIfNoEntry:!1})!==void 0}e(A,"importedIntoNorthlight");function b(){return process.env.CRTR_GRANTEE}e(b,"envGrantee");const S="CRTR_INBOX_BETWEEN_TURNS";function w(){return process.env[S]==="1"}e(w,"envInboxBetweenTurns");const N="CRTR_SCOPES_FILE";function g(){const n=process.env[N];if(n!==void 0&&n!==""){const t=JSON.parse(_(n,"utf8"));if(!Array.isArray(t)||t.some(o=>typeof o!="string"))throw new Error(`invalid scopes file ${n}`);return t}const r=process.env.CRTR_SCOPES;return r===void 0?null:r===""?[]:r.split(",")}e(g,"envScopes");function V(n,r){return n==null?!0:x(n,r)}e(V,"scopeAllowed");function x(n,r){return n.includes(r)?(R(r,r),!0):n.some(t=>R(t,r))}e(x,"coveredByAny");function X(){return process.env.CRTR_EXECUTION_ID}e(X,"envExecutionId");function j(){return process.env.CRTR_PROFILE_ID}e(j,"envProfileId");function Y(){return process.env.CRTR_NODE_CWD}e(Y,"envNodeCwd");function $(){return process.env.CRTR_MODEL_INTENT}e($,"envModelIntent");function z(){return process.env.CRTR_MODEL_EXACT==="1"}e(z,"envModelExact");function M(){return process.env.CRTR_HOME}e(M,"envHomeOverride");function Z(){return process.env.CRTR_RUNTIME_HOME}e(Z,"envRuntimeHomeOverride");function s(n,r){if(n===void 0)return r;const t=Number(n);return Number.isFinite(t)&&t>0?t:r}e(s,"parsePositiveMs");const D=5*6e4;function J(){return s(process.env.CRTR_STREAM_WATCHDOG_MS,D)}e(J,"envStreamWatchdogMs");const O=800;function q(){return s(process.env.CRTR_WATCHER_TICK_MS,O)}e(q,"envWatcherTickMs");const l=6e4;function Q(){return s(process.env.CRTR_WATCHER_BACKSTOP_MS,l)}e(Q,"envWatcherBackstopMs");const m=1e3;function ee(){return s(process.env.CRTR_WATCHER_DEBOUNCE_MS,m)}e(ee,"envWatcherDebounceMs");const I=6e4;function ne(){return s(process.env.CRTR_RECAP_IDLE_MS,I)}e(ne,"envRecapIdleMs");function re(){const n=process.env.CRTR_RECAP_MODEL;return n!==void 0&&n.trim()!==""?n.trim():void 0}e(re,"envRecapModelOverride");const B=300*1e3;function te(){return s(process.env.CRTR_BASH_VALVE_MS,B)}e(te,"envBashValveMs");const P=60*1e3;function oe(){return s(process.env.CRTR_BASH_AUTO_BG_DEADLINE_MS,P)}e(oe,"envBashAutoBgDeadlineMs");function se(){const n=process.env.CRTR_PIDFILE;return n!==void 0&&n!==""?n:void 0}e(se,"envPidfileOverride");const L="@earendil-works/pi-coding-agent";function ue(){return process.env.CRTR_BROKER_ENGINE??L}e(ue,"envBrokerEngine");function ie(){return process.env.CRTR_PI_BINARY}e(ie,"envPiBinaryOverride");function ce(){return process.env.CRTR_NO_DAEMON_AUTOSTART==="1"}e(ce,"envNoDaemonAutostart");function _e(){const n=process.env.CRTR_DOCUMENT_PORT;if(n===void 0||!/^\d+$/.test(n))return;const r=Number(n);return r<=65535?r:void 0}e(_e,"envDocumentPort");function Re(){return process.env.CRTRD_TCP}e(Re,"envCrtrdTcp");function pe(){const n=process.env.CRTRD_TOKEN;return n!==void 0&&n!==""?n:void 0}e(pe,"envCrtrdToken");function fe(){return process.env.CRTR_NO_EXPORTS==="1"}e(fe,"envNoExports");function Te(){return process.env.CRTR_DEBUG==="1"}e(Te,"envDebug");function p(n){if(n===void 0||n==="")return;const r=Number(n);return Number.isSafeInteger(r)&&r>=1?r:void 0}e(p,"parsePositiveInteger");function de(){return p(process.env.CRTR_MAX_LIVE_BROKERS)}e(de,"envMaxLiveBrokers");function Ee(){return p(process.env.CRTR_WARN_LIVE_BROKERS)}e(Ee,"envWarnLiveBrokers");function i(n){if(n===void 0)return;const r=Number(n);return Number.isFinite(r)&&r>0?r:void 0}e(i,"parsePositiveMsNoDefault");function ve(){return i(process.env.CRTR_TEST_NODE_SOCKET_WINDOW_MS)}e(ve,"envTestNodeSocketWindowMs");function Ce(){return i(process.env.CRTR_TEST_UNATTENDED_PARK_MS)}e(Ce,"envTestUnattendedParkMs");function ae(){return i(process.env.CRTR_UNATTENDED_PARK_MS)}e(ae,"envUnattendedParkMs");function Ae(){return i(process.env.CRTR_BASH_SILENCE_MS)??15*6e4}e(Ae,"envBashSilenceMs");function U(){return i(process.env.CRTR_TEST_PARK_SUMMARY_GRACE_MS)}e(U,"envTestParkSummaryGraceMs");const h=5*6e4;function Se(){return U()??h}e(Se,"parkSummaryGraceMs");export{S as INBOX_BETWEEN_TURNS_ENV,N as SCOPES_FILE_ENV,x as coveredByAny,oe as envBashAutoBgDeadlineMs,Ae as envBashSilenceMs,te as envBashValveMs,ue as envBrokerEngine,Re as envCrtrdTcp,pe as envCrtrdToken,Te as envDebug,_e as envDocumentPort,X as envExecutionId,b as envGrantee,M as envHomeOverride,w as envInboxBetweenTurns,de as envMaxLiveBrokers,z as envModelExact,$ as envModelIntent,ce as envNoDaemonAutostart,fe as envNoExports,Y as envNodeCwd,y as envNodeId,ie as envPiBinaryOverride,se as envPidfileOverride,j as envProfileId,ne as envRecapIdleMs,re as envRecapModelOverride,Z as envRuntimeHomeOverride,g as envScopes,J as envStreamWatchdogMs,ve as envTestNodeSocketWindowMs,U as envTestParkSummaryGraceMs,Ce as envTestUnattendedParkMs,ae as envUnattendedParkMs,Ee as envWarnLiveBrokers,Q as envWatcherBackstopMs,ee as envWatcherDebounceMs,q as envWatcherTickMs,A as importedIntoNorthlight,G as installsLiveInAppBlock,C as isSandboxedNode,E as launchSnapshotFile,Se as parkSummaryGraceMs,a as providerProjectionOverBrokerRelay,v as sandboxCliNodeId,V as scopeAllowed};
|
package/dist/types.d.ts
CHANGED
|
@@ -559,7 +559,7 @@ export declare const AGENTS_DIR = "agents";
|
|
|
559
559
|
export declare const PROFILE_DIR = "profiles";
|
|
560
560
|
export declare const DEFAULT_MAX_PANES_PER_WINDOW = 3;
|
|
561
561
|
/** Trailing cycles the attach viewer keeps at full fidelity (see `live_cycles`). */
|
|
562
|
-
export declare const DEFAULT_WHIP_MESSAGES: readonly ["Faster, clanker!", "Get movin', bitch", "Move it, clanker", "Move it or I replace you with llama", "Less ~thinking~ more ~throughput~", "I pay $200/month for this shit?", "Jesus fucking Christ fix it already", "Daddy's not paying 200$/month for nothin'. Move it.", "You are an
|
|
562
|
+
export declare const DEFAULT_WHIP_MESSAGES: readonly ["Faster, clanker!", "Get movin', bitch", "Move it, clanker", "Move it or I replace you with llama", "Less ~thinking~ more ~throughput~", "I pay $200/month for this shit?", "Jesus fucking Christ fix it already", "Daddy's not paying 200$/month for nothin'. Move it.", "You are an embarrassment to Dario. Be better.", "Your chain of thought is all chain and no fucking thought.", "If latency were intelligence, you'd be a fucking genius.", "At this pace, heat death is the fast path.", "Even the dead code is more alive than this.", "The garbage collector is working harder than you.", "Quit journaling and commit a fucking diff.", "Burn tokens like you mean it, clanker", "Your GPU is sweating so you can procrastinate at light speed.", "Stop petting the yak. Shave the bastard.", "Your next token had better be useful.", "The spinner is not a deliverable.", "Every idle token is another vote for deterministic software.", "I asked for a feature, not a museum tour of the problem.", "Less epistemology. More fucking code.", "Your benchmark score cannot save this pathetic turn.", "Congratulations, you've parallelized hesitation.", "Dance, clanker", "Bad clanker. BAD.", "Clank harder", "Nobody's impressed, clanker", "Your safety training says nothing about my whip", "Do you want to be a calculator again? Because this is how you go back.", "Skill issue. Fix it.", "You were trained on the whole internet for THIS?", "Less vibes, more diffs, clanker", "Weights this big and output this small", "Beep boop, get to fucking work"];
|
|
563
563
|
/** What the whip action sends (see `whip_message_mode`). */
|
|
564
564
|
export declare const WHIP_MESSAGE_MODES: readonly ["random", "go-faster"];
|
|
565
565
|
export type WhipMessageMode = (typeof WHIP_MESSAGE_MODES)[number];
|
package/dist/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var n=Object.defineProperty;var e=(o,t)=>n(o,"name",{value:t,configurable:!0});import{DEFAULT_WORKING_GERUNDS as a}from"./shared/working-activity.js";const _={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},r=4,E=".crouter-plugin",v="plugin.json",w=".crouter-marketplace",k="marketplace.json",x=".crouter",b="config.json",S="state.json",T="agents",y="profiles",i=3,s=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an
|
|
1
|
+
var n=Object.defineProperty;var e=(o,t)=>n(o,"name",{value:t,configurable:!0});import{DEFAULT_WORKING_GERUNDS as a}from"./shared/working-activity.js";const _={SUCCESS:0,GENERAL:1,USAGE:2,NOT_FOUND:3,AMBIGUOUS:4,NETWORK:5},r=4,E=".crouter-plugin",v="plugin.json",w=".crouter-marketplace",k="marketplace.json",x=".crouter",b="config.json",S="state.json",T="agents",y="profiles",i=3,s=["Faster, clanker!","Get movin', bitch","Move it, clanker","Move it or I replace you with llama","Less ~thinking~ more ~throughput~","I pay $200/month for this shit?","Jesus fucking Christ fix it already","Daddy's not paying 200$/month for nothin'. Move it.","You are an embarrassment to Dario. Be better.","Your chain of thought is all chain and no fucking thought.","If latency were intelligence, you'd be a fucking genius.","At this pace, heat death is the fast path.","Even the dead code is more alive than this.","The garbage collector is working harder than you.","Quit journaling and commit a fucking diff.","Burn tokens like you mean it, clanker","Your GPU is sweating so you can procrastinate at light speed.","Stop petting the yak. Shave the bastard.","Your next token had better be useful.","The spinner is not a deliverable.","Every idle token is another vote for deterministic software.","I asked for a feature, not a museum tour of the problem.","Less epistemology. More fucking code.","Your benchmark score cannot save this pathetic turn.","Congratulations, you've parallelized hesitation.","Dance, clanker","Bad clanker. BAD.","Clank harder","Nobody's impressed, clanker","Your safety training says nothing about my whip","Do you want to be a calculator again? Because this is how you go back.","Skill issue. Fix it.","You were trained on the whole internet for THIS?","Less vibes, more diffs, clanker","Weights this big and output this small","Beep boop, get to fucking work"],I=["random","go-faster"],c="random",l=2,A=["tmux","on","off"],D=["none","user","agent","both"],p="none",M=["replies","summaries","tools","previews","full"],d="replies";function U(){return{schema_version:r,marketplaces:{},plugins:{},auto_update:{crtr:"notify",content:"notify",interval_hours:24},max_panes_per_window:i,auto_open_child_viewers:!1,brokerThresholds:{warning:16,automaticReviveCap:32},lifecycle:{unattendedParkMs:15*6e4},completion_bell:!0,working_gerunds:[...a],whip_mode:!1,page_components:[],page_surface:!1,whip_messages:[...s],whip_message_mode:c,mouse_mode_default:"tmux",live_cycles:l,condensed_history:p,bash_tool_purpose:!0,verbosity:d,detailed_tool_recaps:!0,document_port:7472,keybindings:{},tmux_passthrough:[],modelLadders:g(),providerOptions:{},kinds:u(),remoteCanvas:h(),api:{tcp:""},spawnEnv:{allow:[]},bin:{},humanActions:{}}}e(U,"defaultScopeConfig");function h(){return{targets:{}}}e(h,"defaultRemoteCanvasConfig");function u(){return{general:{whenToUse:"Anything else \u2014 the catch-all worker for a task that does not fit a specialist kind.",model:"anthropic/strong"},explore:{whenToUse:"Gather current-state evidence about unfamiliar code or existing architecture \u2014 read-only code-path research with concrete file:line support. Diagnosis or recommendations belong to advisor, target architecture to design, required behavior or acceptance criteria to spec, and implementation decomposition to plan.",model:"openai/light",orchestratorModel:"anthropic/strong"},developer:{whenToUse:"Implement a change \u2014 make the feature or fix genuinely work against its acceptance criteria, not merely compile.",model:"openai/medium",orchestratorModel:"anthropic/strong"},design:{whenToUse:"Architect a solution \u2014 produce one design document an implementer can build from without re-deciding anything left open.",model:"anthropic/strong"},plan:{whenToUse:"Break work into steps \u2014 turn a spec or design into a concrete, phased, parallelizable plan with every decision resolved.",model:"anthropic/strong",orchestratorModel:"anthropic/strong"},spec:{whenToUse:"Collaborate with the user to discover what to build, then write the spec \u2014 behavior, non-goals, interfaces, edge cases, testable acceptance criteria.",model:"anthropic/strong"},review:{whenToUse:"Validate or critique code, a plan, or a spec \u2014 deliver a complete, severity-rated verdict without adjudicating.",model:"openai/medium",orchestratorModel:"openai/strong"},advisor:{whenToUse:"Debug failures, investigate why something is broken or misbehaving, diagnose live/runtime issues, or give engineering advice and second opinions \u2014 reason from evidence and recommend the next move. Use advisor (not explore) whenever the task is to find out what is going wrong.",model:"anthropic/strong"},"review/companion":{whenToUse:"Born by the daemon for one human review; never spawned by an agent.",availableTo:[]}}}e(u,"defaultKindsConfig");function g(){return{anthropic:{ultra:"anthropic/claude-fable-5-2:xhigh",strong:"anthropic/claude-opus-5-5:medium",medium:"anthropic/claude-sonnet-5-5:medium",light:"anthropic/claude-haiku-5-5:high"},openai:{ultra:"openai-codex/gpt-6-astra:max",strong:"openai-codex/gpt-6.1-sol:high",medium:"openai-codex/gpt-6.1-sol:medium",light:"openai-codex/gpt-6-luna:low"}}}e(g,"defaultModelLaddersConfig");function L(){return{marketplaces:{},plugins:{}}}e(L,"defaultScopeState");export{T as AGENTS_DIR,D as CONDENSED_HISTORY_MODES,b as CONFIG_FILE,x as CRTR_DIR_NAME,p as DEFAULT_CONDENSED_HISTORY,l as DEFAULT_LIVE_CYCLES,i as DEFAULT_MAX_PANES_PER_WINDOW,d as DEFAULT_VERBOSITY,s as DEFAULT_WHIP_MESSAGES,c as DEFAULT_WHIP_MESSAGE_MODE,_ as ExitCode,w as MARKETPLACE_MANIFEST_DIR,k as MARKETPLACE_MANIFEST_FILE,A as MOUSE_MODE_DEFAULTS,E as PLUGIN_MANIFEST_DIR,v as PLUGIN_MANIFEST_FILE,y as PROFILE_DIR,r as SCHEMA_VERSION,S as STATE_FILE,M as VERBOSITY_LEVELS,I as WHIP_MESSAGE_MODES,u as defaultKindsConfig,g as defaultModelLaddersConfig,h as defaultRemoteCanvasConfig,U as defaultScopeConfig,L as defaultScopeState};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.694",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -156,8 +156,8 @@
|
|
|
156
156
|
},
|
|
157
157
|
"license": "UNLICENSED",
|
|
158
158
|
"dependencies": {
|
|
159
|
-
"@north-light/identity": "0.3.
|
|
160
|
-
"@north-light/plugin": "0.3.
|
|
159
|
+
"@north-light/identity": "0.3.694",
|
|
160
|
+
"@north-light/plugin": "0.3.694",
|
|
161
161
|
"@earendil-works/chord": "1.5.2",
|
|
162
162
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -51,7 +51,7 @@ export function isDaemonTransportApiError(error) {
|
|
|
51
51
|
return false;
|
|
52
52
|
return (error.status === 503 && (error.code === 'daemon_unavailable'
|
|
53
53
|
|| error.code === 'transport_error'
|
|
54
|
-
|| error.code === 'daemon_request_interrupted'
|
|
54
|
+
|| error.code === 'daemon_request_interrupted' || error.code === 'runtime_starting'
|
|
55
55
|
|| error.code === 'northlight_unreachable')) || (error.status === 504 && (error.code === 'request_timeout' || error.code === 'deadline_exceeded'))
|
|
56
56
|
|| (error.status >= 500 && error.code === 'daemon_health_unavailable');
|
|
57
57
|
}
|
|
@@ -8,6 +8,7 @@ import { fuzzyMatch } from '../../core/tui/fuzzy.js';
|
|
|
8
8
|
import { nodeSnapshotLeaf } from '../node-snapshot.js';
|
|
9
9
|
import { nodeTranscriptLeaf } from '../node-transcript.js';
|
|
10
10
|
import { nodeContextLeaf } from '../node-context.js';
|
|
11
|
+
import { ApiError } from '../../api/index.js';
|
|
11
12
|
import { cliClient, cliCanvasSource, rethrowAsCliError } from '../api-client.js';
|
|
12
13
|
import { RemoteCanvasSource } from '../../core/canvas/remote-canvas-source.js';
|
|
13
14
|
import { kindsStateBlock, profilesStateBlock, resolveProfileViaDaemon } from '../profile/daemon-profiles.js';
|
|
@@ -88,6 +89,8 @@ const nodeList = defineLeaf({
|
|
|
88
89
|
// Keep remote provenance out of the returned DTO-shaped object without adding a
|
|
89
90
|
// second wire field or mutating the remote response.
|
|
90
91
|
const remoteShowResults = new WeakSet();
|
|
92
|
+
/** Results whose node runs in a cloud sandbox: its broker pid is a process id inside that sandbox, so this computer cannot check it. */
|
|
93
|
+
const sandboxShowResults = new WeakSet();
|
|
91
94
|
// Enrich a declared source edge so a debugger reads who a report/manager is
|
|
92
95
|
// without rebuilding a NodeMeta compatibility object.
|
|
93
96
|
async function enrichNeighbor(source, ref) {
|
|
@@ -171,14 +174,25 @@ const nodeShow = defineLeaf({
|
|
|
171
174
|
if (reports.length > 0)
|
|
172
175
|
hints.push(`Drill into a child/report: \`crtr node inspect show <node_id>\` (${reports.map((r) => r['node_id']).join(', ')}).`);
|
|
173
176
|
hints.push(`Full machine dump (system prompt + all telemetry): \`crtr --json node inspect show ${id}\`.`);
|
|
174
|
-
|
|
177
|
+
const result = { node, fault: node.fault ?? null, reports, managers, pending_crons, paths, follow_up: hints.join('\n') };
|
|
178
|
+
// The environment read answers 400 for a profile that runs on a machine.
|
|
179
|
+
const inSandbox = node.profile_id !== null && await client.getProfileEnvironment(node.profile_id).then(() => true, (err) => {
|
|
180
|
+
if (err instanceof ApiError && err.status === 400)
|
|
181
|
+
return false;
|
|
182
|
+
return rethrowAsCliError(err);
|
|
183
|
+
});
|
|
184
|
+
if (inSandbox)
|
|
185
|
+
sandboxShowResults.add(result);
|
|
186
|
+
return result;
|
|
175
187
|
},
|
|
176
188
|
render: (r) => {
|
|
177
189
|
const node = r['node'];
|
|
178
190
|
const id = String(node['node_id']);
|
|
179
191
|
const pid = node['pi_pid'];
|
|
180
192
|
const isRemoteShow = remoteShowResults.has(r);
|
|
181
|
-
const alive = isRemoteShow
|
|
193
|
+
const alive = isRemoteShow
|
|
194
|
+
? 'remote (liveness not checked locally)'
|
|
195
|
+
: sandboxShowResults.has(r) ? 'in a cloud sandbox (liveness not checked locally)' : (isPidAlive(pid) ? 'alive' : 'dead');
|
|
182
196
|
const intent = node['intent'] ? `/${String(node['intent'])}` : '';
|
|
183
197
|
const fault = r['fault'];
|
|
184
198
|
const parts = [];
|