@north-light/cli 0.3.645 → 0.3.646
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/clients/attach/viewer.js +315 -315
- package/dist/core/import/load/stores.d.ts +0 -1
- package/dist/core/import/load/stores.js +2 -2
- package/dist/core/layout.js +2 -2
- package/dist/core/runtime/blaxel-environment.d.ts +3 -0
- package/dist/core/runtime/blaxel-environment.js +1 -1
- package/dist/core/runtime/spawn.js +1 -1
- package/dist/core/runtime/unsandboxed.d.ts +1 -0
- package/dist/core/runtime/unsandboxed.js +1 -1
- package/dist/core/runtime/warm-pool.js +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -27,7 +27,6 @@ export interface StoreResult {
|
|
|
27
27
|
inserted: Record<string, string[][]>;
|
|
28
28
|
unresolvedPlugins: string[];
|
|
29
29
|
}
|
|
30
|
-
/** Must run inside the copy transaction (after the profile rows exist). */
|
|
31
30
|
export declare function writeStores(input: StoreInput): Promise<StoreResult>;
|
|
32
31
|
/** Record the copy's credentials with stable ids; any failure aborts the transaction that marks the verified import done. */
|
|
33
32
|
export declare function recordImportedActivations(db: CanvasDb, runId: string, person: string): Promise<void>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var C=Object.defineProperty;var
|
|
2
|
-
`),a]))}
|
|
1
|
+
var C=Object.defineProperty;var p=(n,r)=>C(n,"name",{value:r,configurable:!0});import{createHash as U}from"node:crypto";import{loadSecretsKey as N,open as j,seal as I}from"../../secrets/index.js";import{insertAccount as D,upsertModelCooldown as F}from"../../subscription-state.js";import{validateEnvVarName as x,isReservedEnvName as M}from"../../env-name.js";import{decodeKeys as V,encodeKeys as W}from"./copy.js";import{compareInstallOwners as K}from"../../scoped-state/migrate-app-installs.js";import{recordCredentialActivation as H}from"../../model-auth/activations.js";const P=["auth","credentials","env","settings","plugins"],b=p((n,r)=>`imports/${n}/stores/${r}.sealed`,"storeKey"),$=p((n,r)=>`import_store|${n}|${r}`,"aadOf");async function ae(n,r,c,o){if(o===null||typeof o!="object"||Array.isArray(o))throw new J(`the ${c} store must be a JSON object`);const{sealed:a,keyId:_}=I(JSON.stringify(o),N(),$(r,c));await n.put(b(r,c),Buffer.concat([Buffer.from(`${_}
|
|
2
|
+
`),a]))}p(ae,"putStore");class J extends Error{static{p(this,"StoreBodyError")}}async function S(n,r,c){const o=await n.get(b(r,c));if(o===null)return null;const a=o.indexOf(10);return JSON.parse(j(o.subarray(a+1),o.subarray(0,a).toString("utf8"),N(),$(r,c)))}p(S,"readStore");const re=p((n,r)=>S(n,r,"plugins"),"readPluginsStore"),B=p(n=>n.source_marketplace!=null,"hasFleetSource"),ne=p(n=>P.map(r=>b(n,r)),"allStoreKeys");function G(n){if(n===null||typeof n!="object"||Array.isArray(n))return n;const{runtime:r,api:c,...o}=n,a=o.paths;if(a!==null&&typeof a=="object"&&!Array.isArray(a)){const{user_files:_,...i}=a;Object.keys(i).length===0?delete o.paths:o.paths=i}return o}p(G,"withoutMachineSettings");async function oe(n){const{db:r,blobs:c,runId:o,person:a}=n,_=p(e=>n.objectMap.get(e)??e,"mapId"),i=p(e=>e.startsWith("profile:")?`profile:${_(e.slice(8))}`:e,"mapOwner"),f={},g=[],k=p((e,s)=>{(f[e]??=[]).push(s)},"record"),m=p(async(e,s,l,d)=>{await r.prepareUncached(`${s} ON CONFLICT DO NOTHING RETURNING 1 AS ok`).get(...l)!==void 0&&k(e,d)},"insert"),T=N(),A=new Date().toISOString(),E=await S(c,o,"credentials");if(E!==null){for(const e of E.accounts)if(await r.prepare("SELECT 1 FROM model_accounts WHERE person = ? AND provider_id = ? AND (id = ? OR label_key = ?)").get(a,e.provider,e.id,e.labelKey)===void 0){await D(r,a,e.provider,{providerId:e.provider,id:e.id,label:e.label,labelKey:e.labelKey,position:e.position,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},{refresh:e.refresh,access:e.access,expires:e.expires,...e.accountId?{accountId:e.accountId}:{},...e.clientId?{clientId:e.clientId}:{}}),k("model_accounts",[a,e.provider,e.id]);for(const l of e.cooldowns)await F(r,a,e.provider,e.id,l.family,l.until,l.at),k("model_account_cooldowns",[a,e.provider,e.id,l.family])}E.rotation!==void 0&&await m("model_settings","INSERT INTO model_settings (person, default_fallback_strength, revert_when_available) VALUES (?, ?, ?)",[a,E.rotation.defaultFallbackStrength,E.rotation.revertWhenAvailable===null?null:E.rotation.revertWhenAvailable?1:0],[a]),E.openaiDeviceId!==void 0&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(E.openaiDeviceId)&&await r.prepare("INSERT INTO model_settings (person, openai_device_id) VALUES (?, ?) ON CONFLICT (person) DO UPDATE SET openai_device_id = COALESCE(model_settings.openai_device_id, EXCLUDED.openai_device_id)").run(a,E.openaiDeviceId.toLowerCase())}const R=await S(c,o,"auth");if(R!==null)for(const[e,s]of Object.entries(R.apiKeys)){const{sealed:l,keyId:d}=I(JSON.stringify(s),T,`model_api_keys|${a}|${e}`);await m("model_api_keys","INSERT INTO model_api_keys (person, provider_id, credential_sealed, key_id, updated_at) VALUES (?, ?, ?, ?, ?)",[a,e,l,d,A],[a,e])}const L=await S(c,o,"env");if(L!==null)for(const[e,s]of Object.entries(L.profiles)){const l=_(e);for(const[d,t]of Object.entries(s)){if(!x(d).isValid||M(d)||typeof t!="string"||t.includes("\0"))continue;const{sealed:u,keyId:w}=I(t,T,`env_vars|${a}|profile|${l}|${d}`);await m("env_vars","INSERT INTO env_vars (person, owner_kind, owner_id, name, value_sealed, key_id, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,"profile",l,d,u,w,A],[a,"profile",l,d])}}const O=await S(c,o,"settings");if(O!==null){for(const[e,s]of Object.entries(O.settings))await m("scope_settings","INSERT INTO scope_settings (person, owner_key, raw_json) VALUES (?, ?, ?)",[a,i(e),JSON.stringify(G(s))],[a,i(e)]);for(const[e,s]of Object.entries(O.state))await m("scope_bookkeeping","INSERT INTO scope_bookkeeping (person, owner_key, last_self_check, active_canvas) VALUES (?, ?, ?, ?)",[a,i(e),s.last_self_check??null,s.activeCanvas??null],[a,i(e)]);for(const[e,s]of Object.entries(O.profileProjects)){const l=_(e);if(await r.prepare("SELECT 1 FROM profile_projects WHERE profile_id = ?").get(l)!==void 0)continue;let d=0;for(const t of s)await m("profile_projects","INSERT INTO profile_projects (profile_id, path, position) VALUES (?, ?, ?)",[l,t,d++],[l,t])}for(const[e,s]of Object.entries(O.defaults))await m("profile_defaults","INSERT INTO profile_defaults (person, directory, profile_id) VALUES (?, ?, ?)",[a,e,_(s)],[a,e])}const h=await S(c,o,"plugins");if(h!==null){const e=p(async t=>{if(t.startsWith("app:"))return t;if(t==="user")return"app:terminal";if(!t.startsWith("profile:"))throw new Error(`unsupported install owner in the bundle: ${t}`);return(await r.prepare("SELECT grantee FROM profiles WHERE id = ?").get(_(t.slice(8))))?.grantee??"app:terminal"},"appOf"),s=new Map;for(const t of new Set([...h.marketplaces,...h.plugins].map(u=>u.owner)))t.startsWith("profile:")&&s.set(t,(await r.prepare("SELECT last_used_at FROM profiles WHERE id = ?").get(_(t.slice(8))))?.last_used_at??"");const l=p(t=>[...t].sort((u,w)=>K(i(u.owner),s.get(u.owner)??"",i(w.owner),s.get(w.owner)??"")),"byProfileFirst"),d=new Map;for(const t of l(h.marketplaces)){const u=await e(t.owner),w=new Map((await r.prepare("SELECT name, url FROM scope_marketplaces WHERE person = ? AND owner_key = ?").all(a,u)).map(v=>[v.name,v.url]));let y=t.name;for(let v=2;w.has(y)&&w.get(y)!==(t.url??null);v+=1)y=`${t.name}-${v}`;d.set(`${t.owner}\0${t.name}`,y),await m("scope_marketplaces","INSERT INTO scope_marketplaces (person, owner_key, name, last_updated, url, ref, installed_at) VALUES (?, ?, ?, ?, ?, ?, ?)",[a,u,y,t.last_updated??null,t.url??null,t.ref??null,t.installed_at??null],[a,u,y])}for(const t of l(h.plugins)){if(!B(t)){g.push(`${t.owner}:${t.name}`);continue}const u=await e(t.owner),w=t.source_marketplace==null?null:d.get(`${t.owner}\0${t.source_marketplace}`)??t.source_marketplace;await m("scope_plugins","INSERT INTO scope_plugins (person, owner_key, name, last_updated, etag, checked_at, enabled, source_marketplace, version, source_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",[a,u,t.name,t.last_updated??null,t.etag??null,t.checked_at??null,t.enabled?1:0,w,t.version??null,t.source_path??null],[a,u,t.name])}(f.scope_plugins??[]).length+(f.scope_marketplaces??[]).length>0&&await m("person_settings","INSERT INTO person_settings (person, plugins_revision) VALUES (?, 1)",[a],[a])}for(const[e,s]of Object.entries(f))await r.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?) ON CONFLICT (run_id, table_name) DO UPDATE SET inserted_keys = EXCLUDED.inserted_keys").run(o,e,W(s));return Object.keys(f).length>0&&await r.prepare("SELECT pg_notify('crtr_signal', ?)").get(`settings:${a}`),{inserted:f,unresolvedPlugins:g}}p(oe,"writeStores");async function se(n,r,c){const o=await n.prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? AND table_name IN ('model_accounts', 'model_api_keys')").all(r),a=p(i=>o.filter(f=>f.table_name===i).flatMap(f=>V(f.inserted_keys)),"keys"),_=[...[...new Set(a("model_accounts").map(i=>i[1]))].map(i=>({kind:"subscription",provider:i})),...a("model_api_keys").map(i=>({kind:"api_key",provider:i[1]}))];for(const{kind:i,provider:f}of _){const g=U("sha256").update(JSON.stringify([r,i,f])).digest("hex"),k=`${g.slice(0,8)}-${g.slice(8,12)}-4${g.slice(13,16)}-8${g.slice(17,20)}-${g.slice(20,32)}`;await H(c,i,f,k)}}p(se,"recordImportedActivations");export{P as STORE_NAMES,J as StoreBodyError,ne as allStoreKeys,B as hasFleetSource,ae as putStore,re as readPluginsStore,se as recordImportedActivations,b as storeKey,oe as writeStores};
|
package/dist/core/layout.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var $=Object.defineProperty;var n=(r
|
|
2
|
-
`,384)}n(
|
|
1
|
+
var $=Object.defineProperty;var n=(o,r)=>$(o,"name",{value:r,configurable:!0});import{existsSync as i,mkdirSync as d,readFileSync as R,statSync as S}from"node:fs";import{homedir as g,userInfo as _}from"node:os";import{basename as x,dirname as f,isAbsolute as A,join as t,resolve as p}from"node:path";import{envHomeOverride as T}from"../shared/env.js";import{readConfig as C}from"./config.js";import{isCloudRole as O}from"./canvas/person-state.js";import{publishFileExclusive as z,syncDirectory as h}from"./fs-utils.js";const l="1";function s(){const o=p(T()||(process.platform==="linux"?"/":t(g(),".crouter")));if(L()&&o===k())throw new Error(`refusing to use the account's real crouter root ${o} from a node --test process; point CRTR_HOME (not only HOME) at a temporary directory`);return o}n(s,"layoutRoot");function L(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}n(L,"runningUnderNodeTest");let c;function k(){if(c===void 0)try{c=p(_().homedir,".crouter")}catch{c=null}return c}n(k,"accountLayoutRoot");function u(){return t(s(),"runtime")}n(u,"runtimeRoot");function v(){return t(s(),"user")}n(v,"userRoot");function w(){return t(s(),"apps")}n(w,"appsRoot");function y(){return t(u(),"secrets")}n(y,"secretsDir");function P(o,r){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(r))throw new Error(`invalid profile id: ${r}`);const e=m(o);return{dir:t(e.profiles,r),env:t(y(),"env",x(e.root),r),home:e.home}}n(P,"profileSpace");function E(){return process.platform==="linux"?"/run/crtr":u()}n(E,"socketDir");function a(){return t(u(),"layout")}n(a,"layoutVersionFile");function F(){const r=(O()?void 0:C("user").paths?.user_files)??(process.platform==="linux"?t(v(),"files"):f(s()));if(!A(r))throw new Error("paths.user_files must be absolute");return p(r)}n(F,"userFilesRoot");function m(o){const r=o.startsWith("app:")?o.slice(4):o;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(r)||r==="."||r==="..")throw new Error(`invalid app id: ${o}`);const e=t(w(),r);return{root:e,profiles:t(e,"profiles"),conversations:t(e,"conversations"),nodes:t(e,"nodes"),files:t(e,"files"),home:t(e,"home"),cache:t(e,"cache")}}n(m,"appSpace");function W(o,r){if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(r))throw new Error(`invalid cron id: ${r}`);return t(m(o).root,"crons",r)}n(W,"cronFolder");function X(o){const r=m(o);return process.platform==="linux"?r.home:x(r.root)==="terminal"?F():r.home}n(X,"appProcessHome");function M(o){const r=Array.from(o.subarray(0,32),e=>e===92?"\\\\":e===34?'\\"':e===10?"\\n":e===13?"\\r":e===9?"\\t":e>=32&&e<127?String.fromCharCode(e):`\\x${e.toString(16).padStart(2,"0")}`).join("");return`${o.length} bytes, preview "${r}"${o.length>32?"\u2026":""}`}n(M,"describeLayoutMarker");function N(o){const r=R(o);if(r.toString("utf8").trim()!==l)throw new Error(`unsupported runtime layout version: ${o} holds ${M(r)}; expected "${l}"`)}n(N,"assertSupportedLayoutMarker");function D(){if(process.env.CRTR_LAYOUT_REFUSE==="1")return!0;if(i(a()))return N(a()),!1;const o=s(),r=process.platform==="linux"&&o==="/"&&i("/volume")?"/volume":o;return i(t(r,"canvas"))||i(t(r,"canvas.db"))?!0:i(t(u(),"canvas.db"))}n(D,"layoutNeedsMigration");function B(){if(D())throw new Error("layout_migration_required");for(const o of[u(),v(),w(),y()]){const r=d(o,{recursive:!0,mode:448});if(r!==void 0){for(let e=o;h(e),e!==r;e=f(e));h(f(r))}}if(d(E(),{recursive:!0,mode:493}),process.platform==="linux"&&(S(E()).mode&511)!==493)throw new Error("launcher socket directory must be mode 0755");i(a())||z(a(),`${l}
|
|
2
|
+
`,384)}n(B,"initializeEmptyLayout");export{l as LAYOUT_VERSION,X as appProcessHome,m as appSpace,w as appsRoot,N as assertSupportedLayoutMarker,W as cronFolder,M as describeLayoutMarker,B as initializeEmptyLayout,D as layoutNeedsMigration,s as layoutRoot,a as layoutVersionFile,P as profileSpace,u as runtimeRoot,y as secretsDir,E as socketDir,F as userFilesRoot,v as userRoot};
|
|
@@ -1,2 +1,5 @@
|
|
|
1
1
|
/** The Blaxel environment the node's profile points at, or null when it runs on a machine. Reads rows only, so it is safe before any environment is registered. A leaf module: the launch and run-start paths import it without pulling in the ledger. */
|
|
2
2
|
export declare function blaxelEnvironmentOf(profileId: string | null): Promise<string | null>;
|
|
3
|
+
/** The environment that runs the node off this process — a Blaxel environment, or on a cloud role a remote machine (an imported Mac) — or
|
|
4
|
+
* null when it launches here. Birth and the warm pool read it: such a node is born dormant and `reviveNode` picks the runner. */
|
|
5
|
+
export declare function remoteEnvironmentOf(profileId: string | null): Promise<string | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var o=Object.defineProperty;var
|
|
1
|
+
var o=Object.defineProperty;var e=(n,t)=>o(n,"name",{value:t,configurable:!0});import{openDb as r}from"../canvas/db.js";import{isCloudRole as i}from"../canvas/person-state.js";import{machineEnvironmentOfProfile as l}from"./runner/machine/environment.js";async function a(n){return n===null?null:(await(await r()).prepare("SELECT e.object AS object FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ? AND e.kind = 'blaxel'").get(n))?.object??null}e(a,"blaxelEnvironmentOf");async function p(n){return n===null?null:await a(n)??(i()?await l(n):null)}e(p,"remoteEnvironmentOf");export{a as blaxelEnvironmentOf,p as remoteEnvironmentOf};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var me=Object.defineProperty;var d=(e,o)=>me(e,"name",{value:o,configurable:!0});import{accessSync as he,constants as pe}from"node:fs";import{isAbsolute as _e,resolve as ke,join as ve}from"node:path";import{appSpace as ge}from"../layout.js";import{ApiError as ne}from"../../api/errors.js";import{spawnNode as ye,forkSourceNode as be,currentNodeContext as xe,rootOfSpine as $e,newNodeId as Se,preflightNodeId as Ce}from"./nodes.js";import{resolveProfileOperand as Ee}from"../profiles/manifest.js";import{selectProfileForCwd as Re,selectProfileForCwdReadOnly as Oe}from"../profiles/select.js";import{buildLaunchSpecAsync as oe,buildPiArgv as Ie}from"./launch.js";import{runsOnBlaxel as Fe,sandboxWorktreeRequest as Pe}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Be,rollbackManagedWorktreeAsync as De}from"../worktree-mutation-async.js";import{usage as w,brokerLaunchFailed as D}from"../errors.js";import{writeGoal as Ne}from"./kickoff.js";import{appendSituationalContext as Le,formatSituationalProse as Me}from"./situational-context.js";import{ensureRoadmap as Te}from"./roadmap.js";import{buildWakeBearings as Ae}from"./bearings.js";import{encodeKickoffOrigin as We,KICKOFF_ORIGIN_ENV as je}from"./stamp/protocol.js";import{carryInitialInput as ze}from"../runs/initial-input.js";import{ExecutionCapReached as He,beginExecution as Ke,crtrHome as Ge,getNode as u,fullName as re,jobDir as Ue,recordExecutionPid as Ve,abortExecution as j,setFrozen as z}from"../canvas/index.js";import{contextDir as H,nodeAgentDir as K}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as Xe}from"../spaces/open-beneath.js";import{conversationIdFromPath as N,conversationStore as S}from"../conversation-store/index.js";import{appMemoryTooSmall as qe,boundFleet as Ye,brokerThresholdsForDaemon as te}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{emitEvent as L}from"../events/emit.js";import{blaxelEnvironmentOf as Qe}from"./blaxel-environment.js";import{openViewerWindow as Ze,focusOf as en,windowOfPane as nn}from"./placement.js";import{awaitBrokerViewSocket as on}from"./view-socket.js";import{readLogSnapshot as rn}from"../events/read.js";import{transition as v}from"./lifecycle.js";import{beginBootFaultAttempt as tn}from"../canvas/recovery.js";import{headlessBrokerHost as G}from"./host.js";import{ensureDaemon as an}from"../../daemon/manage.js";import{readConfig as dn}from"../config.js";import{modelRequestFromConfig as sn,unregisteredConcreteModel as ln,unroutableConcreteModel as cn}from"../model-routes.js";import{openModelRegistry as un}from"./model-registry.js";import{MODEL_SPEC_NEXT as fn}from"./model-selection.js";import{forkNodeLedger as wn}from"./ledger.js";import{appRungForGrant as mn}from"../llm/app-rungs.js";import{APP_FAMILY as U}from"../model-routes.js";import{discoverLifecycleHookRegistry as hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as pn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as _n}from"../async-array.js";import{checkStart as kn}from"./start-check.js";function g(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}d(g,"launchFailureOutcome");async function vn(e,o,a){try{return await G.launch(e,o,a)}catch(r){try{await v(e,"crash",{reason:"launch_failed",outcome:g(r)})}catch{}const t=r.message;throw D(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}d(vn,"launchBrokerOrCrash");function gn(e){return rn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}d(gn,"lastStartupStep");function yn(e,o){const a=gn(e),r=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(o.reason==="exited"){const{code:t,signal:s}=o.status;return{text:`exited (code ${t??"null"}, signal ${s??"null"}) before binding its view socket; ${r}`,fields:{reason:"exited",code:t,signal:s,last_startup_step:a}}}return{text:`was still starting after ${Math.round(o.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${r}`,fields:{reason:"timeout",waited_ms:o.waitedMs,last_startup_step:a}}}d(yn,"notReadyDescription");async function bn(e,o){try{await v(e,"crash",{reason:"launch_failed",outcome:g(o)})}catch{}try{G.teardown(e)}catch{}}d(bn,"crashAndTearDown");async function xn(e){const o=(await S().list()).map(({conversation_id:t,path:s})=>({id:t,path:s})),a=o.filter(t=>t.id===e),r=a.length>0?a:o.filter(t=>t.id.startsWith(e));if(r.length===0)throw w(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(r.length>1)throw w(`--fork-from '${e}': ambiguous \u2014 ${r.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return r[0].path}d(xn,"resolveSessionUuid");async function ie(e){const o=e.trim();if(o==="")throw w("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(o.includes("/")||o.endsWith(".jsonl")){const r=N(_e(o)?o:ke(process.cwd(),o));if(r===null)throw w(`--fork-from '${o}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await S().header(r)).path}const a=await u(o);if(a!==null){const r=a.pi_session_file;if(r==null||r==="")throw w(`node ${o} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=N(r);if(t===null)throw w(`node ${o} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await S().header(t)).path}return await xn(o)}d(ie,"resolveForkSource");async function $n(e,o,a,r={}){return e===null?null:e!==void 0&&e!==""?Ee(e).profileId:o!==null?(await u(o))?.profile_id??null:r.readOnlySelection===!0?Oe(a):Re(a)}d($n,"resolveProfileId");function ae(e){const o=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return sn(e.model,o,e.modelExact===!0)}d(ae,"requestFromLaunch");async function de(e,o,a){const r=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await mn(o,r,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:s,...l}=e.env??{};return{...e,model:t.model,modelIntent:{family:U,strength:t.strength},modelExact:void 0,env:{...l,CRTR_MODEL_INTENT:`${U}/${t.strength}`}}}d(de,"appPaidLaunch");async function se(e,o,a){if(e===void 0||e.kind==="logical"&&e.family!==U)return;const r=await ln(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await un(),o);if(r!==void 0)throw w(`model '${r.request.spec}' is not registered in this daemon.`,{received:r.request.spec,next:fn});const t=await cn(e,o);if(t!==void 0)throw w(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}d(se,"assertLaunchModelRegistered");function Sn(e,o,a){const r=e??o??null;if(!a&&r===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return r}d(Sn,"resolveSpawner");async function le(e,o,a){try{an()}catch{}const r=xe(),t=e.root===!0,s=Sn(e.parent,r.nodeId??null,t),l=e.mode??"base",y=e.rootLifecycle??(t?"resident":"terminal"),ce=t&&y==="resident",R=s===null?null:await u(s),V=e.creator===void 0||e.creator===null?null:await u(e.creator);e.nodeId!==void 0&&await Ce(e.nodeId);const b=e.forkFrom!==void 0?await ie(e.forkFrom):void 0,M=b===void 0?null:await be(b),T=await _n([R,V,M],async f=>f?.isolated===!0||f?.run_id!=null&&(await u(f.run_id))?.isolated===!0);if(T&&e.isolated===!1)throw new ne(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const O=T||e.isolated===!0;if(O&&e.worktree===!0)throw new ne(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});const C=e.worktree===!0,m=O||C?e.nodeId??await Se():e.nodeId,I=O?e.run!==void 0&&t&&!T?e.cwd:ve(ge(e.run?.grantee??R?.grantee??"app:terminal").nodes,m):e.cwd,h=await $n(e.profile,s,I),X=e.run?.grant_id??R?.grant_id??null,E=e.run??V??R??M,q=await de((await oe(e.kind,l,{lifecycle:y,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:I,profileId:h,app:E?.grantee??"app:terminal"})).launch,X,e.model);await se(ae(q),{cwd:I,profileId:h}),await kn({grantee:E?.grantee??"app:terminal",sub:E?.sub,grant_id:E?.grant_id});const Y=M?.node_id??null;let x,F=I;const A=C&&await Fe(h)?await Pe(h,e.worktreeCwd??e.cwd,m,e.worktreeBase):void 0;try{C&&A===void 0&&(x=await Be(e.worktreeCwd??e.cwd,m,e.worktreeBase),F=x.path);const f=C?await de((await oe(e.kind,l,{lifecycle:y,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:F,profileId:h,app:E?.grantee??"app:terminal"})).launch,X,e.model):q;A!==void 0&&(f.worktree=A),C&&await se(ae(f),{cwd:F,profileId:h});const n=await ye({kind:e.kind,mode:l,lifecycle:y,cwd:F,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:Y,spawnedBy:t?s??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:O,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:b,modelOverride:e.model===void 0?void 0:f.model,...x!==void 0?{managedWorktree:x}:{},...m!==void 0?{nodeId:m}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await wn(n.node_id,Y??null)}catch(i){throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}if(await Ne(n.node_id,e.prompt),e.situationalContext!==void 0&&await Le(n.node_id,Me(e.situationalContext)),o!==void 0)try{o(n.node_id)}catch(i){throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}const W=e.prompt!=="",ue=`${W&&e.wakeOrigin!==void 0?`${Ae(e.wakeOrigin)}
|
|
1
|
+
var me=Object.defineProperty;var d=(e,o)=>me(e,"name",{value:o,configurable:!0});import{accessSync as he,constants as pe}from"node:fs";import{isAbsolute as _e,resolve as ke,join as ve}from"node:path";import{appSpace as ge}from"../layout.js";import{ApiError as ne}from"../../api/errors.js";import{spawnNode as ye,forkSourceNode as be,currentNodeContext as xe,rootOfSpine as $e,newNodeId as Se,preflightNodeId as Ce}from"./nodes.js";import{resolveProfileOperand as Ee}from"../profiles/manifest.js";import{selectProfileForCwd as Re,selectProfileForCwdReadOnly as Oe}from"../profiles/select.js";import{buildLaunchSpecAsync as oe,buildPiArgv as Ie}from"./launch.js";import{runsOnBlaxel as Fe,sandboxWorktreeRequest as Pe}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Be,rollbackManagedWorktreeAsync as De}from"../worktree-mutation-async.js";import{usage as w,brokerLaunchFailed as D}from"../errors.js";import{writeGoal as Ne}from"./kickoff.js";import{appendSituationalContext as Le,formatSituationalProse as Me}from"./situational-context.js";import{ensureRoadmap as Te}from"./roadmap.js";import{buildWakeBearings as Ae}from"./bearings.js";import{encodeKickoffOrigin as We,KICKOFF_ORIGIN_ENV as je}from"./stamp/protocol.js";import{carryInitialInput as ze}from"../runs/initial-input.js";import{ExecutionCapReached as He,beginExecution as Ke,crtrHome as Ge,getNode as u,fullName as re,jobDir as Ue,recordExecutionPid as Ve,abortExecution as j,setFrozen as z}from"../canvas/index.js";import{contextDir as H,nodeAgentDir as K}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as Xe}from"../spaces/open-beneath.js";import{conversationIdFromPath as N,conversationStore as S}from"../conversation-store/index.js";import{appMemoryTooSmall as qe,boundFleet as Ye,brokerThresholdsForDaemon as te}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{emitEvent as L}from"../events/emit.js";import{remoteEnvironmentOf as Qe}from"./blaxel-environment.js";import{openViewerWindow as Ze,focusOf as en,windowOfPane as nn}from"./placement.js";import{awaitBrokerViewSocket as on}from"./view-socket.js";import{readLogSnapshot as rn}from"../events/read.js";import{transition as v}from"./lifecycle.js";import{beginBootFaultAttempt as tn}from"../canvas/recovery.js";import{headlessBrokerHost as G}from"./host.js";import{ensureDaemon as an}from"../../daemon/manage.js";import{readConfig as dn}from"../config.js";import{modelRequestFromConfig as sn,unregisteredConcreteModel as ln,unroutableConcreteModel as cn}from"../model-routes.js";import{openModelRegistry as un}from"./model-registry.js";import{MODEL_SPEC_NEXT as fn}from"./model-selection.js";import{forkNodeLedger as wn}from"./ledger.js";import{appRungForGrant as mn}from"../llm/app-rungs.js";import{APP_FAMILY as U}from"../model-routes.js";import{discoverLifecycleHookRegistry as hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as pn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as _n}from"../async-array.js";import{checkStart as kn}from"./start-check.js";function g(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}d(g,"launchFailureOutcome");async function vn(e,o,a){try{return await G.launch(e,o,a)}catch(r){try{await v(e,"crash",{reason:"launch_failed",outcome:g(r)})}catch{}const t=r.message;throw D(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}d(vn,"launchBrokerOrCrash");function gn(e){return rn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}d(gn,"lastStartupStep");function yn(e,o){const a=gn(e),r=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(o.reason==="exited"){const{code:t,signal:s}=o.status;return{text:`exited (code ${t??"null"}, signal ${s??"null"}) before binding its view socket; ${r}`,fields:{reason:"exited",code:t,signal:s,last_startup_step:a}}}return{text:`was still starting after ${Math.round(o.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${r}`,fields:{reason:"timeout",waited_ms:o.waitedMs,last_startup_step:a}}}d(yn,"notReadyDescription");async function bn(e,o){try{await v(e,"crash",{reason:"launch_failed",outcome:g(o)})}catch{}try{G.teardown(e)}catch{}}d(bn,"crashAndTearDown");async function xn(e){const o=(await S().list()).map(({conversation_id:t,path:s})=>({id:t,path:s})),a=o.filter(t=>t.id===e),r=a.length>0?a:o.filter(t=>t.id.startsWith(e));if(r.length===0)throw w(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(r.length>1)throw w(`--fork-from '${e}': ambiguous \u2014 ${r.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return r[0].path}d(xn,"resolveSessionUuid");async function ie(e){const o=e.trim();if(o==="")throw w("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(o.includes("/")||o.endsWith(".jsonl")){const r=N(_e(o)?o:ke(process.cwd(),o));if(r===null)throw w(`--fork-from '${o}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await S().header(r)).path}const a=await u(o);if(a!==null){const r=a.pi_session_file;if(r==null||r==="")throw w(`node ${o} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=N(r);if(t===null)throw w(`node ${o} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await S().header(t)).path}return await xn(o)}d(ie,"resolveForkSource");async function $n(e,o,a,r={}){return e===null?null:e!==void 0&&e!==""?Ee(e).profileId:o!==null?(await u(o))?.profile_id??null:r.readOnlySelection===!0?Oe(a):Re(a)}d($n,"resolveProfileId");function ae(e){const o=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return sn(e.model,o,e.modelExact===!0)}d(ae,"requestFromLaunch");async function de(e,o,a){const r=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await mn(o,r,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:s,...l}=e.env??{};return{...e,model:t.model,modelIntent:{family:U,strength:t.strength},modelExact:void 0,env:{...l,CRTR_MODEL_INTENT:`${U}/${t.strength}`}}}d(de,"appPaidLaunch");async function se(e,o,a){if(e===void 0||e.kind==="logical"&&e.family!==U)return;const r=await ln(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await un(),o);if(r!==void 0)throw w(`model '${r.request.spec}' is not registered in this daemon.`,{received:r.request.spec,next:fn});const t=await cn(e,o);if(t!==void 0)throw w(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}d(se,"assertLaunchModelRegistered");function Sn(e,o,a){const r=e??o??null;if(!a&&r===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return r}d(Sn,"resolveSpawner");async function le(e,o,a){try{an()}catch{}const r=xe(),t=e.root===!0,s=Sn(e.parent,r.nodeId??null,t),l=e.mode??"base",y=e.rootLifecycle??(t?"resident":"terminal"),ce=t&&y==="resident",R=s===null?null:await u(s),V=e.creator===void 0||e.creator===null?null:await u(e.creator);e.nodeId!==void 0&&await Ce(e.nodeId);const b=e.forkFrom!==void 0?await ie(e.forkFrom):void 0,M=b===void 0?null:await be(b),T=await _n([R,V,M],async f=>f?.isolated===!0||f?.run_id!=null&&(await u(f.run_id))?.isolated===!0);if(T&&e.isolated===!1)throw new ne(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const O=T||e.isolated===!0;if(O&&e.worktree===!0)throw new ne(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});const C=e.worktree===!0,m=O||C?e.nodeId??await Se():e.nodeId,I=O?e.run!==void 0&&t&&!T?e.cwd:ve(ge(e.run?.grantee??R?.grantee??"app:terminal").nodes,m):e.cwd,h=await $n(e.profile,s,I),X=e.run?.grant_id??R?.grant_id??null,E=e.run??V??R??M,q=await de((await oe(e.kind,l,{lifecycle:y,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:I,profileId:h,app:E?.grantee??"app:terminal"})).launch,X,e.model);await se(ae(q),{cwd:I,profileId:h}),await kn({grantee:E?.grantee??"app:terminal",sub:E?.sub,grant_id:E?.grant_id});const Y=M?.node_id??null;let x,F=I;const A=C&&await Fe(h)?await Pe(h,e.worktreeCwd??e.cwd,m,e.worktreeBase):void 0;try{C&&A===void 0&&(x=await Be(e.worktreeCwd??e.cwd,m,e.worktreeBase),F=x.path);const f=C?await de((await oe(e.kind,l,{lifecycle:y,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:F,profileId:h,app:E?.grantee??"app:terminal"})).launch,X,e.model):q;A!==void 0&&(f.worktree=A),C&&await se(ae(f),{cwd:F,profileId:h});const n=await ye({kind:e.kind,mode:l,lifecycle:y,cwd:F,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:Y,spawnedBy:t?s??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:O,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:b,modelOverride:e.model===void 0?void 0:f.model,...x!==void 0?{managedWorktree:x}:{},...m!==void 0?{nodeId:m}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await wn(n.node_id,Y??null)}catch(i){throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}if(await Ne(n.node_id,e.prompt),e.situationalContext!==void 0&&await Le(n.node_id,Me(e.situationalContext)),o!==void 0)try{o(n.node_id)}catch(i){throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}const W=e.prompt!=="",ue=`${W&&e.wakeOrigin!==void 0?`${Ae(e.wakeOrigin)}
|
|
2
2
|
|
|
3
3
|
`:""}${e.prompt}`;l==="orchestrator"&&await Te(n.node_id,{goal:e.prompt.trim()}),await Cn(n);let J;if(b!==void 0)try{const i=N(b);if(i===null)throw new Error(`invalid fork source ${b}`);const c=await S().fork(i,n.node_id);J=(await S().header(c)).path}catch(i){throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}const p=Ie(n,{prompt:ue,resumeSessionPath:J});if(p.env={...p.env,CRTR_SUBTREE:await $e(n.node_id)},W){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};p.env[je]=We(i),await ze(p,n)}const _=Ye();if(await Qe(n.profile_id??null)!==null)return await z(n.node_id,new Date().toISOString()),L({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const Q=await _.reserveSlot(n.node_id),k=Q?await Je(n.node_id):null;if(k?.verdict==="too_small"){_.releaseReservation(n.node_id);const i=qe(k);throw await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),i}if(!Q||k?.verdict==="denied")return k?.verdict==="denied"&&_.releaseReservation(n.node_id),await z(n.node_id,new Date().toISOString()),L({level:"info",event:"broker.frozen",node_id:n.node_id,fields:k?.verdict==="denied"?{reason:"app_memory",free_bytes:k.free_bytes,needed_bytes:k.needed_bytes}:{reason:"broker_cap",live_count:await _.occupancy(),hard_cap:te().automaticReviveCap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const fe=await tn(n.node_id),{automaticReviveCap:we}=te();let $;try{$=await Ke(n.node_id,{daemonEpoch:_.epoch(),cap:we})}catch(i){if(!(i instanceof He))throw i;return _.releaseReservation(n.node_id),await z(n.node_id,new Date().toISOString()),L({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null}}p.env={...p.env,CRTR_EXECUTION_ID:$};let P;try{P=await vn(n.node_id,p,{cwd:n.cwd,name:re(n),resuming:!1})}catch(i){throw await j($,{reason:"launch_failed"}),i}finally{_.releaseReservation(n.node_id)}if(P.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await j($,{reason:"launch_failed"}),await v(n.node_id,"crash",{reason:"launch_failed",outcome:g(i)}),D(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await Ve($,n.node_id,P.pid)==="shutdown")throw await j($,{reason:"superseded"}),G.teardown(n.node_id),D(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(ce&&e.readiness==="await"){const i=await on(n.node_id,P.exited);if(!i.ready){const c=yn(n.node_id,i);L({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:c.fields});const B=await fe.explanation();throw await bn(n.node_id,new Error(B??c.text)),D(B!==null?`the root broker ${n.node_id} could not start \u2014 ${B}`:`the root broker ${n.node_id} ${c.text} \u2014 it was not started.`,B!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let Z=null,ee=null;if(!t&&s!==null&&dn("user").auto_open_child_viewers)try{const i=await en(s);if(i!==null&&i.pane!==null&&i.pane!==""){const c=await Ze(n.node_id,i.session??"",{name:re(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:W});c!==null&&c.pane!==null&&c.pane!==""&&(ee=c.session,Z=nn(c.pane))}}catch{}return{node:await u(n.node_id),frozen:!1,window:Z,session:ee}}catch(f){throw x!==void 0&&m!==void 0&&await u(m)===null&&await De(x),f}}d(le,"spawnChildPrepared");async function yo(e){return le(e)}d(yo,"spawnChild");async function Cn(e){const o=hn(e.cwd,e.profile_id).plans.get("node:start")??[];await pn(o,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await K(e.node_id),contextDir:await H(e.node_id),jobDir:Ue(e.node_id)},runtime:{isBirth:!0,canvasHome:Ge(),profile:e.profile_id??null}})}d(Cn,"invokeBirthLifecycleHooks");const En=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function bo(e,o,a){const r=await u(e);if(r===null)throw w(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const t=await ie(e),s=await H(e);try{await S().header(N(t)),he(s,pe.R_OK)}catch(l){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${l.message}`)}return le({kind:r.kind,mode:"base",cwd:r.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...a===void 0?{}:{actor:a},profile:r.profile_id,model:r.model_override??void 0,...o===void 0?{}:{scopes:o}},async l=>{const y=await H(l);Xe(await K(e),s,await K(l),y,En)})}d(bo,"forkNode");export{de as appPaidLaunch,se as assertLaunchModelRegistered,bo as forkNode,Cn as invokeBirthLifecycleHooks,ie as resolveForkSource,$n as resolveProfileId,Sn as resolveSpawner,yo as spawnChild,le as spawnChildPrepared};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/** A cloud role is never an unsandboxed machine: a person's settings there may still carry an imported Mac's `runtime.unsandboxed`. */
|
|
1
2
|
export declare function isUnsandboxedMachine(): boolean;
|
|
2
3
|
/** Throw `403 unsandboxed_machine` when this machine is unsandboxed and `grantee` is not `app:terminal`. */
|
|
3
4
|
export declare function assertGranteeRunsHere(grantee: string | null | undefined): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var o=Object.defineProperty;var e=(r
|
|
1
|
+
var o=Object.defineProperty;var e=(n,r)=>o(n,"name",{value:r,configurable:!0});import{ApiError as t}from"../../api/errors.js";import{readConfig as i}from"../config.js";import{isCloudRole as s}from"../canvas/person-state.js";function u(){return!s()&&i("user").runtime?.unsandboxed===!0}e(u,"isUnsandboxedMachine");function c(n){const r=n??"app:terminal";if(!(r==="app:terminal"||!u()))throw new t(403,"unsandboxed_machine",`This computer runs only your own terminal agents; ${r} runs on your hosted machine.`)}e(c,"assertGranteeRunsHere");export{c as assertGranteeRunsHere,u as isUnsandboxedMachine};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var $=Object.defineProperty;var n=(e,r)=>$(e,"name",{value:r,configurable:!0});import{createHash as b,randomUUID as R}from"node:crypto";import{openDb as L}from"../canvas/db.js";import{claimReconcilerLease as C,releaseReconcilerLease as E,renewReconcilerLease as W}from"../canvas/reconciler-leases.js";import{claimWarmSpare as M,deleteNode as w,getNode as p,listNodes as P,listWarmSpares as u,registerWarmSpare as I,unregisterWarmSpare as y,updateNode as A,warmSpareCount as h}from"../canvas/index.js";import{recordedPidLiveness as D}from"../canvas/pid.js";import{nowIso as g}from"../fs-utils.js";import{admitNodeCreate as O}from"../command-hooks/lifecycle-create.js";import{isDrained as T}from"../../daemon/drain.js";import{spawnChildPrepared as H}from"./spawn.js";import{
|
|
1
|
+
var $=Object.defineProperty;var n=(e,r)=>$(e,"name",{value:r,configurable:!0});import{createHash as b,randomUUID as R}from"node:crypto";import{openDb as L}from"../canvas/db.js";import{claimReconcilerLease as C,releaseReconcilerLease as E,renewReconcilerLease as W}from"../canvas/reconciler-leases.js";import{claimWarmSpare as M,deleteNode as w,getNode as p,listNodes as P,listWarmSpares as u,registerWarmSpare as I,unregisterWarmSpare as y,updateNode as A,warmSpareCount as h}from"../canvas/index.js";import{recordedPidLiveness as D}from"../canvas/pid.js";import{nowIso as g}from"../fs-utils.js";import{admitNodeCreate as O}from"../command-hooks/lifecycle-create.js";import{isDrained as T}from"../../daemon/drain.js";import{spawnChildPrepared as H}from"./spawn.js";import{remoteEnvironmentOf as F}from"./blaxel-environment.js";import{newNodeId as K}from"./nodes.js";import{checkStart as U}from"./start-check.js";import{buildLaunchSpecAsync as j}from"./launch.js";import{setModelLive as B}from"./model-swap.js";import{setSituationalContextLive as G}from"./situational-live.js";import{deliverBearingsLive as J}from"./deliver-live.js";import{closeNode as _}from"./close.js";import{transition as z}from"./lifecycle.js";import{stopNodeSandboxes as Q}from"../spaces/stop.js";function v(){return process.env.CRTR_WARM_POOL!=="0"}n(v,"warmPoolEnabled");function V(e,r,a){const t=Object.entries(a.env??{}).sort(([s],[i])=>s<i?-1:s>i?1:0),o=JSON.stringify([e,r,a.tools??[],a.extensions??[],a.systemPrompt??null,t]);return b("sha256").update(o).digest("hex").slice(0,32)}n(V,"warmRecipeKey");async function d(e){const{launch:r}=await j(e.kind,e.mode,{lifecycle:"resident",hasManager:!1,...e.model!==null?{model:e.model}:{},cwd:e.cwd,profileId:e.profileId,app:"app:terminal"});return{key:V(e.cwd,e.profileId,r),launch:r,request:e}}n(d,"resolveRecipe");async function S(e){const r=e.creator===null?null:await p(e.creator);await U({grantee:r?.grantee??"app:terminal",sub:r?.sub,grant_id:r?.grant_id})}n(S,"checkClaimantStart");async function ve(e,r={},a){await S(e);const t=await d(e);if(await h(t.key)===0)return null;const o=g(),s=await O({kind:e.kind,mode:e.mode,cwd:e.cwd,profile:e.profileId,root:!0,parentId:null,requestingNodeId:e.creator,lifecycle:"resident",replaces:null},e.creator===null?"app:terminal":await(async()=>{const c=await p(e.creator);if(!c?.grantee)throw new Error("warm node creator has no app");return c.grantee})());let i;try{i=await M(t.key,o,r)}finally{s()}return i===null?null:k(i,t,o,a)}n(ve,"claimWarmNode");async function Se(e,r,a){return await S(e),k(r,await d(e),g(),a)}n(Se,"resumeWarmClaim");async function k(e,r,a,t){const{request:o}=r,i=(await p(e))?.launch?.model;await A(e,{created:a,kind:o.kind,mode:o.mode,name:o.name??o.kind,creator:o.creator,launch:r.launch,persona_ack:{kind:o.kind,mode:o.mode,lifecycle:"resident"},...o.model!==null?{model_override:o.model}:{}});try{t?.(e)}catch(l){return await m(e,"birth preparation",l)}try{await J(e)}catch(l){return await m(e,"bearings delivery",l)}const c=r.launch.model;if(c!==void 0&&c!==i)try{await B(e,c,r.launch.modelIntent)}catch(l){return await m(e,"model swap",l)}if(o.situationalContext!==null)try{await G(e,o.situationalContext)}catch(l){return await m(e,"situational-context delivery",l)}return e}n(k,"completeWarmClaim");async function m(e,r,a){console.error(`[warm-pool] ${r} failed on claim; closing the spare: ${a.message}`);try{await _(e)}catch{}return null}n(m,"abandonSpare");const X=3600*1e3;async function ke(){const e=[];let r;try{r=await u()}catch(t){return console.error(`[warm-pool] spare scan failed: ${t.message}`),e}const a=Date.now()-X;for(const t of r){if(await Y(t.node_id))continue;const o=Date.parse(t.created),s=Number.isNaN(o)||o<a,i=D(t.pi_pid,t.pi_pid_identity),c=(t.status==="active"||t.status==="idle")&&i==="alive";if(!(c&&!s)&&!(i==="indeterminate"&&!s))try{if(!await y(t.node_id))continue;if(c)try{await _(t.node_id)}catch{}await w(t.node_id),e.push(t.node_id)}catch(l){console.error(`[warm-pool] reap failed for ${t.node_id}: ${l.message}`)}}return e}n(ke,"reapStaleSpares");async function xe(){for(const e of await u()){if(!await y(e.node_id))continue;await z(e.node_id,"cancel",{reason:"closed"});const r=await Q(e.node_id,"warm_pool_drained");if(!r.confirmed)throw new Error(`drain: the broker of spare ${e.node_id} could not be confirmed stopped: ${r.error?.message??"unknown"}`);await w(e.node_id)}}n(xe,"emptyWarmPool");const f=6e4;async function x(e,r){const a=R();if(await C(e,r,a,f)===void 0)return;const t=setInterval(()=>{W(e,r,a,f).catch(()=>{})},f/3);return t.unref(),async()=>{clearInterval(t),await E(e,r,a)}}n(x,"holdMintLease");async function Y(e){return await(await L()).prepare("SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND expires_at > ?").get("warm-pool-mint",e,new Date().toISOString())!==void 0}n(Y,"mintLeaseHeld");function Ne(e){if(v())try{d({...e,model:null,situationalContext:null}).then(N).catch(r=>console.error(`[warm-pool] recipe resolution failed: ${r.message}`))}catch(r){console.error(`[warm-pool] recipe resolution failed: ${r.message}`)}}n(Ne,"refillWarmPool");async function N(e){if(await T())return;const{key:r}=e;if(await F(e.request.profileId)!==null)return;const a=await x("warm-pool",r);if(a!==void 0){if(await h(r)>0){await a();return}Z(e,await K()).finally(()=>a().catch(()=>{}))}}n(N,"mint");async function Z({key:e,request:r},a){const t=await x("warm-pool-mint",a);if(t===void 0){console.error(`[warm-pool] mint refused for ${r.kind}: the mint lease of ${a} is held elsewhere`);return}try{await H({nodeId:a,kind:r.kind,mode:r.mode,cwd:r.cwd,prompt:"",root:!0,readiness:"await",profile:r.profileId},async o=>{await I(o,e)})}catch(o){console.error(`[warm-pool] mint failed for ${r.kind}: ${o.message}`)}finally{await t().catch(()=>{})}}n(Z,"birthSpare");const q=2;async function $e(){if(!v())return;let e;try{const r=new Set;e=[];for(const a of(await P({status:["active","idle"]})).reverse()){if(a.parent!==null||a.kind==="human")continue;const t=a.profile_id??null;if(!r.has(t??"")&&(r.add(t??""),e.push({cwd:a.cwd,profileId:t}),e.length>=q))break}}catch(r){console.error(`[warm-pool] prewarm scan failed: ${r.message}`);return}for(const r of e)try{d({kind:"general",mode:"base",cwd:r.cwd,profileId:r.profileId,model:null,situationalContext:null,name:null,creator:null}).then(N).catch(a=>console.error(`[warm-pool] prewarm failed for ${r.cwd}: ${a.message}`))}catch(a){console.error(`[warm-pool] prewarm failed for ${r.cwd}: ${a.message}`)}}n($e,"prewarmRecentRecipes");export{Z as birthSpare,ve as claimWarmNode,xe as emptyWarmPool,x as holdMintLease,$e as prewarmRecentRecipes,ke as reapStaleSpares,Ne as refillWarmPool,Se as resumeWarmClaim,v as warmPoolEnabled};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.646",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -145,7 +145,7 @@
|
|
|
145
145
|
},
|
|
146
146
|
"license": "UNLICENSED",
|
|
147
147
|
"dependencies": {
|
|
148
|
-
"@north-light/identity": "0.3.
|
|
148
|
+
"@north-light/identity": "0.3.646",
|
|
149
149
|
"@earendil-works/chord": "1.1.0",
|
|
150
150
|
"@earendil-works/pi-agent-core": "1.1.0",
|
|
151
151
|
"@earendil-works/pi-ai": "1.1.0",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.646",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.646",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "UNLICENSED",
|
|
12
12
|
"workspaces": [
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"@milkdown/preset-gfm": "^7.22.3",
|
|
29
29
|
"@milkdown/prose": "^7.22.3",
|
|
30
30
|
"@milkdown/utils": "^7.22.3",
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
31
|
+
"@north-light/identity": "0.3.646",
|
|
32
32
|
"cron-parser": "^5.6.0",
|
|
33
33
|
"esbuild": "^0.27.7",
|
|
34
34
|
"jose": "^6.2.12",
|
|
@@ -11956,17 +11956,17 @@
|
|
|
11956
11956
|
},
|
|
11957
11957
|
"packages/crouter-api": {
|
|
11958
11958
|
"name": "@north-light/api",
|
|
11959
|
-
"version": "0.3.
|
|
11959
|
+
"version": "0.3.646",
|
|
11960
11960
|
"license": "UNLICENSED"
|
|
11961
11961
|
},
|
|
11962
11962
|
"packages/crouter-env-docker": {
|
|
11963
11963
|
"name": "@north-light/env-docker",
|
|
11964
|
-
"version": "0.3.
|
|
11964
|
+
"version": "0.3.646",
|
|
11965
11965
|
"license": "UNLICENSED"
|
|
11966
11966
|
},
|
|
11967
11967
|
"packages/crouter-identity": {
|
|
11968
11968
|
"name": "@north-light/identity",
|
|
11969
|
-
"version": "0.3.
|
|
11969
|
+
"version": "0.3.646",
|
|
11970
11970
|
"license": "UNLICENSED",
|
|
11971
11971
|
"dependencies": {
|
|
11972
11972
|
"jose": "^6.2.1"
|
|
@@ -11974,21 +11974,21 @@
|
|
|
11974
11974
|
},
|
|
11975
11975
|
"packages/crouter-plugin": {
|
|
11976
11976
|
"name": "@north-light/plugin",
|
|
11977
|
-
"version": "0.3.
|
|
11977
|
+
"version": "0.3.646",
|
|
11978
11978
|
"license": "UNLICENSED",
|
|
11979
11979
|
"dependencies": {
|
|
11980
|
-
"@north-light/api": "0.3.
|
|
11981
|
-
"@north-light/identity": "0.3.
|
|
11980
|
+
"@north-light/api": "0.3.646",
|
|
11981
|
+
"@north-light/identity": "0.3.646"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.646",
|
|
11987
11987
|
"license": "UNLICENSED",
|
|
11988
11988
|
"dependencies": {
|
|
11989
|
-
"@north-light/api": "0.3.
|
|
11990
|
-
"@north-light/identity": "0.3.
|
|
11991
|
-
"@north-light/plugin": "0.3.
|
|
11989
|
+
"@north-light/api": "0.3.646",
|
|
11990
|
+
"@north-light/identity": "0.3.646",
|
|
11991
|
+
"@north-light/plugin": "0.3.646",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|