@north-light/cli 0.3.666 → 0.3.668
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.d.ts +2 -1
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/bash-jobs.d.ts +3 -0
- package/dist/api/dto/broker-ops.d.ts +37 -0
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/02-turn-lifecycle/00-ending-a-turn.md +3 -1
- package/dist/builtin-memory/04-base-worker-exploring.md +2 -2
- package/dist/clients/attach/chrome/canvas-panels.d.ts +9 -1
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/chrome/roster.js +6 -6
- package/dist/clients/attach/render/card-presentation.js +2 -2
- package/dist/clients/attach/viewer.js +499 -499
- package/dist/commands/node/bash.js +4 -4
- package/dist/commands/node.js +1 -1
- package/dist/core/bash-job-supervisor.js +3 -3
- package/dist/core/bash-jobs.js +5 -5
- package/dist/core/canvas/canvas.js +18 -18
- package/dist/core/canvas/memory-reads.js +2 -1
- package/dist/core/canvas/waits.d.ts +2 -0
- package/dist/core/canvas/waits.js +6 -6
- package/dist/core/feed/messages.d.ts +5 -2
- package/dist/core/feed/messages.js +10 -5
- package/dist/core/grants/mirror.d.ts +11 -3
- package/dist/core/grants/mirror.js +6 -4
- package/dist/core/grants/on-sync.js +1 -1
- package/dist/core/graph/events.d.ts +9 -0
- package/dist/core/graph/events.js +12 -12
- package/dist/core/graph/kinds/document.js +2 -2
- package/dist/core/graph/kinds/kind.d.ts +2 -1
- package/dist/core/graph/kinds/node.js +1 -1
- package/dist/core/graph/names.d.ts +4 -3
- package/dist/core/graph/names.js +10 -9
- package/dist/core/graph/watches.d.ts +11 -2
- package/dist/core/graph/watches.js +13 -9
- package/dist/core/human/requests.d.ts +18 -1
- package/dist/core/human/requests.js +20 -18
- package/dist/core/human/scan.d.ts +3 -2
- package/dist/core/human/scan.js +1 -1
- package/dist/core/runtime/broker/attachments-fetch.d.ts +2 -1
- package/dist/core/runtime/broker/attachments-fetch.js +1 -1
- package/dist/core/runtime/broker/bash-job-launch.js +1 -1
- package/dist/core/runtime/broker/boot-state.d.ts +5 -0
- package/dist/core/runtime/broker/boot-state.js +1 -1
- package/dist/core/runtime/broker/cycle-start.d.ts +50 -0
- package/dist/core/runtime/broker/cycle-start.js +2 -0
- package/dist/core/runtime/broker/fault-retry.js +1 -1
- package/dist/core/runtime/broker/frame-dispatch.d.ts +2 -0
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker/frame-memory-refs.d.ts +2 -0
- package/dist/core/runtime/broker/frame-memory-refs.js +1 -1
- package/dist/core/runtime/broker/job-reporter.d.ts +4 -2
- package/dist/core/runtime/broker/job-reporter.js +2 -2
- package/dist/core/runtime/broker/rebind.d.ts +3 -0
- package/dist/core/runtime/broker/rebind.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +1 -1
- package/dist/core/runtime/runner/blaxel/release-image.d.ts +37 -0
- package/dist/core/runtime/runner/blaxel/release-image.js +3 -0
- package/dist/core/runtime/runner/blaxel/runner.d.ts +1 -1
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/secrets/blaxel-launch.d.ts +8 -0
- package/dist/core/secrets/blaxel-launch.js +3 -3
- package/dist/core/substrate/delivery/corpus.d.ts +7 -2
- package/dist/core/substrate/delivery/corpus.js +2 -2
- package/dist/core/substrate/delivery/deliver.js +3 -3
- package/dist/core/substrate/delivery/render-boot.js +27 -27
- package/dist/core/substrate/delivery/render-event.d.ts +5 -4
- package/dist/core/substrate/delivery/render-event.js +6 -6
- package/dist/daemon/api/bridge.js +3 -3
- package/dist/daemon/api/environment-of.d.ts +4 -0
- package/dist/daemon/api/environment-of.js +3 -3
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.d.ts +2 -0
- package/dist/daemon/api/handlers/bash-jobs.js +3 -3
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/broker-recovery.d.ts +2 -0
- package/dist/daemon/api/handlers/broker-recovery.js +1 -1
- package/dist/daemon/api/handlers/canvas.js +6 -6
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/handlers/node-records.d.ts +7 -0
- package/dist/daemon/api/handlers/node-records.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/cron/authority.d.ts +3 -1
- package/dist/daemon/cron/authority.js +1 -1
- package/dist/daemon/cron/escalation.js +1 -1
- package/dist/daemon/cron/sinks.js +2 -2
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/machine-daemon.js +1 -1
- package/dist/daemon/machine-link/client.d.ts +8 -0
- package/dist/daemon/machine-link/client.js +1 -1
- package/dist/daemon/machine-link/frames.d.ts +18 -0
- package/dist/daemon/machine-link/frames.js +1 -1
- package/dist/daemon/machine-link/holder.d.ts +2 -0
- package/dist/daemon/machine-link/holder.js +5 -5
- package/dist/daemon/machine-link/job-sweep.d.ts +15 -0
- package/dist/daemon/machine-link/job-sweep.js +1 -0
- package/dist/daemon/reconcilers/action-lane.js +1 -1
- package/dist/daemon/reconcilers/bash-deadline.js +1 -1
- package/dist/pi-extensions/canvas-context-intro.js +2 -2
- package/dist/pi-extensions/canvas-doc-substrate.js +4 -4
- package/dist/pi-extensions/canvas-passive-context.d.ts +13 -10
- package/dist/pi-extensions/canvas-passive-context.js +9 -12
- package/dist/pi-extensions/canvas-recap.js +6 -6
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/dist/pi-extensions/canvas-structured-output.js +6 -6
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
- package/scripts/sandbox-bootstrap.sh +36 -7
- package/scripts/sandbox-start.mjs +41 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var O=Object.defineProperty;var o=(n,e)=>O(n,"name",{value:e,configurable:!0});import{createFrameReplies as j}from"./frame-replies.js";import{createEngineDriver as q}from"./engine-drive.js";import{announceMessageOrigin as x}from"../stamp/channel.js";import{createClientHandlers as z}from"./frame-client.js";import{createMemoryRefGuidance as B}from"./frame-memory-refs.js";import{createEngineControlHandler as J}from"./frame-engine-control.js";import{createReadHandler as L}from"./frame-read.js";import{createSessionHandler as Q}from"./frame-session.js";import{createKickoffDriver as U,createPromptDispatchTracker as V,createTurnAcceptanceGate as X}from"./turn-ignition.js";import{prependRunDeferredMail as y}from"./run-deferred-mail.js";function ce(n){const{nodeId:e,registry:s,toolGroups:v,projection:k,rebind:l,boundaryReviewId:m,pendingDialogs:w,sendWelcome:D,replayExtraPendingDialogsTo:b,reWelcomeAll:A,disposeAndExit:C,persistModelChoice:M,broadcastModelChanged:F,registryOf:E,formatModelSpec:R,formatExactModelSpec:S,turnAdmission:u,runNode:h,memoryInventory:H,onKickoffAdmitted:P}=n,t=o(()=>l.session(),"currentSession"),T=o(()=>l.services(),"currentServices"),a=j(s),{notWritable:G}=a,c=B(t,e,H),p=V(t),_=X(),f=U({session:t,dispatches:p,turnAdmission:u,prependDeferred:h?r=>y(e,r):void 0,onAdmitted:P}),g=q({nodeId:e,registry:s,replies:a,session:t,dispatches:p,memoryRefs:c,rebind:l,projection:k,toolGroups:v,turnAdmission:u,prependDeferred:h?r=>y(e,r):void 0}),I=o((r,i)=>{G(r,"drive the engine")||((i.type==="prompt"||i.type==="steer"||i.type==="follow_up")&&x(i.text,{type:"human",channel:{type:"viewer"}}),g(r,i))},"handleDriveFrame"),d=z({registry:s,replies:a,session:t,driveEngine:g,turnAcceptance:_,pendingDialogs:w,sendWelcome:D,replayExtraPendingDialogsTo:b,disposeAndExit:C}),W=J({registry:s,replies:a,session:t,services:T,registryOf:E,persistModelChoice:M,broadcastModelChanged:o(async(...r)=>{await F(...r),f.drivePending()},"broadcastModelChanged"),formatModelSpec:R}),K=L({registry:s,replies:a,session:t,boundaryReviewId:m,memoryRefs:c,formatExactModelSpec:S}),N=Q({registry:s,replies:a,rebind:l,session:t,boundaryReviewId:m,memoryRefs:c,reWelcomeAll:A});return{handlers:{hello:d.hello,drive:I,deliver:d.deliver,dialog:d.dialog,engineControl:W,read:K,session:N,authentication:o(r=>{a.ackTo(r,"reload_auth")},"authentication"),bye:d.bye,shutdown:d.shutdown},kickoff:o((r,i)=>f.kickoff(r,i),"kickoff"),notifyTurnAccepted:_.notifyAccepted,pendingPromptDispatches:p.pending,resetForSession:o(()=>{},"resetForSession"),refreshMemoryNames:o(r=>r===void 0?c.invalidate():(c.replace(r),Promise.resolve()),"refreshMemoryNames")}}o(ce,"createFrameDispatchContext");function de(n,e,s){switch(s.type){case"hello":n.handlers.hello(e,s);return;case"prompt":case"steer":case"follow_up":case"abort":case"bash":n.handlers.drive(e,s);return;case"deliver":n.handlers.deliver(e,s);return;case"extension_ui_response":n.handlers.dialog(e,s);return;case"set_model":case"deliver_custom_message":case"cycle_model":case"cycle_ladder":case"cycle_thinking":case"dequeue":case"set_thinking_level":case"set_auto_retry":case"set_auto_compaction":case"compact":case"set_session_name":n.handlers.engineControl(e,s);return;case"get_commands":case"list_models":case"list_scoped_models":case"list_memory_refs":case"get_tree":case"get_settings":case"list_sessions":case"get_human_fork_coordinates":n.handlers.read(e,s);return;case"navigate_tree":case"reload":case"export":case"new_session":case"switch_session":case"fork":case"clone":case"share":n.handlers.session(e,s);return;case"reload_auth":n.handlers.authentication(e);return;case"bye":n.handlers.bye(e);return;case"shutdown":n.handlers.shutdown(e);return}}o(de,"handleFrame");export{ce as createFrameDispatchContext,de as handleFrame};
|
|
@@ -21,5 +21,7 @@ export type MemoryRefGuidance = {
|
|
|
21
21
|
guidanceFor(text: string): string | null;
|
|
22
22
|
/** Refresh the inventory after a successful session reload. */
|
|
23
23
|
invalidate(): Promise<void>;
|
|
24
|
+
/** Replace the inventory with names already read (a new cycle's). */
|
|
25
|
+
replace(names: ComposerNames): void;
|
|
24
26
|
};
|
|
25
27
|
export declare function createMemoryRefGuidance(session: () => BrokerSession, nodeId: string, initial: ComposerNames): MemoryRefGuidance;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var i=Object.defineProperty;var
|
|
1
|
+
var i=Object.defineProperty;var a=(r,e)=>i(r,"name",{value:e,configurable:!0});import{emitEvent as m}from"../../events/emit.js";import{brokerDelivery as f}from"./daemon-ops.js";import{buildGuidance as u}from"../../../shared/inline-ref-guidance.js";import{isLeadingEngineCommand as c}from"./engine-routing.js";async function l(r){const e=await f(r,{activity:"names"});if(e.refs===void 0||e.names===void 0)throw new Error(`delivery route returned no names for ${r}`);return{refs:e.refs,names:e.names}}a(l,"composerNames");function g(r,e,t){let s={refs:t.refs,names:new Set(t.names)};return{refs:a(()=>s.refs,"refs"),guidanceFor(n){try{return c(n,r())?null:u(n,s.names)}catch(o){return m({level:"warn",event:"broker.memory_refs.guidance_resolve_failed",error:o}),null}},async invalidate(){this.replace(await l(e))},replace(n){s={refs:n.refs,names:new Set(n.names)}}}}a(g,"createMemoryRefGuidance");export{l as composerNames,g as createMemoryRefGuidance};
|
|
@@ -2,14 +2,16 @@ import type { JobReportRequest } from '../../../api/dto/delivery.js';
|
|
|
2
2
|
/** Job output is reported in chunks of this size; the control plane stores one blob per chunk. */
|
|
3
3
|
export declare const JOB_OUTPUT_CHUNK_BYTES: number;
|
|
4
4
|
export type PostJobReport = (jobId: string, request: Omit<JobReportRequest, 'expected_execution_id'>) => Promise<void>;
|
|
5
|
+
/** True when `jobId` has nothing left to report: its report is complete, or it was never backgrounded (a foreground command). */
|
|
6
|
+
export declare function isJobReportSettled(contextDir: string, jobId: string): boolean;
|
|
5
7
|
export declare class JobReporter {
|
|
6
8
|
private readonly contextDir;
|
|
7
9
|
private readonly post;
|
|
8
10
|
/** What was last sent for each job, so an unchanged process identity or activity sample is not sent again. */
|
|
9
11
|
private readonly sent;
|
|
10
12
|
constructor(contextDir: string, post: PostJobReport);
|
|
11
|
-
/** One pass over this node's backgrounded jobs
|
|
12
|
-
tick(): Promise<void>;
|
|
13
|
+
/** One pass over this node's backgrounded jobs, or over just `only`. Never throws: a failed report is retried on the next pass. */
|
|
14
|
+
tick(only?: string): Promise<void>;
|
|
13
15
|
private report;
|
|
14
16
|
/** Report the log from `offset` on: chunks already full are final, the one holding `offset` is sent again as it grows. */
|
|
15
17
|
private uploadOutput;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}}async report(
|
|
1
|
+
var v=Object.defineProperty;var c=(s,e)=>v(s,"name",{value:e,configurable:!0});import{existsSync as u,readFileSync as S,readdirSync as b,statSync as w}from"node:fs";import{readFileBeneath as _,writeFileBeneath as J}from"../../spaces/open-beneath.js";import{bashJobPaths as y,bashJobsDir as O,isBashJobProcessConfirmedGone as B,isSafeBashJobId as g,readJobSupervisorState as l,signalBashJob as C}from"../../bash-jobs.js";import{ApiError as p}from"../../../api/errors.js";const f=64*1024,R=2e3;function m(s){try{const e=JSON.parse(_(s.root,s.jobReported).toString("utf8"));return{offset:Number.isSafeInteger(e.offset)?e.offset:0,done:e.done===!0}}catch{return{offset:0,done:!1}}}c(m,"readReported");function h(s,e){J(s.root,s.jobReported,JSON.stringify(e),{atomic:!0})}c(h,"writeReported");function A(s,e){const i=y(s,e);return m(i).done||!u(i.jobBg)}c(A,"isJobReportSettled");class E{static{c(this,"JobReporter")}contextDir;post;sent=new Map;constructor(e,i){this.contextDir=e,this.post=i}async tick(e){let i;if(e!==void 0)i=g(e)?[e]:[];else try{i=b(O(this.contextDir)).filter(g)}catch{return}for(const n of i)try{await this.report(n)}catch(t){t instanceof p&&(t.status===404||t.status===409)||process.stderr.write(`crtr: job ${n} report failed: ${t.message}
|
|
2
|
+
`)}}async report(e){const i=y(this.contextDir,e),n=m(i);if(n.done||!u(i.jobBg)||!u(i.cmdSh))return;const t=l(this.contextDir,e),o=this.sent.get(e)??{};this.sent.set(e,o);try{const r={...t.pgid===void 0||t.pgid===o.pgid?{}:{pgid:t.pgid},...t.pgidIdentity===void 0||t.pgidIdentity===o.identity?{}:{pgid_identity:t.pgidIdentity}},d=t.activity===void 0?void 0:JSON.stringify(t.activity),a=t.activity===void 0||d===o.activity?{}:{activity:{last_ms:t.activity.lastActivityMs,sampled_ms:t.activity.sampledAtMs,files:t.activity.files}};Object.keys(r).length>0||Object.keys(a).length>0?(await this.post(e,{...r,...a}),t.pgid!==void 0&&(o.pgid=t.pgid),t.pgidIdentity!==void 0&&(o.identity=t.pgidIdentity),o.activity=d):t.exitCode===void 0&&await this.post(e,{});const x=t.exitCode===void 0&&B(t.pgid,t.pgidIdentity)&&l(this.contextDir,e).exitCode===void 0;n.offset=await this.uploadOutput(e,i,n.offset),h(i,n),(t.exitCode!==void 0||x)&&(await this.post(e,t.exitCode!==void 0?{exit_code:t.exitCode}:{vanished:!0}),h(i,{...n,done:!0}),this.sent.delete(e))}catch(r){if(r instanceof p&&r.code==="unknown_node")return;if(!(r instanceof p&&r.code==="job_not_running"))throw r;const d=t.pgid,a=t.pgidIdentity;d!==void 0&&a!==void 0&&t.exitCode===void 0&&await C(d,a,void 0),h(i,{...n,done:!0}),this.sent.delete(e)}}async uploadOutput(e,i,n){let t;try{t=w(i.jobLog).size}catch{return n}if(t<=n)return n;const o=S(i.jobLog);for(let r=Math.floor(n/f);r*f<o.length;r++){const d=o.subarray(r*f,(r+1)*f);await this.post(e,{output:{seq:r,data_base64:d.toString("base64")}}),n=r*f+d.length}return n}start(){let e=!1;const i=setInterval(()=>{e||(e=!0,this.tick().finally(()=>{e=!1}))},R);return i.unref(),()=>clearInterval(i)}}export{f as JOB_OUTPUT_CHUNK_BYTES,E as JobReporter,A as isJobReportSettled};
|
|
@@ -66,6 +66,7 @@ export declare class RebindDriver {
|
|
|
66
66
|
private rebinding;
|
|
67
67
|
private agentRunActiveValue;
|
|
68
68
|
private shutdownRequested;
|
|
69
|
+
private beforeBind;
|
|
69
70
|
constructor(deps: RebindDriverDeps);
|
|
70
71
|
session(): BrokerSession;
|
|
71
72
|
services(): AgentSessionServices;
|
|
@@ -75,6 +76,8 @@ export declare class RebindDriver {
|
|
|
75
76
|
/** Resolves when the rebinds requested so far have finished binding extensions (every session_start hook), failed, or been superseded; undefined when none is in flight. */
|
|
76
77
|
pendingRebind(): Promise<void> | undefined;
|
|
77
78
|
requestShutdown(): void;
|
|
79
|
+
/** Run `hook` once, on the next session bind, after the session is built and before its extensions bind. */
|
|
80
|
+
beforeNextBind(hook: ((session: BrokerSession) => Promise<void>) | undefined): void;
|
|
78
81
|
setRebindSession(): void;
|
|
79
82
|
enqueueRebind(candidateSession: BrokerSession, candidateServices: AgentSessionServices): Promise<void>;
|
|
80
83
|
/** Run a session replacement on the serialized lane. A viewer op (`client` set) is acked to that viewer; the broker's own
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var l=(a,e)=>k(a,"name",{value:e,configurable:!0});import{mkdirSync as I,writeFileSync as w}from"node:fs";import{join as A}from"node:path";import{nodeRunJobDir as _}from"../../canvas/paths.js";import{emitEvent as u}from"../../events/emit.js";import{operationIdContext as c}from"../../events/operation-id.js";import{installPersonaTransitionGate as E}from"../broker-persona-guidance.js";import{installRetryCardElision as T}from"./retry-card-elision.js";import{abortSessionFromExtension as S}from"./extension-abort.js";import{brokerRecovery as x,mutateBrokerFault as F,mutateBrokerProviderRetry as P,postBrokerIdle as V,settleBroker as N}from"./daemon-ops.js";import{brokerSignalClient as C}from"./signal-stream.js";const m=2,b=3e4,g=Symbol("replacement-deadline-exceeded"),M="(interrupted)",y=Symbol.for("crtr.trailing-thinking-guard");function q(a){for(let e=a.length-1;e>=0;e--){const t=a[e];if(t!==void 0){if(t.type==="text"){if(t.text.trim().length===0)continue;return t}if(t.type==="thinking"){const n=t.thinkingSignature,d=typeof n=="string"&&n.trim().length>0;if(t.redacted!==!0&&t.thinking.trim().length===0&&!d)continue;return t}return t}}}l(q,"lastSerializedBlock");function R(a){return a.map(e=>e.role!=="assistant"||e.stopReason==="error"||e.stopReason==="aborted"||q(e.content)?.type!=="thinking"?e:{...e,content:[...e.content,{type:"text",text:M}]})}l(R,"guardTrailingThinking");function G(a){const e=a.convertToLlm;if(e[y]===!0)return;const t=l(n=>{const d=e(n);return d instanceof Promise?d.then(R):R(d)},"wrapped");t[y]=!0,a.convertToLlm=t}l(G,"installTrailingThinkingGuard");class z{static{l(this,"RebindDriver")}deps;sessionValue;servicesValue;unsubscribe;installed;nextSubscriptionGeneration=0;rebindTail=Promise.resolve();latestRebindRequest=0;replacementTail=Promise.resolve();admittedReplacements=0;rebindsInFlight=0;rebinding;agentRunActiveValue=!1;shutdownRequested=!1;beforeBind;constructor(e){this.deps=e,this.sessionValue=e.session,this.servicesValue=e.services}session(){return this.sessionValue}services(){return this.servicesValue}installedGeneration(){return this.installed}isAgentRunActive(){return this.agentRunActiveValue}isReplacing(){return this.admittedReplacements>0}pendingRebind(){return this.rebinding?.done}requestShutdown(){if(!this.agentRunActiveValue){this.deps.disposeAndExit("shutdown-hook");return}this.shutdownRequested=!0}beforeNextBind(e){this.beforeBind=e}setRebindSession(){this.deps.runtime?.setRebindSession(e=>this.enqueueRebind(e,this.deps.runtime.services))}enqueueRebind(e,t){const n=++this.latestRebindRequest;if(this.rebindsInFlight++===0){let s;this.rebinding={done:new Promise(o=>{s=o}),resolve:s}}const d=this.rebindTail.then(async()=>{if(n!==this.latestRebindRequest)return;if(this.installed!==void 0){typeof this.sessionValue.sessionFile=="string"&&this.sessionValue.sessionFile!==""&&await P(this.deps.nodeId,{op:"invalidate",session_id:this.sessionValue.sessionManager.getSessionId()});const i=(await x(this.deps.nodeId)).fault;i?.link==="pi\u2192provider"&&i.retry.disposition==="auto"&&i.retry.by==="daemon"&&await F(this.deps.nodeId,{op:"clear",link:"pi\u2192provider",preserve_episode:!0})}this.installed?.executingTools.clear(),this.removeInstalledSubscription(),this.deps.setActiveSession(e),this.deps.projection().reset(),this.deps.faultRetry().reset(),this.agentRunActiveValue=!1,this.deps.onSessionRebind(),this.deps.toolGroups.resetForSession(),this.sessionValue=e,this.servicesValue=t;const s=e.agent;s&&(E(this.deps.nodeId,{agent:s,sessionManager:e.sessionManager}),T(s),s.steeringMode="all",this.deps.runNode&&this.deps.runSteer.bind(s,e),s.followUpMode="all",G(s));const o={id:++this.nextSubscriptionGeneration,session:e,fallback:{blocked:!1},stagedProviderAgentEnd:null,stagedWatchdogAbort:!1,stagedRefreshAbort:!1,stagedOverflowFailure:null,executingTools:new Set};this.unsubscribe=this.sessionValue.subscribe(i=>{if(!this.deps.projection().isCurrent(o))return;if(c.current()!==void 0){this.executeSubscriptionCallback(o,i);return}const r=o.fallback;if(i.type==="turn_start"&&r.storedId!==void 0){r.storedId=void 0,r.blocked=!0,c.fresh(()=>{u({level:"warn",event:"broker.turn.fallback_overlap",fields:{generation:o.id,engine_event:i.type}}),this.executeSubscriptionCallback(o,i)});return}if(i.type==="turn_start"&&!r.blocked){c.fresh(v=>{r.storedId=v,this.executeSubscriptionCallback(o,i)});return}const h=r.storedId;if(h!==void 0&&!r.blocked){c.run(h,()=>{this.executeSubscriptionCallback(o,i),i.type==="agent_settled"&&r.storedId===h&&(r.storedId=void 0)});return}this.executeSubscriptionCallback(o,i)}),this.installed=o;const p=this.beforeBind;if(this.beforeBind=void 0,p!==void 0&&await p(e),await e.bindExtensions({uiContext:this.deps.uiContext(),mode:"rpc",abortHandler:l(()=>S(e,()=>{const i=this.installed;i?.session===e&&(i.stagedRefreshAbort=!0)}),"abortHandler"),shutdownHandler:l(()=>this.requestShutdown(),"shutdownHandler")}),n===this.latestRebindRequest){if(this.deps.cfg.editorName!==void 0&&this.deps.cfg.editorName!=="")try{e.setSessionName(this.deps.cfg.editorName)}catch{}try{this.deps.turnReplies.seed(this.deps.transcriptMessages(e))}catch(i){u({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply seed failed: ${String(i)}`}})}this.deps.projection().rearmIfStreaming(o),this.captureSystemPrompt(e)}}).finally(()=>{--this.rebindsInFlight>0||(this.rebinding?.resolve(),this.rebinding=void 0)});return this.rebindTail=d.catch(()=>{}),d}runReplacement(e,t,n){const d=this.deps.runtime;if(d===void 0)return e!==null&&this.deps.registry.sendFrame(e,{type:"error",code:"engine_error",message:"session replacement unsupported at this engine pin"}),Promise.resolve(!1);if(this.admittedReplacements>=m)return c.fresh(()=>u({level:"warn",event:"broker.session_replacement.rejected",outcome:"skipped",fields:{op:t,reason:"capacity",admitted:m,cap:m}})),this.ackTo(e,t,!1,`session replacement busy (${m} active or queued)`),Promise.resolve(!1);this.admittedReplacements++;let s=!1;const o=this.replacementTail.then(async()=>{try{await c.fresh(async()=>{const p=process.hrtime.bigint();let i;try{const f=new Promise(h=>{i=setTimeout(()=>h(g),b)}),r=await Promise.race([n(d),f]);if(r===g){u({level:"error",event:"broker.session_replacement.timed_out",outcome:"failed",duration_ms:Number(process.hrtime.bigint()-p)/1e6,fields:{op:t,deadline_ms:b,mutation_outcome:"indeterminate"}}),this.ackTo(e,t,!1,"session replacement timed out; broker restarting because session state is indeterminate"),this.deps.disposeAndExit("session-replacement-timeout",1);return}r.cancelled||this.deps.reWelcomeAll(),s=!r.cancelled,this.ackTo(e,t,!r.cancelled,r.cancelled?r.detail??"cancelled by extension":void 0)}catch(f){u({level:"error",event:"broker.session_replacement.failed",outcome:"failed",error:f,fields:{op:t,mutation_outcome:"indeterminate"}}),this.ackTo(e,t,!1,"session replacement failed; broker restarting because session state is indeterminate"),this.deps.disposeAndExit("session-replacement-failed",1)}finally{clearTimeout(i)}})}finally{this.admittedReplacements--,this.admittedReplacements===0&&this.deps.onReplacementIdle?.()}});return this.replacementTail=o.catch(()=>{}),o.then(()=>s,()=>!1)}removeInstalledSubscription(){this.unsubscribe?.(),this.unsubscribe=void 0,this.installed=void 0}captureSystemPrompt(e){try{const t=_(this.deps.nodeId);I(t,{recursive:!0}),w(A(t,"system-prompt.md"),e.systemPrompt,"utf8")}catch{}}executeSubscriptionCallback(e,t){try{t.type==="agent_start"&&(this.agentRunActiveValue=!0),t.type==="agent_end"&&(e.stagedProviderAgentEnd=t,e.stagedOverflowFailure=null),t.type==="compaction_end"&&t.reason==="overflow"&&t.willRetry===!1&&typeof t.errorMessage=="string"&&(e.stagedOverflowFailure={errorMessage:t.errorMessage}),t.type==="agent_settled"&&(this.agentRunActiveValue=!1,this.publishAndScheduleProviderRecovery(e)),this.deps.toolGroups.observeToolGroupEvent(t),this.deps.turnReplies.observe(t),this.deps.projection().relayEvent(t,e)}catch(n){u({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`event relay threw: ${String(n)}`}})}}async publishAndScheduleProviderRecovery(e){try{if(await this.deps.faultRetry().publishSettledProviderFault(e),this.shutdownRequested){this.deps.disposeAndExit("shutdown-after-settle");return}const t=this.deps.faultRetry();await t.schedule()!=="armed"&&!t.fallbackInFlight()&&await t.faultIsFatal()&&await this.idleAfterFatalFault(e)}catch(t){this.deps.faultRetry().abandonTurnEnd(),u({level:"error",event:"broker.daemon.operation.failed",node_id:this.deps.nodeId,error:t,fields:{operation:"provider_fault_settlement"}}),this.shutdownRequested&&this.deps.disposeAndExit("shutdown-after-settle")}}async idleAfterFatalFault(e){const t=l(()=>this.installed===e&&!this.agentRunActiveValue&&!e.session.isStreaming,"stillSettled");!t()||(await N(this.deps.nodeId,{stopReason:"error",pushedFinal:!1,faultSettled:!0})).action!=="stay_resident"||!t()||(await V(this.deps.nodeId),C().stop())}ackTo(e,t,n=!0,d,s){e!==null&&this.deps.registry.sendFrame(e,{type:"ack",for:t,ok:n,...d!==void 0?{detail:d}:{},...s!==void 0?{id:s}:{}})}}export{z as RebindDriver};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var $e=Object.defineProperty;var n=(t,o)=>$e(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as We,envModelIntent as Ge,envNodeCwd as je,envNodeId as Ve,envProfileId as Xe,envScopes as qe,scopeAllowed as Ye}from"../../shared/env.js";import{createServer as He}from"node:net";import{WebSocketServer as ze,createWebSocketStream as Je}from"ws";import{BROKER_VIEW_PORT as Qe}from"./view-socket.js";import{existsSync as Te,readFileSync as Ze,unlinkSync as ke}from"node:fs";import{join as Ce}from"node:path";import{randomUUID as O}from"node:crypto";import{mark as et}from"../timing.js";import{SUBMIT_RESULT_TOOL as tt}from"./structured-output.js";import{flushConversation as se,installSessionManagerStorePatch as nt}from"../conversation-store/index.js";import{getAgentDir as Q,ModelRegistry as rt,ModelRuntime as ot}from"@earendil-works/pi-coding-agent";import{nodeRunDir as st,viewSocketPath as it}from"../canvas/paths.js";import{bindBrokerEventSource as at}from"../events/source.js";import{emitEvent as R,flushBrokerLog as dt}from"../events/emit.js";import{operationIdContext as lt}from"../events/operation-id.js";import{findMissingPackagePaths as ct}from"./package-health.js";import{installBrokerConfigSnapshot as mt}from"../config.js";import{FRONT_DOOR_ENV as ut}from"./front-door.js";import{CANVAS_EXTENSIONS as ie,piInvocationToSdkConfig as ft}from"./launch.js";import{assertEngineVersion as pt,loadBrokerEngine as gt}from"./broker-sdk.js";import{initCrtrTheme as vt}from"./crtr-theme.js";import{resolveBundledPiPackageDir as _t}from"./pi-cli.js";import{captureSessionChatCapabilities as ht}from"./command-surface.js";import{InMemoryCredentialStore as St}from"@earendil-works/pi-ai";import{configureBrokerModelRuntime as wt,refusalRetryAt as Rt}from"./broker/model-adapter.js";import{brokerApiUrl as bt,mutateBrokerFault as Z,recordBrokerTurn as xe}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as Et}from"./launch-recipe.js";import{fetchRunAttachments as Ae}from"./broker/attachments-fetch.js";import{modelRequestFromConfig as yt,expandModelCandidates as Tt,parseModelSpec as kt,unregisteredConcreteModel as Ct}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as xt}from"./stream-watchdog.js";import{probeOnline as At}from"./connectivity.js";import{CRTR_CYCLE_CUSTOM_TYPE as Me,cycleAwareMessages as Mt,endedByAbort as Pt}from"./session-cycles.js";import{turnErrorOf as Ot}from"../llm/refusal.js";import{projectTranscript as It}from"./session-visibility.js";import{currentTurnVisibility as Dt}from"./turn-visibility.js";import{isUnknownModel as ae}from"./model-selection.js";import{BrokerClientRegistry as Nt}from"./broker/client-registry.js";import{ToolGroupTracker as Ft}from"./broker/tool-groups.js";import{TurnReplyTracker as Lt}from"./broker/turn-replies.js";import{onNodeNamed as Bt}from"./broker/node-named.js";import{FaultRetry as Kt,willDaemonRetry as Ut}from"./broker/fault-retry.js";import{RunTurnEnds as $t}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as Wt}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as Gt,BROKER_START_CYCLE as jt,BROKER_IDLE_TURN_START as Vt,BROKER_RUN_TURN_BUSY as Xt,BROKER_RUN_STEER as qt}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as Yt}from"./broker/run-steer.js";import{prependRunDeferredMail as Ht,settleRunDeferredMail as zt}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as Jt}from"./broker/run-turn-queue.js";import{EventProjection as Qt}from"./broker/event-projection.js";import{createFrameDispatchContext as Zt,handleFrame as en}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as tn,installAdvertisedCommandInvocationContract as nn}from"./advertised-command-invocation.js";import{RebindDriver as rn}from"./broker/rebind.js";import{beginRuntimeTeardown as on}from"./broker/extension-abort.js";import{receiveNodeToken as sn}from"./broker/node-token.js";import{serveCliRelay as an}from"./broker/cli-relay.js";import{recordBrokerRelease as dn}from"./lifecycle.js";import{setTurnCauseSource as ln}from"./broker/turn-cause.js";import{decodeKickoffOrigin as Pe,KICKOFF_ORIGIN_ENV as Oe}from"./stamp/protocol.js";import{announceMessageOrigin as Ie}from"./stamp/channel.js";import{commitBrokerModel as cn,recordConversationWriteFault as De}from"./broker/daemon-ops.js";import{bootExtensionState as mn}from"./broker/boot-state.js";import{composerNames as un}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as fn,FrameOverflowError as pn,normalizeSnapshotTail as gn}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as Br,REVIEW_BOUNDARY_NAVIGATION_CODE as Kr}from"./broker/frame-replies.js";function de(t){return new rt(t.modelRuntime)}n(de,"registryOf");function U(t,o){if(t==null||ae(t))return null;const i=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${i}`}n(U,"formatModelSpec");function vn(t,o){const i=U(t,void 0);return i===null?null:`${i}:${o===void 0||o===""?"off":o}`}n(vn,"formatExactModelSpec");const _n=12e4;let ee=null;import{brokerSignalClient as $}from"./broker/signal-stream.js";function hn(){$().stop();const t=ee;if(ee=null,t!==null)try{t.dispose()}catch{}}n(hn,"disposeActiveSession");function Sn(t,o){const i=Ye(o,"crtr:act")?void 0:["bash"],g=t!==void 0&&t.length>0?[...new Set([...t,tt])]:t===void 0?void 0:[...t];return{...g!==void 0?{tools:g}:{},...i!==void 0?{excludeTools:i}:{}}}n(Sn,"brokerToolOptions");async function Nr(t,o=process.hrtime.bigint(),i=new Date().toISOString()){at(t);const g=await sn(),s=await an(t,g);process.env.CRTR_API_SOCKET=s.path,lt.fresh(()=>{R({level:"info",event:"broker.startup.cli_entry",ts:i,duration_ms:0,fields:{runtime_version:process.version,engine_version:null,model:null}}),R({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 a=new Set;let c=null;const l=n((e,r=null)=>{a.has(e)||(a.add(e),et(e,{duration_ms:Number(process.hrtime.bigint()-o)/1e6}),R({level:"info",event:e,duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:c,model:r}}))},"emitStartupMilestone");process.env[ut]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,nt(t);const _=await gt();pt(_.VERSION),c=_.VERSION;const S=st(t),k=Ce(S,"broker-launch.json"),w=JSON.parse(Ze(k,"utf8"));if(!w.configSnapshot)throw new Error("broker launch is missing its config snapshot");mt(w.configSnapshot);const m=ft(w);m.modelExact===!0?process.env.CRTR_MODEL_EXACT="1":delete process.env.CRTR_MODEL_EXACT;const b=await un(t);let E,I;const Y=n(e=>{E!==void 0?E(e):I??=e},"onSignal");process.on("SIGTERM",()=>Y("SIGTERM")),process.on("SIGINT",()=>Y("SIGINT")),process.on("SIGUSR1",()=>{const e=process.env.CRTR_EXECUTION_ID;e!==void 0&&e!==""&&$().start(t,e)});let{session:W,services:D,resuming:ce,runtime:G}=await En(_,m);l("broker.startup.session_built");const x=(await mn(t)).node.review_binding?.review_id,y=We();ee=W;const B=At;try{process.env.PI_PACKAGE_DIR=_t(),vt(D.settingsManager.getTheme(),Q(),!1)}catch(e){R({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of ct(Q()))R({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const j=it(t),h=new Nt(t),H=new Map,M=new Ft(t,e=>h.broadcast(e)),V=new Lt(t,e=>h.broadcast(e));Bt(e=>h.broadcast({type:"node_named",...e}));let F=!1,me=!1,z,J,ue,f,X;const te=new $t;let K,fe=n(()=>{},"notifyTurnAccepted"),pe=n(()=>{},"resetFrameState");const ne=Wt();let ge=n(()=>0,"pendingPromptDispatches"),ve;const P=Jt({runNode:y,session:n(()=>f.session(),"session"),isReplacing:n(()=>f.isReplacing(),"isReplacing"),pendingRebind:n(()=>f.pendingRebind(),"pendingRebind"),isAgentRunActive:n(()=>f.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:n(()=>ge(),"pendingDispatches"),turnAdmission:ne,prependDeferred:n(e=>Ht(t,e),"prependDeferred"),onError:n(e=>R({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),_e=Yt(P.steerable);globalThis[qt]=_e,ln(()=>f.session());const he=P.drain;m.firstPrompt!==void 0&&m.firstPrompt!==""&&P.holdForKickoff(),globalThis[Vt]=P.start,globalThis[Xt]=P.busy,f=new rn({nodeId:t,cfg:m,session:W,services:D,runtime:G,registry:h,toolGroups:M,turnReplies:V,runSteer:_e,runNode:y,transcriptMessages:n(e=>le(e,x)?.map(({message:r})=>r)??e.sessionManager.buildSessionContext().messages,"transcriptMessages"),uiContext:n(()=>ue,"uiContext"),faultRetry:n(()=>X,"faultRetry"),projection:n(()=>K,"projection"),setActiveSession:n(e=>{if(ee=e,ve?.(),y||process.env.CRTR_RUN_ID){let r="stop",d,u=!1;ve=e.subscribe(v=>{if(v.type==="agent_start"&&(r="stop",d=void 0,u=!1,te.started()),v.type==="agent_end"){const p=[...v.messages??[]].reverse().find(T=>T.role==="assistant");p&&(r=p.stopReason,d=Pt(p)?void 0:Ot(p,Rt(p)),u=p.role==="assistant"&&Ut(p,e.model?.contextWindow))}v.type==="agent_settled"&&(te.settled(e.sessionManager,{stop_reason:r,...d?{error:d}:{}},u),y&&(se().then(()=>zt(t,e)).catch(async p=>{if(String(p?.message).startsWith("conversation_write_failed")){R({level:"error",event:"broker.exited",node_id:t,error:p,fields:{fault:"conversation_write_failed"}}),await De(t,p),C("conversation_write_failed",1);return}R({level:"error",event:"broker.run_deferred_mail.settle_failed",error:p})}),queueMicrotask(()=>{f.session()===e&&he()})))})}},"setActiveSession"),disposeAndExit:n((e,r)=>C(e,r),"disposeAndExit"),onSessionRebind:n(()=>{pe()},"onSessionRebind"),onReplacementIdle:n(()=>{y&&he()},"onReplacementIdle"),reWelcomeAll:n(()=>re(),"reWelcomeAll")});const Se=n(async(e,r=!1)=>{const d=f.session(),u=U(d.model,d.thinkingLevel);if(u===null)return null;const v=await cn(t,{spec:u,...e!==void 0?{intent:e}:{},userSelected:r});return r&&(m.model=v.modelOverride,e!==void 0?(process.env.CRTR_MODEL_INTENT=`${e.family}/${e.strength}`,delete process.env.CRTR_MODEL_EXACT,m.modelExact=void 0):(delete process.env.CRTR_MODEL_INTENT,process.env.CRTR_MODEL_EXACT="1",m.modelExact=!0)),v.modelOverride},"persistModelChoice"),we=n(async(e=!0,r,d=!1)=>{const u=f.session(),v=U(u.model,u.thinkingLevel),p=e?await Se(r,d):v;h.broadcast({type:"model_changed",model:ae(u.model)?void 0:u.model,spec:p})},"broadcastModelChanged");X=new Kt({nodeId:t,cfg:m,retryProbe:B,currentSession:n(()=>f.session(),"currentSession"),currentServices:n(()=>f.services(),"currentServices"),installedGeneration:n(()=>f.installedGeneration(),"installedGeneration"),registryOf:de,formatModelSpec:U,broadcastModelChanged:we,turnAdmission:ne,reWelcomeAll:n(()=>re(),"reWelcomeAll"),...y?{turnEnds:te}:{}});const Re=n(()=>{X.rearmIfStranded().catch(e=>{R({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry re-arm failed: ${e instanceof Error?e.message:String(e)}`}})})},"rearmStrandedRetry");$().subscribe("resync",Re),$().subscribe("fault-retry",Re),K=new Qt({registry:h,faultRetry:X,installedGeneration:n(()=>f.installedGeneration(),"installedGeneration"),currentSession:n(()=>f.session(),"currentSession"),notifyTurnAccepted:n(()=>fe(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:U});const Fe=n(e=>{const r=f.session(),d=le(r,x),u=gn(e.snapshotTail),v=d===void 0||u===void 0?d:d.slice(-u),p=v?.map(({message:L})=>L)??r.sessionManager.buildSessionContext().messages,T=M.summaries(),q=v!==void 0&&u!==void 0?wn(p):void 0,Ue=q===void 0?T:Object.fromEntries(Object.entries(T).filter(([L])=>q.has(L)));return{messages:p,...v===void 0?{}:{messageIds:v.map(({id:L})=>L)},messageVisibility:v?.map(({visibility:L})=>L)??p.map(()=>"visible"),turnVisibility:Dt(),stats:r.getSessionStats(),state:{model:ae(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:Ue,turnReplies:V.snapshot(),workingActivity:K.currentWorkingActivity(),queued:{steering:[...r.getSteeringMessages()],followUp:[...r.getFollowUpMessages()]}}},"buildSnapshot"),be=n(e=>{const r=e.role==="controller"?H.values().next().value:void 0;h.sendFrame(e,{type:"welcome",snapshot:Fe(e),role:e.role,pending_dialog:r!==void 0?r.request:null,agentDir:Q()},!0)},"sendWelcome"),Le=n(e=>{const r=[...H.values()];for(let d=1;d<r.length;d++)h.sendFrame(e,r[d].request)},"replayExtraPendingDialogsTo"),re=n(()=>{try{const e=f.session();V.seed(le(e,x)?.map(({message:r})=>r)??e.sessionManager.buildSessionContext().messages)}catch(e){R({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply reseed failed: ${String(e)}`}})}h.forEachHelloed(be)},"reWelcomeAll"),Ee=n(async e=>{if(F)return;F=!0;const r=$().latestNode;r!==void 0&&(r.intent==="idle-release"||r.status==="done")&&dn(t,process.env.CRTR_EXECUTION_ID??null),$().stop(),e===0&&await se().catch(async d=>{e=1,R({level:"error",event:"broker.exited",node_id:t,error:d,fields:{fault:"conversation_write_failed"}}),await De(t,d)}),M.persistPendingSummary(),K.dispose(),hn();try{z?.close(),J?.close()}catch{}s.close(),h.dispose();try{Te(j)&&ke(j)}catch{}h.clearAttachState(),await dt(),process.exit(e)},"completeExit"),C=n((e,r=0)=>{if(F)return;const d=e==="shutdown-hook"||e==="shutdown-after-settle";if(d&&M.finishOpenToolGroup(!0),d&&(M.hasSummaryTasks()||V.hasTasks())){if(me)return;me=!0,Promise.allSettled([M.waitForSummaryTasks(),V.waitForTasks()]).finally(()=>Ee(r));return}Ee(r)},"disposeAndExit");globalThis[Gt]=C,ue=yn({writable:n(()=>h.writableClients(),"writable"),forward:n((e,r)=>h.sendFrame(e,r),"forward"),pending:H,broadcast:n(e=>h.broadcastUi(e),"broadcast"),onKnownStreamWait:n(e=>K.knownStreamWait(e),"onKnownStreamWait")}),f.setRebindSession(),await f.enqueueRebind(W,D),l("broker.startup.extensions_bound");const A=Zt({nodeId:t,registry:h,toolGroups:M,projection:K,rebind:f,boundaryReviewId:x,pendingDialogs:H,sendWelcome:be,replayExtraPendingDialogsTo:Le,reWelcomeAll:re,disposeAndExit:C,persistModelChoice:Se,broadcastModelChanged:we,registryOf:de,formatModelSpec:U,formatExactModelSpec:vn,turnAdmission:ne,memoryInventory:b,runNode:y,onKickoffAdmitted:P.releaseKickoff});fe=A.notifyTurnAccepted,pe=A.resetForSession,ge=A.pendingPromptDispatches,globalThis[jt]=async e=>{for(const T of Et){const q=e.env[T];q===void 0?delete process.env[T]:process.env[T]=q}process.env[Oe]=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?m.model=e.model:delete m.model,e.modelExact?(m.modelExact=!0,process.env.CRTR_MODEL_EXACT="1"):(delete m.modelExact,delete process.env.CRTR_MODEL_EXACT),m.editorName=e.editorLabel,P.holdForKickoff(),M.finishOpenToolGroup(!0);const r=f.session(),d=r.sessionManager.getSessionFile();if(d===void 0||d==="")throw new Error("in-place cycle needs a persisted session file");const u=r.sessionManager,v=u.getLeafId();if(u.resetLeaf(),u.appendCustomEntry(Me,{cycle:e.cycle,fromLeaf:v}),await se(),!await f.runReplacement(null,"cycle",T=>T.switchSession(d)))return C("cycle-replacement-failed",1),!1;Ie(e.prompt,Pe(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await Ae(t)}catch(T){return R({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:T,fields:{operation:"attachments_fetch"}}),C("attachments-fetch-failed",1),!1}return A.kickoff(e.prompt,e.messageIds),!0};const Be=2500;let oe=!1;const Ke=n(async e=>{if(F||oe)return;if(oe=!0,f.isAgentRunActive()||f.session().isStreaming||A.pendingPromptDispatches()>0){const d=Date.now()+Be;for(;A.pendingPromptDispatches()>0&&!f.session().isStreaming&&Date.now()<d;)await new Promise(u=>setTimeout(u,25));if(f.session().isStreaming){const u=d-Date.now();if(u>0){let v;try{on(),await Promise.race([f.session().abort().then(()=>!0,()=>!1),new Promise(T=>{v=setTimeout(()=>T(!1),u)})])&&await xe(t,{event:"closed",end_reason:"teardown-aborted"})}finally{v!==void 0&&clearTimeout(v)}}}else(A.pendingPromptDispatches()>0||f.isAgentRunActive())&&await xe(t,{event:"interrupted"})}C(e)},"abortAndExit");if(E=n(e=>{Ke(e)},"signalTeardown"),I!==void 0){E(I);return}try{Te(j)&&ke(j)}catch{}const ye=n(e=>{const r=h.create(e);e.on("data",u=>{let v;try{v=r.decoder.push(u)}catch(p){p instanceof pn?(h.sendFrame(r,{type:"error",code:"frame_overflow",message:p.message}),h.dropClient(r,`frame overflow: ${p.message}`)):h.dropClient(r,`decoder error: ${String(p)}`);return}for(const p of v)try{en(A,r,p)}catch{}});const d=n(()=>{h.removeClient(r)},"drop");e.on("close",d),e.on("error",()=>{})},"serveViewer");z=He(ye),bt()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(J=new ze({host:"::",port:Qe,path:"/view",maxPayload:fn.maxLineBytes}),J.on("connection",e=>ye(Je(e))),J.on("error",e=>{F||(R({level:"error",event:"broker.socket.failed",error:e}),C("socket-error",1))})),z.on("error",e=>{F||(R({level:"error",event:"broker.socket.failed",error:e}),C("socket-error",1))}),z.listen(j,async()=>{Promise.all([Z(t,{op:"clear",link:"viewer\u2194broker"}),Z(t,{op:"clear",link:"relay\u2194broker"})]).catch(r=>R({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"broker_socket_bound_fault_clear"}}));let e;try{e=await X.recoverOnStartup()}catch(r){R({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"recovery_startup"}}),C("recovery-startup-failed",1);return}if(!(F||oe))if(e==="none"&&m.firstPrompt!==void 0&&m.firstPrompt!==""){const r=Pe(process.env[Oe]);r!==null&&Ie(m.firstPrompt,r);try{await Ae(t)}catch(u){R({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:u,fields:{operation:"attachments_fetch"}}),C("attachments-fetch-failed",1);return}const d=process.env.CRTR_KICKOFF_MESSAGE_IDS;A.kickoff(m.firstPrompt,d?JSON.parse(d):[])}else P.releaseKickoff()}),h.persistAttachState()}n(Nr,"runBroker");function wn(t){const o=new Set;for(const i of t)if(!(i.role!=="assistant"||!Array.isArray(i.content)))for(const g of i.content)g!==null&&typeof g=="object"&&g.type==="toolCall"&&typeof g.id=="string"&&o.add(g.id);return o}n(wn,"toolCallIds");function le(t,o){const i=t.sessionManager,g=Mt(i);return g!==void 0&&tn(g.map(({message:s})=>s)),g===void 0?void 0:It(g,{boundaryReviewId:o,sessionEntries:i.getEntries?.()})}n(le,"snapshotMessages");function Ne(){const t=Ve();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}n(Ne,"currentBrokerNodeId");async function Rn(t,o){const i=yt(o.model,Ge(),o.modelExact===!0);if(i===void 0)return;const g=de(t),s={cwd:je()??o.cwd,profileId:Xe()},a=await Ct(i,g,s);if(a!==void 0)throw await Z(Ne(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`model '${a.request.spec}' is not registered in the serving model registry`}}),new Error(`[broker] FATAL: model '${a.request.spec}' is not registered in the serving model registry`);const c=await Tt(i,s.cwd,s.profileId),l=kt(i.spec);for(const _ of c){const S=g.find(_.providerId,_.modelId);if(S===void 0)continue;const w=l?.providerId===_.providerId&&l.modelId===_.modelId?l.thinkingLevel??(_.thinkingLevel===void 0?void 0:"off"):_.thinkingLevel;return{model:S,thinkingLevel:w}}if(o.modelExact===!0){const _=c.map(S=>`'${S.providerId}/${S.modelId}' unregistered`).join("; ");throw await Z(Ne(),{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`)}R({level:"warn",event:"broker.model.none_viable",fields:{rejected_candidates:c.map(_=>({provider:_.providerId,model:_.modelId,reason:"unregistered"})).slice(0,16)}})}n(Rn,"resolveLaunchModel");function bn(t){let o=!0;return{runtime:new Proxy(t,{get(g,s,a){return o&&s==="getAvailableSnapshot"?()=>[]:o&&s==="getAvailable"?async()=>[]:o&&s==="getModel"?()=>{}:Reflect.get(g,s,a)}}),reveal:n(()=>{o=!1},"reveal")}}n(bn,"modelLessRegistry");async function En(t,o){const i=Q(),g=n(async w=>{const m=await ot.create({credentials:new St,modelsPath:Ce(w.agentDir,"models.json")});wt(m);const b=await t.createAgentSessionServices({cwd:w.cwd,agentDir:w.agentDir,modelRuntime:m,resourceLoaderOptions:{additionalExtensionPaths:o.extensionPaths,appendSystemPrompt:o.appendSystemPromptPath!==void 0?[o.appendSystemPromptPath]:void 0,noContextFiles:!0,extensionsOverride:n(N=>({...N,extensions:N.extensions.filter(x=>!/[/\\]provider-rotation\.(?:ts|js)$/.test(x.path))}),"extensionsOverride")}}),E=b.resourceLoader.getExtensions();if(o.extensionPaths.some(N=>ie.includes(N))){const N=new Set(E.extensions.map(y=>y.path)),x=ie.filter(y=>!N.has(y));if(x.length>0){const y=E.errors.filter(B=>ie.includes(B.path)).map(B=>`${B.path}: ${B.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${x.join(", ")}${y===""?"":` (${y})`}`)}}b.settingsManager.getRetryEnabled=()=>!1;const I=await Rn(b,o),Y=I?.model,W=I?.thinkingLevel,D=I===void 0?bn(b.modelRuntime):void 0,ce=D!==void 0?{...b,modelRuntime:D.runtime}:b,G=await t.createAgentSessionFromServices({services:ce,sessionManager:w.sessionManager,model:Y,thinkingLevel:W,...Sn(o.tools,qe()),sessionStartEvent:w.sessionStartEvent});return nn(G.session),ht(G.session),D?.reveal(),{...G,services:b}},"buildForManager"),s=o.resumeSessionPath,a=o.forkFrom!==void 0&&o.forkFrom!=="";if(!a&&(s===void 0||s==="")&&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 c=!a&&s!==void 0&&s!=="",l=c&&o.newCycle===!0,_=c&&!l;let S;if(a)S=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(_||l){if(S=await t.SessionManager.open(s),l){const w=S.getLeafId();S.resetLeaf(),S.appendCustomEntry(Me,{cycle:Number(process.env.CRTR_CYCLES),fromLeaf:w})}}else S=await t.SessionManager.create(o.cwd);if(t.createAgentSessionRuntime!==void 0){const w=n(async b=>{const E=await g({cwd:b.cwd,agentDir:b.agentDir,sessionManager:b.sessionManager,sessionStartEvent:b.sessionStartEvent});return{...E,diagnostics:E.services.diagnostics??[]}},"factory"),m=await t.createAgentSessionRuntime(w,{cwd:o.cwd,agentDir:i,sessionManager:S});return{session:m.session,services:m.services,resuming:_,runtime:m}}const k=await g({cwd:o.cwd,agentDir:i,sessionManager:S});return{session:k.session,services:k.services,resuming:_,runtime:void 0}}n(En,"buildBrokerSession");function yn(t){const o=n((s,a,c,l)=>{if(l?.signal?.aborted)return Promise.resolve(s);const _=t.writable();return _.length===0?Promise.resolve(s):new Promise(S=>{let k;const w=n(()=>{k!==void 0&&clearTimeout(k),l?.signal?.removeEventListener("abort",m),t.pending.delete(a.id)},"cleanup"),m=n(()=>{w(),t.broadcast({type:"extension_ui_dismiss",id:a.id}),S(s)},"onAbort");l?.signal?.addEventListener("abort",m,{once:!0});const b=l?.timeout!==void 0?l.timeout:_n;k=setTimeout(()=>{w(),t.broadcast({type:"extension_ui_dismiss",id:a.id}),S(s)},b),typeof k.unref=="function"&&k.unref(),t.pending.set(a.id,{request:a,resolve:n(E=>{w(),t.broadcast({type:"extension_ui_dismiss",id:a.id}),S(c(E))},"resolve")});for(const E of _)t.forward(E,a)})},"dialogPromise"),i=n(()=>{},"noop");return{[xt]:t.onKnownStreamWait??(s=>()=>{}),get theme(){const s=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(s==null)throw new Error("Theme not initialized. Call initTheme() first.");return s},select:n((s,a,c)=>o(void 0,{type:"extension_ui_request",id:O(),method:"select",title:s,options:a,timeout:c?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,c),"select"),confirm:n((s,a,c)=>o(!1,{type:"extension_ui_request",id:O(),method:"confirm",title:s,message:a,timeout:c?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,c),"confirm"),input:n((s,a,c)=>o(void 0,{type:"extension_ui_request",id:O(),method:"input",title:s,placeholder:a,timeout:c?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,c),"input"),editor:n((s,a)=>o(void 0,{type:"extension_ui_request",id:O(),method:"editor",title:s,prefill:a},c=>"cancelled"in c&&c.cancelled?void 0:"value"in c?c.value:void 0),"editor"),setStatus:n((s,a)=>t.broadcast({type:"extension_ui_request",id:O(),method:"setStatus",statusKey:s,statusText:a}),"setStatus"),setWidget:n((s,a,c)=>{typeof a!="function"&&t.broadcast({type:"extension_ui_request",id:O(),method:"setWidget",widgetKey:s,widgetLines:a,widgetPlacement:c?.placement})},"setWidget"),setTitle:n(s=>t.broadcast({type:"extension_ui_request",id:O(),method:"setTitle",title:s}),"setTitle"),notify:n((s,a)=>{const c=a==="warn"?"warning":a;t.broadcast({type:"extension_ui_request",id:O(),method:"notify",message:s,notifyType:c})},"notify"),onTerminalInput:n(()=>i,"onTerminalInput"),setWorkingMessage:i,setWorkingVisible:i,setWorkingIndicator:i,setHiddenThinkingLabel:i,setFooter:i,setHeader:i,custom:n(()=>Promise.resolve(void 0),"custom"),pasteToEditor:i,setEditorText:i,getEditorText:n(()=>"","getEditorText"),addAutocompleteProvider:i,setEditorComponent:i,getEditorComponent:n(()=>{},"getEditorComponent"),getAllThemes:n(()=>[],"getAllThemes"),getTheme:n(()=>{},"getTheme"),setTheme:i,getToolsExpanded:n(()=>!1,"getToolsExpanded"),setToolsExpanded:i}}n(yn,"makeBrokerUiContext");export{Kr as REVIEW_BOUNDARY_NAVIGATION_CODE,Br as ReviewBoundaryNavigationError,Sn as brokerToolOptions,En as buildBrokerSession,hn as disposeActiveSession,yn as makeBrokerUiContext,Nr as runBroker,le as snapshotMessages};
|
|
1
|
+
var Xe=Object.defineProperty;var n=(t,o)=>Xe(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as qe,envModelIntent as Ye,envNodeCwd as He,envNodeId as ze,envProfileId as Je,envScopes as Qe,scopeAllowed as Ze}from"../../shared/env.js";import{createServer as et}from"node:net";import{WebSocketServer as tt,createWebSocketStream as nt}from"ws";import{BROKER_VIEW_PORT as rt}from"./view-socket.js";import{existsSync as ke,readFileSync as ot,unlinkSync as Ce}from"node:fs";import{join as xe}from"node:path";import{randomUUID as O}from"node:crypto";import{mark as st}from"../timing.js";import{SUBMIT_RESULT_TOOL as it}from"./structured-output.js";import{flushConversation as ie,installSessionManagerStorePatch as at}from"../conversation-store/index.js";import{getAgentDir as Z,ModelRegistry as dt,ModelRuntime as lt}from"@earendil-works/pi-coding-agent";import{nodeRunDir as ct,viewSocketPath as mt}from"../canvas/paths.js";import{bindBrokerEventSource as ut}from"../events/source.js";import{emitEvent as R,flushBrokerLog as Ae}from"../events/emit.js";import{operationIdContext as ft}from"../events/operation-id.js";import{findMissingPackagePaths as pt}from"./package-health.js";import{installBrokerConfigSnapshot as gt}from"../config.js";import{FRONT_DOOR_ENV as vt}from"./front-door.js";import{CANVAS_EXTENSIONS as ae,piInvocationToSdkConfig as _t}from"./launch.js";import{assertEngineVersion as ht,loadBrokerEngine as wt}from"./broker-sdk.js";import{initCrtrTheme as St}from"./crtr-theme.js";import{resolveBundledPiPackageDir as bt}from"./pi-cli.js";import{captureSessionChatCapabilities as Rt}from"./command-surface.js";import{InMemoryCredentialStore as yt}from"@earendil-works/pi-ai";import{configureBrokerModelRuntime as Et,refusalRetryAt as Tt}from"./broker/model-adapter.js";import{brokerApiUrl as kt,mutateBrokerFault as ee,recordBrokerTurn as Me}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as Ct}from"./launch-recipe.js";import{fetchRunAttachments as Pe}from"./broker/attachments-fetch.js";import{modelRequestFromConfig as xt,expandModelCandidates as At,parseModelSpec as Mt,unregisteredConcreteModel as Pt}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as Ot}from"./stream-watchdog.js";import{probeOnline as Dt}from"./connectivity.js";import{CRTR_CYCLE_CUSTOM_TYPE as Oe,cycleAwareMessages as It,endedByAbort as Nt}from"./session-cycles.js";import{turnErrorOf as Ft}from"../llm/refusal.js";import{projectTranscript as Lt}from"./session-visibility.js";import{currentTurnVisibility as Bt}from"./turn-visibility.js";import{isUnknownModel as de}from"./model-selection.js";import{BrokerClientRegistry as Kt}from"./broker/client-registry.js";import{ToolGroupTracker as Ut}from"./broker/tool-groups.js";import{TurnReplyTracker as $t}from"./broker/turn-replies.js";import{onNodeNamed as Wt}from"./broker/node-named.js";import{FaultRetry as Gt,willDaemonRetry as jt}from"./broker/fault-retry.js";import{RunTurnEnds as Vt}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as Xt}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as qt,BROKER_START_CYCLE as Yt,BROKER_IDLE_TURN_START as Ht,BROKER_RUN_TURN_BUSY as zt,BROKER_RUN_STEER as Jt}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as Qt}from"./broker/run-steer.js";import{prependRunDeferredMail as Zt,settleRunDeferredMail as en}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as tn}from"./broker/run-turn-queue.js";import{EventProjection as nn}from"./broker/event-projection.js";import{createFrameDispatchContext as rn,handleFrame as on}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as sn,installAdvertisedCommandInvocationContract as an}from"./advertised-command-invocation.js";import{RebindDriver as dn}from"./broker/rebind.js";import{beginRuntimeTeardown as ln}from"./broker/extension-abort.js";import{receiveNodeToken as cn}from"./broker/node-token.js";import{serveCliRelay as mn}from"./broker/cli-relay.js";import{recordBrokerRelease as un}from"./lifecycle.js";import{setTurnCauseSource as fn}from"./broker/turn-cause.js";import{decodeKickoffOrigin as De,KICKOFF_ORIGIN_ENV as Ie}from"./stamp/protocol.js";import{announceMessageOrigin as Ne}from"./stamp/channel.js";import{commitBrokerModel as pn,recordConversationWriteFault as Fe}from"./broker/daemon-ops.js";import{bootExtensionState as gn}from"./broker/boot-state.js";import{startCycle as Le,takeCycleAttachments as Be}from"./broker/cycle-start.js";import{composerNames as vn}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as _n,FrameOverflowError as hn,normalizeSnapshotTail as wn}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as Gr,REVIEW_BOUNDARY_NAVIGATION_CODE as jr}from"./broker/frame-replies.js";function le(t){return new dt(t.modelRuntime)}n(le,"registryOf");function G(t,o){if(t==null||de(t))return null;const i=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${i}`}n(G,"formatModelSpec");function Sn(t,o){const i=G(t,void 0);return i===null?null:`${i}:${o===void 0||o===""?"off":o}`}n(Sn,"formatExactModelSpec");const bn=12e4;let te=null;import{brokerSignalClient as j}from"./broker/signal-stream.js";function Rn(){j().stop();const t=te;if(te=null,t!==null)try{t.dispose()}catch{}}n(Rn,"disposeActiveSession");function yn(t,o){const i=Ze(o,"crtr:act")?void 0:["bash"],g=t!==void 0&&t.length>0?[...new Set([...t,it])]:t===void 0?void 0:[...t];return{...g!==void 0?{tools:g}:{},...i!==void 0?{excludeTools:i}:{}}}n(yn,"brokerToolOptions");async function Ur(t,o=process.hrtime.bigint(),i=new Date().toISOString()){ut(t);const g=await cn(),s=await mn(t,g);process.env.CRTR_API_SOCKET=s.path,ft.fresh(()=>{R({level:"info",event:"broker.startup.cli_entry",ts:i,duration_ms:0,fields:{runtime_version:process.version,engine_version:null,model:null}}),R({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 a=new Set;let c=null;const l=n((e,r=null)=>{a.has(e)||(a.add(e),st(e,{duration_ms:Number(process.hrtime.bigint()-o)/1e6}),R({level:"info",event:e,duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:c,model:r}}))},"emitStartupMilestone");process.env[vt]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,at(t);const _=await wt();ht(_.VERSION),c=_.VERSION;const w=ct(t),T=xe(w,"broker-launch.json"),S=JSON.parse(ot(T,"utf8"));if(!S.configSnapshot)throw new Error("broker launch is missing its config snapshot");gt(S.configSnapshot);const u=_t(S);u.modelExact===!0?process.env.CRTR_MODEL_EXACT="1":delete process.env.CRTR_MODEL_EXACT;let b,E;const D=new AbortController,H=n(e=>{b!==void 0?b(e):(E??=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!==""&&j().start(t,e)});let{session:I,services:N,resuming:me,runtime:V}=await Cn(_,u);l("broker.startup.session_built");const x=await Le(t,I,"startup",D.signal);D.signal.aborted&&(I.dispose(),await Ae(),process.exit(0));const $=x?.names===void 0?await vn(t):x.names,A=(await gn(t)).node.review_binding?.review_id,L=qe();te=I;const Ue=Dt;try{process.env.PI_PACKAGE_DIR=bt(),St(N.settingsManager.getTheme(),Z(),!1)}catch(e){R({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of pt(Z()))R({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const X=mt(t),h=new Kt(t),z=new Map,M=new Ut(t,e=>h.broadcast(e)),q=new $t(t,e=>h.broadcast(e));Wt(e=>h.broadcast({type:"node_named",...e}));let B=!1,ue=!1,J,Q,fe,m,Y;const ne=new Vt;let W,pe=n(()=>{},"notifyTurnAccepted"),ge=n(()=>{},"resetFrameState");const re=Xt();let ve=n(()=>0,"pendingPromptDispatches"),_e;const P=tn({runNode:L,session:n(()=>m.session(),"session"),isReplacing:n(()=>m.isReplacing(),"isReplacing"),pendingRebind:n(()=>m.pendingRebind(),"pendingRebind"),isAgentRunActive:n(()=>m.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:n(()=>ve(),"pendingDispatches"),turnAdmission:re,prependDeferred:n(e=>Zt(t,e),"prependDeferred"),onError:n(e=>R({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),he=Qt(P.steerable);globalThis[Jt]=he,fn(()=>m.session());const we=P.drain;u.firstPrompt!==void 0&&u.firstPrompt!==""&&P.holdForKickoff(),globalThis[Ht]=P.start,globalThis[zt]=P.busy,m=new dn({nodeId:t,cfg:u,session:I,services:N,runtime:V,registry:h,toolGroups:M,turnReplies:q,runSteer:he,runNode:L,transcriptMessages:n(e=>ce(e,A)?.map(({message:r})=>r)??e.sessionManager.buildSessionContext().messages,"transcriptMessages"),uiContext:n(()=>fe,"uiContext"),faultRetry:n(()=>Y,"faultRetry"),projection:n(()=>W,"projection"),setActiveSession:n(e=>{if(te=e,_e?.(),L||process.env.CRTR_RUN_ID){let r="stop",d,f=!1;_e=e.subscribe(v=>{if(v.type==="agent_start"&&(r="stop",d=void 0,f=!1,ne.started()),v.type==="agent_end"){const p=[...v.messages??[]].reverse().find(y=>y.role==="assistant");p&&(r=p.stopReason,d=Nt(p)?void 0:Ft(p,Tt(p)),f=p.role==="assistant"&&jt(p,e.model?.contextWindow))}v.type==="agent_settled"&&(ne.settled(e.sessionManager,{stop_reason:r,...d?{error:d}:{}},f),L&&(ie().then(()=>en(t,e)).catch(async p=>{if(String(p?.message).startsWith("conversation_write_failed")){R({level:"error",event:"broker.exited",node_id:t,error:p,fields:{fault:"conversation_write_failed"}}),await Fe(t,p),k("conversation_write_failed",1);return}R({level:"error",event:"broker.run_deferred_mail.settle_failed",error:p})}),queueMicrotask(()=>{m.session()===e&&we()})))})}},"setActiveSession"),disposeAndExit:n((e,r)=>k(e,r),"disposeAndExit"),onSessionRebind:n(()=>{ge()},"onSessionRebind"),onReplacementIdle:n(()=>{L&&we()},"onReplacementIdle"),reWelcomeAll:n(()=>oe(),"reWelcomeAll")});const Se=n(async(e,r=!1)=>{const d=m.session(),f=G(d.model,d.thinkingLevel);if(f===null)return null;const v=await pn(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"),be=n(async(e=!0,r,d=!1)=>{const f=m.session(),v=G(f.model,f.thinkingLevel),p=e?await Se(r,d):v;h.broadcast({type:"model_changed",model:de(f.model)?void 0:f.model,spec:p})},"broadcastModelChanged");Y=new Gt({nodeId:t,cfg:u,retryProbe:Ue,currentSession:n(()=>m.session(),"currentSession"),currentServices:n(()=>m.services(),"currentServices"),installedGeneration:n(()=>m.installedGeneration(),"installedGeneration"),registryOf:le,formatModelSpec:G,broadcastModelChanged:be,turnAdmission:re,reWelcomeAll:n(()=>oe(),"reWelcomeAll"),...L?{turnEnds:ne}:{}});const Re=n(()=>{Y.rearmIfStranded().catch(e=>{R({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry re-arm failed: ${e instanceof Error?e.message:String(e)}`}})})},"rearmStrandedRetry");j().subscribe("resync",Re),j().subscribe("fault-retry",Re),W=new nn({registry:h,faultRetry:Y,installedGeneration:n(()=>m.installedGeneration(),"installedGeneration"),currentSession:n(()=>m.session(),"currentSession"),notifyTurnAccepted:n(()=>pe(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:G});const $e=n(e=>{const r=m.session(),d=ce(r,A),f=wn(e.snapshotTail),v=d===void 0||f===void 0?d:d.slice(-f),p=v?.map(({message:U})=>U)??r.sessionManager.buildSessionContext().messages,y=M.summaries(),K=v!==void 0&&f!==void 0?En(p):void 0,Ve=K===void 0?y:Object.fromEntries(Object.entries(y).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:Bt(),stats:r.getSessionStats(),state:{model:de(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:Ve,turnReplies:q.snapshot(),workingActivity:W.currentWorkingActivity(),queued:{steering:[...r.getSteeringMessages()],followUp:[...r.getFollowUpMessages()]}}},"buildSnapshot"),ye=n(e=>{const r=e.role==="controller"?z.values().next().value:void 0;h.sendFrame(e,{type:"welcome",snapshot:$e(e),role:e.role,pending_dialog:r!==void 0?r.request:null,agentDir:Z()},!0)},"sendWelcome"),We=n(e=>{const r=[...z.values()];for(let d=1;d<r.length;d++)h.sendFrame(e,r[d].request)},"replayExtraPendingDialogsTo"),oe=n(()=>{try{const e=m.session();q.seed(ce(e,A)?.map(({message:r})=>r)??e.sessionManager.buildSessionContext().messages)}catch(e){R({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply reseed failed: ${String(e)}`}})}h.forEachHelloed(ye)},"reWelcomeAll"),Ee=n(async e=>{if(B)return;B=!0;const r=j().latestNode;r!==void 0&&(r.intent==="idle-release"||r.status==="done")&&un(t,process.env.CRTR_EXECUTION_ID??null),j().stop(),e===0&&await ie().catch(async d=>{e=1,R({level:"error",event:"broker.exited",node_id:t,error:d,fields:{fault:"conversation_write_failed"}}),await Fe(t,d)}),M.persistPendingSummary(),W.dispose(),Rn();try{J?.close(),Q?.close()}catch{}s.close(),h.dispose();try{ke(X)&&Ce(X)}catch{}h.clearAttachState(),await Ae(),process.exit(e)},"completeExit"),k=n((e,r=0)=>{if(B)return;const d=e==="shutdown-hook"||e==="shutdown-after-settle";if(d&&M.finishOpenToolGroup(!0),d&&(M.hasSummaryTasks()||q.hasTasks())){if(ue)return;ue=!0,Promise.allSettled([M.waitForSummaryTasks(),q.waitForTasks()]).finally(()=>Ee(r));return}Ee(r)},"disposeAndExit");globalThis[qt]=k,fe=xn({writable:n(()=>h.writableClients(),"writable"),forward:n((e,r)=>h.sendFrame(e,r),"forward"),pending:z,broadcast:n(e=>h.broadcastUi(e),"broadcast"),onKnownStreamWait:n(e=>W.knownStreamWait(e),"onKnownStreamWait")}),m.setRebindSession(),await m.enqueueRebind(I,N),l("broker.startup.extensions_bound");const C=rn({nodeId:t,registry:h,toolGroups:M,projection:W,rebind:m,boundaryReviewId:A,pendingDialogs:z,sendWelcome:ye,replayExtraPendingDialogsTo:We,reWelcomeAll:oe,disposeAndExit:k,persistModelChoice:Se,broadcastModelChanged:be,registryOf:le,formatModelSpec:G,formatExactModelSpec:Sn,turnAdmission:re,memoryInventory:$,runNode:L,onKickoffAdmitted:P.releaseKickoff});pe=C.notifyTurnAccepted,ge=C.resetForSession,ve=C.pendingPromptDispatches,globalThis[Yt]=async e=>{for(const y of Ct){const K=e.env[y];K===void 0?delete process.env[y]:process.env[y]=K}process.env[Ie]=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=m.session(),d=r.sessionManager.getSessionFile();if(d===void 0||d==="")throw new Error("in-place cycle needs a persisted session file");const f=r.sessionManager,v=f.getLeafId();f.resetLeaf(),f.appendCustomEntry(Oe,{cycle:e.cycle,fromLeaf:v}),await ie(),m.beforeNextBind(async y=>{const K=await Le(t,y,"resume");await C.refreshMemoryNames(K?.names)});const p=await m.runReplacement(null,"cycle",y=>y.switchSession(d));if(m.beforeNextBind(void 0),!p)return k("cycle-replacement-failed",1),!1;Ne(e.prompt,De(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await Pe(t,Be(t))}catch(y){return R({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:y,fields:{operation:"attachments_fetch"}}),k("attachments-fetch-failed",1),!1}return C.kickoff(e.prompt,e.messageIds),!0};const Ge=2500;let se=!1;const je=n(async e=>{if(B||se)return;if(se=!0,m.isAgentRunActive()||m.session().isStreaming||C.pendingPromptDispatches()>0){const d=Date.now()+Ge;for(;C.pendingPromptDispatches()>0&&!m.session().isStreaming&&Date.now()<d;)await new Promise(f=>setTimeout(f,25));if(m.session().isStreaming){const f=d-Date.now();if(f>0){let v;try{ln(),await Promise.race([m.session().abort().then(()=>!0,()=>!1),new Promise(y=>{v=setTimeout(()=>y(!1),f)})])&&await Me(t,{event:"closed",end_reason:"teardown-aborted"})}finally{v!==void 0&&clearTimeout(v)}}}else(C.pendingPromptDispatches()>0||m.isAgentRunActive())&&await Me(t,{event:"interrupted"})}k(e)},"abortAndExit");if(b=n(e=>{je(e)},"signalTeardown"),E!==void 0){b(E);return}try{ke(X)&&Ce(X)}catch{}const Te=n(e=>{const r=h.create(e);e.on("data",f=>{let v;try{v=r.decoder.push(f)}catch(p){p instanceof hn?(h.sendFrame(r,{type:"error",code:"frame_overflow",message:p.message}),h.dropClient(r,`frame overflow: ${p.message}`)):h.dropClient(r,`decoder error: ${String(p)}`);return}for(const p of v)try{on(C,r,p)}catch{}});const d=n(()=>{h.removeClient(r)},"drop");e.on("close",d),e.on("error",()=>{})},"serveViewer");J=et(Te),kt()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(Q=new tt({host:"::",port:rt,path:"/view",maxPayload:_n.maxLineBytes}),Q.on("connection",e=>Te(nt(e))),Q.on("error",e=>{B||(R({level:"error",event:"broker.socket.failed",error:e}),k("socket-error",1))})),J.on("error",e=>{B||(R({level:"error",event:"broker.socket.failed",error:e}),k("socket-error",1))}),J.listen(X,async()=>{Promise.all([ee(t,{op:"clear",link:"viewer\u2194broker"}),ee(t,{op:"clear",link:"relay\u2194broker"})]).catch(r=>R({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"broker_socket_bound_fault_clear"}}));let e;try{e=await Y.recoverOnStartup()}catch(r){R({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:r,fields:{operation:"recovery_startup"}}),k("recovery-startup-failed",1);return}if(!(B||se))if(e==="none"&&u.firstPrompt!==void 0&&u.firstPrompt!==""){const r=De(process.env[Ie]);r!==null&&Ne(u.firstPrompt,r);try{await Pe(t,Be(t))}catch(f){R({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:f,fields:{operation:"attachments_fetch"}}),k("attachments-fetch-failed",1);return}const d=process.env.CRTR_KICKOFF_MESSAGE_IDS;C.kickoff(u.firstPrompt,d?JSON.parse(d):[])}else P.releaseKickoff()}),h.persistAttachState()}n(Ur,"runBroker");function En(t){const o=new Set;for(const i of t)if(!(i.role!=="assistant"||!Array.isArray(i.content)))for(const g of i.content)g!==null&&typeof g=="object"&&g.type==="toolCall"&&typeof g.id=="string"&&o.add(g.id);return o}n(En,"toolCallIds");function ce(t,o){const i=t.sessionManager,g=It(i);return g!==void 0&&sn(g.map(({message:s})=>s)),g===void 0?void 0:Lt(g,{boundaryReviewId:o,sessionEntries:i.getEntries?.()})}n(ce,"snapshotMessages");function Ke(){const t=ze();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}n(Ke,"currentBrokerNodeId");async function Tn(t,o){const i=xt(o.model,Ye(),o.modelExact===!0);if(i===void 0)return;const g=le(t),s={cwd:He()??o.cwd,profileId:Je()},a=await Pt(i,g,s);if(a!==void 0)throw await ee(Ke(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`model '${a.request.spec}' is not registered in the serving model registry`}}),new Error(`[broker] FATAL: model '${a.request.spec}' is not registered in the serving model registry`);const c=await At(i,s.cwd,s.profileId),l=Mt(i.spec);for(const _ of c){const w=g.find(_.providerId,_.modelId);if(w===void 0)continue;const S=l?.providerId===_.providerId&&l.modelId===_.modelId?l.thinkingLevel??(_.thinkingLevel===void 0?void 0:"off"):_.thinkingLevel;return{model:w,thinkingLevel:S}}if(o.modelExact===!0){const _=c.map(w=>`'${w.providerId}/${w.modelId}' unregistered`).join("; ");throw await ee(Ke(),{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`)}R({level:"warn",event:"broker.model.none_viable",fields:{rejected_candidates:c.map(_=>({provider:_.providerId,model:_.modelId,reason:"unregistered"})).slice(0,16)}})}n(Tn,"resolveLaunchModel");function kn(t){let o=!0;return{runtime:new Proxy(t,{get(g,s,a){return o&&s==="getAvailableSnapshot"?()=>[]:o&&s==="getAvailable"?async()=>[]:o&&s==="getModel"?()=>{}:Reflect.get(g,s,a)}}),reveal:n(()=>{o=!1},"reveal")}}n(kn,"modelLessRegistry");async function Cn(t,o){const i=Z(),g=n(async S=>{const u=await lt.create({credentials:new yt,modelsPath:xe(S.agentDir,"models.json")});Et(u);const b=await t.createAgentSessionServices({cwd:S.cwd,agentDir:S.agentDir,modelRuntime:u,resourceLoaderOptions:{additionalExtensionPaths:o.extensionPaths,appendSystemPrompt:o.appendSystemPromptPath!==void 0?[o.appendSystemPromptPath]:void 0,noContextFiles:!0,extensionsOverride:n(x=>({...x,extensions:x.extensions.filter($=>!/[/\\]provider-rotation\.(?:ts|js)$/.test($.path))}),"extensionsOverride")}}),E=b.resourceLoader.getExtensions();if(o.extensionPaths.some(x=>ae.includes(x))){const x=new Set(E.extensions.map(F=>F.path)),$=ae.filter(F=>!x.has(F));if($.length>0){const F=E.errors.filter(A=>ae.includes(A.path)).map(A=>`${A.path}: ${A.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${$.join(", ")}${F===""?"":` (${F})`}`)}}b.settingsManager.getRetryEnabled=()=>!1;const D=await Tn(b,o),H=D?.model,I=D?.thinkingLevel,N=D===void 0?kn(b.modelRuntime):void 0,me=N!==void 0?{...b,modelRuntime:N.runtime}:b,V=await t.createAgentSessionFromServices({services:me,sessionManager:S.sessionManager,model:H,thinkingLevel:I,...yn(o.tools,Qe()),sessionStartEvent:S.sessionStartEvent});return an(V.session),Rt(V.session),N?.reveal(),{...V,services:b}},"buildForManager"),s=o.resumeSessionPath,a=o.forkFrom!==void 0&&o.forkFrom!=="";if(!a&&(s===void 0||s==="")&&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 c=!a&&s!==void 0&&s!=="",l=c&&o.newCycle===!0,_=c&&!l;let w;if(a)w=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(_||l){if(w=await t.SessionManager.open(s),l){const S=w.getLeafId();w.resetLeaf(),w.appendCustomEntry(Oe,{cycle:Number(process.env.CRTR_CYCLES),fromLeaf:S})}}else w=await t.SessionManager.create(o.cwd);if(t.createAgentSessionRuntime!==void 0){const S=n(async b=>{const E=await g({cwd:b.cwd,agentDir:b.agentDir,sessionManager:b.sessionManager,sessionStartEvent:b.sessionStartEvent});return{...E,diagnostics:E.services.diagnostics??[]}},"factory"),u=await t.createAgentSessionRuntime(S,{cwd:o.cwd,agentDir:i,sessionManager:w});return{session:u.session,services:u.services,resuming:_,runtime:u}}const T=await g({cwd:o.cwd,agentDir:i,sessionManager:w});return{session:T.session,services:T.services,resuming:_,runtime:void 0}}n(Cn,"buildBrokerSession");function xn(t){const o=n((s,a,c,l)=>{if(l?.signal?.aborted)return Promise.resolve(s);const _=t.writable();return _.length===0?Promise.resolve(s):new Promise(w=>{let T;const S=n(()=>{T!==void 0&&clearTimeout(T),l?.signal?.removeEventListener("abort",u),t.pending.delete(a.id)},"cleanup"),u=n(()=>{S(),t.broadcast({type:"extension_ui_dismiss",id:a.id}),w(s)},"onAbort");l?.signal?.addEventListener("abort",u,{once:!0});const b=l?.timeout!==void 0?l.timeout:bn;T=setTimeout(()=>{S(),t.broadcast({type:"extension_ui_dismiss",id:a.id}),w(s)},b),typeof T.unref=="function"&&T.unref(),t.pending.set(a.id,{request:a,resolve:n(E=>{S(),t.broadcast({type:"extension_ui_dismiss",id:a.id}),w(c(E))},"resolve")});for(const E of _)t.forward(E,a)})},"dialogPromise"),i=n(()=>{},"noop");return{[Ot]:t.onKnownStreamWait??(s=>()=>{}),get theme(){const s=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(s==null)throw new Error("Theme not initialized. Call initTheme() first.");return s},select:n((s,a,c)=>o(void 0,{type:"extension_ui_request",id:O(),method:"select",title:s,options:a,timeout:c?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,c),"select"),confirm:n((s,a,c)=>o(!1,{type:"extension_ui_request",id:O(),method:"confirm",title:s,message:a,timeout:c?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,c),"confirm"),input:n((s,a,c)=>o(void 0,{type:"extension_ui_request",id:O(),method:"input",title:s,placeholder:a,timeout:c?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,c),"input"),editor:n((s,a)=>o(void 0,{type:"extension_ui_request",id:O(),method:"editor",title:s,prefill:a},c=>"cancelled"in c&&c.cancelled?void 0:"value"in c?c.value:void 0),"editor"),setStatus:n((s,a)=>t.broadcast({type:"extension_ui_request",id:O(),method:"setStatus",statusKey:s,statusText:a}),"setStatus"),setWidget:n((s,a,c)=>{typeof a!="function"&&t.broadcast({type:"extension_ui_request",id:O(),method:"setWidget",widgetKey:s,widgetLines:a,widgetPlacement:c?.placement})},"setWidget"),setTitle:n(s=>t.broadcast({type:"extension_ui_request",id:O(),method:"setTitle",title:s}),"setTitle"),notify:n((s,a)=>{const c=a==="warn"?"warning":a;t.broadcast({type:"extension_ui_request",id:O(),method:"notify",message:s,notifyType:c})},"notify"),onTerminalInput:n(()=>i,"onTerminalInput"),setWorkingMessage:i,setWorkingVisible:i,setWorkingIndicator:i,setHiddenThinkingLabel:i,setFooter:i,setHeader:i,custom:n(()=>Promise.resolve(void 0),"custom"),pasteToEditor:i,setEditorText:i,getEditorText:n(()=>"","getEditorText"),addAutocompleteProvider:i,setEditorComponent:i,getEditorComponent:n(()=>{},"getEditorComponent"),getAllThemes:n(()=>[],"getAllThemes"),getTheme:n(()=>{},"getTheme"),setTheme:i,getToolsExpanded:n(()=>!1,"getToolsExpanded"),setToolsExpanded:i}}n(xn,"makeBrokerUiContext");export{jr as REVIEW_BOUNDARY_NAVIGATION_CODE,Gr as ReviewBoundaryNavigationError,yn as brokerToolOptions,Cn as buildBrokerSession,Rn as disposeActiveSession,xn as makeBrokerUiContext,Ur as runBroker,ce as snapshotMessages};
|
|
@@ -11,6 +11,9 @@ export interface Recipe {
|
|
|
11
11
|
pi_packages: string | null;
|
|
12
12
|
}
|
|
13
13
|
export declare const NODE_BASE_IMAGE = "public.ecr.aws/docker/library/node:24-alpine";
|
|
14
|
+
export declare const SANDBOX_API_IMAGE = "ghcr.io/blaxel-ai/sandbox:latest";
|
|
15
|
+
/** The user the sandbox bootstrap runs the node as. */
|
|
16
|
+
export declare const RUN_USER = "crtr";
|
|
14
17
|
/** Where the image installs the recipe's pi packages: one pi agent dir of its own, not any app's. The start script (`sandbox-start.mjs`) links its
|
|
15
18
|
* `npm`/`git` trees into, and merges its `packages` setting with, the agent dir of whichever app the node runs in. Keep the two in step. */
|
|
16
19
|
export declare const RECIPE_PI_AGENT_DIR = "/var/lib/crtr/recipe-pi-agent";
|
|
@@ -3,4 +3,4 @@ var B=Object.defineProperty;var l=(e,r)=>B(e,"name",{value:r,configurable:!0});i
|
|
|
3
3
|
`)}l(X,"recipeDockerfile");const ee=l((e,r,a)=>new Promise((o,i)=>{const n=P("git",e,{cwd:a,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let t="";n.stderr.on("data",s=>{t+=s.toString()}),n.on("error",i),n.on("close",s=>{s===0?o():i(new Error(`git ${e[0]} failed (${s}): ${t.slice(0,300)}`))})}),"runGit");async function le(e){const r=e.git??ee,a=e.packagesToken??null,o=e.cloneUrl??(n=>`https://github.com/${n}.git`);G(g(e.dir,U),{recursive:!0});const i=e.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:${e.token}`).toString("base64")}`};for(const n of e.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),g(U,n.name)],i,e.dir)}b(g(e.dir,"Dockerfile"),X(e.recipe,e.revision,a!==null)),a!==null&&b(g(e.dir,".env.build"),`NODE_AUTH_TOKEN=${a}
|
|
4
4
|
`,{mode:384}),e.recipe.setup_script!==null&&e.recipe.setup_script.trim()!==""&&b(g(e.dir,I),e.recipe.setup_script.endsWith(`
|
|
5
5
|
`)?e.recipe.setup_script:`${e.recipe.setup_script}
|
|
6
|
-
`)}l(le,"prepareBuildDir");function v(e,r,a){for(const o of F(r).sort()){const i=g(r,o),n=C(i),t=j(e,i).split("\\").join("/");n.isDirectory()?v(e,i,a):n.isSymbolicLink()?a.push({name:t,data:Buffer.from(K(i)),mode:y.S_IFLNK|511}):n.isFile()&&a.push({name:t,data:M(i),mode:y.S_IFREG|n.mode&511})}}l(v,"walk");function te(e){const r=[];v(e,e,r);const a=[],o=[];let i=0;for(const s of r){const u=Buffer.from(s.name),m=z(s.data),$=q(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($,14),p.writeUInt32LE(m.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(u.length,26),a.push(p,u,m);const c=Buffer.alloc(46);c.writeUInt32LE(33639248,0),c.writeUInt16LE(788,4),c.writeUInt16LE(20,6),c.writeUInt16LE(2048,8),c.writeUInt16LE(8,10),c.writeUInt32LE(33,14),c.writeUInt32LE($,16),c.writeUInt32LE(m.length,20),c.writeUInt32LE(s.data.length,24),c.writeUInt16LE(u.length,28),c.writeUInt32LE(s.mode<<16>>>0,38),c.writeUInt32LE(i,42),o.push(c,u),i+=p.length+u.length+m.length}const n=Buffer.concat(o),t=Buffer.alloc(22);return t.writeUInt32LE(101010256,0),t.writeUInt16LE(r.length,8),t.writeUInt16LE(r.length,10),t.writeUInt32LE(n.length,12),t.writeUInt32LE(i,16),Buffer.concat([...a,n,t])}l(te,"zipDirectory");async function
|
|
6
|
+
`)}l(le,"prepareBuildDir");function v(e,r,a){for(const o of F(r).sort()){const i=g(r,o),n=C(i),t=j(e,i).split("\\").join("/");n.isDirectory()?v(e,i,a):n.isSymbolicLink()?a.push({name:t,data:Buffer.from(K(i)),mode:y.S_IFLNK|511}):n.isFile()&&a.push({name:t,data:M(i),mode:y.S_IFREG|n.mode&511})}}l(v,"walk");function te(e){const r=[];v(e,e,r);const a=[],o=[];let i=0;for(const s of r){const u=Buffer.from(s.name),m=z(s.data),$=q(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($,14),p.writeUInt32LE(m.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(u.length,26),a.push(p,u,m);const c=Buffer.alloc(46);c.writeUInt32LE(33639248,0),c.writeUInt16LE(788,4),c.writeUInt16LE(20,6),c.writeUInt16LE(2048,8),c.writeUInt16LE(8,10),c.writeUInt32LE(33,14),c.writeUInt32LE($,16),c.writeUInt32LE(m.length,20),c.writeUInt32LE(s.data.length,24),c.writeUInt16LE(u.length,28),c.writeUInt32LE(s.mode<<16>>>0,38),c.writeUInt32LE(i,42),o.push(c,u),i+=p.length+u.length+m.length}const n=Buffer.concat(o),t=Buffer.alloc(22);return t.writeUInt32LE(101010256,0),t.writeUInt16LE(r.length,8),t.writeUInt16LE(r.length,10),t.writeUInt32LE(n.length,12),t.writeUInt32LE(i,16),Buffer.concat([...a,n,t])}l(te,"zipDirectory");async function x(e,r,a,o,i=[]){const n=`${e.controlUrl??"https://api.blaxel.ai/v0"}${a}`,t=await(e.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${e.apiKey}`,"x-blaxel-workspace":e.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await t.text();let u=null;if(s!=="")try{u=JSON.parse(s)}catch{u={raw:s}}if(!t.ok&&!i.includes(t.status))throw new H(t.status,null,`Blaxel ${r} ${n} failed (${t.status}): ${s.slice(0,300)}`);return{status:t.status,headers:t.headers,json:u}}l(x,"api");async function S(e,r){const{status:a,json:o}=await x(e,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return a===404?null:o}l(S,"getImage");async function pe(e,r){await x(e,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}l(pe,"deleteImage");async function de(e,r,a,o={}){const i=o.sleep??(f=>new Promise(w=>setTimeout(w,f))),n=o.now??Date.now,t=n(),s=await S(e,r),u=new Set((s?.spec?.tags??[]).map(f=>f.name)),m=s?.metadata?.events?.length??0,p=(await x(e,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(p===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const c=await(e.fetch??fetch)(p,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(te(a))});if(!c.ok)throw new Error(`uploading the build context of image ${r} failed (${c.status}): ${(await c.text()).slice(0,300)}`);const A=t+(o.timeoutMs??20*6e4);let _=null;for(;;){const f=await S(e,r),w=f?.metadata?.status;if(w==="BUILT"&&(f?.metadata?.events?.length??0)>=m+2){_??=n();const E=(f?.spec?.tags??[]).filter(d=>d.name!==void 0),L=(f?.metadata?.events??[]).slice(m).map(d=>d.time??"").filter(d=>d!=="").sort()[0],R=l(d=>L!==void 0&&Date.parse(d??"")>=Date.parse(L),"touchedSince"),N=E.filter(d=>!u.has(d.name)||R(d.createdAt)||R(d.updatedAt)),k=n()-_>=(o.tagGraceMs??6e4),O=(N.length>0?N:k?E:[]).sort((d,D)=>(D.updatedAt??"").localeCompare(d.updatedAt??""))[0]?.name;if(O!==void 0)return{ref:`sandbox/${r}:${O}`,buildMs:n()-t};if(k)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(w==="FAILED"||w==="TERMINATED"){const E=f?.metadata?.events??[];throw new Error(`building image ${r} ${w.toLowerCase()}: ${E[E.length-1]?.message??"no message"}`)}if(n()>A)throw new Error(`building image ${r} did not finish within ${o.timeoutMs??20*6e4} ms (last status ${w??"none"})`);await i(o.pollMs??3e3)}}l(de,"buildImage");const ue=l(e=>`env-${e}`,"environmentImageName");function fe(e){Y(e,{recursive:!0,force:!0})}l(fe,"removeBuildDir");export{J as NODE_BASE_IMAGE,T as RECIPE_PI_AGENT_DIR,U as REPOS_DIR,h as RUN_USER,W as SANDBOX_API_IMAGE,I as SETUP_SCRIPT_FILE,de as buildImage,pe as deleteImage,ue as environmentImageName,S as getImage,le as prepareBuildDir,X as recipeDockerfile,fe as removeBuildDir,te as zipDirectory};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { BlaxelConfig } from './client.js';
|
|
2
|
+
import { type BuildImageOptions, type BuiltImage } from './image-build.js';
|
|
3
|
+
/** Where the bootstrap keeps releases. Keep in step with `ROOT` in scripts/sandbox-bootstrap.sh. */
|
|
4
|
+
export declare const RELEASES_DIR = "/opt/crtr/releases";
|
|
5
|
+
/** Written into an unpacked release by the bootstrap and by this image: the sha256 of the tarball it came from. The bootstrap trusts a present release only when this equals the sha the wake names. */
|
|
6
|
+
export declare const RELEASE_SHA_FILE = ".sha256";
|
|
7
|
+
/** Written last into an unpacked release: it is complete. */
|
|
8
|
+
export declare const RELEASE_COMPLETE_FILE = ".complete";
|
|
9
|
+
export declare const RELEASE_TARBALL_FILE = "runtime.tar.gz";
|
|
10
|
+
/** The pointer object's key in the release bucket, beside `runtime.tar.gz` and its sha256. */
|
|
11
|
+
export declare const releaseImageKey: (version: string) => string;
|
|
12
|
+
/** The Blaxel image name of a release: `0.3.668-delivery.1` -> `crtr-release-0-3-668-delivery-1`. Every release has its own image, so a release's image is deleted by name. */
|
|
13
|
+
export declare function releaseImageName(version: string): string;
|
|
14
|
+
/** The Dockerfile of a release image. Pure. Two stages: the release is unpacked in the first, so the tarball is in no layer of the final image.
|
|
15
|
+
* The base is the recipe image's (node, sandbox-api, the `crtr` user), plus `ripgrep` (pi's grep tool) and `python3` (the stock image has it). */
|
|
16
|
+
export declare function releaseImageDockerfile(version: string, sha256: string): string;
|
|
17
|
+
/** What `releases/<version>/sandbox-image.json` holds. `sha256` is the tarball's, so a pointer left over from another build of the same version is refused. */
|
|
18
|
+
export interface ReleaseImagePointer {
|
|
19
|
+
release: string;
|
|
20
|
+
sha256: string;
|
|
21
|
+
image: string;
|
|
22
|
+
}
|
|
23
|
+
export declare function releaseImagePointerText(pointer: ReleaseImagePointer): string;
|
|
24
|
+
/** The image a pointer names for `release` and the tarball `sha256` the wake carries. Throws on a malformed pointer, one for another release, or one built from another tarball: none is a reason to launch silently from the stock image. */
|
|
25
|
+
export declare function parseReleaseImagePointer(text: string, release: string, sha256: string): string;
|
|
26
|
+
export interface BuildReleaseImageInput {
|
|
27
|
+
release: string;
|
|
28
|
+
/** The `runtime.tar.gz` the release was published with (scripts/sandbox-release.mjs). */
|
|
29
|
+
tarball: string;
|
|
30
|
+
/** Its sha256; checked against the file, so an image is never built from a tarball other than the one the wake will name. */
|
|
31
|
+
sha256: string;
|
|
32
|
+
}
|
|
33
|
+
/** Builds the release's image in the workspace `config` names and returns its pointer. */
|
|
34
|
+
export declare function buildReleaseImage(config: BlaxelConfig, input: BuildReleaseImageInput, options?: BuildImageOptions): Promise<{
|
|
35
|
+
pointer: ReleaseImagePointer;
|
|
36
|
+
built: BuiltImage;
|
|
37
|
+
}>;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var p=Object.defineProperty;var o=(e,r)=>p(e,"name",{value:r,configurable:!0});import{createHash as f}from"node:crypto";import{copyFileSync as E,mkdtempSync as g,readFileSync as w,writeFileSync as d}from"node:fs";import{tmpdir as b}from"node:os";import{join as l}from"node:path";import{buildImage as R,NODE_BASE_IMAGE as h,removeBuildDir as S,RUN_USER as c,SANDBOX_API_IMAGE as u}from"./image-build.js";const x="/opt/crtr/releases",y=".sha256",I=".complete",n="runtime.tar.gz",A=/^[0-9a-f]{64}$/,O=/^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$/,i=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 ${n} /tmp/${n}`,`RUN mkdir -p ${a} && tar -xzf /tmp/${n} -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/${c} -s /bin/sh ${c} && mkdir -p /run/crtr /var/lib/crtr /work/.crtr && chown -R ${c} /run/crtr /var/lib/crtr /work`,"COPY --from=release /opt/crtr /opt/crtr","WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""].join(`
|
|
2
|
+
`)}o(N,"releaseImageDockerfile");function C(e){return`${JSON.stringify(e)}
|
|
3
|
+
`}o(C,"releaseImagePointerText");function M(e,r,a){let s;try{s=JSON.parse(e)}catch{throw new Error(`${i(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(`${i(r)} must hold {release, sha256, image}`);if(t.release!==r)throw new Error(`${i(r)} names release ${t.release}`);if(t.sha256!==a)throw new Error(`${i(r)} was built from tarball ${t.sha256}, not ${a}`);return t.image}o(M,"parseReleaseImagePointer");async function T(e,r,a={}){const s=f("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(l(b(),"crtr-release-image-"));try{E(r.tarball,l(t,n)),d(l(t,"Dockerfile"),N(r.release,r.sha256));const m=await R(e,$(r.release),t,a);return{pointer:{release:r.release,sha256:r.sha256,image:m.ref},built:m}}finally{S(t)}}o(T,"buildReleaseImage");export{x as RELEASES_DIR,I as RELEASE_COMPLETE_FILE,y as RELEASE_SHA_FILE,n as RELEASE_TARBALL_FILE,T as buildReleaseImage,M as parseReleaseImagePointer,N as releaseImageDockerfile,i as releaseImageKey,$ as releaseImageName,C as releaseImagePointerText};
|
|
@@ -12,7 +12,7 @@ export declare const brokerProcessName: (executionId: string) => string;
|
|
|
12
12
|
export declare const sandboxNameFor: (execution: RunnerExecution) => string;
|
|
13
13
|
/** What `start` needs from the control plane beyond the execution: the environment's image and size, the release object, the secrets. */
|
|
14
14
|
export interface BlaxelLaunchContext {
|
|
15
|
-
/** `environments.image_ref` for a recipe environment, else `blaxel/base-image:latest`. */
|
|
15
|
+
/** `environments.image_ref` for a recipe environment, else the release's own image (release-image.ts) when it was published with one, else `blaxel/base-image:latest`. */
|
|
16
16
|
image: string;
|
|
17
17
|
memoryMb: number;
|
|
18
18
|
/** `CRTR_API_URL` the broker reaches `/v1` at. */
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var he=Object.defineProperty;var d=(e,o)=>he(e,"name",{value:o,configurable:!0});import{accessSync as pe,constants as ke}from"node:fs";import{isAbsolute as _e,resolve as ve,join as ge}from"node:path";import{appSpace as ye}from"../layout.js";import{ApiError as oe}from"../../api/errors.js";import{spawnNode as be,forkSourceNode as xe,currentNodeContext as $e,rootOfSpine as Ce,newNodeId as Se,preflightNodeId as Oe}from"./nodes.js";import{resolveProfileOperand as Ee}from"../profiles/manifest.js";import{selectProfileForCwd as Re,selectProfileForCwdReadOnly as Ie}from"../profiles/select.js";import{buildLaunchSpecAsync as re,buildPiArgv as Fe}from"./launch.js";import{runsOnBlaxel as Me,sandboxWorktreeRequest as Be}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Pe,rollbackManagedWorktreeAsync as De}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Ne,rollbackManagedWorktreeOnMachine as Le,worktreeMachineOf as Te}from"../worktree-machine.js";import{usage as w,brokerLaunchFailed as N}from"../errors.js";import{writeGoal as Ae}from"./kickoff.js";import{appendSituationalContext as We,formatSituationalProse as je}from"./situational-context.js";import{ensureRoadmap as ze}from"./roadmap.js";import{buildWakeBearings as He}from"./bearings.js";import{encodeKickoffOrigin as Ke,KICKOFF_ORIGIN_ENV as Ge}from"./stamp/protocol.js";import{carryInitialInput as Ue}from"../runs/initial-input.js";import{ExecutionCapReached as Ve,beginExecution as Xe,crtrHome as qe,getNode as u,fullName as te,jobDir as Ye,recordExecutionPid as Je,abortExecution as z,setFrozen as H}from"../canvas/index.js";import{contextDir as K,nodeAgentDir as G}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as Qe}from"../spaces/open-beneath.js";import{conversationIdFromPath as L,conversationStore as S}from"../conversation-store/index.js";import{appMemoryTooSmall as Ze,boundFleet as en,brokerThresholdsForDaemon as ie}from"./fleet.js";import{admitBrokerMemory as nn}from"./memory-admission.js";import{emitEvent as T}from"../events/emit.js";import{remoteEnvironmentOf as on}from"./blaxel-environment.js";import{openViewerWindow as rn,focusOf as tn,windowOfPane as an}from"./placement.js";import{awaitBrokerViewSocket as dn}from"./view-socket.js";import{readLogSnapshot as sn}from"../events/read.js";import{transition as g}from"./lifecycle.js";import{beginBootFaultAttempt as ln}from"../canvas/recovery.js";import{headlessBrokerHost as U}from"./host.js";import{ensureDaemon as cn}from"../../daemon/manage.js";import{readConfig as un}from"../config.js";import{modelRequestFromConfig as fn,unregisteredConcreteModel as wn,unroutableConcreteModel as mn}from"../model-routes.js";import{openModelRegistry as hn}from"./model-registry.js";import{MODEL_SPEC_NEXT as pn}from"./model-selection.js";import{forkNodeLedger as kn}from"./ledger.js";import{appRungForGrant as _n}from"../llm/app-rungs.js";import{APP_FAMILY as V}from"../model-routes.js";import{discoverLifecycleHookRegistry as vn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as gn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as yn}from"../async-array.js";import{checkStart as bn}from"./start-check.js";function y(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}d(y,"launchFailureOutcome");async function xn(e,o,a){try{return await U.launch(e,o,a)}catch(r){try{await g(e,"crash",{reason:"launch_failed",outcome:y(r)})}catch{}const t=r.message;throw N(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}d(xn,"launchBrokerOrCrash");function $n(e){return sn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}d($n,"lastStartupStep");function Cn(e,o){const a=$n(e),r=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(o.reason==="exited"){const{code:t,signal:s}=o.status;return{text:`exited (code ${t??"null"}, signal ${s??"null"}) before binding its view socket; ${r}`,fields:{reason:"exited",code:t,signal:s,last_startup_step:a}}}return{text:`was still starting after ${Math.round(o.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${r}`,fields:{reason:"timeout",waited_ms:o.waitedMs,last_startup_step:a}}}d(Cn,"notReadyDescription");async function Sn(e,o){try{await g(e,"crash",{reason:"launch_failed",outcome:y(o)})}catch{}try{U.teardown(e)}catch{}}d(Sn,"crashAndTearDown");async function On(e){const o=(await S().list()).map(({conversation_id:t,path:s})=>({id:t,path:s})),a=o.filter(t=>t.id===e),r=a.length>0?a:o.filter(t=>t.id.startsWith(e));if(r.length===0)throw w(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(r.length>1)throw w(`--fork-from '${e}': ambiguous \u2014 ${r.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return r[0].path}d(On,"resolveSessionUuid");async function ae(e){const o=e.trim();if(o==="")throw w("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(o.includes("/")||o.endsWith(".jsonl")){const r=L(_e(o)?o:ve(process.cwd(),o));if(r===null)throw w(`--fork-from '${o}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await S().header(r)).path}const a=await u(o);if(a!==null){const r=a.pi_session_file;if(r==null||r==="")throw w(`node ${o} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=L(r);if(t===null)throw w(`node ${o} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await S().header(t)).path}return await On(o)}d(ae,"resolveForkSource");async function En(e,o,a,r={}){return e===null?null:e!==void 0&&e!==""?Ee(e).profileId:o!==null?(await u(o))?.profile_id??null:r.readOnlySelection===!0?Ie(a):Re(a)}d(En,"resolveProfileId");function de(e){const o=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return fn(e.model,o,e.modelExact===!0)}d(de,"requestFromLaunch");async function se(e,o,a){const r=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await _n(o,r,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:s,...l}=e.env??{};return{...e,model:t.model,modelIntent:{family:V,strength:t.strength},modelExact:void 0,env:{...l,CRTR_MODEL_INTENT:`${V}/${t.strength}`}}}d(se,"appPaidLaunch");async function le(e,o,a){if(e===void 0||e.kind==="logical"&&e.family!==V)return;const r=await wn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await hn(),o);if(r!==void 0)throw w(`model '${r.request.spec}' is not registered in this daemon.`,{received:r.request.spec,next:pn});const t=await mn(e,o);if(t!==void 0)throw w(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}d(le,"assertLaunchModelRegistered");function Rn(e,o,a){const r=e??o??null;if(!a&&r===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return r}d(Rn,"resolveSpawner");async function ce(e,o,a){try{cn()}catch{}const r=$e(),t=e.root===!0,s=Rn(e.parent,r.nodeId??null,t),l=e.mode??"base",b=e.rootLifecycle??(t?"resident":"terminal"),ue=t&&b==="resident",E=s===null?null:await u(s),X=e.creator===void 0||e.creator===null?null:await u(e.creator);e.nodeId!==void 0&&await Oe(e.nodeId);const x=e.forkFrom!==void 0?await ae(e.forkFrom):void 0,A=x===void 0?null:await xe(x),W=await yn([E,X,A],async f=>f?.isolated===!0||f?.run_id!=null&&(await u(f.run_id))?.isolated===!0);if(W&&e.isolated===!1)throw new oe(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const R=W||e.isolated===!0;if(R&&e.worktree===!0)throw new oe(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});const $=e.worktree===!0,m=R||$?e.nodeId??await Se():e.nodeId,I=R?e.run!==void 0&&t&&!W?e.cwd:ge(ye(e.run?.grantee??E?.grantee??"app:terminal").nodes,m):e.cwd,h=await En(e.profile,s,I),q=e.run?.grant_id??E?.grant_id??null,O=e.run??X??E??A,Y=await se((await re(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:I,profileId:h,app:O?.grantee??"app:terminal"})).launch,q,e.model);await le(de(Y),{cwd:I,profileId:h}),await bn({grantee:O?.grantee??"app:terminal",sub:O?.sub,grant_id:O?.grant_id});const J=A?.node_id??null;let p,F=I;const M=$&&await Me(h)?await Be(h,e.worktreeCwd??e.cwd,m,e.worktreeBase):void 0,B=$&&M===void 0?await Te(h):null;try{$&&M===void 0&&(p=B!==null?await Ne(B,e.worktreeCwd??e.cwd,m,e.worktreeBase):await Pe(e.worktreeCwd??e.cwd,m,e.worktreeBase),F=p.path);const f=$?await se((await re(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:F,profileId:h,app:O?.grantee??"app:terminal"})).launch,q,e.model):Y;M!==void 0&&(f.worktree=M),$&&await le(de(f),{cwd:F,profileId:h});const n=await be({kind:e.kind,mode:l,lifecycle:b,cwd:F,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:J,spawnedBy:t?s??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:R,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:x,modelOverride:e.model===void 0?void 0:f.model,...p!==void 0?{managedWorktree:p}:{},...m!==void 0?{nodeId:m}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await kn(n.node_id,J??null)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}if(await Ae(n.node_id,e.prompt),e.situationalContext!==void 0&&await We(n.node_id,je(e.situationalContext)),o!==void 0)try{o(n.node_id)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}const j=e.prompt!=="",fe=`${j&&e.wakeOrigin!==void 0?`${He(e.wakeOrigin)}
|
|
1
|
+
var ke=Object.defineProperty;var d=(e,r)=>ke(e,"name",{value:r,configurable:!0});import{accessSync as _e,constants as ve}from"node:fs";import{isAbsolute as ge,resolve as ye,join as be}from"node:path";import{appSpace as xe}from"../layout.js";import{ApiError as oe}from"../../api/errors.js";import{spawnNode as Ce,forkSourceNode as $e,currentNodeContext as Se,rootOfSpine as Ee,newNodeId as te,preflightNodeId as Oe}from"./nodes.js";import{resolveProfileOperand as Re}from"../profiles/manifest.js";import{selectProfileForCwd as Ie,selectProfileForCwdReadOnly as Fe}from"../profiles/select.js";import{buildLaunchSpecAsync as ie,buildPiArgv as Me}from"./launch.js";import{devEnvironmentCwd as Be,runsOnBlaxel as Pe,sandboxWorktreeRequest as De}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ne,rollbackManagedWorktreeAsync as Le}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Te,rollbackManagedWorktreeOnMachine as Ae,worktreeMachineOf as We}from"../worktree-machine.js";import{usage as h,brokerLaunchFailed as L}from"../errors.js";import{writeGoal as je}from"./kickoff.js";import{appendSituationalContext as ze,formatSituationalProse as He}from"./situational-context.js";import{ensureRoadmap as Ke}from"./roadmap.js";import{buildWakeBearings as Ge}from"./bearings.js";import{encodeKickoffOrigin as Ue,KICKOFF_ORIGIN_ENV as Ve}from"./stamp/protocol.js";import{carryInitialInput as Xe}from"../runs/initial-input.js";import{ExecutionCapReached as qe,beginExecution as Ye,crtrHome as Je,getNode as u,fullName as ae,jobDir as Qe,recordExecutionPid as Ze,abortExecution as H,setFrozen as K}from"../canvas/index.js";import{contextDir as G,nodeAgentDir as U}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as en}from"../spaces/open-beneath.js";import{conversationIdFromPath as T,conversationStore as S}from"../conversation-store/index.js";import{appMemoryTooSmall as nn,boundFleet as rn,brokerThresholdsForDaemon as de}from"./fleet.js";import{admitBrokerMemory as on}from"./memory-admission.js";import{emitEvent as A}from"../events/emit.js";import{remoteEnvironmentOf as tn}from"./blaxel-environment.js";import{openViewerWindow as an,focusOf as dn,windowOfPane as sn}from"./placement.js";import{awaitBrokerViewSocket as ln}from"./view-socket.js";import{readLogSnapshot as cn}from"../events/read.js";import{transition as g}from"./lifecycle.js";import{beginBootFaultAttempt as un}from"../canvas/recovery.js";import{headlessBrokerHost as V}from"./host.js";import{ensureDaemon as fn}from"../../daemon/manage.js";import{readConfig as wn}from"../config.js";import{modelRequestFromConfig as mn,unregisteredConcreteModel as hn,unroutableConcreteModel as pn}from"../model-routes.js";import{openModelRegistry as kn}from"./model-registry.js";import{MODEL_SPEC_NEXT as _n}from"./model-selection.js";import{forkNodeLedger as vn}from"./ledger.js";import{appRungForGrant as gn}from"../llm/app-rungs.js";import{APP_FAMILY as X}from"../model-routes.js";import{discoverLifecycleHookRegistry as yn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as bn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as xn}from"../async-array.js";import{checkStart as Cn}from"./start-check.js";function y(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}d(y,"launchFailureOutcome");async function $n(e,r,a){try{return await V.launch(e,r,a)}catch(o){try{await g(e,"crash",{reason:"launch_failed",outcome:y(o)})}catch{}const t=o.message;throw L(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}d($n,"launchBrokerOrCrash");function Sn(e){return cn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}d(Sn,"lastStartupStep");function En(e,r){const a=Sn(e),o=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(r.reason==="exited"){const{code:t,signal:s}=r.status;return{text:`exited (code ${t??"null"}, signal ${s??"null"}) before binding its view socket; ${o}`,fields:{reason:"exited",code:t,signal:s,last_startup_step:a}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${o}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:a}}}d(En,"notReadyDescription");async function On(e,r){try{await g(e,"crash",{reason:"launch_failed",outcome:y(r)})}catch{}try{V.teardown(e)}catch{}}d(On,"crashAndTearDown");async function Rn(e){const r=(await S().list()).map(({conversation_id:t,path:s})=>({id:t,path:s})),a=r.filter(t=>t.id===e),o=a.length>0?a:r.filter(t=>t.id.startsWith(e));if(o.length===0)throw h(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(o.length>1)throw h(`--fork-from '${e}': ambiguous \u2014 ${o.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return o[0].path}d(Rn,"resolveSessionUuid");async function se(e){const r=e.trim();if(r==="")throw h("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const o=T(ge(r)?r:ye(process.cwd(),r));if(o===null)throw h(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await S().header(o)).path}const a=await u(r);if(a!==null){const o=a.pi_session_file;if(o==null||o==="")throw h(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=T(o);if(t===null)throw h(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await S().header(t)).path}return await Rn(r)}d(se,"resolveForkSource");async function In(e,r,a,o={}){return e===null?null:e!==void 0&&e!==""?Re(e).profileId:r!==null?(await u(r))?.profile_id??null:o.readOnlySelection===!0?Fe(a):Ie(a)}d(In,"resolveProfileId");function le(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return mn(e.model,r,e.modelExact===!0)}d(le,"requestFromLaunch");async function ce(e,r,a){const o=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await gn(r,o,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:s,...l}=e.env??{};return{...e,model:t.model,modelIntent:{family:X,strength:t.strength},modelExact:void 0,env:{...l,CRTR_MODEL_INTENT:`${X}/${t.strength}`}}}d(ce,"appPaidLaunch");async function ue(e,r,a){if(e===void 0||e.kind==="logical"&&e.family!==X)return;const o=await hn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await kn(),r);if(o!==void 0)throw h(`model '${o.request.spec}' is not registered in this daemon.`,{received:o.request.spec,next:_n});const t=await pn(e,r);if(t!==void 0)throw h(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}d(ue,"assertLaunchModelRegistered");function Fn(e,r,a){const o=e??r??null;if(!a&&o===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return o}d(Fn,"resolveSpawner");async function fe(e,r,a){try{fn()}catch{}const o=Se(),t=e.root===!0,s=Fn(e.parent,o.nodeId??null,t),l=e.mode??"base",b=e.rootLifecycle??(t?"resident":"terminal"),we=t&&b==="resident",I=s===null?null:await u(s),q=e.creator===void 0||e.creator===null?null:await u(e.creator);e.nodeId!==void 0&&await Oe(e.nodeId);const x=e.forkFrom!==void 0?await se(e.forkFrom):void 0,W=x===void 0?null:await $e(x),j=await xn([I,q,W],async f=>f?.isolated===!0||f?.run_id!=null&&(await u(f.run_id))?.isolated===!0);if(j&&e.isolated===!1)throw new oe(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const E=j||e.isolated===!0;if(E&&e.worktree===!0)throw new oe(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let w=E||e.worktree===!0?e.nodeId??await te():e.nodeId,C=E?e.run!==void 0&&t&&!j?e.cwd:be(xe(e.run?.grantee??I?.grantee??"app:terminal").nodes,w):e.cwd;const m=await In(e.profile,s,C),F=E?null:await Be(m,e.worktreeCwd??C);F!==null&&(C=F,w??=await te());const O=e.worktree===!0||F!==null,Y=e.run?.grant_id??I?.grant_id??null,R=e.run??q??I??W,J=await ce((await ie(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:C,profileId:m,app:R?.grantee??"app:terminal"})).launch,Y,e.model);await ue(le(J),{cwd:C,profileId:m}),await Cn({grantee:R?.grantee??"app:terminal",sub:R?.sub,grant_id:R?.grant_id});const Q=W?.node_id??null;let p,M=C;const B=O&&await Pe(m)?await De(m,F??e.worktreeCwd??e.cwd,w,e.worktreeBase):void 0,P=O&&B===void 0?await We(m):null;try{O&&B===void 0&&(p=P!==null?await Te(P,e.worktreeCwd??e.cwd,w,e.worktreeBase):await Ne(e.worktreeCwd??e.cwd,w,e.worktreeBase),M=p.path);const f=O?await ce((await ie(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:M,profileId:m,app:R?.grantee??"app:terminal"})).launch,Y,e.model):J;B!==void 0&&(f.worktree=B),O&&await ue(le(f),{cwd:M,profileId:m});const n=await Ce({kind:e.kind,mode:l,lifecycle:b,cwd:M,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:Q,spawnedBy:t?s??void 0:void 0,profile_id:m,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:E,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:x,modelOverride:e.model===void 0?void 0:f.model,...p!==void 0?{managedWorktree:p}:{},...w!==void 0?{nodeId:w}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await vn(n.node_id,Q??null)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}if(await je(n.node_id,e.prompt),e.situationalContext!==void 0&&await ze(n.node_id,He(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}const z=e.prompt!=="",me=`${z&&e.wakeOrigin!==void 0?`${Ge(e.wakeOrigin)}
|
|
2
2
|
|
|
3
|
-
`:""}${e.prompt}`;l==="orchestrator"&&await
|
|
3
|
+
`:""}${e.prompt}`;l==="orchestrator"&&await Ke(n.node_id,{goal:e.prompt.trim()}),await Mn(n);let Z;if(x!==void 0)try{const i=T(x);if(i===null)throw new Error(`invalid fork source ${x}`);const c=await S().fork(i,n.node_id);Z=(await S().header(c)).path}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}const k=Me(n,{prompt:me,resumeSessionPath:Z});if(k.env={...k.env,CRTR_SUBTREE:await Ee(n.node_id)},z){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};k.env[Ve]=Ue(i),await Xe(k,n)}const _=rn();if(await tn(n.profile_id??null)!==null)return await K(n.node_id,new Date().toISOString()),A({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const ee=await _.reserveSlot(n.node_id),v=ee?await on(n.node_id):null;if(v?.verdict==="too_small"){_.releaseReservation(n.node_id);const i=nn(v);throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}if(!ee||v?.verdict==="denied")return v?.verdict==="denied"&&_.releaseReservation(n.node_id),await K(n.node_id,new Date().toISOString()),A({level:"info",event:"broker.frozen",node_id:n.node_id,fields:v?.verdict==="denied"?{reason:"app_memory",free_bytes:v.free_bytes,needed_bytes:v.needed_bytes}:{reason:"broker_cap",live_count:await _.occupancy(),hard_cap:de().automaticReviveCap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null};const he=await un(n.node_id),{automaticReviveCap:pe}=de();let $;try{$=await Ye(n.node_id,{daemonEpoch:_.epoch(),cap:pe})}catch(i){if(!(i instanceof qe))throw i;return _.releaseReservation(n.node_id),await K(n.node_id,new Date().toISOString()),A({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await u(n.node_id),frozen:!0,window:null,session:null}}k.env={...k.env,CRTR_EXECUTION_ID:$};let D;try{D=await $n(n.node_id,k,{cwd:n.cwd,name:ae(n),resuming:!1})}catch(i){throw await H($,{reason:"launch_failed"}),i}finally{_.releaseReservation(n.node_id)}if(D.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await H($,{reason:"launch_failed"}),await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),L(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await Ze($,n.node_id,D.pid)==="shutdown")throw await H($,{reason:"superseded"}),V.teardown(n.node_id),L(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(we&&e.readiness==="await"){const i=await ln(n.node_id,D.exited);if(!i.ready){const c=En(n.node_id,i);A({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:c.fields});const N=await he.explanation();throw await On(n.node_id,new Error(N??c.text)),L(N!==null?`the root broker ${n.node_id} could not start \u2014 ${N}`:`the root broker ${n.node_id} ${c.text} \u2014 it was not started.`,N!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let ne=null,re=null;if(!t&&s!==null&&wn("user").auto_open_child_viewers)try{const i=await dn(s);if(i!==null&&i.pane!==null&&i.pane!==""){const c=await an(n.node_id,i.session??"",{name:ae(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:z});c!==null&&c.pane!==null&&c.pane!==""&&(re=c.session,ne=sn(c.pane))}}catch{}return{node:await u(n.node_id),frozen:!1,window:ne,session:re}}catch(f){throw p!==void 0&&w!==void 0&&await u(w)===null&&(P!==null?await Ae(P,p):await Le(p)),f}}d(fe,"spawnChildPrepared");async function Er(e){return fe(e)}d(Er,"spawnChild");async function Mn(e){const r=yn(e.cwd,e.profile_id).plans.get("node:start")??[];await bn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await U(e.node_id),contextDir:await G(e.node_id),jobDir:Qe(e.node_id)},runtime:{isBirth:!0,canvasHome:Je(),profile:e.profile_id??null}})}d(Mn,"invokeBirthLifecycleHooks");const Bn=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function Or(e,r,a){const o=await u(e);if(o===null)throw h(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const t=await se(e),s=await G(e);try{await S().header(T(t)),_e(s,ve.R_OK)}catch(l){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${l.message}`)}return fe({kind:o.kind,mode:"base",cwd:o.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...a===void 0?{}:{actor:a},profile:o.profile_id,model:o.model_override??void 0,...r===void 0?{}:{scopes:r}},async l=>{const b=await G(l);en(await U(e),s,await U(l),b,Bn)})}d(Or,"forkNode");export{ce as appPaidLaunch,ue as assertLaunchModelRegistered,Or as forkNode,Mn as invokeBirthLifecycleHooks,se as resolveForkSource,In as resolveProfileId,Fn as resolveSpawner,Er as spawnChild,fe as spawnChildPrepared};
|
|
@@ -1,8 +1,14 @@
|
|
|
1
|
+
import { type EnvironmentImage } from '../../daemon/reconcilers/recipe-image.js';
|
|
1
2
|
import type { BlaxelLaunchContext } from '../runtime/runner/blaxel/runner.js';
|
|
2
3
|
import type { RunnerStartInput } from '../runtime/runner/types.js';
|
|
3
4
|
export declare const BASE_IMAGE = "blaxel/base-image:latest";
|
|
4
5
|
/** How long the signed release URL stays valid. */
|
|
5
6
|
export declare const RELEASE_URL_TTL_S: number;
|
|
7
|
+
/** The sandbox image a launch starts from: the environment's recipe image when it has one; otherwise the release's own image (`releaseImage`, from the pointer object
|
|
8
|
+
* beside the release) when the release was published with one; otherwise the stock image, whose bootstrap installs the release at boot. */
|
|
9
|
+
export declare function launchImage(environment: Exclude<EnvironmentImage, {
|
|
10
|
+
state: 'pending';
|
|
11
|
+
}>, releaseImage: string | null): string;
|
|
6
12
|
export interface ReleaseSigner {
|
|
7
13
|
bucket: string;
|
|
8
14
|
endpoint: string;
|
|
@@ -17,6 +23,8 @@ export interface BlaxelLaunchDeps {
|
|
|
17
23
|
signer: ReleaseSigner;
|
|
18
24
|
/** The sha256 text of `releases/<version>/runtime.tar.gz.sha256`; default: the blob store. */
|
|
19
25
|
releaseSha?: (version: string) => Promise<string | null>;
|
|
26
|
+
/** The text of `releases/<version>/sandbox-image.json`; default: the blob store. Null: the release has no image. */
|
|
27
|
+
releaseImage?: (version: string) => Promise<string | null>;
|
|
20
28
|
now?: () => Date;
|
|
21
29
|
}
|
|
22
30
|
/** Reads the control plane's settings from the environment: `CRTR_PUBLIC_API_URL` (where a sandbox reaches `/v1`) and the four `CRTR_R2_*` variables. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.defineProperty;var t=(r,e)=>A(r,"name",{value:e,configurable:!0});import{createHash as I,createHmac as R}from"node:crypto";import{openDb as C}from"../canvas/db.js";import{blobStore as S}from"../blobs/index.js";import{environmentOfNode as $,packagesTokenFor as b}from"../../daemon/api/environment-of.js";import{EnvironmentImagePending as T}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{resolveEnvironmentImage as y}from"../../daemon/reconcilers/recipe-image.js";import{parseReleaseImagePointer as U,releaseImageKey as x}from"../runtime/runner/blaxel/release-image.js";import{environmentSecrets as L}from"./environment-secrets.js";import{environmentOwnerProfile as v,profileInApp as D}from"./environment-owner.js";const H="blaxel/base-image:latest",P=900;function z(r,e){return r.state==="image"?r.ref:e??H}t(z,"launchImage");function K(r=process.env){const e=t(a=>{const n=r[a];if(!n)throw new Error(`${a} is required to sign release URLs`);return n},"need");return{bucket:e("CRTR_R2_BUCKET"),endpoint:e("CRTR_R2_ENDPOINT"),accessKeyId:e("CRTR_R2_ACCESS_KEY_ID"),secretAccessKey:e("CRTR_R2_SECRET_ACCESS_KEY")}}t(K,"releaseSignerFromEnv");const O=t(r=>I("sha256").update(r).digest("hex"),"sha256hex"),w=t((r,e)=>R("sha256",r).update(e).digest(),"hmac"),h=t(r=>encodeURIComponent(r).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),"encode");function N(r,e,a,n=new Date){const l=new URL(r.endpoint),i=n.toISOString().replace(/[:-]|\.\d{3}/g,""),o=i.slice(0,8),s=`${o}/auto/s3/aws4_request`,m=`/${h(r.bucket)}/${e.split("/").map(h).join("/")}`,f=[["X-Amz-Algorithm","AWS4-HMAC-SHA256"],["X-Amz-Credential",`${r.accessKeyId}/${s}`],["X-Amz-Date",i],["X-Amz-Expires",String(a)],["X-Amz-SignedHeaders","host"]].sort(([c],[_])=>c<_?-1:1).map(([c,_])=>`${h(c)}=${h(_)}`).join("&"),p=["GET",m,f,`host:${l.host}
|
|
2
2
|
`,"host","UNSIGNED-PAYLOAD"].join(`
|
|
3
|
-
`),
|
|
4
|
-
`),
|
|
3
|
+
`),d=["AWS4-HMAC-SHA256",i,s,O(p)].join(`
|
|
4
|
+
`),E=w(w(w(w(`AWS4${r.secretAccessKey}`,o),"auto"),"s3"),"aws4_request"),g=R("sha256",E).update(d).digest("hex");return`${l.origin}${m}?${f}&X-Amz-Signature=${g}`}t(N,"presignGet");function V(r=process.env){const e=r.CRTR_PUBLIC_API_URL;if(!e||!/^https?:\/\//.test(e))throw new Error("CRTR_PUBLIC_API_URL must be an http(s) URL for the Blaxel runner");return{apiUrl:e,signer:K(r)}}t(V,"blaxelLaunchDepsFromEnv");async function M(r){const e=await(await S()).get(`releases/${r}/runtime.tar.gz.sha256`);return e===null?null:e.toString("utf8")}t(M,"defaultReleaseSha");async function j(r){const e=await(await S()).get(x(r));return e===null?null:e.toString("utf8")}t(j,"defaultReleaseImage");function Z(r){return async e=>{const a=await C(),n=await a.prepare("SELECT profile_id, grantee FROM node_rows WHERE node_id = ?").get(e.nodeId);if(n===void 0)throw new Error(`no node ${e.nodeId}`);if(n.profile_id===null)throw new Error(`node ${e.nodeId} has no profile, so it has no person`);const l=await a.prepare("SELECT person FROM profiles WHERE id = ?").get(n.profile_id);if(l===void 0)throw new Error(`profile ${n.profile_id} has no row`);const i=n.grantee??"app:terminal",o=await $(n.profile_id),s=await y(o);if(s.state==="pending")throw new T(o,s.error);const m=await a.prepare("SELECT memory_mb FROM environments WHERE object = ?").get(o);if(m===void 0)throw new Error(`no environment ${o}`);const u=await v(o),f=u!==null&&await D(u,i),p=(await(r.releaseSha??M)(e.release)??"").trim().split(/\s+/)[0]??"";if(!/^[0-9a-f]{64}$/.test(p))throw new Error(`release ${e.release} has no sha256 object (releases/${e.release}/runtime.tar.gz.sha256)`);const d=s.state==="base"?await(r.releaseImage??j)(e.release):null,E=d===null?null:U(d,e.release,p),g=await b(o),c=await L({person:l.person,app:i,ownerProfile:u,ownerProfileInApp:f,includeDeployment:!1});return{image:z(s,E),memoryMb:Number(m.memory_mb),apiUrl:r.apiUrl,releaseUrl:N(r.signer,`releases/${e.release}/runtime.tar.gz`,P,r.now?.()),releaseSha256:p,secrets:g!==null?{NODE_AUTH_TOKEN:g,...c}:c}}}t(Z,"createBlaxelLaunchContext");export{H as BASE_IMAGE,P as RELEASE_URL_TTL_S,V as blaxelLaunchDepsFromEnv,Z as createBlaxelLaunchContext,z as launchImage,N as presignGet,K as releaseSignerFromEnv};
|