@north-light/cli 0.3.694 → 0.3.696

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 (189) hide show
  1. package/README.md +4 -7
  2. package/dist/api/command-manifest/result.d.ts +5 -5
  3. package/dist/api/command-manifest/result.js +1 -1
  4. package/dist/api/contract.d.ts +1 -1
  5. package/dist/api/contract.js +1 -1
  6. package/dist/api/dto/run-events.d.ts +1 -0
  7. package/dist/api/dto/run-events.js +1 -0
  8. package/dist/api/dto/worktree.d.ts +0 -4
  9. package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
  10. package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
  11. package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
  12. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  13. package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
  14. package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
  15. package/dist/builtin-memory/crouter-sdk/README.md +14 -42
  16. package/dist/builtin-memory/crouter-sdk/client.md +5 -7
  17. package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
  18. package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
  19. package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
  20. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  21. package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
  22. package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
  23. package/dist/clients/attach/session/connection.d.ts +11 -2
  24. package/dist/clients/attach/session/connection.js +1 -1
  25. package/dist/clients/attach/session/keys.d.ts +2 -0
  26. package/dist/clients/attach/session/keys.js +1 -1
  27. package/dist/clients/attach/session/pane-tag.d.ts +3 -3
  28. package/dist/clients/attach/session/reconnect.js +1 -1
  29. package/dist/clients/attach/viewer.js +539 -538
  30. package/dist/commands/node-worktree.js +1 -1
  31. package/dist/commands/surface/node/placement.d.ts +2 -2
  32. package/dist/commands/surface/node/placement.js +1 -1
  33. package/dist/commands/surface.js +1 -1
  34. package/dist/core/broker-client/client.d.ts +6 -9
  35. package/dist/core/broker-client/client.js +1 -1
  36. package/dist/core/broker-client/transport-relay.d.ts +12 -1
  37. package/dist/core/broker-client/transport-relay.js +1 -1
  38. package/dist/core/canvas/canvas.js +5 -5
  39. package/dist/core/canvas/types.d.ts +0 -2
  40. package/dist/core/conversation-store/row-store.js +10 -10
  41. package/dist/core/graph/names.js +9 -9
  42. package/dist/core/keybindings/attach-control.d.ts +3 -0
  43. package/dist/core/keybindings/attach-control.js +1 -1
  44. package/dist/core/keybindings/catalog.js +1 -1
  45. package/dist/core/ledger/chunks.d.ts +3 -1
  46. package/dist/core/ledger/chunks.js +2 -2
  47. package/dist/core/ledger/index.d.ts +1 -1
  48. package/dist/core/ledger/index.js +1 -1
  49. package/dist/core/ledger/read.d.ts +4 -0
  50. package/dist/core/ledger/read.js +2 -2
  51. package/dist/core/llm/run.js +2 -2
  52. package/dist/core/logged-step-timings.d.ts +7 -0
  53. package/dist/core/logged-step-timings.js +1 -0
  54. package/dist/core/permissions/evaluator.d.ts +2 -1
  55. package/dist/core/permissions/evaluator.js +2 -2
  56. package/dist/core/providers/receipts.js +1 -1
  57. package/dist/core/runs/operations.js +8 -8
  58. package/dist/core/runtime/broker/model-adapter.js +3 -3
  59. package/dist/core/runtime/broker.js +1 -1
  60. package/dist/core/runtime/nodes.d.ts +1 -1
  61. package/dist/core/runtime/nodes.js +1 -1
  62. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  63. package/dist/core/runtime/placement-tmux.js +1 -1
  64. package/dist/core/runtime/revive.js +2 -2
  65. package/dist/core/runtime/runner/machine/executor.d.ts +0 -3
  66. package/dist/core/runtime/runner/machine/executor.js +1 -1
  67. package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
  68. package/dist/core/runtime/runner/machine/ops.d.ts +7 -13
  69. package/dist/core/runtime/runner/machine/ops.js +1 -1
  70. package/dist/core/runtime/runner/machine/runner.d.ts +3 -2
  71. package/dist/core/runtime/runner/machine/runner.js +1 -1
  72. package/dist/core/runtime/tmux-bindings.js +3 -3
  73. package/dist/core/runtime/tmux-driver.d.ts +0 -10
  74. package/dist/core/runtime/tmux-driver.js +6 -6
  75. package/dist/core/step-timings.d.ts +7 -1
  76. package/dist/core/step-timings.js +1 -1
  77. package/dist/core/worktree-close.js +4 -6
  78. package/dist/core/worktree-landing.d.ts +0 -38
  79. package/dist/core/worktree-landing.js +2 -3
  80. package/dist/core/worktree-sweep.d.ts +0 -1
  81. package/dist/core/worktree-sweep.js +4 -6
  82. package/dist/core/worktree.d.ts +0 -4
  83. package/dist/core/worktree.js +13 -15
  84. package/dist/daemon/api/app-listener.d.ts +1 -0
  85. package/dist/daemon/api/app-listener.js +10 -10
  86. package/dist/daemon/api/bridge.js +5 -5
  87. package/dist/daemon/api/handlers/attach.js +1 -1
  88. package/dist/daemon/api/handlers/conversations.js +3 -3
  89. package/dist/daemon/api/server.d.ts +1 -1
  90. package/dist/daemon/api/server.js +1 -1
  91. package/dist/daemon/cron/armed-context.js +1 -1
  92. package/dist/daemon/crtrd.js +20 -18
  93. package/dist/daemon/machine-daemon.js +1 -1
  94. package/dist/daemon/machine-link/client.d.ts +7 -1
  95. package/dist/daemon/machine-link/client.js +1 -1
  96. package/dist/daemon/machine-link/forward.d.ts +2 -4
  97. package/dist/daemon/machine-link/forward.js +1 -1
  98. package/dist/daemon/machine-link/holder.js +5 -5
  99. package/dist/daemon/pidfile.js +2 -1
  100. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  101. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  102. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +1 -1
  103. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +2 -2
  104. package/dist/daemon/runs/append-section.js +2 -2
  105. package/dist/daemon/runs/observer.js +3 -3
  106. package/docs/apps/guides/stream-a-run.md +6 -7
  107. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  108. package/docs/concepts/nodes-and-the-canvas.md +2 -2
  109. package/docs/concepts/profiles-kinds-and-modes.md +1 -1
  110. package/docs/concepts/scopes-and-trust.md +1 -1
  111. package/docs/concepts/why-a-daemon.md +1 -1
  112. package/docs/sdk/README.md +13 -41
  113. package/docs/sdk/client.md +5 -7
  114. package/docs/sdk/docker.md +1 -1
  115. package/docs/sdk/errors.md +3 -43
  116. package/docs/sdk/getting-started.md +11 -83
  117. package/docs/sdk/release-notes.md +10 -0
  118. package/docs/sdk/resources.md +11 -44
  119. package/package.json +3 -3
  120. package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
  121. package/packages/crouter-api/dist/api/contract.js +1 -1
  122. package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
  123. package/packages/crouter-api/dist/clients/attach/session/connection.js +73 -25
  124. package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
  125. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
  126. package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
  127. package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
  128. package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
  129. package/packages/crouter-api/dist/commands/surface.js +2 -3
  130. package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
  131. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +24 -7
  132. package/packages/crouter-api/dist/core/canvas/canvas.js +2 -3
  133. package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
  134. package/packages/crouter-api/dist/core/graph/names.js +7 -20
  135. package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
  136. package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
  137. package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
  138. package/packages/crouter-api/dist/core/ledger/index.js +1 -1
  139. package/packages/crouter-api/dist/core/ledger/read.js +18 -1
  140. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  141. package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
  142. package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
  143. package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
  144. package/packages/crouter-api/dist/core/runs/operations.js +5 -4
  145. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
  146. package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
  147. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
  148. package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
  149. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
  150. package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +14 -32
  151. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
  152. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
  153. package/packages/crouter-api/dist/core/step-timings.js +7 -2
  154. package/packages/crouter-api/dist/core/worktree-close.js +5 -51
  155. package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
  156. package/packages/crouter-api/dist/core/worktree.js +9 -74
  157. package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
  158. package/packages/crouter-api/dist/daemon/machine-link/forward.js +22 -10
  159. package/packages/crouter-api/dist/daemon/machine-link/holder.js +7 -0
  160. package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
  161. package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
  162. package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
  163. package/packages/crouter-api/package.json +1 -1
  164. package/packages/crouter-identity/package.json +1 -1
  165. package/packages/crouter-plugin/dist/serve.js +1 -1
  166. package/packages/crouter-plugin/package.json +3 -3
  167. package/runtime.lock.json +14 -14
  168. package/scripts/self-update.mjs +7 -3
  169. package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
  170. package/dist/builtin-memory/crouter-sdk/files.md +0 -50
  171. package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
  172. package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
  173. package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
  174. package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
  175. package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
  176. package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
  177. package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
  178. package/dist/commands/surface-reload.d.ts +0 -7
  179. package/dist/commands/surface-reload.js +0 -1
  180. package/docs/sdk/bash.md +0 -39
  181. package/docs/sdk/files.md +0 -49
  182. package/docs/sdk/guides/README.md +0 -17
  183. package/docs/sdk/guides/event-driven-assistant.md +0 -24
  184. package/docs/sdk/guides/fan-out-pipeline.md +0 -24
  185. package/docs/sdk/guides/human-approval.md +0 -24
  186. package/docs/sdk/guides/typed-extraction.md +0 -24
  187. package/docs/sdk/nodes.md +0 -194
  188. package/docs/sdk/streaming.md +0 -149
  189. package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
@@ -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 x=Object.defineProperty;var a=(s,e)=>x(s,"name",{value:e,configurable:!0});import{EventEmitter as b}from"node:events";import{createHmac as A,timingSafeEqual as I}from"node:crypto";import{WebSocket as l,WebSocketServer as P}from"ws";import{openDb as R}from"../../core/canvas/db.js";import{loadSecretsKey as k}from"../../core/secrets/key.js";import{LINK_MAX_PAYLOAD_BYTES as _,parseFrame as v}from"./frames.js";import{apiAddress as B,heldLinkOf as g,MachineViewLink as E,UNROUTABLE_PREFIX as O}from"./holder.js";const w=8*1024*1024,T=1013,D=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/view$/,L=new P({noServer:!0,maxPayload:_}),S=a(s=>A("sha256",k().key).update(`machine-view:${s}`).digest("hex"),"forwardToken");function $(s,e){const r=g(s);return r!==null?new E(r,e):new q(s,e)}a($,"openMachineView");class q extends b{static{a(this,"ForwardedViewLink")}environmentId;nodeId;ws;ended=!1;failed=!1;queued=[];queuedBytes=0;constructor(e,r){super(),this.environmentId=e,this.nodeId=r,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!==l.OPEN?(this.queuedBytes+=e.length,this.queuedBytes>w?(this.finish("machine view: the holder did not accept the channel before its queue filled"),!1):(this.queued.push(e),!0)):this.ws.bufferedAmount>w?(this.finish("machine view: the holder is not draining the channel"),!1):(this.sendData(e),!0)}destroy(){return this.ended||(this.ws?.readyState===l.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 R()).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(O))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===B())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 t=new l(r.toString(),{headers:{authorization:`Bearer ${S(this.environmentId)}`},maxPayload:_});this.ws=t,t.on("open",()=>{for(const n of this.queued.splice(0))this.sendData(n)}),t.on("unexpected-response",(n,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}`)}),t.on("message",n=>{const i=v(n);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))}),t.on("error",n=>this.finish(n.message)),t.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 M(s,e,r){return new Promise(t=>{const n=$(s,e),i=setTimeout(()=>{t(!1),n.destroy()},r);n.on("connect",()=>{clearTimeout(i),t(!0),n.destroy()}),n.on("error",()=>{}),n.on("close",()=>{clearTimeout(i),t(!1)})})}a(M,"probeMachineView");async function J(s,e,r,t){const n=Date.now()+t;let i=!1;for(r?.then(()=>{i=!0});Date.now()<=n&&!i;){if(await M(s,e,Math.max(1,Math.min(2e3,n-Date.now()))))return!0;await new Promise(c=>setTimeout(c,250))}return!1}a(J,"waitForMachineView");function Y(s){const e=D.exec(new URL(s.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Y,"machineViewEnvironment");function K(s,e,r,t){const n=s.headers.authorization,i=/^Bearer (\S+)$/.exec(Array.isArray(n)?n[0]??"":n??"")?.[1]??"",c=Buffer.from(S(t)),p=Buffer.from(i);if(p.length!==c.length||!I(p,c))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine view forward credential refused"};const f=new URL(s.url??"/","http://runtime.local").searchParams.get("node");if(f===null||f==="")return{status:400,text:"Bad Request",code:"bad_request",message:"node is required"};const y=g(t);return y===null?{status:409,text:"Conflict",code:"machine_offline",message:"this API process holds no link for the machine"}:(L.handleUpgrade(s,e,r,d=>{const o=new E(y,f),u=a(h=>{d.readyState===l.OPEN&&d.send(JSON.stringify(h))},"send");o.on("connect",()=>u({type:"view.ready",channel:""})),o.on("data",h=>{if(d.bufferedAmount>w){o.destroy(),d.close(T,"viewer too slow");return}u({type:"view.data",channel:"",bytes:h.toString("base64")})}),o.on("error",h=>u({type:"view.close",channel:"",error:h.message})),o.on("close",()=>d.close()),d.on("message",h=>{const m=v(h);m?.type==="view.data"?o.write(Buffer.from(m.bytes,"base64")):m?.type==="view.close"&&o.destroy()}),d.on("close",()=>o.destroy()),d.on("error",()=>o.destroy())}),null)}a(K,"handleMachineViewUpgrade");export{w as VIEW_BUFFER_LIMIT_BYTES,K as handleMachineViewUpgrade,Y as machineViewEnvironment,$ as openMachineView,M as probeMachineView,J 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 T}from"../reconcilers/live-obligation.js";import{EventEmitter as _}from"node:events";import{hostname as y}from"node:os";import{randomUUID as I}from"node:crypto";import{WebSocket as L,WebSocketServer as b}from"ws";import{openDb as r}from"../../core/canvas/db.js";import{emitEvent as m}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}${y()}:${process.pid}`,"apiAddress"),u=s(()=>new Date(Date.now()+W).toISOString(),"lease");class J extends _{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){m({level:"error",event:e,fields:{environment:this.environmentId},error:n})}send(e){return this.ws.readyState!==L.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 T()).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}`),m({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 _{static{s(this,"MachineViewLink")}link;ended=!1;failed=!1;channel=I();constructor(e,n){super(),this.link=e,e.channels.set(this.channel,this),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 fe(i){const e=z.exec(new URL(i.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}s(fe,"machineLinkEnvironment");async function _e(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 f=Number(D.generation);return e.destroyed?(await d.prepare("DELETE FROM machine_links WHERE environment = ? AND generation = ?").run(t,f),null):(B.handleUpgrade(i,e,n,A=>{const h=new J(t,f,A,o),N=c.get(t);c.set(t,h),N?.ws.close(g,"superseded"),h.start(),h.claim().catch(k=>m({level:"error",event:"daemon.machine_link.claim_failed",fields:{environment:t},error:k}))}),null)}s(_e,"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,_e as handleMachineLinkUpgrade,ue as heldLinkOf,fe 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 +1,2 @@
1
- var o=Object.defineProperty;var i=(r,n)=>o(r,"name",{value:n,configurable:!0});import{existsSync as m,readFileSync as u}from"node:fs";import{join as f}from"node:path";import{crtrHome as p}from"../core/canvas/paths.js";import{isPidAlive as e}from"../core/canvas/pid.js";import{envPidfileOverride as c}from"../shared/env.js";function l(){return c()??f(p(),"crtrd.pid")}i(l,"pidfilePath");function d(){const r=l();if(!m(r))return null;const n=u(r,"utf8").trim(),t=Number(n);return Number.isFinite(t)&&t>0?t:null}i(d,"readPidfile");function y(){const r=d();return r!==null&&e(r)}i(y,"isDaemonRunning");export{y as isDaemonRunning,e as isPidAlive,l as pidfilePath,d as readPidfile};
1
+ var o=Object.defineProperty;var i=(r,n)=>o(r,"name",{value:n,configurable:!0});import{existsSync as m,readFileSync as p}from"node:fs";import{join as u}from"node:path";import{crtrHome as f}from"../core/canvas/paths.js";import{isPidAlive as e}from"../core/canvas/pid.js";import{envPidfileOverride as l}from"../shared/env.js";function c(){return l()??u(f(),"crtrd.pid")}i(c,"pidfilePath");function d(){const r=c();if(!m(r))return null;const n=p(r,"utf8").split(`
2
+ `,1)[0].trim(),t=Number(n);return Number.isFinite(t)&&t>0?t:null}i(d,"readPidfile");function y(){const r=d();return r!==null&&e(r)}i(y,"isDaemonRunning");export{y as isDaemonRunning,e as isPidAlive,c as pidfilePath,d as readPidfile};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var o=(e,t)=>E(e,"name",{value:t,configurable:!0});import{getNode as _,getRow as m}from"../../core/canvas/index.js";import{managedWorktreeSweepCandidates as k}from"../../core/canvas/managed-worktree-sweep-candidates.js";import{isSafeNodeId as h}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as y,recordedPidLiveness as S}from"../../core/canvas/pid.js";import{emitEvent as c}from"../../core/events/emit.js";import{operationIdContext as f}from"../../core/events/operation-id.js";import{reconcileManagedWorktree as v}from"../../core/worktree-sweep.js";import{runThrottledLane as R}from"./throttled-lane.js";const T=60*1e3,W=300*1e3,I=3,b=["done","dead","canceled"];function w(e){return b.includes(e.status)}o(w,"isTerminal");function g(e,t){return t?.state==="closed"||t?.state==="open"&&e.status==="done"&&e.final_report!==null}o(g,"hasSweepDisposition");async function L(e,t,i){return await t.isClaimed(e.node_id)||e.frozen_at!==null||!w(e)||!g(e,(await _(e.node_id))?.managed_worktree)?!1:S(e.pi_pid,e.pi_pid_identity,i)==="dead"}o(L,"engineIsGone");function M(e,t){const i=e.node_id,s=e.pi_pid,r=e.pi_pid_identity;return{stillEligible:o(async()=>{if(await t.isClaimed(i))return!1;const a=await m(i);return a===null||!w(a)||a.frozen_at!==null||!g(a,(await _(i))?.managed_worktree)?!1:a.pi_pid===s&&a.pi_pid_identity===r},"stillEligible")}}o(M,"eligibilityGuard");class z{static{o(this,"ManagedWorktreeSweepReconciler")}run(t,i){if(!i.lifecycle.acceptsDetachedWork())return;const s=R("managed-worktree-sweep","",t,T,W,r=>this.sweep(t,i.fleet,r)).then(()=>{}).catch(r=>{f.fresh(()=>c({level:"error",event:"worktree.sweep.failed",error:r}))});i.lifecycle.registerDetached(s)}async candidates(t){try{return await k(t)}catch(i){return f.fresh(()=>{c({level:"error",event:"worktree.sweep.scan_failed",error:i})}),null}}async sweep(t,i,s){const r=await this.candidates(t);if(r===null||r.length===0)return;let a=Number(s.state??0);(!Number.isInteger(a)||a>=r.length)&&(a=0);const d=Math.min(I,r.length),n=[];for(let l=0;l<d;l+=1)n.push(r[(a+l)%r.length]);if(!await s.save(String((a+d)%r.length)))return;const p=await y();if(p!==null)for(const l of n){const u=await m(l);if(!(u===null||!await L(u,i,p))){if(!await s.holds())return;await this.reconcileOne(u,t,i)}}}async reconcileOne(t,i,s){const r=t.node_id,a=h(r)?{node_id:r}:{},d=h(r)?{}:{affected_node_id:r};try{const n=await v(r,M(t,s),i);f.fresh(()=>{if(n.status==="complete"){c({level:"info",event:"worktree.sweep.reconciled",outcome:"succeeded",...a,fields:{...d,...n.stash===void 0?{}:{base_checkout_stash:n.stash}}});return}n.status!=="skipped"&&(n.status==="refused"&&n.unchanged===!0||c({level:n.status==="failed"?"error":"warn",event:n.status==="failed"?"worktree.sweep.failed":"worktree.sweep.refused",outcome:n.status==="failed"?"failed":"skipped",...a,fields:{...d,reason:n.reason,...n.detail===void 0?{}:{detail:n.detail}}}))})}catch(n){f.fresh(()=>{c({level:"error",event:"worktree.sweep.failed",...a,error:n,fields:d})})}}}export{z as ManagedWorktreeSweepReconciler,I as WORKTREE_SWEEP_BUDGET,T as WORKTREE_SWEEP_INTERVAL_MS};
1
+ var E=Object.defineProperty;var o=(e,t)=>E(e,"name",{value:t,configurable:!0});import{getNode as m,getRow as _}from"../../core/canvas/index.js";import{managedWorktreeSweepCandidates as k}from"../../core/canvas/managed-worktree-sweep-candidates.js";import{isSafeNodeId as h}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as y,recordedPidLiveness as S}from"../../core/canvas/pid.js";import{emitEvent as c}from"../../core/events/emit.js";import{operationIdContext as f}from"../../core/events/operation-id.js";import{reconcileManagedWorktree as v}from"../../core/worktree-sweep.js";import{runThrottledLane as R}from"./throttled-lane.js";const T=60*1e3,W=300*1e3,I=3,L=["done","dead","canceled"];function w(e){return L.includes(e.status)}o(w,"isTerminal");function g(e,t){return t?.state==="closed"||t?.state==="open"&&e.status==="done"&&e.final_report!==null}o(g,"hasSweepDisposition");async function M(e,t,n){return await t.isClaimed(e.node_id)||e.frozen_at!==null||!w(e)||!g(e,(await m(e.node_id))?.managed_worktree)?!1:S(e.pi_pid,e.pi_pid_identity,n)==="dead"}o(M,"engineIsGone");function N(e,t){const n=e.node_id,s=e.pi_pid,r=e.pi_pid_identity;return{stillEligible:o(async()=>{if(await t.isClaimed(n))return!1;const i=await _(n);return i===null||!w(i)||i.frozen_at!==null||!g(i,(await m(n))?.managed_worktree)?!1:i.pi_pid===s&&i.pi_pid_identity===r},"stillEligible")}}o(N,"eligibilityGuard");class z{static{o(this,"ManagedWorktreeSweepReconciler")}run(t,n){if(!n.lifecycle.acceptsDetachedWork())return;const s=R("managed-worktree-sweep","",t,T,W,r=>this.sweep(t,n.fleet,r)).then(()=>{}).catch(r=>{f.fresh(()=>c({level:"error",event:"worktree.sweep.failed",error:r}))});n.lifecycle.registerDetached(s)}async candidates(t){try{return await k(t)}catch(n){return f.fresh(()=>{c({level:"error",event:"worktree.sweep.scan_failed",error:n})}),null}}async sweep(t,n,s){const r=await this.candidates(t);if(r===null||r.length===0)return;let i=Number(s.state??0);(!Number.isInteger(i)||i>=r.length)&&(i=0);const d=Math.min(I,r.length),a=[];for(let l=0;l<d;l+=1)a.push(r[(i+l)%r.length]);if(!await s.save(String((i+d)%r.length)))return;const p=await y();if(p!==null)for(const l of a){const u=await _(l);if(!(u===null||!await M(u,n,p))){if(!await s.holds())return;await this.reconcileOne(u,t,n)}}}async reconcileOne(t,n,s){const r=t.node_id,i=h(r)?{node_id:r}:{},d=h(r)?{}:{affected_node_id:r};try{const a=await v(r,N(t,s),n);f.fresh(()=>{if(a.status==="complete"){c({level:"info",event:"worktree.sweep.reconciled",outcome:"succeeded",...i,fields:d});return}a.status!=="skipped"&&(a.status==="refused"&&a.unchanged===!0||c({level:a.status==="failed"?"error":"warn",event:a.status==="failed"?"worktree.sweep.failed":"worktree.sweep.refused",outcome:a.status==="failed"?"failed":"skipped",...i,fields:{...d,reason:a.reason,...a.detail===void 0?{}:{detail:a.detail}}}))})}catch(a){f.fresh(()=>{c({level:"error",event:"worktree.sweep.failed",...i,error:a,fields:d})})}}}export{z as ManagedWorktreeSweepReconciler,I as WORKTREE_SWEEP_BUDGET,T as WORKTREE_SWEEP_INTERVAL_MS};
@@ -1 +1 @@
1
- var N=Object.defineProperty;var s=(i,e)=>N(i,"name",{value:e,configurable:!0});import{clearFrozen as f,getNode as y,getRow as D}from"../../../core/canvas/index.js";import{openDb as _}from"../../../core/canvas/db.js";import{fullName as z}from"../../../core/canvas/labels.js";import{isSafeNodeId as d}from"../../../core/canvas/paths.js";import{emitEvent as u}from"../../../core/events/emit.js";import{operationIdContext as L}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as T}from"../../../core/canvas/deliveries.js";import{publishNotice as C}from"../../../core/runtime/close.js";import{transition as p}from"../../../core/runtime/lifecycle.js";import{isStartRefusal as m}from"../../../core/runtime/start-check.js";import{EnvironmentImagePending as A}from"./remote-wake.js";import{asNodePerson as M}from"./node-person.js";import{MachineLaunchUncertainError as b,MachineOfflineError as w}from"../../../core/runtime/runner/machine/ops.js";import{commitReopenResident as I}from"../../../core/runtime/reopen.js";import{reviveNode as h}from"../../../core/runtime/revive.js";import{hasPendingWake as k}from"../live-obligation.js";import{readInterruptedTurn as O}from"../../../core/canvas/recovery.js";import{mapAsync as P}from"../../../core/async-array.js";const E=6,U=10*6e4,x=2e4;async function H(i){const e=await(await _()).prepare("SELECT idle_release_attempts, idle_release_last_attempt_at, idle_release_acked_count FROM nodes WHERE node_id = ?").get(i);return{attempts:Number(e?.idle_release_attempts??0),acknowledgedCount:Number(e?.idle_release_acked_count??0),lastAttempt:e?.idle_release_last_attempt_at==null?void 0:Date.parse(e.idle_release_last_attempt_at)}}s(H,"readEpisode");async function F(i,e,a,t,r){const n=await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ? AND idle_release_attempts = ?").run(a,new Date(r).toISOString(),t,i,e);return Number(n.changes)===1}s(F,"claimAttempt");async function W(i,e){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ?").run(e.attempts,e.lastAttempt===void 0?null:new Date(e.lastAttempt).toISOString(),e.acknowledgedCount,i)}s(W,"writeEpisode");function $(i,e){if(e)return 2;const a=i.launched_at;if(a==null)return 1;const t=i.last_settled_at;return t==null?2:Date.parse(t)>Date.parse(a)?1:2}s($,"thawTier");function B(i,e){const a=i.row.frozen_at,t=e.row.frozen_at;return a==null?t==null?0:1:t==null?-1:Date.parse(a)-Date.parse(t)}s(B,"compareThaw");class le{static{s(this,"FreezeLaneReconciler")}async endEpisode(e){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = 0, idle_release_last_attempt_at = NULL, idle_release_acked_count = 0 WHERE node_id = ? AND (idle_release_attempts <> 0 OR idle_release_last_attempt_at IS NOT NULL OR idle_release_acked_count <> 0)").run(e)}async run(e,a){const t=await P(a.candidates,async n=>({...n,tier:$(n.row,await k(n.row.node_id))}));t.sort(B);const r={stalled:0,waitingOnMail:0};for(const n of t)await L.fresh(()=>M(n.row,()=>this.enact(e,n,a.fleet)))==="frozen"&&(n.tier===1?r.stalled+=1:r.waitingOnMail+=1);return r}async enact(e,a,t){const r=a.row.node_id;try{return a.enact==="thaw"?await this.enactThaw(a.row):a.enact==="reopen"?await this.enactReopen(a.row):a.enact==="idle-release"?await this.enactIdleRelease(e,a.row):(await t.applyDeadRowPolicy(r),await t.has(r)?"launched":(await D(r))?.frozen_at!=null?"frozen":"skipped")}catch(n){return u({level:"error",event:"node.lifecycle.enact_failed",...d(r)?{node_id:r}:{},error:n,fields:{...d(r)?{}:{affected_node_id:r},enact:a.enact}}),"skipped"}}async enactReopen(e){await I(e.node_id);try{return(await h(e.node_id,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":"launched"}catch(a){if(m(a)||a instanceof A||a instanceof w)return await this.settleRefusedStart(e.node_id,a,"reopen");throw a}}async settleRefusedStart(e,a,t){return a instanceof b||await p(e,"release"),await f(e),u({level:"warn",event:"node.start.refused",node_id:e,error:a,fields:{enact:t}}),"skipped"}async enactThaw(e){const a=(await O(e.node_id))?.interrupted===!0;if(!a&&e.lifecycle==="resident"&&(await y(e.node_id))?.pi_session_id!=null&&!await k(e.node_id))return await p(e.node_id,"release"),await f(e.node_id),"skipped";try{return(await h(e.node_id,{resume:!0,capacity:"freeze",recovery:!0,...a?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}catch(t){if(m(t)||t instanceof A||t instanceof w)return await this.settleRefusedStart(e.node_id,t,"thaw");const r=await y(e.node_id);throw r!==null&&(r.status==="active"||r.status==="idle")&&(await p(e.node_id,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:t instanceof Error?t.message:String(t)}}}),await f(e.node_id)),t}}async enactIdleRelease(e,a){const t=a.node_id,r=await T(t),n=await H(t),l=n.attempts===0||n.acknowledgedCount!==r,o=l?0:n.attempts;if(o>=E)return await this.endEpisode(t),u({level:"warn",event:"broker.idle_release.exhausted",...d(t)?{node_id:t}:{},fields:{...d(t)?{}:{affected_node_id:t},attempts:o,max_attempts:E}}),await p(t,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:o}}}),await C(t,"notice.crash",`Child crashed \u2014 ${z(a)} (${t}) failed to relaunch after ${o} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${t}\`.`,{reason:"child-crashed",child:t}),"skipped";const v=l?void 0:n.lastAttempt,S=Math.min(x*2**o,U);if(v!==void 0&&e-v<S||!await F(t,n.attempts,o+1,r,e))return"skipped";const R=s(()=>W(t,{attempts:l?0:o,lastAttempt:l?void 0:n.lastAttempt,acknowledgedCount:r}),"giveBack");let g;try{g=await h(t,{resume:!0,capacity:"freeze"})}catch(c){if(!(c instanceof w||m(c)))throw c;return await R(),await this.settleRefusedStart(t,c,"idle-release")}return g.outcome==="frozen"?(await R(),"frozen"):(u({level:"info",event:"broker.revive.idle_release",...d(t)?{node_id:t}:{},attempt:o+1,fields:{...d(t)?{}:{affected_node_id:t},attempts:o+1,max_attempts:E}}),"launched")}}export{le as FreezeLaneReconciler,B as compareThaw,$ as thawTier};
1
+ var N=Object.defineProperty;var s=(i,e)=>N(i,"name",{value:e,configurable:!0});import{clearFrozen as m,getNode as y,getRow as D}from"../../../core/canvas/index.js";import{openDb as _}from"../../../core/canvas/db.js";import{fullName as z}from"../../../core/canvas/labels.js";import{isSafeNodeId as d}from"../../../core/canvas/paths.js";import{emitEvent as u}from"../../../core/events/emit.js";import{operationIdContext as T}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as L}from"../../../core/canvas/deliveries.js";import{publishNotice as C}from"../../../core/runtime/close.js";import{transition as p}from"../../../core/runtime/lifecycle.js";import{isStartRefusal as w}from"../../../core/runtime/start-check.js";import{EnvironmentImagePending as A}from"./remote-wake.js";import{asNodePerson as b}from"./node-person.js";import{MachineOfflineError as f}from"../../../core/runtime/runner/machine/ops.js";import{commitReopenResident as I}from"../../../core/runtime/reopen.js";import{reviveNode as h}from"../../../core/runtime/revive.js";import{hasPendingWake as k}from"../live-obligation.js";import{readInterruptedTurn as M}from"../../../core/canvas/recovery.js";import{mapAsync as O}from"../../../core/async-array.js";const E=6,P=10*6e4,U=2e4;async function x(i){const e=await(await _()).prepare("SELECT idle_release_attempts, idle_release_last_attempt_at, idle_release_acked_count FROM nodes WHERE node_id = ?").get(i);return{attempts:Number(e?.idle_release_attempts??0),acknowledgedCount:Number(e?.idle_release_acked_count??0),lastAttempt:e?.idle_release_last_attempt_at==null?void 0:Date.parse(e.idle_release_last_attempt_at)}}s(x,"readEpisode");async function H(i,e,a,t,r){const n=await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ? AND idle_release_attempts = ?").run(a,new Date(r).toISOString(),t,i,e);return Number(n.changes)===1}s(H,"claimAttempt");async function F(i,e){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ?").run(e.attempts,e.lastAttempt===void 0?null:new Date(e.lastAttempt).toISOString(),e.acknowledgedCount,i)}s(F,"writeEpisode");function W(i,e){if(e)return 2;const a=i.launched_at;if(a==null)return 1;const t=i.last_settled_at;return t==null?2:Date.parse(t)>Date.parse(a)?1:2}s(W,"thawTier");function $(i,e){const a=i.row.frozen_at,t=e.row.frozen_at;return a==null?t==null?0:1:t==null?-1:Date.parse(a)-Date.parse(t)}s($,"compareThaw");class de{static{s(this,"FreezeLaneReconciler")}async endEpisode(e){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = 0, idle_release_last_attempt_at = NULL, idle_release_acked_count = 0 WHERE node_id = ? AND (idle_release_attempts <> 0 OR idle_release_last_attempt_at IS NOT NULL OR idle_release_acked_count <> 0)").run(e)}async run(e,a){const t=await O(a.candidates,async n=>({...n,tier:W(n.row,await k(n.row.node_id))}));t.sort($);const r={stalled:0,waitingOnMail:0};for(const n of t)await T.fresh(()=>b(n.row,()=>this.enact(e,n,a.fleet)))==="frozen"&&(n.tier===1?r.stalled+=1:r.waitingOnMail+=1);return r}async enact(e,a,t){const r=a.row.node_id;try{return a.enact==="thaw"?await this.enactThaw(a.row):a.enact==="reopen"?await this.enactReopen(a.row):a.enact==="idle-release"?await this.enactIdleRelease(e,a.row):(await t.applyDeadRowPolicy(r),await t.has(r)?"launched":(await D(r))?.frozen_at!=null?"frozen":"skipped")}catch(n){return u({level:"error",event:"node.lifecycle.enact_failed",...d(r)?{node_id:r}:{},error:n,fields:{...d(r)?{}:{affected_node_id:r},enact:a.enact}}),"skipped"}}async enactReopen(e){await I(e.node_id);try{return(await h(e.node_id,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":"launched"}catch(a){if(w(a)||a instanceof A||a instanceof f)return await this.settleRefusedStart(e.node_id,a,"reopen");throw a}}async settleRefusedStart(e,a,t){return a instanceof f&&a.sent||await p(e,"release"),await m(e),u({level:"warn",event:"node.start.refused",node_id:e,error:a,fields:{enact:t}}),"skipped"}async enactThaw(e){const a=(await M(e.node_id))?.interrupted===!0;if(!a&&e.lifecycle==="resident"&&(await y(e.node_id))?.pi_session_id!=null&&!await k(e.node_id))return await p(e.node_id,"release"),await m(e.node_id),"skipped";try{return(await h(e.node_id,{resume:!0,capacity:"freeze",recovery:!0,...a?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}catch(t){if(w(t)||t instanceof A||t instanceof f)return await this.settleRefusedStart(e.node_id,t,"thaw");const r=await y(e.node_id);throw r!==null&&(r.status==="active"||r.status==="idle")&&(await p(e.node_id,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:t instanceof Error?t.message:String(t)}}}),await m(e.node_id)),t}}async enactIdleRelease(e,a){const t=a.node_id,r=await L(t),n=await x(t),l=n.attempts===0||n.acknowledgedCount!==r,o=l?0:n.attempts;if(o>=E)return await this.endEpisode(t),u({level:"warn",event:"broker.idle_release.exhausted",...d(t)?{node_id:t}:{},fields:{...d(t)?{}:{affected_node_id:t},attempts:o,max_attempts:E}}),await p(t,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:o}}}),await C(t,"notice.crash",`Child crashed \u2014 ${z(a)} (${t}) failed to relaunch after ${o} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${t}\`.`,{reason:"child-crashed",child:t}),"skipped";const v=l?void 0:n.lastAttempt,S=Math.min(U*2**o,P);if(v!==void 0&&e-v<S||!await H(t,n.attempts,o+1,r,e))return"skipped";const R=s(()=>F(t,{attempts:l?0:o,lastAttempt:l?void 0:n.lastAttempt,acknowledgedCount:r}),"giveBack");let g;try{g=await h(t,{resume:!0,capacity:"freeze"})}catch(c){if(!(c instanceof f||w(c)))throw c;return await R(),await this.settleRefusedStart(t,c,"idle-release")}return g.outcome==="frozen"?(await R(),"frozen"):(u({level:"info",event:"broker.revive.idle_release",...d(t)?{node_id:t}:{},attempt:o+1,fields:{...d(t)?{}:{affected_node_id:t},attempts:o+1,max_attempts:E}}),"launched")}}export{de as FreezeLaneReconciler,$ as compareThaw,W as thawTier};
@@ -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};
@@ -1,2 +1,2 @@
1
- var T=Object.defineProperty;var _=(t,e)=>T(t,"name",{value:e,configurable:!0});import{appendRunEvent as c}from"../../core/runs/events.js";import{openQuestionIds as x}from"../../core/runs/questions.js";import{getNode as h}from"../../core/canvas/canvas.js";import{payerOfGrant as N}from"../../core/grants/mirror.js";import{runSchemaRepromptPending as S}from"../../core/runtime/stop-guard.js";const k="crtr-turn-input",D="crtr-system-prompt",g="crtr-turn-end",w=_(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"zero");function O(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e?.text=="string").map(e=>e.text).join(`
2
- `):""}_(O,"text");function j(t){if(t==null)return;const{code:e,message:o,retry_at:u}=t;if(e!=="content_refused"&&e!=="model_error"&&e!=="rate_limited"||typeof o!="string")throw new Error("invalid crtr-turn-end error");if(e==="rate_limited"){if(typeof u!="string")throw new Error("invalid crtr-turn-end error");return{code:e,message:o,retry_at:u}}return{code:e,message:o}}_(j,"turnEndError");function v(t){return{input_tokens:t.input??0,output_tokens:t.output??0,cache_read_tokens:t.cacheRead??0,cache_write_tokens:t.cacheWrite??0,cost_usd:t.cost?.total??0}}_(v,"usageParts");async function A(t,e,o){if(e!==t||!o.some(f=>f.type==="custom"&&f.customType===g))return!1;const u=await h(t);return u!==null&&await S(u)}_(A,"rootRepromptPending");async function Y(t,e,o,u,f,R){let l=f;for(const n of u){if(n.type==="custom"&&n.customType===k){const r=n.data?.message_ids;if(!Array.isArray(r)||!r.every(i=>typeof i=="string"))throw new Error("invalid crtr-turn-input message_ids");l=[...new Set([...l,...r])]}if(n.type==="custom"&&n.customType===D){const r=n.data?.text;if(typeof r!="string")throw new Error("invalid crtr-system-prompt text");await c(t,e,o,"node.system_prompt.set",{entry_id:n.id,text:r})}if(n.type==="custom"&&n.customType===g){const r=n.data,i=r?.stop_reason;if(typeof i!="string")throw new Error("invalid crtr-turn-end stop_reason");const a=j(r?.error),s=await t.prepare("SELECT body_json FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'node.turn.started' ORDER BY sequence_number DESC LIMIT 1").get(e,o);if(!s)throw new Error("crtr-turn-end without node.turn.started");const{input:p}=JSON.parse(s.body_json),y=await t.prepare("SELECT status, pi_pid FROM node_rows WHERE run_id = ? AND node_id != ?").all(e,o),d=R??await A(e,o,[n]),m=y.some(E=>E.pi_pid!==null&&E.status==="active")||d?"running":(await x(e,t)).length?"waiting_on_user":"idle";await c(t,e,o,"node.turn.completed",{entry_id:n.id,message_ids:p.message_ids,run_status:m,stop_reason:i,...a?{error:a}:{}}),o===e&&await t.prepare("UPDATE nodes SET last_turn_error_json = ? WHERE node_id = ?").run(a?JSON.stringify(a):null,e)}if(n.type==="message"){const r=n.message;if(r.role==="user"){const i=await t.prepare("SELECT type, body_json FROM run_events WHERE run_id = ? AND node_id = ? AND type IN ('node.turn.started', 'node.turn.completed') ORDER BY sequence_number DESC LIMIT 1").get(e,o),a=i?.type==="node.turn.started"?JSON.parse(i.body_json).input.message_ids:[];await c(t,e,o,"node.turn.started",{entry_id:n.id,input:{text:O(r.content),message_ids:[...new Set([...a,...l])]}}),l=[]}if(r.role==="assistant"){let i=!1;const a=_(async()=>{if(i)return;i=!0;const s=r.content.filter(p=>p.type==="text").map(p=>p.text).join("");await c(t,e,o,"node.output_text.done",{entry_id:n.id,text:s,stop_reason:r.stopReason})},"doneText");for(const s of r.content)s.type==="thinking"&&await c(t,e,o,"node.thinking.done",{entry_id:n.id,text:s.thinking}),s.type==="text"&&await a(),s.type==="toolCall"&&(await a(),await c(t,e,o,"node.tool_call.started",{entry_id:n.id,tool_call_id:s.id,name:s.name,arguments:s.arguments}));if(await a(),r.usage){const s=v(r.usage),p=await t.prepare("SELECT usage_json, grant_id FROM nodes WHERE node_id = ?").get(e),y=p.usage_json?JSON.parse(p.usage_json):w(),d=w();for(const m of Object.keys(d))d[m]=y[m]+s[m];await t.prepare("UPDATE nodes SET usage_json = ? WHERE node_id = ?").run(JSON.stringify(d),e),await c(t,e,o,"usage",{entry_id:n.id,served_model:r.model,payer:await N(p.grant_id),...s,usage:d})}await t.prepare("DELETE FROM run_events WHERE run_id = ? AND node_id = ? AND type IN ('node.thinking.delta', 'node.output_text.delta')").run(e,o)}r.role==="toolResult"&&await c(t,e,o,"node.tool_call.completed",{entry_id:n.id,tool_call_id:r.toolCallId,name:r.toolName,result:r.content,status:r.isError?"error":"ok"})}}return l}_(Y,"appendConversationEvents");export{D as SYSTEM_PROMPT_TYPE,g as TURN_END_TYPE,k as TURN_INPUT_TYPE,Y as appendConversationEvents,A as rootRepromptPending};
1
+ var R=Object.defineProperty;var c=(t,e)=>R(t,"name",{value:e,configurable:!0});import{appendRunEvent as p}from"../../core/runs/events.js";import{openQuestionIds as T}from"../../core/runs/questions.js";import{getNode as x}from"../../core/canvas/canvas.js";import{payerOfGrant as h}from"../../core/grants/mirror.js";import{runSchemaRepromptPending as N}from"../../core/runtime/stop-guard.js";const D="crtr-turn-input",S="crtr-system-prompt",f="crtr-turn-end";function v(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e?.text=="string").map(e=>e.text).join(`
2
+ `):""}c(v,"text");function A(t){if(t==null)return;const{code:e,message:n,retry_at:_}=t;if(e!=="content_refused"&&e!=="model_error"&&e!=="rate_limited"||typeof n!="string")throw new Error("invalid crtr-turn-end error");if(e==="rate_limited"){if(typeof _!="string")throw new Error("invalid crtr-turn-end error");return{code:e,message:n,retry_at:_}}return{code:e,message:n}}c(A,"turnEndError");function O(t){return{input_tokens:t.input??0,output_tokens:t.output??0,cache_read_tokens:t.cacheRead??0,cache_write_tokens:t.cacheWrite??0,cost_usd:t.cost?.total??0}}c(O,"usageParts");async function k(t,e,n){if(e!==t||!n.some(l=>l.type==="custom"&&l.customType===f))return!1;const _=await x(t);return _!==null&&await N(_)}c(k,"rootRepromptPending");async function H(t,e,n,_,l,y){let d=l;for(const o of _){if(o.type==="custom"&&o.customType===D){const r=o.data?.message_ids;if(!Array.isArray(r)||!r.every(s=>typeof s=="string"))throw new Error("invalid crtr-turn-input message_ids");d=[...new Set([...d,...r])]}if(o.type==="custom"&&o.customType===S){const r=o.data?.text;if(typeof r!="string")throw new Error("invalid crtr-system-prompt text");await p(t,e,n,"node.system_prompt.set",{entry_id:o.id,text:r})}if(o.type==="custom"&&o.customType===f){const r=o.data,s=r?.stop_reason;if(typeof s!="string")throw new Error("invalid crtr-turn-end stop_reason");const a=A(r?.error),i=await t.prepare("SELECT body_json FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'node.turn.started' ORDER BY sequence_number DESC LIMIT 1").get(e,n);if(!i)throw new Error("crtr-turn-end without node.turn.started");const{input:u}=JSON.parse(i.body_json),E=await t.prepare("SELECT status, pi_pid FROM node_rows WHERE run_id = ? AND node_id != ?").all(e,n),w=y??await k(e,n,[o]),g=E.some(m=>m.pi_pid!==null&&m.status==="active")||w?"running":(await T(e,t)).length?"waiting_on_user":"idle";await p(t,e,n,"node.turn.completed",{entry_id:o.id,message_ids:u.message_ids,run_status:g,stop_reason:s,...a?{error:a}:{}}),n===e&&await t.prepare("UPDATE nodes SET last_turn_error_json = ? WHERE node_id = ?").run(a?JSON.stringify(a):null,e)}if(o.type==="message"){const r=o.message;if(r.role==="user"){const s=await t.prepare("SELECT type, body_json FROM run_events WHERE run_id = ? AND node_id = ? AND type IN ('node.turn.started', 'node.turn.completed') ORDER BY sequence_number DESC LIMIT 1").get(e,n),a=s?.type==="node.turn.started"?JSON.parse(s.body_json).input.message_ids:[];await p(t,e,n,"node.turn.started",{entry_id:o.id,input:{text:v(r.content),message_ids:[...new Set([...a,...d])]}}),d=[]}if(r.role==="assistant"){let s=!1;const a=c(async()=>{if(s)return;s=!0;const i=r.content.filter(u=>u.type==="text").map(u=>u.text).join("");await p(t,e,n,"node.output_text.done",{entry_id:o.id,text:i,stop_reason:r.stopReason})},"doneText");for(const i of r.content)i.type==="thinking"&&await p(t,e,n,"node.thinking.done",{entry_id:o.id,text:i.thinking}),i.type==="text"&&await a(),i.type==="toolCall"&&(await a(),await p(t,e,n,"node.tool_call.started",{entry_id:o.id,tool_call_id:i.id,name:i.name,arguments:i.arguments}));if(await a(),r.usage){const i=O(r.usage),u=await t.prepare("SELECT grant_id FROM nodes WHERE node_id = ?").get(e);await p(t,e,n,"usage",{entry_id:o.id,served_model:r.model,payer:await h(u.grant_id),...i,usage:await(await import("../../core/ledger/read.js")).runUsage(e)})}await t.prepare("DELETE FROM run_events WHERE run_id = ? AND node_id = ? AND type IN ('node.thinking.delta', 'node.output_text.delta')").run(e,n)}r.role==="toolResult"&&await p(t,e,n,"node.tool_call.completed",{entry_id:o.id,tool_call_id:r.toolCallId,name:r.toolName,result:r.content,status:r.isError?"error":"ok"})}}return d}c(H,"appendConversationEvents");export{S as SYSTEM_PROMPT_TYPE,f as TURN_END_TYPE,D as TURN_INPUT_TYPE,H as appendConversationEvents,k as rootRepromptPending};
@@ -1,6 +1,6 @@
1
- var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});import{randomUUID as y}from"node:crypto";import{openDb as d,withCanvasWrite as C}from"../../core/canvas/db.js";import{claimReconcilerLease as F,releaseReconcilerLease as O,renewReconcilerLease as x}from"../../core/canvas/reconciler-leases.js";import{getNode as R}from"../../core/canvas/canvas.js";import{BrokerClient as H,SocketTransport as D}from"../../core/broker-client/client.js";import{liveExecutionForNode as N}from"../../core/canvas/executions.js";import{runnerForExecution as W}from"../../core/runtime/runner/index.js";import{connectWssView as q}from"../../core/runtime/view-socket.js";import{openMachineView as U}from"../machine-link/forward.js";import{ViewLinkTransport as A}from"./view-transport.js";import{emitRunEvent as g,emitRunSettlement as T,emitRunStatus as j}from"../../core/runs/events.js";import{cancelOpenQuestions as J}from"../../core/runs/questions.js";import{emitEvent as c}from"../../core/events/emit.js";import{toRunOutcomeDTO as P}from"../api/map.js";import{readOutputResult as V}from"../../core/runtime/output-result.js";const B=JSON.stringify({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),p=new Map,h="run-observer",E=1e4,Y=250;async function m(t,e,i){return await C(async n=>await n.prepare("SELECT 1 AS held FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ? FOR SHARE").get(h,t,e,new Date().toISOString())===void 0?{held:!1}:{held:!0,value:await i()})}l(m,"whileHoldingLease");class v{static{l(this,"RunObserver")}nodeId;runId;owner;client;timer;status;piPid=null;outcomeRevision;openAssistant=!1;assistantStartSequence=0;block=null;thinking="";output="";pendingThinking="";pendingOutput="";flushTimer;closed=!1;lastRenewAt=Date.now();released=Promise.resolve();polling;frames=Promise.resolve();constructor(e,i,n,s,r){this.nodeId=e,this.runId=i,this.owner=n,this.status=s,this.outcomeRevision=r,this.timer=setInterval(()=>{this.pollOrClose()},250),this.timer.unref(),p.set(e,this)}static async start(e,i,n){const s=await d(),r=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = ? ORDER BY sequence_number DESC LIMIT 1").get(e,e===i?"node.settled":"child.settled"),a=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = 'node.status.changed' ORDER BY sequence_number DESC LIMIT 1").get(e),o=new v(e,i,n,a?JSON.parse(a.body_json).status:void 0,r?JSON.parse(r.body_json).outcome.revision:void 0);return await o.writeStream(null,null),await o.poll(),o}async pollOrClose(){try{await this.poll()}catch(e){this.close(),c({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:e})}}poll(){return this.polling===void 0&&(this.polling=this.pollOnce().finally(()=>{this.polling=void 0})),this.polling}async holdLease(){return Date.now()-this.lastRenewAt<E/3?!0:await x(h,this.nodeId,this.owner,E)?(this.lastRenewAt=Date.now(),!0):!1}async writeStream(e,i,n=!1){return(await(await d()).prepare(`UPDATE nodes SET ${n?"":`stream_message_seq = ${e===null?"NULL":"(SELECT event_cursor FROM nodes WHERE node_id = ?)"},`} stream_block = ?
2
- WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],i===null?null:JSON.stringify(i),this.nodeId,h,this.nodeId,this.owner,new Date().toISOString())).changes===1}async pollOnce(){if(this.closed)return;if(!await this.holdLease()){this.close();return}const e=await R(this.nodeId);if(!e||e.run_id!==this.runId||!await I(this.runId)){this.close();return}this.piPid=e.pi_pid??null;const i=e.pi_pid===null?"dormant":e.status;if(this.status!==i){if(!(await m(this.nodeId,this.owner,()=>j(this.runId,this.nodeId,i,e.intent??null))).held){this.close();return}this.status=i}const n=await P(e);if(n&&n.revision!==this.outcomeRevision&&Date.now()-Date.parse(n.settled_at)<720*60*6e4){if(this.nodeId===this.runId){const a=await(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ? ORDER BY created DESC").all(this.runId,this.runId);for(const o of a)await k(o.node_id,this.runId),await p.get(o.node_id)?.poll()}this.outcomeRevision=n.revision;const s=this.nodeId===this.runId&&n.kind==="result"?await V(this.nodeId):void 0;if(!(await m(this.nodeId,this.owner,()=>this.nodeId===this.runId?T(this.runId,this.nodeId,"node.settled",{outcome:n,usage:JSON.parse(e.usage_json??B),...s===void 0?{}:{result:s}}):T(this.runId,this.nodeId,"child.settled",{child_node_id:this.nodeId,outcome:n}))).held){this.close();return}if(e.grantee&&e.grantee!=="app:terminal"){const a=this.nodeId===this.runId?{run_id:this.runId}:{node_id:this.nodeId};J(a,this.nodeId===this.runId?"the run settled":"the asking node was closed").catch(o=>c({level:"error",event:"daemon.runs.question_cancel_failed",node_id:this.nodeId,error:o}))}}e.pi_pid===null?this.close():await this.connect()}async settlePoll(){await this.polling?.catch(()=>{}),await this.frames,await this.released}async viewAdmitted(){const e=await N(this.nodeId);return!(e?.runner==="blaxel"&&e.idleAt!==null)}async dropView(){const e=this.client;e&&(this.client=void 0,await this.frames,await this.flushDeltas(),this.discardDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null),e.close())}async connect(){if(this.closed)return;if(!await this.viewAdmitted()){await this.dropView();return}if(this.client)return;const e=await $(this.nodeId),i=await this.viewAdmitted();if(this.client||this.closed||!i){e.destroy();return}const n=new H(this.nodeId,{transport:e});this.client=n,n.on("connect",()=>n.send({type:"hello",role:"observer",client_id:y(),attends:!1}));const s=l(async r=>{if(!(this.closed||this.client!==n)){if(r.type==="message_start"&&r.message.role==="assistant"){if(this.discardDeltas(),this.openAssistant=!0,this.block=null,this.thinking="",this.output="",!await this.writeStream("run-cursor",null)){this.close();return}this.assistantStartSequence=Number((await(await d()).prepare("SELECT stream_message_seq FROM nodes WHERE node_id = ?").get(this.nodeId)).stream_message_seq)}if(r.type==="message_update"&&r.message.role==="assistant"&&this.openAssistant){const a=r.message.content;if(!Array.isArray(a))return;const o=a.at(-1);if(o&&typeof o=="object"&&"type"in o&&(o.type==="toolCall"?this.block={kind:"tool_call",name:"name"in o&&typeof o.name=="string"?o.name:""}:(o.type==="text"||o.type==="thinking")&&(this.block={kind:o.type})),!await this.writeStream(null,this.block,!0)){this.close();return}const f=a.filter(u=>u?.type==="thinking").map(u=>u.thinking).join(""),_=a.filter(u=>u?.type==="text").map(u=>u.text).join(""),L=f.startsWith(this.thinking)?f.slice(this.thinking.length):f,b=_.startsWith(this.output)?_.slice(this.output.length):_;this.thinking=f,this.output=_,this.pendingThinking+=L,this.pendingOutput+=b,(this.pendingThinking||this.pendingOutput)&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushDeltas().catch(u=>c({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:u}))},Y),this.flushTimer.unref())}r.type==="message_end"&&r.message.role==="assistant"&&(await this.flushDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null))}},"handleFrame");n.on("frame",r=>{this.frames=this.frames.then(()=>s(r)).catch(a=>{this.close(),c({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:a})})}),n.on("error",()=>{}),n.on("close",()=>{this.client===n&&(this.client=void 0,this.discardDeltas(),this.openAssistant=!1,this.block=null,this.released=this.released.then(async()=>{await this.writeStream(null,null)}).catch(()=>{}))}),n.connect()}async flushDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0;const e=this.pendingThinking,i=this.pendingOutput;if(this.pendingThinking="",this.pendingOutput="",!this.openAssistant||!e&&!i)return;(await m(this.nodeId,this.owner,async()=>{if(await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND sequence_number >= ? AND type IN ('node.output_text.done', 'node.thinking.done', 'usage') LIMIT 1").get(this.runId,this.nodeId,this.assistantStartSequence)){this.openAssistant=!1;return}e&&await g(this.runId,this.nodeId,"node.thinking.delta",{delta:e}),i&&await g(this.runId,this.nodeId,"node.output_text.delta",{delta:i})})).held||this.close()}discardDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.pendingThinking="",this.pendingOutput=""}close(){if(this.closed)return;this.closed=!0,this.discardDeltas(),clearInterval(this.timer),p.delete(this.nodeId),this.released=this.released.then(async()=>{await this.writeStream(null,null),await O(h,this.nodeId,this.owner)}).then(()=>{}).catch(i=>{c({level:"error",event:"daemon.runs.observer_release_failed",node_id:this.nodeId,error:i})});const e=this.client;this.client=void 0,e?.close()}}async function $(t){const e=await N(t);if(e===null)return new D(t,{recordsViewerFaults:!1});const i=await W(e.runner).viewerAddress(e);return i.kind==="machine"?new A(t,()=>U(i.environmentId,t)):i.kind==="unix"?new D(t,{recordsViewerFaults:!1}):new A(t,()=>q(i.url,i.headers))}l($,"viewTransport");async function he(t){const e=await(await d()).prepare("SELECT stream_message_seq FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null?null:Number(e.stream_message_seq)}l(he,"openAssistantMessageStartSequence");async function pe(t){const e=await(await d()).prepare("SELECT stream_message_seq, stream_block FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null||e.stream_block===null?null:JSON.parse(e.stream_block)}l(pe,"openAssistantBlock");async function fe(){const t=[...p.values()];for(const e of t)e.close();await Promise.all(t.map(e=>e.settlePoll())),await Promise.all([...w.values()].map(e=>e.catch(()=>{})))}l(fe,"closeRunObserversForTests");async function I(t){return await(await d()).prepare("SELECT 1 FROM nodes WHERE node_id = ? AND run_id = ? AND event_cursor IS NOT NULL").get(t,t)!==void 0}l(I,"runRootExists");const w=new Map;async function k(t,e){const i=w.get(t);if(i)return i;if(p.has(t))return;const n=G(t,e).finally(()=>w.delete(t));return w.set(t,n),n}l(k,"ensureRunObserver");async function G(t,e){if(!await I(e))return;const i=y();if(await F(h,t,i,E)!==void 0)try{if(t!==e){const n=await R(t);if(!await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'child.started' LIMIT 1").get(e,t)&&n&&Date.now()-Date.parse(n.created)<720*60*6e4&&!(await m(t,i,()=>g(e,t,"child.started",{child_node_id:t,kind:n.kind}))).held)return}await v.start(t,e,i)}catch(n){throw await O(h,t,i).catch(()=>{}),n}}l(G,"startRunObserver");async function _e(){const t=new Date(Date.now()-2592e6).toISOString(),e=await(await d()).prepare(`SELECT n.node_id, n.run_id, n.pi_pid, COALESCE(n.outcome_revision, 1) AS revision, e.body_json
1
+ var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});import{randomUUID as y}from"node:crypto";import{openDb as d,withCanvasWrite as C}from"../../core/canvas/db.js";import{claimReconcilerLease as F,releaseReconcilerLease as R,renewReconcilerLease as x}from"../../core/canvas/reconciler-leases.js";import{getNode as D}from"../../core/canvas/canvas.js";import{BrokerClient as H,SocketTransport as O}from"../../core/broker-client/client.js";import{liveExecutionForNode as N}from"../../core/canvas/executions.js";import{runnerForExecution as W}from"../../core/runtime/runner/index.js";import{connectWssView as q}from"../../core/runtime/view-socket.js";import{openMachineView as U}from"../machine-link/forward.js";import{ViewLinkTransport as A}from"./view-transport.js";import{emitRunEvent as g,emitRunSettlement as T,emitRunStatus as j}from"../../core/runs/events.js";import{cancelOpenQuestions as P}from"../../core/runs/questions.js";import{emitEvent as h}from"../../core/events/emit.js";import{runUsage as V}from"../../core/ledger/index.js";import{toRunOutcomeDTO as B}from"../api/map.js";import{readOutputResult as J}from"../../core/runtime/output-result.js";const p=new Map,c="run-observer",E=1e4,Y=250;async function w(t,e,i){return await C(async n=>await n.prepare("SELECT 1 AS held FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ? FOR SHARE").get(c,t,e,new Date().toISOString())===void 0?{held:!1}:{held:!0,value:await i()})}l(w,"whileHoldingLease");class v{static{l(this,"RunObserver")}nodeId;runId;owner;client;timer;status;piPid=null;outcomeRevision;openAssistant=!1;assistantStartSequence=0;block=null;thinking="";output="";pendingThinking="";pendingOutput="";flushTimer;closed=!1;lastRenewAt=Date.now();released=Promise.resolve();polling;frames=Promise.resolve();constructor(e,i,n,s,r){this.nodeId=e,this.runId=i,this.owner=n,this.status=s,this.outcomeRevision=r,this.timer=setInterval(()=>{this.pollOrClose()},250),this.timer.unref(),p.set(e,this)}static async start(e,i,n){const s=await d(),r=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = ? ORDER BY sequence_number DESC LIMIT 1").get(e,e===i?"node.settled":"child.settled"),a=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = 'node.status.changed' ORDER BY sequence_number DESC LIMIT 1").get(e),o=new v(e,i,n,a?JSON.parse(a.body_json).status:void 0,r?JSON.parse(r.body_json).outcome.revision:void 0);return await o.writeStream(null,null),await o.poll(),o}async pollOrClose(){try{await this.poll()}catch(e){this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:e})}}poll(){return this.polling===void 0&&(this.polling=this.pollOnce().finally(()=>{this.polling=void 0})),this.polling}async holdLease(){return Date.now()-this.lastRenewAt<E/3?!0:await x(c,this.nodeId,this.owner,E)?(this.lastRenewAt=Date.now(),!0):!1}async writeStream(e,i,n=!1){return(await(await d()).prepare(`UPDATE nodes SET ${n?"":`stream_message_seq = ${e===null?"NULL":"(SELECT event_cursor FROM nodes WHERE node_id = ?)"},`} stream_block = ?
2
+ WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],i===null?null:JSON.stringify(i),this.nodeId,c,this.nodeId,this.owner,new Date().toISOString())).changes===1}async pollOnce(){if(this.closed)return;if(!await this.holdLease()){this.close();return}const e=await D(this.nodeId);if(!e||e.run_id!==this.runId||!await I(this.runId)){this.close();return}this.piPid=e.pi_pid??null;const i=e.pi_pid===null?"dormant":e.status;if(this.status!==i){if(!(await w(this.nodeId,this.owner,()=>j(this.runId,this.nodeId,i,e.intent??null))).held){this.close();return}this.status=i}const n=await B(e);if(n&&n.revision!==this.outcomeRevision&&Date.now()-Date.parse(n.settled_at)<720*60*6e4){if(this.nodeId===this.runId){const a=await(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ? ORDER BY created DESC").all(this.runId,this.runId);for(const o of a)await L(o.node_id,this.runId),await p.get(o.node_id)?.poll()}this.outcomeRevision=n.revision;const s=this.nodeId===this.runId&&n.kind==="result"?await J(this.nodeId):void 0;if(!(await w(this.nodeId,this.owner,async()=>this.nodeId===this.runId?T(this.runId,this.nodeId,"node.settled",{outcome:n,usage:await V(this.runId),...s===void 0?{}:{result:s}}):T(this.runId,this.nodeId,"child.settled",{child_node_id:this.nodeId,outcome:n}))).held){this.close();return}if(e.grantee&&e.grantee!=="app:terminal"){const a=this.nodeId===this.runId?{run_id:this.runId}:{node_id:this.nodeId};P(a,this.nodeId===this.runId?"the run settled":"the asking node was closed").catch(o=>h({level:"error",event:"daemon.runs.question_cancel_failed",node_id:this.nodeId,error:o}))}}e.pi_pid===null?this.close():await this.connect()}async settlePoll(){await this.polling?.catch(()=>{}),await this.frames,await this.released}async viewAdmitted(){const e=await N(this.nodeId);return!(e?.runner==="blaxel"&&e.idleAt!==null)}async dropView(){const e=this.client;e&&(this.client=void 0,await this.frames,await this.flushDeltas(),this.discardDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null),e.close())}async connect(){if(this.closed)return;if(!await this.viewAdmitted()){await this.dropView();return}if(this.client)return;const e=await $(this.nodeId),i=await this.viewAdmitted();if(this.client||this.closed||!i){e.destroy();return}const n=new H(this.nodeId,{transport:e});this.client=n,n.on("connect",()=>n.send({type:"hello",role:"observer",client_id:y(),attends:!1}));const s=l(async r=>{if(!(this.closed||this.client!==n)){if(r.type==="message_start"&&r.message.role==="assistant"){if(this.discardDeltas(),this.openAssistant=!0,this.block=null,this.thinking="",this.output="",!await this.writeStream("run-cursor",null)){this.close();return}this.assistantStartSequence=Number((await(await d()).prepare("SELECT stream_message_seq FROM nodes WHERE node_id = ?").get(this.nodeId)).stream_message_seq)}if(r.type==="message_update"&&r.message.role==="assistant"&&this.openAssistant){const a=r.message.content;if(!Array.isArray(a))return;const o=a.at(-1);if(o&&typeof o=="object"&&"type"in o&&(o.type==="toolCall"?this.block={kind:"tool_call",name:"name"in o&&typeof o.name=="string"?o.name:""}:(o.type==="text"||o.type==="thinking")&&(this.block={kind:o.type})),!await this.writeStream(null,this.block,!0)){this.close();return}const f=a.filter(u=>u?.type==="thinking").map(u=>u.thinking).join(""),m=a.filter(u=>u?.type==="text").map(u=>u.text).join(""),k=f.startsWith(this.thinking)?f.slice(this.thinking.length):f,b=m.startsWith(this.output)?m.slice(this.output.length):m;this.thinking=f,this.output=m,this.pendingThinking+=k,this.pendingOutput+=b,(this.pendingThinking||this.pendingOutput)&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushDeltas().catch(u=>h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:u}))},Y),this.flushTimer.unref())}r.type==="message_end"&&r.message.role==="assistant"&&(await this.flushDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null))}},"handleFrame");n.on("frame",r=>{this.frames=this.frames.then(()=>s(r)).catch(a=>{this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:a})})}),n.on("error",()=>{}),n.on("close",()=>{this.client===n&&(this.client=void 0,this.discardDeltas(),this.openAssistant=!1,this.block=null,this.released=this.released.then(async()=>{await this.writeStream(null,null)}).catch(()=>{}))}),n.connect()}async flushDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0;const e=this.pendingThinking,i=this.pendingOutput;if(this.pendingThinking="",this.pendingOutput="",!this.openAssistant||!e&&!i)return;(await w(this.nodeId,this.owner,async()=>{if(await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND sequence_number >= ? AND type IN ('node.output_text.done', 'node.thinking.done', 'usage') LIMIT 1").get(this.runId,this.nodeId,this.assistantStartSequence)){this.openAssistant=!1;return}e&&await g(this.runId,this.nodeId,"node.thinking.delta",{delta:e}),i&&await g(this.runId,this.nodeId,"node.output_text.delta",{delta:i})})).held||this.close()}discardDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.pendingThinking="",this.pendingOutput=""}close(){if(this.closed)return;this.closed=!0,this.discardDeltas(),clearInterval(this.timer),p.delete(this.nodeId),this.released=this.released.then(async()=>{await this.writeStream(null,null),await R(c,this.nodeId,this.owner)}).then(()=>{}).catch(i=>{h({level:"error",event:"daemon.runs.observer_release_failed",node_id:this.nodeId,error:i})});const e=this.client;this.client=void 0,e?.close()}}async function $(t){const e=await N(t);if(e===null)return new O(t,{recordsViewerFaults:!1});const i=await W(e.runner).viewerAddress(e);return i.kind==="machine"?new A(t,()=>U(i.environmentId,t)):i.kind==="unix"?new O(t,{recordsViewerFaults:!1}):new A(t,()=>q(i.url,i.headers))}l($,"viewTransport");async function pe(t){const e=await(await d()).prepare("SELECT stream_message_seq FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null?null:Number(e.stream_message_seq)}l(pe,"openAssistantMessageStartSequence");async function fe(t){const e=await(await d()).prepare("SELECT stream_message_seq, stream_block FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null||e.stream_block===null?null:JSON.parse(e.stream_block)}l(fe,"openAssistantBlock");async function me(){const t=[...p.values()];for(const e of t)e.close();await Promise.all(t.map(e=>e.settlePoll())),await Promise.all([..._.values()].map(e=>e.catch(()=>{})))}l(me,"closeRunObserversForTests");async function I(t){return await(await d()).prepare("SELECT 1 FROM nodes WHERE node_id = ? AND run_id = ? AND event_cursor IS NOT NULL").get(t,t)!==void 0}l(I,"runRootExists");const _=new Map;async function L(t,e){const i=_.get(t);if(i)return i;if(p.has(t))return;const n=Q(t,e).finally(()=>_.delete(t));return _.set(t,n),n}l(L,"ensureRunObserver");async function Q(t,e){if(!await I(e))return;const i=y();if(await F(c,t,i,E)!==void 0)try{if(t!==e){const n=await D(t);if(!await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'child.started' LIMIT 1").get(e,t)&&n&&Date.now()-Date.parse(n.created)<720*60*6e4&&!(await w(t,i,()=>g(e,t,"child.started",{child_node_id:t,kind:n.kind}))).held)return}await v.start(t,e,i)}catch(n){throw await R(c,t,i).catch(()=>{}),n}}l(Q,"startRunObserver");async function we(){const t=new Date(Date.now()-2592e6).toISOString(),e=await(await d()).prepare(`SELECT n.node_id, n.run_id, n.pi_pid, COALESCE(n.outcome_revision, 1) AS revision, e.body_json
3
3
  FROM node_rows n
4
4
  LEFT JOIN run_events e ON n.pi_pid IS NULL AND e.run_id = n.run_id AND e.node_id = n.node_id
5
5
  AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
6
- WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await k(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){Q(s.node_id,r)}}l(_e,"pollRunObservers");const S=new Map;function Q(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),c({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(Q,"reportObserverFailure");export{fe as closeRunObserversForTests,k as ensureRunObserver,pe as openAssistantBlock,he as openAssistantMessageStartSequence,_e as pollRunObservers};
6
+ WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers};
@@ -66,19 +66,18 @@ A refused or failed model call ends the turn with an empty `message.done` (`stop
66
66
 
67
67
  ## A quiet run
68
68
 
69
- A runtime that sleeps when nothing holds a connection to it ends a run's stream after 60 s with no running turn and no new event. `RunStream` reports that and does not reconnect:
69
+ A runtime that sleeps when nothing holds a connection to it ends a run's stream after 60 s with no running turn and no new event. Iteration then ends normally, `stream.idle` is `true` and the stream does not reconnect; reopen from `stream.position` when you want more:
70
70
 
71
71
  ```ts
72
72
  const stream = runtime.runs.events(runId, {after: cursor});
73
- for await (const event of stream) handle(event);
74
- const end = await stream.whenEnded(); // rejects on a transport failure or abort()
75
- if (end.reason === 'idle') {
76
- // the run is quiet and nothing was missed; reopen later with runtime.runs.events(runId, {after: end.cursor})
73
+ for await (const event of stream) handle(event); // throws on a transport failure or abort()
74
+ if (stream.idle) {
75
+ // the run is quiet and nothing was missed; reopen later with runtime.runs.events(runId, {after: stream.position})
77
76
  }
78
77
  ```
79
78
 
80
- A settled run ends with `reason: 'settled'`. `runs.reply` reopens through an idle close on its own.
79
+ A settled run ends iteration after `node.settled` with `idle` false. `runs.reply` reopens through an idle close on its own.
81
80
 
82
81
  ## Typed events
83
82
 
84
- `RunEvent` is the union of every run event, discriminated on `type`. `RunEventOf<'node.turn.completed'>` picks one, and `RunStream.on(type, listener)` passes the listener that event. An event type a newer runtime adds and your SDK version does not declare is still delivered as-is.
83
+ `RunEvent` is the union of every run event, discriminated on `type`. `RunEventOf<'node.turn.completed'>` picks one; narrow on `event.type` inside the loop. An event type a newer runtime adds and your SDK version does not declare is still delivered as-is.
@@ -23,4 +23,4 @@ A node wakes when work actually arrives: a subscribed child pushes a report, ano
23
23
 
24
24
  Do not keep a node active to poll a child, a person, or a message. Creation automatically subscribes a parent to its child, and the runtime delivers the child’s outcome. Waiting for something the canvas can push is free: end the turn and let the node become dormant. Schedule a cron only for recurring work or an external condition that nothing can push into the canvas, such as checking a CI run. A timer added “just in case” a child does not report duplicates a runtime guarantee and hides a runtime defect.
25
25
 
26
- A broker crash does not erase the node. The daemon retains the durable node row, conversation, waits, and outstanding inbox entries, then applies its recovery policy. This is what makes a resident event-driven assistant practical: it can wait for a webhook, be dormant for hours, and resume its saved work only when the webhook produces a message. Use [`nodes.message`](../sdk/nodes.md#sending-a-follow-up) to deliver that external event, and run `crtr canvas read internal/nodes-and-canvas` for lifecycle operations.
26
+ A broker crash does not erase the node. The daemon retains the durable node row, conversation, waits, and outstanding inbox entries, then applies its recovery policy. This is what makes a resident event-driven assistant practical: it can wait for a webhook, be dormant for hours, and resume its saved work only when the webhook produces a message. Use `crtr node message` (or `CrtrClient` from `@north-light/api`) to deliver that external event, and run `crtr canvas read internal/nodes-and-canvas` for lifecycle operations.
@@ -7,7 +7,7 @@ description: When deciding whether an agent task should outlive one request, rea
7
7
 
8
8
  Use a node when the work may need a follow-up, a report, a child, or time without a caller holding a request open. A node is a durable unit of agent work: it has an identity, a goal, graph relationships, the documents it writes for other readers, a context directory for its scripts and data, and a broker that hosts its agent engine. It is not an HTTP request with an LLM response attached.
9
9
 
10
- The canvas is a durable graph of **objects**, not only nodes. Documents, nodes, bash jobs, owners (a person, an app, a repo, a profile) and custom objects registered by outside services are all objects with an id and a name, and the same verbs work on every one of them: `crtr canvas read`, `list`, `search`, `watch`, `unwatch` and `edges`. Edges record what an object links to, who acted on it and who watches it. Reading an object, writing a document, messaging a node or spawning one makes you a watcher, so its later events reach your inbox. See [Documents](./documents.md) for the document object. The canvas makes an agent's work and its relationship to other work visible after the process that created it has returned. This is why [`client.nodes.create`](../sdk/nodes.md) returns a node you can retrieve, message, stream, or wait on instead of only returning generated text. An application can create a root node, show its progress, and later call `nodes.message` when a person or an external event has more work for it.
10
+ The canvas is a durable graph of **objects**, not only nodes. Documents, nodes, bash jobs, owners (a person, an app, a repo, a profile) and custom objects registered by outside services are all objects with an id and a name, and the same verbs work on every one of them: `crtr canvas read`, `list`, `search`, `watch`, `unwatch` and `edges`. Edges record what an object links to, who acted on it and who watches it. Reading an object, writing a document, messaging a node or spawning one makes you a watcher, so its later events reach your inbox. See [Documents](./documents.md) for the document object. The canvas makes an agent's work and its relationship to other work visible after the process that created it has returned. This is why `crtr node new` (and `CrtrClient` from `@north-light/api`) returns a node you can retrieve, message, stream, or wait on instead of only returning generated text. A program can create a root node, show its progress, and later message it when a person or an external event has more work for it.
11
11
 
12
12
  ```mermaid
13
13
  flowchart TD
@@ -26,4 +26,4 @@ The one way work reports upward is a **push**. A push writes a report, which is
26
26
 
27
27
  A node owns an outcome, not merely a deliverable. It may write documents, files and reports while working, but its terminal result is credible only when it has evidence that the requested goal was met. The canvas supports that responsibility: it preserves the goal, the node's documents and reports, and relationships across fresh contexts and broker replacement. A node's context directory holds only what is not a document — scripts, data, logs; writing meant for another reader is a document shared by `[[name]]`.
28
28
 
29
- Use a one-shot SDK call such as [`nodes.parse`](../sdk/nodes.md#parse-and-structured-output) when work is bounded and its only useful output is a typed result. Use `nodes.create` when the application needs a continuing conversation or must observe work while it runs. For the operational graph and report model, run `crtr canvas read internal/nodes-and-canvas`.
29
+ Use a one-shot SDK call such as `runs.parse` when work is bounded and its only useful output is a typed result. Create a node with `crtr node new` or `CrtrClient` when the application needs a continuing conversation or must observe work while it runs. For the operational graph and report model, run `crtr canvas read internal/nodes-and-canvas`.
@@ -28,4 +28,4 @@ A kind is a recurring role, not a decorative name. It carries a role-specific po
28
28
 
29
29
  Base mode is the normal choice: the node owns and performs the work, using a child only for a separable part. Promote to orchestrator only when independent parts can proceed in parallel and the benefits outweigh coordination and integration. A terminal orchestrator still finishes normally; residency is separate and belongs to a person-facing ongoing conversation.
30
30
 
31
- These choices keep the application prompt focused. Identity belongs in a profile, standing role in a kind, task-specific intent in the prompt, coordination in mode, and reusable knowledge in the narrowest document owner. For the full selection rules, run `crtr canvas read internal/agent-shaping`; [`nodes.create`](../sdk/nodes.md) documents the profile, kind, and mode fields an application passes.
31
+ These choices keep the application prompt focused. Identity belongs in a profile, standing role in a kind, task-specific intent in the prompt, coordination in mode, and reusable knowledge in the narrowest document owner. For the full selection rules, run `crtr canvas read internal/agent-shaping`; `crtr node new -h` documents the profile, kind, and mode fields a caller passes.
@@ -23,7 +23,7 @@ Scope strings are prefixed with `crtr:`. These are the ones the daemon and CLI c
23
23
 
24
24
  The `memory` in `crtr:memory:*` is the scope family's name for access to **documents** (see [Documents](./documents.md)); there is no separate memory store. The older short names (`ask`, `act`, `schedule`, `memory:read`, `memory:write`, `llm`) are not accepted by `crtr sys connect --scopes`. A node's own documents, and an app's documents for its own nodes, need no `crtr:memory` scope.
25
25
 
26
- This is an allow-list, not a claim that code will behave. The daemon checks the scope at the route that performs the action and rejects an unavailable one. The SDK’s [`nodes.create`](../sdk/nodes.md) `scopes` field narrows a run: a run's list must stay inside what its creator and grant hold, and `crtr:act` requires `crtr:llm`. `client.memory` is not scope-gated: it lists and reads the person's `knowledge` and `preference` documents, and the answer is filtered by privacy, which is `public` or `private`. An app's ceiling is `public` documents; a grant holding `crtr:memory:read_private:user` or `crtr:memory:manage:user` widens it to `private` ones. Within that ceiling, the app's registered schema and the relation facts it writes decide who may read a document, not a per-call scope. The exception is a run started with a `scopes` list: it reads its own app's documents (including automatic delivery of them at boot) only with `crtr:memory:read:app:<id>` and writes or edits them only with `crtr:memory:rw:app:<id>`; a refused write answers `scope_missing` naming the scope. Such a run still publishes its own reports with `crtr push` and its promoted node still gets a roadmap, but cannot edit any other document through that path, and a child never regains a scope its parent's list dropped.
26
+ This is an allow-list, not a claim that code will behave. The daemon checks the scope at the route that performs the action and rejects an unavailable one. The node-create route's `scopes` field narrows a run: a run's list must stay inside what its creator and grant hold, and `crtr:act` requires `crtr:llm`. `client.memory` is not scope-gated: it lists and reads the person's `knowledge` and `preference` documents, and the answer is filtered by privacy, which is `public` or `private`. An app's ceiling is `public` documents; a grant holding `crtr:memory:read_private:user` or `crtr:memory:manage:user` widens it to `private` ones. Within that ceiling, the app's registered schema and the relation facts it writes decide who may read a document, not a per-call scope. The exception is a run started with a `scopes` list: it reads its own app's documents (including automatic delivery of them at boot) only with `crtr:memory:read:app:<id>` and writes or edits them only with `crtr:memory:rw:app:<id>`; a refused write answers `scope_missing` naming the scope. Such a run still publishes its own reports with `crtr push` and its promoted node still gets a roadmap, but cannot edit any other document through that path, and a child never regains a scope its parent's list dropped.
27
27
 
28
28
  ```mermaid
29
29
  flowchart LR
@@ -20,7 +20,7 @@ flowchart LR
20
20
 
21
21
  The broker has one job: host a node’s agent session. The daemon has the broader job: preserve the node graph, state transitions, waits, reports, and broker lifecycle. A viewer may stream a broker’s live session, but it does not become the authority that decides whether that node is active, dormant, or revived. Closing a viewer closes a view, not the node’s durable identity.
22
22
 
23
- This is why a process crash is recoverable rather than an automatic loss of work. The daemon retains the node row, session information, context directory, documents, waits, and inbox state, then applies recovery to the broker execution. A later wake or explicit revival can continue the node’s saved conversation. The application should create nodes through [`client.nodes`](../sdk/nodes.md), not start an LLM process itself, because the daemon is the component that keeps the engine and durable canvas state coordinated.
23
+ This is why a process crash is recoverable rather than an automatic loss of work. The daemon retains the node row, session information, context directory, documents, waits, and inbox state, then applies recovery to the broker execution. A later wake or explicit revival can continue the node’s saved conversation. The application should create nodes through the daemon (`crtr node new` or `CrtrClient` from `@north-light/api`), not start an LLM process itself, because the daemon is the component that keeps the engine and durable canvas state coordinated.
24
24
 
25
25
  The costs are real. A daemon must be running, and canvas state has one home instead of being scattered across terminals and application processes. Local clients use its owner-only Unix socket. Remote clients use its configured TCP listener and bearer token. A network interruption can therefore fail a mutation loudly rather than encouraging a client to replay it and risk doing the action twice.
26
26
 
@@ -1,65 +1,37 @@
1
1
  ---
2
2
  title: SDK overview
3
- description: Drive a crouter daemon from a Node or browser application with the typed SDK.
3
+ description: What the typed SDK covers on a daemon you run yourself, and where daemon owners go for nodes, bash, crons and the human inbox.
4
4
  ---
5
5
 
6
6
  # `@north-light/sdk`
7
7
 
8
- The ESM-only client an application installs to drive a crouter daemon: create agent runs, watch streamed events, wait for typed results, and reach the rest of the daemon's `/v1` API.
8
+ The ESM-only client an application installs to start runs on a person's runtime, read their results, and manage what the app owns there. Apps that sign people in with Northlight are documented on the SDK docs site, which starts at [Quick setup](https://sdk.docs.northlight.ai/docs/quickstart).
9
9
 
10
- One package, one class. `new Crouter()` in Node talks to the owner's unix socket. `new Crouter({ baseURL, token })` in a browser or a remote process talks to the daemon's TCP listener with a bearer token. Resource methods issue `/v1` requests; `createAndWait`, `parse`, and `auth.status` compose more than one request. crtrd stays the sole owner of canvas state.
10
+ `new Crouter()` in Node talks to the owner's unix socket. `new Crouter({ baseURL, token })` in a browser or a remote process talks to the daemon's TCP listener with a bearer token. On either, the client offers the app routes (`runs`, `uploads`, `docs`, `memory`, …) plus the few owner calls an app setup needs: `models.credentials.install`, `spendLimits` and `customObjects`. crtrd stays the sole owner of canvas state.
11
11
 
12
- ```ts
13
- import Crouter from '@north-light/sdk';
14
- import { z } from 'zod';
12
+ ## Driving nodes, bash, crons or the human inbox
15
13
 
16
- const client = new Crouter();
14
+ The SDK does not wrap the owner's node, bash, cron, human-inbox, canvas-view, file and system routes. A program that drives the owner's own daemon uses `CrtrClient` from `@north-light/api`, the typed client the `crtr` CLI itself uses, or the `crtr` CLI. `client.request(method, path, body?, options?)` still reaches any `/v1` route with the SDK's authentication, retries and error mapping.
17
15
 
18
- const run = await client.nodes.parse({
19
- prompt: 'Summarize the failing tests in this repo.',
20
- cwd: '/path/to/repo',
21
- output_schema: z.object({ failures: z.array(z.string()), root_cause: z.string() }),
22
- });
16
+ ```ts
17
+ import { CrtrClient } from '@north-light/api';
18
+ import { socketFetch, defaultSocketPath } from '@north-light/api/node';
23
19
 
24
- if (run.kind === 'result') console.log(run.output_parsed.root_cause);
20
+ const crtr = new CrtrClient({ baseUrl: 'http://localhost', fetch: socketFetch(defaultSocketPath()) });
21
+ const node = await crtr.createNode({ prompt: 'List the top-level directories here.', cwd: process.cwd(), root: true });
25
22
  ```
26
23
 
27
- ## Building an app for other people
28
-
29
- An app that signs people in with Northlight and runs agents on their runtimes is documented on the SDK docs site, which starts at [Quick setup](https://sdk.docs.northlight.ai/docs/quickstart). This section and the pages below cover driving a crouter daemon you run yourself.
30
-
31
24
  ## Pages
32
25
 
33
26
  | Page | Covers |
34
27
  |---|---|
35
- | [Getting started](./getting-started.md) | Install, `new Crouter()` on the owner's socket, `client.auth.status()` and `crtr sys connect` for a browser or remote app, Chrome's local-network prompt |
28
+ | [Getting started](./getting-started.md) | Install, `new Crouter()` on the owner's socket, `crtr sys connect` for a browser or remote app, Chrome's local-network prompt |
36
29
  | [Client construction](./client.md) | Every constructor option and its environment-variable fallback; per-request options |
37
- | [Nodes](./nodes.md) | `create` parameters, the outcome union, `parse()` with a zod schema, `waitForOutcome`, `message`, `cancel`, nested resources |
38
- | [Streaming](./streaming.md) | The event table, `stream()` / `events()`, the activity helper, resume with `after`, `stream_gap` and `stream_dropped` |
39
- | [Files](./files.md) | Absolute-path reads, writes, and one-level lists |
40
- | [Bash](./bash.md) | One bounded command and its output result |
41
- | [Resource map](./resources.md) | Every namespace (including `customObjects`, `runs`, `memory`, `shares`, `providers`) with its routes, what is deliberately excluded, and the `client.request()` escape hatch |
42
- | [Errors](./errors.md) | The daemon's scoped-token and wire errors, identifier validation, and node retries |
30
+ | [Resource map](./resources.md) | Every namespace with its routes, and the `client.request()` escape hatch |
31
+ | [Errors](./errors.md) | The daemon's scoped-token and wire errors, and identifier validation |
43
32
  | [Docker environment](./docker.md) | `start()`, `attach()`, `connection()` from `@north-light/env-docker` |
44
33
  | [Release notes](https://sdk.docs.northlight.ai/docs/release-notes) | Behavior changes an existing app must act on, newest first |
45
34
 
46
- ## Phases
47
-
48
- The surface ships in three cuts.
49
-
50
- | Phase | What lands | State |
51
- |---|---|---|
52
- | **Phase 1** | Client construction and transports; `client.auth.status()`; `client.nodes.create`, `retrieve`, `list`, `outcome`, `waitForOutcome`, `createAndWait`, `parse`, `message`, `cancel`, and `interrupt`; `nodes.reports.list`; `profiles.ensure` and `retrieve`; `system.status` and `health`; the error hierarchy; per-request options; `crtr sys connect`; and `env-docker.connection()` | Shipped |
53
- | **Phase 2 namespaces** | Node lifecycle, job, worktree, and result; canvas and canvas history; crons; human requests and inbox; models; `client.files.read` through `/v1/files/peek`, `write`, and `list`; and `client.bash.run` | Shipped |
54
- | **Phase 2 streaming** | `GET /v1/nodes/{id}/events`, `nodes.stream(params, options?)`, `nodes.events(id, options?)`, `NodeStream`, and the activity helper | Shipped |
55
- | **Phase 3** | The review, comment, and chat-inventory namespaces | Not shipped |
56
-
57
- The per-run `scopes` create field ships in phase 1. `nodes.update` scope support remains phase 2 and is not in the shipped client or wire declarations.
58
-
59
- ## Verification status
60
-
61
- The SDK declarations and streaming examples are verified.
62
-
63
35
  ## Where the agents read this
64
36
 
65
37
  The same content routed for agents lives in the built-in document `crouter-sdk`, which ships with the `crtr` binary. An agent working in an application's repository reaches it with `crtr canvas read crouter-sdk` and does not need this repository checked out.
@@ -63,10 +63,9 @@ Autostart is Node-only and applies only to the socket transport. A `baseURL` cli
63
63
  Every request-capable method accepts an options object as its last argument, after any path, body, or query arguments. Each field overrides the client-level default for that one request.
64
64
 
65
65
  ```ts
66
- const id = 'example-node';
67
66
  const signal = new AbortController().signal;
68
67
 
69
- await client.nodes.retrieve(id, {
68
+ await client.runs.get('run-1', {
70
69
  signal, // AbortSignal — real cancellation, passed straight to fetch
71
70
  timeout: 5_000, // ms, this request only
72
71
  maxRetries: 0, // this request only
@@ -83,7 +82,7 @@ await client.nodes.retrieve(id, {
83
82
  | `deadlineAt` | `number` (epoch ms) | The same deadline as an absolute instant, for passing one deadline to several calls. With `budgetMs` too, the earlier wins. |
84
83
  | `headers` | `Record<string, string>` | Merged over `defaultHeaders`, client `headers`, and the token-generated header; a matching name, including `Authorization`, wins. |
85
84
 
86
- `signal` is real cancellation. The long-polling helpers (`waitForOutcome`, `createAndWait`, `parse`) honour it between polls and during the in-flight request, and aborting them stops the client — it does not cancel the node. To stop the run itself, call `client.nodes.cancel(id)` or `client.nodes.interrupt(id)`. Streams use `NodeEventsOptions`: the same fields except `timeout`, plus `after` for `nodes.events`; see [Streaming](./streaming.md).
85
+ `signal` is real cancellation. The long-polling helpers (`runs.wait`, `runs.parse`) honour it between polls and during the in-flight request, and aborting them stops the client — it does not cancel the run. To stop the run itself, call `client.runs.cancel(id)` or `client.runs.interrupt(id)`.
87
86
 
88
87
  ### One deadline per call
89
88
 
@@ -93,9 +92,8 @@ Without `budgetMs`/`deadlineAt` a call has one `timeout` per attempt, so a keyed
93
92
  await client.runs.message(runId, text, { budgetMs: 20_000 });
94
93
  ```
95
94
 
96
- - The deadline is fixed once, when the call starts, and every attempt, every backoff, every `retry_after_s`/`Retry-After` wait, the token fetch and the refresh after a 401 share it. The call rejects at the deadline (plus the scheduling of one timer) whether the time goes to the headers, the body, a retry wait or the token hook, even when your `fetch` ignores its `AbortSignal`. The compound helpers (`runs.wait`, `runs.parse`, `nodes.waitForOutcome`, `nodes.createAndWait`, `nodes.parse`) fix one deadline for the whole helper, not one per poll.
95
+ - The deadline is fixed once, when the call starts, and every attempt, every backoff, every `retry_after_s`/`Retry-After` wait, the token fetch and the refresh after a 401 share it. The call rejects at the deadline (plus the scheduling of one timer) whether the time goes to the headers, the body, a retry wait or the token hook, even when your `fetch` ignores its `AbortSignal`. The compound helpers (`runs.wait`, `runs.parse`) fix one deadline for the whole helper, not one per poll.
97
96
  - A retry wait that would reach the deadline is not slept: the call rejects at once with `DeadlineExceededError` (`code: 'deadline_exceeded'`, status 504). `reason` is `'retry_after'` when the server asked for a wait longer than the time left (`retryAfterRequestS` is that request), and `'elapsed'` when time simply ran out; `deadlineAt` is the instant, and `cause` is the last refusal.
98
- - A stream (`nodes.stream`, `nodes.events`): `budgetMs` / `deadlineAt` bound opening it (the create or retrieve, the token hook and the connection); once open it lives until it ends or its `signal` aborts.
99
97
  - `budgetMs` and `deadlineAt` must fit a timer: at most 2,147,483,647 ms (about 24.8 days) from now, or the call throws `RangeError`.
100
98
  - **Holding a lease while you call.** An app that takes a lease or lock for an SDK call sets `budgetMs` and keeps the lease longer than it, with margin, so the call has ended or been abandoned before the lease can be taken over: `LEASE_MS >= BUDGET_MS + MARGIN_MS`. State that inequality next to the constants (or assert it at module load) rather than renewing the lease while a call is unbounded.
101
99
  - `OAuth2Client` gives each directory operation (discovery, a code exchange or refresh, a revocation, the JWKS read behind `verifyIdToken`) the same kind of deadline, `OAuth2Options.timeoutMs` (default 10 s). A refresh runs under the user's store lock, so the lock is held no longer than `timeoutMs` plus the store's own time.
@@ -106,10 +104,10 @@ await client.runs.message(runId, text, { budgetMs: 20_000 });
106
104
  |---|---|
107
105
  | `.withResponse()` / `.asResponse()` | They exist to hand back the raw `Response` and an `x-request-id`. The daemon emits no request id, and a caller who needs raw bytes uses `client.request()`. |
108
106
  | `apiKey` | The daemon's credential is a token (`CRTRD_TOKEN`) everywhere in the product. `apiKey` would be a second name for one thing. |
109
- | Resource-prefixed ids | Node ids have their own format. The SDK validates unsafe path identifiers locally with `TypeError`, and the daemon validates the request too; nothing is re-prefixed. |
107
+ | Resource-prefixed ids | Run ids have their own format. The SDK validates unsafe path identifiers locally with `TypeError`, and the daemon validates the request too; nothing is re-prefixed. |
110
108
 
111
109
  ## Wire naming
112
110
 
113
- Wire fields are `snake_case` — `output_schema`, `root_lifecycle`, `pin_cwd`, `final_report_path`. The SDK does not camelize them. Namespaces and method names are camelCase (`client.nodes.waitForOutcome`, `client.nodes.worktree`).
111
+ Wire fields are `snake_case` — `run_id`, `output_schema`, `expires_at`. The SDK does not camelize them. Namespaces and method names are camelCase (`client.customObjects`, `client.runs.listAll`).
114
112
 
115
113
  Timestamps are ISO-8601 strings (`created`, `settled_at`, `finalized_at`, `deadline_at`), not Unix seconds.
@@ -22,7 +22,7 @@ import Crouter from '@north-light/sdk';
22
22
  const env = await start({ volume: 'my-agent-home' });
23
23
  const client = new Crouter(env.connection());
24
24
 
25
- await client.nodes.create({ prompt: 'Do the thing.', root: true });
25
+ await client.runs.start({ prompt: 'Do the thing.' });
26
26
 
27
27
  await env.stop();
28
28
  ```