@north-light/cli 0.3.687 → 0.3.688

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
- var A=Object.defineProperty;var _=(o,t)=>A(o,"name",{value:t,configurable:!0});import{randomUUID as O}from"node:crypto";import{existsSync as F,readFileSync as W,rmSync as q}from"node:fs";import{join as B}from"node:path";import{SessionManager as j}from"@earendil-works/pi-coding-agent";import{blobStore as l}from"../blobs/index.js";import{openDb as w,withCanvasWrite as y}from"../canvas/db.js";import{appSpace as J}from"../layout.js";import{appendConversationEvents as T,rootRepromptPending as L}from"../../daemon/runs/append-section.js";import{ConversationNotFoundError as R}from"./index.js";const N="s.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC",D=_((o,t,r)=>`conversations/${o}/${t}/${r}.jsonl`,"keyFor"),C=_(o=>o.map(t=>JSON.stringify(t)+`
2
- `).join(""),"encode"),$=_(o=>o.split(`
3
- `).filter(Boolean).map(t=>JSON.parse(t)),"decode"),h=_(()=>new Date().toISOString(),"at");async function g(o,t,r=!1){const i=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 ${N} LIMIT 1${r?" FOR UPDATE OF s":""}`).get(t);if(!i)throw new R(t);return i}_(g,"binding");async function b(o,t){return await o.prepare("SELECT seq, blob_key, bytes, entries, created FROM conversation_parts WHERE conversation_id = ? ORDER BY seq").all(t)}_(b,"parts");async function x(o,t){return await o.prepare("SELECT seq, body, bytes, created FROM conversation_entries WHERE conversation_id = ? ORDER BY seq").all(t)}_(x,"tail");async function M(o,t){const r=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(t,t);return{parts:r.filter(i=>i.kind==="part").map(({seq:i,blob_key:n,bytes:s,entries:e,created:a})=>({seq:Number(i),blob_key:n,bytes:Number(s),entries:Number(e),created:a})),tail:r.filter(i=>i.kind==="tail").map(({seq:i,body:n,bytes:s,created:e})=>({seq:Number(i),body:n,bytes:Number(s),created:e}))}}_(M,"snapshot");const I=4*1024*1024,Y=4;async function*V(o,t,r){const i=[];let n=0;const s=_(()=>{for(;n<o&&i.length<r;){const e=t(n++);e.catch(()=>{}),i.push(e)}},"fill");for(s();i.length>0;){const e=await i.shift();s(),yield e}}_(V,"readAhead");async function m(o,t,r){const i=[];let n=0;const s=await l();for(const e of o.parts){const a=Math.max(t,n),c=Math.min(r,n+e.bytes);if(a<c){const d=await s.get(e.blob_key,{start:a-n,length:c-a});if(!d)throw new Error(`missing conversation object: ${e.blob_key}`);i.push(d)}n+=e.bytes}for(const e of o.tail){const a=Math.max(t,n),c=Math.min(r,n+e.bytes);a<c&&i.push(Buffer.from(e.body+`
5
- `).subarray(a-n,c-n)),n+=e.bytes}return Buffer.concat(i)}_(m,"bytesOf");const k=new Map;async function H(o,t,r){const i=await w();if(await i.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(o)||!F(r))return;let n=W(r);const s=n.lastIndexOf(10);if(s<0)return;n=n.subarray(0,s+1);const e=await i.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 "+N+" LIMIT 1").get(o);let a=[];if(e?.run_id&&e.event_offset!==null){const p=Number(e.event_offset);if(n.length<p)throw new Error(`conversation shorter than indexed offset: ${o}`);a=$(n.subarray(p).toString("utf8")).filter(u=>u.type!=="session")}const c=e?.run_id?await L(e.run_id,e.node_id,a):!1,d=D(t,o,0);await(await l()).put(d,n),await y(async p=>{if(!await p.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING seq").get(o,d,n.length,Math.max(0,n.toString("utf8").split(`
6
- `).filter(Boolean).length-1),h())||!e?.run_id||e.event_offset===null)return;const f=e.source_session_id?[]:await T(p,e.run_id,e.node_id,a,JSON.parse(e.input_ids_json),c);await p.prepare("UPDATE sessions SET event_offset = ?, indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(n.length,a.at(-1)?.id??null,JSON.stringify(f),e.binding_id)})}_(H,"importOne");async function v(o,t){const r=await t.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 ${N} LIMIT 1`).get(o),i=k.get(o);if(!r&&!i)throw new R(o);let n=(await b(t,o))[0];if(!n){const c=i?.path??r?.transcript_path??void 0;c&&await H(o,i?.node??r.node_id,c),n=(await b(t,o))[0]}if(!n||n.seq!==0)throw new R(o);const s=await(await l()).get(n.blob_key,{start:0,length:Math.min(n.bytes,256*1024)});if(!s)throw new Error(`missing conversation object: ${n.blob_key}`);const e=s.indexOf(10);if(e<0)throw new Error(`invalid conversation header: ${o}`);const a=JSON.parse(s.subarray(0,e).toString("utf8"));if(a.type!=="session"||a.id!==o)throw new Error(`invalid conversation header: ${o}`);return{header:a,path:r?.transcript_path??i?.path??"",binding:r}}_(v,"initial");function rt(){const o={async create(t,r,i,n){const e=await(await w()).prepare("SELECT grantee, run_id FROM node_rows WHERE node_id = ?").get(t);if(!e)throw new Error(`missing conversation owner ${t}`);const a=r.id,c=B(J(e.grantee).conversations,t,`${r.timestamp.replace(/[:.]/g,"-")}_${a}.jsonl`),d=C([r,...i]),p=D(t,a,0),u=e.run_id?await L(e.run_id,t,i):!1;return await(await l()).put(p,d),await y(async f=>{if(await f.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ?").get(a))throw new Error(`conversation already exists: ${a}`);const E=h(),S=r.parentSession?await f.prepare("SELECT session_id FROM sessions WHERE transcript_path = ? LIMIT 1").get(r.parentSession):void 0;if(await f.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(O(),a,t,c,S?S.session_id:null,E,E,E),await f.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(a,p,Buffer.byteLength(d),i.length,E),e.run_id&&!S){const U=await T(f,e.run_id,t,i,[],u);await f.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?").run(i.at(-1)?.id??null,JSON.stringify(U),a,t)}}),{conversation_id:a,path:c}},async append(t,r){if(!r.length)return;const i=await g(await w(),t),n=i.run_id?await L(i.run_id,i.node_id,r):!1;await y(async s=>{const e=await g(s,t,!0);if(!(await b(s,t)).length)throw new R(t);const a=[];for(const c of r){const d=JSON.stringify(c);await s.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(t,c.id,d,Buffer.byteLength(d)+1,h())&&a.push(c)}if(e.run_id&&a.length){const c=await T(s,e.run_id,e.node_id,a,JSON.parse(e.input_ids_json??"[]"),n);await s.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(a.at(-1).id,JSON.stringify(c),e.binding_id)}})},async readLines(t){const r=await w(),{path:i}=await v(t,r),n=await M(r,t),s=n.parts.reduce((a,c)=>a+c.bytes,0)+n.tail.reduce((a,c)=>a+c.bytes,0);async function*e(){let a="";for await(const c of V(Math.ceil(s/I),d=>m(n,d*I,Math.min(s,(d+1)*I)),Y)){const d=a+c.toString("latin1"),p=d.lastIndexOf(`
7
- `);a=d.slice(p+1);for(const u of d.slice(0,p+1).split(`
8
- `))u&&(yield Buffer.from(u,"latin1").toString("utf8"))}a&&(yield Buffer.from(a,"latin1").toString("utf8"))}return _(e,"lines"),{path:i,lines:e()}},async read(t,r){const i=await w(),{header:n,path:s}=await v(t,i),e=await M(i,t),a=e.parts.reduce((f,E)=>f+E.bytes,0)+e.tail.reduce((f,E)=>f+E.bytes,0),c=_(f=>$(f).filter(E=>E.type!=="session"),"entriesOf");if(!r||a<=r.head+r.tail)return{header:n,entries:c((await m(e,0,a)).toString("utf8")),path:s};const d=(await m(e,0,Math.max(0,r.head))).toString("utf8").split(`
9
- `);d.pop();const p=Math.max(0,a-r.tail),u=(await m(e,p>0?p-1:0,a)).toString("utf8").split(`
1
+ var U=Object.defineProperty;var _=(o,t)=>U(o,"name",{value:t,configurable:!0});import{randomUUID as O}from"node:crypto";import{existsSync as W,readFileSync as q,rmSync as B}from"node:fs";import{join as j}from"node:path";import{SessionManager as J}from"@earendil-works/pi-coding-agent";import{blobStore as E}from"../blobs/index.js";import{openDb as w,withCanvasWrite as y}from"../canvas/db.js";import{appSpace as x}from"../layout.js";import{appendConversationEvents as T,rootRepromptPending as L}from"../../daemon/runs/append-section.js";import{ConversationNotFoundError as R}from"./index.js";const N="s.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC",D=_((o,t,r)=>`conversations/${o}/${t}/${r}.jsonl`,"keyFor"),C=_(o=>o.map(t=>JSON.stringify(t)+`
2
+ `).join(""),"encode"),H=_(o=>o.split(`
3
+ `).filter(Boolean).map(t=>JSON.parse(t)),"decode"),h=_(()=>new Date().toISOString(),"at");async function g(o,t,r=!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 ${N} LIMIT 1${r?" FOR UPDATE OF s":""}`).get(t);if(!a)throw new R(t);return a}_(g,"binding");async function b(o,t){return await o.prepare("SELECT seq, blob_key, bytes, entries, created FROM conversation_parts WHERE conversation_id = ? ORDER BY seq").all(t)}_(b,"parts");async function Y(o,t){return await o.prepare("SELECT seq, body, bytes, created FROM conversation_entries WHERE conversation_id = ? ORDER BY seq").all(t)}_(Y,"tail");async function M(o,t){const r=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(t,t);return{parts:r.filter(a=>a.kind==="part").map(({seq:a,blob_key:n,bytes:s,entries:e,created:i})=>({seq:Number(a),blob_key:n,bytes:Number(s),entries:Number(e),created:i})),tail:r.filter(a=>a.kind==="tail").map(({seq:a,body:n,bytes:s,created:e})=>({seq:Number(a),body:n,bytes:Number(s),created:e}))}}_(M,"snapshot");const I=4*1024*1024,V=4,P=16;async function*$(o,t,r){const a=[];let n=0;const s=_(()=>{for(;n<o&&a.length<r;){const e=t(n++);e.catch(()=>{}),a.push(e)}},"fill");for(s();a.length>0;){const e=await a.shift();s(),yield e}}_($,"readAhead");async function S(o,t,r){const a=[];let n=0;const s=await E(),e=[];for(const i of o.parts){const c=Math.max(t,n),d=Math.min(r,n+i.bytes);c<d&&e.push({key:i.blob_key,range:{start:c-n,length:d-c}}),n+=i.bytes}for await(const i of $(e.length,async c=>{const d=await s.get(e[c].key,e[c].range);if(!d)throw new Error(`missing conversation object: ${e[c].key}`);return d},P))a.push(i);for(const i of o.tail){const c=Math.max(t,n),d=Math.min(r,n+i.bytes);c<d&&a.push(Buffer.from(i.body+`
5
+ `).subarray(c-n,d-n)),n+=i.bytes}return Buffer.concat(a)}_(S,"bytesOf");const k=new Map;async function A(o,t,r){const a=await w();if(await a.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(o)||!W(r))return;let n=q(r);const s=n.lastIndexOf(10);if(s<0)return;n=n.subarray(0,s+1);const e=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 "+N+" LIMIT 1").get(o);let i=[];if(e?.run_id&&e.event_offset!==null){const p=Number(e.event_offset);if(n.length<p)throw new Error(`conversation shorter than indexed offset: ${o}`);i=H(n.subarray(p).toString("utf8")).filter(u=>u.type!=="session")}const c=e?.run_id?await L(e.run_id,e.node_id,i):!1,d=D(t,o,0);await(await E()).put(d,n),await y(async p=>{if(!await p.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING seq").get(o,d,n.length,Math.max(0,n.toString("utf8").split(`
6
+ `).filter(Boolean).length-1),h())||!e?.run_id||e.event_offset===null)return;const f=e.source_session_id?[]:await T(p,e.run_id,e.node_id,i,JSON.parse(e.input_ids_json),c);await p.prepare("UPDATE sessions SET event_offset = ?, indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(n.length,i.at(-1)?.id??null,JSON.stringify(f),e.binding_id)})}_(A,"importOne");async function m(o,t){const r=await t.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 ${N} LIMIT 1`).get(o),a=k.get(o);if(!r&&!a)throw new R(o);let n=(await b(t,o))[0];if(!n){const c=a?.path??r?.transcript_path??void 0;c&&await A(o,a?.node??r.node_id,c),n=(await b(t,o))[0]}if(!n||n.seq!==0)throw new R(o);const s=await(await E()).get(n.blob_key,{start:0,length:Math.min(n.bytes,256*1024)});if(!s)throw new Error(`missing conversation object: ${n.blob_key}`);const e=s.indexOf(10);if(e<0)throw new Error(`invalid conversation header: ${o}`);const i=JSON.parse(s.subarray(0,e).toString("utf8"));if(i.type!=="session"||i.id!==o)throw new Error(`invalid conversation header: ${o}`);return{header:i,path:r?.transcript_path??a?.path??"",binding:r}}_(m,"initial");function at(){const o={async create(t,r,a,n){const e=await(await w()).prepare("SELECT grantee, run_id FROM node_rows WHERE node_id = ?").get(t);if(!e)throw new Error(`missing conversation owner ${t}`);const i=r.id,c=j(x(e.grantee).conversations,t,`${r.timestamp.replace(/[:.]/g,"-")}_${i}.jsonl`),d=C([r,...a]),p=D(t,i,0),u=e.run_id?await L(e.run_id,t,a):!1;return await(await E()).put(p,d),await y(async f=>{if(await f.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ?").get(i))throw new Error(`conversation already exists: ${i}`);const l=h(),v=r.parentSession?await f.prepare("SELECT session_id FROM sessions WHERE transcript_path = ? LIMIT 1").get(r.parentSession):void 0;if(await f.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(O(),i,t,c,v?v.session_id:null,l,l,l),await f.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(i,p,Buffer.byteLength(d),a.length,l),e.run_id&&!v){const F=await T(f,e.run_id,t,a,[],u);await f.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?").run(a.at(-1)?.id??null,JSON.stringify(F),i,t)}}),{conversation_id:i,path:c}},async append(t,r){if(!r.length)return;const a=await g(await w(),t),n=a.run_id?await L(a.run_id,a.node_id,r):!1;await y(async s=>{const e=await g(s,t,!0);if(!(await b(s,t)).length)throw new R(t);const i=[];for(const c of r){const d=JSON.stringify(c);await s.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(t,c.id,d,Buffer.byteLength(d)+1,h())&&i.push(c)}if(e.run_id&&i.length){const c=await T(s,e.run_id,e.node_id,i,JSON.parse(e.input_ids_json??"[]"),n);await s.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(i.at(-1).id,JSON.stringify(c),e.binding_id)}})},async readLines(t){const r=await w(),{path:a}=await m(t,r),n=await M(r,t),s=n.parts.reduce((i,c)=>i+c.bytes,0)+n.tail.reduce((i,c)=>i+c.bytes,0);async function*e(){let i="";for await(const c of $(Math.ceil(s/I),d=>S(n,d*I,Math.min(s,(d+1)*I)),V)){const d=i+c.toString("latin1"),p=d.lastIndexOf(`
7
+ `);i=d.slice(p+1);for(const u of d.slice(0,p+1).split(`
8
+ `))u&&(yield Buffer.from(u,"latin1").toString("utf8"))}i&&(yield Buffer.from(i,"latin1").toString("utf8"))}return _(e,"lines"),{path:a,lines:e()}},async read(t,r){const a=await w(),{header:n,path:s}=await m(t,a),e=await M(a,t),i=e.parts.reduce((f,l)=>f+l.bytes,0)+e.tail.reduce((f,l)=>f+l.bytes,0),c=_(f=>H(f).filter(l=>l.type!=="session"),"entriesOf");if(!r||i<=r.head+r.tail)return{header:n,entries:c((await S(e,0,i)).toString("utf8")),path:s};const d=(await S(e,0,Math.max(0,r.head))).toString("utf8").split(`
9
+ `);d.pop();const p=Math.max(0,i-r.tail),u=(await S(e,p>0?p-1:0,i)).toString("utf8").split(`
10
10
  `);return p>0&&u.shift(),{header:n,entries:c(d.join(`
11
11
  `)),tail:c(u.join(`
12
- `)),path:s}},async header(t){const r=await w(),{header:i,path:n}=await v(t,r),s=await M(r,t);return{header:i,path:n,mtime:Date.parse(s.tail.at(-1)?.created??s.parts.at(-1).created),size:s.parts.reduce((e,a)=>e+a.bytes,0)+s.tail.reduce((e,a)=>e+a.bytes,0)}},async list(t){const i=await(await w()).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, ${N}`).all(),n=[];for(const s of i){if(t&&s.node_id!==t)continue;const e=await o.header(s.session_id);n.push({conversation_id:s.session_id,node_id:s.node_id,...e})}return n.sort((s,e)=>e.mtime-s.mtime)},async replace(t,r,i){if(r.id!==t)throw new Error("replacement header id differs from conversation id");const n=await w(),s=await g(n,t);if(s.run_id)throw new Error(`run conversation ${t} is append-only; replace refused`);const e=`conversations/${s.node_id}/${t}/0-${O()}.jsonl`,a=C([r,...i]);await(await l()).put(e,a);const c=await y(async d=>{if((await g(d,t,!0)).run_id)throw new Error(`run conversation ${t} is append-only; replace refused`);const u=await b(d,t);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(t),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(t),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(t,e,Buffer.byteLength(a),i.length,h()),u});for(const d of c)await(await l()).delete(d.blob_key)},async fork(t,r,i,n){const s=await o.read(t);let e=s.entries;if(i!==void 0){const a=j.inMemory(s.header.cwd,void 0,[s.header,...e]);a.createBranchedSession(i),e=a.getEntries()}return(await o.create(r??(await v(t,await w())).binding?.node_id??k.get(t).node,{...s.header,id:O(),timestamp:h(),cwd:n??s.header.cwd,parentSession:s.path},e)).conversation_id},async delete(t,r){const i=await w(),n=await b(i,t);await y(async s=>{await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(t),await s.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(t),await s.prepare("DELETE FROM sessions WHERE session_id = ?").run(t)});for(const s of n)await(await l()).delete(s.blob_key);r&&q(r,{force:!0})},async commit(t){return await y(async r=>{const i=await g(r,t,!0),n=await x(r,t),s=await b(r,t);if(!n.length)return s.at(-1)?.seq??0;const e=(s.at(-1)?.seq??0)+1,a=D(i.node_id,t,e),c=n.map(d=>d.body+`
13
- `).join("");return await(await l()).put(a,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await r.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(t,e,a,Buffer.byteLength(c),n.length,h()),await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(t,n.at(-1).seq),e})},async importLegacy(t){const i=await(await w()).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 ${t?"AND n.run_id = ?":""} ORDER BY s.session_id, ${N}`).all(...t?[t]:[]);for(const n of i)await H(n.session_id,n.node_id,n.transcript_path)},recover(t){for(const r of t)r.transcript_path&&k.set(r.session_id,{node:r.node_id,path:r.transcript_path})}};return o}_(rt,"createRowStore");function G(o,t,r){const i=o.indexOf(10);if(i<0)throw new Error(`invalid conversation header: ${t}`);const n=JSON.parse(o.subarray(0,i).toString("utf8"));if(n.type!=="session"||n.id!==t)throw new Error(`invalid conversation header: ${t}`);const s=r(n.cwd);return s===n.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...n,cwd:s})),o.subarray(i)])}_(G,"withHeaderCwd");async function it(o,t,r){const i=await w(),n=await g(i,o),s=(await b(i,o))[0];if(!s||s.seq!==0)return!1;const e=await(await l()).get(s.blob_key);if(!e)throw new Error(`missing conversation object: ${s.blob_key}`);const a=G(e,o,p=>p===t?r:p);if(a===null)return!1;const c=`conversations/${n.node_id}/${o}/0-${O()}.jsonl`;await(await l()).put(c,a);const d=await y(async p=>await p.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ? WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,a.length,o,s.blob_key)!==void 0);if(await(await l()).delete(d?s.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${o}`);return!0}_(it,"relocateConversationHeader");export{rt as createRowStore,V as readAhead,it as relocateConversationHeader,G as withHeaderCwd};
12
+ `)),path:s}},async header(t){const r=await w(),{header:a,path:n}=await m(t,r),s=await M(r,t);return{header:a,path:n,mtime:Date.parse(s.tail.at(-1)?.created??s.parts.at(-1).created),size:s.parts.reduce((e,i)=>e+i.bytes,0)+s.tail.reduce((e,i)=>e+i.bytes,0)}},async list(t){const a=await(await w()).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, ${N}`).all(),n=[];for(const s of a){if(t&&s.node_id!==t)continue;const e=await o.header(s.session_id);n.push({conversation_id:s.session_id,node_id:s.node_id,...e})}return n.sort((s,e)=>e.mtime-s.mtime)},async replace(t,r,a){if(r.id!==t)throw new Error("replacement header id differs from conversation id");const n=await w(),s=await g(n,t);if(s.run_id)throw new Error(`run conversation ${t} is append-only; replace refused`);const e=`conversations/${s.node_id}/${t}/0-${O()}.jsonl`,i=C([r,...a]);await(await E()).put(e,i);const c=await y(async d=>{if((await g(d,t,!0)).run_id)throw new Error(`run conversation ${t} is append-only; replace refused`);const u=await b(d,t);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(t),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(t),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(t,e,Buffer.byteLength(i),a.length,h()),u});for(const d of c)await(await E()).delete(d.blob_key)},async fork(t,r,a,n){const s=await o.read(t);let e=s.entries;if(a!==void 0){const i=J.inMemory(s.header.cwd,void 0,[s.header,...e]);i.createBranchedSession(a),e=i.getEntries()}return(await o.create(r??(await m(t,await w())).binding?.node_id??k.get(t).node,{...s.header,id:O(),timestamp:h(),cwd:n??s.header.cwd,parentSession:s.path},e)).conversation_id},async delete(t,r){const a=await w(),n=await b(a,t);await y(async s=>{await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(t),await s.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(t),await s.prepare("DELETE FROM sessions WHERE session_id = ?").run(t)});for(const s of n)await(await E()).delete(s.blob_key);r&&B(r,{force:!0})},async commit(t){return await y(async r=>{const a=await g(r,t,!0),n=await Y(r,t),s=await b(r,t);if(!n.length)return s.at(-1)?.seq??0;const e=(s.at(-1)?.seq??0)+1,i=D(a.node_id,t,e),c=n.map(d=>d.body+`
13
+ `).join("");return await(await E()).put(i,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await r.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(t,e,i,Buffer.byteLength(c),n.length,h()),await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(t,n.at(-1).seq),e})},async importLegacy(t){const a=await(await w()).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 ${t?"AND n.run_id = ?":""} ORDER BY s.session_id, ${N}`).all(...t?[t]:[]);for(const n of a)await A(n.session_id,n.node_id,n.transcript_path)},recover(t){for(const r of t)r.transcript_path&&k.set(r.session_id,{node:r.node_id,path:r.transcript_path})}};return o}_(at,"createRowStore");function G(o,t,r){const a=o.indexOf(10);if(a<0)throw new Error(`invalid conversation header: ${t}`);const n=JSON.parse(o.subarray(0,a).toString("utf8"));if(n.type!=="session"||n.id!==t)throw new Error(`invalid conversation header: ${t}`);const s=r(n.cwd);return s===n.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...n,cwd:s})),o.subarray(a)])}_(G,"withHeaderCwd");async function it(o,t,r){const a=await w(),n=await g(a,o),s=(await b(a,o))[0];if(!s||s.seq!==0)return!1;const e=await(await E()).get(s.blob_key);if(!e)throw new Error(`missing conversation object: ${s.blob_key}`);const i=G(e,o,p=>p===t?r:p);if(i===null)return!1;const c=`conversations/${n.node_id}/${o}/0-${O()}.jsonl`;await(await E()).put(c,i);const d=await y(async p=>await p.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ? WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,i.length,o,s.blob_key)!==void 0);if(await(await E()).delete(d?s.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${o}`);return!0}_(it,"relocateConversationHeader");export{at as createRowStore,$ as readAhead,it as relocateConversationHeader,G as withHeaderCwd};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.687",
3
+ "version": "0.3.688",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "license": "UNLICENSED",
158
158
  "dependencies": {
159
- "@north-light/identity": "0.3.687",
160
- "@north-light/plugin": "0.3.687",
159
+ "@north-light/identity": "0.3.688",
160
+ "@north-light/plugin": "0.3.688",
161
161
  "@earendil-works/chord": "1.5.2",
162
162
  "@earendil-works/pi-agent-core": "1.5.2",
163
163
  "@earendil-works/pi-ai": "1.5.2",
@@ -38,6 +38,8 @@ const CHUNK = 4 * 1024 * 1024;
38
38
  /** Ranges a streaming read keeps in flight. Each range of a conversation object is its own R2 request, which costs seconds from the
39
39
  * cloud, so one range at a time made a 35 MB conversation take two minutes and a broker starting on it time out. */
40
40
  const READ_AHEAD = 4;
41
+ /** Part objects of one range fetched at once. */
42
+ const PART_FETCHES = 16;
41
43
  /** `fetch(0)`, `fetch(1)`, … `fetch(count - 1)` in order, keeping up to `depth` of them running ahead of the consumer. */
42
44
  export async function* readAhead(count, fetch, depth) {
43
45
  const running = [];
@@ -62,16 +64,21 @@ async function bytesOf(snap, start, end) {
62
64
  const out = [];
63
65
  let offset = 0;
64
66
  const blobs = await blobStore();
67
+ const fetches = [];
65
68
  for (const part of snap.parts) {
66
69
  const from = Math.max(start, offset), to = Math.min(end, offset + part.bytes);
67
- if (from < to) {
68
- const data = await blobs.get(part.blob_key, { start: from - offset, length: to - from });
69
- if (!data)
70
- throw new Error(`missing conversation object: ${part.blob_key}`);
71
- out.push(data);
72
- }
70
+ if (from < to)
71
+ fetches.push({ key: part.blob_key, range: { start: from - offset, length: to - from } });
73
72
  offset += part.bytes;
74
73
  }
74
+ // A conversation is one small object per commit, and each get is a round trip, so the parts are fetched PART_FETCHES at a time.
75
+ for await (const data of readAhead(fetches.length, async (i) => {
76
+ const got = await blobs.get(fetches[i].key, fetches[i].range);
77
+ if (!got)
78
+ throw new Error(`missing conversation object: ${fetches[i].key}`);
79
+ return got;
80
+ }, PART_FETCHES))
81
+ out.push(data);
75
82
  for (const row of snap.tail) {
76
83
  const from = Math.max(start, offset), to = Math.min(end, offset + row.bytes);
77
84
  if (from < to)
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.687",
3
+ "version": "0.3.688",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.687",
3
+ "version": "0.3.688",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.687",
3
+ "version": "0.3.688",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.687",
31
- "@north-light/identity": "0.3.687"
30
+ "@north-light/api": "0.3.688",
31
+ "@north-light/identity": "0.3.688"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.687",
3
+ "version": "0.3.688",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.687",
9
+ "version": "0.3.688",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.687",
32
- "@north-light/plugin": "0.3.687",
31
+ "@north-light/identity": "0.3.688",
32
+ "@north-light/plugin": "0.3.688",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -10667,17 +10667,17 @@
10667
10667
  },
10668
10668
  "packages/crouter-api": {
10669
10669
  "name": "@north-light/api",
10670
- "version": "0.3.687",
10670
+ "version": "0.3.688",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.687",
10675
+ "version": "0.3.688",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.687",
10680
+ "version": "0.3.688",
10681
10681
  "license": "UNLICENSED",
10682
10682
  "dependencies": {
10683
10683
  "jose": "^6.2.1"
@@ -10685,21 +10685,21 @@
10685
10685
  },
10686
10686
  "packages/crouter-plugin": {
10687
10687
  "name": "@north-light/plugin",
10688
- "version": "0.3.687",
10688
+ "version": "0.3.688",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.687",
10692
- "@north-light/identity": "0.3.687"
10691
+ "@north-light/api": "0.3.688",
10692
+ "@north-light/identity": "0.3.688"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.687",
10697
+ "version": "0.3.688",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.687",
10701
- "@north-light/identity": "0.3.687",
10702
- "@north-light/plugin": "0.3.687",
10700
+ "@north-light/api": "0.3.688",
10701
+ "@north-light/identity": "0.3.688",
10702
+ "@north-light/plugin": "0.3.688",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {