@north-light/cli 0.3.640 → 0.3.642

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.
@@ -1,12 +1,12 @@
1
- var A=Object.defineProperty;var d=(n,s)=>A(n,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as H,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as p}from"./catalog.js";const f=d((n,s)=>`${p(n)}.${p(s)}`,"sq");async function P(n,s,c){if(c.length===0)return 0;const e=d(o=>f(s,o),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const E=d(async(o,t,r,u=!1)=>{const R=await n.prepareUncached(`SELECT ${p(t)}::text AS value FROM ${e(o)} WHERE ${r} AND ${p(t)} IS NOT NULL`).all();for(const{value:m}of R){const h=u?D(m,c):S(c,m);h!==m&&(await n.prepareUncached(`UPDATE ${e(o)} SET ${p(t)} = ? WHERE ${p(t)}::text = ? AND ${r}`).run(h,m),a+=1)}},"apply");return await E("nodes","cwd",`node_id IN ${i}`),await E("worktrees","path",`node_id IN ${i}`),await E("worktrees","repo_root",`node_id IN ${i}`),await E("crons","cwd",`anchor_node IN ${i}`),await E("provider_approvals","prepared_files","TRUE",!0),await E("upload_uses","path",`run_id IN ${i}`),a}d(P,"rewritePaths");async function B(n,s,c,e,i){if(c.length===0)return 0;const a=d(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
2
- AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let o=0;for(const{conversation_id:t,blob_key:r}of E){const u=M(i,r),R=await e.get(u);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${u} is missing: the header of conversation ${t} cannot be rewritten`);const m=C(R,t,h=>S(c,h));m!==null&&(await e.put(u,m),o+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ? WHERE conversation_id = ? AND seq = 0`).run((m??R).length,t)}return o}d(B,"rewriteConversationHeaders");async function K(n,s){const c=f(s,"human_requests"),e=d(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
1
+ var A=Object.defineProperty;var p=(n,s)=>A(n,"name",{value:s,configurable:!0});import{createProfileBlaxelEnvironment as U}from"../../environments.js";import{KEY_MAPPED_TABLES as H,mapPath as S}from"../bundle/layout.js";import{ImportLaneError as N}from"./stage.js";import{withHeaderCwd as C}from"../../conversation-store/row-store.js";import{runBlobKey as M}from"../bundle/blob-keys.js";import{q as l}from"./catalog.js";const f=p((n,s)=>`${l(n)}.${l(s)}`,"sq");async function B(n,s,c){if(c.length===0)return 0;const e=p(o=>f(s,o),"S"),i=`(SELECT node_id FROM ${e("nodes")} WHERE status IN ('active', 'idle'))`;let a=0;const E=p(async(o,t,r,u=!1)=>{const R=await n.prepareUncached(`SELECT ${l(t)}::text AS value FROM ${e(o)} WHERE ${r} AND ${l(t)} IS NOT NULL`).all();for(const{value:m}of R){const h=u?D(m,c):S(c,m);h!==m&&(await n.prepareUncached(`UPDATE ${e(o)} SET ${l(t)} = ? WHERE ${l(t)}::text = ? AND ${r}`).run(h,m),a+=1)}},"apply");return await E("nodes","cwd",`node_id IN ${i}`),await E("worktrees","path",`node_id IN ${i}`),await E("worktrees","repo_root",`node_id IN ${i}`),await E("crons","cwd",`anchor_node IN ${i}`),await E("provider_approvals","prepared_files","TRUE",!0),await E("upload_uses","path",`run_id IN ${i}`),a}p(B,"rewritePaths");async function K(n,s,c,e,i){if(c.length===0)return 0;const a=p(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT conversation_id, blob_key FROM ${a("conversation_parts")} WHERE seq = 0
2
+ AND split_part(blob_key, '/', 2) IN (SELECT node_id FROM ${a("nodes")} WHERE status IN ('active', 'idle'))`).all();let o=0;for(const{conversation_id:t,blob_key:r}of E){const u=M(i,r),R=await e.get(u);if(R===null)throw new N("rewrite-paths","bundle_invalid",`${u} is missing: the header of conversation ${t} cannot be rewritten`);const m=C(R,t,h=>S(c,h));m!==null&&(await e.put(u,m),o+=1),await n.prepareUncached(`UPDATE ${a("conversation_parts")} SET bytes = ? WHERE conversation_id = ? AND seq = 0`).run((m??R).length,t)}return o}p(K,"rewriteConversationHeaders");async function J(n,s){const c=f(s,"human_requests"),e=p(a=>`CASE WHEN ${a} IS NULL OR ${a} NOT LIKE '/%' THEN ${a}
3
3
  WHEN rtrim(${a}, '/') = rtrim(request_dir, '/') THEN 'requests/' || request_id
4
4
  WHEN ${a} LIKE rtrim(request_dir, '/') || '/%' THEN 'requests/' || request_id || '/' || substr(${a}, length(rtrim(request_dir, '/')) + 2)
5
5
  ELSE 'requests/' || request_id || '/source/' || regexp_replace(${a}, '^.*/', '') END`,"moved"),i=await n.prepareUncached(`UPDATE ${c} SET file = ${e("file")}, presentation_dir = ${e("presentation_dir")},
6
- request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}d(K,"rewriteRequestPaths");function D(n,s){const c=d(e=>typeof e=="string"?S(s,e):Array.isArray(e)?e.map(c):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,c(a)])):e,"walk");try{return JSON.stringify(c(JSON.parse(n)))}catch{return S(s,n)}}d(D,"rewriteJsonPaths");async function J(n,s,c,e,i){const a=d(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let o=0;for(const t of E)await n.prepareUncached(`SELECT 1 AS found FROM ${f(c,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,t.name,t.id)!==void 0&&(await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(`${t.name}-${e}`,t.id),o+=1);return o}d(J,"renameClashingProfiles");async function Y(n,s,c,e,i){const a=d(t=>f(s,t),"S");let E=0;const o=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const t of o){let r=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(r=(await n.prepareUncached(`SELECT environment_id FROM ${f(c,"profiles")} WHERE id = ?`).get(t.id))?.environment_id??await U(n,{profileId:t.id,grantee:t.grantee??"app:terminal",person:i})),r===null)throw new N("fill","bundle_invalid",`profile ${t.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(r,t.id),E+=1}return E}d(Y,"fillEnvironments");async function X(n,s,c,e){const i=d(o=>f(s,o),"S"),a={},E=d(async(o,t,...r)=>{const u=Number((await n.prepareUncached(t).run(...r)).changes);u>0&&(a[o]=(a[o]??0)+u)},"del");await E("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await n.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await n.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[o,t]of Object.entries(H))await E(o,`DELETE FROM ${i(o)} WHERE ${p(t)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,o);for(const o of c.tables.values())o.columns.includes("claimed_by")&&o.columns.includes("lease_expires_at")&&await n.prepareUncached(`UPDATE ${i(o.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}d(X,"pruneStaged");async function z(n,s,c){const e=d(E=>f(s,E),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${f(c,"documents")} t WHERE t.object = d.object))`;await n.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
6
+ request_dir = CASE WHEN request_dir LIKE '/%' THEN 'requests/' || request_id ELSE request_dir END`).run();return Number(i.changes)}p(J,"rewriteRequestPaths");function D(n,s){const c=p(e=>typeof e=="string"?S(s,e):Array.isArray(e)?e.map(c):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,a])=>[i,c(a)])):e,"walk");try{return JSON.stringify(c(JSON.parse(n)))}catch{return S(s,n)}}p(D,"rewriteJsonPaths");async function Y(n,s,c,e,i){const a=p(t=>f(s,t),"S"),E=await n.prepareUncached(`SELECT id, name FROM ${a("profiles")} ORDER BY id`).all();let o=0;for(const t of E)await n.prepareUncached(`SELECT 1 AS found FROM ${f(c,"profiles")} WHERE person = ? AND name = ? AND id <> ?`).get(i,t.name,t.id)!==void 0&&(await n.prepareUncached(`UPDATE ${a("profiles")} SET name = ? WHERE id = ?`).run(`${t.name}-${e}`,t.id),o+=1);return o}p(Y,"renameClashingProfiles");async function X(n,s,c,e,i){const a=p(t=>f(s,t),"S");let E=0;const o=await n.prepareUncached(`SELECT id, grantee FROM ${a("profiles")} WHERE environment_id IS NULL ORDER BY id`).all();for(const t of o){let r=e.kind==="machine"?e.environmentObject??null:null;if(e.kind==="hosted"&&(r=(await n.prepareUncached(`SELECT environment_id FROM ${f(c,"profiles")} WHERE id = ?`).get(t.id))?.environment_id??await U(n,{profileId:t.id,grantee:t.grantee??"app:terminal",person:i})),r===null)throw new N("fill","bundle_invalid",`profile ${t.id} has no environment and the source names none`);await n.prepareUncached(`UPDATE ${a("profiles")} SET environment_id = ? WHERE id = ?`).run(r,t.id),E+=1}return E}p(X,"fillEnvironments");async function z(n,s,c,e){const i=p(o=>f(s,o),"S"),a={},E=p(async(o,t,...r)=>{const u=Number((await n.prepareUncached(t).run(...r)).changes);u>0&&(a[o]=(a[o]??0)+u)},"del");await E("limits",`DELETE FROM ${i("limits")} WHERE source <> 'person'`),e.kind==="hosted"&&(await n.prepareUncached(`UPDATE ${i("profiles")} SET environment_id = NULL WHERE environment_id IN (SELECT object FROM ${i("environments")})`).run(),await n.prepareUncached(`UPDATE ${i("objects")} SET home_machine = 'import-hosted-source' WHERE id IN (SELECT object FROM ${i("environments")})`).run());for(const[o,t]of Object.entries(H))await E(o,`DELETE FROM ${i(o)} WHERE ${l(t)}::text IN (SELECT source_key FROM import_key_map WHERE source_install_id = ? AND table_name = ?)`,e.installId,o);for(const o of c.tables.values())o.columns.includes("claimed_by")&&o.columns.includes("lease_expires_at")&&await n.prepareUncached(`UPDATE ${i(o.name)} SET claimed_by = NULL, lease_expires_at = NULL WHERE claimed_by IS NOT NULL OR lease_expires_at IS NOT NULL`).run();return a}p(z,"pruneStaged");async function G(n,s,c){const e=p(E=>f(s,E),"S"),i=`(SELECT d.object FROM ${e("documents")} d WHERE EXISTS (SELECT 1 FROM ${f(c,"documents")} t WHERE t.object = d.object))`;await n.exec(`CREATE TABLE ${e("_arr_revisions")} AS SELECT r.* FROM ${e("revisions")} r WHERE r.document IN ${i};
7
7
  CREATE TABLE ${e("_arr_parents")} AS SELECT p.* FROM ${e("revision_parents")} p WHERE p.child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`);const a=await n.prepareUncached(`SELECT r.document, r.rev_id, r.body_hash, r.rationale, r.created_at,
8
8
  COALESCE((SELECT array_agg(p.parent) FROM ${e("revision_parents")} p WHERE p.child = r.rev_id), ARRAY[]::text[]) AS parents
9
- FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(E=>({...E}))}d(z,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]};async function G(n,s,c,e,i,a,E){const o=d(r=>[...E.get(r)??[],...r==="profiles"?["environment_id"]:[],...g[r]??[],"claimed_by","lease_expires_at"],"ignored"),t=[];for(const r of i){const u=e.tables.get(r);if(u===void 0||a.has(r)||u.primaryKey.length===0)continue;const R=u.primaryKey,m=R.some(l=>u.identity.includes(l)),h=R.map(l=>`s.${p(l)} = t.${p(l)}`).join(" AND "),I=m?"TRUE":R.map(l=>`s.${p(l)} IS DISTINCT FROM t.${p(l)}`).join(" OR "),v=new Set([...u.identity,...E.get(r)??[]]);for(const l of e.uniqueKeys.filter(_=>_.table===r&&!_.columns.every(T=>v.has(T)))){const _=l.predicate===null?"":` WHERE ${l.predicate}`,T=l.columns.map($=>`s.${p($)} = t.${p($)}`).join(" AND "),L=await n.prepareUncached(`SELECT ${l.columns.map($=>`s.${p($)}::text`).join(" || ',' || ")} AS value
10
- FROM (SELECT * FROM ${f(s,r)}${_}) s JOIN (SELECT * FROM ${f(c,r)}${_}) t ON ${T} AND (${I}) LIMIT 10`).all();L.length>0&&t.push({table:r,key:l.name,values:L.map($=>$.value)});const y=m?"TRUE":R.map($=>`a.${p($)} IS DISTINCT FROM b.${p($)}`).join(" OR "),O=await n.prepareUncached(`SELECT DISTINCT ${l.columns.map($=>`a.${p($)}::text`).join(" || ',' || ")} AS value
11
- FROM (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) a JOIN (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) b ON ${l.columns.map($=>`a.${p($)} = b.${p($)}`).join(" AND ")} AND a.row_id < b.row_id AND (${y}) LIMIT 10`).all();O.length>0&&t.push({table:r,key:l.name,values:O.map($=>$.value),staged:!0})}const w=u.columns.filter(l=>!u.identity.includes(l)&&!o(r).includes(l));if(w.length>0&&!m){const l=w.map(T=>`s.${p(T)} IS DISTINCT FROM t.${p(T)}`).join(" OR "),_=await n.prepareUncached(`SELECT ${R.map(T=>`s.${p(T)}::text`).join(" || ',' || ")} AS value
12
- FROM ${f(s,r)} s JOIN ${f(c,r)} t ON ${h} WHERE ${l} LIMIT 10`).all();_.length>0&&t.push({table:r,key:"primary key payload",values:_.map(T=>T.value)})}}if(t.length>0){const r=t[0];throw new N("pre-check","unique_conflict",`${r.table} ${r.key} collides ${r.staged===!0?"within the bundle":"with the target"}: ${r.values.join(", ")}`,{collisions:t})}}d(G,"precheck");export{Y as fillEnvironments,G as precheck,X as pruneStaged,J as renameClashingProfiles,B as rewriteConversationHeaders,P as rewritePaths,K as rewriteRequestPaths,z as takeRepoSyncedDocuments};
9
+ FROM ${e("revisions")} r WHERE r.document IN ${i} ORDER BY r.document, r.number`).all();return await n.prepareUncached(`DELETE FROM ${e("revision_parents")} WHERE child IN (SELECT rev_id FROM ${e("revisions")} WHERE document IN ${i})`).run(),await n.prepareUncached(`DELETE FROM ${e("revisions")} WHERE document IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("objects")} WHERE id IN ${i}`).run(),await n.prepareUncached(`DELETE FROM ${e("documents")} WHERE object IN ${i}`).run(),a.map(E=>({...E}))}p(G,"takeRepoSyncedDocuments");const g={edges:["created_at"],relations:["created_at"]},W={charges:["payer","units","usd"]};async function Q(n,s,c,e,i,a,E){const o=p(r=>[...E.get(r)??[],...r==="profiles"?["environment_id"]:[],...g[r]??[],"claimed_by","lease_expires_at"],"ignored"),t=[];for(const r of i){const u=e.tables.get(r);if(u===void 0||a.has(r)||u.primaryKey.length===0)continue;const R=u.primaryKey,m=R.some(d=>u.identity.includes(d)),h=R.map(d=>`s.${l(d)} = t.${l(d)}`).join(" AND "),I=m?"TRUE":R.map(d=>`s.${l(d)} IS DISTINCT FROM t.${l(d)}`).join(" OR "),v=new Set([...u.identity,...E.get(r)??[]]);for(const d of e.uniqueKeys.filter(_=>_.table===r&&!_.columns.every(T=>v.has(T)))){const _=d.predicate===null?"":` WHERE ${d.predicate}`,T=d.columns.map($=>`s.${l($)} = t.${l($)}`).join(" AND "),O=await n.prepareUncached(`SELECT ${d.columns.map($=>`s.${l($)}::text`).join(" || ',' || ")} AS value
10
+ FROM (SELECT * FROM ${f(s,r)}${_}) s JOIN (SELECT * FROM ${f(c,r)}${_}) t ON ${T} AND (${I}) LIMIT 10`).all();O.length>0&&t.push({table:r,key:d.name,values:O.map($=>$.value)});const y=m?"TRUE":R.map($=>`a.${l($)} IS DISTINCT FROM b.${l($)}`).join(" OR "),L=await n.prepareUncached(`SELECT DISTINCT ${d.columns.map($=>`a.${l($)}::text`).join(" || ',' || ")} AS value
11
+ FROM (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) a JOIN (SELECT ctid AS row_id, * FROM ${f(s,r)}${_}) b ON ${d.columns.map($=>`a.${l($)} = b.${l($)}`).join(" AND ")} AND a.row_id < b.row_id AND (${y}) LIMIT 10`).all();L.length>0&&t.push({table:r,key:d.name,values:L.map($=>$.value),staged:!0})}const w=u.columns.filter(d=>!u.identity.includes(d)&&!o(r).includes(d)&&(W[r]?.includes(d)??!0));if(w.length>0&&!m){const d=w.map(T=>`s.${l(T)} IS DISTINCT FROM t.${l(T)}`).join(" OR "),_=await n.prepareUncached(`SELECT ${R.map(T=>`s.${l(T)}::text`).join(" || ',' || ")} AS value
12
+ FROM ${f(s,r)} s JOIN ${f(c,r)} t ON ${h} WHERE ${d} LIMIT 10`).all();_.length>0&&t.push({table:r,key:"primary key payload",values:_.map(T=>T.value)})}}if(t.length>0){const r=t[0];throw new N("pre-check","unique_conflict",`${r.table} ${r.key} collides ${r.staged===!0?"within the bundle":"with the target"}: ${r.values.join(", ")}`,{collisions:t})}}p(Q,"precheck");export{X as fillEnvironments,Q as precheck,z as pruneStaged,Y as renameClashingProfiles,K as rewriteConversationHeaders,B as rewritePaths,J as rewriteRequestPaths,G as takeRepoSyncedDocuments};
@@ -60,7 +60,11 @@ export declare function resumeWarmClaim(request: WarmRequest, nodeId: string, be
60
60
  * new owner. Only after winning the marker is the broker killed and the row +
61
61
  * dir deleted. Never throws: a failed reap is retried on the next sweep. */
62
62
  export declare function reapStaleSpares(): Promise<string[]>;
63
- /** Remove every spare, live or not, with its broker. A drained daemon mints none, so the pool stays empty until the drain ends. */
63
+ /** Remove every spare, live or not, with its broker. A drained daemon mints none, so the pool stays empty until the drain ends.
64
+ * The broker is confirmed gone before the row and directory are deleted. `closeNode` cannot do that: it reaps an empty node at
65
+ * once and queues the broker teardown for later, and a broker still shutting down rewrites `run/job/attach.json` while the
66
+ * directory is removed, which fails the removal (ENOTEMPTY) and the drain with it. A spare's broker that cannot be confirmed
67
+ * stopped fails the drain, as it does for a busy node in `settleDrain`. */
64
68
  export declare function emptyWarmPool(): Promise<void>;
65
69
  /** Claims the lease and renews it until the returned release runs; undefined when another holder has it. */
66
70
  export declare function holdMintLease(lane: string, key: string): Promise<(() => Promise<void>) | undefined>;
@@ -1 +1 @@
1
- var N=Object.defineProperty;var n=(e,r)=>N(e,"name",{value:r,configurable:!0});import{createHash as R,randomUUID as L}from"node:crypto";import{openDb as b}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 u,getNode as p,listNodes as P,listWarmSpares as y,registerWarmSpare as I,unregisterWarmSpare as h,updateNode as A,warmSpareCount as g}from"../canvas/index.js";import{recordedPidLiveness as D}from"../canvas/pid.js";import{nowIso as _}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{blaxelEnvironmentOf 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 f}from"./close.js";function v(){return process.env.CRTR_WARM_POOL!=="0"}n(v,"warmPoolEnabled");function z(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 R("sha256").update(o).digest("hex").slice(0,32)}n(z,"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:z(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 ye(e,r={},a){await S(e);const t=await d(e);if(await g(t.key)===0)return null;const o=_(),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(ye,"claimWarmNode");async function he(e,r,a){return await S(e),k(r,await d(e),_(),a)}n(he,"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 f(e)}catch{}return null}n(m,"abandonSpare");const Q=3600*1e3;async function ge(){const e=[];let r;try{r=await y()}catch(t){return console.error(`[warm-pool] spare scan failed: ${t.message}`),e}const a=Date.now()-Q;for(const t of r){if(await V(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 h(t.node_id))continue;if(c)try{await f(t.node_id)}catch{}await u(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(ge,"reapStaleSpares");async function _e(){for(const e of await y())if(await h(e.node_id)){try{await f(e.node_id)}catch(r){console.error(`[warm-pool] close failed for ${e.node_id}: ${r.message}`)}await u(e.node_id)}}n(_e,"emptyWarmPool");const w=6e4;async function x(e,r){const a=L();if(await C(e,r,a,w)===void 0)return;const t=setInterval(()=>{W(e,r,a,w).catch(()=>{})},w/3);return t.unref(),async()=>{clearInterval(t),await E(e,r,a)}}n(x,"holdMintLease");async function V(e){return await(await b()).prepare("SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND expires_at > ?").get("warm-pool-mint",e,new Date().toISOString())!==void 0}n(V,"mintLeaseHeld");function ve(e){if(v())try{d({...e,model:null,situationalContext:null}).then($).catch(r=>console.error(`[warm-pool] recipe resolution failed: ${r.message}`))}catch(r){console.error(`[warm-pool] recipe resolution failed: ${r.message}`)}}n(ve,"refillWarmPool");async function $(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 g(r)>0){await a();return}X(e,await K()).finally(()=>a().catch(()=>{}))}}n($,"mint");async function X({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(X,"birthSpare");const Y=2;async function Se(){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>=Y))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($).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(Se,"prewarmRecentRecipes");export{X as birthSpare,ye as claimWarmNode,_e as emptyWarmPool,x as holdMintLease,Se as prewarmRecentRecipes,ge as reapStaleSpares,ve as refillWarmPool,he as resumeWarmClaim,v as warmPoolEnabled};
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{blaxelEnvironmentOf 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.640",
3
+ "version": "0.3.642",
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.640",
148
+ "@north-light/identity": "0.3.642",
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",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.640",
3
+ "version": "0.3.642",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.640",
3
+ "version": "0.3.642",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.640",
9
+ "version": "0.3.642",
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.640",
31
+ "@north-light/identity": "0.3.642",
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.640",
11959
+ "version": "0.3.642",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.640",
11964
+ "version": "0.3.642",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.640",
11969
+ "version": "0.3.642",
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.640",
11977
+ "version": "0.3.642",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.640",
11981
- "@north-light/identity": "0.3.640"
11980
+ "@north-light/api": "0.3.642",
11981
+ "@north-light/identity": "0.3.642"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.640",
11986
+ "version": "0.3.642",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.640",
11990
- "@north-light/identity": "0.3.640",
11991
- "@north-light/plugin": "0.3.640",
11989
+ "@north-light/api": "0.3.642",
11990
+ "@north-light/identity": "0.3.642",
11991
+ "@north-light/plugin": "0.3.642",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {