@north-light/cli 0.3.705 → 0.3.707

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.
@@ -1605,9 +1605,9 @@ ${s}`}catch{return}finally{if(t!==void 0)try{wui(t)}catch{}}}function Rui(){if(p
1605
1605
  `),r=[],i=s=>{r.push(s)},o=0;for(;o<n.length;){let s=Wli(n,o);if(s!==null){let c=Gli(s.rows,e);for(let u=0;u<s.rows.length;u++)i({text:jli(s.rows[u],c),tone:u<s.headerRows?"accent":void 0});o=s.next;continue}let a=n[o];i({text:a,tone:Fli(a)?"muted":void 0}),o++}return r}function Vli(t,e,n,r){let i=zli(t,n).map(s=>s.tone!==void 0?E0n(s,r,s.tone==="accent"):w0n(s.text,r)),o=b0n(i,n);return o.length<=e?{lines:o,skippedCount:0}:{lines:o.slice(0,e),skippedCount:o.length-e}}var Az=class{constructor(e,n,r,i,o,s=x0n,a){this.text=e;this.options=n;this.context=r;this.theme=i;this.command=o;this.staticPreview=s;this.structuredPreview=a}text;options;context;theme;command;staticPreview;structuredPreview;currentPreview(){return this.command===void 0?this.staticPreview:_li(this.command)}render(e){let n=this.currentPreview(),r=!!this.options.isPartial,i=!!this.context.isError,s=r||i?[Qli(this.options,this.theme)]:[];if(this.options.expanded){let c=h0n(this.text,this.theme,!0),u=this.command!==void 0?[this.theme.fg("muted",`$ ${this.command}`),""]:[];return b0n(["",...s,...u,...c.split(`
1606
1606
  `)],e)}if(!r){if(n.isHelp){let l=h0n(Lli(this.text),this.theme),p=FC(l,o7e,e).visualLines??[],h=this.theme.fg("dim","(schema \u2014 ctrl+o to expand)");return gz(["",...s,...p,h],e)}let c=this.command!==void 0?Mhe(this.command):void 0,u=c!==void 0&&this.structuredPreview!==void 0?YAn(this.structuredPreview,c):null;if(u!==null){let l=u.findIndex(f=>f.text!==""),d=u.map((f,g)=>E0n(f,this.theme,g===l)),h=FC(d.join(`
1607
1607
  `),o7e,e).visualLines??[],m=this.theme.fg("dim","(ctrl+o to expand)");return gz(["",...s,...h,m],e)}if(!i&&n.suppressOutput){let l=this.theme.fg("dim","(suppressed \u2014 ctrl+o to expand)");return gz(["",...s,l],e)}}let a=Vli(this.text,o7e,e,this.theme);if(a.skippedCount>0){let c=this.theme.fg("dim",`\u2026 (${a.skippedCount} more lines, ctrl+o to expand)`);return gz(["",...s,...a.lines,c],e)}return gz(["",...s,...a.lines],e)}invalidate(){}};function f0n(t){let e=t.split(`
1608
- `,1)[0];return e.startsWith("$ ")&&Sli(e.slice(2))}var yz=class extends ha{constructor(n,r,i){super(1,1,s=>i.bg("customMessageBg",s));this.content=n;this.theme=i;this.expanded=r;let o={isHelp:f0n(n),suppressOutput:!1};this.body=new Az(n,{expanded:r},{},i,void 0,o),this.addChild(this.body)}content;theme;body;expanded;setExpanded(n){if(this.expanded===n)return;this.expanded=n;let r={isHelp:f0n(this.content),suppressOutput:!1};this.body=new Az(this.content,{expanded:n},{},this.theme,void 0,r),this.clear(),this.addChild(this.body)}};function C0n(t,e=new Ig){let n=u0n(t);return bli(n)?{definition:{name:"bash",label:"bash",description:"Render crtr bash output with crtr-specific chrome in the attach viewer.",parameters:{},renderCall(i,o,s){let a=u0n(i)||n,c=Mhe(a),u=c!==void 0&&c.some(g=>g==="-h"||g==="--help"),l=(c??[]).filter(g=>g!=="-h"&&g!=="--help"),d=l.join(" "),p=u?VAn:KAn(l),h=u?`${p} crtr help`:`${p} crtr`,m=o.fg("accent",o.bold(h)),f=d?` ${e.folded?Tli(l,o):o.fg("toolTitle",o.bold(d))}`:"";return e.capture(new ve(`${m}${f}`,0,0))},renderResult(i,o,s,a){return new Az(Rli(i),o,a,s,n,x0n,Bhe(i).at(-1))}}}:void 0}La();var Kli=/\b(?:request|operation) was aborted\b|\bthe user aborted\b/i;function Phe(t){return t.stopReason==="aborted"?!0:t.stopReason==="error"&&Kli.test(t.errorMessage??"")}ov();ov();var Yli=new Set(["restart-continuation","review-boundary"]);function v0n(t){return Yli.has(t)}var I0n=new Set(["bullets","filesDeleted"]),Jli=5,Xli=1e3;function s7e(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t,n=Object.keys(e);return n.length!==I0n.size||!n.every(r=>I0n.has(r))||!Array.isArray(e.bullets)||e.bullets.length===0||!e.bullets.every(r=>typeof r=="string"&&r.trim()!=="")||typeof e.filesDeleted!="number"||!Number.isSafeInteger(e.filesDeleted)||e.filesDeleted<0?null:{bullets:e.bullets.slice(0,Jli).map(r=>r.trim().slice(0,Xli).trimEnd()),filesDeleted:e.filesDeleted}}function S0n(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t)){if(n.trim()==="")continue;let i=s7e(r);i!==null&&(e[n]=i)}return e}function ih(t){return t.role!=="assistant"?"":XAe(t)}function RI(t){return t.role==="user"&&AB(t)===null}var _0n="start";function Zli(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;return e.version!==1||typeof e.text!="string"||!Array.isArray(e.sources)||e.text.trim()===""||e.sources.length===0||!e.sources.every(n=>typeof n=="string"&&n!=="")?null:{version:1,sources:e.sources.slice(0,200),text:e.text.slice(0,4e4)}}function k0n(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t)){if(n.trim()==="")continue;let i=Zli(r);i!==null&&(e[n]=i)}return e}function a7e(t){if(typeof t!="object"||t===null)return;let e=t.timestamp;return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}function T0n(t,e){if(t.length===0)return"";if(t.length===1)return t[0].text;let n=new Set(t.map(r=>r.key));if(e!==void 0&&e.sources.every(r=>n.has(r))){let r=new Set(e.sources),i=-1;t.forEach((s,a)=>{r.has(s.key)&&(i=a)});let o=t.slice(i+1).map(s=>s.text);return[e.text,...o].join(`
1608
+ `,1)[0];return e.startsWith("$ ")&&Sli(e.slice(2))}var yz=class extends ha{constructor(n,r,i){super(1,1,s=>i.bg("customMessageBg",s));this.content=n;this.theme=i;this.expanded=r;let o={isHelp:f0n(n),suppressOutput:!1};this.body=new Az(n,{expanded:r},{},i,void 0,o),this.addChild(this.body)}content;theme;body;expanded;setExpanded(n){if(this.expanded===n)return;this.expanded=n;let r={isHelp:f0n(this.content),suppressOutput:!1};this.body=new Az(this.content,{expanded:n},{},this.theme,void 0,r),this.clear(),this.addChild(this.body)}};function C0n(t,e=new Ig){let n=u0n(t);return bli(n)?{definition:{name:"bash",label:"bash",description:"Render crtr bash output with crtr-specific chrome in the attach viewer.",parameters:{},renderCall(i,o,s){let a=u0n(i)||n,c=Mhe(a),u=c!==void 0&&c.some(g=>g==="-h"||g==="--help"),l=(c??[]).filter(g=>g!=="-h"&&g!=="--help"),d=l.join(" "),p=u?VAn:KAn(l),h=u?`${p} crtr help`:`${p} crtr`,m=o.fg("accent",o.bold(h)),f=d?` ${e.folded?Tli(l,o):o.fg("toolTitle",o.bold(d))}`:"";return e.capture(new ve(`${m}${f}`,0,0))},renderResult(i,o,s,a){return new Az(Rli(i),o,a,s,n,x0n,Bhe(i).at(-1))}}}:void 0}La();var Kli=/\b(?:request|operation) was aborted\b|\bthe user aborted\b/i;function Phe(t){return t.stopReason==="aborted"?!0:t.stopReason==="error"&&Kli.test(t.errorMessage??"")}ov();ov();var Yli=new Set(["restart-continuation","review-boundary"]);function v0n(t){return Yli.has(t)}var I0n=new Set(["bullets","filesDeleted"]),Jli=5,Xli=1e3;function s7e(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t,n=Object.keys(e);return n.length!==I0n.size||!n.every(r=>I0n.has(r))||!Array.isArray(e.bullets)||e.bullets.length===0||!e.bullets.every(r=>typeof r=="string"&&r.trim()!=="")||typeof e.filesDeleted!="number"||!Number.isSafeInteger(e.filesDeleted)||e.filesDeleted<0?null:{bullets:e.bullets.slice(0,Jli).map(r=>r.trim().slice(0,Xli).trimEnd()),filesDeleted:e.filesDeleted}}function S0n(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t)){if(n.trim()==="")continue;let i=s7e(r);i!==null&&(e[n]=i)}return e}function ih(t){return t.role!=="assistant"?"":XAe(t)}function RI(t){return t.role==="user"&&AB(t)===null}var _0n="start";function Zli(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;return e.version!==1||typeof e.text!="string"||!Array.isArray(e.sources)||e.text.trim()===""||e.sources.length===0||!e.sources.every(n=>typeof n=="string"&&n!=="")?null:{version:1,sources:e.sources.slice(0,200),text:e.text.slice(0,4e4)}}function k0n(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t)){if(n.trim()==="")continue;let i=Zli(r);i!==null&&(e[n]=i)}return e}function a7e(t){if(typeof t!="object"||t===null)return;let e=t.timestamp;return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}function T0n(t,e){if(t.length===0)return"";if(t.length===1)return t[0].text;let n=new Set(e?.sources),r=-1;return t.forEach((i,o)=>{n.has(i.key)&&(r=o)}),r>=0?[e.text,...t.slice(r+1).map(i=>i.text)].join(`
1609
1609
 
1610
- `)}return t.map(r=>r.text).join(`
1610
+ `):t.map(i=>i.text).join(`
1611
1611
 
1612
1612
  `)}var edi=/^[ \t]{0,3}```mermaid[^\n]*\n([\s\S]*?)\n[ \t]{0,3}```[ \t]*$/gm,tdi=/^```(?:text|plain|plaintext)?[ \t]*\n([^\n]+)\n```[ \t]*$/gim,ndi=/^```(?:text|plain|plaintext)?[ \t]*\n[^\n]+\n```[ \t]*$/im,rdi=/\s*(?:→|⟶|⇒|⟹)\s*/,idi=/[=;{}\[\]`]/,odi=/[\u2500-\u259F\u25A0-\u25FF]/;function sdi(t){let e=t.split(`
1613
1613
  `),n=1/0;for(let r of e)r.trim()!==""&&(n=Math.min(n,r.length-r.replace(/^[ \t]+/,"").length));return!Number.isFinite(n)||n===0?t:e.map(r=>r.trim()===""?"":r.slice(n)).join(`
@@ -13,9 +13,7 @@ export interface TurnReplyTrackerOptions {
13
13
  *
14
14
  * The open turn is a projection of the bound session's branch, so anything that
15
15
  * moves the leaf in place (a fault-retry rewind, `/tree`) must call `seed()`
16
- * again: otherwise prose from the abandoned branch stays in every later rewrite,
17
- * and the viewer — which honours a rewrite only when all its sources are still
18
- * in the turn — falls back to showing every message verbatim. */
16
+ * again: otherwise prose from the abandoned branch stays in every later rewrite. */
19
17
  export declare class TurnReplyTracker {
20
18
  private readonly nodeId;
21
19
  private readonly broadcast;
@@ -6,7 +6,7 @@ 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
- /** 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. */
9
+ /** Wait for the node's broker on the Mac to accept a viewer, retrying a channel that closes (its view.sock refused) after 250 ms; a pending channel is waited on, not replaced. 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
10
  export declare function waitForMachineView(environmentId: string, nodeId: string, exited: Promise<unknown> | undefined, waitMs: number): Promise<BrokerViewLink | null>;
11
11
  /** The environment id of a forwarded viewer upgrade path, or null for any other path. */
12
12
  export declare function machineViewEnvironment(req: IncomingMessage): string | null;
@@ -1 +1 @@
1
- var x=Object.defineProperty;var a=(r,e)=>x(r,"name",{value:e,configurable:!0});import{EventEmitter as A}from"node:events";import{createHmac as I,timingSafeEqual as R}from"node:crypto";import{WebSocket as u,WebSocketServer as P}from"ws";import{markAt as k}from"../../core/logged-step-timings.js";import{addStepTiming as B}from"../../core/step-timings.js";import{emitEvent as _}from"../../core/events/emit.js";import{openDb as O}from"../../core/canvas/db.js";import{loadSecretsKey as T}from"../../core/secrets/key.js";import{LINK_MAX_PAYLOAD_BYTES as v,parseFrame as g}from"./frames.js";import{apiAddress as D,heldLinkOf as E,MachineViewLink as S,UNROUTABLE_PREFIX as L}from"./holder.js";const y=8*1024*1024,$=1013,q=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/view$/,M=new P({noServer:!0,maxPayload:v}),b=a(r=>I("sha256",T().key).update(`machine-view:${r}`).digest("hex"),"forwardToken");function N(r,e){const n=E(r);return n!==null?new S(n,e):new U(r,e)}a(N,"openMachineView");class U extends A{static{a(this,"ForwardedViewLink")}environmentId;nodeId;ws;ended=!1;failed=!1;queued=[];queuedBytes=0;constructor(e,n){super(),this.environmentId=e,this.nodeId=n;const s=performance.now();this.once("connect",()=>_({level:"info",event:"daemon.timing.forwarded_view_ready",node_id:this.nodeId,fields:{environment:this.environmentId,open_to_ready_ms:Math.round((performance.now()-s)*10)/10}})),this.dial().catch(t=>this.finish(t instanceof Error?t.message:String(t)))}get destroyed(){return this.ended}write(e){return this.ended?!1:this.ws?.readyState!==u.OPEN?(this.queuedBytes+=e.length,this.queuedBytes>y?(this.finish("machine view: the holder did not accept the channel before its queue filled"),!1):(this.queued.push(e),!0)):this.ws.bufferedAmount>y?(this.finish("machine view: the holder is not draining the channel"),!1):(this.sendData(e),!0)}destroy(){return this.ended||(this.ws?.readyState===u.OPEN&&this.ws.send(JSON.stringify({type:"view.close",channel:""})),this.finish(void 0)),this}sendData(e){this.ws?.send(JSON.stringify({type:"view.data",channel:"",bytes:Buffer.from(e).toString("base64")}))}async dial(){const e=await(await O()).prepare("SELECT api_address, lease_expires_at FROM machine_links WHERE environment = ?").get(this.environmentId);if(e===void 0||Date.parse(e.lease_expires_at)<=Date.now())throw new Error(`machine_offline: machine ${this.environmentId} has no live link`);if(e.api_address.startsWith(L))throw new Error(`machine_unreachable: the API process holding the link wrote ${e.api_address}; set CRTR_API_ADDRESS or listen on TCP`);if(e.api_address===D())throw new Error(`machine_offline: the link row names this API process (${e.api_address}) but it holds no link`);if(this.ended)return;const n=new URL(`/v1/machines/${encodeURIComponent(this.environmentId)}/view`,e.api_address.includes("://")?e.api_address:`ws://${e.api_address}`);n.protocol=n.protocol==="https:"?"wss:":n.protocol==="http:"?"ws:":n.protocol,n.searchParams.set("node",this.nodeId);const s=new u(n.toString(),{headers:{authorization:`Bearer ${b(this.environmentId)}`},maxPayload:v});this.ws=s,s.on("open",()=>{for(const t of this.queued.splice(0))this.sendData(t)}),s.on("unexpected-response",(t,i)=>{i.resume(),this.finish(i.statusCode===409?"machine_offline: the holder no longer holds the link":`machine view refused by ${e.api_address}: ${i.statusCode}`)}),s.on("message",t=>{const i=g(t);i!==null&&(i.type==="view.ready"?this.emit("connect"):i.type==="view.data"?this.emit("data",Buffer.from(i.bytes,"base64")):i.type==="view.close"&&this.finish(i.error))}),s.on("error",t=>this.finish(t.message)),s.on("close",()=>this.finish("machine view forward closed"))}finish(e){this.ended||(this.ended=!0,this.ws?.close(),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}function C(r,e,n){return new Promise(s=>{const t=N(r,e),i=setTimeout(()=>{_({level:"info",event:"daemon.timing.view_ready_timeout",node_id:e,fields:{channel:t.channel??"",timeout_ms:n}}),s(null),t.destroy()},n);t.on("error",()=>{}),t.on("connect",()=>{clearTimeout(i),s(t)}),t.on("close",()=>{clearTimeout(i),s(null)})})}a(C,"openReadyMachineView");async function G(r,e,n,s){const t=Date.now()+s;let i=!1;n?.then(()=>{i=!0});for(let l=1;Date.now()<=t&&!i;l++){const f=performance.now(),h=await C(r,e,Math.max(1,Math.min(2e3,t-Date.now())));if(B(`probe_${l}_${h!==null?"ready":"failed"}_ms`,performance.now()-f),h!==null)return k("ready_received"),h;await new Promise(m=>setTimeout(m,250))}return null}a(G,"waitForMachineView");function Q(r){const e=q.exec(new URL(r.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Q,"machineViewEnvironment");function ee(r,e,n,s){const t=r.headers.authorization,i=/^Bearer (\S+)$/.exec(Array.isArray(t)?t[0]??"":t??"")?.[1]??"",l=Buffer.from(b(s)),f=Buffer.from(i);if(f.length!==l.length||!R(f,l))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine view forward credential refused"};const h=new URL(r.url??"/","http://runtime.local").searchParams.get("node");if(h===null||h==="")return{status:400,text:"Bad Request",code:"bad_request",message:"node is required"};const m=E(s);return m===null?{status:409,text:"Conflict",code:"machine_offline",message:"this API process holds no link for the machine"}:(M.handleUpgrade(r,e,n,d=>{const o=new S(m,h),p=a(c=>{d.readyState===u.OPEN&&d.send(JSON.stringify(c))},"send");o.on("connect",()=>p({type:"view.ready",channel:""})),o.on("data",c=>{if(d.bufferedAmount>y){o.destroy(),d.close($,"viewer too slow");return}p({type:"view.data",channel:"",bytes:c.toString("base64")})}),o.on("error",c=>p({type:"view.close",channel:"",error:c.message})),o.on("close",()=>d.close()),d.on("message",c=>{const w=g(c);w?.type==="view.data"?o.write(Buffer.from(w.bytes,"base64")):w?.type==="view.close"&&o.destroy()}),d.on("close",()=>o.destroy()),d.on("error",()=>o.destroy())}),null)}a(ee,"handleMachineViewUpgrade");export{y as VIEW_BUFFER_LIMIT_BYTES,ee as handleMachineViewUpgrade,Q as machineViewEnvironment,N as openMachineView,G as waitForMachineView};
1
+ var x=Object.defineProperty;var a=(r,e)=>x(r,"name",{value:e,configurable:!0});import{EventEmitter as A}from"node:events";import{createHmac as I,timingSafeEqual as R}from"node:crypto";import{WebSocket as m,WebSocketServer as P}from"ws";import{markAt as k}from"../../core/logged-step-timings.js";import{addStepTiming as T}from"../../core/step-timings.js";import{emitEvent as _}from"../../core/events/emit.js";import{openDb as B}from"../../core/canvas/db.js";import{loadSecretsKey as O}from"../../core/secrets/key.js";import{LINK_MAX_PAYLOAD_BYTES as v,parseFrame as g}from"./frames.js";import{apiAddress as D,heldLinkOf as E,MachineViewLink as S,UNROUTABLE_PREFIX as L}from"./holder.js";const y=8*1024*1024,$=1013,M=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/view$/,U=new P({noServer:!0,maxPayload:v}),b=a(r=>I("sha256",O().key).update(`machine-view:${r}`).digest("hex"),"forwardToken");function q(r,e){const i=E(r);return i!==null?new S(i,e):new N(r,e)}a(q,"openMachineView");class N extends A{static{a(this,"ForwardedViewLink")}environmentId;nodeId;ws;ended=!1;failed=!1;queued=[];queuedBytes=0;constructor(e,i){super(),this.environmentId=e,this.nodeId=i;const s=performance.now();this.once("connect",()=>_({level:"info",event:"daemon.timing.forwarded_view_ready",node_id:this.nodeId,fields:{environment:this.environmentId,open_to_ready_ms:Math.round((performance.now()-s)*10)/10}})),this.dial().catch(n=>this.finish(n instanceof Error?n.message:String(n)))}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 B()).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 i=new URL(`/v1/machines/${encodeURIComponent(this.environmentId)}/view`,e.api_address.includes("://")?e.api_address:`ws://${e.api_address}`);i.protocol=i.protocol==="https:"?"wss:":i.protocol==="http:"?"ws:":i.protocol,i.searchParams.set("node",this.nodeId);const s=new m(i.toString(),{headers:{authorization:`Bearer ${b(this.environmentId)}`},maxPayload:v});this.ws=s,s.on("open",()=>{for(const n of this.queued.splice(0))this.sendData(n)}),s.on("unexpected-response",(n,t)=>{t.resume(),this.finish(t.statusCode===409?"machine_offline: the holder no longer holds the link":`machine view refused by ${e.api_address}: ${t.statusCode}`)}),s.on("message",n=>{const t=g(n);t!==null&&(t.type==="view.ready"?this.emit("connect"):t.type==="view.data"?this.emit("data",Buffer.from(t.bytes,"base64")):t.type==="view.close"&&this.finish(t.error))}),s.on("error",n=>this.finish(n.message)),s.on("close",()=>this.finish("machine view forward closed"))}finish(e){this.ended||(this.ended=!0,this.ws?.close(),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}function C(r,e,i,s){return new Promise(n=>{const t=q(r,e),c=Math.max(1,i-Date.now());let d=!1;const o=a(()=>{d||(d=!0,clearTimeout(l),n(null),t.destroy())},"giveUp"),l=setTimeout(()=>{_({level:"info",event:"daemon.timing.view_ready_timeout",node_id:e,fields:{channel:t.channel??"",timeout_ms:c}}),o()},c);s?.then(o),t.on("error",()=>{}),t.on("connect",()=>{d=!0,clearTimeout(l),n(t)}),t.on("close",()=>{d=!0,clearTimeout(l),n(null)})})}a(C,"openReadyMachineView");async function G(r,e,i,s){const n=Date.now()+s;let t=!1;i?.then(()=>{t=!0});for(let c=1;Date.now()<=n&&!t;c++){const d=performance.now(),o=await C(r,e,n,i);if(T(`probe_${c}_${o!==null?"ready":"failed"}_ms`,performance.now()-d),o!==null)return k("ready_received"),o;await new Promise(l=>setTimeout(l,250))}return null}a(G,"waitForMachineView");function Q(r){const e=M.exec(new URL(r.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Q,"machineViewEnvironment");function ee(r,e,i,s){const n=r.headers.authorization,t=/^Bearer (\S+)$/.exec(Array.isArray(n)?n[0]??"":n??"")?.[1]??"",c=Buffer.from(b(s)),d=Buffer.from(t);if(d.length!==c.length||!R(d,c))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine view forward credential refused"};const o=new URL(r.url??"/","http://runtime.local").searchParams.get("node");if(o===null||o==="")return{status:400,text:"Bad Request",code:"bad_request",message:"node is required"};const l=E(s);return l===null?{status:409,text:"Conflict",code:"machine_offline",message:"this API process holds no link for the machine"}:(U.handleUpgrade(r,e,i,f=>{const h=new S(l,o),p=a(u=>{f.readyState===m.OPEN&&f.send(JSON.stringify(u))},"send");h.on("connect",()=>p({type:"view.ready",channel:""})),h.on("data",u=>{if(f.bufferedAmount>y){h.destroy(),f.close($,"viewer too slow");return}p({type:"view.data",channel:"",bytes:u.toString("base64")})}),h.on("error",u=>p({type:"view.close",channel:"",error:u.message})),h.on("close",()=>f.close()),f.on("message",u=>{const w=g(u);w?.type==="view.data"?h.write(Buffer.from(w.bytes,"base64")):w?.type==="view.close"&&h.destroy()}),f.on("close",()=>h.destroy()),f.on("error",()=>h.destroy())}),null)}a(ee,"handleMachineViewUpgrade");export{y as VIEW_BUFFER_LIMIT_BYTES,ee as handleMachineViewUpgrade,Q as machineViewEnvironment,q as openMachineView,G as waitForMachineView};
@@ -21,7 +21,7 @@ export interface TurnProse {
21
21
  text: string;
22
22
  }
23
23
  /** The text a viewer shows as a turn's reply. One prose message is the reply
24
- * verbatim. Otherwise the latest rewrite whose sources are all still in the turn,
25
- * followed by any later prose it does not cover, verbatim. A missing or stale
26
- * rewrite degrades to concatenation, never to a lost answer. */
24
+ * verbatim. Otherwise the latest rewrite, when it covers any prose the viewer
25
+ * holds, followed by the later prose verbatim; earlier sources may be outside the
26
+ * viewer's last messages. Without such a rewrite, the prose is concatenated. */
27
27
  export declare function turnReplyText(prose: readonly TurnProse[], reply: TurnReply | undefined): string;
@@ -1,5 +1,5 @@
1
- var f=Object.defineProperty;var o=(t,e)=>f(t,"name",{value:e,configurable:!0});const a="start",p=4e4,x=200;function l(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;const e=t;return e.version!==1||typeof e.text!="string"||!Array.isArray(e.sources)||e.text.trim()===""||e.sources.length===0||!e.sources.every(r=>typeof r=="string"&&r!=="")?null:{version:1,sources:e.sources.slice(0,200),text:e.text.slice(0,4e4)}}o(l,"normalizeTurnReply");function d(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};const e={};for(const[r,n]of Object.entries(t)){if(r.trim()==="")continue;const i=l(n);i!==null&&(e[r]=i)}return e}o(d,"normalizeTurnReplyRecord");function R(t){if(typeof t!="object"||t===null)return;const e=t.timestamp;return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}o(R,"messageKey");function A(t){return t.role==="assistant"&&t.stopReason!=="aborted"&&t.stopReason!=="error"}o(A,"isSettledAssistant");function _(t,e){if(t.length===0)return"";if(t.length===1)return t[0].text;const r=new Set(t.map(n=>n.key));if(e!==void 0&&e.sources.every(n=>r.has(n))){const n=new Set(e.sources);let i=-1;t.forEach((s,c)=>{n.has(s.key)&&(i=c)});const u=t.slice(i+1).map(s=>s.text);return[e.text,...u].join(`
1
+ var u=Object.defineProperty;var o=(t,e)=>u(t,"name",{value:e,configurable:!0});const l="start",y=4e4,p=200;function c(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;const e=t;return e.version!==1||typeof e.text!="string"||!Array.isArray(e.sources)||e.text.trim()===""||e.sources.length===0||!e.sources.every(n=>typeof n=="string"&&n!=="")?null:{version:1,sources:e.sources.slice(0,200),text:e.text.slice(0,4e4)}}o(c,"normalizeTurnReply");function a(t){if(typeof t!="object"||t===null||Array.isArray(t))return{};const e={};for(const[n,i]of Object.entries(t)){if(n.trim()==="")continue;const r=c(i);r!==null&&(e[n]=r)}return e}o(a,"normalizeTurnReplyRecord");function x(t){if(typeof t!="object"||t===null)return;const e=t.timestamp;return typeof e=="number"&&Number.isFinite(e)?String(e):void 0}o(x,"messageKey");function R(t){return t.role==="assistant"&&t.stopReason!=="aborted"&&t.stopReason!=="error"}o(R,"isSettledAssistant");function d(t,e){if(t.length===0)return"";if(t.length===1)return t[0].text;const n=new Set(e?.sources);let i=-1;return t.forEach((r,s)=>{n.has(r.key)&&(i=s)}),i>=0?[e.text,...t.slice(i+1).map(r=>r.text)].join(`
2
2
 
3
- `)}return t.map(n=>n.text).join(`
3
+ `):t.map(r=>r.text).join(`
4
4
 
5
- `)}o(_,"turnReplyText");export{a as START_TURN_KEY,A as isSettledAssistant,R as messageKey,l as normalizeTurnReply,d as normalizeTurnReplyRecord,_ as turnReplyText};
5
+ `)}o(d,"turnReplyText");export{l as START_TURN_KEY,R as isSettledAssistant,x as messageKey,c as normalizeTurnReply,a as normalizeTurnReplyRecord,d as turnReplyText};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.705",
3
+ "version": "0.3.707",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "license": "UNLICENSED",
158
158
  "dependencies": {
159
- "@north-light/identity": "0.3.705",
160
- "@north-light/plugin": "0.3.705",
159
+ "@north-light/identity": "0.3.707",
160
+ "@north-light/plugin": "0.3.707",
161
161
  "@earendil-works/chord": "1.5.2",
162
162
  "@earendil-works/pi-agent-core": "1.5.2",
163
163
  "@earendil-works/pi-ai": "1.5.2",
@@ -115,22 +115,26 @@ class ForwardedViewLink extends EventEmitter {
115
115
  this.emit('close', this.failed);
116
116
  }
117
117
  }
118
- /** One readiness check: the Mac connected the node's view.sock within `timeoutMs`. The channel that connected is returned open, for the caller to use or destroy; null when it did not connect. */
119
- function openReadyMachineView(environmentId, nodeId, timeoutMs) {
118
+ /** One readiness check: the Mac connected the node's view.sock before `deadline`. A channel still pending is kept until it connects, closes, the deadline passes or the launch exits; the channel that connected is returned open, for the caller to use or destroy, and null when it closed, the deadline passed or the launch exited (a pending channel is destroyed then). */
119
+ function openReadyMachineView(environmentId, nodeId, deadline, exited) {
120
120
  return new Promise((resolve) => {
121
121
  const view = openMachineView(environmentId, nodeId);
122
+ const timeoutMs = Math.max(1, deadline - Date.now());
123
+ let settled = false;
124
+ const giveUp = () => { if (settled)
125
+ return; settled = true; clearTimeout(timer); resolve(null); view.destroy(); };
122
126
  const timer = setTimeout(() => {
123
127
  emitEvent({ level: 'info', event: 'daemon.timing.view_ready_timeout', node_id: nodeId, fields: { channel: view.channel ?? '', timeout_ms: timeoutMs } });
124
- resolve(null);
125
- view.destroy();
128
+ giveUp();
126
129
  }, timeoutMs);
130
+ void exited?.then(giveUp);
127
131
  // The no-op error listener stays on the returned channel until its user attaches its own: an error before then must not throw.
128
132
  view.on('error', () => { });
129
- view.on('connect', () => { clearTimeout(timer); resolve(view); });
130
- view.on('close', () => { clearTimeout(timer); resolve(null); });
133
+ view.on('connect', () => { settled = true; clearTimeout(timer); resolve(view); });
134
+ view.on('close', () => { settled = true; clearTimeout(timer); resolve(null); });
131
135
  });
132
136
  }
133
- /** 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. */
137
+ /** Wait for the node's broker on the Mac to accept a viewer, retrying a channel that closes (its view.sock refused) after 250 ms; a pending channel is waited on, not replaced. The accepted channel, open, or null on the deadline or when the launch exits. A caller that does not use the channel destroys it. */
134
138
  export async function waitForMachineView(environmentId, nodeId, exited, waitMs) {
135
139
  const deadline = Date.now() + waitMs;
136
140
  let exitSeen = false;
@@ -138,7 +142,7 @@ export async function waitForMachineView(environmentId, nodeId, exited, waitMs)
138
142
  // Each attempt's length and outcome land in the calling request's step timings (`probe_<n>_ready_ms` / `probe_<n>_failed_ms`), and `ready_received_at` marks the first ready.
139
143
  for (let attempt = 1; Date.now() <= deadline && !exitSeen; attempt++) {
140
144
  const started = performance.now();
141
- const ready = await openReadyMachineView(environmentId, nodeId, Math.max(1, Math.min(2000, deadline - Date.now())));
145
+ const ready = await openReadyMachineView(environmentId, nodeId, deadline, exited);
142
146
  addStepTiming(`probe_${attempt}_${ready !== null ? 'ready' : 'failed'}_ms`, performance.now() - started);
143
147
  if (ready !== null) {
144
148
  markAt('ready_received');
@@ -48,24 +48,19 @@ export function isSettledAssistant(message) {
48
48
  return message.role === 'assistant' && message.stopReason !== 'aborted' && message.stopReason !== 'error';
49
49
  }
50
50
  /** The text a viewer shows as a turn's reply. One prose message is the reply
51
- * verbatim. Otherwise the latest rewrite whose sources are all still in the turn,
52
- * followed by any later prose it does not cover, verbatim. A missing or stale
53
- * rewrite degrades to concatenation, never to a lost answer. */
51
+ * verbatim. Otherwise the latest rewrite, when it covers any prose the viewer
52
+ * holds, followed by the later prose verbatim; earlier sources may be outside the
53
+ * viewer's last messages. Without such a rewrite, the prose is concatenated. */
54
54
  export function turnReplyText(prose, reply) {
55
55
  if (prose.length === 0)
56
56
  return '';
57
57
  if (prose.length === 1)
58
58
  return prose[0].text;
59
- const keys = new Set(prose.map((item) => item.key));
60
- if (reply !== undefined && reply.sources.every((source) => keys.has(source))) {
61
- const covered = new Set(reply.sources);
62
- // Prose up to the last covered message is subsumed by the rewrite; only
63
- // messages after it are appended.
64
- let lastCovered = -1;
65
- prose.forEach((item, index) => { if (covered.has(item.key))
66
- lastCovered = index; });
67
- const tail = prose.slice(lastCovered + 1).map((item) => item.text);
68
- return [reply.text, ...tail].join('\n\n');
69
- }
59
+ const covered = new Set(reply?.sources);
60
+ let lastCovered = -1;
61
+ prose.forEach((item, index) => { if (covered.has(item.key))
62
+ lastCovered = index; });
63
+ if (lastCovered >= 0)
64
+ return [reply.text, ...prose.slice(lastCovered + 1).map((item) => item.text)].join('\n\n');
70
65
  return prose.map((item) => item.text).join('\n\n');
71
66
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.705",
3
+ "version": "0.3.707",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.705",
3
+ "version": "0.3.707",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.705",
3
+ "version": "0.3.707",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.705",
31
- "@north-light/identity": "0.3.705"
30
+ "@north-light/api": "0.3.707",
31
+ "@north-light/identity": "0.3.707"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.705",
3
+ "version": "0.3.707",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.705",
9
+ "version": "0.3.707",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.705",
32
- "@north-light/plugin": "0.3.705",
31
+ "@north-light/identity": "0.3.707",
32
+ "@north-light/plugin": "0.3.707",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -10667,17 +10667,17 @@
10667
10667
  },
10668
10668
  "packages/crouter-api": {
10669
10669
  "name": "@north-light/api",
10670
- "version": "0.3.705",
10670
+ "version": "0.3.707",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.705",
10675
+ "version": "0.3.707",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.705",
10680
+ "version": "0.3.707",
10681
10681
  "license": "UNLICENSED",
10682
10682
  "dependencies": {
10683
10683
  "jose": "^6.2.1"
@@ -10685,21 +10685,21 @@
10685
10685
  },
10686
10686
  "packages/crouter-plugin": {
10687
10687
  "name": "@north-light/plugin",
10688
- "version": "0.3.705",
10688
+ "version": "0.3.707",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.705",
10692
- "@north-light/identity": "0.3.705"
10691
+ "@north-light/api": "0.3.707",
10692
+ "@north-light/identity": "0.3.707"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.705",
10697
+ "version": "0.3.707",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.705",
10701
- "@north-light/identity": "0.3.705",
10702
- "@north-light/plugin": "0.3.705",
10700
+ "@north-light/api": "0.3.707",
10701
+ "@north-light/identity": "0.3.707",
10702
+ "@north-light/plugin": "0.3.707",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {