@north-light/cli 0.3.679 → 0.3.680
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/client.js +3 -3
- package/dist/api/server-timing.d.ts +3 -0
- package/dist/api/server-timing.js +1 -0
- package/dist/clients/attach/viewer.js +447 -447
- package/dist/core/checkout-identities.js +3 -3
- package/dist/core/conversation-store/client.d.ts +9 -0
- package/dist/core/conversation-store/client.js +2 -2
- package/dist/core/conversation-store/index.d.ts +10 -2
- package/dist/core/conversation-store/index.js +1 -1
- package/dist/core/conversation-store/patch.js +1 -1
- package/dist/core/conversation-store/row-store.js +9 -9
- package/dist/core/runtime/broker.d.ts +3 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/front-door.js +4 -4
- package/dist/core/runtime/runner/blaxel/image-build.js +3 -3
- package/dist/core/runtime/runner/blaxel/release-image.js +2 -2
- package/dist/core/runtime/runner/machine/call.d.ts +5 -0
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/ops.d.ts +2 -0
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/step-timings.d.ts +13 -0
- package/dist/core/step-timings.js +1 -0
- package/dist/core/timing.d.ts +2 -0
- package/dist/core/timing.js +2 -2
- package/dist/daemon/api/handlers/conversations.js +1 -1
- package/dist/daemon/api/handlers/nodes.d.ts +1 -0
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -1
- package/packages/crouter-api/dist/api/server-timing.js +11 -0
- package/packages/crouter-api/dist/core/checkout-identities.js +4 -1
- package/packages/crouter-api/dist/core/conversation-store/client.js +8 -1
- package/packages/crouter-api/dist/core/conversation-store/index.js +1 -0
- package/packages/crouter-api/dist/core/conversation-store/patch.js +1 -2
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +2 -2
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +2 -2
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +1 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +7 -0
- package/packages/crouter-api/dist/core/runtime/spawn.js +30 -8
- package/packages/crouter-api/dist/core/step-timings.js +37 -0
- package/packages/crouter-api/dist/core/timing.js +14 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/sandbox-bootstrap.sh +1 -8
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
ON CONFLICT (environment, dir) DO UPDATE SET chain_json = EXCLUDED.chain_json, observed_at = EXCLUDED.observed_at`).run(e,f,JSON.stringify(
|
|
3
|
-
WHERE p.person IN (?, ?) AND c.dir = ? ORDER BY c.observed_at DESC LIMIT 1`).get(
|
|
1
|
+
var p=Object.defineProperty;var a=(e,r)=>p(e,"name",{value:r,configurable:!0});import{resolve as s}from"node:path";import{withCanvasWrite as h}from"./canvas/db.js";import{isCloudRole as l,PersonOutsideRequestError as w}from"./canvas/person-state.js";import{emitEvent as u}from"./events/emit.js";import{timedStep as d}from"./step-timings.js";import{realpathOrSelf as m}from"./fs-utils.js";import{checkoutChain as c}from"./graph/repo-sync/identity.js";import{callMachine as E}from"./runtime/runner/machine/call.js";import{machineEnvironmentOfProfile as y}from"./runtime/runner/machine/environment.js";import{MachineCallFailedError as O,MachineLostError as v,MachineOfflineError as _}from"./runtime/runner/machine/ops.js";const A={"repo.identify":a(async({dirs:e})=>{const r=performance.now(),i=await Promise.all(e.map(async n=>{const o=await c(m(s(n)));return o.every(t=>t.ok)?[n,o]:null}));return u({level:"info",event:"machine.repo_identify.timing",fields:{dirs:e.length,duration_ms:Math.round(performance.now()-r)}}),Object.fromEntries(i.filter(n=>n!==null))},"repo.identify")};async function C(e,r){const i=[...new Set(r.map(t=>s(t)))];if(i.length===0)return!0;let n;try{n=await d("repo_identify_call",()=>E(e,"repo.identify",{dirs:i}))}catch(t){if(!(t instanceof _||t instanceof v||t instanceof O))throw t;return u({level:"warn",event:"repo.identify.failed",error:t,fields:{environment:e,dirs:i.length}}),!1}const o=new Date().toISOString();return await h(async t=>{for(const f of i)n[f]!==void 0&&await t.prepare(`INSERT INTO checkout_identities (environment, dir, chain_json, observed_at) VALUES (?, ?, ?::jsonb, ?)
|
|
2
|
+
ON CONFLICT (environment, dir) DO UPDATE SET chain_json = EXCLUDED.chain_json, observed_at = EXCLUDED.observed_at`).run(e,f,JSON.stringify(n[f]),o)}),!0}a(C,"warmMachineCheckouts");function S(e){const r=typeof e=="string"?JSON.parse(e):e;return Array.isArray(r)?r:[]}a(S,"chainOf");async function x(e,r,i){if(!l())return await c(r);let n;try{n=await i()}catch(t){if(t instanceof w)return await c(r);throw t}const o=await e.prepare(`SELECT c.chain_json FROM checkout_identities c JOIN profiles p ON p.environment_id = c.environment
|
|
3
|
+
WHERE p.person IN (?, ?) AND c.dir = ? ORDER BY c.observed_at DESC LIMIT 1`).get(n.replace(/^user:/,""),`user:${n.replace(/^user:/,"")}`,s(r));return o===void 0?await c(r):S(o.chain_json)}a(x,"checkoutChainOf");async function P(e,r){const i=l()&&e!=null?await y(e):null;if(i!==null){await C(i,r);return}for(const n of r)await c(m(s(n)))}a(P,"warmCheckoutDirs");export{x as checkoutChainOf,A as machineCheckoutHandlers,P as warmCheckoutDirs,C as warmMachineCheckouts};
|
|
@@ -1,2 +1,11 @@
|
|
|
1
1
|
import type { ConversationStoreClient } from './index.js';
|
|
2
|
+
/** Set by the broker while it builds its session: told of each blocking request, with how long it parked the calling thread. */
|
|
3
|
+
export interface ConversationRequestMark {
|
|
4
|
+
method: string;
|
|
5
|
+
route: string;
|
|
6
|
+
durationMs: number;
|
|
7
|
+
firstRequest: boolean;
|
|
8
|
+
workerAgeMs: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function setConversationRequestMark(mark: ((request: ConversationRequestMark) => void) | undefined): void;
|
|
2
11
|
export declare function createStoreClient(address: string, token?: string): ConversationStoreClient;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var P=Object.defineProperty;var
|
|
2
|
-
`).map(a=>JSON.parse(a)),o=t;return e.tail===void 0?{header:r,entries:o,path:e.path??""}:{header:r,entries:o.slice(0,e.tail-1),tail:o.slice(e.tail-1),path:e.path??""}},"parseRead")
|
|
1
|
+
var P=Object.defineProperty;var n=(l,w)=>P(l,"name",{value:w,configurable:!0});import{MessageChannel as $,Worker as O,receiveMessageOnPort as A}from"node:worker_threads";import{ConversationNotFoundError as _}from"./index.js";let E;function R(l){E=l}n(R,"setConversationRequestMark");function y(l,w){const i=new O(new URL(import.meta.url.endsWith(".ts")?"./client-worker.ts":"./client-worker.js",import.meta.url),{workerData:{address:l,token:w}});i.unref();const v=Date.now();let S=0,s;i.on("error",e=>{s=e}),i.on("exit",e=>{s=new Error(`conversation store worker exited with ${e}`)});function m(e,r,t){if(!t)throw new Error("conversation store worker returned no reply");if(t.error)throw new Error(t.error);if(t.status===404)throw new _(r.split("/")[2]??r);if(!t.status||t.status>=400)throw new Error(`conversation store ${e} ${r} failed (${t.status}): ${t.body}`);return{body:t.body??"",...t.path?{path:t.path}:{},...t.tail?{tail:Number(t.tail)}:{}}}n(m,"settle");function c(e,r,t){if(s)throw s;const o=new SharedArrayBuffer(4),{port1:a,port2:d}=new $,f=process.hrtime.bigint(),p=S++===0;try{i.postMessage({method:e,path:r,data:t,signal:o,reply:d},[d]);const h=Atomics.wait(new Int32Array(o),0,0,3e4);if(E?.({method:e,route:r.replace(/\/[0-9a-f-]{36}/gi,"/:id"),durationMs:Number(process.hrtime.bigint()-f)/1e6,firstRequest:p,workerAgeMs:Date.now()-v}),h==="timed-out")throw a.postMessage("cancel"),new Error(`conversation store request timed out: ${e} ${r}`);return m(e,r,A(a)?.message)}finally{a.close()}}n(c,"call");function T(e,r){if(s)return Promise.reject(s);const{port1:t,port2:o}=new $;return new Promise((a,d)=>{const f=setTimeout(()=>{t.postMessage("cancel"),t.close(),d(new Error(`conversation store request timed out: ${e} ${r}`))},3e4);f.unref(),t.once("message",p=>{clearTimeout(f),t.close();try{a(m(e,r,p))}catch(h){d(h)}}),i.postMessage({method:e,path:r,reply:o},[o])})}n(T,"callAsync");const u=n(e=>`/conversations/${encodeURIComponent(e)}`,"url");function b(e,r){if(s)throw s;i.postMessage({kind:"append",method:"POST",path:`${u(e)}/entries`,data:{entries:r}})}n(b,"enqueueAppend");function M(){if(s)return Promise.reject(s);const{port1:e,port2:r}=new $;return new Promise((t,o)=>{e.once("message",a=>{e.close();try{m("POST","/commit",a),t()}catch(d){o(d)}}),i.postMessage({kind:"flush",method:"POST",path:"/commit",reply:r},[r])})}n(M,"flush");const g=n(e=>{const[r,...t]=e.body.trimEnd().split(`
|
|
2
|
+
`).map(a=>JSON.parse(a)),o=t;return e.tail===void 0?{header:r,entries:o,path:e.path??""}:{header:r,entries:o.slice(0,e.tail-1),tail:o.slice(e.tail-1),path:e.path??""}},"parseRead"),k=n((e,r)=>r?`${u(e)}?head=${r.head}&tail=${r.tail}`:u(e),"readPath");return{create(e,r,t,o){return JSON.parse(c("POST","/conversations",{node_id:e,header:r,entries:t,path:o}).body)},append(e,r){b(e,r)},flush:M,replace(e,r,t){c("PUT",u(e),{header:r,entries:t})},read(e,r){return g(c("GET",k(e,r)))},async readAsync(e,r){return g(await T("GET",k(e,r)))},header(e){return JSON.parse(c("GET",`${u(e)}/header`).body)},fork(e,r,t,o){return JSON.parse(c("POST",`${u(e)}/fork`,{node_id:r,leaf_id:t,cwd:o}).body).conversation_id},list(e){const r=e===void 0?"":`?node_id=${encodeURIComponent(e)}`;return JSON.parse(c("GET",`/conversations${r}`).body).conversations},delete(e){c("DELETE",u(e))}}}n(y,"createStoreClient");export{y as createStoreClient,R as setConversationRequestMark};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { SessionEntry, SessionHeader } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
export { setConversationRequestMark, type ConversationRequestMark } from './client.js';
|
|
2
3
|
export type { SessionEntry, SessionHeader };
|
|
3
4
|
export declare class ConversationNotFoundError extends Error {
|
|
4
5
|
readonly code = "not_found";
|
|
@@ -22,7 +23,11 @@ export interface ConversationWindow {
|
|
|
22
23
|
* (`client.ts`: an `Atomics.wait` worker, no db) implements it. It is declared apart from
|
|
23
24
|
* `ConversationStore` so a change to the daemon's store never changes pi's contract. */
|
|
24
25
|
export interface ConversationStoreClient {
|
|
25
|
-
|
|
26
|
+
/** Returns the new conversation's id and the transcript path the server assigned. */
|
|
27
|
+
create(nodeId: string, header: SessionHeader, entries: SessionEntry[], path?: string): {
|
|
28
|
+
conversation_id: string;
|
|
29
|
+
path: string;
|
|
30
|
+
};
|
|
26
31
|
/** Enqueue entries in order without blocking the broker's event loop. */
|
|
27
32
|
append(id: string, entries: SessionEntry[]): void;
|
|
28
33
|
/** Wait for pending appends and seal each dirty conversation. */
|
|
@@ -52,7 +57,10 @@ export interface ConversationStoreClient {
|
|
|
52
57
|
}
|
|
53
58
|
/** The daemon's file store (`createFileStore`, installed by `sessions.ts`). */
|
|
54
59
|
export interface ConversationStore {
|
|
55
|
-
create(nodeId: string, header: SessionHeader, entries: SessionEntry[], path?: string): Promise<
|
|
60
|
+
create(nodeId: string, header: SessionHeader, entries: SessionEntry[], path?: string): Promise<{
|
|
61
|
+
conversation_id: string;
|
|
62
|
+
path: string;
|
|
63
|
+
}>;
|
|
56
64
|
append(id: string, entries: SessionEntry[]): Promise<void>;
|
|
57
65
|
replace(id: string, header: SessionHeader, entries: SessionEntry[]): Promise<void>;
|
|
58
66
|
read(id: string, window?: ConversationWindow): Promise<{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var n=(e,r)=>c(e,"name",{value:r,configurable:!0});import{appsRoot as i}from"../layout.js";import{apiSocketPath as p}from"../canvas/paths.js";import{createStoreClient as u}from"./client.js";import{currentNodeToken as f}from"../runtime/broker/node-token.js";class d extends Error{static{n(this,"ConversationNotFoundError")}code="not_found";constructor(r){super(`conversation not found: ${r}`)}}function C(e){return e instanceof d}n(C,"isConversationNotFound");function
|
|
1
|
+
var c=Object.defineProperty;var n=(e,r)=>c(e,"name",{value:r,configurable:!0});import{appsRoot as i}from"../layout.js";import{apiSocketPath as p}from"../canvas/paths.js";import{createStoreClient as u}from"./client.js";import{setConversationRequestMark as E}from"./client.js";import{currentNodeToken as f}from"../runtime/broker/node-token.js";class d extends Error{static{n(this,"ConversationNotFoundError")}code="not_found";constructor(r){super(`conversation not found: ${r}`)}}function C(e){return e instanceof d}n(C,"isConversationNotFound");function k(e){return/(?:^|\/)[^/]+_([0-9a-f-]{36})\.jsonl$/i.exec(e)?.[1]??null}n(k,"conversationIdFromPath");function A(){return i()}n(A,"defaultConversationRoot");function l(){return process.env.CRTR_API_URL||p()}n(l,"conversationApiAddress");let t,a;function P(e){t=e}n(P,"installConversationStore");function R(){if(t)return t;const e=s();return{create:n(async(...r)=>e.create(...r),"create"),append:n(async(r,o)=>e.append(r,o),"append"),replace:n(async(...r)=>e.replace(...r),"replace"),read:n(async(...r)=>e.read(...r),"read"),header:n(async(...r)=>e.header(...r),"header"),fork:n(async(...r)=>e.fork(...r),"fork"),list:n(async(...r)=>e.list(...r),"list"),delete:n(async r=>e.delete(r),"delete")}}n(R,"conversationStore");function s(){const e=l();return a?.address!==e&&(a={address:e,store:u(e,f())}),a.store}n(s,"conversationClient");async function S(){t||await s().flush()}n(S,"flushConversation");async function F(e,r){if(t)return t.read(e,r);const o=s();return o.readAsync?o.readAsync(e,r):o.read(e,r)}n(F,"readConversationAsync");import{installSessionManagerStorePatch as M}from"./patch.js";import{findOrphanedParents as T,relinkOrphanedParents as $,repairConversationFile as g}from"./repair.js";export{d as ConversationNotFoundError,l as conversationApiAddress,s as conversationClient,k as conversationIdFromPath,R as conversationStore,A as defaultConversationRoot,T as findOrphanedParents,S as flushConversation,P as installConversationStore,M as installSessionManagerStorePatch,C as isConversationNotFound,F as readConversationAsync,$ as relinkOrphanedParents,g as repairConversationFile,E as setConversationRequestMark};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var x=Object.defineProperty;var
|
|
1
|
+
var x=Object.defineProperty;var l=(p,i)=>x(p,"name",{value:i,configurable:!0});import{dirname as S,resolve as E}from"node:path";import{SessionManager as m}from"@earendil-works/pi-coding-agent";import{conversationClient as B,conversationIdFromPath as P}from"./index.js";import{findOrphanedParents as O}from"./repair.js";import{emitEvent as k}from"../events/emit.js";let N=!1;function z(p,i=B()){if(N)return;const c=m.prototype,a=m;for(const e of["_setSessionFile","_rewriteFile","_persist","createBranchedSession","newSession"])if(typeof c[e]!="function")throw new Error(`pi SessionManager.${e} changed; store patch cannot start`);for(const e of["create","open","continueRecent","forkFrom","findById","list","listAll"])if(typeof a[e]!="function")throw new Error(`pi SessionManager.${e} changed; store patch cannot start`);const D=c.createBranchedSession,w=c.newSession;function M(e,s){const t=O(s);t.length!==0&&k({level:"error",event:"conversation.orphaned_parent",fields:{conversation_id:e,orphan_count:t.length,orphans:t.slice(0,20).map(n=>({entry_id:n.entryId,missing_parent_id:n.missingParentId}))}})}l(M,"reportOrphans");function y(e,s){const{header:t,entries:n,path:o}=i.read(e);M(t.id,n);const r=m.inMemory(s??t.cwd);r.sessionFile=o,r.sessionDir=S(o),r._loadEntries([t,...n]),r.persist=!0,r.flushed=!0;const d=r.fileEntries[0];return d?.type==="session"&&d.version!==t.version&&r._rewriteFile(),r}l(y,"fromStore");function u(e){const[s,...t]=e.fileEntries;if(!s||s.type!=="session")throw new Error("conversation has no session header");e.sessionFile=i.create(p,s,t).path,e.sessionDir=S(e.sessionFile),e.flushed=!0}l(u,"persistNew");function b(e,s){i.append(e.sessionId,[s])}l(b,"appendInOrder");function g(e){const s=P(e);if(!s)throw new Error(`invalid conversation path: ${e}`);return s}l(g,"idOf"),c._setSessionFile=function(e){const{header:s,entries:t}=i.read(g(e));this.sessionFile=i.header(s.id).path,this.sessionDir=S(this.sessionFile),M(s.id,t),this._loadEntries([s,...t]),this.flushed=!0},c._rewriteFile=function(){if(!this.persist||!this.sessionFile)return;const[e,...s]=this.fileEntries;if(!e||e.type!=="session")throw new Error("conversation has no session header");i.replace(e.id,e,s)},c._persist=function(e){!this.persist||!this.sessionFile||(this.flushed?b(this,e):u(this))},c.newSession=function(e){if(!this.persist)return w.call(this,e);const s=this.flushed&&this.fileEntries.length===1&&this.sessionFile!==void 0?this.sessionId:void 0;if(s!==void 0&&(e?.id===void 0||e.id===s)){const t=this.sessionFile;w.call(this,{...e,id:s});const n=this.fileEntries[0];if(!n||n.type!=="session")throw new Error("conversation has no session header");return i.replace(s,n,[]),this.sessionFile=t,this.flushed=!0,t}return w.call(this,e),u(this),this.sessionFile},c.createBranchedSession=function(e){if(!this.persist)return D.call(this,e);const s=this.sessionFile;this.persist=!1;try{D.call(this,e)}finally{this.persist=!0}const t=this.fileEntries[0];if(!t||t.type!=="session")throw new Error("branch has no header");return this.fileEntries[0]={...t,parentSession:s},u(this),this.sessionFile},a.create=(e,s,t)=>{const n=m.inMemory(e,t);return n.persist=!0,u(n),n},a.open=(e,s,t)=>y(g(e),t),a.continueRecent=e=>{const s=i.list().find(t=>t.header.cwd===E(e));return s?y(s.conversation_id,e):a.create(e)},a.forkFrom=(e,s)=>y(i.fork(g(e),p,void 0,s)),a.findById=(e,s)=>i.list().find(t=>t.conversation_id===s&&t.header.cwd===E(e))?.path;function I(e){return i.list().filter(s=>e===void 0||s.header.cwd===E(e)).map(s=>{let t,n=0,o="",r;const d=[];for(const f of i.read(s.conversation_id).entries){if(f.type==="session_info"&&(t=f.name?.trim()||void 0),f.type!=="message")continue;n++;const h=f.message;if(h.role!=="user"&&h.role!=="assistant")continue;const A=typeof h.timestamp=="number"?h.timestamp:Date.parse(f.timestamp);Number.isNaN(A)||(r=Math.max(r??0,A));const F=typeof h.content=="string"?h.content:Array.isArray(h.content)?h.content.filter(v=>v.type==="text").map(v=>v.text??"").join(" "):"";F&&(d.push(F),!o&&h.role==="user"&&(o=F))}const _=new Date(s.header.timestamp);return{path:s.path,id:s.conversation_id,cwd:s.header.cwd,...t?{name:t}:{},...s.header.parentSession?{parentSessionPath:s.header.parentSession}:{},created:_,modified:r&&r>0?new Date(r):Number.isNaN(_.getTime())?new Date(s.mtime):_,messageCount:n,firstMessage:o||"(no messages)",allMessagesText:d.join(" ")}})}l(I,"sessionInfos"),a.list=async(e,s,t,n)=>{n?.throwIfAborted();const o=I(e);return t?.(o.length,o.length,o),o},a.listAll=async(...e)=>(e.find(t=>t instanceof AbortSignal)?.throwIfAborted(),I()),N=!0}l(z,"installSessionManagerStorePatch");export{z as installSessionManagerStorePatch};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
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
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
|
|
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(
|
|
5
|
-
`).subarray(
|
|
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,
|
|
7
|
-
`);
|
|
8
|
-
`))u&&(yield Buffer.from(u,"latin1").toString("utf8"))}
|
|
9
|
-
`);d.pop();const p=Math.max(0,
|
|
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(`
|
|
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:
|
|
13
|
-
`).join("");return await(await l()).put(
|
|
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};
|
|
@@ -39,7 +39,9 @@ export declare function brokerToolOptions(tools: readonly string[] | undefined,
|
|
|
39
39
|
};
|
|
40
40
|
export declare function runBroker(nodeId: string, startupAt?: bigint, startupTs?: string): Promise<void>;
|
|
41
41
|
export declare function snapshotMessages(session: CreateAgentSessionResult['session'], boundaryReviewId?: string): import("./session-visibility.js").ProjectedMessage[] | undefined;
|
|
42
|
-
export declare function buildBrokerSession(engine: BrokerEngine, cfg: BrokerSdkConfig
|
|
42
|
+
export declare function buildBrokerSession(engine: BrokerEngine, cfg: BrokerSdkConfig,
|
|
43
|
+
/** Called with a step's event name and the time it started, as each step of the build ends. */
|
|
44
|
+
step?: (event: string, startedAt: bigint) => void): Promise<{
|
|
43
45
|
session: CreateAgentSessionResult['session'];
|
|
44
46
|
services: AgentSessionServices;
|
|
45
47
|
resuming: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var He=Object.defineProperty;var n=(t,o)=>He(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as Je,envModelIntent as ze,envNodeCwd as Qe,envNodeId as Ze,envProfileId as et,envScopes as tt,scopeAllowed as nt}from"../../shared/env.js";import{createServer as rt}from"node:net";import{WebSocketServer as ot,createWebSocketStream as it}from"ws";import{BROKER_VIEW_PORT as st}from"./view-socket.js";import{existsSync as xe,readFileSync as at,unlinkSync as Ae,writeFileSync as dt}from"node:fs";import{join as Me}from"node:path";import{randomUUID as O}from"node:crypto";import{mark as lt}from"../timing.js";import{SUBMIT_RESULT_TOOL as ct}from"./structured-output.js";import{flushConversation as ae,installSessionManagerStorePatch as mt}from"../conversation-store/index.js";import{getAgentDir as ee,ModelRegistry as ut,ModelRuntime as ft}from"@earendil-works/pi-coding-agent";import{nodeRunDir as pt,viewSocketPath as gt}from"../canvas/paths.js";import{bindBrokerEventSource as vt}from"../events/source.js";import{emitEvent as b,flushBrokerLog as Pe}from"../events/emit.js";import{operationIdContext as _t}from"../events/operation-id.js";import{findMissingPackagePaths as ht}from"./package-health.js";import{installBrokerConfigSnapshot as wt}from"../config.js";import{FRONT_DOOR_ENV as St}from"./front-door.js";import{CANVAS_EXTENSIONS as de,piInvocationToSdkConfig as bt}from"./launch.js";import{assertEngineVersion as yt,loadBrokerEngine as Rt}from"./broker-sdk.js";import{initCrtrTheme as Et}from"./crtr-theme.js";import{resolveBundledPiPackageDir as Tt}from"./pi-cli.js";import{captureSessionChatCapabilities as kt}from"./command-surface.js";import{InMemoryCredentialStore as Ct}from"@earendil-works/pi-ai";import{configureBrokerModelRuntime as xt,refusalRetryAt as At}from"./broker/model-adapter.js";import{brokerApiUrl as Mt,brokerExecutionId as Pt,mutateBrokerFault as te,recordBrokerTurn as Oe}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as Ot}from"./launch-recipe.js";import{fetchRunAttachments as De}from"./broker/attachments-fetch.js";import{modelRequestFromConfig as Dt,expandModelCandidates as Nt,parseModelSpec as It,unregisteredConcreteModel as Ft}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as Lt}from"./stream-watchdog.js";import{probeOnline as Bt}from"./connectivity.js";import{CRTR_CYCLE_CUSTOM_TYPE as Ne,cycleAwareMessages as Kt,endedByAbort as Ut}from"./session-cycles.js";import{turnErrorOf as $t}from"../llm/refusal.js";import{projectTranscript as Wt}from"./session-visibility.js";import{currentTurnVisibility as Gt}from"./turn-visibility.js";import{isUnknownModel as le}from"./model-selection.js";import{BrokerClientRegistry as jt}from"./broker/client-registry.js";import{ToolGroupTracker as Vt}from"./broker/tool-groups.js";import{TurnReplyTracker as qt}from"./broker/turn-replies.js";import{onNodeNamed as Xt}from"./broker/node-named.js";import{FaultRetry as Yt,willDaemonRetry as Ht}from"./broker/fault-retry.js";import{RunTurnEnds as Jt}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as zt}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as Qt,BROKER_START_CYCLE as Zt,BROKER_IDLE_TURN_START as en,BROKER_RUN_TURN_BUSY as tn,BROKER_RUN_STEER as nn}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as rn}from"./broker/run-steer.js";import{prependRunDeferredMail as on,settleRunDeferredMail as sn}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as an}from"./broker/run-turn-queue.js";import{EventProjection as dn}from"./broker/event-projection.js";import{createFrameDispatchContext as ln,handleFrame as cn}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as mn,installAdvertisedCommandInvocationContract as un}from"./advertised-command-invocation.js";import{RebindDriver as fn}from"./broker/rebind.js";import{beginRuntimeTeardown as pn}from"./broker/extension-abort.js";import{receiveNodeToken as gn}from"./broker/node-token.js";import{serveCliRelay as vn}from"./broker/cli-relay.js";import{recordBrokerRelease as _n}from"./lifecycle.js";import{setTurnCauseSource as hn}from"./broker/turn-cause.js";import{decodeKickoffOrigin as Ie,KICKOFF_ORIGIN_ENV as Fe}from"./stamp/protocol.js";import{announceMessageOrigin as Le}from"./stamp/channel.js";import{commitBrokerModel as wn,recordConversationWriteFault as Be}from"./broker/daemon-ops.js";import{bootExtensionState as Sn,holdStartupClaims as bn,releaseStartupClaims as yn}from"./broker/boot-state.js";import{bindCarriedStart as Ke,publishCarriedStart as Rn,startCycle as Ue,takeCycleAttachments as $e}from"./broker/cycle-start.js";import{composerNames as En}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as Tn,FrameOverflowError as kn,normalizeSnapshotTail as Cn}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as zr,REVIEW_BOUNDARY_NAVIGATION_CODE as Qr}from"./broker/frame-replies.js";function ce(t){return new ut(t.modelRuntime)}n(ce,"registryOf");function G(t,o){if(t==null||le(t))return null;const s=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${s}`}n(G,"formatModelSpec");function xn(t,o){const s=G(t,void 0);return s===null?null:`${s}:${o===void 0||o===""?"off":o}`}n(xn,"formatExactModelSpec");const An=12e4;let ne=null;import{brokerSignalClient as $}from"./broker/signal-stream.js";function Mn(){$().stop();const t=ne;if(ne=null,t!==null)try{t.dispose()}catch{}}n(Mn,"disposeActiveSession");function Pn(t,o){const s=nt(o,"crtr:act")?void 0:["bash"],g=t!==void 0&&t.length>0?[...new Set([...t,ct])]:t===void 0?void 0:[...t];return{...g!==void 0?{tools:g}:{},...s!==void 0?{excludeTools:s}:{}}}n(Pn,"brokerToolOptions");async function Yr(t,o=process.hrtime.bigint(),s=new Date().toISOString()){vt(t);const g=await gn(),i=await vn(t,g);process.env.CRTR_API_SOCKET=i.path,_t.fresh(()=>{b({level:"info",event:"broker.startup.cli_entry",ts:s,duration_ms:0,fields:{runtime_version:process.version,engine_version:null,model:null}}),b({level:"info",event:"broker.startup.module_loaded",duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:null,model:null}})});const d=new Set;let m=null;const l=n((e,r=null)=>{d.has(e)||(d.add(e),lt(e,{duration_ms:Number(process.hrtime.bigint()-o)/1e6}),b({level:"info",event:e,duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:m,model:r}}))},"emitStartupMilestone");process.env[St]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,mt(t);const _=await Rt();yt(_.VERSION),m=_.VERSION;const S=pt(t),k=Me(S,"broker-launch.json"),h=JSON.parse(at(k,"utf8"));if(!h.configSnapshot)throw new Error("broker launch is missing its config snapshot");if(wt(h.configSnapshot),h.start!==void 0){const{start:e,...r}=h;dt(k,JSON.stringify(r))}const u=bt(h);u.modelExact===!0?process.env.CRTR_MODEL_EXACT="1":delete process.env.CRTR_MODEL_EXACT;let y,T;const D=new AbortController,H=n(e=>{y!==void 0?y(e):(T??=e,D.abort())},"onSignal");process.on("SIGTERM",()=>H("SIGTERM")),process.on("SIGINT",()=>H("SIGINT")),process.on("SIGUSR1",()=>{const e=process.env.CRTR_EXECUTION_ID;e!==void 0&&e!==""&&$().start(t,e)});let{session:N,services:I,resuming:ue,runtime:j}=await In(_,u);l("broker.startup.session_built");const E=h.start;E!==void 0&&bn();const F=E===void 0?await Ue(t,N,"startup",D.signal):Rn(t,E);D.signal.aborted&&(N.dispose(),await Pe(),process.exit(0));const A=F?.names===void 0?await En(t):F.names,J=(await Sn(t)).node.review_binding?.review_id,L=Je();ne=N;const Ge=Bt;try{process.env.PI_PACKAGE_DIR=Tt(),Et(I.settingsManager.getTheme(),ee(),!1)}catch(e){b({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of ht(ee()))b({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const q=gt(t),w=new jt(t),z=new Map,M=new Vt(t,e=>w.broadcast(e)),X=new qt(t,e=>w.broadcast(e));Xt(e=>w.broadcast({type:"node_named",...e}));let B=!1,fe=!1,Q,Z,pe,c,Y;const re=new Jt;let W,ge=n(()=>{},"notifyTurnAccepted"),ve=n(()=>{},"resetFrameState"),_e=n(()=>{},"bindAnswered");const oe=zt(E===void 0?void 0:new Promise(e=>{_e=e}));let he=n(()=>0,"pendingPromptDispatches"),we;const P=an({runNode:L,session:n(()=>c.session(),"session"),isReplacing:n(()=>c.isReplacing(),"isReplacing"),pendingRebind:n(()=>c.pendingRebind(),"pendingRebind"),isAgentRunActive:n(()=>c.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:n(()=>he(),"pendingDispatches"),turnAdmission:oe,prependDeferred:n(e=>on(t,e),"prependDeferred"),onError:n(e=>b({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),Se=rn(P.steerable);globalThis[nn]=Se,hn(()=>c.session());const be=P.drain;u.firstPrompt!==void 0&&u.firstPrompt!==""&&P.holdForKickoff(),globalThis[en]=P.start,globalThis[tn]=P.busy,c=new fn({nodeId:t,cfg:u,session:N,services:I,runtime:j,registry:w,toolGroups:M,turnReplies:X,runSteer:Se,runNode:L,transcriptMessages:n(e=>me(e,J)?.map(({message:r})=>r)??e.sessionManager.buildSessionContext().messages,"transcriptMessages"),uiContext:n(()=>pe,"uiContext"),faultRetry:n(()=>Y,"faultRetry"),projection:n(()=>W,"projection"),setActiveSession:n(e=>{if(ne=e,we?.(),L||process.env.CRTR_RUN_ID){let r="stop",a,f=!1;we=e.subscribe(v=>{if(v.type==="agent_start"&&(r="stop",a=void 0,f=!1,re.started()),v.type==="agent_end"){const p=[...v.messages??[]].reverse().find(R=>R.role==="assistant");p&&(r=p.stopReason,a=Ut(p)?void 0:$t(p,At(p)),f=p.role==="assistant"&&Ht(p,e.model?.contextWindow))}v.type==="agent_settled"&&(re.settled(e.sessionManager,{stop_reason:r,...a?{error:a}:{}},f),L&&(ae().then(()=>sn(t,e)).catch(async p=>{if(String(p?.message).startsWith("conversation_write_failed")){b({level:"error",event:"broker.exited",node_id:t,error:p,fields:{fault:"conversation_write_failed"}}),await Be(t,p),C("conversation_write_failed",1);return}b({level:"error",event:"broker.run_deferred_mail.settle_failed",error:p})}),queueMicrotask(()=>{c.session()===e&&be()})))})}},"setActiveSession"),disposeAndExit:n((e,r)=>C(e,r),"disposeAndExit"),onSessionRebind:n(()=>{ve()},"onSessionRebind"),onReplacementIdle:n(()=>{L&&be()},"onReplacementIdle"),reWelcomeAll:n(()=>ie(),"reWelcomeAll")});const ye=n(async(e,r=!1)=>{const a=c.session(),f=G(a.model,a.thinkingLevel);if(f===null)return null;const v=await wn(t,{spec:f,...e!==void 0?{intent:e}:{},userSelected:r});return r&&(u.model=v.modelOverride,e!==void 0?(process.env.CRTR_MODEL_INTENT=`${e.family}/${e.strength}`,delete process.env.CRTR_MODEL_EXACT,u.modelExact=void 0):(delete process.env.CRTR_MODEL_INTENT,process.env.CRTR_MODEL_EXACT="1",u.modelExact=!0)),v.modelOverride},"persistModelChoice"),Re=n(async(e=!0,r,a=!1)=>{const f=c.session(),v=G(f.model,f.thinkingLevel),p=e?await ye(r,a):v;w.broadcast({type:"model_changed",model:le(f.model)?void 0:f.model,spec:p})},"broadcastModelChanged");Y=new Yt({nodeId:t,cfg:u,retryProbe:Ge,currentSession:n(()=>c.session(),"currentSession"),currentServices:n(()=>c.services(),"currentServices"),installedGeneration:n(()=>c.installedGeneration(),"installedGeneration"),registryOf:ce,formatModelSpec:G,broadcastModelChanged:Re,turnAdmission:oe,reWelcomeAll:n(()=>ie(),"reWelcomeAll"),...L?{turnEnds:re}:{}});const Ee=n(()=>{Y.rearmIfStranded().catch(e=>{b({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry re-arm failed: ${e instanceof Error?e.message:String(e)}`}})})},"rearmStrandedRetry");$().subscribe("resync",Ee),$().subscribe("fault-retry",Ee),W=new dn({registry:w,faultRetry:Y,installedGeneration:n(()=>c.installedGeneration(),"installedGeneration"),currentSession:n(()=>c.session(),"currentSession"),notifyTurnAccepted:n(()=>ge(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:G});const je=n(e=>{const r=c.session(),a=me(r,J),f=Cn(e.snapshotTail),v=a===void 0||f===void 0?a:a.slice(-f),p=v?.map(({message:U})=>U)??r.sessionManager.buildSessionContext().messages,R=M.summaries(),K=v!==void 0&&f!==void 0?On(p):void 0,Ye=K===void 0?R:Object.fromEntries(Object.entries(R).filter(([U])=>K.has(U)));return{messages:p,...v===void 0?{}:{messageIds:v.map(({id:U})=>U)},messageVisibility:v?.map(({visibility:U})=>U)??p.map(()=>"visible"),turnVisibility:Gt(),stats:r.getSessionStats(),state:{model:le(r.model)?void 0:r.model,thinkingLevel:r.thinkingLevel,isStreaming:r.isStreaming,isCompacting:r.isCompacting,steeringMode:r.steeringMode,followUpMode:r.followUpMode,sessionFile:r.sessionFile,sessionId:r.sessionId,sessionName:r.sessionName,autoCompactionEnabled:r.autoCompactionEnabled,messageCount:r.messages.length,pendingMessageCount:r.pendingMessageCount},display:{...w.displaySnapshot()},toolGroupSummaries:Ye,turnReplies:X.snapshot(),workingActivity:W.currentWorkingActivity(),queued:{steering:[...r.getSteeringMessages()],followUp:[...r.getFollowUpMessages()]}}},"buildSnapshot"),Te=n(e=>{const r=e.role==="controller"?z.values().next().value:void 0;w.sendFrame(e,{type:"welcome",snapshot:je(e),role:e.role,pending_dialog:r!==void 0?r.request:null,agentDir:ee()},!0)},"sendWelcome"),Ve=n(e=>{const r=[...z.values()];for(let a=1;a<r.length;a++)w.sendFrame(e,r[a].request)},"replayExtraPendingDialogsTo"),ie=n(()=>{try{const e=c.session();X.seed(me(e,J)?.map(({message:r})=>r)??e.sessionManager.buildSessionContext().messages)}catch(e){b({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply reseed failed: ${String(e)}`}})}w.forEachHelloed(Te)},"reWelcomeAll"),ke=n(async e=>{if(B)return;B=!0;const r=$().latestNode;r!==void 0&&(r.intent==="idle-release"||r.status==="done")&&_n(t,process.env.CRTR_EXECUTION_ID??null),$().stop(),e===0&&await ae().catch(async a=>{e=1,b({level:"error",event:"broker.exited",node_id:t,error:a,fields:{fault:"conversation_write_failed"}}),await Be(t,a)}),M.persistPendingSummary(),W.dispose(),Mn();try{Q?.close(),Z?.close()}catch{}i.close(),w.dispose();try{xe(q)&&Ae(q)}catch{}w.clearAttachState(),await Pe(),process.exit(e)},"completeExit"),C=n((e,r=0)=>{if(B)return;const a=e==="shutdown-hook"||e==="shutdown-after-settle";if(a&&M.finishOpenToolGroup(!0),a&&(M.hasSummaryTasks()||X.hasTasks())){if(fe)return;fe=!0,Promise.allSettled([M.waitForSummaryTasks(),X.waitForTasks()]).finally(()=>ke(r));return}ke(r)},"disposeAndExit");globalThis[Qt]=C,pe=Fn({writable:n(()=>w.writableClients(),"writable"),forward:n((e,r)=>w.sendFrame(e,r),"forward"),pending:z,broadcast:n(e=>w.broadcastUi(e),"broadcast"),onKnownStreamWait:n(e=>W.knownStreamWait(e),"onKnownStreamWait")}),c.setRebindSession(),await c.enqueueRebind(N,I),l("broker.startup.extensions_bound");const x=ln({nodeId:t,registry:w,toolGroups:M,projection:W,rebind:c,boundaryReviewId:J,pendingDialogs:z,sendWelcome:Te,replayExtraPendingDialogsTo:Ve,reWelcomeAll:ie,disposeAndExit:C,persistModelChoice:ye,broadcastModelChanged:Re,registryOf:ce,formatModelSpec:G,formatExactModelSpec:xn,turnAdmission:oe,memoryInventory:A,runNode:L,onKickoffAdmitted:P.releaseKickoff});ge=x.notifyTurnAccepted,ve=x.resetForSession,he=x.pendingPromptDispatches,globalThis[Zt]=async e=>{for(const R of Ot){const K=e.env[R];K===void 0?delete process.env[R]:process.env[R]=K}process.env[Fe]=e.origin,e.messageIds.length>0?process.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(e.messageIds):delete process.env.CRTR_KICKOFF_MESSAGE_IDS,e.model!==void 0?u.model=e.model:delete u.model,e.modelExact?(u.modelExact=!0,process.env.CRTR_MODEL_EXACT="1"):(delete u.modelExact,delete process.env.CRTR_MODEL_EXACT),u.editorName=e.editorLabel,P.holdForKickoff(),M.finishOpenToolGroup(!0);const r=c.session(),a=r.sessionManager.getSessionFile();if(a===void 0||a==="")throw new Error("in-place cycle needs a persisted session file");const f=r.sessionManager,v=f.getLeafId();f.resetLeaf(),f.appendCustomEntry(Ne,{cycle:e.cycle,fromLeaf:v}),await ae(),c.beforeNextBind(async R=>{const K=await Ue(t,R,"resume");await x.refreshMemoryNames(K?.names)});const p=await c.runReplacement(null,"cycle",R=>R.switchSession(a));if(c.beforeNextBind(void 0),!p)return C("cycle-replacement-failed",1),!1;Le(e.prompt,Ie(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await De(t,$e(t))}catch(R){return b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:R,fields:{operation:"attachments_fetch"}}),C("attachments-fetch-failed",1),!1}return x.kickoff(e.prompt,e.messageIds),!0};const qe=2500;let se=!1;const Xe=n(async e=>{if(B||se)return;if(se=!0,c.isAgentRunActive()||c.session().isStreaming||x.pendingPromptDispatches()>0){const a=Date.now()+qe;for(;x.pendingPromptDispatches()>0&&!c.session().isStreaming&&Date.now()<a;)await new Promise(f=>setTimeout(f,25));if(c.session().isStreaming){const f=a-Date.now();if(f>0){let v;try{pn(),await Promise.race([c.session().abort().then(()=>!0,()=>!1),new Promise(R=>{v=setTimeout(()=>R(!1),f)})])&&await Oe(t,{event:"closed",end_reason:"teardown-aborted"})}finally{v!==void 0&&clearTimeout(v)}}}else(x.pendingPromptDispatches()>0||c.isAgentRunActive())&&await Oe(t,{event:"interrupted"})}C(e)},"abortAndExit");if(y=n(e=>{Xe(e)},"signalTeardown"),T!==void 0){y(T);return}try{xe(q)&&Ae(q)}catch{}const Ce=n(e=>{const r=w.create(e);e.on("data",f=>{let v;try{v=r.decoder.push(f)}catch(p){p instanceof kn?(w.sendFrame(r,{type:"error",code:"frame_overflow",message:p.message}),w.dropClient(r,`frame overflow: ${p.message}`)):w.dropClient(r,`decoder error: ${String(p)}`);return}for(const p of v)try{cn(x,r,p)}catch{}});const a=n(()=>{w.removeClient(r)},"drop");e.on("close",a),e.on("error",()=>{})},"serveViewer");Q=rt(Ce),Mt()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(Z=new ot({host:"::",port:st,path:"/view",maxPayload:Tn.maxLineBytes}),Z.on("connection",e=>Ce(it(e))),Z.on("error",e=>{B||(b({level:"error",event:"broker.socket.failed",error:e}),C("socket-error",1))})),Q.on("error",e=>{B||(b({level:"error",event:"broker.socket.failed",error:e}),C("socket-error",1))}),Q.listen(q,async()=>{if(Promise.all([te(t,{op:"clear",link:"viewer\u2194broker"}),te(t,{op:"clear",link:"relay\u2194broker"})]).catch(r=>b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"broker_socket_bound_fault_clear"}})),E!==void 0){let r;try{try{r=await Ke(t,c.session(),E)}catch(a){b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:a,fields:{operation:"session_bound",attempt:1}}),r=await Ke(t,c.session(),E)}}catch(a){b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:a,fields:{operation:"session_bound",attempt:2}}),C("session-bound-failed",1);return}if(r?.action==="shutdown"){c.requestShutdown();return}if(r?.action==="relaunch_root")throw new Error("a startup bind never relaunches a root");$().start(t,Pt()),yn(),_e()}let e;try{e=await Y.recoverOnStartup()}catch(r){b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"recovery_startup"}}),C("recovery-startup-failed",1);return}if(!(B||se))if(e==="none"&&u.firstPrompt!==void 0&&u.firstPrompt!==""){const r=Ie(process.env[Fe]);r!==null&&Le(u.firstPrompt,r);try{await De(t,$e(t))}catch(f){b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:f,fields:{operation:"attachments_fetch"}}),C("attachments-fetch-failed",1);return}const a=process.env.CRTR_KICKOFF_MESSAGE_IDS;x.kickoff(u.firstPrompt,a?JSON.parse(a):[])}else P.releaseKickoff()}),w.persistAttachState()}n(Yr,"runBroker");function On(t){const o=new Set;for(const s of t)if(!(s.role!=="assistant"||!Array.isArray(s.content)))for(const g of s.content)g!==null&&typeof g=="object"&&g.type==="toolCall"&&typeof g.id=="string"&&o.add(g.id);return o}n(On,"toolCallIds");function me(t,o){const s=t.sessionManager,g=Kt(s);return g!==void 0&&mn(g.map(({message:i})=>i)),g===void 0?void 0:Wt(g,{boundaryReviewId:o,sessionEntries:s.getEntries?.()})}n(me,"snapshotMessages");function We(){const t=Ze();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}n(We,"currentBrokerNodeId");async function Dn(t,o){const s=Dt(o.model,ze(),o.modelExact===!0);if(s===void 0)return;const g=ce(t),i={cwd:Qe()??o.cwd,profileId:et()},d=await Ft(s,g,i);if(d!==void 0)throw await te(We(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`model '${d.request.spec}' is not registered in the serving model registry`}}),new Error(`[broker] FATAL: model '${d.request.spec}' is not registered in the serving model registry`);const m=await Nt(s,i.cwd,i.profileId),l=It(s.spec);for(const _ of m){const S=g.find(_.providerId,_.modelId);if(S===void 0)continue;const h=l?.providerId===_.providerId&&l.modelId===_.modelId?l.thinkingLevel??(_.thinkingLevel===void 0?void 0:"off"):_.thinkingLevel;return{model:S,thinkingLevel:h}}if(o.modelExact===!0){const _=m.map(S=>`'${S.providerId}/${S.modelId}' unregistered`).join("; ");throw await te(We(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`exact-consult model '${o.model}' is unavailable \u2014 refusing to substitute (${_})`}}),new Error(`[broker] FATAL: exact-consult model '${o.model}' is unavailable`)}b({level:"warn",event:"broker.model.none_viable",fields:{rejected_candidates:m.map(_=>({provider:_.providerId,model:_.modelId,reason:"unregistered"})).slice(0,16)}})}n(Dn,"resolveLaunchModel");function Nn(t){let o=!0;return{runtime:new Proxy(t,{get(g,i,d){return o&&i==="getAvailableSnapshot"?()=>[]:o&&i==="getAvailable"?async()=>[]:o&&i==="getModel"?()=>{}:Reflect.get(g,i,d)}}),reveal:n(()=>{o=!1},"reveal")}}n(Nn,"modelLessRegistry");async function In(t,o){const s=ee(),g=n(async h=>{const u=await ft.create({credentials:new Ct,modelsPath:Me(h.agentDir,"models.json")});xt(u);const y=await t.createAgentSessionServices({cwd:h.cwd,agentDir:h.agentDir,modelRuntime:u,resourceLoaderOptions:{additionalExtensionPaths:o.extensionPaths,appendSystemPrompt:o.appendSystemPromptPath!==void 0?[o.appendSystemPromptPath]:void 0,noContextFiles:!0,extensionsOverride:n(E=>({...E,extensions:E.extensions.filter(F=>!/[/\\]provider-rotation\.(?:ts|js)$/.test(F.path))}),"extensionsOverride")}}),T=y.resourceLoader.getExtensions();if(o.extensionPaths.some(E=>de.includes(E))){const E=new Set(T.extensions.map(A=>A.path)),F=de.filter(A=>!E.has(A));if(F.length>0){const A=T.errors.filter(V=>de.includes(V.path)).map(V=>`${V.path}: ${V.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${F.join(", ")}${A===""?"":` (${A})`}`)}}y.settingsManager.getRetryEnabled=()=>!1;const D=await Dn(y,o),H=D?.model,N=D?.thinkingLevel,I=D===void 0?Nn(y.modelRuntime):void 0,ue=I!==void 0?{...y,modelRuntime:I.runtime}:y,j=await t.createAgentSessionFromServices({services:ue,sessionManager:h.sessionManager,model:H,thinkingLevel:N,...Pn(o.tools,tt()),sessionStartEvent:h.sessionStartEvent});return un(j.session),kt(j.session),I?.reveal(),{...j,services:y}},"buildForManager"),i=o.resumeSessionPath,d=o.forkFrom!==void 0&&o.forkFrom!=="";if(!d&&(i===void 0||i==="")&&o.resumeSessionId!==void 0&&o.resumeSessionId!=="")throw new Error(`[broker] resume requires a session .jsonl PATH; got only a bare id '${o.resumeSessionId}' (pi_session_file was never captured for this node)`);const m=!d&&i!==void 0&&i!=="",l=m&&o.newCycle===!0,_=m&&!l;let S;if(d)S=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(_||l){if(S=await t.SessionManager.open(i),l){const h=S.getLeafId();S.resetLeaf(),S.appendCustomEntry(Ne,{cycle:Number(process.env.CRTR_CYCLES),fromLeaf:h})}}else S=await t.SessionManager.create(o.cwd);if(t.createAgentSessionRuntime!==void 0){const h=n(async y=>{const T=await g({cwd:y.cwd,agentDir:y.agentDir,sessionManager:y.sessionManager,sessionStartEvent:y.sessionStartEvent});return{...T,diagnostics:T.services.diagnostics??[]}},"factory"),u=await t.createAgentSessionRuntime(h,{cwd:o.cwd,agentDir:s,sessionManager:S});return{session:u.session,services:u.services,resuming:_,runtime:u}}const k=await g({cwd:o.cwd,agentDir:s,sessionManager:S});return{session:k.session,services:k.services,resuming:_,runtime:void 0}}n(In,"buildBrokerSession");function Fn(t){const o=n((i,d,m,l)=>{if(l?.signal?.aborted)return Promise.resolve(i);const _=t.writable();return _.length===0?Promise.resolve(i):new Promise(S=>{let k;const h=n(()=>{k!==void 0&&clearTimeout(k),l?.signal?.removeEventListener("abort",u),t.pending.delete(d.id)},"cleanup"),u=n(()=>{h(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),S(i)},"onAbort");l?.signal?.addEventListener("abort",u,{once:!0});const y=l?.timeout!==void 0?l.timeout:An;k=setTimeout(()=>{h(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),S(i)},y),typeof k.unref=="function"&&k.unref(),t.pending.set(d.id,{request:d,resolve:n(T=>{h(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),S(m(T))},"resolve")});for(const T of _)t.forward(T,d)})},"dialogPromise"),s=n(()=>{},"noop");return{[Lt]:t.onKnownStreamWait??(i=>()=>{}),get theme(){const i=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(i==null)throw new Error("Theme not initialized. Call initTheme() first.");return i},select:n((i,d,m)=>o(void 0,{type:"extension_ui_request",id:O(),method:"select",title:i,options:d,timeout:m?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,m),"select"),confirm:n((i,d,m)=>o(!1,{type:"extension_ui_request",id:O(),method:"confirm",title:i,message:d,timeout:m?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,m),"confirm"),input:n((i,d,m)=>o(void 0,{type:"extension_ui_request",id:O(),method:"input",title:i,placeholder:d,timeout:m?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,m),"input"),editor:n((i,d)=>o(void 0,{type:"extension_ui_request",id:O(),method:"editor",title:i,prefill:d},m=>"cancelled"in m&&m.cancelled?void 0:"value"in m?m.value:void 0),"editor"),setStatus:n((i,d)=>t.broadcast({type:"extension_ui_request",id:O(),method:"setStatus",statusKey:i,statusText:d}),"setStatus"),setWidget:n((i,d,m)=>{typeof d!="function"&&t.broadcast({type:"extension_ui_request",id:O(),method:"setWidget",widgetKey:i,widgetLines:d,widgetPlacement:m?.placement})},"setWidget"),setTitle:n(i=>t.broadcast({type:"extension_ui_request",id:O(),method:"setTitle",title:i}),"setTitle"),notify:n((i,d)=>{const m=d==="warn"?"warning":d;t.broadcast({type:"extension_ui_request",id:O(),method:"notify",message:i,notifyType:m})},"notify"),onTerminalInput:n(()=>s,"onTerminalInput"),setWorkingMessage:s,setWorkingVisible:s,setWorkingIndicator:s,setHiddenThinkingLabel:s,setFooter:s,setHeader:s,custom:n(()=>Promise.resolve(void 0),"custom"),pasteToEditor:s,setEditorText:s,getEditorText:n(()=>"","getEditorText"),addAutocompleteProvider:s,setEditorComponent:s,getEditorComponent:n(()=>{},"getEditorComponent"),getAllThemes:n(()=>[],"getAllThemes"),getTheme:n(()=>{},"getTheme"),setTheme:s,getToolsExpanded:n(()=>!1,"getToolsExpanded"),setToolsExpanded:s}}n(Fn,"makeBrokerUiContext");export{Qr as REVIEW_BOUNDARY_NAVIGATION_CODE,zr as ReviewBoundaryNavigationError,Pn as brokerToolOptions,In as buildBrokerSession,Mn as disposeActiveSession,Fn as makeBrokerUiContext,Yr as runBroker,me as snapshotMessages};
|
|
1
|
+
var nt=Object.defineProperty;var n=(t,o)=>nt(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as rt,envModelIntent as ot,envNodeCwd as st,envNodeId as it,envProfileId as at,envScopes as dt,scopeAllowed as lt}from"../../shared/env.js";import{createServer as ct}from"node:net";import{WebSocketServer as mt,createWebSocketStream as ut}from"ws";import{BROKER_VIEW_PORT as ft}from"./view-socket.js";import{existsSync as De,readFileSync as pt,unlinkSync as Ne,writeFileSync as gt}from"node:fs";import{join as Ie}from"node:path";import{randomUUID as I}from"node:crypto";import{mark as Fe}from"../timing.js";import{SUBMIT_RESULT_TOOL as vt}from"./structured-output.js";import{flushConversation as ue,installSessionManagerStorePatch as _t}from"../conversation-store/index.js";import{getAgentDir as oe,ModelRegistry as ht,ModelRuntime as bt}from"@earendil-works/pi-coding-agent";import{nodeRunDir as wt,viewSocketPath as St}from"../canvas/paths.js";import{bindBrokerEventSource as Rt}from"../events/source.js";import{emitEvent as b,flushBrokerLog as Le}from"../events/emit.js";import{operationIdContext as yt}from"../events/operation-id.js";import{findMissingPackagePaths as kt}from"./package-health.js";import{installBrokerConfigSnapshot as Et}from"../config.js";import{FRONT_DOOR_ENV as Tt}from"./front-door.js";import{CANVAS_EXTENSIONS as fe,piInvocationToSdkConfig as Ct}from"./launch.js";import{setConversationRequestMark as Be}from"../conversation-store/index.js";import{assertEngineVersion as At,loadBrokerEngine as Mt}from"./broker-sdk.js";import{initCrtrTheme as xt}from"./crtr-theme.js";import{resolveBundledPiPackageDir as Pt}from"./pi-cli.js";import{captureSessionChatCapabilities as Ot}from"./command-surface.js";import{InMemoryCredentialStore as Dt}from"@earendil-works/pi-ai";import{configureBrokerModelRuntime as Nt,refusalRetryAt as It}from"./broker/model-adapter.js";import{brokerApiUrl as Ft,brokerExecutionId as Lt,mutateBrokerFault as se,recordBrokerTurn as Ke}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as Bt}from"./launch-recipe.js";import{fetchRunAttachments as Ue}from"./broker/attachments-fetch.js";import{modelRequestFromConfig as Kt,expandModelCandidates as Ut,parseModelSpec as $t,unregisteredConcreteModel as Wt}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as Gt}from"./stream-watchdog.js";import{probeOnline as jt}from"./connectivity.js";import{CRTR_CYCLE_CUSTOM_TYPE as $e,cycleAwareMessages as Vt,endedByAbort as qt}from"./session-cycles.js";import{turnErrorOf as Xt}from"../llm/refusal.js";import{projectTranscript as Yt}from"./session-visibility.js";import{currentTurnVisibility as Ht}from"./turn-visibility.js";import{isUnknownModel as pe}from"./model-selection.js";import{BrokerClientRegistry as Jt}from"./broker/client-registry.js";import{ToolGroupTracker as zt}from"./broker/tool-groups.js";import{TurnReplyTracker as Qt}from"./broker/turn-replies.js";import{onNodeNamed as Zt}from"./broker/node-named.js";import{FaultRetry as en,willDaemonRetry as tn}from"./broker/fault-retry.js";import{RunTurnEnds as nn}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as rn}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as on,BROKER_START_CYCLE as sn,BROKER_IDLE_TURN_START as an,BROKER_RUN_TURN_BUSY as dn,BROKER_RUN_STEER as ln}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as cn}from"./broker/run-steer.js";import{prependRunDeferredMail as mn,settleRunDeferredMail as un}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as fn}from"./broker/run-turn-queue.js";import{EventProjection as pn}from"./broker/event-projection.js";import{createFrameDispatchContext as gn,handleFrame as vn}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as _n,installAdvertisedCommandInvocationContract as hn}from"./advertised-command-invocation.js";import{RebindDriver as bn}from"./broker/rebind.js";import{beginRuntimeTeardown as wn}from"./broker/extension-abort.js";import{receiveNodeToken as Sn}from"./broker/node-token.js";import{serveCliRelay as Rn}from"./broker/cli-relay.js";import{recordBrokerRelease as yn}from"./lifecycle.js";import{setTurnCauseSource as kn}from"./broker/turn-cause.js";import{decodeKickoffOrigin as We,KICKOFF_ORIGIN_ENV as Ge}from"./stamp/protocol.js";import{announceMessageOrigin as je}from"./stamp/channel.js";import{commitBrokerModel as En,recordConversationWriteFault as Ve}from"./broker/daemon-ops.js";import{bootExtensionState as Tn,holdStartupClaims as Cn,releaseStartupClaims as An}from"./broker/boot-state.js";import{bindCarriedStart as qe,publishCarriedStart as Mn,startCycle as Xe,takeCycleAttachments as Ye}from"./broker/cycle-start.js";import{composerNames as xn}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as Pn,FrameOverflowError as On,normalizeSnapshotTail as Dn}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as oo,REVIEW_BOUNDARY_NAVIGATION_CODE as so}from"./broker/frame-replies.js";function ge(t){return new ht(t.modelRuntime)}n(ge,"registryOf");function V(t,o){if(t==null||pe(t))return null;const s=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${s}`}n(V,"formatModelSpec");function Nn(t,o){const s=V(t,void 0);return s===null?null:`${s}:${o===void 0||o===""?"off":o}`}n(Nn,"formatExactModelSpec");const In=12e4;let ie=null;import{brokerSignalClient as G}from"./broker/signal-stream.js";function Fn(){G().stop();const t=ie;if(ie=null,t!==null)try{t.dispose()}catch{}}n(Fn,"disposeActiveSession");function Ln(t,o){const s=lt(o,"crtr:act")?void 0:["bash"],_=t!==void 0&&t.length>0?[...new Set([...t,vt])]:t===void 0?void 0:[...t];return{..._!==void 0?{tools:_}:{},...s!==void 0?{excludeTools:s}:{}}}n(Ln,"brokerToolOptions");async function to(t,o=process.hrtime.bigint(),s=new Date().toISOString()){Rt(t);const _=await Sn(),i=await Rn(t,_);process.env.CRTR_API_SOCKET=i.path,yt.fresh(()=>{b({level:"info",event:"broker.startup.cli_entry",ts:s,duration_ms:0,fields:{runtime_version:process.version,engine_version:null,model:null}}),b({level:"info",event:"broker.startup.module_loaded",duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:null,model:null}})});const d=new Set;let u=null;const l=n((e,r=null)=>{d.has(e)||(d.add(e),Fe(e,{duration_ms:Number(process.hrtime.bigint()-o)/1e6}),b({level:"info",event:e,duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:u,model:r}}))},"emitStartupMilestone"),v=n((e,r,a={})=>{const m=process.hrtime.bigint(),p=Number(m-r)/1e6,f=Number(m-o)/1e6;Fe(e,{duration_ms:p}),b({level:"info",event:e,duration_ms:p,fields:{at_ms:f,...a}})},"emitStartupStep");process.env[Tt]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,_t(t),Be(e=>v("broker.startup.conversation_request",process.hrtime.bigint()-BigInt(Math.round(e.durationMs*1e6)),{method:e.method,route:e.route,first_request:e.firstRequest,worker_age_ms:e.workerAgeMs}));const y=process.hrtime.bigint(),w=await Mt();v("broker.startup.engine_loaded",y);const A=process.hrtime.bigint();At(w.VERSION),v("broker.startup.version_checked",A),u=w.VERSION;const S=process.hrtime.bigint(),x=wt(t),k=Ie(x,"broker-launch.json"),C=JSON.parse(pt(k,"utf8"));if(!C.configSnapshot)throw new Error("broker launch is missing its config snapshot");if(Et(C.configSnapshot),C.start!==void 0){const{start:e,...r}=C;gt(k,JSON.stringify(r))}const g=Ct(C);g.modelExact===!0?process.env.CRTR_MODEL_EXACT="1":delete process.env.CRTR_MODEL_EXACT,v("broker.startup.launch_recipe_read",S);let F,q;const L=new AbortController,Z=n(e=>{F!==void 0?F(e):(q??=e,L.abort())},"onSignal");process.on("SIGTERM",()=>Z("SIGTERM")),process.on("SIGINT",()=>Z("SIGINT")),process.on("SIGUSR1",()=>{const e=process.env.CRTR_EXECUTION_ID;e!==void 0&&e!==""&&G().start(t,e)});const ae=process.hrtime.bigint();let{session:P,services:X,resuming:_e,runtime:Y}=await $n(w,g,(e,r)=>v(e,r));Be(void 0),v("broker.startup.session_build",ae),l("broker.startup.session_built");const E=C.start;E!==void 0&&Cn();const B=E===void 0?await Xe(t,P,"startup",L.signal):Mn(t,E);L.signal.aborted&&(P.dispose(),await Le(),process.exit(0));const O=B?.names===void 0?await xn(t):B.names,ee=(await Tn(t)).node.review_binding?.review_id,K=rt();ie=P;const Je=jt;try{process.env.PI_PACKAGE_DIR=Pt(),xt(X.settingsManager.getTheme(),oe(),!1)}catch(e){b({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of kt(oe()))b({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const J=St(t),h=new Jt(t),te=new Map,D=new zt(t,e=>h.broadcast(e)),z=new Qt(t,e=>h.broadcast(e));Zt(e=>h.broadcast({type:"node_named",...e}));let U=!1,he=!1,ne,re,be,c,Q;const de=new nn;let j,we=n(()=>{},"notifyTurnAccepted"),Se=n(()=>{},"resetFrameState"),Re=n(()=>{},"bindAnswered");const le=rn(E===void 0?void 0:new Promise(e=>{Re=e}));let ye=n(()=>0,"pendingPromptDispatches"),ke;const N=fn({runNode:K,session:n(()=>c.session(),"session"),isReplacing:n(()=>c.isReplacing(),"isReplacing"),pendingRebind:n(()=>c.pendingRebind(),"pendingRebind"),isAgentRunActive:n(()=>c.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:n(()=>ye(),"pendingDispatches"),turnAdmission:le,prependDeferred:n(e=>mn(t,e),"prependDeferred"),onError:n(e=>b({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),Ee=cn(N.steerable);globalThis[ln]=Ee,kn(()=>c.session());const Te=N.drain;g.firstPrompt!==void 0&&g.firstPrompt!==""&&N.holdForKickoff(),globalThis[an]=N.start,globalThis[dn]=N.busy,c=new bn({nodeId:t,cfg:g,session:P,services:X,runtime:Y,registry:h,toolGroups:D,turnReplies:z,runSteer:Ee,runNode:K,transcriptMessages:n(e=>ve(e,ee)?.map(({message:r})=>r)??e.sessionManager.buildSessionContext().messages,"transcriptMessages"),uiContext:n(()=>be,"uiContext"),faultRetry:n(()=>Q,"faultRetry"),projection:n(()=>j,"projection"),setActiveSession:n(e=>{if(ie=e,ke?.(),K||process.env.CRTR_RUN_ID){let r="stop",a,m=!1;ke=e.subscribe(p=>{if(p.type==="agent_start"&&(r="stop",a=void 0,m=!1,de.started()),p.type==="agent_end"){const f=[...p.messages??[]].reverse().find(R=>R.role==="assistant");f&&(r=f.stopReason,a=qt(f)?void 0:Xt(f,It(f)),m=f.role==="assistant"&&tn(f,e.model?.contextWindow))}p.type==="agent_settled"&&(de.settled(e.sessionManager,{stop_reason:r,...a?{error:a}:{}},m),K&&(ue().then(()=>un(t,e)).catch(async f=>{if(String(f?.message).startsWith("conversation_write_failed")){b({level:"error",event:"broker.exited",node_id:t,error:f,fields:{fault:"conversation_write_failed"}}),await Ve(t,f),T("conversation_write_failed",1);return}b({level:"error",event:"broker.run_deferred_mail.settle_failed",error:f})}),queueMicrotask(()=>{c.session()===e&&Te()})))})}},"setActiveSession"),disposeAndExit:n((e,r)=>T(e,r),"disposeAndExit"),onSessionRebind:n(()=>{Se()},"onSessionRebind"),onReplacementIdle:n(()=>{K&&Te()},"onReplacementIdle"),reWelcomeAll:n(()=>ce(),"reWelcomeAll")});const Ce=n(async(e,r=!1)=>{const a=c.session(),m=V(a.model,a.thinkingLevel);if(m===null)return null;const p=await En(t,{spec:m,...e!==void 0?{intent:e}:{},userSelected:r});return r&&(g.model=p.modelOverride,e!==void 0?(process.env.CRTR_MODEL_INTENT=`${e.family}/${e.strength}`,delete process.env.CRTR_MODEL_EXACT,g.modelExact=void 0):(delete process.env.CRTR_MODEL_INTENT,process.env.CRTR_MODEL_EXACT="1",g.modelExact=!0)),p.modelOverride},"persistModelChoice"),Ae=n(async(e=!0,r,a=!1)=>{const m=c.session(),p=V(m.model,m.thinkingLevel),f=e?await Ce(r,a):p;h.broadcast({type:"model_changed",model:pe(m.model)?void 0:m.model,spec:f})},"broadcastModelChanged");Q=new en({nodeId:t,cfg:g,retryProbe:Je,currentSession:n(()=>c.session(),"currentSession"),currentServices:n(()=>c.services(),"currentServices"),installedGeneration:n(()=>c.installedGeneration(),"installedGeneration"),registryOf:ge,formatModelSpec:V,broadcastModelChanged:Ae,turnAdmission:le,reWelcomeAll:n(()=>ce(),"reWelcomeAll"),...K?{turnEnds:de}:{}});const Me=n(()=>{Q.rearmIfStranded().catch(e=>{b({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry re-arm failed: ${e instanceof Error?e.message:String(e)}`}})})},"rearmStrandedRetry");G().subscribe("resync",Me),G().subscribe("fault-retry",Me),j=new pn({registry:h,faultRetry:Q,installedGeneration:n(()=>c.installedGeneration(),"installedGeneration"),currentSession:n(()=>c.session(),"currentSession"),notifyTurnAccepted:n(()=>we(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:V});const ze=n(e=>{const r=c.session(),a=ve(r,ee),m=Dn(e.snapshotTail),p=a===void 0||m===void 0?a:a.slice(-m),f=p?.map(({message:W})=>W)??r.sessionManager.buildSessionContext().messages,R=D.summaries(),$=p!==void 0&&m!==void 0?Bn(f):void 0,tt=$===void 0?R:Object.fromEntries(Object.entries(R).filter(([W])=>$.has(W)));return{messages:f,...p===void 0?{}:{messageIds:p.map(({id:W})=>W)},messageVisibility:p?.map(({visibility:W})=>W)??f.map(()=>"visible"),turnVisibility:Ht(),stats:r.getSessionStats(),state:{model:pe(r.model)?void 0:r.model,thinkingLevel:r.thinkingLevel,isStreaming:r.isStreaming,isCompacting:r.isCompacting,steeringMode:r.steeringMode,followUpMode:r.followUpMode,sessionFile:r.sessionFile,sessionId:r.sessionId,sessionName:r.sessionName,autoCompactionEnabled:r.autoCompactionEnabled,messageCount:r.messages.length,pendingMessageCount:r.pendingMessageCount},display:{...h.displaySnapshot()},toolGroupSummaries:tt,turnReplies:z.snapshot(),workingActivity:j.currentWorkingActivity(),queued:{steering:[...r.getSteeringMessages()],followUp:[...r.getFollowUpMessages()]}}},"buildSnapshot"),xe=n(e=>{const r=e.role==="controller"?te.values().next().value:void 0;h.sendFrame(e,{type:"welcome",snapshot:ze(e),role:e.role,pending_dialog:r!==void 0?r.request:null,agentDir:oe()},!0)},"sendWelcome"),Qe=n(e=>{const r=[...te.values()];for(let a=1;a<r.length;a++)h.sendFrame(e,r[a].request)},"replayExtraPendingDialogsTo"),ce=n(()=>{try{const e=c.session();z.seed(ve(e,ee)?.map(({message:r})=>r)??e.sessionManager.buildSessionContext().messages)}catch(e){b({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply reseed failed: ${String(e)}`}})}h.forEachHelloed(xe)},"reWelcomeAll"),Pe=n(async e=>{if(U)return;U=!0;const r=G().latestNode;r!==void 0&&(r.intent==="idle-release"||r.status==="done")&&yn(t,process.env.CRTR_EXECUTION_ID??null),G().stop(),e===0&&await ue().catch(async a=>{e=1,b({level:"error",event:"broker.exited",node_id:t,error:a,fields:{fault:"conversation_write_failed"}}),await Ve(t,a)}),D.persistPendingSummary(),j.dispose(),Fn();try{ne?.close(),re?.close()}catch{}i.close(),h.dispose();try{De(J)&&Ne(J)}catch{}h.clearAttachState(),await Le(),process.exit(e)},"completeExit"),T=n((e,r=0)=>{if(U)return;const a=e==="shutdown-hook"||e==="shutdown-after-settle";if(a&&D.finishOpenToolGroup(!0),a&&(D.hasSummaryTasks()||z.hasTasks())){if(he)return;he=!0,Promise.allSettled([D.waitForSummaryTasks(),z.waitForTasks()]).finally(()=>Pe(r));return}Pe(r)},"disposeAndExit");globalThis[on]=T,be=Wn({writable:n(()=>h.writableClients(),"writable"),forward:n((e,r)=>h.sendFrame(e,r),"forward"),pending:te,broadcast:n(e=>h.broadcastUi(e),"broadcast"),onKnownStreamWait:n(e=>j.knownStreamWait(e),"onKnownStreamWait")}),c.setRebindSession(),await c.enqueueRebind(P,X),l("broker.startup.extensions_bound");const M=gn({nodeId:t,registry:h,toolGroups:D,projection:j,rebind:c,boundaryReviewId:ee,pendingDialogs:te,sendWelcome:xe,replayExtraPendingDialogsTo:Qe,reWelcomeAll:ce,disposeAndExit:T,persistModelChoice:Ce,broadcastModelChanged:Ae,registryOf:ge,formatModelSpec:V,formatExactModelSpec:Nn,turnAdmission:le,memoryInventory:O,runNode:K,onKickoffAdmitted:N.releaseKickoff});we=M.notifyTurnAccepted,Se=M.resetForSession,ye=M.pendingPromptDispatches,globalThis[sn]=async e=>{for(const R of Bt){const $=e.env[R];$===void 0?delete process.env[R]:process.env[R]=$}process.env[Ge]=e.origin,e.messageIds.length>0?process.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(e.messageIds):delete process.env.CRTR_KICKOFF_MESSAGE_IDS,e.model!==void 0?g.model=e.model:delete g.model,e.modelExact?(g.modelExact=!0,process.env.CRTR_MODEL_EXACT="1"):(delete g.modelExact,delete process.env.CRTR_MODEL_EXACT),g.editorName=e.editorLabel,N.holdForKickoff(),D.finishOpenToolGroup(!0);const r=c.session(),a=r.sessionManager.getSessionFile();if(a===void 0||a==="")throw new Error("in-place cycle needs a persisted session file");const m=r.sessionManager,p=m.getLeafId();m.resetLeaf(),m.appendCustomEntry($e,{cycle:e.cycle,fromLeaf:p}),await ue(),c.beforeNextBind(async R=>{const $=await Xe(t,R,"resume");await M.refreshMemoryNames($?.names)});const f=await c.runReplacement(null,"cycle",R=>R.switchSession(a));if(c.beforeNextBind(void 0),!f)return T("cycle-replacement-failed",1),!1;je(e.prompt,We(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await Ue(t,Ye(t))}catch(R){return b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:R,fields:{operation:"attachments_fetch"}}),T("attachments-fetch-failed",1),!1}return M.kickoff(e.prompt,e.messageIds),!0};const Ze=2500;let me=!1;const et=n(async e=>{if(U||me)return;if(me=!0,c.isAgentRunActive()||c.session().isStreaming||M.pendingPromptDispatches()>0){const a=Date.now()+Ze;for(;M.pendingPromptDispatches()>0&&!c.session().isStreaming&&Date.now()<a;)await new Promise(m=>setTimeout(m,25));if(c.session().isStreaming){const m=a-Date.now();if(m>0){let p;try{wn(),await Promise.race([c.session().abort().then(()=>!0,()=>!1),new Promise(R=>{p=setTimeout(()=>R(!1),m)})])&&await Ke(t,{event:"closed",end_reason:"teardown-aborted"})}finally{p!==void 0&&clearTimeout(p)}}}else(M.pendingPromptDispatches()>0||c.isAgentRunActive())&&await Ke(t,{event:"interrupted"})}T(e)},"abortAndExit");if(F=n(e=>{et(e)},"signalTeardown"),q!==void 0){F(q);return}try{De(J)&&Ne(J)}catch{}const Oe=n(e=>{l("broker.startup.first_viewer_connected");const r=h.create(e);e.on("data",m=>{let p;try{p=r.decoder.push(m)}catch(f){f instanceof On?(h.sendFrame(r,{type:"error",code:"frame_overflow",message:f.message}),h.dropClient(r,`frame overflow: ${f.message}`)):h.dropClient(r,`decoder error: ${String(f)}`);return}for(const f of p)try{vn(M,r,f)}catch{}});const a=n(()=>{h.removeClient(r)},"drop");e.on("close",a),e.on("error",()=>{})},"serveViewer");ne=ct(Oe),Ft()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(re=new mt({host:"::",port:ft,path:"/view",maxPayload:Pn.maxLineBytes}),re.on("connection",e=>Oe(ut(e))),re.on("error",e=>{U||(b({level:"error",event:"broker.socket.failed",error:e}),T("socket-error",1))})),ne.on("error",e=>{U||(b({level:"error",event:"broker.socket.failed",error:e}),T("socket-error",1))}),ne.listen(J,async()=>{if(l("broker.startup.listening"),Promise.all([se(t,{op:"clear",link:"viewer\u2194broker"}),se(t,{op:"clear",link:"relay\u2194broker"})]).catch(r=>b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"broker_socket_bound_fault_clear"}})),E!==void 0){let r;try{try{r=await qe(t,c.session(),E)}catch(a){b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:a,fields:{operation:"session_bound",attempt:1}}),r=await qe(t,c.session(),E)}}catch(a){b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:a,fields:{operation:"session_bound",attempt:2}}),T("session-bound-failed",1);return}if(r?.action==="shutdown"){c.requestShutdown();return}if(r?.action==="relaunch_root")throw new Error("a startup bind never relaunches a root");G().start(t,Lt()),An(),Re()}let e;try{e=await Q.recoverOnStartup()}catch(r){b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"recovery_startup"}}),T("recovery-startup-failed",1);return}if(!(U||me))if(e==="none"&&g.firstPrompt!==void 0&&g.firstPrompt!==""){const r=We(process.env[Ge]);r!==null&&je(g.firstPrompt,r);try{await Ue(t,Ye(t))}catch(m){b({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:m,fields:{operation:"attachments_fetch"}}),T("attachments-fetch-failed",1);return}const a=process.env.CRTR_KICKOFF_MESSAGE_IDS;M.kickoff(g.firstPrompt,a?JSON.parse(a):[])}else N.releaseKickoff()}),h.persistAttachState()}n(to,"runBroker");function Bn(t){const o=new Set;for(const s of t)if(!(s.role!=="assistant"||!Array.isArray(s.content)))for(const _ of s.content)_!==null&&typeof _=="object"&&_.type==="toolCall"&&typeof _.id=="string"&&o.add(_.id);return o}n(Bn,"toolCallIds");function ve(t,o){const s=t.sessionManager,_=Vt(s);return _!==void 0&&_n(_.map(({message:i})=>i)),_===void 0?void 0:Yt(_,{boundaryReviewId:o,sessionEntries:s.getEntries?.()})}n(ve,"snapshotMessages");function He(){const t=it();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}n(He,"currentBrokerNodeId");async function Kn(t,o){const s=Kt(o.model,ot(),o.modelExact===!0);if(s===void 0)return;const _=ge(t),i={cwd:st()??o.cwd,profileId:at()},d=await Wt(s,_,i);if(d!==void 0)throw await se(He(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`model '${d.request.spec}' is not registered in the serving model registry`}}),new Error(`[broker] FATAL: model '${d.request.spec}' is not registered in the serving model registry`);const u=await Ut(s,i.cwd,i.profileId),l=$t(s.spec);for(const v of u){const y=_.find(v.providerId,v.modelId);if(y===void 0)continue;const A=l?.providerId===v.providerId&&l.modelId===v.modelId?l.thinkingLevel??(v.thinkingLevel===void 0?void 0:"off"):v.thinkingLevel;return{model:y,thinkingLevel:A}}if(o.modelExact===!0){const v=u.map(y=>`'${y.providerId}/${y.modelId}' unregistered`).join("; ");throw await se(He(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`exact-consult model '${o.model}' is unavailable \u2014 refusing to substitute (${v})`}}),new Error(`[broker] FATAL: exact-consult model '${o.model}' is unavailable`)}b({level:"warn",event:"broker.model.none_viable",fields:{rejected_candidates:u.map(v=>({provider:v.providerId,model:v.modelId,reason:"unregistered"})).slice(0,16)}})}n(Kn,"resolveLaunchModel");function Un(t){let o=!0;return{runtime:new Proxy(t,{get(_,i,d){return o&&i==="getAvailableSnapshot"?()=>[]:o&&i==="getAvailable"?async()=>[]:o&&i==="getModel"?()=>{}:Reflect.get(_,i,d)}}),reveal:n(()=>{o=!1},"reveal")}}n(Un,"modelLessRegistry");async function $n(t,o,s=()=>{}){const _=oe(),i=n(async S=>{const x=process.hrtime.bigint(),k=await bt.create({credentials:new Dt,modelsPath:Ie(S.agentDir,"models.json")});Nt(k),s("broker.startup.model_runtime",x);const C=process.hrtime.bigint(),g=await t.createAgentSessionServices({cwd:S.cwd,agentDir:S.agentDir,modelRuntime:k,resourceLoaderOptions:{additionalExtensionPaths:o.extensionPaths,appendSystemPrompt:o.appendSystemPromptPath!==void 0?[o.appendSystemPromptPath]:void 0,noContextFiles:!0,extensionsOverride:n(E=>({...E,extensions:E.extensions.filter(B=>!/[/\\]provider-rotation\.(?:ts|js)$/.test(B.path))}),"extensionsOverride")}});s("broker.startup.resources_loaded",C);const F=g.resourceLoader.getExtensions();if(o.extensionPaths.some(E=>fe.includes(E))){const E=new Set(F.extensions.map(O=>O.path)),B=fe.filter(O=>!E.has(O));if(B.length>0){const O=F.errors.filter(H=>fe.includes(H.path)).map(H=>`${H.path}: ${H.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${B.join(", ")}${O===""?"":` (${O})`}`)}}g.settingsManager.getRetryEnabled=()=>!1;const q=process.hrtime.bigint(),L=await Kn(g,o);s("broker.startup.model_resolved",q);const Z=L?.model,ae=L?.thinkingLevel,P=L===void 0?Un(g.modelRuntime):void 0,X=P!==void 0?{...g,modelRuntime:P.runtime}:g,_e=process.hrtime.bigint(),Y=await t.createAgentSessionFromServices({services:X,sessionManager:S.sessionManager,model:Z,thinkingLevel:ae,...Ln(o.tools,dt()),sessionStartEvent:S.sessionStartEvent});return s("broker.startup.session_from_services",_e),hn(Y.session),Ot(Y.session),P?.reveal(),{...Y,services:g}},"buildForManager"),d=o.resumeSessionPath,u=o.forkFrom!==void 0&&o.forkFrom!=="";if(!u&&(d===void 0||d==="")&&o.resumeSessionId!==void 0&&o.resumeSessionId!=="")throw new Error(`[broker] resume requires a session .jsonl PATH; got only a bare id '${o.resumeSessionId}' (pi_session_file was never captured for this node)`);const l=!u&&d!==void 0&&d!=="",v=l&&o.newCycle===!0,y=l&&!v;let w;if(u)w=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(y||v){if(w=await t.SessionManager.open(d),v){const S=w.getLeafId();w.resetLeaf(),w.appendCustomEntry($e,{cycle:Number(process.env.CRTR_CYCLES),fromLeaf:S})}}else{const S=process.hrtime.bigint();w=await t.SessionManager.create(o.cwd),s("broker.startup.conversation_created",S)}if(t.createAgentSessionRuntime!==void 0){const S=n(async k=>{const C=await i({cwd:k.cwd,agentDir:k.agentDir,sessionManager:k.sessionManager,sessionStartEvent:k.sessionStartEvent});return{...C,diagnostics:C.services.diagnostics??[]}},"factory"),x=await t.createAgentSessionRuntime(S,{cwd:o.cwd,agentDir:_,sessionManager:w});return{session:x.session,services:x.services,resuming:y,runtime:x}}const A=await i({cwd:o.cwd,agentDir:_,sessionManager:w});return{session:A.session,services:A.services,resuming:y,runtime:void 0}}n($n,"buildBrokerSession");function Wn(t){const o=n((i,d,u,l)=>{if(l?.signal?.aborted)return Promise.resolve(i);const v=t.writable();return v.length===0?Promise.resolve(i):new Promise(y=>{let w;const A=n(()=>{w!==void 0&&clearTimeout(w),l?.signal?.removeEventListener("abort",S),t.pending.delete(d.id)},"cleanup"),S=n(()=>{A(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(i)},"onAbort");l?.signal?.addEventListener("abort",S,{once:!0});const x=l?.timeout!==void 0?l.timeout:In;w=setTimeout(()=>{A(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(i)},x),typeof w.unref=="function"&&w.unref(),t.pending.set(d.id,{request:d,resolve:n(k=>{A(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(u(k))},"resolve")});for(const k of v)t.forward(k,d)})},"dialogPromise"),s=n(()=>{},"noop");return{[Gt]:t.onKnownStreamWait??(i=>()=>{}),get theme(){const i=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(i==null)throw new Error("Theme not initialized. Call initTheme() first.");return i},select:n((i,d,u)=>o(void 0,{type:"extension_ui_request",id:I(),method:"select",title:i,options:d,timeout:u?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,u),"select"),confirm:n((i,d,u)=>o(!1,{type:"extension_ui_request",id:I(),method:"confirm",title:i,message:d,timeout:u?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,u),"confirm"),input:n((i,d,u)=>o(void 0,{type:"extension_ui_request",id:I(),method:"input",title:i,placeholder:d,timeout:u?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,u),"input"),editor:n((i,d)=>o(void 0,{type:"extension_ui_request",id:I(),method:"editor",title:i,prefill:d},u=>"cancelled"in u&&u.cancelled?void 0:"value"in u?u.value:void 0),"editor"),setStatus:n((i,d)=>t.broadcast({type:"extension_ui_request",id:I(),method:"setStatus",statusKey:i,statusText:d}),"setStatus"),setWidget:n((i,d,u)=>{typeof d!="function"&&t.broadcast({type:"extension_ui_request",id:I(),method:"setWidget",widgetKey:i,widgetLines:d,widgetPlacement:u?.placement})},"setWidget"),setTitle:n(i=>t.broadcast({type:"extension_ui_request",id:I(),method:"setTitle",title:i}),"setTitle"),notify:n((i,d)=>{const u=d==="warn"?"warning":d;t.broadcast({type:"extension_ui_request",id:I(),method:"notify",message:i,notifyType:u})},"notify"),onTerminalInput:n(()=>s,"onTerminalInput"),setWorkingMessage:s,setWorkingVisible:s,setWorkingIndicator:s,setHiddenThinkingLabel:s,setFooter:s,setHeader:s,custom:n(()=>Promise.resolve(void 0),"custom"),pasteToEditor:s,setEditorText:s,getEditorText:n(()=>"","getEditorText"),addAutocompleteProvider:s,setEditorComponent:s,getEditorComponent:n(()=>{},"getEditorComponent"),getAllThemes:n(()=>[],"getAllThemes"),getTheme:n(()=>{},"getTheme"),setTheme:s,getToolsExpanded:n(()=>!1,"getToolsExpanded"),setToolsExpanded:s}}n(Wn,"makeBrokerUiContext");export{so as REVIEW_BOUNDARY_NAVIGATION_CODE,oo as ReviewBoundaryNavigationError,Ln as brokerToolOptions,$n as buildBrokerSession,Fn as disposeActiveSession,Wn as makeBrokerUiContext,to as runBroker,ve as snapshotMessages};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var E=Object.defineProperty;var p=(i,s)=>E(i,"name",{value:s,configurable:!0});import{existsSync as x,statSync as b}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as A}from"../../build-root.js";import{FRONT_DOOR_ENV as L}from"./front-door-env.js";import{frontDoorBootPrompt as M}from"./first-run-offer.js";import{readMachineConfig as W}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as $}from"./node-id-token.js";import{markTourOffered as B,recordSetupCompleted as G,setupCompleted as V,tourOfferPending as U}from"./setup-marker.js";function I(i){try{return x(i)&&b(i).isDirectory()}catch{return!1}}p(I,"isDir");const Y=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function j(){let i=!1;const s=p(()=>{i=!0},"onSigint");process.once("SIGINT",s);try{const{runSetup:t}=await import("../../commands/sys/setup-wizard.js"),e=await t();if(i){const c=new Error("Interrupted");throw c.name="AbortError",c}await G(e)}finally{process.removeListener("SIGINT",s)}}p(j,"runFirstSetup");function J(i){let s=process.cwd(),t,e,c,u=!1,m,a;const
|
|
1
|
+
var E=Object.defineProperty;var p=(i,s)=>E(i,"name",{value:s,configurable:!0});import{existsSync as x,statSync as b}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as A}from"../../build-root.js";import{FRONT_DOOR_ENV as L}from"./front-door-env.js";import{frontDoorBootPrompt as M}from"./first-run-offer.js";import{readMachineConfig as W}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as $}from"./node-id-token.js";import{markTourOffered as B,recordSetupCompleted as G,setupCompleted as V,tourOfferPending as U}from"./setup-marker.js";function I(i){try{return x(i)&&b(i).isDirectory()}catch{return!1}}p(I,"isDir");const Y=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function j(){let i=!1;const s=p(()=>{i=!0},"onSigint");process.once("SIGINT",s);try{const{runSetup:t}=await import("../../commands/sys/setup-wizard.js"),e=await t();if(i){const c=new Error("Interrupted");throw c.name="AbortError",c}await G(e)}finally{process.removeListener("SIGINT",s)}}p(j,"runFirstSetup");function J(i){let s=process.cwd(),t,e,c,u=!1,m,a;const n=[];for(let f=0;f<i.length;f++){const o=i[f];if(o==="--name")t=i[++f];else if(o==="--kind")e=i[++f];else if(o==="--profile")c=i[++f];else if(o==="--pick-profile")u=!0;else if(o==="--continue"||o==="-c")m="continue";else if(o==="--resume"||o==="-r"){m="pick";const w=i[f+1];w!==void 0&&$(w)&&!I(h(w))&&(a=w,f++)}else o.startsWith("--")||n.push(o)}n.length>0&&I(h(n[0]))&&(s=h(n.shift()));const g=n.length>0?n.join(" "):void 0;return{cwd:s,prompt:g,name:t,kind:e,profile:c,pickProfile:u,resume:m,resumeId:a}}p(J,"parseRootArgs");import{FRONT_DOOR_ENV as se}from"./front-door-env.js";async function ie(i){const s=i.slice(2),t=s[0];if(process.env[L]||t==="-h"||t==="--help"||t==="--version"||t==="-v"||t!==void 0&&A.includes(t))return!1;if(t!==void 0){const r=/\s/.test(t),d=!t.startsWith("-")&&I(h(t)),l=Y.has(t);if(!r&&!d&&!l)return!1;if(d){const{buildRoot:C}=await import("../../build-root.js");if((await C()).subtrees.some(D=>D.name===t))return!1}}const e=J(s),c=p(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:r}=await import("../profiles/manifest.js");e.profile=r(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await c();const u=process.stdin.isTTY&&process.stdout.isTTY;let m=!1;u&&!V()&&(await j(),m=!0);let a=null,n,g=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:r,noResumeTargetMessage:d}=await import("./resume-root.js"),l=await r(e.resumeId);"error"in l&&(process.stderr.write(`${l.error}
|
|
2
2
|
`),process.exit(1)),"none"in l?(e.resumeId.includes("-")&&(process.stderr.write(`${d(e.resumeId)}
|
|
3
|
-
`),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await c()):(a=l.node.profile_id,
|
|
3
|
+
`),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await c()):(a=l.node.profile_id,n=l.node.node_id,I(l.node.cwd)&&(g=l.node.cwd))}if(n===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:d}=await import("../profiles/select.js");m&&e.profile===void 0&&process.stdout.write(`
|
|
4
4
|
Choose a profile
|
|
5
|
-
`),a=e.profile??(u?await r(e.cwd,void 0,e.pickProfile,!1):d(e.cwd))}const{
|
|
5
|
+
`),a=e.profile??(u?await r(e.cwd,void 0,e.pickProfile,!1):d(e.cwd))}const{cliClient:f}=await import("../../commands/api-client.js"),[{exitForMissingProviderCredential:o,hasConfiguredProviderCredential:w},R]=await Promise.all([import("./provider-credential-gate.js"),a===null?[]:f().listProfileEnv(a).then(r=>r.names)]),k=p(async()=>{const r=await f().getModelAuthReadiness({cwd:e.cwd,...a===null?{}:{profile:a}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await w(R)&&!await k()){u||o();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||o()}const{inTmux:P}=await import("./placement-tmux.js");if(u&&!P()){const{TMUX_STARTED_ENV:r,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[r]===void 0&&d(s,n!==void 0?null:a,g)}const[{bootRoot:v},{resumeRoot:y},{rendererWarning:N,missingPackageWarning:O,piAgentDir:S}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=O(S());r!==null&&process.stderr.write(`
|
|
6
6
|
${r}
|
|
7
7
|
|
|
8
8
|
`);const d=N();d!==null&&process.stderr.write(`
|
|
9
9
|
${d}
|
|
10
10
|
|
|
11
|
-
`)}catch{}if(
|
|
11
|
+
`)}catch{}if(n!==void 0){const{resumeNodeById:r}=await import("./resume-root.js");await r(n)}if(e.resume!==void 0&&await y(e.cwd,e.resume==="pick")==="aborted")return!0;const T=u&&(m||await U()),{prompt:F,initialWhip:_}=M({offerTour:T,signedIn:T&&W()!==void 0,userPrompt:e.prompt});return T&&P()&&await B(),await v({...e,prompt:F,initialWhip:_,selectedProfileId:a??void 0}),!0}p(ie,"maybeBootRoot");export{se as FRONT_DOOR_ENV,ie as maybeBootRoot,J as parseRootArgs};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as K}from"node:child_process";import{constants as
|
|
2
|
-
`).map(r=>r.trim()).filter(r=>r!==""),"lines")
|
|
1
|
+
var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as K}from"node:child_process";import{constants as v,lstatSync as j,mkdirSync as q,readFileSync as z,readdirSync as H,readlinkSync as J,rmSync as W,writeFileSync as _}from"node:fs";import{join as E,relative as V}from"node:path";import{crc32 as Z,deflateRawSync as Q}from"node:zlib";import{BlaxelApiError as X}from"./client.js";const tt="public.ecr.aws/docker/library/node:24-alpine",et="ghcr.io/blaxel-ai/sandbox:latest",f="crtr",A="/var/lib/crtr/recipe-pi-agent",rt="1.1.0",b="recipe-setup.sh",L="repos",D="/work/.crtr/setup.log",P="/work/.crtr/setup-failed",B=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),nt=c(t=>(t??"").split(`
|
|
2
|
+
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${D} 2>&1 || echo ${B(t)} "exited $?" >> ${P}`,"guarded");function st(t,r,i=!1){const o=nt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${tt}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${et} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${f} -s /bin/sh ${f} && mkdir -p /work/.crtr ${A} && chown -R ${f} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${P} ${D}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${f} ${L}/ /work/`),o.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${rt}`)),a&&e.push(`COPY ${b} /tmp/${b}`),e.push("WORKDIR /work");for(const s of o)e.push($(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${A} pi install ${B(s)}`));a&&e.push($("setup script",`bash /tmp/${b}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${f} /work /home/${f} /var/lib/crtr`)),e.push("",...n);for(const s of["/work",`/home/${f}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${f}:${f} ${s} ${s}`);for(const s of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${s} ${s}`);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 /home/${f}/.npmrc`),e.push(`USER ${f}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
|
|
3
3
|
`)}c(st,"recipeDockerfile");const ot=c((t,r,i)=>new Promise((o,a)=>{const n=K("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",s=>{e+=s.toString()}),n.on("error",a),n.on("close",s=>{s===0?o():a(new Error(`git ${t[0]} failed (${s}): ${e.slice(0,300)}`))})}),"runGit");async function ht(t){const r=t.git??ot,i=t.packagesToken??null,o=t.cloneUrl??(n=>`https://github.com/${n}.git`);q(E(t.dir,L),{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,o(n.github_full_name),E(L,n.name)],a,t.dir)}_(E(t.dir,"Dockerfile"),st(t.recipe,t.revision,i!==null)),i!==null&&_(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
|
|
4
4
|
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&_(E(t.dir,b),t.recipe.setup_script.endsWith(`
|
|
5
5
|
`)?t.recipe.setup_script:`${t.recipe.setup_script}
|
|
6
|
-
`)}c(ht,"prepareBuildDir");function C(t,r,i){for(const o of H(r).sort()){const a=E(r,o),n=j(a),e=V(t,a).split("\\").join("/");n.isDirectory()?C(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(J(a)),mode:
|
|
6
|
+
`)}c(ht,"prepareBuildDir");function C(t,r,i){for(const o of H(r).sort()){const a=E(r,o),n=j(a),e=V(t,a).split("\\").join("/");n.isDirectory()?C(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(J(a)),mode:v.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:z(a),mode:v.S_IFREG|n.mode&511})}}c(C,"walk");function it(t){const r=[];C(t,t,r);const i=[],o=[];let a=0;for(const s of r){const u=Buffer.from(s.name),g=Q(s.data),I=Z(s.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE(I,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(u.length,26),i.push(p,u,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(s.data.length,24),l.writeUInt16LE(u.length,28),l.writeUInt32LE(s.mode<<16>>>0,38),l.writeUInt32LE(a,42),o.push(l,u),a+=p.length+u.length+g.length}const n=Buffer.concat(o),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(it,"zipDirectory");async function R(t,r,i,o,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"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await e.text();let u=null;if(s!=="")try{u=JSON.parse(s)}catch{u={raw:s}}if(!e.ok&&!a.includes(e.status))throw new X(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${s.slice(0,300)}`);return{status:e.status,headers:e.headers,json:u}}c(R,"api");async function G(t,r){const{status:i,json:o}=await R(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:o}c(G,"getImage");async function mt(t,r){await R(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(mt,"deleteImage");async function wt(t,r,i,o={}){const a=o.sleep??(h=>new Promise(d=>setTimeout(d,h))),n=o.now??Date.now,e=n(),s=await G(t,r),u=new Set((s?.spec?.tags??[]).map(h=>h.name)),g=c(h=>(h?.metadata?.events??[]).map(d=>Date.parse(d.time??"")).filter(d=>!Number.isNaN(d)),"eventTimes"),I=Math.max(-1/0,...g(s)),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(it(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const F=e+(o.timeoutMs??20*6e4);let N=null;for(;;){const h=await G(t,r),d=h?.metadata?.status,k=g(h).filter(m=>m>I).sort((m,x)=>m-x);if(d==="BUILT"&&k.length>=2){N??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],O=c(w=>Date.parse(w??"")>=x,"touchedSince"),T=m.filter(w=>!u.has(w.name)||O(w.createdAt)||O(w.updatedAt)),y=n()-N>=(o.tagGraceMs??6e4),S=(T.length>0?T:y?m:[]).sort((w,M)=>(M.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(S!==void 0)return{ref:`sandbox/${r}:${S}`,buildMs:n()-e};if(y)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(d==="FAILED"||d==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${d.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>F)throw new Error(`building image ${r} did not finish within ${o.timeoutMs??20*6e4} ms (last status ${d??"none"})`);await a(o.pollMs??3e3)}}c(wt,"buildImage");const gt=c(t=>`env-${t}`,"environmentImageName");function Et(t){W(t,{recursive:!0,force:!0})}c(Et,"removeBuildDir");export{tt as NODE_BASE_IMAGE,A as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,f as RUN_USER,et as SANDBOX_API_IMAGE,P as SETUP_FAILED_FILE,D as SETUP_LOG_FILE,b as SETUP_SCRIPT_FILE,wt as buildImage,mt as deleteImage,gt as environmentImageName,G as getImage,ht as prepareBuildDir,st as recipeDockerfile,Et as removeBuildDir,it as zipDirectory};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var p=Object.defineProperty;var o=(e,r)=>p(e,"name",{value:r,configurable:!0});import{createHash as
|
|
1
|
+
var p=Object.defineProperty;var o=(e,r)=>p(e,"name",{value:r,configurable:!0});import{createHash as E}from"node:crypto";import{copyFileSync as f,mkdtempSync as g,readFileSync as w,writeFileSync as d}from"node:fs";import{tmpdir as R}from"node:os";import{join as c}from"node:path";import{buildImage as S,NODE_BASE_IMAGE as h,removeBuildDir as b,RUN_USER as n,SANDBOX_API_IMAGE as u}from"./image-build.js";const x="/opt/crtr/releases",y=".sha256",I=".complete",i="runtime.tar.gz",A=/^[0-9a-f]{64}$/,O=/^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$/,l=o(e=>`releases/${e}/sandbox-image.json`,"releaseImageKey");function $(e){if(!O.test(e))throw new Error(`${JSON.stringify(e)} is not a release version`);const r=`crtr-release-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`;if(r.length>63)throw new Error(`image name ${r} is longer than 63 characters`);return r}o($,"releaseImageName");function N(e,r){if(!A.test(r))throw new Error("sha256 must be 64 lowercase hex characters");$(e);const a=`${x}/${e}`;return[`FROM ${h} AS release`,`COPY ${i} /tmp/${i}`,`RUN mkdir -p ${a} && tar -xzf /tmp/${i} -C ${a} && echo ${r} > ${a}/${y} && : > ${a}/${I}`,"",`FROM ${h}`,"RUN apk add --no-cache bash git curl ripgrep python3",`COPY --from=${u} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${n} -s /bin/sh ${n} && mkdir -p /run/crtr /var/lib/crtr /work/.crtr && chown -R ${n} /run/crtr /var/lib/crtr /work`,"COPY --from=release /opt/crtr /opt/crtr",`USER ${n}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""].join(`
|
|
2
2
|
`)}o(N,"releaseImageDockerfile");function C(e){return`${JSON.stringify(e)}
|
|
3
|
-
`}o(C,"releaseImagePointerText");function
|
|
3
|
+
`}o(C,"releaseImagePointerText");function U(e,r,a){let s;try{s=JSON.parse(e)}catch{throw new Error(`${l(r)} is not JSON`)}const t=s;if(t===null||typeof t!="object"||typeof t.release!="string"||typeof t.sha256!="string"||typeof t.image!="string"||t.image==="")throw new Error(`${l(r)} must hold {release, sha256, image}`);if(t.release!==r)throw new Error(`${l(r)} names release ${t.release}`);if(t.sha256!==a)throw new Error(`${l(r)} was built from tarball ${t.sha256}, not ${a}`);return t.image}o(U,"parseReleaseImagePointer");async function M(e,r,a={}){const s=E("sha256").update(w(r.tarball)).digest("hex");if(s!==r.sha256)throw new Error(`${r.tarball} has sha256 ${s}, not ${r.sha256}`);const t=g(c(R(),"crtr-release-image-"));try{f(r.tarball,c(t,i)),d(c(t,"Dockerfile"),N(r.release,r.sha256));const m=await S(e,$(r.release),t,a);return{pointer:{release:r.release,sha256:r.sha256,image:m.ref},built:m}}finally{b(t)}}o(M,"buildReleaseImage");export{x as RELEASES_DIR,I as RELEASE_COMPLETE_FILE,y as RELEASE_SHA_FILE,i as RELEASE_TARBALL_FILE,M as buildReleaseImage,U as parseReleaseImagePointer,N as releaseImageDockerfile,l as releaseImageKey,$ as releaseImageName,C as releaseImagePointerText};
|
|
@@ -2,6 +2,11 @@ import { type MachineOp, type MachineOpTable } from './ops.js';
|
|
|
2
2
|
/** Seconds a caller waits: `start` 60, every other op 15 (design). The `worktree.*` ops run Git under a repository lock that waits up to
|
|
3
3
|
* 25 s, so they get 60 too (`worktree.finalize` also asks origin, bounded at 10 s). */
|
|
4
4
|
export declare const MACHINE_CALL_TIMEOUT_S: Record<MachineOp, number>;
|
|
5
|
+
/** When a call was queued and when its holder settled it (epoch ms), for the create request's step timings. Null when the row is gone or unsettled. */
|
|
6
|
+
export declare function callTimes(callId: string): Promise<{
|
|
7
|
+
createdAt: number;
|
|
8
|
+
finishedAt: number;
|
|
9
|
+
} | null>;
|
|
5
10
|
export interface CallMachineOptions {
|
|
6
11
|
timeoutMs?: number;
|
|
7
12
|
rereadMs?: number;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var p=Object.defineProperty;var s=(e,
|
|
1
|
+
var p=Object.defineProperty;var s=(e,a)=>p(e,"name",{value:a,configurable:!0});import{randomUUID as E}from"node:crypto";import{openDb as w,withCanvasWrite as m}from"../../../canvas/db.js";import{brokerSignalBus as g}from"../../../../daemon/broker-signals/bus.js";import{MachineCallFailedError as S,MachineLostError as c,MachineOfflineError as _}from"./ops.js";const N={start:60,wake:15,stop:15,status:15,"status.all":15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15,"job.stop":15,"worktree.create":60,"worktree.rollback":60,"worktree.close":60,"worktree.abandon":60,"worktree.finalize":60,"repo.identify":15},M=1e3;async function A(e){const a=await(await w()).prepare("SELECT created_at, finished_at FROM machine_calls WHERE call_id = ?").get(e);return a===void 0||a.finished_at===null?null:{createdAt:Date.parse(a.created_at),finishedAt:Date.parse(a.finished_at)}}s(A,"callTimes");async function k(e,a,n){const r=E(),o=new Date().toISOString();if(!await m(async t=>await t.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,o)===void 0?!1:(await t.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(r,e,a,JSON.stringify(n),o),await t.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new _(e,"no live link");return r}s(k,"enqueueMachineCall");async function L(e,a,n,r={}){return await D(e,a,await k(e,a,n),r)}s(L,"callMachine");async function D(e,a,n,r={}){const o=Date.now()+(r.timeoutMs??N[a]*1e3);let l,t=!1;const i=await g.subscribe(u=>{u===n&&(t=!0,l?.())},{kinds:["machine_call"]});try{return await O(e,a,n,o,r.rereadMs??M,u=>new Promise(f=>{if(t){t=!1,f();return}const h=setTimeout(()=>{l=void 0,f()},u);l=s(()=>{clearTimeout(h),l=void 0,t=!1,f()},"wake")}))}finally{i()}}s(D,"awaitMachineCall");async function O(e,a,n,r,o,l){for(;;){const t=await(await w()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(n);if(t===void 0)throw new c(e,n);if(t.state==="done")return t.result_json===null?null:JSON.parse(t.result_json);if(t.state==="failed"){const i=t.result_json===null?{}:JSON.parse(t.result_json);throw i.code==="machine_offline"?new _(e,i.message,i.sent===!0):i.code==="machine_lost"?new c(e,n):new S(e,a,i.message??"unknown")}if(t.claimed_generation!==null&&t.lease_expires_at!==null&&t.lease_expires_at<=new Date().toISOString()){if(await d(n,"lease expired")===void 0)continue;throw new c(e,n)}if(Date.now()>=r){const i=await d(n,"timed out");if(i===void 0)continue;throw i===null?new _(e,"no holder claimed the call"):new c(e,n)}await l(Math.min(o,Math.max(0,r-Date.now())))}}s(O,"waitForCall");async function d(e,a){const n=await(await w()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?, args_json = '{}',
|
|
2
2
|
result_json = CASE WHEN claimed_generation IS NULL THEN ? ELSE ? END
|
|
3
|
-
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:
|
|
3
|
+
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:a,sent:!1}),JSON.stringify({code:"machine_lost",message:a}),e);return n===void 0?void 0:n.claimed_generation===null?null:Number(n.claimed_generation)}s(d,"failOpenCall");export{N as MACHINE_CALL_TIMEOUT_S,D as awaitMachineCall,L as callMachine,A as callTimes,k as enqueueMachineCall};
|