@north-light/cli 0.3.695 → 0.3.697

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.
Files changed (33) hide show
  1. package/dist/clients/attach/session/connection.js +1 -1
  2. package/dist/clients/attach/viewer.js +374 -374
  3. package/dist/commands/node/bash.js +2 -2
  4. package/dist/core/broker-client/transport-relay.d.ts +12 -1
  5. package/dist/core/broker-client/transport-relay.js +1 -1
  6. package/dist/core/runtime/runner/machine/executor.d.ts +0 -3
  7. package/dist/core/runtime/runner/machine/executor.js +1 -1
  8. package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
  9. package/dist/core/runtime/runner/machine/ops.d.ts +5 -6
  10. package/dist/core/runtime/runner/machine/runner.d.ts +3 -0
  11. package/dist/core/runtime/runner/machine/runner.js +1 -1
  12. package/dist/daemon/api/bridge.js +4 -4
  13. package/dist/daemon/api/handlers/attach.js +1 -1
  14. package/dist/daemon/machine-daemon.js +1 -1
  15. package/dist/daemon/machine-link/client.d.ts +10 -4
  16. package/dist/daemon/machine-link/client.js +1 -1
  17. package/dist/daemon/machine-link/forward.d.ts +2 -4
  18. package/dist/daemon/machine-link/forward.js +1 -1
  19. package/dist/daemon/machine-link/holder.js +5 -5
  20. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +1 -1
  21. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +2 -2
  22. package/package.json +3 -3
  23. package/packages/crouter-api/dist/clients/attach/session/connection.js +37 -24
  24. package/packages/crouter-api/dist/commands/node/bash.js +1 -1
  25. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +24 -7
  26. package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +10 -8
  27. package/packages/crouter-api/dist/daemon/machine-link/forward.js +12 -11
  28. package/packages/crouter-api/dist/daemon/machine-link/holder.js +5 -0
  29. package/packages/crouter-api/package.json +1 -1
  30. package/packages/crouter-identity/package.json +1 -1
  31. package/packages/crouter-plugin/package.json +3 -3
  32. package/runtime.lock.json +14 -14
  33. package/scripts/self-update.mjs +7 -3
@@ -6,10 +6,8 @@ import { type MachineLinkRefusal } from './holder.js';
6
6
  export declare const VIEW_BUFFER_LIMIT_BYTES: number;
7
7
  /** A viewer channel to a node on a machine: over the link this process holds, or forwarded to the API process that does. */
8
8
  export declare function openMachineView(environmentId: string, nodeId: string): BrokerViewLink;
9
- /** One readiness check: the Mac connected the node's view.sock within `timeoutMs`. */
10
- export declare function probeMachineView(environmentId: string, nodeId: string, timeoutMs: number): Promise<boolean>;
11
- /** Wait for the node's broker on the Mac to accept a viewer, retrying while its view.sock refuses; false on the deadline or when the launch exits. */
12
- export declare function waitForMachineView(environmentId: string, nodeId: string, exited: Promise<unknown> | undefined, waitMs: number): Promise<boolean>;
9
+ /** Wait for the node's broker on the Mac to accept a viewer, retrying while its view.sock refuses; the accepted channel, open, or null on the deadline or when the launch exits. A caller that does not use the channel destroys it. */
10
+ export declare function waitForMachineView(environmentId: string, nodeId: string, exited: Promise<unknown> | undefined, waitMs: number): Promise<BrokerViewLink | null>;
13
11
  /** The environment id of a forwarded viewer upgrade path, or null for any other path. */
14
12
  export declare function machineViewEnvironment(req: IncomingMessage): string | null;
15
13
  /** The holder's side: authenticate the forwarding API process, open a channel on the link this process holds and pipe it. Returns a refusal for the caller to write, or null once upgraded. */
@@ -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 u,WebSocketServer as P}from"ws";import{markAt as R}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 P({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!==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 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 u(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(!1),t.destroy()},r);t.on("connect",()=>{clearTimeout(n),s(!0),t.destroy()}),t.on("error",()=>{}),t.on("close",()=>{clearTimeout(n),s(!1)})})}a(C,"probeMachineView");async function G(i,e,r,s){const t=Date.now()+s;let n=!1;r?.then(()=>{n=!0});for(let f=1;Date.now()<=t&&!n;f++){const l=performance.now(),c=await C(i,e,Math.max(1,Math.min(2e3,t-Date.now())));if(k(`probe_${f}_${c?"ready":"failed"}_ms`,performance.now()-l),c)return R("ready_received"),!0;await new Promise(m=>setTimeout(m,250))}return!1}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]??"",f=Buffer.from(S(s)),l=Buffer.from(n);if(l.length!==f.length||!A(l,f))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine view forward credential refused"};const c=new URL(i.url??"/","http://runtime.local").searchParams.get("node");if(c===null||c==="")return{status:400,text:"Bad Request",code:"bad_request",message:"node is required"};const m=g(s);return m===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(m,c),p=a(h=>{d.readyState===u.OPEN&&d.send(JSON.stringify(h))},"send");o.on("connect",()=>p({type:"view.ready",channel:""})),o.on("data",h=>{if(d.bufferedAmount>y){o.destroy(),d.close($,"viewer too slow");return}p({type:"view.data",channel:"",bytes:h.toString("base64")})}),o.on("error",h=>p({type:"view.close",channel:"",error:h.message})),o.on("close",()=>d.close()),d.on("message",h=>{const w=v(h);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,C as probeMachineView,G as waitForMachineView};
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,9 +1,9 @@
1
- var R=Object.defineProperty;var s=(i,e)=>R(i,"name",{value:e,configurable:!0});import{importedNodesHeld as y}from"../reconcilers/live-obligation.js";import{EventEmitter as f}from"node:events";import{hostname as T}from"node:os";import{randomUUID as L}from"node:crypto";import{WebSocket as I,WebSocketServer as b}from"ws";import{openDb as r}from"../../core/canvas/db.js";import{emitEvent as h}from"../../core/events/emit.js";import{endExecution as O,recordExecutionExit as x}from"../../core/canvas/executions.js";import{machineEnvironmentOfNode as p}from"../../core/runtime/runner/machine/runner.js";import{storeJobReport as C}from"../api/handlers/bash-jobs.js";import{APIError as E}from"../../api/errors.js";import{brokerSignalBus as M}from"../broker-signals/bus.js";import{verifyMachineCredential as w}from"./credential.js";import{CLOSE_REVOKED as U,CLOSE_SUPERSEDED as g,LINK_MAX_PAYLOAD_BYTES as H,parseFrame as P}from"./frames.js";const W=45e3,j=15e3,F=3e4,$=1e3,v=10,B=new b({noServer:!0,maxPayload:H}),c=new Map,K="unroutable:";let S;const he=s(i=>{S=i},"setApiAddress"),X=s(()=>process.env.CRTR_API_ADDRESS??S??`${K}${T()}:${process.pid}`,"apiAddress"),u=s(()=>new Date(Date.now()+W).toISOString(),"lease");class J extends f{static{s(this,"HeldLink")}environmentId;generation;ws;token;timers=[];unsubscribe;claiming=!1;closed=!1;alive=!0;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))},j)),this.timers.push(setInterval(()=>{if(!this.alive){e.terminate();return}this.alive=!1;try{e.ping()}catch{}},F)),this.timers.push(setInterval(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},$)),M.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){h({level:"error",event:e,fields:{environment:this.environmentId},error:n})}send(e){return this.ws.readyState!==I.OPEN?!1:(this.ws.send(JSON.stringify(e)),!0)}async renew(){if(this.closed)return;const e=await r(),n=u();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(g,"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(U,"revoked")}async credentialValid(){return await w(this.environmentId,this.token)}async claim(){if(!(this.closed||this.claiming)){this.claiming=!0;try{for(;;){const e=await(await r()).prepare(`UPDATE machine_calls SET state = 'sent', claimed_generation = ?, lease_expires_at = ?
1
+ var y=Object.defineProperty;var s=(i,e)=>y(i,"name",{value:e,configurable:!0});import{importedNodesHeld as T}from"../reconcilers/live-obligation.js";import{EventEmitter as f}from"node:events";import{hostname as I}from"node:os";import{randomUUID as L}from"node:crypto";import{WebSocket as b,WebSocketServer as O}from"ws";import{openDb as r}from"../../core/canvas/db.js";import{emitEvent as h}from"../../core/events/emit.js";import{endExecution as x,recordExecutionExit as C}from"../../core/canvas/executions.js";import{machineEnvironmentOfNode as p}from"../../core/runtime/runner/machine/runner.js";import{storeJobReport as M}from"../api/handlers/bash-jobs.js";import{APIError as E}from"../../api/errors.js";import{brokerSignalBus as U}from"../broker-signals/bus.js";import{verifyMachineCredential as w}from"./credential.js";import{compareReleaseVersions as H,RUNTIME_VERSION_HEADER as P}from"../../api/runtime-version.js";import{crtrVersion as g}from"../../shared/crtr-version.js";import{CLOSE_REVOKED as W,CLOSE_SUPERSEDED as v,LINK_MAX_PAYLOAD_BYTES as j,parseFrame as F}from"./frames.js";const $=45e3,B=15e3,K=3e4,V=1e3,S=10,X=new O({noServer:!0,maxPayload:j}),c=new Map,J="unroutable:";let D;const pe=s(i=>{D=i},"setApiAddress"),G=s(()=>process.env.CRTR_API_ADDRESS??D??`${J}${I()}:${process.pid}`,"apiAddress"),u=s(()=>new Date(Date.now()+$).toISOString(),"lease");class z extends f{static{s(this,"HeldLink")}environmentId;generation;ws;token;timers=[];unsubscribe;claiming=!1;closed=!1;alive=!0;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))},B)),this.timers.push(setInterval(()=>{if(!this.alive){e.terminate();return}this.alive=!1;try{e.ping()}catch{}},K)),this.timers.push(setInterval(()=>{this.claim().catch(n=>this.fault("daemon.machine_link.claim_failed",n))},V)),U.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){h({level:"error",event:e,fields:{environment:this.environmentId},error:n})}send(e){return this.ws.readyState!==b.OPEN?!1:(this.ws.send(JSON.stringify(e)),!0)}async renew(){if(this.closed)return;const e=await r(),n=u();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(v,"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(W,"revoked")}async credentialValid(){return await w(this.environmentId,this.token)}async claim(){if(!(this.closed||this.claiming)){this.claiming=!0;try{for(;;){const e=await(await r()).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
- ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT ${v})
5
- RETURNING call_id, op, args_json`).all(this.generation,u(),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<v)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 r()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await r()).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 G(e,n,t,this.environmentId,this.generation,a)}async onMessage(e){const n=P(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 V(this.environmentId,n);return;case"job.report":await this.storeJobReport(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 C(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 teardown(){if(this.closed)return;this.closed=!0;for(const t of this.timers)clearInterval(t);this.unsubscribe?.(),c.get(this.environmentId)===this&&c.delete(this.environmentId);for(const t of[...this.channels.values()])t.finish("machine link closed");const e=await r(),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 G(i,e,n,t,a,o){const l=await r();(await l.prepare(`UPDATE machine_calls SET state = ?, result_json = ?, finished_at = ?, args_json = '{}'
4
+ ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT ${S})
5
+ RETURNING call_id, op, args_json`).all(this.generation,u(),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 r()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND generation = ?").get(this.environmentId,this.generation)!==void 0}async release(e){await(await r()).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 Y(e,n,t,this.environmentId,this.generation,a)}async onMessage(e){const n=F(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 q(this.environmentId,n);return;case"job.report":await this.storeJobReport(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 M(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 teardown(){if(this.closed)return;this.closed=!0;for(const t of this.timers)clearInterval(t);this.unsubscribe?.(),c.get(this.environmentId)===this&&c.delete(this.environmentId);for(const t of[...this.channels.values()])t.finish("machine link closed");const e=await r(),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 Y(i,e,n,t,a,o){const l=await r();(await l.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
- ${o?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,a,...o?[t,a]:[])).changes>0&&await l.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}s(G,"withNotify");async function V(i,e){const n=await r(),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 y()).has(e.node)||(await x(e.execution,{code:e.code,signal:e.signal}),!await O(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}`),h({level:"info",event:"broker.exit.reported",node_id:e.node,fields:{environment:i,code:e.code,signal:e.signal}}),!0)}s(V,"recordMachineBrokerExit");class me extends f{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",()=>h({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 ue=s(i=>c.get(i)??null,"heldLinkOf"),z=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/link$/;function _e(i){const e=z.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}s(_e,"machineLinkEnvironment");async function fe(i,e,n,t){const a=i.headers.authorization,o=/^Bearer (\S+)$/.exec(Array.isArray(a)?a[0]??"":a??"")?.[1];if(o===void 0||!await w(t,o))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine credential refused"};const l=new Date().toISOString(),d=await r(),D=await d.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
7
+ ${o?"AND EXISTS (SELECT 1 FROM machine_links WHERE environment = ? AND generation = ?)":""}`).run(e,JSON.stringify(n),new Date().toISOString(),i,t,a,...o?[t,a]:[])).changes>0&&await l.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine_call:${i}`)}s(Y,"withNotify");async function q(i,e){const n=await r(),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 T()).has(e.node)||(await C(e.execution,{code:e.code,signal:e.signal}),!await x(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}`),h({level:"info",event:"broker.exit.reported",node_id:e.node,fields:{environment:i,code:e.code,signal:e.signal}}),!0)}s(q,"recordMachineBrokerExit");class Ee extends f{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",()=>h({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 we=s(i=>c.get(i)??null,"heldLinkOf"),Z=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/link$/;function ge(i){const e=Z.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}s(ge,"machineLinkEnvironment");async function ve(i,e,n,t){const a=i.headers.authorization,o=/^Bearer (\S+)$/.exec(Array.isArray(a)?a[0]??"":a??"")?.[1];if(o===void 0||!await w(t,o))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine credential refused"};if(H(String(i.headers[P.toLowerCase()]??""),g())<0)return{status:426,text:"Upgrade Required",code:"machine_release_behind",message:g()};const l=new Date().toISOString(),d=await r(),A=await d.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
8
8
  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
9
- RETURNING generation`).get(t,X(),l,u());await d.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(l,t);const _=Number(D.generation);return e.destroyed?(await d.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(t,_),null):(B.handleUpgrade(i,e,n,A=>{const m=new J(t,_,A,o),N=c.get(t);c.set(t,m),N?.ws.close(g,"superseded"),m.start(),m.claim().catch(k=>h({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:t},error:k}))}),null)}s(fe,"handleMachineLinkUpgrade");export{J as HeldLink,W as LINK_LEASE_MS,F as LINK_PING_MS,j as LINK_RENEW_MS,me as MachineViewLink,K as UNROUTABLE_PREFIX,X as apiAddress,fe as handleMachineLinkUpgrade,ue as heldLinkOf,_e as machineLinkEnvironment,V as recordMachineBrokerExit,he as setApiAddress};
9
+ RETURNING generation`).get(t,G(),l,u());await d.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(l,t);const _=Number(A.generation);return e.destroyed?(await d.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(t,_),null):(X.handleUpgrade(i,e,n,N=>{const m=new z(t,_,N,o),R=c.get(t);c.set(t,m),R?.ws.close(v,"superseded"),m.start(),m.claim().catch(k=>h({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:t},error:k}))}),null)}s(ve,"handleMachineLinkUpgrade");export{z as HeldLink,$ as LINK_LEASE_MS,K as LINK_PING_MS,B as LINK_RENEW_MS,Ee as MachineViewLink,J as UNROUTABLE_PREFIX,G as apiAddress,ve as handleMachineLinkUpgrade,we as heldLinkOf,ge as machineLinkEnvironment,q as recordMachineBrokerExit,pe as setApiAddress};
@@ -1,5 +1,5 @@
1
1
  /** Ends each `running` machine execution whose machine reports no broker for it. The rows are read before the call, so a broker that
2
2
  * started after the scan is never judged by it (its execution was not yet `running`). An environment whose call fails (offline, lost)
3
- * is left as it is. A machine on a release before `status.all` is asked per execution with `status`, as before. A node held by an
3
+ * is left as it is. A node held by an
4
4
  * import is left to the import. Returns the nodes whose execution this call ended, so the caller can re-read their rows. */
5
5
  export declare function endGoneMachineExecutions(): Promise<ReadonlySet<string>>;
@@ -1,4 +1,4 @@
1
- var s=Object.defineProperty;var c=(n,o)=>s(n,"name",{value:o,configurable:!0});import{openDb as l}from"../../../core/canvas/db.js";import{endExecution as m,liveExecutionForNode as f}from"../../../core/canvas/executions.js";import{emitEvent as d}from"../../../core/events/emit.js";import{callMachine as u}from"../../../core/runtime/runner/machine/call.js";import{MachineCallFailedError as p,MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{importedNodesHeld as h}from"../live-obligation.js";import{endRemoteExecutionIfGone as w}from"./remote-wake.js";async function I(){const n=new Set;let o,a;try{a=await h(),o=await(await l()).prepare(`SELECT x.execution_id, x.node_id, e.object AS environment
1
+ var s=Object.defineProperty;var a=(n,o)=>s(n,"name",{value:o,configurable:!0});import{openDb as l}from"../../../core/canvas/db.js";import{endExecution as m}from"../../../core/canvas/executions.js";import{emitEvent as c}from"../../../core/events/emit.js";import{callMachine as f}from"../../../core/runtime/runner/machine/call.js";import{MachineOfflineError as u}from"../../../core/runtime/runner/machine/ops.js";import{importedNodesHeld as p}from"../live-obligation.js";async function y(){const n=new Set;let o,t;try{t=await p(),o=await(await l()).prepare(`SELECT x.execution_id, x.node_id, e.object AS environment
2
2
  FROM executions x JOIN nodes n ON n.node_id = x.node_id JOIN profiles p ON p.id = n.profile_id
3
3
  JOIN environments e ON e.object = p.environment_id AND e.kind = 'machine'
4
- WHERE x.state = 'running' AND x.runner = 'machine'`).all()}catch(e){return d({level:"error",event:"execution.machine_check_failed",error:e}),n}const i=new Map;for(const e of o)a.has(e.node_id)||i.set(e.environment,[...i.get(e.environment)??[],e]);return await Promise.all([...i].map(async([e,t])=>{try{await _(e,t,n)}catch(r){d({level:r instanceof x?"debug":"warn",event:"execution.machine_check_failed",fields:{environment:e},error:r})}})),n}c(I,"endGoneMachineExecutions");async function _(n,o,a){let i;try{i=new Set((await u(n,"status.all",{})).running.map(e=>e.execution))}catch(e){if(!(e instanceof p&&e.message.includes("does not execute status.all")))throw e;for(const{node_id:t}of o){const r=await f(t);r?.state==="running"&&r.runner==="machine"&&await w(r)&&a.add(t)}return}for(const{execution_id:e,node_id:t}of o)i.has(e)||await m(e,{reason:"lost"})&&(a.add(t),d({level:"warn",event:"execution.lost",node_id:t}))}c(_,"endGoneOn");export{I as endGoneMachineExecutions};
4
+ WHERE x.state = 'running' AND x.runner = 'machine'`).all()}catch(e){return c({level:"error",event:"execution.machine_check_failed",error:e}),n}const i=new Map;for(const e of o)t.has(e.node_id)||i.set(e.environment,[...i.get(e.environment)??[],e]);return await Promise.all([...i].map(async([e,r])=>{try{await x(e,r,n)}catch(d){c({level:d instanceof u?"debug":"warn",event:"execution.machine_check_failed",fields:{environment:e},error:d})}})),n}a(y,"endGoneMachineExecutions");async function x(n,o,t){const i=new Set((await f(n,"status.all",{})).running.map(e=>e.execution));for(const{execution_id:e,node_id:r}of o)i.has(e)||await m(e,{reason:"lost"})&&(t.add(r),c({level:"warn",event:"execution.lost",node_id:r}))}a(x,"endGoneOn");export{y as endGoneMachineExecutions};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.695",
3
+ "version": "0.3.697",
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.695",
160
- "@north-light/plugin": "0.3.695",
159
+ "@north-light/identity": "0.3.697",
160
+ "@north-light/plugin": "0.3.697",
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",
@@ -12,7 +12,8 @@ import { apiSocketPath, viewSocketPath } from '../../../core/canvas/paths.js';
12
12
  import { BrokerClient, BrokerUnavailableError, RelayTransport } from '../../../core/broker-client/index.js';
13
13
  import { resolveRemoteCanvasTarget } from '../../../core/remote-canvas-target.js';
14
14
  import { ApiCanvasSource, cliCanvasSource, cliClient, rethrowAsCliError } from '../../../commands/api-client.js';
15
- import { InputError } from '../../../core/io.js';
15
+ import { InputError, apiErrorToCliError } from '../../../core/io.js';
16
+ import { ApiError } from '../../../api/index.js';
16
17
  import { readMachineConfig } from '../../../daemon/machine-link/config.js';
17
18
  import { personBearer } from '../../../core/directory/person-credential.js';
18
19
  /** The person bearer is cached until 30 s before it ends; a viewer redials with whatever the target holds at that moment, so a shorter timer keeps it fresh. */
@@ -109,30 +110,31 @@ hello) {
109
110
  }
110
111
  meta = localMeta;
111
112
  nodeIdentity = localMeta;
112
- // Attach revives a dormant node (B2 acceptance): the server-side
113
- // ensureAttach runs reviveNode (the ONE sanctioned launcher) and waits for
114
- // the broker's view socket, returning socket_path === viewSocketPath(nodeId).
115
- // The viewer connects through crtrd's Unix-socket WebSocket bridge after
116
- // this ensure. The daemon, not the broker, owns attending viewer presence.
117
- try {
118
- const attach = await cliClient().ensureAttach(nodeId, { resume: true, revive: true, wakeParked });
119
- if (attach.parked) {
120
- const saved = await cliClient().getSnapshot(nodeId);
121
- // The API DTO stays dependency-light and structural; this viewer is the
122
- // consumer that knows the complete broker snapshot contract.
123
- initialSnapshot = saved.snapshot;
124
- initialCommands = saved.commands;
125
- }
113
+ if (machine !== undefined) {
114
+ // On a Mac the viewer's WebSocket upgrade alone admits the attach: it authorizes, revives and waits for the broker once, and its channel
115
+ // is the viewer's. A focus of a parked node dials without waking it; the upgrade's `node_dormant` refusal says the node is parked.
116
+ transport = new RelayTransport(nodeId, await machineRelayTarget(machine.apiUrl, machine.directoryUrl), wakeParked);
126
117
  }
127
- catch (err) {
128
- rethrowAsCliError(err, 'The node may be finalized or otherwise not attachable.');
129
- }
130
- // Local only: remote attach reaches crtrd over WebSocket rather than a
131
- // local socket file, so `--canvas` has nothing to pre-wait on. An offline
132
- // parked focus has deliberately no socket to wait for.
133
- if (machine !== undefined)
134
- transport = new RelayTransport(nodeId, await machineRelayTarget(machine.apiUrl, machine.directoryUrl));
135
118
  else {
119
+ // Attach revives a dormant node (B2 acceptance): the server-side
120
+ // ensureAttach runs reviveNode (the ONE sanctioned launcher) and waits for
121
+ // the broker's view socket, returning socket_path === viewSocketPath(nodeId).
122
+ // The viewer connects through crtrd's Unix-socket WebSocket bridge after
123
+ // this ensure. The daemon, not the broker, owns attending viewer presence.
124
+ try {
125
+ const attach = await cliClient().ensureAttach(nodeId, { resume: true, revive: true, wakeParked });
126
+ if (attach.parked) {
127
+ const saved = await cliClient().getSnapshot(nodeId);
128
+ // The API DTO stays dependency-light and structural; this viewer is the
129
+ // consumer that knows the complete broker snapshot contract.
130
+ initialSnapshot = saved.snapshot;
131
+ initialCommands = saved.commands;
132
+ }
133
+ }
134
+ catch (err) {
135
+ rethrowAsCliError(err, 'The node may be finalized or otherwise not attachable.');
136
+ }
137
+ // An offline parked focus has deliberately no socket to wait for.
136
138
  if (initialSnapshot === undefined)
137
139
  await preWaitForViewSocket(nodeId);
138
140
  transport = new RelayTransport(nodeId, { socketPath: apiSocketPath() });
@@ -144,6 +146,10 @@ hello) {
144
146
  /** One error shape for a connect-time failure, whether the connect race below
145
147
  * caught it or the deferred `assertConnected` checkpoint did. */
146
148
  const toAttachError = (err) => {
149
+ // An upgrade the daemon refused with an API error shows as that error, as the attach ensure it replaced did.
150
+ const refusal = err?.refusal;
151
+ if (refusal !== undefined)
152
+ return apiErrorToCliError(new ApiError(refusal.status, refusal.code, refusal.message), 'The node may be finalized or otherwise not attachable.');
147
153
  if (err instanceof BrokerUnavailableError) {
148
154
  return new InputError({
149
155
  error: 'no_broker',
@@ -190,7 +196,14 @@ hello) {
190
196
  socket.on('connect', onConnect);
191
197
  socket.on('error', onErr);
192
198
  socket.connect();
193
- }).catch((err) => {
199
+ }).catch(async (err) => {
200
+ // A Mac's upgrade refuses a parked node it was told not to wake: show its saved snapshot, offline, as a local parked focus does.
201
+ if (machine !== undefined && !wakeParked && String(err?.message).includes('node_dormant')) {
202
+ const saved = await cliClient().getSnapshot(nodeId).catch((e) => rethrowAsCliError(e, 'The node may be finalized or otherwise not attachable.'));
203
+ initialSnapshot = saved.snapshot;
204
+ initialCommands = saved.commands;
205
+ return;
206
+ }
194
207
  throw toAttachError(err);
195
208
  });
196
209
  // A broker listens before its session exists and answers `hello` only once it does. Wait for that answer here, so the caller's screen stays up and
@@ -136,7 +136,7 @@ const nodeBashBackground = defineLeaf({
136
136
  if (node === null) {
137
137
  throw new InputError({ error: 'not_found', message: `no node: ${id}`, next: 'List nodes with `crtr node inspect list`.' });
138
138
  }
139
- const jobs = backgroundRunningBashJobs(node.paths.context_dir);
139
+ const jobs = backgroundRunningBashJobs(contextDir(node.node_id, node.grantee));
140
140
  const now = Date.now();
141
141
  const elapsed = jobs.map((job) => ({ job_id: job.jobId, elapsed_ms: now - (jobStartedAtMs(job.jobId) ?? now) }));
142
142
  // No tmux toast. A tmux status-line message commandeers the whole client's
@@ -10,7 +10,7 @@ import { EventEmitter } from 'node:events';
10
10
  import { WebSocket } from 'ws';
11
11
  import { classify } from '../fault-classifier.js';
12
12
  import { AttachRefusedError, BrokerUnavailableError } from './transport.js';
13
- function relayUrl(target, nodeId) {
13
+ function relayUrl(target, nodeId, wakeParked) {
14
14
  if ('socketPath' in target) {
15
15
  return `ws+unix://${target.socketPath}:/v1/nodes/${encodeURIComponent(nodeId)}/attach?revive=0`;
16
16
  }
@@ -20,24 +20,30 @@ function relayUrl(target, nodeId) {
20
20
  // A person typed `crtr surface attach` at this node, so an exact parked
21
21
  // resident is woken for it — the same thing the LOCAL attach ensure does for
22
22
  // a direct attach. The bridge leaves a parked node parked without this, which
23
- // is what a product page reconnecting its viewport wants.
24
- url.search = '?wakeParked=1';
23
+ // is what a product page reconnecting its viewport wants, and what a focus
24
+ // of a parked node wants for its first dial.
25
+ url.search = wakeParked ? '?wakeParked=1' : '';
25
26
  url.hash = '';
26
27
  return url.toString();
27
28
  }
28
29
  export class RelayTransport extends EventEmitter {
29
30
  nodeId;
30
31
  target;
32
+ wakeParked;
31
33
  ws;
32
34
  closeEmitted = false;
33
- constructor(nodeId, target) {
35
+ constructor(nodeId, target,
36
+ /** Whether the first dial wakes an exact parked resident; every redial does. */
37
+ wakeParked = true) {
34
38
  super();
35
39
  this.nodeId = nodeId;
36
40
  this.target = target;
41
+ this.wakeParked = wakeParked;
37
42
  }
38
43
  refusal;
44
+ refusalError;
39
45
  get url() {
40
- return relayUrl(this.target, this.nodeId);
46
+ return relayUrl(this.target, this.nodeId, this.wakeParked);
41
47
  }
42
48
  dial() {
43
49
  const ws = new WebSocket(this.url, {
@@ -51,6 +57,7 @@ export class RelayTransport extends EventEmitter {
51
57
  text += c.toString(); });
52
58
  res.on('end', () => {
53
59
  this.refusal = refusalMessage(res.statusCode, text);
60
+ this.refusalError = refusalOf(res.statusCode, text);
54
61
  ws.terminate();
55
62
  });
56
63
  });
@@ -68,6 +75,7 @@ export class RelayTransport extends EventEmitter {
68
75
  }
69
76
  /** Re-dial the same daemon attach endpoint after a broker replacement. */
70
77
  redial(_options) {
78
+ this.wakeParked = true;
71
79
  this.destroy();
72
80
  this.closeEmitted = false;
73
81
  return new Promise((resolve, reject) => {
@@ -93,7 +101,7 @@ export class RelayTransport extends EventEmitter {
93
101
  catch {
94
102
  /* ignore */
95
103
  }
96
- reject(this.refusal === undefined ? err : new Error(this.refusal));
104
+ reject(this.refusal === undefined ? err : Object.assign(new Error(this.refusal), { refusal: this.refusalError }));
97
105
  });
98
106
  ws.on('close', (code, reason) => {
99
107
  if (!settled)
@@ -139,7 +147,7 @@ export class RelayTransport extends EventEmitter {
139
147
  this.emit('frame', frame);
140
148
  }
141
149
  onError(err) {
142
- this.emitError(new Error(`relay transport error: ${this.refusal ?? err.message}`));
150
+ this.emitError(Object.assign(new Error(`relay transport error: ${this.refusal ?? err.message}`), { refusal: this.refusalError }));
143
151
  // 'close' follows 'error'; teardown converges there.
144
152
  }
145
153
  /** A 1008 invalid-id close or a 1011 whose reason starts with "no running
@@ -174,6 +182,15 @@ export class RelayTransport extends EventEmitter {
174
182
  this.emit('error', err);
175
183
  }
176
184
  }
185
+ function refusalOf(status, body) {
186
+ try {
187
+ const e = JSON.parse(body).error;
188
+ if (status !== undefined && typeof e?.code === 'string')
189
+ return { status, code: e.code, message: typeof e.message === 'string' ? e.message : '' };
190
+ }
191
+ catch { /* not JSON */ }
192
+ return undefined;
193
+ }
177
194
  /** `409 broker_not_ready: <message>` from a refused upgrade's `{error:{code,message}}` body. */
178
195
  export function refusalMessage(status, body) {
179
196
  try {
@@ -1,11 +1,6 @@
1
- // src/core/runtime/runner/machine/runner.ts — the remote machine runner (design-import I13): the third runner, for a node whose
2
- // profile's environment is kind `machine` and that machine is not this process's own host. Every method is one `callMachine`
3
- // to the Mac over its link; the Mac executes it with `machine/executor.ts`.
4
- //
5
- // The node token is minted HERE, in the control plane (the Mac has no database to mint it in) and travels in the `start` call.
6
- // `wake` and `stop` throw `machine_offline` untouched where the caller can wait; `stop` and `status` fold a failed call into
7
- // `confirmed: false` / `unknown` as the runner interface requires (the caller leaves everything as it is and retries).
1
+ import { getNode } from '../../../canvas/canvas.js';
8
2
  import { openDb } from '../../../canvas/db.js';
3
+ import { personIdAsync } from '../../../canvas/person.js';
9
4
  import { mintExecutionToken } from '../../../canvas/node-tokens.js';
10
5
  import { callMachine } from './call.js';
11
6
  import { machineEnvironmentOfProfile } from './environment.js';
@@ -21,6 +16,12 @@ const defaultEnvironmentOf = async (nodeId) => {
21
16
  throw new Error(`node ${nodeId} has no machine environment`);
22
17
  return environment;
23
18
  };
19
+ const defaultBundle = async (input) => {
20
+ // Loaded here: the handler imports the runtime that imports this module.
21
+ const { buildStartBundle } = await import('../../../../daemon/api/handlers/execution-start.js');
22
+ const node = await getNode(input.nodeId);
23
+ return await buildStartBundle({ nodeId: input.nodeId, app: node?.grantee ?? 'app:terminal', sub: node?.sub ?? await personIdAsync(), launchJson: input.launchJson, runner: 'machine' });
24
+ };
24
25
  const asError = (error) => error instanceof Error ? error : new Error(String(error));
25
26
  export function createMachineRunner(deps = {}) {
26
27
  const environmentOf = deps.environmentOf ?? defaultEnvironmentOf;
@@ -28,9 +29,10 @@ export function createMachineRunner(deps = {}) {
28
29
  kind: 'machine',
29
30
  async start(input) {
30
31
  const environment = await environmentOf(input.nodeId);
32
+ const bundle = await (deps.bundle ?? defaultBundle)(input);
31
33
  const nodeToken = await (deps.mintToken ?? ((i) => mintExecutionToken(i.executionId, i.nodeId)))(input);
32
34
  try {
33
- const result = await callMachine(environment, 'start', { ...input, nodeToken });
35
+ const result = await callMachine(environment, 'start', { ...input, nodeToken, bundle });
34
36
  return { pid: result.pid, exited: null };
35
37
  }
36
38
  catch (error) {
@@ -115,17 +115,18 @@ class ForwardedViewLink extends EventEmitter {
115
115
  this.emit('close', this.failed);
116
116
  }
117
117
  }
118
- /** One readiness check: the Mac connected the node's view.sock within `timeoutMs`. */
119
- export function probeMachineView(environmentId, nodeId, timeoutMs) {
118
+ /** One readiness check: the Mac connected the node's view.sock within `timeoutMs`. The channel that connected is returned open, for the caller to use or destroy; null when it did not connect. */
119
+ function openReadyMachineView(environmentId, nodeId, timeoutMs) {
120
120
  return new Promise((resolve) => {
121
121
  const view = openMachineView(environmentId, nodeId);
122
- const timer = setTimeout(() => { resolve(false); view.destroy(); }, timeoutMs);
123
- view.on('connect', () => { clearTimeout(timer); resolve(true); view.destroy(); });
122
+ const timer = setTimeout(() => { resolve(null); view.destroy(); }, timeoutMs);
123
+ // The no-op error listener stays on the returned channel until its user attaches its own: an error before then must not throw.
124
124
  view.on('error', () => { });
125
- view.on('close', () => { clearTimeout(timer); resolve(false); });
125
+ view.on('connect', () => { clearTimeout(timer); resolve(view); });
126
+ view.on('close', () => { clearTimeout(timer); resolve(null); });
126
127
  });
127
128
  }
128
- /** Wait for the node's broker on the Mac to accept a viewer, retrying while its view.sock refuses; false on the deadline or when the launch exits. */
129
+ /** Wait for the node's broker on the Mac to accept a viewer, retrying while its view.sock refuses; the accepted channel, open, or null on the deadline or when the launch exits. A caller that does not use the channel destroys it. */
129
130
  export async function waitForMachineView(environmentId, nodeId, exited, waitMs) {
130
131
  const deadline = Date.now() + waitMs;
131
132
  let exitSeen = false;
@@ -133,15 +134,15 @@ export async function waitForMachineView(environmentId, nodeId, exited, waitMs)
133
134
  // Each attempt's length and outcome land in the calling request's step timings (`probe_<n>_ready_ms` / `probe_<n>_failed_ms`), and `ready_received_at` marks the first ready.
134
135
  for (let attempt = 1; Date.now() <= deadline && !exitSeen; attempt++) {
135
136
  const started = performance.now();
136
- const ready = await probeMachineView(environmentId, nodeId, Math.max(1, Math.min(2000, deadline - Date.now())));
137
- addStepTiming(`probe_${attempt}_${ready ? 'ready' : 'failed'}_ms`, performance.now() - started);
138
- if (ready) {
137
+ const ready = await openReadyMachineView(environmentId, nodeId, Math.max(1, Math.min(2000, deadline - Date.now())));
138
+ addStepTiming(`probe_${attempt}_${ready !== null ? 'ready' : 'failed'}_ms`, performance.now() - started);
139
+ if (ready !== null) {
139
140
  markAt('ready_received');
140
- return true;
141
+ return ready;
141
142
  }
142
143
  await new Promise((resolve) => setTimeout(resolve, 250));
143
144
  }
144
- return false;
145
+ return null;
145
146
  }
146
147
  /** The environment id of a forwarded viewer upgrade path, or null for any other path. */
147
148
  export function machineViewEnvironment(req) {
@@ -18,6 +18,8 @@ import { storeJobReport } from '../api/handlers/bash-jobs.js';
18
18
  import { APIError } from '../../api/errors.js';
19
19
  import { brokerSignalBus } from '../broker-signals/bus.js';
20
20
  import { verifyMachineCredential } from './credential.js';
21
+ import { compareReleaseVersions, RUNTIME_VERSION_HEADER } from '../../api/runtime-version.js';
22
+ import { crtrVersion } from '../../shared/crtr-version.js';
21
23
  import { CLOSE_REVOKED, CLOSE_SUPERSEDED, LINK_MAX_PAYLOAD_BYTES, parseFrame } from './frames.js';
22
24
  export const LINK_LEASE_MS = 45_000;
23
25
  export const LINK_RENEW_MS = 15_000;
@@ -295,6 +297,9 @@ export async function handleMachineLinkUpgrade(req, socket, head, environmentId)
295
297
  const token = /^Bearer (\S+)$/.exec(Array.isArray(header) ? header[0] ?? '' : header ?? '')?.[1];
296
298
  if (token === undefined || !await verifyMachineCredential(environmentId, token))
297
299
  return { status: 401, text: 'Unauthorized', code: 'unauthorized', message: 'machine credential refused' };
300
+ // A Mac older than this control plane (or naming no release) may lack an op it would be sent: it installs crtrVersion() and links again. A newer one links.
301
+ if (compareReleaseVersions(String(req.headers[RUNTIME_VERSION_HEADER.toLowerCase()] ?? ''), crtrVersion()) < 0)
302
+ return { status: 426, text: 'Upgrade Required', code: 'machine_release_behind', message: crtrVersion() };
298
303
  const now = new Date().toISOString();
299
304
  const db = await openDb();
300
305
  const row = await db.prepare(`INSERT INTO machine_links (environment, generation, api_address, connected_at, lease_expires_at) VALUES (?, 1, ?, ?, ?)
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.695",
3
+ "version": "0.3.697",
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.695",
3
+ "version": "0.3.697",
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.695",
3
+ "version": "0.3.697",
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.695",
31
- "@north-light/identity": "0.3.695"
30
+ "@north-light/api": "0.3.697",
31
+ "@north-light/identity": "0.3.697"
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.695",
3
+ "version": "0.3.697",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.695",
9
+ "version": "0.3.697",
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.695",
32
- "@north-light/plugin": "0.3.695",
31
+ "@north-light/identity": "0.3.697",
32
+ "@north-light/plugin": "0.3.697",
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.695",
10670
+ "version": "0.3.697",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.695",
10675
+ "version": "0.3.697",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.695",
10680
+ "version": "0.3.697",
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.695",
10688
+ "version": "0.3.697",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.695",
10692
- "@north-light/identity": "0.3.695"
10691
+ "@north-light/api": "0.3.697",
10692
+ "@north-light/identity": "0.3.697"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.695",
10697
+ "version": "0.3.697",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.695",
10701
- "@north-light/identity": "0.3.695",
10702
- "@north-light/plugin": "0.3.695",
10700
+ "@north-light/api": "0.3.697",
10701
+ "@north-light/identity": "0.3.697",
10702
+ "@north-light/plugin": "0.3.697",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {
@@ -26,8 +26,12 @@ function run(command, args, options) {
26
26
  return result;
27
27
  }
28
28
 
29
- function latestArchive(directory) {
30
- const result = run('npm', ['pack', `${PACKAGE_NAME}@latest`, '--json', '--pack-destination', directory], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] });
29
+ // `--version <x.y.z>` installs that exact release (an imported Mac's machine daemon matching its control plane); otherwise `latest`.
30
+ const versionAt = process.argv.indexOf('--version');
31
+ const wanted = versionAt === -1 ? 'latest' : process.argv[versionAt + 1];
32
+
33
+ function releaseArchive(directory) {
34
+ const result = run('npm', ['pack', `${PACKAGE_NAME}@${wanted}`, '--json', '--pack-destination', directory], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] });
31
35
  const packed = JSON.parse(result.stdout);
32
36
  if (!Array.isArray(packed) || typeof packed[0]?.filename !== 'string') throw new Error('npm pack did not report an archive');
33
37
  return join(directory, packed[0].filename);
@@ -35,7 +39,7 @@ function latestArchive(directory) {
35
39
 
36
40
  const temporary = mkdtempSync(join(tmpdir(), 'crtr-self-update-'));
37
41
  try {
38
- const archive = latestArchive(temporary);
42
+ const archive = releaseArchive(temporary);
39
43
  const release = join(temporary, 'package');
40
44
  mkdirSync(release);
41
45
  run('tar', ['-xzf', archive, '--strip-components=1', '-C', release]);