@north-light/cli 0.3.730 → 0.3.731
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.d.ts +5 -0
- package/dist/api/errors.js +1 -1
- package/dist/clients/attach/viewer.js +526 -526
- package/dist/core/canvas/history.d.ts +1 -1
- package/dist/core/canvas/history.js +8 -8
- package/dist/core/conversation-store/row-store.js +13 -13
- package/dist/core/environment-starter-script.d.ts +1 -1
- package/dist/core/environment-starter-script.js +4 -1
- package/dist/core/model-auth/activations.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
- package/dist/daemon/api/bridge.js +2 -2
- package/dist/daemon/api/handlers/canvas.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/errors.js +11 -0
- package/packages/crouter-api/dist/core/canvas/history.js +3 -3
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -2
- package/packages/crouter-api/dist/core/environment-starter-script.js +4 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +4 -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
|
@@ -95,7 +95,7 @@ export interface ResolvedRef {
|
|
|
95
95
|
/** Rendered body. */
|
|
96
96
|
body: string;
|
|
97
97
|
/** The verbatim record (session bytes or jsonl line); null for an inbox entry. */
|
|
98
|
-
raw: string | null;
|
|
98
|
+
raw: (() => Promise<string | null>) | null;
|
|
99
99
|
path: string | null;
|
|
100
100
|
}
|
|
101
101
|
/** Resolve a `<node-id>:inbox/<n>`, `<node-id>:session` or
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var S=Object.defineProperty;var
|
|
1
|
+
var S=Object.defineProperty;var a=(n,s)=>S(n,"name",{value:s,configurable:!0});import{envNodeId as M}from"../../shared/env.js";import{getNode as p,listNodes as j,view as v}from"./canvas.js";import{openDb as E}from"./db.js";import{readTextIfExists as O}from"../fs-utils.js";import{conversationIdFromPath as y,conversationStore as g,ConversationNotFoundError as I}from"../conversation-store/index.js";import{reportBodyByName as C}from"../feed/reports.js";import{readStamps as A}from"../runtime/stamp/protocol.js";import{forEachAsync as B}from"../async-array.js";const nn=["human","inbox","wake","revive","restart-continuation","stop-guard","park","recovery","context-nudge","kickoff","unknown"],en=["user","assistant","toolResult"];async function R(){const n=M();if(n!==void 0&&n!==""){const s=await p(n);if(s!==null)return s.cwd}return process.cwd()}a(R,"callerCwd");function x(n){const s=Date.parse(n);return Number.isNaN(s)?0:s}a(x,"toMs");async function k(n){return(await(await E()).prepare(`SELECT m.created_at, m.sender_node_id, d.urgency, m.kind, m.label, m.body_ref, m.body_json
|
|
2
2
|
FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
3
3
|
WHERE d.destination_id = ? AND d.wake = 1
|
|
4
|
-
ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}
|
|
5
|
-
`),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,c=n.ref!==null?o?typeof r=="string"?r:O(n.ref)??"":await C(n.ref)??"":i,u=c!==""&&c!==n.label,
|
|
4
|
+
ORDER BY m.seq, d.created_at, d.delivery_id`).all(n)).map(e=>({ts:e.created_at,from:e.sender_node_id,tier:e.urgency,kind:e.kind,label:e.label,ref:e.body_ref,data:e.body_json===null?null:JSON.parse(e.body_json)}))}a(k,"allInboxEntries");async function _(n){const s=[`from: ${n.from??"system"}`,`tier: ${n.tier}`].join(`
|
|
5
|
+
`),e=`[${n.kind}] ${n.label}`,t=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body:void 0,i=typeof t=="string"?t.trim():"",o=typeof t=="string",r=typeof n.data=="object"&&n.data!==null&&!Array.isArray(n.data)?n.data.body_full:void 0,c=n.ref!==null?o?typeof r=="string"?r:O(n.ref)??"":await C(n.ref)??"":i,u=c!==""&&c!==n.label,d=[s,e];return n.ref!==null&&d.push(`ref: ${n.ref}`),u&&d.push(c),d.join(`
|
|
6
6
|
|
|
7
|
-
`)}
|
|
8
|
-
`)}
|
|
9
|
-
`).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:
|
|
7
|
+
`)}a(_,"inboxEntryBody");async function D(n,s,e,t){const i=`inbox/${String(t).padStart(6,"0")}`,o=await _(e),r={ref:`${n.node_id}:${i}`,nodeId:n.node_id,relpath:i,source:"inbox",ts:e.ts,tsMs:x(e.ts),title:`[${e.kind}] from ${e.from??"system"}: ${e.label}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:a(()=>o,"loadBody"),origin:"inbox"};return typeof e.from=="string"&&e.from!==""&&(r.from=e.from),r}a(D,"inboxArtifact");async function N(n){const s=(await p(n))?.pi_session_file,e=typeof s=="string"?y(s):null;if(e===null)return null;try{return(await g().header(e)).path}catch(t){if(t instanceof I)return null;throw t}}a(N,"resolveSessionFile");function T(n){if(typeof n=="string")return n;if(!Array.isArray(n))return"";const s=[];for(const e of n){if(e===null||typeof e!="object")continue;const t=e;t.type==="text"&&typeof t.text=="string"?s.push(t.text):t.type==="toolCall"&&s.push(`Tool: ${typeof t.name=="string"?t.name:"call"}`)}return s.join(`
|
|
8
|
+
`)}a(T,"textFromBlocks");function F(n){return n==null?"unknown":n.type==="human"?"human":n.kind}a(F,"originToken");function L(n){if(n==null||n.type!=="runtime")return;const s=n.entries;if(s===void 0||s.length===0)return;const e=new Set;for(const t of s){const i=t.fromName??t.from;typeof i=="string"&&i!==""&&e.add(i)}return e.size===0?void 0:[...e].join(", ")}a(L,"sendersOf");async function $(n){const s=await N(n);if(s===null)return[];const e=(await g().read(y(s))).entries,t=new Map;for(const o of A(e)){if(o.kind!=="message")continue;const r=o.payload;typeof r.msgTs=="number"&&t.set(r.msgTs,r.origin)}const i=[];for(const o of e){if(o===null||typeof o!="object")continue;const r=o;if(r.type!=="message")continue;const c=r.message;if(c===null||typeof c!="object")continue;const u=c,d=typeof u.role=="string"?u.role:"";if(d==="")continue;const f=typeof u.timestamp=="number"?u.timestamp:void 0,l=typeof r.timestamp=="string"?r.timestamp:f!==void 0?new Date(f).toISOString():"",m=T(u.content),b={index:i.length,role:d,text:m,ts:l,tsMs:f??x(l)};if(d==="user"){const w=f!==void 0&&t.has(f)?t.get(f):null;b.origin=F(w);const h=L(w);h!==void 0&&(b.from=h)}i.push(b)}return i}a($,"sessionMessages");async function J(n,s){const e=(await g().read(y(n))).entries;let t=0;for(const i of e){if(i.type!=="message")continue;const o=i.message;if(!(o===null||typeof o!="object"||typeof o.role!="string")){if(t===s)return JSON.stringify(i);t++}}return null}a(J,"rawSessionLine");function K(n,s,e){const t=`session/${String(e.index).padStart(6,"0")}`,i=e.text.split(`
|
|
9
|
+
`).map(r=>r.trim()).find(r=>r!=="")??"",o={ref:`${n.node_id}:${t}`,nodeId:n.node_id,relpath:t,source:"transcript",ts:e.ts,tsMs:e.tsMs,title:`[${e.role}] ${i.length>80?`${i.slice(0,80)}\u2026`:i}`,nodeName:n.name,nodeKind:n.kind,nodeStatus:n.status,nodeCwd:n.cwd,nodeDesc:s,loadBody:a(()=>e.text,"loadBody"),role:e.role};return e.origin!==void 0&&(o.origin=e.origin),e.from!==void 0&&(o.from=e.from),o}a(K,"transcriptArtifact");async function W(n){return(await p(n))?.description??""}a(W,"nodeDescOf");async function tn(n,s){const e=await P(n),t=s.kinds,i=s.statuses,o=e.filter(d=>!(t!==void 0&&t.length>0&&!t.includes(d.kind)||i!==void 0&&i.length>0&&!i.includes(d.status))),r=s.types!==void 0&&s.types.length>0?s.types:["inbox"],c=new Set(r),u=[];for(const d of o){const f=await W(d.node_id);if(c.has("inbox")&&await B(await k(d.node_id),async(l,m)=>u.push(await D(d,f,l,m))),c.has("transcript"))for(const l of await $(d.node_id))u.push(K(d,f,l))}return u.filter(d=>s.sinceMs!==void 0&&d.tsMs<s.sinceMs||s.untilMs!==void 0&&d.tsMs>s.untilMs?!1:G(d,s))}a(tn,"buildCorpus");function G(n,s){const{origins:e,roles:t,from:i}=s;return!(e!==void 0&&e.length>0&&(n.origin===void 0||!e.includes(n.origin))||t!==void 0&&t.length>0&&(n.role===void 0||!t.includes(n.role))||i!==void 0&&i!==""&&(n.from===void 0||!n.from.toLowerCase().includes(i.toLowerCase())))}a(G,"matchesMessageFilters");function sn(n,s){const e=new Map;for(const t of n){let i;switch(s){case"origin":i=t.origin;break;case"role":i=t.role;break;case"node":i=`${t.nodeName} (${t.nodeId})`;break;case"kind":i=t.nodeKind;break;case"type":i=t.source;break;case"day":i=t.ts.slice(0,10)||void 0;break}i===void 0||i===""||e.set(i,(e.get(i)??0)+1)}return[...e.entries()].map(([t,i])=>({key:t,count:i})).sort((t,i)=>i.count-t.count||t.key.localeCompare(i.key))}a(sn,"groupCorpus");async function P(n){const s=await j(),e=new Map(s.map(i=>[i.node_id,i]));if(n.nodes!==void 0&&n.nodes.length>0)return n.nodes.map(i=>e.get(i)).filter(i=>i!==void 0);if(n.under!==void 0&&n.under!=="")return[n.under,...await v(n.under)].map(o=>e.get(o)).filter(o=>o!==void 0);if(n.allCwds===!0)return s;const t=n.cwd!==void 0&&n.cwd!==""?n.cwd:await R();return s.filter(i=>i.cwd===t)}a(P,"scopedRows");async function on(n){const s=n.indexOf(":");if(s===-1)return null;const e=n.slice(0,s),t=n.slice(s+1),i=await p(e);if(i===null)return null;if(t.startsWith("inbox/")){const o=Number(t.slice(6)),r=(await k(e))[o];return r===void 0?null:{nodeId:e,relpath:t,source:"inbox",ts:r.ts,nodeName:i.name,body:await _(r),raw:null,path:null}}if(t==="session"||t.startsWith("session/")){const o=await N(e);if(o===null)return null;const r=await $(e);if(t==="session"){const d=r.map(f=>`## ${f.role}${f.origin!==void 0?` (origin: ${f.origin})`:""}
|
|
10
10
|
|
|
11
11
|
${f.text}`).join(`
|
|
12
12
|
|
|
13
|
-
`);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:
|
|
14
|
-
`).join("")})
|
|
13
|
+
`);return{nodeId:e,relpath:t,source:"transcript",ts:r[r.length-1]?.ts??i.created,nodeName:i.name,body:d,raw:a(async()=>{const{header:f,entries:l}=await g().read(y(o));return[f,...l].map(m=>`${JSON.stringify(m)}
|
|
14
|
+
`).join("")},"raw"),path:o}}const c=Number(t.slice(8)),u=r[c];return u===void 0?null:{nodeId:e,relpath:t,source:"transcript",ts:u.ts,nodeName:i.name,body:u.text,raw:a(()=>J(o,c),"raw"),path:o}}return null}a(on,"resolveRef");export{en as MESSAGE_ROLES,nn as ORIGIN_TOKENS,tn as buildCorpus,R as callerCwd,sn as groupCorpus,on as resolveRef};
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var J=Object.defineProperty;var
|
|
2
|
-
`).join(""),"encode")
|
|
3
|
-
`).filter(Boolean).map(e=>JSON.parse(e)),"decode"),N=
|
|
4
|
-
UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(e,e);return{parts:s.filter(a=>a.kind==="part").map(({seq:a,blob_key:t,bytes:r,entries:n,created:
|
|
5
|
-
`).subarray(c-t,d-t)),t+=
|
|
1
|
+
var J=Object.defineProperty;var _=(o,e)=>J(o,"name",{value:e,configurable:!0});import{randomUUID as v}from"node:crypto";import{existsSync as x,readFileSync as P,rmSync as Y}from"node:fs";import{join as V}from"node:path";import{SessionManager as G}from"@earendil-works/pi-coding-agent";import{blobStore as y}from"../blobs/index.js";import{openDb as E,withCanvasWrite as b}from"../canvas/db.js";import{appSpace as z}from"../layout.js";import{timedSpan as D}from"../logged-step-timings.js";import{addStepTiming as K}from"../step-timings.js";import{appendConversationEvents as M,rootRepromptPending as A}from"../../daemon/runs/append-section.js";import{ConversationNotFoundError as T}from"./index.js";const R="s.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC",C=_((o,e,s)=>`conversations/${o}/${e}/${s}.jsonl`,"keyFor"),W=_(o=>o.map(e=>JSON.stringify(e)+`
|
|
2
|
+
`).join(""),"encode"),$=_(o=>o.split(`
|
|
3
|
+
`).filter(Boolean).map(e=>JSON.parse(e)),"decode"),N=_(()=>new Date().toISOString(),"at");async function m(o,e,s=!1){const a=await o.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${R} LIMIT 1${s?" FOR UPDATE OF s":""}`).get(e);if(!a)throw new T(e);return a}_(m,"binding");async function h(o,e){return await o.prepare("SELECT seq, blob_key, bytes, entries, created FROM conversation_parts WHERE conversation_id = ? ORDER BY seq").all(e)}_(h,"parts");async function q(o,e){return await o.prepare("SELECT seq, body, bytes, created FROM conversation_entries WHERE conversation_id = ? ORDER BY seq").all(e)}_(q,"tail");async function H(o,e){const s=await o.prepare(`SELECT 'part' AS kind, seq, blob_key, NULL AS body, bytes, entries, created FROM conversation_parts WHERE conversation_id = ?
|
|
4
|
+
UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(e,e);return{parts:s.filter(a=>a.kind==="part").map(({seq:a,blob_key:t,bytes:r,entries:n,created:i})=>({seq:Number(a),blob_key:t,bytes:Number(r),entries:Number(n),created:i})),tail:s.filter(a=>a.kind==="tail").map(({seq:a,body:t,bytes:r,created:n})=>({seq:Number(a),body:t,bytes:Number(r),created:n}))}}_(H,"snapshot");const I=4*1024*1024,Q=4,X=16;async function*B(o,e,s){const a=[];let t=0;const r=_(()=>{for(;t<o&&a.length<s;){const n=e(t++);n.catch(()=>{}),a.push(n)}},"fill");for(r();a.length>0;){const n=await a.shift();r(),yield n}}_(B,"readAhead");async function S(o,e,s){const a=[];let t=0;const r=await y(),n=[];for(const i of o.parts){const c=Math.max(e,t),d=Math.min(s,t+i.bytes);c<d&&n.push({key:i.blob_key,range:{start:c-t,length:d-c}}),t+=i.bytes}for await(const i of B(n.length,async c=>{const d=await r.get(n[c].key,n[c].range);if(!d)throw new Error(`missing conversation object: ${n[c].key}`);return d},X))a.push(i);for(const i of o.tail){const c=Math.max(e,t),d=Math.min(s,t+i.bytes);c<d&&a.push(Buffer.from(i.body+`
|
|
5
|
+
`).subarray(c-t,d-t)),t+=i.bytes}return Buffer.concat(a)}_(S,"bytesOf");async function*k(o){const e=o.parts.reduce((a,t)=>a+t.bytes,0)+o.tail.reduce((a,t)=>a+t.bytes,0);let s="";for await(const a of B(Math.ceil(e/I),t=>S(o,t*I,Math.min(e,(t+1)*I)),Q)){const t=s+a.toString("latin1"),r=t.lastIndexOf(`
|
|
6
6
|
`);s=t.slice(r+1);for(const n of t.slice(0,r+1).split(`
|
|
7
|
-
`))n&&(yield Buffer.from(n,"latin1").toString("utf8"))}s&&(yield Buffer.from(s,"latin1").toString("utf8"))}
|
|
8
|
-
`).filter(Boolean).length-1),N())||!n?.run_id||n.event_offset===null)return;const w=n.source_session_id?[]:await M(
|
|
9
|
-
`);return
|
|
10
|
-
`)),path:r}}if(!s||
|
|
11
|
-
`);
|
|
12
|
-
`);return l>0&&w.shift(),{header:t,entries:c(
|
|
7
|
+
`))n&&(yield Buffer.from(n,"latin1").toString("utf8"))}s&&(yield Buffer.from(s,"latin1").toString("utf8"))}_(k,"linesOf");const U=new Map;async function j(o,e,s){const a=await E();if(await a.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(o)||!x(s))return;let t=P(s);const r=t.lastIndexOf(10);if(r<0)return;t=t.subarray(0,r+1);const n=await a.prepare("SELECT s.binding_id, s.node_id, s.event_offset, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY "+R+" LIMIT 1").get(o);let i=[];if(n?.run_id&&n.event_offset!==null){const u=Number(n.event_offset);if(t.length<u)throw new Error(`conversation shorter than indexed offset: ${o}`);i=$(t.subarray(u).toString("utf8")).filter(l=>l.type!=="session")}const c=n?.run_id?await A(n.run_id,n.node_id,i):!1,d=C(e,o,0);await(await y()).put(d,t),await b(async u=>{if(!await u.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING seq").get(o,d,t.length,Math.max(0,t.toString("utf8").split(`
|
|
8
|
+
`).filter(Boolean).length-1),N())||!n?.run_id||n.event_offset===null)return;const w=n.source_session_id?[]:await M(u,n.run_id,n.node_id,i,JSON.parse(n.input_ids_json),c);await u.prepare("UPDATE sessions SET event_offset = ?, indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(t.length,i.at(-1)?.id??null,JSON.stringify(w),n.binding_id)})}_(j,"importOne");async function L(o,e){const s=await e.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${R} LIMIT 1`).get(o),a=U.get(o);if(!s&&!a)throw new T(o);let t=(await h(e,o))[0];if(!t){const c=a?.path??s?.transcript_path??void 0;c&&await j(o,a?.node??s.node_id,c),t=(await h(e,o))[0]}if(!t||t.seq!==0)throw new T(o);const r=await(await y()).get(t.blob_key,{start:0,length:Math.min(t.bytes,256*1024)});if(!r)throw new Error(`missing conversation object: ${t.blob_key}`);const n=r.indexOf(10);if(n<0)throw new Error(`invalid conversation header: ${o}`);const i=JSON.parse(r.subarray(0,n).toString("utf8"));if(i.type!=="session"||i.id!==o)throw new Error(`invalid conversation header: ${o}`);return{header:i,path:s?.transcript_path??a?.path??"",binding:s}}_(L,"initial");function _e(){const o={async create(e,s,a,t){const r=await E(),n=await D("owner_read",async()=>await r.prepare("SELECT grantee, run_id FROM node_rows WHERE node_id = ?").get(e));if(!n)throw new Error(`missing conversation owner ${e}`);const i=s.id,c=V(z(n.grantee).conversations,e,`${s.timestamp.replace(/[:.]/g,"-")}_${i}.jsonl`),d=W([s,...a]),u=C(e,i,0),l=n.run_id?await A(n.run_id,e,a):!1;return K("blob_bytes",Buffer.byteLength(d)),await D("blob_put",async()=>await(await y()).put(u,d)),await D("transaction",()=>b(async w=>{if(await w.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ?").get(i))throw new Error(`conversation already exists: ${i}`);const p=N(),f=s.parentSession?await w.prepare("SELECT session_id FROM sessions WHERE transcript_path = ? LIMIT 1").get(s.parentSession):void 0;if(await w.prepare("INSERT INTO sessions (binding_id, session_id, node_id, transcript_path, source_session_id, fork_entry_id, created_at, bound_at, unbound_at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)").run(v(),i,e,c,f?f.session_id:null,p,p,p),await w.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(i,u,Buffer.byteLength(d),a.length,p),n.run_id&&!f){const g=await M(w,n.run_id,e,a,[],l);await w.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?").run(a.at(-1)?.id??null,JSON.stringify(g),i,e)}},{timingName:"create_tx"})),{conversation_id:i,path:c}},async append(e,s){if(!s.length)return;const a=await m(await E(),e),t=a.run_id?await A(a.run_id,a.node_id,s):!1;await b(async r=>{const n=await m(r,e,!0);if(!(await h(r,e)).length)throw new T(e);const i=[];for(const c of s){const d=JSON.stringify(c);if(await r.prepare("INSERT INTO conversation_entries (conversation_id, entry_id, body, bytes, execution_id, created) VALUES (?, ?, ?, ?, NULL, ?) ON CONFLICT (conversation_id, entry_id) DO NOTHING RETURNING entry_id").get(e,c.id,d,Buffer.byteLength(d)+1,N())&&(i.push(c),c.type==="custom"&&c.customType==="crtr-cycle")){await r.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0 FOR UPDATE").get(e);const l=[...await h(r,e),...await q(r,e)].reduce((w,p)=>w+Number(p.bytes),0)-Buffer.byteLength(d)-1;await r.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0").run(l,e)}}if(n.run_id&&i.length){const c=await M(r,n.run_id,n.node_id,i,JSON.parse(n.input_ids_json??"[]"),t);await r.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(i.at(-1).id,JSON.stringify(c),n.binding_id)}})},async readLines(e){const s=await E(),{path:a}=await L(e,s);return{path:a,lines:k(await H(s,e))}},async read(e,s){const a=await E(),{header:t,path:r}=await L(e,a),n=await H(a,e),i=n.parts.reduce((p,f)=>p+f.bytes,0)+n.tail.reduce((p,f)=>p+f.bytes,0),c=_(p=>$(p).filter(f=>f.type!=="session"),"entriesOf"),d=_(async()=>{const p=await a.prepare("SELECT cycle_offset FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(e);let f=p?.cycle_offset==null?null:Number(p.cycle_offset);if(f===null){f=0;let g=0;for await(const O of k(n)){if(O.includes('"crtr-cycle"')){const F=JSON.parse(O);F.type==="custom"&&F.customType==="crtr-cycle"&&(f=g)}g+=Buffer.byteLength(O)+1}await b(async O=>{await O.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0 AND cycle_offset IS NULL").run(f,e)})}return f},"cycleOffset");if(s==="cycle"){const p=await d();return{header:t,entries:c((await S(n,p,i)).toString("utf8")),path:r}}if(s&&"beforeCycle"in s){const p=await d(),f=Math.max(0,p-s.beforeCycle),g=(await S(n,f>0?f-1:0,p)).toString("utf8").split(`
|
|
9
|
+
`);return f>0&&g.shift(),{header:t,entries:c(g.join(`
|
|
10
|
+
`)),path:r}}if(!s||i<=s.head+s.tail){const p=[];for await(const f of k(n))p.push(...c(f));return{header:t,entries:p,path:r}}const u=(await S(n,0,Math.max(0,s.head))).toString("utf8").split(`
|
|
11
|
+
`);u.pop();const l=Math.max(0,i-s.tail),w=(await S(n,l>0?l-1:0,i)).toString("utf8").split(`
|
|
12
|
+
`);return l>0&&w.shift(),{header:t,entries:c(u.join(`
|
|
13
13
|
`)),tail:c(w.join(`
|
|
14
|
-
`)),path:r}},async header(e){const s=await E(),{header:a,path:t}=await L(e,s),r=await H(s,e);return{header:a,path:t,mtime:Date.parse(r.tail.at(-1)?.created??r.parts.at(-1).created),size:r.parts.reduce((n,
|
|
15
|
-
`).join("");return await(await y()).put(
|
|
14
|
+
`)),path:r}},async header(e){const s=await E(),{header:a,path:t}=await L(e,s),r=await H(s,e);return{header:a,path:t,mtime:Date.parse(r.tail.at(-1)?.created??r.parts.at(-1).created),size:r.parts.reduce((n,i)=>n+i.bytes,0)+r.tail.reduce((n,i)=>n+i.bytes,0)}},async list(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${R}`).all(),t=[];for(const r of a){if(e&&r.node_id!==e)continue;const n=await o.header(r.session_id);t.push({conversation_id:r.session_id,node_id:r.node_id,...n})}return t.sort((r,n)=>n.mtime-r.mtime)},async replace(e,s,a){if(s.id!==e)throw new Error("replacement header id differs from conversation id");const t=await E(),r=await m(t,e);if(r.run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const n=`conversations/${r.node_id}/${e}/0-${v()}.jsonl`,i=W([s,...a]);await(await y()).put(n,i);const c=await b(async d=>{if((await m(d,e,!0)).run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const l=await h(d,e);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(e,n,Buffer.byteLength(i),a.length,N()),l});for(const d of c)await(await y()).delete(d.blob_key)},async fork(e,s,a,t){const r=await o.read(e);let n=r.entries;if(a!==void 0){const i=G.inMemory(r.header.cwd,void 0,[r.header,...n]);i.createBranchedSession(a),n=i.getEntries()}return(await o.create(s??(await L(e,await E())).binding?.node_id??U.get(e).node,{...r.header,id:v(),timestamp:N(),cwd:t??r.header.cwd,parentSession:r.path},n)).conversation_id},async delete(e,s){const a=await E(),t=await h(a,e);await b(async r=>{await r.prepare("DELETE FROM sessions WHERE session_id = ?").run(e),await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await r.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e)});for(const r of t)await(await y()).delete(r.blob_key);s&&Y(s,{force:!0})},async commit(e){return await b(async s=>{const a=await m(s,e,!0),t=await q(s,e),r=await h(s,e);if(!t.length)return r.at(-1)?.seq??0;const n=(r.at(-1)?.seq??0)+1,i=C(a.node_id,e,n),c=t.map(d=>d.body+`
|
|
15
|
+
`).join("");return await(await y()).put(i,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await s.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,i,Buffer.byteLength(c),t.length,N()),await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(e,t.at(-1).seq),n})},async importLegacy(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id, s.transcript_path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ${e?"AND n.run_id = ?":""} ORDER BY s.session_id, ${R}`).all(...e?[e]:[]);for(const t of a)await j(t.session_id,t.node_id,t.transcript_path)},recover(e){for(const s of e)s.transcript_path&&U.set(s.session_id,{node:s.node_id,path:s.transcript_path})}};return o}_(_e,"createRowStore");function Z(o,e,s){const a=o.indexOf(10);if(a<0)throw new Error(`invalid conversation header: ${e}`);const t=JSON.parse(o.subarray(0,a).toString("utf8"));if(t.type!=="session"||t.id!==e)throw new Error(`invalid conversation header: ${e}`);const r=s(t.cwd);return r===t.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...t,cwd:r})),o.subarray(a)])}_(Z,"withHeaderCwd");async function ue(o,e,s){const a=await E(),t=await m(a,o),r=(await h(a,o))[0];if(!r||r.seq!==0)return!1;const n=await(await y()).get(r.blob_key);if(!n)throw new Error(`missing conversation object: ${r.blob_key}`);const i=Z(n,o,u=>u===e?s:u);if(i===null)return!1;const c=`conversations/${t.node_id}/${o}/0-${v()}.jsonl`;await(await y()).put(c,i);const d=await b(async u=>await u.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ?, cycle_offset = CASE WHEN cycle_offset > 0 THEN cycle_offset + ? - bytes ELSE cycle_offset END WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,i.length,i.length,o,r.blob_key)!==void 0);if(await(await y()).delete(d?r.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${o}`);return!0}_(ue,"relocateConversationHeader");export{_e as createRowStore,B as readAhead,ue as relocateConversationHeader,Z as withHeaderCwd};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - The sandbox user is \"crtr\"
|
|
1
|
+
export declare const STARTER_SETUP_SCRIPT = "#!/usr/bin/env bash\n# Setup script for a crtr cloud environment.\n#\n# How it runs\n# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.\n# - Your repositories are already checked out at /work/<repo name> before this runs.\n# - The sandbox user is \"crtr\". Files you create for it must be chowned to it. A node runs with HOME set to its app's home\n# (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.\n# - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,\n# with the token filled in from NODE_AUTH_TOKEN at run time. pnpm 12 ignores a token in a repository's own .npmrc, so do not rely on one.\n# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run `pnpm install` in a sandbox,\n# or install at build time below.\n# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.\n# - The image keeps /work, /home/crtr, /usr, /etc and /lib. Anything written to /root or /tmp is lost.\n#\n# Secrets (API keys, database URLs) do not belong here: anything written by this script is baked into the image. Store them on the profile\n# instead and every sandbox gets them as environment variables:\n# printf '%s' \"<value>\" | crtr profile env set <profile> --name OPENAI_API_KEY\n#\n# Apply this file with:\n# crtr profile environment set --profile <profile> --setup-script-file ./setup.sh\n# then watch the build with `crtr profile environment show --profile <profile>` (ready when image_revision equals recipe_revision).\n#\n# Uncomment the sections you need. Delete the rest.\n\nset -euo pipefail\n\n# \u2500\u2500 1. System packages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Alpine package names: https://pkgs.alpinelinux.org/packages\n# apk add --no-cache build-base python3 # native npm modules (node-gyp)\n# apk add --no-cache jq sqlite # command-line tools your agents use\n# apk add --no-cache chromium # headless browser tests\n\n# \u2500\u2500 2. A local Postgres \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# Creates a database cluster owned by crtr. Section 5 starts it on the agent's first shell command.\n# apk add --no-cache postgresql postgresql-contrib\n# mkdir -p /run/postgresql && chown crtr /run/postgresql\n# su crtr -c 'initdb -D /home/crtr/pg -U postgres --auth=trust'\n\n# \u2500\u2500 3. App dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# To install a repository's packages at build time:\n# (cd /work/<repo name> && npm ci)\n# (cd /work/<repo name> && pnpm install --frozen-lockfile)\n# Each full install can take 0.5-1.5 GB of the sandbox disk. Install only the repositories agents work in most.\n\n# \u2500\u2500 4. Global CLIs \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# npm install -g typescript tsx\n# curl -fsSL https://example.com/install.sh | sh\n\n# \u2500\u2500 5. Start services on the agent's first command \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# The agent's shell is non-interactive bash, which runs the file named by $BASH_ENV before each command. Write a start script here, then\n# set BASH_ENV on the profile: printf '%s' /home/crtr/.services-up.sh | crtr profile env set <profile> --name BASH_ENV\n# cat > /home/crtr/.services-up.sh <<'UP'\n# pg_ctl -D /home/crtr/pg status >/dev/null 2>&1 || pg_ctl -D /home/crtr/pg -o \"-k /tmp -h localhost\" -l /tmp/pg.log -w start >/dev/null 2>&1 || true\n# UP\n# chown crtr /home/crtr/.services-up.sh\n\n# \u2500\u2500 6. Seed files and config \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n# cp /work/<repo name>/.env.example /work/<repo name>/.env # placeholders only; real values come from `crtr profile env`\n# chown -R crtr /work/<repo name>\n";
|
|
@@ -4,7 +4,10 @@ const e=`#!/usr/bin/env bash
|
|
|
4
4
|
# How it runs
|
|
5
5
|
# - Once per image build, as root, in /work, on Alpine Linux (use apk, not apt). Every sandbox of the profile starts from the result.
|
|
6
6
|
# - Your repositories are already checked out at /work/<repo name> before this runs.
|
|
7
|
-
# - The sandbox user is "crtr"
|
|
7
|
+
# - The sandbox user is "crtr". Files you create for it must be chowned to it. A node runs with HOME set to its app's home
|
|
8
|
+
# (/var/lib/crtr/apps/<app>/home, created at run time), not /home/crtr, so dotfiles written to /home/crtr are not read through ~.
|
|
9
|
+
# - Private GitHub Packages (@northlight-systems) already work: /home/crtr/.npmrc holds the auth line and NPM_CONFIG_USERCONFIG points at it,
|
|
10
|
+
# with the token filled in from NODE_AUTH_TOKEN at run time. pnpm 12 ignores a token in a repository's own .npmrc, so do not rely on one.
|
|
8
11
|
# - Already done for you: git, gh, curl, ripgrep, Node 24, pnpm. Packages are not pre-installed: run \`pnpm install\` in a sandbox,
|
|
9
12
|
# or install at build time below.
|
|
10
13
|
# - Output goes to /work/.crtr/setup.log in the image. If this script exits non-zero, sandboxes refuse to start and point at that log.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var f=Object.defineProperty;var n=(t,i)=>f(t,"name",{value:i,configurable:!0});import{randomUUID as m}from"node:crypto";import{afterCommit as w,openDb as s}from"../canvas/db.js";import{personIdAsync as E,runAsPerson as h}from"../canvas/person.js";import{personHasSnapshot as S}from"../scoped-state/person-store.js";import{loadPersonSettings as y}from"../scoped-state/person-rows.js";import{directoryIssuer as p}from"../directory/issuer.js";import{emitEvent as l}from"../events/emit.js";import{describeOutboundFailure as A,outboundFetch as g,outboundJson as k,outboundRefusal as _}from"../events/outbound.js";import{mintDirectoryToken as T}from"../grants/sync.js";const O=5e3,D=10*6e4,R=5e3,N=1e4,u=new Map;async function L(t){if(p()===null)return null;const i=await E(),a=t.id??m();return await(await s()).prepare(`INSERT INTO credential_activations(activation_id,person,kind,provider,activated_at) VALUES(?,?,?,?,?)${t.idempotent?" ON CONFLICT (activation_id) DO NOTHING":""}`).run(a,i,t.kind,t.provider,new Date().toISOString()),w(()=>{v(a).catch(()=>{})}),a}n(L,"recordActivation");async function J(t,i,a,e){return h(t,async()=>(S()||await y(t),L({kind:i,provider:a,id:e,idempotent:e!==void 0})))}n(J,"recordCredentialActivation");async function K(t){return await(await s()).prepare("SELECT 1 FROM credential_activations WHERE activation_id=?").get(t)!==void 0}n(K,"activationRecorded");function M(t){return Math.min(D,O*2**Math.max(0,t-1))}n(M,"backoffMs");function v(t){let i=u.get(t);return i||(i=b(t).finally(()=>u.delete(t)),u.set(t,i)),i}n(v,"deliverActivation");async function b(t){const i=p();if(i===null)throw new Error("credential activation needs a directory-connected runtime");const a=await s(),e=await a.prepare("SELECT activation_id,person,kind,provider,activated_at FROM credential_activations WHERE activation_id=?").get(t);if(!e)throw new Error(`no credential activation ${t}`);await a.prepare("UPDATE credential_activations SET attempts=attempts+1, last_attempt_at=? WHERE activation_id=?").run(new Date().toISOString(),t);const r=`${i}/v1/runtime/credential-activations`;try{const o=await T(i),d=await g("credential_activation",r,{method:"POST",headers:{Authorization:`Bearer ${o.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({activation_id:e.activation_id,user_id:e.person,kind:e.kind,provider:e.provider,activated_at:e.activated_at}),signal:AbortSignal.timeout(1e4)});if(d.status===400)throw await a.prepare("DELETE FROM credential_activations WHERE activation_id=? AND acknowledged_at IS NULL").run(t),l({level:"warn",event:"model_auth.activation.rejected",fields:{activation_id:t,kind:e.kind,provider:e.provider}}),_("credential_activation",r,"directory rejected the credential activation: 400");if(!d.ok)throw _("credential_activation",r,`directory refused the credential activation: ${d.status}`);const c=await k("credential_activation",r,d);if(c.trial!=="closed"&&c.trial!=="not_active")throw new TypeError(`directory answered the credential activation without a trial state: ${JSON.stringify(c.trial)}`);return await a.prepare("UPDATE credential_activations SET acknowledged_at=? WHERE activation_id=? AND acknowledged_at IS NULL").run(new Date().toISOString(),t),l({level:"info",event:"model_auth.activation.acknowledged",fields:{activation_id:t,kind:e.kind,provider:e.provider,trial:c.trial}}),c.trial}catch(o){throw l({level:"warn",event:"model_auth.activation.delivery_failed",error:o,fields:{activation_id:t,...A(o)}}),o}}n(b,"attempt");async function V(t,i=N){let a;const e=new Promise(r=>{a=setTimeout(()=>r({status:"pending"}),i)});try{return await Promise.race([v(t).then(r=>({status:"acknowledged",trial:r}),()=>({status:"pending"})),e])}finally{clearTimeout(a)}}n(V,"awaitActivationAck");async function F(t=Date.now()){if(p()===null)return 0;const i=await(await s()).prepare("SELECT activation_id,attempts,last_attempt_at FROM credential_activations WHERE acknowledged_at IS NULL ORDER BY activated_at").all();let a=0;for(const e of i)u.has(e.activation_id)||e.last_attempt_at!==null&&Date.parse(e.last_attempt_at)+M(Number(e.attempts))>t||(v(e.activation_id).catch(()=>{}),a++);return a}n(F,"sweepActivations");function z(t=R){let i=!1;const a=n(()=>{i||(i=!0,F().catch(r=>l({level:"error",event:"model_auth.activation.sweep_failed",error:r})).finally(()=>{i=!1}))},"tick"),e=setInterval(a,t);return e.unref(),a(),()=>clearInterval(e)}n(z,"startActivationDelivery");export{O as BASE_BACKOFF_MS,D as MAX_BACKOFF_MS,K as activationRecorded,V as awaitActivationAck,v as deliverActivation,L as recordActivation,J as recordCredentialActivation,z as startActivationDelivery,F as sweepActivations};
|
|
@@ -25,6 +25,9 @@ export declare const SETUP_SCRIPT_FILE = "recipe-setup.sh";
|
|
|
25
25
|
/** The run user's npmrc. pnpm 12 ignores an env-expanded `_authToken` in a repository's `.npmrc`, so the GitHub Packages auth line lives here; it names the
|
|
26
26
|
* variable, never its value. `store-dir` pins one pnpm store in the image that every repository's `pnpm install` links from. */
|
|
27
27
|
export declare const RUN_USER_NPMRC: string[];
|
|
28
|
+
/** A node runs with HOME set to its app's home (`/var/lib/crtr/apps/<app>/home`), not `/home/crtr`, so npm and pnpm would never read the npmrc above;
|
|
29
|
+
* this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
|
|
30
|
+
export declare const RUN_USER_NPMRC_ENV = "ENV NPM_CONFIG_USERCONFIG=/home/crtr/.npmrc";
|
|
28
31
|
export declare const REPOS_DIR = "repos";
|
|
29
32
|
/** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
|
|
30
33
|
export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var j=Object.defineProperty;var c=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as
|
|
1
|
+
var j=Object.defineProperty;var c=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as v,lstatSync as z,mkdirSync as W,readFileSync as V,readdirSync as J,readlinkSync as X,rmSync as Z,writeFileSync as _}from"node:fs";import{join as E,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",ot="ghcr.io/blaxel-ai/sandbox:latest",p="crtr",D="/var/lib/crtr/recipe-pi-agent",st="blaxel.toml",it=`[build]
|
|
2
2
|
slim = false
|
|
3
|
-
`,at="1.1.0",
|
|
4
|
-
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${G} 2>&1 || echo ${
|
|
5
|
-
`)}c(
|
|
6
|
-
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&
|
|
3
|
+
`,at="1.1.0",b="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${p}/.local/share/pnpm/store`],lt=`ENV NPM_CONFIG_USERCONFIG=/home/${p}/.npmrc`,B=c(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${p}/.npmrc`,"writeRunUserNpmrc"),N="repos",G="/work/.crtr/setup.log",C="/work/.crtr/setup-failed",M="/usr/local/bin/gh",pt=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],L=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),ut=c(t=>(t??"").split(`
|
|
4
|
+
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${G} 2>&1 || echo ${L(t)} "exited $?" >> ${C}`,"guarded");function dt(t,r,i=!1){const s=ut(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${pt.map(L).join(" ")} > ${M} && chmod 755 ${M}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${D} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${C} ${G}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${N}/ /work/`),s.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${b} /tmp/${b}`),e.push("WORKDIR /work"),e.push(`RUN ${B()}`);for(const o of s)e.push($(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${D} pi install ${L(o)}`));a&&e.push($("setup script",`bash /tmp/${b}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision`)),e.push("",...n);for(const o of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${B()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(lt,`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
|
|
5
|
+
`)}c(dt,"recipeDockerfile");const ht=c((t,r,i)=>new Promise((s,a)=>{const n=q("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function Ut(t){const r=t.git??ht,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(E(t.dir,N),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),E(N,n.name)],a,t.dir)}_(E(t.dir,st),it),_(E(t.dir,"Dockerfile"),dt(t.recipe,t.revision,i!==null)),i!==null&&_(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
|
|
6
|
+
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&_(E(t.dir,b),t.recipe.setup_script.endsWith(`
|
|
7
7
|
`)?t.recipe.setup_script:`${t.recipe.setup_script}
|
|
8
|
-
`)}c(
|
|
8
|
+
`)}c(Ut,"prepareBuildDir");function F(t,r,i){for(const s of J(r).sort()){const a=E(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(X(a)),mode:v.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:V(a),mode:v.S_IFREG|n.mode&511})}}c(F,"walk");function ft(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),g=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE(g.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=u.length+d.length+g.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ft,"zipDirectory");async function R(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(R,"api");async function H(t,r){const{status:i,json:s}=await R(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(H,"getImage");async function xt(t,r){await R(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(xt,"deleteImage");const mt=60*6e4;async function Nt(t,r,i,s={}){const a=s.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(f=>f.name)),g=c(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...g(o)),l=(await R(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ft(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const O=s.timeoutMs??mt,K=e+O;let T=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,k=g(f).filter(m=>m>I).sort((m,x)=>m-x);if(h==="BUILT"&&k.length>=2){T??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],S=c(w=>Date.parse(w??"")>=x,"touchedSince"),y=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),A=n()-T>=(s.tagGraceMs??6e4),P=(y.length>0?y:A?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${r}:${P}`,buildMs:n()-e};if(A)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(h==="FAILED"||h==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${h.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${O} ms (last status ${h??"none"})`);await a(s.pollMs??3e3)}}c(Nt,"buildImage");const Lt=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{it as BLAXEL_TOML,st as BLAXEL_TOML_FILE,mt as BUILD_TIMEOUT_MS,M as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,D as RECIPE_PI_AGENT_DIR,N as REPOS_DIR,p as RUN_USER,ct as RUN_USER_NPMRC,lt as RUN_USER_NPMRC_ENV,ot as SANDBOX_API_IMAGE,C as SETUP_FAILED_FILE,G as SETUP_LOG_FILE,b as SETUP_SCRIPT_FILE,Nt as buildImage,xt as deleteImage,Lt as environmentImageName,H as getImage,Ut as prepareBuildDir,dt as recipeDockerfile,Rt as removeBuildDir,ft as zipDirectory};
|
|
@@ -3,6 +3,6 @@ content-type: application/json; charset=utf-8\r
|
|
|
3
3
|
content-length: ${Buffer.byteLength(m)}\r
|
|
4
4
|
connection: close\r
|
|
5
5
|
\r
|
|
6
|
-
`+m;try{r.end(p)}catch{try{r.destroy()}catch{}}}i(g,"refuseUpgrade");function re(r,e){const{status:a,body:n}=me(e);g(r,a,"Refused",n.error.code,n.error.message)}i(re,"refuseWithError");function He(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const a=r.headers["x-crtr-attach-revive"];return(Array.isArray(a)?a[0]:a)==="0"}i(He,"reviveOptedOut");function Le(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Le,"wakeParkedRequested");function te(r){return r===1e3||r===1001||r===1005}i(te,"isCleanViewerClose");function _(r,e,a){a.catch(n=>M({level:"error",event:e,node_id:r,error:n}))}i(_,"detach");async function ne(r){const e=await Be(r);return e===null||e.runner==="process"?{kind:"unix",path:he(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Te(e.executionId,Date.now()),await Ce(e.executionId)),Oe(e.runner).viewerAddress(e))}i(ne,"brokerViewAddress");function ze(r,e){return e.kind==="machine"?Ne(e.environmentId,r):e.kind==="wss"?Me(e.url,e.headers):xe(r)}i(ze,"connectBrokerView");function Je(r,e,a){return e.kind==="wss"?G(e.url,e.headers,void 0,a):Re(r,a)}i(Je,"probeBrokerView");async function je(r,e,a,n,c){const m=[];let p=i(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>p(t)),!K(e)){c?.destroy();try{r.close(1008,U(`invalid node id: ${e}`))}catch{}return}if(await Q(e)===null){c?.destroy();try{r.close(1011,U(`no node ${e}`))}catch{}return}const u=performance.now();await R(e,{link:"viewer\u2194crtrd"});const b=performance.now(),o=c??ze(e,a),f=i(()=>Math.round((performance.now()-b)*10)/10,"sinceOpen"),h=i((t,
|
|
7
|
-
`)?
|
|
6
|
+
`+m;try{r.end(p)}catch{try{r.destroy()}catch{}}}i(g,"refuseUpgrade");function re(r,e){const{status:a,body:n}=me(e);g(r,a,"Refused",n.error.code,n.error.message)}i(re,"refuseWithError");function He(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const a=r.headers["x-crtr-attach-revive"];return(Array.isArray(a)?a[0]:a)==="0"}i(He,"reviveOptedOut");function Le(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Le,"wakeParkedRequested");function te(r){return r===1e3||r===1001||r===1005}i(te,"isCleanViewerClose");function _(r,e,a){a.catch(n=>M({level:"error",event:e,node_id:r,error:n}))}i(_,"detach");async function ne(r){const e=await Be(r);return e===null||e.runner==="process"?{kind:"unix",path:he(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Te(e.executionId,Date.now()),await Ce(e.executionId)),Oe(e.runner).viewerAddress(e))}i(ne,"brokerViewAddress");function ze(r,e){return e.kind==="machine"?Ne(e.environmentId,r):e.kind==="wss"?Me(e.url,e.headers):xe(r)}i(ze,"connectBrokerView");function Je(r,e,a){return e.kind==="wss"?G(e.url,e.headers,void 0,a):Re(r,a)}i(Je,"probeBrokerView");async function je(r,e,a,n,c){const m=[];let p=i(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>p(t)),!K(e)){c?.destroy();try{r.close(1008,U(`invalid node id: ${e}`))}catch{}return}if(await Q(e)===null){c?.destroy();try{r.close(1011,U(`no node ${e}`))}catch{}return}const u=performance.now();await R(e,{link:"viewer\u2194crtrd"});const b=performance.now(),o=c??ze(e,a),f=i(()=>Math.round((performance.now()-b)*10)/10,"sinceOpen"),h=i((t,l={})=>{M({level:"info",event:"daemon.timing.bridge_channel",node_id:e,fields:{step:t,address_kind:a.kind,channel:o.channel??"",since_open_ms:f(),since_bridge_start_ms:Math.round((performance.now()-u)*10)/10,...l}})},"bridgeMark");c===void 0&&h("channel_opened");const A=new ke(_e);let k=!1,$=!1,B,H=!1,L=!1,S,z=!1,T="controller",J=Promise.resolve(),C=!1;const O=[];let V=!1,N=!1,j=!1,x=0;const q=i(()=>{c===void 0&&h("channel_connected"),H=!0,!k&&C&&_(e,"daemon.bridge.presence_failed",Y(e,r)),_(e,"daemon.bridge.connect_failed",R(e,{link:"relay\u2194broker"}))},"onBrokerConnect");c===void 0&&o.on("connect",q);const y=i((t,l,s=!1)=>{if(!k){if(k=!0,_(e,"daemon.bridge.presence_failed",s?Fe(e,r):Pe(e,r)),B?.stop(),!o.destroyed)try{o.destroy()}catch{}try{r.close(t,U(l))}catch{}}},"teardown");B=Ue(r,I,a.kind==="machine"?1/0:ee);const oe=i(async t=>{B?.noteActivity();let l;const s=performance.now();try{l=A.push(t)}catch(w){const E=w instanceof ve?`broker sent an oversized frame (${w.message})`:`failed to decode a broker frame for ${e}`;y(1009,E);return}!N&&l.some(w=>w?.type==="welcome")&&(N=!0,x=performance.now(),h("welcome_decoded",{decode_ms:Math.round((x-s)*10)/10,chunk_bytes:t.length,since_hello_ms:S===void 0?-1:Math.round((x-S)*10)/10})),O.push(...l),V||await ie()},"onData"),ie=i(async()=>{V=!0;try{for(;O.length>0&&!k;){const t=O.splice(0),l=N&&!j&&t.some(d=>d?.type==="welcome"),s=performance.now();let w;try{w=await n(T),l&&(j=!0,h("welcome_authorized",{auth_ms:Math.round((performance.now()-s)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}catch(d){M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:d}),y(1011,"revoked");return}if(k)return;if(!w){y(1008,"revoked");return}let E=!1;for(const d of t){if(r.readyState!==r.OPEN)continue;const v=d?.type==="welcome",P=performance.now();r.send(JSON.stringify(d)),v&&(E=!0,h("welcome_forwarded",{send_ms:Math.round((performance.now()-P)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}if(C&&E)try{await We(e,r)&&await Se(e)}catch(d){M({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:d})}}}finally{V=!1}},"drainOutbound");o.on("data",t=>_(e,"daemon.bridge.data_failed",oe(t)));const ae=i(async t=>{const l=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const s=W("relay\u2194broker",t);await D(e,{link:"relay\u2194broker",op:"bridge socket",kind:s.kind,retry:s.disposition==="fatal"?{disposition:"fatal"}:{disposition:"auto",by:"client"},message:t.message})}finally{y(1011,l,!0)}},"onSocketError");o.on("error",t=>_(e,"daemon.bridge.socket_error_failed",ae(t)));const ce=i(async t=>{if(!(k||t))try{await R(e,{link:"relay\u2194broker"})}finally{y(1e3,"broker socket closed",!0)}},"onSocketClose");o.on("close",t=>_(e,"daemon.bridge.socket_close_failed",ce(t)));const se=i(async(t,l)=>{const s=l.toString("utf8");if(k){te(t)&&await R(e,{link:"viewer\u2194crtrd"});return}try{if(te(t))await R(e,{link:"viewer\u2194crtrd"});else if(!$){$=!0;const w=W("viewer\u2194crtrd",{code:t,reason:s});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:w.kind,retry:{disposition:"auto"},message:s||`remote attach closed (${t})`})}}finally{y(t,s||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,l)=>_(e,"daemon.bridge.ws_close_failed",se(t,l)));const le=i(async()=>{try{if(!$){$=!0;const t=W("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{y(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>_(e,"daemon.bridge.ws_error_failed",le())),p=i(t=>{if(k||o.destroyed)return;B?.noteActivity();const s=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!L)try{const v=JSON.parse(s);v?.type==="hello"&&(h("hello_received"),S=performance.now(),L=!0,T=v.role==="observer"?"observer":"controller",C=v.attends!==!1,C&&H&&_(e,"daemon.bridge.presence_failed",Y(e,r)))}catch{}const w=s.endsWith(`
|
|
7
|
+
`)?s:s+`
|
|
8
8
|
`,E=i(()=>{try{o.write(w)}catch{}},"write"),d=S===void 0?!1:z===!1;d&&(z=!0),J=J.then(async()=>{if(k)return;const v=performance.now(),P=await n(T);d&&h("hello_authorized",{auth_ms:Math.round((performance.now()-v)*10)/10,since_hello_ms:Math.round((performance.now()-S)*10)/10}),P?(E(),d&&h("hello_written",{since_hello_ms:Math.round((performance.now()-S)*10)/10})):y(1008,"revoked")}).catch(v=>{M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:v}),y(1011,"revoked")})},"relayMessage");for(const t of m.splice(0))p(t);c!==void 0&&(c.destroyed?y(1011,`no running broker for ${e}`,!0):q())}i(je,"bridgeConnection");async function hr(r,e,a,n,c){await Ae("attach_upgrade",{node:n},r,()=>qe(r,e,a,n,c))}i(hr,"handleAttachUpgrade");async function qe(r,e,a,n,c){const m=we(),p=m===void 0?c:o=>pe(m,()=>c(o));e.on("error",()=>{});let u,b=!1;try{if(!K(n)){g(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await F("admission",async()=>await Q(n)===null)){g(e,404,"Not Found","node_not_found",`no node ${n}`);return}let o;if(He(r)){o=await ne(n);let f;if(o.kind==="machine"?(u=await X(o.environmentId,n,void 0,250)??void 0,f=u!==void 0):f=await Je(n,o,o.kind==="wss"?Z:250),!f){g(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let f;try{const A=await F("revive_decision",async()=>await Ee(n,{resume:!0,capacity:"refuse"},Le(r)));if(A.parked){g(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}f=A.result.launch?.exited}catch(A){re(e,A);return}if(o=await F("address_lookup",async()=>await ne(n)),o.kind==="machine"&&(u=await X(o.environmentId,n,f,Z)??void 0),!(o.kind==="machine"?u!==void 0:o.kind==="wss"?await G(o.url,o.headers,f):await $e(n,f))){o.kind==="machine"?re(e,de(`the broker for ${n} on its machine did not accept a viewer after revive`)):g(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;be("upgrading"),De.handleUpgrade(r,e,a,f=>{b=!0,_(n,"daemon.bridge.connection_failed",je(f,n,o,p,u).catch(h=>{throw u?.destroy(),h}))})}catch(o){const f=o instanceof Error?o.message:String(o);if(Ve(o)){g(e,400,"Bad Request","invalid_request",f);return}g(e,500,"Internal Server Error","internal",`attach upgrade failed: ${f}`)}finally{b||u?.destroy()}}i(qe,"attachUpgrade");export{I as REMOTE_ATTACH_HEARTBEAT_MS,ee as REMOTE_ATTACH_QUIET_MS,hr as handleAttachUpgrade,te as isCleanViewerClose,g as refuseUpgrade,Ue as startRemoteAttachHeartbeat};
|
|
@@ -3,7 +3,7 @@ var Q=Object.defineProperty;var u=(t,e)=>Q(t,"name",{value:e,configurable:!0});i
|
|
|
3
3
|
`).forEach((c,b)=>{l.test(c)&&r.push({ref:p.ref,node:`${p.nodeName} (${p.nodeId})`,ts:p.ts,line:b+1,text:c.trim()})});r.sort((p,n)=>p.ref.localeCompare(n.ref)||p.line-n.line);const m=r.slice(a,a+s),f=a+s<r.length?x(a+s):null;return{status:200,body:{hits:m,next_cursor:f,total:r.length}}}u(Me,"handleHistoryGrep");async function Ae(t){const e=Ie(t.body),s=(e.query??"").trim(),o=e.weigh_body===!0,a=e.full===!0,l=Math.max(1,e.snippet_lines??1),r=Math.min(100,Math.max(1,e.limit??20)),m=e.per_node===!0;if(m&&(e.nodes===void 0||e.nodes.length===0))throw new T(400,"invalid_request","`per_node` requires a non-empty `nodes` list",{param:"nodes"});const f=await L(e,t),h=e.cursor!==void 0?H(e.cursor):0,p=s.toLowerCase().split(/\s+/).filter(i=>i.length>0);let n=f,c;const b=e.sort??(p.length>0?"relevance":"recency");if(p.length>0&&b==="relevance"){c=new Map;const i=[];for(const _ of f){const E=_.title.toLowerCase(),K=_.nodeName.toLowerCase(),V=_.nodeDesc.toLowerCase(),$=o?_.loadBody().toLowerCase():null;let k=0;for(const I of p)E.includes(I)&&(k+=10),K.includes(I)&&(k+=5),V.includes(I)&&(k+=3),$!==null&&$.includes(I)&&(k+=1);k>0&&(c.set(_.ref,k),i.push(_))}n=i}else p.length>0&&(n=f.filter(i=>{const _=`${i.title}
|
|
4
4
|
${i.nodeName}
|
|
5
5
|
${i.nodeDesc}${o?`
|
|
6
|
-
`+i.loadBody():""}`.toLowerCase();return p.some(E=>_.includes(E))}));let d=je(n,b,c);if(m){const i=new Set;d=d.filter(_=>!i.has(_.nodeId)&&i.add(_.nodeId))}const g=m?d:d.slice(h,h+r),w=!m&&h+r<d.length?x(h+r):null;return{status:200,body:{hits:g.map(i=>{const _={ref:i.ref,node:`${i.nodeName} (${i.nodeId})`,kind:i.nodeKind,source:i.source,ts:i.ts,...m?{node_id:i.nodeId}:{}};return b==="relevance"&&c!==void 0&&(_.score=c.get(i.ref)??0),a?_.body=i.loadBody():_.snippet=Oe(i,p,l),_}),next_cursor:w,total:d.length}}}u(Ae,"handleHistorySearch");async function Te(t){const e=(t.query.get("ref")??"").trim();if(!e.includes(":"))throw y(`ref must be <node-id>:inbox/<n>, <node-id>:session, or <node-id>:session/<n>; received: ${e}`,{received:e,next:"Get a valid ref from `crtr canvas history search`. Reports and documents are `crtr canvas read <name>`."});const s=await ce(e);if(s===null)throw me(`no inbox entry or message for ref: ${e}`,{ref:e,next:"Re-run `crtr canvas history search` for a current ref. Reports and documents are `crtr canvas read <name>`."});if((await v(t))?.has(s.nodeId)===!1)throw new T(404,"not_found","artifact not found");const o=s.source,l=t.query.get("format")==="raw"
|
|
6
|
+
`+i.loadBody():""}`.toLowerCase();return p.some(E=>_.includes(E))}));let d=je(n,b,c);if(m){const i=new Set;d=d.filter(_=>!i.has(_.nodeId)&&i.add(_.nodeId))}const g=m?d:d.slice(h,h+r),w=!m&&h+r<d.length?x(h+r):null;return{status:200,body:{hits:g.map(i=>{const _={ref:i.ref,node:`${i.nodeName} (${i.nodeId})`,kind:i.nodeKind,source:i.source,ts:i.ts,...m?{node_id:i.nodeId}:{}};return b==="relevance"&&c!==void 0&&(_.score=c.get(i.ref)??0),a?_.body=i.loadBody():_.snippet=Oe(i,p,l),_}),next_cursor:w,total:d.length}}}u(Ae,"handleHistorySearch");async function Te(t){const e=(t.query.get("ref")??"").trim();if(!e.includes(":"))throw y(`ref must be <node-id>:inbox/<n>, <node-id>:session, or <node-id>:session/<n>; received: ${e}`,{received:e,next:"Get a valid ref from `crtr canvas history search`. Reports and documents are `crtr canvas read <name>`."});const s=await ce(e);if(s===null)throw me(`no inbox entry or message for ref: ${e}`,{ref:e,next:"Re-run `crtr canvas history search` for a current ref. Reports and documents are `crtr canvas read <name>`."});if((await v(t))?.has(s.nodeId)===!1)throw new T(404,"not_found","artifact not found");const o=s.source,l=(t.query.get("format")==="raw"?await s.raw?.():null)??s.body;return{status:200,body:{ref:e,node:`${s.nodeName} (${s.nodeId})`,source:o,ts:s.ts,content:l}}}u(Te,"handleHistoryRead");function Le(t){for(const[o]of t.query)if(o!=="live")throw y(`unknown snapshot query parameter: ${o}`);const e=t.query.getAll("live");if(e.length>1)throw y("live must appear at most once");const s=e[0];if(s===void 0||s==="false"||s==="0")return!1;if(s==="true"||s==="1")return!0;throw y("live must be true or false")}u(Le,"snapshotLiveOnly");async function $e(t){const e=new Set((await P()).map(n=>n.node_id)),s=await v(t),o=(await se(G,e,Le(t))).filter(n=>s===null||s.has(n.node_id)),a=await M(o.map(n=>n.node_id));await re(G,o,a);const l=await te(o.map(n=>n.node_id)),r=await J(o,async n=>{const c=n.srcRow,b=c?.host_kind??"tmux";return{node_id:n.node_id,name:n.name,title:n.handle??n.name,description:n.description??null,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle??c?.lifecycle,status:n.status,cwd:n.cwd,profile_id:n.profile_id??null,parent:c?.parent??null,created:n.created,host_kind:b,enterable:b==="broker",attention_count:n.asks,...c?.cycles!=null?{cycles:c.cycles}:{},...n.mtimeMs!==void 0?{last_activity:new Date(n.mtimeMs).toISOString()}:{},ctx_tokens:n.ctx_tokens,streaming:n.streaming??!1,jobs_active:c!==void 0&&oe(c.pi_pid)?(await ne(await A(),n.node_id)).length:0,waiting_for:l.get(n.node_id)?.controllerId??null,hanging:n.hanging??null,viewed:n.viewed??!1,final_report:c?.final_report??null,finalized_at:c?.finalized_at??null}}),m=new Map;for(const n of await N(s)){const c=m.get(n.from_id);c===void 0?m.set(n.from_id,[n.to_id]):c.push(n.to_id)}const f=new Set(o.map(n=>n.node_id)),h=Object.fromEntries(o.map(n=>[n.node_id,(m.get(n.node_id)??[]).filter(c=>f.has(c))]));return{status:200,body:{generated_at:O(),nodes:r,subscriptions:h}}}u($e,"handleSnapshot");function U(t){const e=t.host_kind??"tmux";return{node_id:t.node_id,name:t.name,kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,host_kind:e,enterable:e==="broker",parent:t.parent,created:t.created,description:t.description}}u(U,"toRosterNodeDTO");async function De(){const t=(await F()).map(U),e=(await N()).map(o=>({from_id:o.from_id,to_id:o.to_id,active:o.active,created:o.created})),s=(await B()).map(o=>({node_id:o.nodeId,object_id:o.objectId,object_type:o.objectType,object_name:o.objectName,created:new Date(o.createdAt).toISOString()}));return{generated_at:O(),nodes:t,edges:e,object_waits:s}}u(De,"buildRoster");async function Fe(t){const e=t.params.id,o=(await(await A()).prepareUncached(`WITH RECURSIVE up(id) AS (
|
|
7
7
|
SELECT CAST(? AS text)
|
|
8
8
|
UNION
|
|
9
9
|
SELECT w.watcher FROM up JOIN watches w ON w.object = up.id AND w.in_tree = 1
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`):""}h(ge,"messageText");function B(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(B,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}h(ve,"boundedRuntimeReason");class we{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=J();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=h((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=k(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=x();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=B(i)?be(i):"reload";B(i)||E({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=N();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=x();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(b=void 0);for(const a of d)M(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return b===this&&b.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=N().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),z()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new H(e,i),this.clearTimer(),E({level:"error",event:t,outcome:"failed",error:i,error_class:T(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof H)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,E({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:T(i),fields:{stage:"poll"}});return}if(se(i)){this.clearTimer(),E({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),D()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(l=>l.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const l=a.entry.entry_id;this.claims.has(l)||(a.entry=ee(a.entry,t),this.claims.set(l,a),a.handoff==="inherited"&&!i?y.fresh(o=>{this.pendingHandoffs.push({...I([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=x();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||U()||this.pendingHandoffs.length>=_||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&w()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=w()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&w()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(f=>f.entry_id)),s=new Set(i.map(f=>f.entry_id)),d=t.filter(f=>n.has(f.entry_id)||s.has(f.entry_id)),a=this.isIdle()&&d.length>0&&d.every(f=>f.tier==="deferred"),l=this.visibleRoute(i)==="critical",o=!a&&!l&&e.length>0,c=!a&&!l&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(c)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await Q(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...V(n));return i}digest(t,e){try{return L(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=_&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=I(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{y.fresh(o=>{a=o,v({level:"info",event:"inbox.delivery.started",operation_id:o,fields:g(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),F(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const l={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(l),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&M(l,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",l=a===void 0||i.length===0?void 0:k(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,c)=>{const f=s&&c===i.length-1;this.pi.sendMessage({customType:C,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:f?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,l)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:C,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(l=>l.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?k(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(o=p)});const c=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||c.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const f=this.digest(c,i),m=f.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(w()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of f){const p=I(u.entries,"visible");y.fresh(R=>{v({level:"info",event:"inbox.delivery.started",operation_id:R,fields:g(p)}),this.pendingHandoffs.push({...p,operationId:R,settlesThroughBridge:!0})})}const q=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)q.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...l]=d;for(const o of l)for(const c of o.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const f of e.hiddenEntries)n.add(f.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const c of a.entries)n.add(c.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>_)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||U())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>_)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=I(i,e)}catch(l){this.raiseReadFatal("poll",l)}let d;try{await y.fresh(async l=>{d=l,v({level:"info",event:"inbox.delivery.started",operation_id:l,fields:g(s)});for(const o of n)await t.sendCustomMessage({customType:C,content:o,display:!0})})}catch(l){throw d===void 0&&this.raiseReadFatal("poll",l),F(d,s,"send",l),l}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&M(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(l=>l.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)F(d.operationId,d,"receipt_commit",s);return P({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await Z(t,s),D()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=new Set(this.buffer.map(f=>f.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(f=>f.awaitingDequeue!==void 0).flatMap(f=>[...f.entryIds])),l=this.pendingHandoffs.filter(f=>(n||f.settleAtAgentSettled!==!0)&&f.entryIds.every(m=>!a.has(m))),o=new Set(l.flatMap(f=>[...f.entryIds])),c=[...this.claims.keys()].filter(f=>s||o.has(f)&&!d.has(f));return c.length===0?"settled":(this.pendingCommit={handoffs:l,entryIds:c,receipts:c.map(f=>{const m=this.claims.get(f);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){b?.dispose("reload",!1);const e=new we(r,t,++ce);b=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}h(Ee,"registerCanvasInboxWatcher");var qe=Ee;export{qe as default,Ee as registerCanvasInboxWatcher};
|
|
1
|
+
var J=Object.defineProperty;var h=(r,t)=>J(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as L,envNodeId as G,envProfileId as X,envWatcherDebounceMs as j,envWatcherTickMs as z,envWatcherBackstopMs as V}from"../shared/env.js";import{coalesceBrokerInbox as Y,entryCards as K}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Q,claimBrokerMail as Z,brokerExtensionState as ee,brokerRecovery as te,mutateBrokerFault as D,recordConversationWriteFault as ie}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ne}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as N}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as se,startupClaimsHeld as re}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as ae}from"../core/runtime/broker/extension-abort.js";import{isTokenRevokedApiError as oe,isTransientDaemonApiError as S}from"../api/errors.js";import{announceMessageOrigin as de,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as le,generateAndCommitInitialName as fe}from"./broker-local.js";import{emitEvent as O}from"../core/events/emit.js";import{errorClassFromError as he}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as F}from"../shared/generated-context.js";import{isProfilePaused as ue}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as P,brokerIdleTurnStart as ce,brokerRunTurnBusy as me,brokerRunSteer as I,HELD_DEFERRED_INBOX_PROMPT_JOIN as pe}from"../core/runtime/broker/held-deferred-inbox.js";const k=64,ye=3e4,ge=5*6e4,H="inbox daemon unreachable",U=16;let v,be=0;class B extends Error{static{h(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function ve(){return{tickMs:z(),debounceMs:j()}}h(ve,"resolveCadence");function w(){const r=G();return r===void 0||r.trim()===""?void 0:r}h(w,"currentNodeId");function q(){const r=X();return r!==void 0&&r!==""&&ue(r)}h(q,"profilePaused");function _(r){try{return he(r)}catch{return{class:"unknown"}}}h(_,"safeErrorClass");function E(r){try{O(r)}catch{}}h(E,"emitBestEffort");function g(r){try{y.fresh(t=>{E({...r,operation_id:t})})}catch{}}h(g,"emitFreshBestEffort");function T(r,t){try{y.run(r,()=>{E({...t,operation_id:r})})}catch{}}h(T,"emitStoredBestEffort");function we(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}h(we,"deliveryOrigin");function x(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-U;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,U),...i>0?{sourceOperationIdsOmitted:i}:{}}}h(x,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}h(b,"deliveryFields");function _e(r){T(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}h(_e,"emitDeliveryCompleted");function M(r,t,e,i){T(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:e,...b(t)}})}h(M,"emitDeliveryFailure");function R(r,t){T(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}h(R,"emitDeliveryAbandoned");function Ee(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
|
|
2
|
+
`):""}h(Ee,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(W,"isSessionShutdownReason");function Ie(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(Ie,"disposalReasonForShutdown");function ke(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}h(ke,"boundedRuntimeReason");class xe{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;failingSince;failureCount=0;nextRetryAt=0;stallFaultRecorded=!1;tickFailed=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=L();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=h((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(o=>o.awaitingDequeue!==void 0))return;const n=C(Ee(i.content)),s=this.pendingHandoffs.find(o=>o.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=w();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?Ie(i):"reload";W(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ke(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=N();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=w();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const o of this.signalUnsubscribers.splice(0))o();const s=n;{const o=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of o)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=N().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),V()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}noteDaemonFailure(t){const e=Date.now();this.tickFailed=!0,this.failingSince??=e,this.failureCount+=1;const i=Math.min(ye,this.cadence.tickMs*2**Math.min(this.failureCount-1,16));this.nextRetryAt=e+i;const n=this.nodeId??w();if(this.stallFaultRecorded||n===void 0||e-this.failingSince<ge)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;D(n,{op:"record",input:{link:"daemon\u2192node",op:H,kind:"connection",retry:{disposition:"auto",nextAt:new Date(this.nextRetryAt).toISOString()},message:s}}).then(()=>{this.stallFaultRecorded=!0},()=>{})}noteDaemonSuccess(){if(this.failingSince===void 0||(this.failingSince=void 0,this.failureCount=0,this.nextRetryAt=0,!this.stallFaultRecorded))return;this.stallFaultRecorded=!1;const t=this.nodeId??w();t!==void 0&&te(t).then(e=>e.fault?.op===H?D(t,{op:"clear",link:"daemon\u2192node"}):void 0).catch(e=>{g({level:"warn",event:"inbox.stall_fault.clear_failed",outcome:"failed",error:e,error_class:_(e),fields:{stage:"poll"}})})}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&me())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new B(e,i),this.clearTimer(),g({level:"error",event:t,outcome:"failed",error:i,error_class:_(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof B)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(re()){this.waitingForStartup||(this.waitingForStartup=!0,se(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}if(this.failingSince!==void 0&&Date.now()<this.nextRetryAt)return;this.tickFailed=!1;const e=this.tick().then(()=>{this.retryNeeded=!1,this.tickFailed||this.noteDaemonSuccess()}).catch(i=>{if(this.canMutate()){if(S(i)){this.retryNeeded=!0,this.noteDaemonFailure(i),g({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:"poll"}});return}if(oe(i)){this.clearTimer(),g({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),P()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await Z(t,"wake",this.reportBodies)}catch(a){throw S(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let o=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ne(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?y.fresh(d=>{this.pendingHandoffs.push({...x([a.entry],"visible"),operationId:d,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),o=!0))}return o&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=w();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||q()||this.pendingHandoffs.length>=k||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&I()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=I()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&I()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(l=>l.entry_id)),s=new Set(i.map(l=>l.entry_id)),o=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),a=this.isIdle()&&o.length>0&&o.every(l=>l.tier==="deferred"),f=this.visibleRoute(i)==="critical",d=!a&&!f&&e.length>0,c=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(d)+Number(c)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await ee(t)).situational_card}catch(o){this.raiseSituationalFatal(n,o)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...K(n));return i}digest(t,e){try{return Y(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=k&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let o;try{o=x(e,t)}catch(d){this.raiseReadFatal(n,d)}let a;try{y.fresh(d=>{a=d,E({level:"info",event:"inbox.delivery.started",operation_id:d,fields:b(o)}),i()})}catch(d){return a===void 0&&this.raiseReadFatal(n,d),M(a,o,"send",d),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...o,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,o){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(d=>d.entry_id)}),i.forEach((d,c)=>{const l=s&&c===i.length-1;this.pi.sendMessage({customType:F,content:d,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},o,f)}sendVisible(t,e,i,n,s,o){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:F,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(de(i,n),s==="idle"){const a=ce();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},o,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(o=>e.has(o.entry_id)),n=new Set(i.map(o=>o.entry_id)),s=this.buffer.filter(o=>!n.has(o.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const d of e.visibleEntries)n.add(d.entry_id);for(const d of e.hiddenEntries)n.add(d.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id))};if(this.runNode&&s==="steer"){let d=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(d=p)});const c=e.visibleEntries.slice(0,d+1);if(e.hiddenEntries.length>0||c.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const l=this.digest(c,i),m=l.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(I()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of l){const p=x(u.entries,"visible");y.fresh(A=>{E({level:"info",event:"inbox.delivery.started",operation_id:A,fields:b(p)}),this.pendingHandoffs.push({...p,operationId:A,settlesThroughBridge:!0})})}const $=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)$.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const o=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=o;for(const d of f)for(const c of d.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const d=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,d,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const d=this.sendVisible(a.entries,a.cards,a.text,we(a),s,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const c of a.entries)n.add(c.entry_id);else a.kind==="human"&&(await le(t,a.text).catch(()=>{}),fe(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>k)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||q())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>k)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const o of i)await this.sendPromptJoinDelivery(t,"visible",o.entries,[...o.cards,o.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=x(i,e)}catch(f){this.raiseReadFatal("poll",f)}let o;try{await y.fresh(async f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const d of n)await t.sendCustomMessage({customType:F,content:d,display:!0})})}catch(f){throw o===void 0&&this.raiseReadFatal("poll",f),M(o,s,"send",f),f}o===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:o,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Q(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const o of e.receipts){const a=s.results.find(f=>f.delivery_id===o.delivery_id);if(a?.outcome!==o.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(o=>o.outcome==="acknowledged")}catch(s){if(S(s)&&this.pendingCommit===e&&this.canMutate())return this.retryNeeded=!0,this.noteDaemonFailure(s),g({level:"warn",event:"inbox.receipt_commit.retrying",outcome:"failed",error:s,error_class:_(s),fields:{stage:"settle"}}),this.syncTimers(),"held";if(this.pendingCommit===e)for(const o of e.handoffs)M(o.operationId,o,"receipt_commit",s);return O({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await ie(t,s),P()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(o=>!s.has(o.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(o=>!this.claims.has(o)));for(const s of n)i&&_e(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ae(),o=new Set(this.buffer.map(l=>l.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),f=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!a.has(m))),d=new Set(f.flatMap(l=>[...l.entryIds])),c=[...this.claims.keys()].filter(l=>s||d.has(l)&&!o.has(l));return c.length===0?"settled":(this.pendingCommit={handoffs:f,entryIds:c,receipts:c.map(l=>{const m=this.claims.get(l);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function Se(r,t){v?.dispose("reload",!1);const e=new xe(r,t,++be);v=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[pe]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(Se,"installWatcher");function Ce(r){const t=Se(r,ve());return()=>t.dispose("shutdown",!1)}h(Ce,"registerCanvasInboxWatcher");var Ge=Ce;export{Ge as default,Ce as registerCanvasInboxWatcher};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.731",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -158,8 +158,8 @@
|
|
|
158
158
|
},
|
|
159
159
|
"license": "UNLICENSED",
|
|
160
160
|
"dependencies": {
|
|
161
|
-
"@north-light/identity": "0.3.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.731",
|
|
162
|
+
"@north-light/plugin": "0.3.731",
|
|
163
163
|
"@earendil-works/chord": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
165
165
|
"@earendil-works/pi-ai": "1.5.2",
|