@north-light/cli 0.3.700 → 0.3.701

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var d=Object.defineProperty;var a=(s,e)=>d(s,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{WebSocket as h}from"ws";import{classify as f}from"../fault-classifier.js";import{AttachRefusedError as u,BrokerUnavailableError as m}from"./transport.js";function g(s,e,t){if("socketPath"in s)return`ws+unix://${s.socketPath}:/v1/nodes/${encodeURIComponent(e)}/attach?revive=0`;const r=new URL(s.previewEndpoint);return r.protocol=r.protocol==="http:"?"ws:":"wss:",r.pathname=`/v1/nodes/${encodeURIComponent(e)}/attach`,r.search=t?"?wakeParked=1":"",r.hash="",r.toString()}a(g,"relayUrl");class O extends l{static{a(this,"RelayTransport")}nodeId;target;wakeParked;ws;closeEmitted=!1;constructor(e,t,r=!0){super(),this.nodeId=e,this.target=t,this.wakeParked=r}refusal;refusalError;get url(){return g(this.target,this.nodeId,this.wakeParked)}dial(){const e=new h(this.url,{..."relayToken"in this.target?{headers:{authorization:`Bearer ${this.target.relayToken}`}}:{},perMessageDeflate:!1});return e.on("unexpected-response",(t,r)=>{let o="";r.on("data",n=>{o.length<2048&&(o+=n.toString())}),r.on("end",()=>{this.refusal=w(r.statusCode,o),this.refusalError=p(r.statusCode,o),e.terminate()})}),this.ws=e,e}connect(){const e=this.dial();e.on("open",()=>{this.emit("connect")}),e.on("message",t=>this.onMessage(t)),e.on("error",t=>this.onError(t)),e.on("close",(t,r)=>this.onClose(t,r.toString()))}redial(e){return this.wakeParked=!0,this.destroy(),this.closeEmitted=!1,new Promise((t,r)=>{const o=this.dial();let n=!1;o.on("open",()=>{n||(n=!0,this.emit("connect"),t())}),o.on("message",i=>this.onMessage(i)),o.on("error",i=>{if(n){this.onError(i);return}n=!0;try{o.terminate()}catch{}r(this.refusal===void 0?i:Object.assign(new Error(this.refusal),{refusal:this.refusalError}))}),o.on("close",(i,c)=>{n&&this.onClose(i,c.toString())})})}send(e){const t=this.ws;if(!(t===void 0||t.readyState!==h.OPEN))try{t.send(JSON.stringify(e))}catch{}}destroy(){const e=this.ws;if(e!==void 0&&e.readyState<=h.OPEN)try{e.close(1e3)}catch{}}onMessage(e){let t;try{t=JSON.parse(e.toString())}catch{return}this.emit("frame",t)}onError(e){this.emitError(Object.assign(new Error(`relay transport error: ${this.refusal??e.message}`),{refusal:this.refusalError}))}onClose(e,t){if(this.closeEmitted)return;this.closeEmitted=!0;const r=f("viewer\u2194broker",{code:e,reason:t}),o=e===1008||r.kind==="protocol"||e===1011&&(/^no running broker/.test(t)||/^no node /.test(t));e===1008?this.emitError(new u(this.nodeId,t)):o&&this.emitError(new m(this.nodeId)),this.emit("close")}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}function p(s,e){try{const t=JSON.parse(e).error;if(s!==void 0&&typeof t?.code=="string")return{status:s,code:t.code,message:typeof t.message=="string"?t.message:""}}catch{}}a(p,"refusalOf");function w(s,e){try{const t=JSON.parse(e).error;if(typeof t?.code=="string")return`attach refused (${s??"?"} ${t.code}): ${typeof t.message=="string"?t.message:""}`}catch{}return`attach refused (${s??"?"})`}a(w,"refusalMessage");export{O as RelayTransport,w as refusalMessage};
1
+ var f=Object.defineProperty;var c=(o,t)=>f(o,"name",{value:t,configurable:!0});import{EventEmitter as u}from"node:events";import{WebSocket as d}from"ws";import{mark as h}from"../timing.js";import{classify as m}from"../fault-classifier.js";import{AttachRefusedError as p,BrokerUnavailableError as g}from"./transport.js";function w(o,t,e){if("socketPath"in o)return`ws+unix://${o.socketPath}:/v1/nodes/${encodeURIComponent(t)}/attach?revive=0`;const r=new URL(o.previewEndpoint);return r.protocol=r.protocol==="http:"?"ws:":"wss:",r.pathname=`/v1/nodes/${encodeURIComponent(t)}/attach`,r.search=e?"?wakeParked=1":"",r.hash="",r.toString()}c(w,"relayUrl");class $ extends u{static{c(this,"RelayTransport")}nodeId;target;wakeParked;ws;closeEmitted=!1;constructor(t,e,r=!0){super(),this.nodeId=t,this.target=e,this.wakeParked=r}refusal;refusalError;get url(){return w(this.target,this.nodeId,this.wakeParked)}dial(){const t=performance.now(),e=c(()=>(performance.now()-t).toFixed(1),"since"),r="socketPath"in this.target?"local":"remote";h("relay.dial_start",{node:this.nodeId,target:r});const s=new d(this.url,{..."relayToken"in this.target?{headers:{authorization:`Bearer ${this.target.relayToken}`}}:{},perMessageDeflate:!1});return s.once("upgrade",()=>h("relay.upgrade_response",{node:this.nodeId,target:r,since_dial_ms:e()})),s.once("open",()=>h("relay.ws_open",{node:this.nodeId,target:r,since_dial_ms:e()})),s.on("unexpected-response",(i,n)=>{let a="";n.on("data",l=>{a.length<2048&&(a+=l.toString())}),n.on("end",()=>{this.refusal=E(n.statusCode,a),this.refusalError=y(n.statusCode,a),s.terminate()})}),this.ws=s,s}connect(){const t=this.dial();t.on("open",()=>{this.emit("connect")}),t.on("message",e=>this.onMessage(e)),t.on("error",e=>this.onError(e)),t.on("close",(e,r)=>this.onClose(e,r.toString()))}redial(t){return this.wakeParked=!0,this.destroy(),this.closeEmitted=!1,new Promise((e,r)=>{const s=this.dial();let i=!1;s.on("open",()=>{i||(i=!0,this.emit("connect"),e())}),s.on("message",n=>this.onMessage(n)),s.on("error",n=>{if(i){this.onError(n);return}i=!0;try{s.terminate()}catch{}r(this.refusal===void 0?n:Object.assign(new Error(this.refusal),{refusal:this.refusalError}))}),s.on("close",(n,a)=>{i&&this.onClose(n,a.toString())})})}send(t){const e=this.ws;if(!(e===void 0||e.readyState!==d.OPEN))try{e.send(JSON.stringify(t))}catch{}}destroy(){const t=this.ws;if(t!==void 0&&t.readyState<=d.OPEN)try{t.close(1e3)}catch{}}onMessage(t){let e;try{e=JSON.parse(t.toString())}catch{return}this.emit("frame",e)}onError(t){this.emitError(Object.assign(new Error(`relay transport error: ${this.refusal??t.message}`),{refusal:this.refusalError}))}onClose(t,e){if(this.closeEmitted)return;this.closeEmitted=!0;const r=m("viewer\u2194broker",{code:t,reason:e}),s=t===1008||r.kind==="protocol"||t===1011&&(/^no running broker/.test(e)||/^no node /.test(e));t===1008?this.emitError(new p(this.nodeId,e)):s&&this.emitError(new g(this.nodeId)),this.emit("close")}emitError(t){this.listenerCount("error")>0&&this.emit("error",t)}}function y(o,t){try{const e=JSON.parse(t).error;if(o!==void 0&&typeof e?.code=="string")return{status:o,code:e.code,message:typeof e.message=="string"?e.message:""}}catch{}}c(y,"refusalOf");function E(o,t){try{const e=JSON.parse(t).error;if(typeof e?.code=="string")return`attach refused (${o??"?"} ${e.code}): ${typeof e.message=="string"?e.message:""}`}catch{}return`attach refused (${o??"?"})`}c(E,"refusalMessage");export{$ as RelayTransport,E as refusalMessage};
@@ -1 +1 @@
1
- var a=Object.defineProperty;var d=(n,e)=>a(n,"name",{value:e,configurable:!0});import{existsSync as o,mkdirSync as l,unlinkSync as c,writeFileSync as h}from"node:fs";import{nodeRunJobDir as r}from"../../canvas/paths.js";import{emitEvent as u}from"../../events/emit.js";import{encodeFrame as p,FrameDecoder as y,BROKER_READ_CAPS as f,SNAPSHOT_TAIL as g}from"../broker-protocol.js";const S=1e3,m=32*1024*1024;class B{static{d(this,"BrokerClientRegistry")}nodeId;attachPath;clients=new Set;displayStatuses=new Map;displayWidgets=new Map;displayTitle;constructor(e){this.nodeId=e,this.attachPath=`${r(e)}/attach.json`}create(e){const t={id:"",role:"observer",socket:e,decoder:new y(f),helloed:!1,attends:!0,snapshotTail:g,pendingBytes:0,queuedFrames:0};return this.clients.add(t),t}writableClients(){const e=[];for(const t of this.clients)!t.helloed||t.role!=="controller"||t.socket.destroyed||t.socket.readableEnded||!t.socket.writable||e.push(t);return e}persistAttachState(){try{let e=0;for(const s of this.clients)s.helloed&&s.attends&&(e+=1);const t=r(this.nodeId);o(t)||l(t,{recursive:!0}),h(this.attachPath,JSON.stringify({viewers:e,updated:new Date().toISOString()},null,2),"utf8")}catch{}}dropClient(e,t){if(this.clients.has(e)){u({level:"info",event:"broker.runtime.diagnostic",fields:{message:`dropping viewer ${e.id||"(pre-hello)"} \u2014 ${t}`}}),this.removeClient(e);try{e.socket.destroy()}catch{}}}removeClient(e){this.clients.delete(e),this.persistAttachState()}sendFrame(e,t){let s;try{s=p(t)}catch{return}const i=Buffer.byteLength(s);if(e.queuedFrames+1>S||e.pendingBytes+i>m){this.dropClient(e,`backpressure high-water mark exceeded (queued=${e.queuedFrames}, pending=${e.pendingBytes}B)`);return}e.queuedFrames+=1,e.pendingBytes+=i;try{e.socket.write(s,()=>{e.queuedFrames-=1,e.pendingBytes-=i})}catch{e.queuedFrames-=1,e.pendingBytes-=i}}broadcast(e){for(const t of this.clients)t.helloed&&this.sendFrame(t,e)}broadcastUi(e){e.type==="extension_ui_request"&&(e.method==="setStatus"?(this.displayStatuses.delete(e.statusKey),e.statusText!==void 0&&this.displayStatuses.set(e.statusKey,e.statusText)):e.method==="setWidget"?(this.displayWidgets.delete(e.widgetKey),e.widgetLines!==void 0&&this.displayWidgets.set(e.widgetKey,{lines:[...e.widgetLines],placement:e.widgetPlacement??"aboveEditor"})):e.method==="setTitle"&&(this.displayTitle=e.title)),this.broadcast(e)}displaySnapshot(){return{statuses:Object.fromEntries(this.displayStatuses),widgets:Object.fromEntries([...this.displayWidgets].map(([e,t])=>[e,{lines:[...t.lines],placement:t.placement}])),title:this.displayTitle}}forEachHelloed(e){for(const t of this.clients)t.helloed&&e(t)}dispose(){for(const e of this.clients)try{e.socket.destroy()}catch{}this.clients.clear()}clearAttachState(){try{o(this.attachPath)&&c(this.attachPath)}catch{}}}export{B as BrokerClientRegistry};
1
+ var u=Object.defineProperty;var a=(o,e)=>u(o,"name",{value:e,configurable:!0});import{existsSync as c,mkdirSync as p,unlinkSync as y,writeFileSync as f}from"node:fs";import{nodeRunJobDir as l}from"../../canvas/paths.js";import{emitEvent as n}from"../../events/emit.js";import{encodeFrame as m,FrameDecoder as w,BROKER_READ_CAPS as g,SNAPSHOT_TAIL as S}from"../broker-protocol.js";const b=1e3,v=32*1024*1024;class A{static{a(this,"BrokerClientRegistry")}nodeId;attachPath;clients=new Set;displayStatuses=new Map;displayWidgets=new Map;displayTitle;constructor(e){this.nodeId=e,this.attachPath=`${l(e)}/attach.json`}create(e){const t={id:"",role:"observer",socket:e,decoder:new w(g),helloed:!1,attends:!0,snapshotTail:S,pendingBytes:0,queuedFrames:0};return this.clients.add(t),t}writableClients(){const e=[];for(const t of this.clients)!t.helloed||t.role!=="controller"||t.socket.destroyed||t.socket.readableEnded||!t.socket.writable||e.push(t);return e}persistAttachState(){try{let e=0;for(const s of this.clients)s.helloed&&s.attends&&(e+=1);const t=l(this.nodeId);c(t)||p(t,{recursive:!0}),f(this.attachPath,JSON.stringify({viewers:e,updated:new Date().toISOString()},null,2),"utf8")}catch{}}dropClient(e,t){if(this.clients.has(e)){n({level:"info",event:"broker.runtime.diagnostic",fields:{message:`dropping viewer ${e.id||"(pre-hello)"} \u2014 ${t}`}}),this.removeClient(e);try{e.socket.destroy()}catch{}}}removeClient(e){this.clients.delete(e),this.persistAttachState()}sendFrame(e,t){let s;const h=performance.now();try{s=m(t)}catch{return}const i=Buffer.byteLength(s);if(e.queuedFrames+1>b||e.pendingBytes+i>v){this.dropClient(e,`backpressure high-water mark exceeded (queued=${e.queuedFrames}, pending=${e.pendingBytes}B)`);return}e.queuedFrames+=1,e.pendingBytes+=i;const r=t.type==="welcome",d=performance.now();r&&n({level:"info",event:"broker.view.welcome_encoded",fields:{client:e.id,bytes:i,encode_ms:Math.round((d-h)*10)/10}});try{e.socket.write(s,()=>{e.queuedFrames-=1,e.pendingBytes-=i,r&&n({level:"info",event:"broker.view.welcome_written",fields:{client:e.id,bytes:i,write_ms:Math.round((performance.now()-d)*10)/10}})})}catch{e.queuedFrames-=1,e.pendingBytes-=i}}broadcast(e){for(const t of this.clients)t.helloed&&this.sendFrame(t,e)}broadcastUi(e){e.type==="extension_ui_request"&&(e.method==="setStatus"?(this.displayStatuses.delete(e.statusKey),e.statusText!==void 0&&this.displayStatuses.set(e.statusKey,e.statusText)):e.method==="setWidget"?(this.displayWidgets.delete(e.widgetKey),e.widgetLines!==void 0&&this.displayWidgets.set(e.widgetKey,{lines:[...e.widgetLines],placement:e.widgetPlacement??"aboveEditor"})):e.method==="setTitle"&&(this.displayTitle=e.title)),this.broadcast(e)}displaySnapshot(){return{statuses:Object.fromEntries(this.displayStatuses),widgets:Object.fromEntries([...this.displayWidgets].map(([e,t])=>[e,{lines:[...t.lines],placement:t.placement}])),title:this.displayTitle}}forEachHelloed(e){for(const t of this.clients)t.helloed&&e(t)}dispose(){for(const e of this.clients)try{e.socket.destroy()}catch{}this.clients.clear()}clearAttachState(){try{c(this.attachPath)&&y(this.attachPath)}catch{}}}export{A as BrokerClientRegistry};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var p=(s,d)=>E(s,"name",{value:d,configurable:!0});import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as S}from"../../../shared/generated-context.js";import{emitEvent as g}from"../../events/emit.js";import{normalizeSnapshotTail as b}from"../broker-protocol.js";function O(s){const{registry:d,replies:f,session:c,driveEngine:h,turnAcceptance:l,pendingDialogs:T,sendWelcome:m,replayExtraPendingDialogsTo:y,disposeAndExit:A}=s,{notWritable:a,ackTo:u}=f;return{hello(e,r){const t=!e.helloed;e.id=r.client_id,e.snapshotTail=b(r.snapshot_tail),t&&(e.helloed=!0,e.role=r.role==="controller"?"controller":"observer",e.attends=r.attends!==!1),m(e),t&&d.persistAttachState(),e.role==="controller"&&y(e)},deliver(e,r){if(a(e,"drive the engine",r.id))return;const t=c().isStreaming?"steer":"prompt";for(const i of r.cards??[])c().sendCustomMessage({customType:S,content:i,display:!0},t==="steer"?{deliverAs:"steer"}:void 0).catch(_=>g({level:"error",event:"broker.deliver.card_failed",error:_}));let n=!1;const o=p(()=>{n||(n=!0,u(e,"deliver",!0,t,r.id))},"ackAccepted");t==="prompt"&&l.waitFor(o);const v=h(e,{type:"prompt",text:r.text,...r.images!==void 0?{images:r.images}:{},delivery:{...r.origin===void 0?{}:{origin:r.origin}}});if(t==="steer"||v===void 0){l.cancel(o),o();return}v.then(i=>{if(l.cancel(o),i===void 0){o();return}g({level:"error",event:"broker.prompt.deliver_failed",error:i}),!n&&(n=!0,u(e,"deliver",!1,String(i),r.id))})},dialog(e,r){a(e,"answer dialogs")||T.get(r.id)?.resolve(r)},bye(e){e.socket.end()},shutdown(e){a(e,"shut the node down")||A("shutdown-frame")}}}p(O,"createClientHandlers");export{O as createClientHandlers};
1
+ var b=Object.defineProperty;var c=(d,s)=>b(d,"name",{value:s,configurable:!0});import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as k}from"../../../shared/generated-context.js";import{emitEvent as p}from"../../events/emit.js";import{normalizeSnapshotTail as w}from"../broker-protocol.js";function O(d){const{registry:s,replies:f,session:u,driveEngine:h,turnAcceptance:l,pendingDialogs:T,sendWelcome:_,replayExtraPendingDialogsTo:m,disposeAndExit:y}=d,{notWritable:a,ackTo:v}=f;return{hello(e,r){const t=!e.helloed;e.id=r.client_id,e.snapshotTail=w(r.snapshot_tail),t&&(e.helloed=!0,e.role=r.role==="controller"?"controller":"observer",e.attends=r.attends!==!1),t&&p({level:"info",event:"broker.view.hello_decoded",fields:{client:r.client_id,role:e.role}}),_(e),t&&s.persistAttachState(),e.role==="controller"&&m(e)},deliver(e,r){if(a(e,"drive the engine",r.id))return;const t=u().isStreaming?"steer":"prompt";for(const i of r.cards??[])u().sendCustomMessage({customType:k,content:i,display:!0},t==="steer"?{deliverAs:"steer"}:void 0).catch(A=>p({level:"error",event:"broker.deliver.card_failed",error:A}));let n=!1;const o=c(()=>{n||(n=!0,v(e,"deliver",!0,t,r.id))},"ackAccepted");t==="prompt"&&l.waitFor(o);const g=h(e,{type:"prompt",text:r.text,...r.images!==void 0?{images:r.images}:{},delivery:{...r.origin===void 0?{}:{origin:r.origin}}});if(t==="steer"||g===void 0){l.cancel(o),o();return}g.then(i=>{if(l.cancel(o),i===void 0){o();return}p({level:"error",event:"broker.prompt.deliver_failed",error:i}),!n&&(n=!0,v(e,"deliver",!1,String(i),r.id))})},dialog(e,r){a(e,"answer dialogs")||T.get(r.id)?.resolve(r)},bye(e){e.socket.end()},shutdown(e){a(e,"shut the node down")||y("shutdown-frame")}}}c(O,"createClientHandlers");export{O as createClientHandlers};
@@ -1,8 +1,8 @@
1
- var re=Object.defineProperty;var i=(r,e)=>re(r,"name",{value:e,configurable:!0});import{WebSocketServer as te}from"ws";import{general as ne}from"../../core/errors.js";import{toErrorBody as ie}from"./map.js";import{isSafeNodeId as D,viewSocketPath as oe}from"../../core/canvas/paths.js";import{getNode as U}from"../../core/canvas/index.js";import{requestPersonId as ae,runAsPerson as ce}from"../../core/canvas/person-state.js";import{BROKER_READ_CAPS as se,CLIENT_READ_CAPS as fe,FrameDecoder as le,FrameOverflowError as ue}from"../../core/runtime/broker-protocol.js";import{emitEvent as A}from"../../core/events/emit.js";import{addStepTiming as de}from"../../core/step-timings.js";import{markAt as me,timedSpan as T,withLoggedStepTimings as he}from"../../core/logged-step-timings.js";import{classify as O}from"../../core/fault-classifier.js";import{clearFault as E,markNodeRead as pe,recordFault as V}from"../../core/canvas/recovery.js";import{decideAttachRevive as we}from"../../core/runtime/revive.js";import{connectViewSocket as ye,connectWssView as ke,probeViewSocket as ve,waitForBrokerViewSocket as ge,waitForWssView as L}from"../../core/runtime/view-socket.js";import{liveExecutionForNode as _e,recordExecutionAwake as be}from"../../core/canvas/executions.js";import{settleSandboxBeforeWake as Ae}from"../reconcilers/ledger-sandbox.js";import{runnerForExecution as Ee}from"../../core/runtime/runner/index.js";import{isBeneathRefusal as Se}from"../../core/spaces/open-beneath.js";import{openMachineView as xe,waitForMachineView as H}from"../machine-link/forward.js";import{attachViewer as J,detachViewer as Re,holdViewerForRedial as $e,presentViewer as Be}from"./viewer-presence.js";const j=3e4,Ce=new te({noServer:!0,maxPayload:se.maxLineBytes}),Te=25e3,Oe=6e4;function Ve(r,e=Te,a=Oe){let n=!0,c=!1,m=Date.now();const h=i(()=>{n=!0},"acknowledge"),u=i(()=>{c||(c=!0,clearInterval(v),r.off("pong",h))},"stop");r.on("pong",h);const v=setInterval(()=>{if(Date.now()-m>a){n=!0;return}if(!n){u(),r.terminate();return}n=!1;try{r.ping()}catch{u(),r.terminate()}},e);return v.unref(),{stop:u,noteActivity:i(()=>{m=Date.now()},"noteActivity")}}i(Ve,"startRemoteAttachHeartbeat");function N(r){const e=Buffer.from(r,"utf8");return e.byteLength<=123?r:e.subarray(0,123).toString("utf8")}i(N,"clampReason");function k(r,e,a,n,c){de("refused_status",e);const m=JSON.stringify({error:{code:n,message:c,origin:"runtime"}}),h=`HTTP/1.1 ${e} ${a}\r
1
+ var se=Object.defineProperty;var a=(r,e)=>se(r,"name",{value:e,configurable:!0});import{WebSocketServer as le}from"ws";import{general as fe}from"../../core/errors.js";import{toErrorBody as ue}from"./map.js";import{isSafeNodeId as K,viewSocketPath as de}from"../../core/canvas/paths.js";import{getNode as Q}from"../../core/canvas/index.js";import{requestPersonId as me,runAsPerson as he}from"../../core/canvas/person-state.js";import{BROKER_READ_CAPS as we,CLIENT_READ_CAPS as pe,FrameDecoder as ye,FrameOverflowError as _e}from"../../core/runtime/broker-protocol.js";import{emitEvent as M}from"../../core/events/emit.js";import{addStepTiming as ke}from"../../core/step-timings.js";import{markAt as ve,timedSpan as F,withLoggedStepTimings as ge}from"../../core/logged-step-timings.js";import{classify as W}from"../../core/fault-classifier.js";import{clearFault as R,markNodeRead as be,recordFault as D}from"../../core/canvas/recovery.js";import{decideAttachRevive as Ae}from"../../core/runtime/revive.js";import{connectViewSocket as Se,connectWssView as Ee,probeViewSocket as xe,waitForBrokerViewSocket as Me,waitForWssView as G}from"../../core/runtime/view-socket.js";import{liveExecutionForNode as Re,recordExecutionAwake as $e}from"../../core/canvas/executions.js";import{settleSandboxBeforeWake as Be}from"../reconcilers/ledger-sandbox.js";import{runnerForExecution as Ce}from"../../core/runtime/runner/index.js";import{isBeneathRefusal as Te}from"../../core/spaces/open-beneath.js";import{openMachineView as Oe,waitForMachineView as X}from"../machine-link/forward.js";import{attachViewer as Y,detachViewer as Ve,holdViewerForRedial as Ne,presentViewer as Pe}from"./viewer-presence.js";const Z=3e4,Fe=new le({noServer:!0,maxPayload:we.maxLineBytes}),We=25e3,De=6e4;function Ue(r,e=We,i=De){let n=!0,c=!1,m=Date.now();const p=a(()=>{n=!0},"acknowledge"),u=a(()=>{c||(c=!0,clearInterval(b),r.off("pong",p))},"stop");r.on("pong",p);const b=setInterval(()=>{if(Date.now()-m>i){n=!0;return}if(!n){u(),r.terminate();return}n=!1;try{r.ping()}catch{u(),r.terminate()}},e);return b.unref(),{stop:u,noteActivity:a(()=>{m=Date.now()},"noteActivity")}}a(Ue,"startRemoteAttachHeartbeat");function U(r){const e=Buffer.from(r,"utf8");return e.byteLength<=123?r:e.subarray(0,123).toString("utf8")}a(U,"clampReason");function g(r,e,i,n,c){ke("refused_status",e);const m=JSON.stringify({error:{code:n,message:c,origin:"runtime"}}),p=`HTTP/1.1 ${e} ${i}\r
2
2
  content-type: application/json; charset=utf-8\r
3
3
  content-length: ${Buffer.byteLength(m)}\r
4
4
  connection: close\r
5
5
  \r
6
- `+m;try{r.end(h)}catch{try{r.destroy()}catch{}}}i(k,"refuseUpgrade");function q(r,e){const{status:a,body:n}=ie(e);k(r,a,"Refused",n.error.code,n.error.message)}i(q,"refuseWithError");function Ne(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const a=r.headers["x-crtr-attach-revive"];return(Array.isArray(a)?a[0]:a)==="0"}i(Ne,"reviveOptedOut");function Pe(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Pe,"wakeParkedRequested");function K(r){return r===1e3||r===1001||r===1005}i(K,"isCleanViewerClose");function w(r,e,a){a.catch(n=>A({level:"error",event:e,node_id:r,error:n}))}i(w,"detach");async function Q(r){const e=await _e(r);return e===null||e.runner==="process"?{kind:"unix",path:oe(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Ae(e.executionId,Date.now()),await be(e.executionId)),Ee(e.runner).viewerAddress(e))}i(Q,"brokerViewAddress");function Fe(r,e){return e.kind==="machine"?xe(e.environmentId,r):e.kind==="wss"?ke(e.url,e.headers):ye(r)}i(Fe,"connectBrokerView");function Me(r,e,a){return e.kind==="wss"?L(e.url,e.headers,void 0,a):ve(r,a)}i(Me,"probeBrokerView");async function We(r,e,a,n,c){const m=[];let h=i(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>h(t)),!D(e)){c?.destroy();try{r.close(1008,N(`invalid node id: ${e}`))}catch{}return}if(await U(e)===null){c?.destroy();try{r.close(1011,N(`no node ${e}`))}catch{}return}const u=performance.now();await E(e,{link:"viewer\u2194crtrd"});const v=performance.now(),o=c??Fe(e,a),f=i(()=>Math.round((performance.now()-v)*10)/10,"sinceOpen"),g=i(t=>{A({level:"info",event:"daemon.timing.bridge_channel",node_id:e,fields:{step:t,address_kind:a.kind,since_open_ms:f(),since_bridge_start_ms:Math.round((performance.now()-u)*10)/10}})},"bridgeMark");c===void 0&&g("channel_opened");const _=new le(fe);let y=!1,S=!1,x,P=!1,F=!1,$="controller",M=Promise.resolve(),R=!1;const B=[];let C=!1;const W=i(()=>{c===void 0&&g("channel_connected"),P=!0,!y&&R&&w(e,"daemon.bridge.presence_failed",J(e,r)),w(e,"daemon.bridge.connect_failed",E(e,{link:"relay\u2194broker"}))},"onBrokerConnect");c===void 0&&o.on("connect",W);const p=i((t,l,s=!1)=>{if(!y){if(y=!0,w(e,"daemon.bridge.presence_failed",s?$e(e,r):Re(e,r)),x?.stop(),!o.destroyed)try{o.destroy()}catch{}try{r.close(t,N(l))}catch{}}},"teardown");x=Ve(r);const z=i(async t=>{x?.noteActivity();let l;try{l=_.push(t)}catch(s){const d=s instanceof ue?`broker sent an oversized frame (${s.message})`:`failed to decode a broker frame for ${e}`;p(1009,d);return}B.push(...l),C||await G()},"onData"),G=i(async()=>{C=!0;try{for(;B.length>0&&!y;){const t=B.splice(0);let l;try{l=await n($)}catch(d){A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:d}),p(1011,"revoked");return}if(y)return;if(!l){p(1008,"revoked");return}let s=!1;for(const d of t)r.readyState===r.OPEN&&(r.send(JSON.stringify(d)),d?.type==="welcome"&&(s=!0,g("welcome_forwarded")));if(R&&s)try{await Be(e,r)&&await pe(e)}catch(d){A({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:d})}}}finally{C=!1}},"drainOutbound");o.on("data",t=>w(e,"daemon.bridge.data_failed",z(t)));const X=i(async t=>{const l=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const s=O("relay\u2194broker",t);await V(e,{link:"relay\u2194broker",op:"bridge socket",kind:s.kind,retry:{disposition:"manual"},message:t.message})}finally{p(1011,l,!0)}},"onSocketError");o.on("error",t=>w(e,"daemon.bridge.socket_error_failed",X(t)));const Y=i(async t=>{if(!(y||t))try{await E(e,{link:"relay\u2194broker"})}finally{p(1e3,"broker socket closed",!0)}},"onSocketClose");o.on("close",t=>w(e,"daemon.bridge.socket_close_failed",Y(t)));const Z=i(async(t,l)=>{const s=l.toString("utf8");if(y){K(t)&&await E(e,{link:"viewer\u2194crtrd"});return}try{if(K(t))await E(e,{link:"viewer\u2194crtrd"});else if(!S){S=!0;const d=O("viewer\u2194crtrd",{code:t,reason:s});await V(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:d.kind,retry:{disposition:"auto"},message:s||`remote attach closed (${t})`})}}finally{p(t,s||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,l)=>w(e,"daemon.bridge.ws_close_failed",Z(t,l)));const I=i(async()=>{try{if(!S){S=!0;const t=O("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await V(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{p(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>w(e,"daemon.bridge.ws_error_failed",I())),h=i(t=>{if(y||o.destroyed)return;x?.noteActivity();const s=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!F)try{const b=JSON.parse(s);b?.type==="hello"&&(g("hello_received"),F=!0,$=b.role==="observer"?"observer":"controller",R=b.attends!==!1,R&&P&&w(e,"daemon.bridge.presence_failed",J(e,r)))}catch{}const d=s.endsWith(`
7
- `)?s:s+`
8
- `,ee=i(()=>{try{o.write(d)}catch{}},"write");M=M.then(async()=>{y||(await n($)?ee():p(1008,"revoked"))}).catch(b=>{A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:b}),p(1011,"revoked")})},"relayMessage");for(const t of m.splice(0))h(t);c!==void 0&&(c.destroyed?p(1011,`no running broker for ${e}`,!0):W())}i(We,"bridgeConnection");async function cr(r,e,a,n,c){await he("attach_upgrade",{node:n},r,()=>De(r,e,a,n,c))}i(cr,"handleAttachUpgrade");async function De(r,e,a,n,c){const m=ae(),h=m===void 0?c:o=>ce(m,()=>c(o));e.on("error",()=>{});let u,v=!1;try{if(!D(n)){k(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await T("admission",async()=>await U(n)===null)){k(e,404,"Not Found","node_not_found",`no node ${n}`);return}let o;if(Ne(r)){o=await Q(n);let f;if(o.kind==="machine"?(u=await H(o.environmentId,n,void 0,250)??void 0,f=u!==void 0):f=await Me(n,o,o.kind==="wss"?j:250),!f){k(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let f;try{const _=await T("revive_decision",async()=>await we(n,{resume:!0,capacity:"refuse"},Pe(r)));if(_.parked){k(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}f=_.result.launch?.exited}catch(_){q(e,_);return}if(o=await T("address_lookup",async()=>await Q(n)),o.kind==="machine"&&(u=await H(o.environmentId,n,f,j)??void 0),!(o.kind==="machine"?u!==void 0:o.kind==="wss"?await L(o.url,o.headers,f):await ge(n,f))){o.kind==="machine"?q(e,ne(`the broker for ${n} on its machine did not accept a viewer after revive`)):k(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;me("upgrading"),Ce.handleUpgrade(r,e,a,f=>{v=!0,w(n,"daemon.bridge.connection_failed",We(f,n,o,h,u).catch(g=>{throw u?.destroy(),g}))})}catch(o){const f=o instanceof Error?o.message:String(o);if(Se(o)){k(e,400,"Bad Request","invalid_request",f);return}k(e,500,"Internal Server Error","internal",`attach upgrade failed: ${f}`)}finally{v||u?.destroy()}}i(De,"attachUpgrade");export{Te as REMOTE_ATTACH_HEARTBEAT_MS,Oe as REMOTE_ATTACH_QUIET_MS,cr as handleAttachUpgrade,K as isCleanViewerClose,k as refuseUpgrade,Ve as startRemoteAttachHeartbeat};
6
+ `+m;try{r.end(p)}catch{try{r.destroy()}catch{}}}a(g,"refuseUpgrade");function I(r,e){const{status:i,body:n}=ue(e);g(r,i,"Refused",n.error.code,n.error.message)}a(I,"refuseWithError");function He(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const i=r.headers["x-crtr-attach-revive"];return(Array.isArray(i)?i[0]:i)==="0"}a(He,"reviveOptedOut");function Le(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}a(Le,"wakeParkedRequested");function ee(r){return r===1e3||r===1001||r===1005}a(ee,"isCleanViewerClose");function _(r,e,i){i.catch(n=>M({level:"error",event:e,node_id:r,error:n}))}a(_,"detach");async function re(r){const e=await Re(r);return e===null||e.runner==="process"?{kind:"unix",path:de(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Be(e.executionId,Date.now()),await $e(e.executionId)),Ce(e.runner).viewerAddress(e))}a(re,"brokerViewAddress");function ze(r,e){return e.kind==="machine"?Oe(e.environmentId,r):e.kind==="wss"?Ee(e.url,e.headers):Se(r)}a(ze,"connectBrokerView");function Je(r,e,i){return e.kind==="wss"?G(e.url,e.headers,void 0,i):xe(r,i)}a(Je,"probeBrokerView");async function je(r,e,i,n,c){const m=[];let p=a(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>p(t)),!K(e)){c?.destroy();try{r.close(1008,U(`invalid node id: ${e}`))}catch{}return}if(await Q(e)===null){c?.destroy();try{r.close(1011,U(`no node ${e}`))}catch{}return}const u=performance.now();await R(e,{link:"viewer\u2194crtrd"});const b=performance.now(),o=c??ze(e,i),f=a(()=>Math.round((performance.now()-b)*10)/10,"sinceOpen"),h=a((t,s={})=>{M({level:"info",event:"daemon.timing.bridge_channel",node_id:e,fields:{step:t,address_kind:i.kind,channel:o.channel??"",since_open_ms:f(),since_bridge_start_ms:Math.round((performance.now()-u)*10)/10,...s}})},"bridgeMark");c===void 0&&h("channel_opened");const A=new ye(pe);let k=!1,$=!1,B,H=!1,L=!1,S,z=!1,T="controller",J=Promise.resolve(),C=!1;const O=[];let V=!1,N=!1,j=!1,x=0;const q=a(()=>{c===void 0&&h("channel_connected"),H=!0,!k&&C&&_(e,"daemon.bridge.presence_failed",Y(e,r)),_(e,"daemon.bridge.connect_failed",R(e,{link:"relay\u2194broker"}))},"onBrokerConnect");c===void 0&&o.on("connect",q);const y=a((t,s,l=!1)=>{if(!k){if(k=!0,_(e,"daemon.bridge.presence_failed",l?Ne(e,r):Ve(e,r)),B?.stop(),!o.destroyed)try{o.destroy()}catch{}try{r.close(t,U(s))}catch{}}},"teardown");B=Ue(r);const te=a(async t=>{B?.noteActivity();let s;const l=performance.now();try{s=A.push(t)}catch(w){const E=w instanceof _e?`broker sent an oversized frame (${w.message})`:`failed to decode a broker frame for ${e}`;y(1009,E);return}!N&&s.some(w=>w?.type==="welcome")&&(N=!0,x=performance.now(),h("welcome_decoded",{decode_ms:Math.round((x-l)*10)/10,chunk_bytes:t.length,since_hello_ms:S===void 0?-1:Math.round((x-S)*10)/10})),O.push(...s),V||await ne()},"onData"),ne=a(async()=>{V=!0;try{for(;O.length>0&&!k;){const t=O.splice(0),s=N&&!j&&t.some(d=>d?.type==="welcome"),l=performance.now();let w;try{w=await n(T),s&&(j=!0,h("welcome_authorized",{auth_ms:Math.round((performance.now()-l)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}catch(d){M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:d}),y(1011,"revoked");return}if(k)return;if(!w){y(1008,"revoked");return}let E=!1;for(const d of t){if(r.readyState!==r.OPEN)continue;const v=d?.type==="welcome",P=performance.now();r.send(JSON.stringify(d)),v&&(E=!0,h("welcome_forwarded",{send_ms:Math.round((performance.now()-P)*10)/10,since_decoded_ms:Math.round((performance.now()-x)*10)/10}))}if(C&&E)try{await Pe(e,r)&&await be(e)}catch(d){M({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:d})}}}finally{V=!1}},"drainOutbound");o.on("data",t=>_(e,"daemon.bridge.data_failed",te(t)));const oe=a(async t=>{const s=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const l=W("relay\u2194broker",t);await D(e,{link:"relay\u2194broker",op:"bridge socket",kind:l.kind,retry:{disposition:"manual"},message:t.message})}finally{y(1011,s,!0)}},"onSocketError");o.on("error",t=>_(e,"daemon.bridge.socket_error_failed",oe(t)));const ae=a(async t=>{if(!(k||t))try{await R(e,{link:"relay\u2194broker"})}finally{y(1e3,"broker socket closed",!0)}},"onSocketClose");o.on("close",t=>_(e,"daemon.bridge.socket_close_failed",ae(t)));const ie=a(async(t,s)=>{const l=s.toString("utf8");if(k){ee(t)&&await R(e,{link:"viewer\u2194crtrd"});return}try{if(ee(t))await R(e,{link:"viewer\u2194crtrd"});else if(!$){$=!0;const w=W("viewer\u2194crtrd",{code:t,reason:l});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:w.kind,retry:{disposition:"auto"},message:l||`remote attach closed (${t})`})}}finally{y(t,l||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,s)=>_(e,"daemon.bridge.ws_close_failed",ie(t,s)));const ce=a(async()=>{try{if(!$){$=!0;const t=W("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await D(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{y(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>_(e,"daemon.bridge.ws_error_failed",ce())),p=a(t=>{if(k||o.destroyed)return;B?.noteActivity();const l=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!L)try{const v=JSON.parse(l);v?.type==="hello"&&(h("hello_received"),S=performance.now(),L=!0,T=v.role==="observer"?"observer":"controller",C=v.attends!==!1,C&&H&&_(e,"daemon.bridge.presence_failed",Y(e,r)))}catch{}const w=l.endsWith(`
7
+ `)?l:l+`
8
+ `,E=a(()=>{try{o.write(w)}catch{}},"write"),d=S===void 0?!1:z===!1;d&&(z=!0),J=J.then(async()=>{if(k)return;const v=performance.now(),P=await n(T);d&&h("hello_authorized",{auth_ms:Math.round((performance.now()-v)*10)/10,since_hello_ms:Math.round((performance.now()-S)*10)/10}),P?(E(),d&&h("hello_written",{since_hello_ms:Math.round((performance.now()-S)*10)/10})):y(1008,"revoked")}).catch(v=>{M({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:v}),y(1011,"revoked")})},"relayMessage");for(const t of m.splice(0))p(t);c!==void 0&&(c.destroyed?y(1011,`no running broker for ${e}`,!0):q())}a(je,"bridgeConnection");async function hr(r,e,i,n,c){await ge("attach_upgrade",{node:n},r,()=>qe(r,e,i,n,c))}a(hr,"handleAttachUpgrade");async function qe(r,e,i,n,c){const m=me(),p=m===void 0?c:o=>he(m,()=>c(o));e.on("error",()=>{});let u,b=!1;try{if(!K(n)){g(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await F("admission",async()=>await Q(n)===null)){g(e,404,"Not Found","node_not_found",`no node ${n}`);return}let o;if(He(r)){o=await re(n);let f;if(o.kind==="machine"?(u=await X(o.environmentId,n,void 0,250)??void 0,f=u!==void 0):f=await Je(n,o,o.kind==="wss"?Z:250),!f){g(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let f;try{const A=await F("revive_decision",async()=>await Ae(n,{resume:!0,capacity:"refuse"},Le(r)));if(A.parked){g(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}f=A.result.launch?.exited}catch(A){I(e,A);return}if(o=await F("address_lookup",async()=>await re(n)),o.kind==="machine"&&(u=await X(o.environmentId,n,f,Z)??void 0),!(o.kind==="machine"?u!==void 0:o.kind==="wss"?await G(o.url,o.headers,f):await Me(n,f))){o.kind==="machine"?I(e,fe(`the broker for ${n} on its machine did not accept a viewer after revive`)):g(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;ve("upgrading"),Fe.handleUpgrade(r,e,i,f=>{b=!0,_(n,"daemon.bridge.connection_failed",je(f,n,o,p,u).catch(h=>{throw u?.destroy(),h}))})}catch(o){const f=o instanceof Error?o.message:String(o);if(Te(o)){g(e,400,"Bad Request","invalid_request",f);return}g(e,500,"Internal Server Error","internal",`attach upgrade failed: ${f}`)}finally{b||u?.destroy()}}a(qe,"attachUpgrade");export{We as REMOTE_ATTACH_HEARTBEAT_MS,De as REMOTE_ATTACH_QUIET_MS,hr as handleAttachUpgrade,ee as isCleanViewerClose,g as refuseUpgrade,Ue as startRemoteAttachHeartbeat};
@@ -75,8 +75,12 @@ export interface ViewSource {
75
75
  * conversation (megabytes), and on a slow uplink one shared queue held every other node's frames behind it. A channel's source is
76
76
  * paused while that channel's queue is deep, so a slow link never buffers a pane stream in memory. `drop` discards a channel the
77
77
  * holder closed, so its queued frames are not uploaded. */
78
+ export interface ViewFrameTrace {
79
+ dequeued(): void;
80
+ sent(): void;
81
+ }
78
82
  export declare function createViewQueue(sink: ViewSink): {
79
- push(data: string, source?: ViewSource, channel?: string): void;
83
+ push(data: string, source?: ViewSource, channel?: string, trace?: ViewFrameTrace): void;
80
84
  waiting(): {
81
85
  bytes: number;
82
86
  frames: number;
@@ -1 +1 @@
1
- var q=Object.defineProperty;var o=(r,u)=>q(r,"name",{value:u,configurable:!0});import{randomUUID as V}from"node:crypto";import{WebSocket as b}from"ws";import{APIError as x}from"../../api/errors.js";import{emitEvent as A}from"../../core/events/emit.js";import{RUNTIME_VERSION_HEADER as K}from"../../api/runtime-version.js";import{crtrVersion as D}from"../../shared/crtr-version.js";import{connectViewSocket as F}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as Y,LINK_MAX_PAYLOAD_BYTES as $,parseFrame as X}from"./frames.js";const z=1e3,H=6e4,Q=64*1024,G=4*1024*1024,Z=1024*1024,ee=8*1024*1024,J=15e3,ne=75e3;function te(r){const u=new Map,p=o(()=>{for(;r.open()&&r.bufferedAmount<Q;){let c;for(const h of u)(c===void 0||h[1].bytes<c[1].bytes)&&(c=h);if(c===void 0)return;const[m,f]=c,s=f.frames.shift();f.bytes-=s.length,f.paused!==void 0&&f.bytes<Z&&(f.paused.resume(),f.paused=void 0),f.frames.length===0&&u.delete(m),r.send(s,p)}},"pump");return{push(c,m,f=""){if(!r.open())return;const s=u.get(f)??{frames:[],bytes:0};u.set(f,s),s.frames.push(c),s.bytes+=c.length,m!==void 0&&s.paused===void 0&&s.bytes>G&&(m.pause(),s.paused=m),p()},waiting:o(()=>[...u.values()].reduce((c,m)=>({bytes:c.bytes+m.bytes,frames:c.frames+m.frames.length}),{bytes:0,frames:0}),"waiting"),drop(c){u.delete(c)},forget(c){for(const m of u.values())m.paused===c&&(m.paused=void 0)}}}o(te,"createViewQueue");function re(r,u){const p=new URL(`/v1/machines/${encodeURIComponent(u)}/link`,r);return p.protocol=p.protocol==="https:"?"wss:":p.protocol==="http:"?"ws:":p.protocol,p.toString()}o(re,"linkUrl");function me(r){const u=r.backoffMinMs??z,p=r.backoffMaxMs??H,c=r.openView??F,m=r.silenceMs??ne;let f=!1,s,h=u,T;const E=new Map,N=new Map,U=200,S=[],L=o(()=>{const d=s;for(;S.length>0&&d?.readyState===b.OPEN;)d.send(JSON.stringify({type:"exit",...S.shift()}))},"flushExits"),O=o((d,t)=>{A({level:"error",event:d,fields:{environment:r.environmentId},error:t})},"fault");let k;const P=o(()=>{if(f)return;if(k!==void 0){if(r.credential()===k){T=setTimeout(P,h),h=Math.min(h*2,p);return}k=void 0}const d=r.credential(),t=new b(re(r.apiUrl,r.environmentId),{headers:{authorization:`Bearer ${d}`,[K]:D()},maxPayload:$});s=t;const a=new Map,_=new Map,y=o(n=>{t.readyState===b.OPEN&&t.send(JSON.stringify(n))},"send"),w=te({get bufferedAmount(){return t.bufferedAmount},open:o(()=>t.readyState===b.OPEN,"open"),send:o((n,e)=>t.send(n,e),"send")}),g=o((n,e)=>w.push(JSON.stringify(n),e,n.channel),"sendView"),I=o(n=>Math.round(n*10)/10,"round"),R=o(async n=>{const e=r.handlers[n.op];if(e===void 0){y({type:"result",call_id:n.call_id,ok:!1,error:`this machine does not execute ${n.op}`});return}const i=new AbortController,l=o(()=>i.abort(new Error("the machine link closed")),"onClose");t.once("close",l);try{y({type:"result",call_id:n.call_id,ok:!0,value:await e(n.args,i.signal)??null})}catch(v){y({type:"result",call_id:n.call_id,ok:!1,error:v instanceof Error?v.message:String(v)})}finally{t.off("close",l)}},"runCall"),B=o(n=>{const e=c(n.node);a.set(n.channel,e);const i=performance.now();e.once("connect",()=>{const l=performance.now(),v=w.waiting(),W=t.bufferedAmount;y({type:"view.ready",channel:n.channel}),A({level:"info",event:"daemon.timing.view_ready_sent",fields:{channel:n.channel,node:n.node,open_to_connect_ms:I(l-i),queued_bytes:v.bytes,queued_frames:v.frames,link_buffered_bytes_before:W,link_buffered_bytes_after:t.bufferedAmount}})}),e.on("data",l=>g({type:"view.data",channel:n.channel,bytes:l.toString("base64")},e)),e.once("error",l=>{w.forget(e),a.delete(n.channel)&&g({type:"view.close",channel:n.channel,error:l.message})}),e.once("close",()=>{w.forget(e),a.delete(n.channel)&&g({type:"view.close",channel:n.channel})})},"openChannel"),j=o((n,e)=>{const i=a.get(n);if(i===void 0||i.write(e))return;const l=(_.get(n)??0)+e.length;if(l>ee){a.delete(n),_.delete(n),i.destroy(),g({type:"view.close",channel:n,error:"the broker is not draining the viewer channel"});return}_.has(n)||i.once("drain",()=>_.delete(n)),_.set(n,l)},"writeToChannel");let M;const C=o(()=>{M!==void 0&&clearTimeout(M),M=setTimeout(()=>{A({level:"warn",event:"daemon.machine_link.silent",fields:{environment:r.environmentId}}),t.terminate()},m)},"heard");t.on("open",()=>{h=u,C(),L(),r.onOpen?.()}),t.on("ping",C),t.on("message",n=>{C();const e=X(n);if(e!==null)try{switch(e.type){case"call":R(e);return;case"job.reported":{const i=E.get(e.id);E.delete(e.id),e.error===void 0?i?.resolve():i?.reject(new x(e.error.status,e.error.code,e.error.message));return}case"turns.answer":N.get(e.id)?.(e.turns);return;case"view.open":B(e);return;case"view.data":j(e.channel,Buffer.from(e.bytes,"base64"));return;case"view.close":{const i=a.get(e.channel);a.delete(e.channel),i?.destroy(),w.drop(e.channel);return}default:return}}catch(i){O("daemon.machine_link.frame_failed",i)}}),t.on("unexpected-response",(n,e)=>{let i="";e.on("data",l=>{i+=l.toString("utf8")}).on("close",()=>{t.terminate(),O("daemon.machine_link.refused",new Error(`${e.statusCode??"no status"} ${i}`));try{e.statusCode===426&&r.onBehind?.(JSON.parse(i).error.message)}catch(l){O("daemon.machine_link.client_error",l)}})}),t.on("error",n=>O("daemon.machine_link.client_error",n)),t.on("close",n=>{M!==void 0&&clearTimeout(M);for(const e of a.values())e.destroy();a.clear(),s===t&&(s=void 0);for(const e of N.values())e(void 0);for(const[e,i]of E)E.delete(e),i.reject(new x(503,"machine_offline","the machine link closed before the job report was answered"));f||(n===Y&&(A({level:"error",event:"daemon.machine_link.revoked",fields:{environment:r.environmentId}}),k=d),T=setTimeout(P,h),h=Math.min(h*2,p))})},"connect");return P(),{stop(){f=!0,T!==void 0&&clearTimeout(T),s?.close()},connected:o(()=>s?.readyState===b.OPEN,"connected"),reportJob(d,t,a){const _=s;if(_?.readyState!==b.OPEN)return Promise.reject(new x(503,"machine_offline","the machine link is not open"));const y=V();return new Promise((w,g)=>{const I=setTimeout(()=>{E.delete(y),g(new x(504,"request_timeout","the control plane did not answer the job report"))},r.jobReportTimeoutMs??J);E.set(y,{resolve:o(()=>{clearTimeout(I),w()},"resolve"),reject:o(R=>{clearTimeout(I),g(R)},"reject")}),_.send(JSON.stringify({type:"job.report",id:y,node:d,job:t,request:a}))})},turns(d){const t=s;if(t?.readyState!==b.OPEN)return Promise.resolve(void 0);const a=V();return new Promise(_=>{const y=setTimeout(()=>w(void 0),r.jobReportTimeoutMs??J),w=o(g=>{clearTimeout(y),N.delete(a),_(g)},"answer");N.set(a,w),t.send(JSON.stringify({type:"turns",id:a,brokers:d}))})},reportWedge(d){s?.readyState===b.OPEN&&s.send(JSON.stringify({type:"wedge",...d}))},reportRunning(d){s?.readyState===b.OPEN&&s.send(JSON.stringify({type:"running",executions:d}))},reportExit(d){S.push(d),S.length>U&&S.shift(),L()}}}o(me,"startMachineLink");export{J as JOB_REPORT_TIMEOUT_MS,H as LINK_BACKOFF_MAX_MS,z as LINK_BACKOFF_MIN_MS,ne as LINK_SILENCE_MS,ee as VIEW_WRITE_LIMIT_BYTES,te as createViewQueue,re as linkUrl,me as startMachineLink};
1
+ var X=Object.defineProperty;var o=(s,f)=>X(s,"name",{value:f,configurable:!0});import{randomUUID as K}from"node:crypto";import{WebSocket as g}from"ws";import{APIError as C}from"../../api/errors.js";import{emitEvent as q}from"../../core/events/emit.js";import{RUNTIME_VERSION_HEADER as z}from"../../api/runtime-version.js";import{crtrVersion as H}from"../../shared/crtr-version.js";import{connectViewSocket as Q}from"../../core/runtime/view-socket.js";import{CLOSE_REVOKED as G,LINK_MAX_PAYLOAD_BYTES as Z,parseFrame as ee}from"./frames.js";const ne=1e3,te=6e4,re=64*1024,oe=4*1024*1024,se=1024*1024,ie=8*1024*1024,D=15e3,de=75e3;function ce(s){const f=new Map,w=o(()=>{for(;s.open()&&s.bufferedAmount<re;){let a;for(const S of f)(a===void 0||S[1].bytes<a[1].bytes)&&(a=S);if(a===void 0)return;const[_,m]=a,{data:i,trace:d}=m.frames.shift();m.bytes-=i.length,m.paused!==void 0&&m.bytes<se&&(m.paused.resume(),m.paused=void 0),m.frames.length===0&&f.delete(_),d?.dequeued(),s.send(i,d===void 0?w:()=>{d.sent(),w()})}},"pump");return{push(a,_,m="",i){if(!s.open())return;const d=f.get(m)??{frames:[],bytes:0};f.set(m,d),d.frames.push({data:a,...i===void 0?{}:{trace:i}}),d.bytes+=a.length,_!==void 0&&d.paused===void 0&&d.bytes>oe&&(_.pause(),d.paused=_),w()},waiting:o(()=>[...f.values()].reduce((a,_)=>({bytes:a.bytes+_.bytes,frames:a.frames+_.frames.length}),{bytes:0,frames:0}),"waiting"),drop(a){f.delete(a)},forget(a){for(const _ of f.values())_.paused===a&&(_.paused=void 0)}}}o(ce,"createViewQueue");function ae(s,f){const w=new URL(`/v1/machines/${encodeURIComponent(f)}/link`,s);return w.protocol=w.protocol==="https:"?"wss:":w.protocol==="http:"?"ws:":w.protocol,w.toString()}o(ae,"linkUrl");function be(s){const f=s.backoffMinMs??ne,w=s.backoffMaxMs??te,a=s.openView??Q,_=s.silenceMs??de;let m=!1,i,d=f,S;const N=new Map,A=new Map,$=200,O=[],U=o(()=>{const l=i;for(;O.length>0&&l?.readyState===g.OPEN;)l.send(JSON.stringify({type:"exit",...O.shift()}))},"flushExits"),x=o((l,t)=>{q({level:"error",event:l,fields:{environment:s.environmentId},error:t})},"fault");let P;const J=o(()=>{if(m)return;if(P!==void 0){if(s.credential()===P){S=setTimeout(J,d),d=Math.min(d*2,w);return}P=void 0}const l=s.credential(),t=new g(ae(s.apiUrl,s.environmentId),{headers:{authorization:`Bearer ${l}`,[z]:H()},maxPayload:Z});i=t;const u=new Map,y=new Map,v=o(e=>{t.readyState===g.OPEN&&t.send(JSON.stringify(e))},"send"),h=ce({get bufferedAmount(){return t.bufferedAmount},open:o(()=>t.readyState===g.OPEN,"open"),send:o((e,n)=>t.send(e,n),"send")}),E=o((e,n,r)=>h.push(JSON.stringify(e),n,e.channel,r),"sendView"),b=o(e=>Math.round(e*10)/10,"round"),L=o(async e=>{const n=s.handlers[e.op];if(n===void 0){v({type:"result",call_id:e.call_id,ok:!1,error:`this machine does not execute ${e.op}`});return}const r=new AbortController,c=o(()=>r.abort(new Error("the machine link closed")),"onClose");t.once("close",c);try{v({type:"result",call_id:e.call_id,ok:!0,value:await n(e.args,r.signal)??null})}catch(k){v({type:"result",call_id:e.call_id,ok:!1,error:k instanceof Error?k.message:String(k)})}finally{t.off("close",c)}},"runCall"),F=o(e=>{const n=performance.now(),r=o((p,M={})=>{q({level:"info",event:`daemon.timing.${p}`,node_id:e.node,fields:{channel:e.channel,...M}})},"mark");r("view_open_received",{link_buffered_bytes:t.bufferedAmount});const c=a(e.node);u.set(e.channel,c);const k=performance.now();r("view_open_started",{open_sync_ms:b(k-n)});let R;c.once("connect",()=>{const p=performance.now();R=p;const M=h.waiting(),I=t.bufferedAmount;t.readyState===g.OPEN&&t.send(JSON.stringify({type:"view.ready",channel:e.channel}),()=>r("view_ready_flushed",{send_ms:b(performance.now()-p),link_buffered_bytes:t.bufferedAmount})),r("view_ready_sent",{open_to_connect_ms:b(p-k),queued_bytes:M.bytes,queued_frames:M.frames,link_buffered_bytes_before:I,link_buffered_bytes_after:t.bufferedAmount})});let B=0,j=0,W=!1;c.on("data",p=>{let M;if(!W){const I=performance.now();B+=1,j+=p.length,B===1&&r("view_output_first_received",{bytes:p.length,since_ready_ms:R===void 0?null:b(I-R)}),p.includes(10)&&(W=!0,r("view_welcome_received",{chunks:B,bytes:j,queued_bytes:h.waiting().bytes,link_buffered_bytes:t.bufferedAmount}),M={dequeued:o(()=>r("view_welcome_dequeued",{queue_ms:b(performance.now()-I),link_buffered_bytes:t.bufferedAmount}),"dequeued"),sent:o(()=>r("view_welcome_sent",{since_received_ms:b(performance.now()-I),link_buffered_bytes:t.bufferedAmount}),"sent")})}E({type:"view.data",channel:e.channel,bytes:p.toString("base64")},c,M)}),c.once("error",p=>{R===void 0&&r("view_connect_failed",{open_to_error_ms:b(performance.now()-k),code:p.code??"unknown"}),h.forget(c),u.delete(e.channel)&&E({type:"view.close",channel:e.channel,error:p.message})}),c.once("close",()=>{h.forget(c),u.delete(e.channel)&&E({type:"view.close",channel:e.channel})})},"openChannel"),Y=o((e,n)=>{const r=u.get(e);if(r===void 0||r.write(n))return;const c=(y.get(e)??0)+n.length;if(c>ie){u.delete(e),y.delete(e),r.destroy(),E({type:"view.close",channel:e,error:"the broker is not draining the viewer channel"});return}y.has(e)||r.once("drain",()=>y.delete(e)),y.set(e,c)},"writeToChannel");let T;const V=o(()=>{T!==void 0&&clearTimeout(T),T=setTimeout(()=>{q({level:"warn",event:"daemon.machine_link.silent",fields:{environment:s.environmentId}}),t.terminate()},_)},"heard");t.on("open",()=>{d=f,V(),U(),s.onOpen?.()}),t.on("ping",V),t.on("message",e=>{V();const n=ee(e);if(n!==null)try{switch(n.type){case"call":L(n);return;case"job.reported":{const r=N.get(n.id);N.delete(n.id),n.error===void 0?r?.resolve():r?.reject(new C(n.error.status,n.error.code,n.error.message));return}case"turns.answer":A.get(n.id)?.(n.turns);return;case"view.open":F(n);return;case"view.data":Y(n.channel,Buffer.from(n.bytes,"base64"));return;case"view.close":{const r=u.get(n.channel);u.delete(n.channel),r?.destroy(),h.drop(n.channel);return}default:return}}catch(r){x("daemon.machine_link.frame_failed",r)}}),t.on("unexpected-response",(e,n)=>{let r="";n.on("data",c=>{r+=c.toString("utf8")}).on("close",()=>{t.terminate(),x("daemon.machine_link.refused",new Error(`${n.statusCode??"no status"} ${r}`));try{n.statusCode===426&&s.onBehind?.(JSON.parse(r).error.message)}catch(c){x("daemon.machine_link.client_error",c)}})}),t.on("error",e=>x("daemon.machine_link.client_error",e)),t.on("close",e=>{T!==void 0&&clearTimeout(T);for(const n of u.values())n.destroy();u.clear(),i===t&&(i=void 0);for(const n of A.values())n(void 0);for(const[n,r]of N)N.delete(n),r.reject(new C(503,"machine_offline","the machine link closed before the job report was answered"));m||(e===G&&(q({level:"error",event:"daemon.machine_link.revoked",fields:{environment:s.environmentId}}),P=l),S=setTimeout(J,d),d=Math.min(d*2,w))})},"connect");return J(),{stop(){m=!0,S!==void 0&&clearTimeout(S),i?.close()},connected:o(()=>i?.readyState===g.OPEN,"connected"),reportJob(l,t,u){const y=i;if(y?.readyState!==g.OPEN)return Promise.reject(new C(503,"machine_offline","the machine link is not open"));const v=K();return new Promise((h,E)=>{const b=setTimeout(()=>{N.delete(v),E(new C(504,"request_timeout","the control plane did not answer the job report"))},s.jobReportTimeoutMs??D);N.set(v,{resolve:o(()=>{clearTimeout(b),h()},"resolve"),reject:o(L=>{clearTimeout(b),E(L)},"reject")}),y.send(JSON.stringify({type:"job.report",id:v,node:l,job:t,request:u}))})},turns(l){const t=i;if(t?.readyState!==g.OPEN)return Promise.resolve(void 0);const u=K();return new Promise(y=>{const v=setTimeout(()=>h(void 0),s.jobReportTimeoutMs??D),h=o(E=>{clearTimeout(v),A.delete(u),y(E)},"answer");A.set(u,h),t.send(JSON.stringify({type:"turns",id:u,brokers:l}))})},reportWedge(l){i?.readyState===g.OPEN&&i.send(JSON.stringify({type:"wedge",...l}))},reportRunning(l){i?.readyState===g.OPEN&&i.send(JSON.stringify({type:"running",executions:l}))},reportExit(l){O.push(l),O.length>$&&O.shift(),U()}}}o(be,"startMachineLink");export{D as JOB_REPORT_TIMEOUT_MS,te as LINK_BACKOFF_MAX_MS,ne as LINK_BACKOFF_MIN_MS,de as LINK_SILENCE_MS,ie as VIEW_WRITE_LIMIT_BYTES,ce as createViewQueue,ae as linkUrl,be as startMachineLink};
@@ -1 +1 @@
1
- var b=Object.defineProperty;var a=(i,e)=>b(i,"name",{value:e,configurable:!0});import{EventEmitter as x}from"node:events";import{createHmac as I,timingSafeEqual as A}from"node:crypto";import{WebSocket as m,WebSocketServer as R}from"ws";import{markAt as P}from"../../core/logged-step-timings.js";import{addStepTiming as k}from"../../core/step-timings.js";import{emitEvent as B}from"../../core/events/emit.js";import{openDb as O}from"../../core/canvas/db.js";import{loadSecretsKey as T}from"../../core/secrets/key.js";import{LINK_MAX_PAYLOAD_BYTES as _,parseFrame as v}from"./frames.js";import{apiAddress as D,heldLinkOf as g,MachineViewLink as E,UNROUTABLE_PREFIX as L}from"./holder.js";const y=8*1024*1024,$=1013,M=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/view$/,q=new R({noServer:!0,maxPayload:_}),S=a(i=>I("sha256",T().key).update(`machine-view:${i}`).digest("hex"),"forwardToken");function N(i,e){const r=g(i);return r!==null?new E(r,e):new U(i,e)}a(N,"openMachineView");class U extends x{static{a(this,"ForwardedViewLink")}environmentId;nodeId;ws;ended=!1;failed=!1;queued=[];queuedBytes=0;constructor(e,r){super(),this.environmentId=e,this.nodeId=r;const s=performance.now();this.once("connect",()=>B({level:"info",event:"daemon.timing.forwarded_view_ready",fields:{environment:this.environmentId,node:this.nodeId,open_to_ready_ms:Math.round((performance.now()-s)*10)/10}})),this.dial().catch(t=>this.finish(t instanceof Error?t.message:String(t)))}get destroyed(){return this.ended}write(e){return this.ended?!1:this.ws?.readyState!==m.OPEN?(this.queuedBytes+=e.length,this.queuedBytes>y?(this.finish("machine view: the holder did not accept the channel before its queue filled"),!1):(this.queued.push(e),!0)):this.ws.bufferedAmount>y?(this.finish("machine view: the holder is not draining the channel"),!1):(this.sendData(e),!0)}destroy(){return this.ended||(this.ws?.readyState===m.OPEN&&this.ws.send(JSON.stringify({type:"view.close",channel:""})),this.finish(void 0)),this}sendData(e){this.ws?.send(JSON.stringify({type:"view.data",channel:"",bytes:Buffer.from(e).toString("base64")}))}async dial(){const e=await(await O()).prepare("SELECT api_address, lease_expires_at FROM machine_links WHERE environment = ?").get(this.environmentId);if(e===void 0||Date.parse(e.lease_expires_at)<=Date.now())throw new Error(`machine_offline: machine ${this.environmentId} has no live link`);if(e.api_address.startsWith(L))throw new Error(`machine_unreachable: the API process holding the link wrote ${e.api_address}; set CRTR_API_ADDRESS or listen on TCP`);if(e.api_address===D())throw new Error(`machine_offline: the link row names this API process (${e.api_address}) but it holds no link`);if(this.ended)return;const r=new URL(`/v1/machines/${encodeURIComponent(this.environmentId)}/view`,e.api_address.includes("://")?e.api_address:`ws://${e.api_address}`);r.protocol=r.protocol==="https:"?"wss:":r.protocol==="http:"?"ws:":r.protocol,r.searchParams.set("node",this.nodeId);const s=new m(r.toString(),{headers:{authorization:`Bearer ${S(this.environmentId)}`},maxPayload:_});this.ws=s,s.on("open",()=>{for(const t of this.queued.splice(0))this.sendData(t)}),s.on("unexpected-response",(t,n)=>{n.resume(),this.finish(n.statusCode===409?"machine_offline: the holder no longer holds the link":`machine view refused by ${e.api_address}: ${n.statusCode}`)}),s.on("message",t=>{const n=v(t);n!==null&&(n.type==="view.ready"?this.emit("connect"):n.type==="view.data"?this.emit("data",Buffer.from(n.bytes,"base64")):n.type==="view.close"&&this.finish(n.error))}),s.on("error",t=>this.finish(t.message)),s.on("close",()=>this.finish("machine view forward closed"))}finish(e){this.ended||(this.ended=!0,this.ws?.close(),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}function C(i,e,r){return new Promise(s=>{const t=N(i,e),n=setTimeout(()=>{s(null),t.destroy()},r);t.on("error",()=>{}),t.on("connect",()=>{clearTimeout(n),s(t)}),t.on("close",()=>{clearTimeout(n),s(null)})})}a(C,"openReadyMachineView");async function G(i,e,r,s){const t=Date.now()+s;let n=!1;r?.then(()=>{n=!0});for(let l=1;Date.now()<=t&&!n;l++){const f=performance.now(),h=await C(i,e,Math.max(1,Math.min(2e3,t-Date.now())));if(k(`probe_${l}_${h!==null?"ready":"failed"}_ms`,performance.now()-f),h!==null)return P("ready_received"),h;await new Promise(u=>setTimeout(u,250))}return null}a(G,"waitForMachineView");function Q(i){const e=M.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Q,"machineViewEnvironment");function ee(i,e,r,s){const t=i.headers.authorization,n=/^Bearer (\S+)$/.exec(Array.isArray(t)?t[0]??"":t??"")?.[1]??"",l=Buffer.from(S(s)),f=Buffer.from(n);if(f.length!==l.length||!A(f,l))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine view forward credential refused"};const h=new URL(i.url??"/","http://runtime.local").searchParams.get("node");if(h===null||h==="")return{status:400,text:"Bad Request",code:"bad_request",message:"node is required"};const u=g(s);return u===null?{status:409,text:"Conflict",code:"machine_offline",message:"this API process holds no link for the machine"}:(q.handleUpgrade(i,e,r,d=>{const o=new E(u,h),p=a(c=>{d.readyState===m.OPEN&&d.send(JSON.stringify(c))},"send");o.on("connect",()=>p({type:"view.ready",channel:""})),o.on("data",c=>{if(d.bufferedAmount>y){o.destroy(),d.close($,"viewer too slow");return}p({type:"view.data",channel:"",bytes:c.toString("base64")})}),o.on("error",c=>p({type:"view.close",channel:"",error:c.message})),o.on("close",()=>d.close()),d.on("message",c=>{const w=v(c);w?.type==="view.data"?o.write(Buffer.from(w.bytes,"base64")):w?.type==="view.close"&&o.destroy()}),d.on("close",()=>o.destroy()),d.on("error",()=>o.destroy())}),null)}a(ee,"handleMachineViewUpgrade");export{y as VIEW_BUFFER_LIMIT_BYTES,ee as handleMachineViewUpgrade,Q as machineViewEnvironment,N as openMachineView,G as waitForMachineView};
1
+ var x=Object.defineProperty;var a=(r,e)=>x(r,"name",{value:e,configurable:!0});import{EventEmitter as A}from"node:events";import{createHmac as I,timingSafeEqual as R}from"node:crypto";import{WebSocket as u,WebSocketServer as P}from"ws";import{markAt as k}from"../../core/logged-step-timings.js";import{addStepTiming as B}from"../../core/step-timings.js";import{emitEvent as _}from"../../core/events/emit.js";import{openDb as O}from"../../core/canvas/db.js";import{loadSecretsKey as T}from"../../core/secrets/key.js";import{LINK_MAX_PAYLOAD_BYTES as v,parseFrame as g}from"./frames.js";import{apiAddress as D,heldLinkOf as E,MachineViewLink as S,UNROUTABLE_PREFIX as L}from"./holder.js";const y=8*1024*1024,$=1013,q=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/view$/,M=new P({noServer:!0,maxPayload:v}),b=a(r=>I("sha256",T().key).update(`machine-view:${r}`).digest("hex"),"forwardToken");function N(r,e){const n=E(r);return n!==null?new S(n,e):new U(r,e)}a(N,"openMachineView");class U extends A{static{a(this,"ForwardedViewLink")}environmentId;nodeId;ws;ended=!1;failed=!1;queued=[];queuedBytes=0;constructor(e,n){super(),this.environmentId=e,this.nodeId=n;const s=performance.now();this.once("connect",()=>_({level:"info",event:"daemon.timing.forwarded_view_ready",node_id:this.nodeId,fields:{environment:this.environmentId,open_to_ready_ms:Math.round((performance.now()-s)*10)/10}})),this.dial().catch(t=>this.finish(t instanceof Error?t.message:String(t)))}get destroyed(){return this.ended}write(e){return this.ended?!1:this.ws?.readyState!==u.OPEN?(this.queuedBytes+=e.length,this.queuedBytes>y?(this.finish("machine view: the holder did not accept the channel before its queue filled"),!1):(this.queued.push(e),!0)):this.ws.bufferedAmount>y?(this.finish("machine view: the holder is not draining the channel"),!1):(this.sendData(e),!0)}destroy(){return this.ended||(this.ws?.readyState===u.OPEN&&this.ws.send(JSON.stringify({type:"view.close",channel:""})),this.finish(void 0)),this}sendData(e){this.ws?.send(JSON.stringify({type:"view.data",channel:"",bytes:Buffer.from(e).toString("base64")}))}async dial(){const e=await(await O()).prepare("SELECT api_address, lease_expires_at FROM machine_links WHERE environment = ?").get(this.environmentId);if(e===void 0||Date.parse(e.lease_expires_at)<=Date.now())throw new Error(`machine_offline: machine ${this.environmentId} has no live link`);if(e.api_address.startsWith(L))throw new Error(`machine_unreachable: the API process holding the link wrote ${e.api_address}; set CRTR_API_ADDRESS or listen on TCP`);if(e.api_address===D())throw new Error(`machine_offline: the link row names this API process (${e.api_address}) but it holds no link`);if(this.ended)return;const n=new URL(`/v1/machines/${encodeURIComponent(this.environmentId)}/view`,e.api_address.includes("://")?e.api_address:`ws://${e.api_address}`);n.protocol=n.protocol==="https:"?"wss:":n.protocol==="http:"?"ws:":n.protocol,n.searchParams.set("node",this.nodeId);const s=new u(n.toString(),{headers:{authorization:`Bearer ${b(this.environmentId)}`},maxPayload:v});this.ws=s,s.on("open",()=>{for(const t of this.queued.splice(0))this.sendData(t)}),s.on("unexpected-response",(t,i)=>{i.resume(),this.finish(i.statusCode===409?"machine_offline: the holder no longer holds the link":`machine view refused by ${e.api_address}: ${i.statusCode}`)}),s.on("message",t=>{const i=g(t);i!==null&&(i.type==="view.ready"?this.emit("connect"):i.type==="view.data"?this.emit("data",Buffer.from(i.bytes,"base64")):i.type==="view.close"&&this.finish(i.error))}),s.on("error",t=>this.finish(t.message)),s.on("close",()=>this.finish("machine view forward closed"))}finish(e){this.ended||(this.ended=!0,this.ws?.close(),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}function C(r,e,n){return new Promise(s=>{const t=N(r,e),i=setTimeout(()=>{_({level:"info",event:"daemon.timing.view_ready_timeout",node_id:e,fields:{channel:t.channel??"",timeout_ms:n}}),s(null),t.destroy()},n);t.on("error",()=>{}),t.on("connect",()=>{clearTimeout(i),s(t)}),t.on("close",()=>{clearTimeout(i),s(null)})})}a(C,"openReadyMachineView");async function G(r,e,n,s){const t=Date.now()+s;let i=!1;n?.then(()=>{i=!0});for(let l=1;Date.now()<=t&&!i;l++){const f=performance.now(),h=await C(r,e,Math.max(1,Math.min(2e3,t-Date.now())));if(B(`probe_${l}_${h!==null?"ready":"failed"}_ms`,performance.now()-f),h!==null)return k("ready_received"),h;await new Promise(m=>setTimeout(m,250))}return null}a(G,"waitForMachineView");function Q(r){const e=q.exec(new URL(r.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Q,"machineViewEnvironment");function ee(r,e,n,s){const t=r.headers.authorization,i=/^Bearer (\S+)$/.exec(Array.isArray(t)?t[0]??"":t??"")?.[1]??"",l=Buffer.from(b(s)),f=Buffer.from(i);if(f.length!==l.length||!R(f,l))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine view forward credential refused"};const h=new URL(r.url??"/","http://runtime.local").searchParams.get("node");if(h===null||h==="")return{status:400,text:"Bad Request",code:"bad_request",message:"node is required"};const m=E(s);return m===null?{status:409,text:"Conflict",code:"machine_offline",message:"this API process holds no link for the machine"}:(M.handleUpgrade(r,e,n,d=>{const o=new S(m,h),p=a(c=>{d.readyState===u.OPEN&&d.send(JSON.stringify(c))},"send");o.on("connect",()=>p({type:"view.ready",channel:""})),o.on("data",c=>{if(d.bufferedAmount>y){o.destroy(),d.close($,"viewer too slow");return}p({type:"view.data",channel:"",bytes:c.toString("base64")})}),o.on("error",c=>p({type:"view.close",channel:"",error:c.message})),o.on("close",()=>d.close()),d.on("message",c=>{const w=g(c);w?.type==="view.data"?o.write(Buffer.from(w.bytes,"base64")):w?.type==="view.close"&&o.destroy()}),d.on("close",()=>o.destroy()),d.on("error",()=>o.destroy())}),null)}a(ee,"handleMachineViewUpgrade");export{y as VIEW_BUFFER_LIMIT_BYTES,ee as handleMachineViewUpgrade,Q as machineViewEnvironment,N as openMachineView,G as waitForMachineView};
@@ -70,10 +70,13 @@ export declare function recordMachineBrokerExit(environmentId: string, exit: {
70
70
  /** A viewer channel to one node's view.sock on the Mac, as the relay's broker-side link. */
71
71
  export declare class MachineViewLink extends EventEmitter implements BrokerViewLink {
72
72
  private readonly link;
73
+ readonly nodeId: string;
73
74
  private ended;
74
75
  private failed;
75
- private readonly channel;
76
+ readonly channel: `${string}-${string}-${string}-${string}-${string}`;
77
+ private readonly opened;
76
78
  constructor(link: HeldLink, nodeId: string);
79
+ sinceOpenMs(): number;
77
80
  get destroyed(): boolean;
78
81
  write(line: string | Buffer): boolean;
79
82
  destroy(): this;
@@ -1,10 +1,10 @@
1
- var b=Object.defineProperty;var s=(i,e)=>b(i,"name",{value:e,configurable:!0});import{importedNodesHeld as x}from"../reconcilers/live-obligation.js";import{EventEmitter as w}from"node:events";import{hostname as I}from"node:os";import{randomUUID as L}from"node:crypto";import{WebSocket as T,WebSocketServer as O}from"ws";import{openDb as o}from"../../core/canvas/db.js";import{emitEvent as u}from"../../core/events/emit.js";import{endExecution as M,liveExecutionForNode as C,recordExecutionExit as U}from"../../core/canvas/executions.js";import{getNode as W}from"../../core/canvas/index.js";import{fullName as H}from"../../core/canvas/labels.js";import{readLiveTurn as P}from"../../core/canvas/recovery.js";import{runningJobs as F}from"../../core/graph/jobs.js";import{readSupervisionMark as j,writeSupervisionMark as $}from"../park-pending.js";import{reportWedge as B,wedgeLabel as J}from"../reconcilers/broker-supervision.js";import{machineEnvironmentOfNode as p}from"../../core/runtime/runner/machine/runner.js";import{storeJobReport as K}from"../api/handlers/bash-jobs.js";import{APIError as E}from"../../api/errors.js";import{brokerSignalBus as V}from"../broker-signals/bus.js";import{verifyMachineCredential as g}from"./credential.js";import{compareReleaseVersions as X,RUNTIME_VERSION_HEADER as G}from"../../api/runtime-version.js";import{crtrVersion as v}from"../../shared/crtr-version.js";import{CLOSE_REVOKED as q,CLOSE_SUPERSEDED as N,LINK_MAX_PAYLOAD_BYTES as z,parseFrame as Y}from"./frames.js";const Z=45e3,Q=15e3,ee=3e4,ne=1e3,S=10,te=new O({noServer:!0,maxPayload:z}),d=new Map,ie="unroutable:";let D;const Te=s(i=>{D=i},"setApiAddress"),ae=s(()=>process.env.CRTR_API_ADDRESS??D??`${ie}${I()}:${process.pid}`,"apiAddress"),_=s(()=>new Date(Date.now()+Z).toISOString(),"lease");class se extends w{static{s(this,"HeldLink")}environmentId;generation;ws;token;timers=[];unsubscribe;claiming=!1;closed=!1;alive=!0;openedAt=new Date().toISOString();channels=new Map;constructor(e,n,t,a){super(),this.environmentId=e,this.generation=n,this.ws=t,this.token=a}start(){const{ws:e}=this;e.on("message",n=>{this.onMessage(n).catch(t=>this.fault("daemon.machine_link.frame_failed",t))}),e.on("pong",()=>{this.alive=!0}),e.on("close",()=>{this.teardown().catch(n=>this.fault("daemon.machine_link.teardown_failed",n))}),e.on("error",()=>{}),this.timers.push(setInterval(()=>{this.renew().catch(n=>this.fault("daemon.machine_link.renew_failed",n))},Q)),this.timers.push(setInterval(()=>{if(!this.alive){e.terminate();return}this.alive=!1;try{e.ping()}catch{}},ee)),this.timers.push(setInterval(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},ne)),V.subscribe(n=>{n===this.environmentId&&this.claim().catch(t=>this.fault("daemon.machine_link.claim_failed",t))},{kinds:["machine"],onListenStart:s(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},"onListenStart")}).then(n=>{this.closed?n():this.unsubscribe=n})}fault(e,n){u({level:"error",event:e,fields:{environment:this.environmentId},error:n})}send(e){return this.ws.readyState!==T.OPEN?!1:(this.ws.send(JSON.stringify(e)),!0)}async renew(){if(this.closed)return;const e=await o(),n=_();if((await e.prepare("UPDATE machine_links SET lease_expires_at = ? WHERE environment = ? AND generation = ?").run(n,this.environmentId,this.generation)).changes===0){this.ws.close(N,"superseded");return}await e.prepare("UPDATE machine_calls SET lease_expires_at = ? WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").run(n,this.environmentId,this.generation),await e.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(new Date().toISOString(),this.environmentId),await this.credentialValid()||this.ws.close(q,"revoked")}async credentialValid(){return await g(this.environmentId,this.token)}async claim(){if(!(this.closed||this.claiming)){this.claiming=!0;try{for(;;){const e=await(await o()).prepare(`UPDATE machine_calls SET state = 'sent', claimed_generation = ?, lease_expires_at = ?
1
+ var b=Object.defineProperty;var a=(i,e)=>b(i,"name",{value:e,configurable:!0});import{importedNodesHeld as x}from"../reconcilers/live-obligation.js";import{EventEmitter as w}from"node:events";import{hostname as I}from"node:os";import{randomUUID as L}from"node:crypto";import{WebSocket as T,WebSocketServer as O}from"ws";import{openDb as o}from"../../core/canvas/db.js";import{emitEvent as d}from"../../core/events/emit.js";import{endExecution as M,liveExecutionForNode as C,recordExecutionExit as U}from"../../core/canvas/executions.js";import{getNode as W}from"../../core/canvas/index.js";import{fullName as H}from"../../core/canvas/labels.js";import{readLiveTurn as P}from"../../core/canvas/recovery.js";import{runningJobs as F}from"../../core/graph/jobs.js";import{readSupervisionMark as j,writeSupervisionMark as $}from"../park-pending.js";import{reportWedge as B,wedgeLabel as J}from"../reconcilers/broker-supervision.js";import{machineEnvironmentOfNode as p}from"../../core/runtime/runner/machine/runner.js";import{storeJobReport as K}from"../api/handlers/bash-jobs.js";import{APIError as E}from"../../api/errors.js";import{brokerSignalBus as V}from"../broker-signals/bus.js";import{verifyMachineCredential as g}from"./credential.js";import{compareReleaseVersions as X,RUNTIME_VERSION_HEADER as G}from"../../api/runtime-version.js";import{crtrVersion as v}from"../../shared/crtr-version.js";import{CLOSE_REVOKED as q,CLOSE_SUPERSEDED as N,LINK_MAX_PAYLOAD_BYTES as z,parseFrame as Y}from"./frames.js";const Z=45e3,Q=15e3,ee=3e4,ne=1e3,S=10,te=new O({noServer:!0,maxPayload:z}),h=new Map,ie="unroutable:";let A;const Te=a(i=>{A=i},"setApiAddress"),se=a(()=>process.env.CRTR_API_ADDRESS??A??`${ie}${I()}:${process.pid}`,"apiAddress"),_=a(()=>new Date(Date.now()+Z).toISOString(),"lease");class ae extends w{static{a(this,"HeldLink")}environmentId;generation;ws;token;timers=[];unsubscribe;claiming=!1;closed=!1;alive=!0;openedAt=new Date().toISOString();channels=new Map;constructor(e,n,t,s){super(),this.environmentId=e,this.generation=n,this.ws=t,this.token=s}start(){const{ws:e}=this;e.on("message",n=>{this.onMessage(n).catch(t=>this.fault("daemon.machine_link.frame_failed",t))}),e.on("pong",()=>{this.alive=!0}),e.on("close",()=>{this.teardown().catch(n=>this.fault("daemon.machine_link.teardown_failed",n))}),e.on("error",()=>{}),this.timers.push(setInterval(()=>{this.renew().catch(n=>this.fault("daemon.machine_link.renew_failed",n))},Q)),this.timers.push(setInterval(()=>{if(!this.alive){e.terminate();return}this.alive=!1;try{e.ping()}catch{}},ee)),this.timers.push(setInterval(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},ne)),V.subscribe(n=>{n===this.environmentId&&this.claim().catch(t=>this.fault("daemon.machine_link.claim_failed",t))},{kinds:["machine"],onListenStart:a(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},"onListenStart")}).then(n=>{this.closed?n():this.unsubscribe=n})}fault(e,n){d({level:"error",event:e,fields:{environment:this.environmentId},error:n})}send(e){return this.ws.readyState!==T.OPEN?!1:(this.ws.send(JSON.stringify(e)),!0)}async renew(){if(this.closed)return;const e=await o(),n=_();if((await e.prepare("UPDATE machine_links SET lease_expires_at = ? WHERE environment = ? AND generation = ?").run(n,this.environmentId,this.generation)).changes===0){this.ws.close(N,"superseded");return}await e.prepare("UPDATE machine_calls SET lease_expires_at = ? WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").run(n,this.environmentId,this.generation),await e.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(new Date().toISOString(),this.environmentId),await this.credentialValid()||this.ws.close(q,"revoked")}async credentialValid(){return await g(this.environmentId,this.token)}async claim(){if(!(this.closed||this.claiming)){this.claiming=!0;try{for(;;){const e=await(await o()).prepare(`UPDATE machine_calls SET state = 'sent', claimed_generation = ?, lease_expires_at = ?
2
2
  WHERE call_id IN (SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'pending'
3
3
  AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)
4
4
  ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT ${S})
5
- RETURNING call_id, op, args_json`).all(this.generation,_(),this.environmentId,this.environmentId,this.generation),n=!this.closed&&await this.isCurrentGeneration();for(const t of e)n?this.send({type:"call",call_id:t.call_id,op:t.op,args:JSON.parse(t.args_json)})||await this.failCall(t.call_id,"machine_offline","link closed before the call was sent",!1):await this.release(t.call_id);if(e.length<S)return}}finally{this.claiming=!1}}}async failCall(e,n,t,a){await this.settle(e,"failed",{code:n,message:t,sent:a},!1)}async isCurrentGeneration(){return await(await o()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await o()).prepare("UPDATE machine_calls SET state = 'pending', claimed_generation = NULL, lease_expires_at = NULL WHERE call_id = ? AND state = 'sent' AND claimed_generation = ?").run(e,this.generation)}async settle(e,n,t,a){await re(e,n,t,this.environmentId,this.generation,a)}async onMessage(e){const n=Y(e);if(n!==null)switch(n.type){case"result":n.ok?await this.settle(n.call_id,"done",n.value??null,!0):await this.settle(n.call_id,"failed",{code:"machine_call_failed",message:n.error},!0);return;case"exit":await A(this.environmentId,n);return;case"running":if(!await this.isCurrentGeneration())return;await oe(this.environmentId,new Set(n.executions),this.openedAt);return;case"job.report":await this.storeJobReport(n);return;case"turns":this.send({type:"turns.answer",id:n.id,turns:await this.turns(n.brokers)});return;case"wedge":await this.recordWedge(n);return;case"view.ready":this.channels.get(n.channel)?.emit("connect");return;case"view.data":this.channels.get(n.channel)?.emit("data",Buffer.from(n.bytes,"base64"));return;case"view.close":this.channels.get(n.channel)?.finish(n.error);return;default:return}}async storeJobReport(e){try{if(await p(e.node)!==this.environmentId)throw new E(404,"unknown_node",`node ${e.node} does not run in this machine environment`);await K(e.node,e.job,e.request),this.send({type:"job.reported",id:e.id})}catch(n){const t=n instanceof E;t||this.fault("daemon.machine_link.job_report_failed",n),this.send({type:"job.reported",id:e.id,error:{status:t?n.status:500,code:t?n.code:"internal_error",message:n.message}})}}async ownNode(e,n){return typeof n!="string"||await p(n)!==this.environmentId||(await C(n))?.executionId!==e?null:await W(n)}async turns(e){const n={};for(const{execution:t,node:a}of e){const r=await this.ownNode(t,a);if(r===null)continue;const c=await P(a),l=c?.busy===!0&&c.progressAt!==null?Date.parse(c.progressAt):Number.NaN,h=Date.parse(r.launched_at??"");n[t]={since:Number.isFinite(l)&&Number.isFinite(h)&&l>=h?l:null,refresh:r.intent==="refresh",jobs:(await F(await o(),a)).length>0}}return n}async recordWedge(e){const n=await this.ownNode(e.execution,e.node);if(n===null||await j(e.node,"wedge_noticed_at")===e.since)return;await $(e.node,"wedge_noticed_at",e.since);const t=e.has_descendants??!0;await B(e.node,{quietForMs:e.quiet_ms,cpuPercent:e.cpu_percent,hasDescendants:e.has_descendants,kickAttempted:e.kick_attempted,kicked:e.kicked,kickSuppressionReason:null,pid:null,label:J(`${H(n)} (${e.node})`,Math.round(e.quiet_ms/6e4),t,!1,e.kicked)})}async teardown(){if(this.closed)return;this.closed=!0;for(const t of this.timers)clearInterval(t);this.unsubscribe?.(),d.get(this.environmentId)===this&&d.delete(this.environmentId);for(const t of[...this.channels.values()])t.finish("machine link closed");const e=await o(),n=await e.prepare("SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").all(this.environmentId,this.generation);for(const{call_id:t}of n)await this.failCall(t,"machine_offline","link dropped before the result",!0);await e.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(this.environmentId,this.generation)}}async function re(i,e,n,t,a,r){const c=await o();(await c.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?, args_json = '{}'
5
+ RETURNING call_id, op, args_json`).all(this.generation,_(),this.environmentId,this.environmentId,this.generation),n=!this.closed&&await this.isCurrentGeneration();for(const t of e)n?this.send({type:"call",call_id:t.call_id,op:t.op,args:JSON.parse(t.args_json)})||await this.failCall(t.call_id,"machine_offline","link closed before the call was sent",!1):await this.release(t.call_id);if(e.length<S)return}}finally{this.claiming=!1}}}async failCall(e,n,t,s){await this.settle(e,"failed",{code:n,message:t,sent:s},!1)}async isCurrentGeneration(){return await(await o()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await o()).prepare("UPDATE machine_calls SET state = 'pending', claimed_generation = NULL, lease_expires_at = NULL WHERE call_id = ? AND state = 'sent' AND claimed_generation = ?").run(e,this.generation)}async settle(e,n,t,s){await re(e,n,t,this.environmentId,this.generation,s)}async onMessage(e){const n=Y(e);if(n!==null)switch(n.type){case"result":n.ok?await this.settle(n.call_id,"done",n.value??null,!0):await this.settle(n.call_id,"failed",{code:"machine_call_failed",message:n.error},!0);return;case"exit":await D(this.environmentId,n);return;case"running":if(!await this.isCurrentGeneration())return;await oe(this.environmentId,new Set(n.executions),this.openedAt);return;case"job.report":await this.storeJobReport(n);return;case"turns":this.send({type:"turns.answer",id:n.id,turns:await this.turns(n.brokers)});return;case"wedge":await this.recordWedge(n);return;case"view.ready":{const t=this.channels.get(n.channel);d({level:"info",event:"daemon.timing.view_ready_received",...t===void 0?{}:{node_id:t.nodeId},fields:{channel:n.channel,known:t!==void 0,...t===void 0?{}:{open_to_ready_ms:t.sinceOpenMs()}}}),t?.emit("connect");return}case"view.data":this.channels.get(n.channel)?.emit("data",Buffer.from(n.bytes,"base64"));return;case"view.close":this.channels.get(n.channel)?.finish(n.error);return;default:return}}async storeJobReport(e){try{if(await p(e.node)!==this.environmentId)throw new E(404,"unknown_node",`node ${e.node} does not run in this machine environment`);await K(e.node,e.job,e.request),this.send({type:"job.reported",id:e.id})}catch(n){const t=n instanceof E;t||this.fault("daemon.machine_link.job_report_failed",n),this.send({type:"job.reported",id:e.id,error:{status:t?n.status:500,code:t?n.code:"internal_error",message:n.message}})}}async ownNode(e,n){return typeof n!="string"||await p(n)!==this.environmentId||(await C(n))?.executionId!==e?null:await W(n)}async turns(e){const n={};for(const{execution:t,node:s}of e){const r=await this.ownNode(t,s);if(r===null)continue;const c=await P(s),l=c?.busy===!0&&c.progressAt!==null?Date.parse(c.progressAt):Number.NaN,u=Date.parse(r.launched_at??"");n[t]={since:Number.isFinite(l)&&Number.isFinite(u)&&l>=u?l:null,refresh:r.intent==="refresh",jobs:(await F(await o(),s)).length>0}}return n}async recordWedge(e){const n=await this.ownNode(e.execution,e.node);if(n===null||await j(e.node,"wedge_noticed_at")===e.since)return;await $(e.node,"wedge_noticed_at",e.since);const t=e.has_descendants??!0;await B(e.node,{quietForMs:e.quiet_ms,cpuPercent:e.cpu_percent,hasDescendants:e.has_descendants,kickAttempted:e.kick_attempted,kicked:e.kicked,kickSuppressionReason:null,pid:null,label:J(`${H(n)} (${e.node})`,Math.round(e.quiet_ms/6e4),t,!1,e.kicked)})}async teardown(){if(this.closed)return;this.closed=!0;for(const t of this.timers)clearInterval(t);this.unsubscribe?.(),h.get(this.environmentId)===this&&h.delete(this.environmentId);for(const t of[...this.channels.values()])t.finish("machine link closed");const e=await o(),n=await e.prepare("SELECT call_id FROM machine_calls WHERE environment = ? AND state = 'sent' AND claimed_generation = ?").all(this.environmentId,this.generation);for(const{call_id:t}of n)await this.failCall(t,"machine_offline","link dropped before the result",!0);await e.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(this.environmentId,this.generation)}}async function re(i,e,n,t,s,r){const c=await o();(await c.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?, args_json = '{}'
6
6
  WHERE call_id = ? AND environment = ? AND claimed_generation = ? AND state = 'sent'
7
- ${r?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,a,...r?[t,a]:[])).changes>0&&await c.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}s(re,"withNotify");async function A(i,e){const n=await o(),t=await n.prepare("SELECT stop_requested_at, stop_reason FROM executions WHERE execution_id = ? AND node_id = ? AND runner = 'machine' AND state != 'exited'").get(e.execution,e.node);return t===void 0||await p(e.node)!==i||(await x()).has(e.node)||(await U(e.execution,{code:e.code,signal:e.signal}),!await M(e.execution,{reason:"exited"}))?!1:(t.stop_requested_at===null&&t.stop_reason===null&&await n.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`execution_exit:${e.node}`),u({level:"info",event:"broker.exit.reported",node_id:e.node,fields:{environment:i,code:e.code,signal:e.signal}}),!0)}s(A,"recordMachineBrokerExit");async function oe(i,e,n){const t=await(await o()).prepare(`SELECT x.execution_id, x.node_id FROM executions x JOIN nodes n ON n.node_id = x.node_id JOIN profiles p ON p.id = n.profile_id
8
- WHERE x.state = 'running' AND x.runner = 'machine' AND p.environment_id = ? AND x.started_at < ?`).all(i,n);for(const a of t)e.has(a.execution_id)||await A(i,{execution:a.execution_id,node:a.node_id,code:null,signal:null})}s(oe,"endUnlistedMachineExecutions");class Oe extends w{static{s(this,"MachineViewLink")}link;ended=!1;failed=!1;channel=L();constructor(e,n){super(),this.link=e,e.channels.set(this.channel,this);const t=performance.now();this.once("connect",()=>u({level:"info",event:"daemon.timing.machine_view_ready",fields:{channel:this.channel,node:n,open_to_ready_ms:Math.round((performance.now()-t)*10)/10}})),e.send({type:"view.open",channel:this.channel,node:n})||queueMicrotask(()=>this.finish("machine link closed"))}get destroyed(){return this.ended}write(e){return!this.ended&&this.link.send({type:"view.data",channel:this.channel,bytes:Buffer.from(e).toString("base64")})}destroy(){return this.ended||(this.link.send({type:"view.close",channel:this.channel}),this.finish(void 0)),this}finish(e){this.ended||(this.ended=!0,this.link.channels.delete(this.channel),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}const Me=s(i=>d.get(i)??null,"heldLinkOf"),ce=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/link$/;function Ce(i){const e=ce.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}s(Ce,"machineLinkEnvironment");async function Ue(i,e,n,t){const a=i.headers.authorization,r=/^Bearer (\S+)$/.exec(Array.isArray(a)?a[0]??"":a??"")?.[1];if(r===void 0||!await g(t,r))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine credential refused"};if(X(String(i.headers[G.toLowerCase()]??""),v())<0)return{status:426,text:"Upgrade Required",code:"machine_release_behind",message:v()};const c=new Date().toISOString(),l=await o(),h=await l.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
7
+ ${r?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,s,...r?[t,s]:[])).changes>0&&await c.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}a(re,"withNotify");async function D(i,e){const n=await o(),t=await n.prepare("SELECT stop_requested_at, stop_reason FROM executions WHERE execution_id = ? AND node_id = ? AND runner = 'machine' AND state != 'exited'").get(e.execution,e.node);return t===void 0||await p(e.node)!==i||(await x()).has(e.node)||(await U(e.execution,{code:e.code,signal:e.signal}),!await M(e.execution,{reason:"exited"}))?!1:(t.stop_requested_at===null&&t.stop_reason===null&&await n.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`execution_exit:${e.node}`),d({level:"info",event:"broker.exit.reported",node_id:e.node,fields:{environment:i,code:e.code,signal:e.signal}}),!0)}a(D,"recordMachineBrokerExit");async function oe(i,e,n){const t=await(await o()).prepare(`SELECT x.execution_id, x.node_id FROM executions x JOIN nodes n ON n.node_id = x.node_id JOIN profiles p ON p.id = n.profile_id
8
+ WHERE x.state = 'running' AND x.runner = 'machine' AND p.environment_id = ? AND x.started_at < ?`).all(i,n);for(const s of t)e.has(s.execution_id)||await D(i,{execution:s.execution_id,node:s.node_id,code:null,signal:null})}a(oe,"endUnlistedMachineExecutions");class Oe extends w{static{a(this,"MachineViewLink")}link;nodeId;ended=!1;failed=!1;channel=L();opened=performance.now();constructor(e,n){super(),this.link=e,this.nodeId=n,e.channels.set(this.channel,this),this.once("connect",()=>d({level:"info",event:"daemon.timing.machine_view_ready",node_id:n,fields:{channel:this.channel,open_to_ready_ms:this.sinceOpenMs()}}));const t=e.send({type:"view.open",channel:this.channel,node:n});d({level:"info",event:"daemon.timing.view_open_sent",node_id:n,fields:{channel:this.channel,sent:t,link_buffered_bytes:e.ws.bufferedAmount,send_sync_ms:this.sinceOpenMs()}}),t||queueMicrotask(()=>this.finish("machine link closed"))}sinceOpenMs(){return Math.round((performance.now()-this.opened)*10)/10}get destroyed(){return this.ended}write(e){return!this.ended&&this.link.send({type:"view.data",channel:this.channel,bytes:Buffer.from(e).toString("base64")})}destroy(){return this.ended||(this.link.send({type:"view.close",channel:this.channel}),this.finish(void 0)),this}finish(e){this.ended||(this.ended=!0,this.link.channels.delete(this.channel),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}const Me=a(i=>h.get(i)??null,"heldLinkOf"),ce=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/link$/;function Ce(i){const e=ce.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Ce,"machineLinkEnvironment");async function Ue(i,e,n,t){const s=i.headers.authorization,r=/^Bearer (\S+)$/.exec(Array.isArray(s)?s[0]??"":s??"")?.[1];if(r===void 0||!await g(t,r))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine credential refused"};if(X(String(i.headers[G.toLowerCase()]??""),v())<0)return{status:426,text:"Upgrade Required",code:"machine_release_behind",message:v()};const c=new Date().toISOString(),l=await o(),u=await l.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
9
9
  ON CONFLICT (environment) DO UPDATE SET generation = machine_links.generation + 1, api_address = EXCLUDED.api_address, connected_at = EXCLUDED.connected_at, lease_expires_at = EXCLUDED.lease_expires_at
10
- RETURNING generation`).get(t,ae(),c,_());await l.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(c,t);const f=Number(h.generation);return e.destroyed?(await l.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(t,f),null):(te.handleUpgrade(i,e,n,k=>{const m=new se(t,f,k,r),R=d.get(t);d.set(t,m),R?.ws.close(N,"superseded"),m.start(),m.claim().catch(y=>u({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:t},error:y}))}),null)}s(Ue,"handleMachineLinkUpgrade");export{se as HeldLink,Z as LINK_LEASE_MS,ee as LINK_PING_MS,Q as LINK_RENEW_MS,Oe as MachineViewLink,ie as UNROUTABLE_PREFIX,ae as apiAddress,Ue as handleMachineLinkUpgrade,Me as heldLinkOf,Ce as machineLinkEnvironment,A as recordMachineBrokerExit,Te as setApiAddress};
10
+ RETURNING generation`).get(t,se(),c,_());await l.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(c,t);const f=Number(u.generation);return e.destroyed?(await l.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(t,f),null):(te.handleUpgrade(i,e,n,k=>{const m=new ae(t,f,k,r),y=h.get(t);h.set(t,m),y?.ws.close(N,"superseded"),m.start(),m.claim().catch(R=>d({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:t},error:R}))}),null)}a(Ue,"handleMachineLinkUpgrade");export{ae as HeldLink,Z as LINK_LEASE_MS,ee as LINK_PING_MS,Q as LINK_RENEW_MS,Oe as MachineViewLink,ie as UNROUTABLE_PREFIX,se as apiAddress,Ue as handleMachineLinkUpgrade,Me as heldLinkOf,Ce as machineLinkEnvironment,D as recordMachineBrokerExit,Te as setApiAddress};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.700",
3
+ "version": "0.3.701",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "license": "UNLICENSED",
158
158
  "dependencies": {
159
- "@north-light/identity": "0.3.700",
160
- "@north-light/plugin": "0.3.700",
159
+ "@north-light/identity": "0.3.701",
160
+ "@north-light/plugin": "0.3.701",
161
161
  "@earendil-works/chord": "1.5.2",
162
162
  "@earendil-works/pi-agent-core": "1.5.2",
163
163
  "@earendil-works/pi-ai": "1.5.2",
@@ -8,6 +8,7 @@
8
8
  // header and never logs it.
9
9
  import { EventEmitter } from 'node:events';
10
10
  import { WebSocket } from 'ws';
11
+ import { mark } from '../timing.js';
11
12
  import { classify } from '../fault-classifier.js';
12
13
  import { AttachRefusedError, BrokerUnavailableError } from './transport.js';
13
14
  function relayUrl(target, nodeId, wakeParked) {
@@ -46,10 +47,17 @@ export class RelayTransport extends EventEmitter {
46
47
  return relayUrl(this.target, this.nodeId, this.wakeParked);
47
48
  }
48
49
  dial() {
50
+ // CRTR_TIMING marks (stderr, same timeline as `viewer.*`): the target kind and the dial's own steps, each with the duration since this dial began.
51
+ const dialStart = performance.now();
52
+ const since = () => (performance.now() - dialStart).toFixed(1);
53
+ const kind = 'socketPath' in this.target ? 'local' : 'remote';
54
+ mark('relay.dial_start', { node: this.nodeId, target: kind });
49
55
  const ws = new WebSocket(this.url, {
50
56
  ...('relayToken' in this.target ? { headers: { authorization: `Bearer ${this.target.relayToken}` } } : {}),
51
57
  perMessageDeflate: false,
52
58
  });
59
+ ws.once('upgrade', () => mark('relay.upgrade_response', { node: this.nodeId, target: kind, since_dial_ms: since() }));
60
+ ws.once('open', () => mark('relay.ws_open', { node: this.nodeId, target: kind, since_dial_ms: since() }));
53
61
  // A refusal's JSON body carries the reason (`broker_not_ready`, `attach_revive_failed`); ws would drop it as a bare status.
54
62
  ws.on('unexpected-response', (_req, res) => {
55
63
  let text = '';
@@ -39,7 +39,7 @@ class ForwardedViewLink extends EventEmitter {
39
39
  this.environmentId = environmentId;
40
40
  this.nodeId = nodeId;
41
41
  const opened = performance.now();
42
- this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.forwarded_view_ready', fields: { environment: this.environmentId, node: this.nodeId, open_to_ready_ms: Math.round((performance.now() - opened) * 10) / 10 } }));
42
+ this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.forwarded_view_ready', node_id: this.nodeId, fields: { environment: this.environmentId, open_to_ready_ms: Math.round((performance.now() - opened) * 10) / 10 } }));
43
43
  this.dial().catch((error) => this.finish(error instanceof Error ? error.message : String(error)));
44
44
  }
45
45
  get destroyed() { return this.ended; }
@@ -119,7 +119,11 @@ class ForwardedViewLink extends EventEmitter {
119
119
  function openReadyMachineView(environmentId, nodeId, timeoutMs) {
120
120
  return new Promise((resolve) => {
121
121
  const view = openMachineView(environmentId, nodeId);
122
- const timer = setTimeout(() => { resolve(null); view.destroy(); }, timeoutMs);
122
+ const timer = setTimeout(() => {
123
+ emitEvent({ level: 'info', event: 'daemon.timing.view_ready_timeout', node_id: nodeId, fields: { channel: view.channel ?? '', timeout_ms: timeoutMs } });
124
+ resolve(null);
125
+ view.destroy();
126
+ }, timeoutMs);
123
127
  // The no-op error listener stays on the returned channel until its user attaches its own: an error before then must not throw.
124
128
  view.on('error', () => { });
125
129
  view.on('connect', () => { clearTimeout(timer); resolve(view); });
@@ -188,9 +188,13 @@ export class HeldLink extends EventEmitter {
188
188
  case 'wedge':
189
189
  await this.recordWedge(frame);
190
190
  return;
191
- case 'view.ready':
192
- this.channels.get(frame.channel)?.emit('connect');
191
+ case 'view.ready': {
192
+ const channel = this.channels.get(frame.channel);
193
+ // One mark per ready frame (a viewer connection sends one); a ready for a channel already closed or never opened here says so.
194
+ emitEvent({ level: 'info', event: 'daemon.timing.view_ready_received', ...(channel === undefined ? {} : { node_id: channel.nodeId }), fields: { channel: frame.channel, known: channel !== undefined, ...(channel === undefined ? {} : { open_to_ready_ms: channel.sinceOpenMs() }) } });
195
+ channel?.emit('connect');
193
196
  return;
197
+ }
194
198
  case 'view.data':
195
199
  this.channels.get(frame.channel)?.emit('data', Buffer.from(frame.bytes, 'base64'));
196
200
  return;
@@ -309,18 +313,23 @@ async function endUnlistedMachineExecutions(environmentId, listed, openedAt) {
309
313
  /** A viewer channel to one node's view.sock on the Mac, as the relay's broker-side link. */
310
314
  export class MachineViewLink extends EventEmitter {
311
315
  link;
316
+ nodeId;
312
317
  ended = false;
313
318
  failed = false;
314
319
  channel = randomUUID();
320
+ opened = performance.now();
315
321
  constructor(link, nodeId) {
316
322
  super();
317
323
  this.link = link;
324
+ this.nodeId = nodeId;
318
325
  link.channels.set(this.channel, this);
319
- const opened = performance.now();
320
- this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.machine_view_ready', fields: { channel: this.channel, node: nodeId, open_to_ready_ms: Math.round((performance.now() - opened) * 10) / 10 } }));
321
- if (!link.send({ type: 'view.open', channel: this.channel, node: nodeId }))
326
+ this.once('connect', () => emitEvent({ level: 'info', event: 'daemon.timing.machine_view_ready', node_id: nodeId, fields: { channel: this.channel, open_to_ready_ms: this.sinceOpenMs() } }));
327
+ const sent = link.send({ type: 'view.open', channel: this.channel, node: nodeId });
328
+ emitEvent({ level: 'info', event: 'daemon.timing.view_open_sent', node_id: nodeId, fields: { channel: this.channel, sent, link_buffered_bytes: link.ws.bufferedAmount, send_sync_ms: this.sinceOpenMs() } });
329
+ if (!sent)
322
330
  queueMicrotask(() => this.finish('machine link closed'));
323
331
  }
332
+ sinceOpenMs() { return Math.round((performance.now() - this.opened) * 10) / 10; }
324
333
  get destroyed() { return this.ended; }
325
334
  write(line) {
326
335
  return !this.ended && this.link.send({ type: 'view.data', channel: this.channel, bytes: Buffer.from(line).toString('base64') });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.700",
3
+ "version": "0.3.701",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.700",
3
+ "version": "0.3.701",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.700",
3
+ "version": "0.3.701",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.700",
31
- "@north-light/identity": "0.3.700"
30
+ "@north-light/api": "0.3.701",
31
+ "@north-light/identity": "0.3.701"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.700",
3
+ "version": "0.3.701",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.700",
9
+ "version": "0.3.701",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.700",
32
- "@north-light/plugin": "0.3.700",
31
+ "@north-light/identity": "0.3.701",
32
+ "@north-light/plugin": "0.3.701",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -10667,17 +10667,17 @@
10667
10667
  },
10668
10668
  "packages/crouter-api": {
10669
10669
  "name": "@north-light/api",
10670
- "version": "0.3.700",
10670
+ "version": "0.3.701",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.700",
10675
+ "version": "0.3.701",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.700",
10680
+ "version": "0.3.701",
10681
10681
  "license": "UNLICENSED",
10682
10682
  "dependencies": {
10683
10683
  "jose": "^6.2.1"
@@ -10685,21 +10685,21 @@
10685
10685
  },
10686
10686
  "packages/crouter-plugin": {
10687
10687
  "name": "@north-light/plugin",
10688
- "version": "0.3.700",
10688
+ "version": "0.3.701",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.700",
10692
- "@north-light/identity": "0.3.700"
10691
+ "@north-light/api": "0.3.701",
10692
+ "@north-light/identity": "0.3.701"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.700",
10697
+ "version": "0.3.701",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.700",
10701
- "@north-light/identity": "0.3.700",
10702
- "@north-light/plugin": "0.3.700",
10700
+ "@north-light/api": "0.3.701",
10701
+ "@north-light/identity": "0.3.701",
10702
+ "@north-light/plugin": "0.3.701",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {