@north-light/cli 0.3.768 → 0.3.770

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.
@@ -0,0 +1,6 @@
1
+ -- 039-drop-import-tables.sql — drops the guest-import tables created by 008-import.sql: import_id_map and import_manifest (which reference import_runs), then import_runs. Guest machines are retired and hosted import is removed; since #1713 nothing reads or writes them.
2
+ -- Removes tables builds before #1713 still read (the start bundle's path map), so `schema_min_reader` rises to 39 and those builds refuse this database.
3
+ DROP TABLE import_id_map;
4
+ DROP TABLE import_manifest;
5
+ DROP TABLE import_runs;
6
+ INSERT INTO canvas_meta (key, value) VALUES ('schema_min_reader', '39') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 38;
4
+ export declare const CANVAS_SCHEMA_VERSION = 39;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=38;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=39;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -1,3 +1,4 @@
1
+ import type { Transport } from '../broker-client/index.js';
1
2
  import type { MessageOrigin } from './stamp/protocol.js';
2
3
  /** Which engine call the broker routed a live deliver to (its ack `detail`):
3
4
  * idle → `prompt`, turn in flight → `steer`. */
@@ -19,4 +20,4 @@ export declare function deliverLive(nodeId: string, text: string, opts?: {
19
20
  * once the broker has PROCESSED the abort — which, on the single frame loop,
20
21
  * also implies every earlier-accepted deliver was already routed (so a
21
22
  * just-delivered send cannot start its turn after this resolves un-aborted). */
22
- export declare function interruptLive(nodeId: string): Promise<LiveInterruptOutcome>;
23
+ export declare function interruptLive(nodeId: string, transport?: Transport): Promise<LiveInterruptOutcome>;
@@ -1 +1 @@
1
- var u=Object.defineProperty;var e=(t,r)=>u(t,"name",{value:r,configurable:!0});import{oneShotControllerRequest as a}from"./broker-request.js";function l(t,r,i={}){const o=i.cards??[];return a({nodeId:t,what:"the interactive delivery",ackFor:"deliver",correlated:!0,frame:e(n=>({type:"deliver",id:n,text:r,...o.length>0?{cards:[...o]}:{},...i.origin!==void 0?{origin:i.origin}:{}}),"frame"),result:e(n=>n==="steer"?"steer":"prompt","result")})}e(l,"deliverLive");function s(t){return a({nodeId:t,what:"the interrupt",ackFor:"abort",correlated:!0,frame:e(r=>({type:"abort",id:r}),"frame"),result:e(r=>r==="turn"||r==="bash"?r:"idle","result")})}e(s,"interruptLive");export{l as deliverLive,s as interruptLive};
1
+ var a=Object.defineProperty;var r=(i,t)=>a(i,"name",{value:t,configurable:!0});import{oneShotControllerRequest as u}from"./broker-request.js";function l(i,t,e={}){const o=e.cards??[];return u({nodeId:i,what:"the interactive delivery",ackFor:"deliver",correlated:!0,frame:r(n=>({type:"deliver",id:n,text:t,...o.length>0?{cards:[...o]}:{},...e.origin!==void 0?{origin:e.origin}:{}}),"frame"),result:r(n=>n==="steer"?"steer":"prompt","result")})}r(l,"deliverLive");function f(i,t){return u({nodeId:i,...t===void 0?{}:{transport:t},what:"the interrupt",ackFor:"abort",correlated:!0,frame:r(e=>({type:"abort",id:e}),"frame"),result:r(e=>e==="turn"||e==="bash"?e:"idle","result")})}r(f,"interruptLive");export{l as deliverLive,f as interruptLive};
@@ -1,6 +1,6 @@
1
- var C=Object.defineProperty;var o=(r,e)=>C(r,"name",{value:e,configurable:!0});import{randomUUID as k}from"node:crypto";import{ApiError as E}from"../../../api/errors.js";import{BrokerClient as B}from"../../../core/broker-client/client.js";import{getNode as p}from"../../../core/canvas/canvas.js";import{emitEvent as w}from"../../../core/events/emit.js";import{isPidAlive as L}from"../../../core/canvas/pid.js";import{BROKER_VIEW_SOCKET_WAIT_MS as D}from"../../../core/runtime/view-socket.js";import{openDb as M}from"../../../core/canvas/db.js";import{brokerSignalBus as $}from"../../broker-signals/bus.js";import{toNodeOutcomeDTO as P}from"../map.js";import{reportsForNode as x}from"./reports.js";import{runAsPerson as j}from"../../../core/canvas/person.js";const G=15e3,V=6e4,T=250,z=512,A=256*1024,H=1e3,J=32*1024*1024;class W{static{o(this,"NodeEventRing")}events=[];bytes=0;nextSequence=1;earliestAvailable=1;append(e){const t={...e,sequence_number:this.nextSequence++},s=Buffer.byteLength(JSON.stringify(t),"utf8");if(s>A)return this.events=[],this.bytes=0,this.earliestAvailable=this.nextSequence,t;for(this.events.push(t),this.bytes+=s;this.events.length>z||this.bytes>A;){const n=this.events.shift();if(n===void 0)break;this.bytes-=Buffer.byteLength(JSON.stringify(n),"utf8"),this.earliestAvailable=n.sequence_number+1}return t}replay(e){if(e===void 0)return{gap:null,events:this.events};const t=e<this.earliestAvailable-1||e>=this.nextSequence?R(this.earliestAvailable):null;return{gap:t,events:t===null?this.events.filter(s=>s.sequence_number>e):this.events}}get empty(){return this.events.length===0}}function R(r){return{type:"error",error:{code:"stream_gap",message:"the requested event cursor is older than this daemon can resume",details:{earliest_sequence:r}}}}o(R,"streamGap");function F(r){return r===null?"arguments: null":Array.isArray(r)?`arguments: array (${r.length} items)`:typeof r=="object"?`arguments: object (${Object.keys(r).length} fields)`:`arguments: ${typeof r}`}o(F,"toolSummary");function m(r){if(typeof r!="object"||r===null)return"";const e=r.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null).filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(""):""}o(m,"assistantText");class N{static{o(this,"NodeEventTranslationState")}toolSummaries=new Map;emittedAssistantText="";resetAssistantText(){this.emittedAssistantText=""}emitAssistantTextDelta(e){const t=m(e),s=t.startsWith(this.emittedAssistantText)?t.slice(this.emittedAssistantText.length):t;return this.emittedAssistantText=t,s}seedAssistantText(e){const t=m(e);return this.emittedAssistantText=t,t}}function K(r,e,t=new N){switch(e.type){case"message_start":return e.message.role==="assistant"&&t.resetAssistantText(),[];case"message_update":{if(e.message.role!=="assistant")return[];const s=t.emitAssistantTextDelta(e.message);return s===""?[]:[{type:"node.output_text.delta",node_id:r,delta:s}]}case"message_end":{if(e.message.role!=="assistant")return[];const s=m(e.message);return t.resetAssistantText(),[{type:"node.output_text.done",node_id:r,text:s}]}case"tool_execution_start":{const s=F(e.args);return t.toolSummaries.set(e.toolCallId,s),[{type:"node.tool_call.started",node_id:r,tool_call_id:e.toolCallId,tool:e.toolName,summary:s}]}case"tool_execution_end":{const s=t.toolSummaries.get(e.toolCallId)??"[arguments unavailable]";return t.toolSummaries.delete(e.toolCallId),[{type:"node.tool_call.completed",node_id:r,tool_call_id:e.toolCallId,tool:e.toolName,status:e.isError?"error":"ok",summary:s}]}case"turn_start":return[{type:"node.turn.started",node_id:r}];case"turn_end":return[{type:"node.turn.completed",node_id:r}];default:return[]}}o(K,"translateBrokerFrame");class U{static{o(this,"NodeEventHub")}nodeId;remove;ring=new W;subscribers=new Set;observer;observerErrorAt;poll;reconnect;idleClose;status;settledRevision;settledOutcome;settledSequence;snapshotSeeded=!1;reportsSeeded=!1;publishedReports=new Set;translationState=new N;fresh=!0;constructor(e,t){this.nodeId=e,this.remove=t}async subscribe(e,t){const s=this.fresh&&e!==void 0;this.fresh=!1,await this.start();const n=this.settledOutcome!==void 0,a=s?{gap:R(1),events:this.ring.replay(void 0).events}:this.ring.replay(e);n||(this.subscribers.add(t),this.status!=="dormant"&&await this.openObserver());let h=!1;return queueMicrotask(()=>{if(!h){a.gap!==null&&t(a.gap);for(const u of a.events)t(u)}}),n&&this.scheduleIdleClose(),{unsubscribe:o(()=>{h=!0,n||this.unsubscribe(t)},"unsubscribe"),terminal:n}}report(e){this.settledRevision!==void 0||this.publishedReports.has(e.id)||(this.publishedReports.add(e.id),this.publish({type:"node.report.pushed",node_id:this.nodeId,report:e}))}async start(){this.idleClose!==void 0&&(clearTimeout(this.idleClose),this.idleClose=void 0),this.poll===void 0&&(await this.check(),this.settledRevision===void 0&&(await this.seedReports(),this.poll=setInterval(()=>this.checkDetached(),T)))}async seedReports(){if(!this.reportsSeeded){this.reportsSeeded=!0;for(const e of(await this.storedReports()).reverse())this.report(e)}}async storedReports(){const e=(await p(this.nodeId))?.sub;return e?await j(e,()=>x(this.nodeId)):await x(this.nodeId)}async refreshReports(){if(!(!this.reportsSeeded||this.settledRevision!==void 0))for(const e of(await this.storedReports()).reverse())this.report(e)}async check(){const e=await p(this.nodeId);if(e===null){this.fail("stream_error",`node ${this.nodeId} no longer exists`);return}const t=await P(e);if(t!==null){this.settledRevision!==t.revision&&(this.settledRevision=t.revision,this.settledOutcome=t,this.settledSequence=this.publish({type:"node.settled",node_id:this.nodeId,outcome:t}).sequence_number,this.stopObserver(),this.stopPoll());return}const s=e.pi_pid===null?"dormant":e.status;if(s==="dormant"){this.observerErrorAt=void 0,this.status!=="dormant"&&(this.status=s,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s}));return}this.status===void 0?this.status=s:this.status!=="dormant"&&this.status!==s&&(this.status=s,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s})),await this.openObserver()}async openObserver(){if(this.observer!==void 0||this.subscribers.size===0)return;const e=new B(this.nodeId);this.observer=e,e.on("connect",()=>{(async()=>{this.observerErrorAt=void 0;const t=await p(this.nodeId);this.status==="dormant"&&t!==null&&t.pi_pid!==null&&(this.status=t.status,this.publish({type:"node.status.changed",node_id:this.nodeId,status:t.status})),e.send({type:"hello",role:"observer",client_id:k(),attends:!1})})().catch(t=>this.fail("stream_error",t instanceof Error?t.message:String(t)))}),e.on("frame",t=>{try{t.type==="welcome"&&this.seedSnapshot(t.snapshot);for(const s of K(this.nodeId,t,this.translationState))this.publish(s)}catch(s){this.fail("stream_error",s instanceof Error?s.message:String(s))}}),e.on("error",()=>{(async()=>{const t=await p(this.nodeId),s=Date.now();if(t!==null&&t.pi_pid!==null&&L(t.pi_pid)){if(this.observerErrorAt??=s,s-this.observerErrorAt<D)return;this.fail("stream_error","observer connection failed");return}this.observerErrorAt=void 0})().catch(t=>this.fail("stream_error",t instanceof Error?t.message:String(t)))}),e.on("close",()=>{this.observer===e&&(this.observer=void 0,!(this.subscribers.size===0||this.settledRevision!==void 0)&&(this.status!=="dormant"&&(this.publish({type:"node.status.changed",node_id:this.nodeId,status:"dormant"}),this.status="dormant"),this.scheduleReconnect()))}),e.connect()}seedSnapshot(e){if(this.snapshotSeeded)return;this.snapshotSeeded=!0;const t=e.messages.filter(n=>n.role==="assistant"),s=e.state.isStreaming?t.pop():void 0;for(const n of t)this.publish({type:"node.output_text.done",node_id:this.nodeId,text:m(n)});s!==void 0&&this.publish({type:"node.output_text.delta",node_id:this.nodeId,delta:this.translationState.seedAssistantText(s)})}scheduleReconnect(){this.reconnect===void 0&&(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.checkDetached()},T))}checkDetached(){this.check().catch(e=>w({level:"error",event:"api.node_events.check_failed",node_id:this.nodeId,error:e}))}publish(e){const t=this.ring.append(e);for(const s of[...this.subscribers])s(t);return t}fail(e,t){const s={type:"error",error:{code:e,message:t}};for(const n of[...this.subscribers])n(s);this.stopObserver(),this.stopPoll()}unsubscribe(e){this.subscribers.delete(e),this.subscribers.size===0&&this.scheduleIdleClose()}scheduleIdleClose(){this.idleClose===void 0&&(this.idleClose=setTimeout(()=>{this.stopObserver(),this.stopPoll(),this.remove()},V))}stopObserver(){this.reconnect!==void 0&&(clearTimeout(this.reconnect),this.reconnect=void 0);const e=this.observer;this.observer=void 0,e?.close()}stopPoll(){this.poll!==void 0&&(clearInterval(this.poll),this.poll=void 0)}}class Y{static{o(this,"NodeEventStreams")}hubs=new Map;unsubscribeBus;refresh(e){this.hubs.get(e)?.refreshReports().catch(t=>w({level:"error",event:"api.node_events.report_refresh_failed",node_id:e,error:t}))}listen(){this.unsubscribeBus??=$.subscribe(e=>this.refresh(e),{kinds:["report"],onListenStart:o(()=>{for(const e of[...this.hubs.keys()])this.refresh(e)},"onListenStart")})}remove(e){if(this.hubs.delete(e),this.hubs.size===0){const t=this.unsubscribeBus;this.unsubscribeBus=void 0,t?.then(s=>s())}}async subscribe(e,t,s){let n=this.hubs.get(e);return n===void 0&&(n=new U(e,()=>this.remove(e)),this.hubs.set(e,n),this.listen()),await n.subscribe(t,s)}report(e,t){this.hubs.get(e)?.report(t),M().then(s=>s.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`report:${e}`)).catch(s=>w({level:"error",event:"api.node_events.report_signal_failed",node_id:e,error:s}))}}const Q=new Y;function X(r){const e=r.get("after");if(e===null||e==="")return{};if(!/^(?:0|[1-9]\d*)$/.test(e))throw new E(400,"invalid_request","`after` must be a non-negative integer");const t=Number(e);if(!Number.isSafeInteger(t))throw new E(400,"invalid_request","`after` must be a safe integer");return{after:t}}o(X,"parseQuery");function I(r){const{type:e,...t}=r;return`event: ${e}
1
+ var C=Object.defineProperty;var o=(n,e)=>C(n,"name",{value:e,configurable:!0});import{randomUUID as k}from"node:crypto";import{ApiError as E}from"../../../api/errors.js";import{BrokerClient as B}from"../../../core/broker-client/client.js";import{viewTransport as L}from"../../runs/observer.js";import{getNode as p}from"../../../core/canvas/canvas.js";import{emitEvent as w}from"../../../core/events/emit.js";import{isPidAlive as D}from"../../../core/canvas/pid.js";import{BROKER_VIEW_SOCKET_WAIT_MS as M}from"../../../core/runtime/view-socket.js";import{openDb as $}from"../../../core/canvas/db.js";import{brokerSignalBus as P}from"../../broker-signals/bus.js";import{toNodeOutcomeDTO as j}from"../map.js";import{reportsForNode as x}from"./reports.js";import{runAsPerson as G}from"../../../core/canvas/person.js";const z=15e3,V=6e4,T=250,H=512,A=256*1024,J=1e3,W=32*1024*1024;class F{static{o(this,"NodeEventRing")}events=[];bytes=0;nextSequence=1;earliestAvailable=1;append(e){const t={...e,sequence_number:this.nextSequence++},s=Buffer.byteLength(JSON.stringify(t),"utf8");if(s>A)return this.events=[],this.bytes=0,this.earliestAvailable=this.nextSequence,t;for(this.events.push(t),this.bytes+=s;this.events.length>H||this.bytes>A;){const r=this.events.shift();if(r===void 0)break;this.bytes-=Buffer.byteLength(JSON.stringify(r),"utf8"),this.earliestAvailable=r.sequence_number+1}return t}replay(e){if(e===void 0)return{gap:null,events:this.events};const t=e<this.earliestAvailable-1||e>=this.nextSequence?R(this.earliestAvailable):null;return{gap:t,events:t===null?this.events.filter(s=>s.sequence_number>e):this.events}}get empty(){return this.events.length===0}}function R(n){return{type:"error",error:{code:"stream_gap",message:"the requested event cursor is older than this daemon can resume",details:{earliest_sequence:n}}}}o(R,"streamGap");function K(n){return n===null?"arguments: null":Array.isArray(n)?`arguments: array (${n.length} items)`:typeof n=="object"?`arguments: object (${Object.keys(n).length} fields)`:`arguments: ${typeof n}`}o(K,"toolSummary");function m(n){if(typeof n!="object"||n===null)return"";const e=n.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null).filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(""):""}o(m,"assistantText");class N{static{o(this,"NodeEventTranslationState")}toolSummaries=new Map;emittedAssistantText="";resetAssistantText(){this.emittedAssistantText=""}emitAssistantTextDelta(e){const t=m(e),s=t.startsWith(this.emittedAssistantText)?t.slice(this.emittedAssistantText.length):t;return this.emittedAssistantText=t,s}seedAssistantText(e){const t=m(e);return this.emittedAssistantText=t,t}}function U(n,e,t=new N){switch(e.type){case"message_start":return e.message.role==="assistant"&&t.resetAssistantText(),[];case"message_update":{if(e.message.role!=="assistant")return[];const s=t.emitAssistantTextDelta(e.message);return s===""?[]:[{type:"node.output_text.delta",node_id:n,delta:s}]}case"message_end":{if(e.message.role!=="assistant")return[];const s=m(e.message);return t.resetAssistantText(),[{type:"node.output_text.done",node_id:n,text:s}]}case"tool_execution_start":{const s=K(e.args);return t.toolSummaries.set(e.toolCallId,s),[{type:"node.tool_call.started",node_id:n,tool_call_id:e.toolCallId,tool:e.toolName,summary:s}]}case"tool_execution_end":{const s=t.toolSummaries.get(e.toolCallId)??"[arguments unavailable]";return t.toolSummaries.delete(e.toolCallId),[{type:"node.tool_call.completed",node_id:n,tool_call_id:e.toolCallId,tool:e.toolName,status:e.isError?"error":"ok",summary:s}]}case"turn_start":return[{type:"node.turn.started",node_id:n}];case"turn_end":return[{type:"node.turn.completed",node_id:n}];default:return[]}}o(U,"translateBrokerFrame");class Y{static{o(this,"NodeEventHub")}nodeId;remove;ring=new F;subscribers=new Set;observer;opening=!1;observerErrorAt;poll;reconnect;idleClose;status;settledRevision;settledOutcome;settledSequence;snapshotSeeded=!1;reportsSeeded=!1;publishedReports=new Set;translationState=new N;fresh=!0;constructor(e,t){this.nodeId=e,this.remove=t}async subscribe(e,t){const s=this.fresh&&e!==void 0;this.fresh=!1,await this.start();const r=this.settledOutcome!==void 0,a=s?{gap:R(1),events:this.ring.replay(void 0).events}:this.ring.replay(e);r||(this.subscribers.add(t),this.status!=="dormant"&&await this.openObserver());let h=!1;return queueMicrotask(()=>{if(!h){a.gap!==null&&t(a.gap);for(const u of a.events)t(u)}}),r&&this.scheduleIdleClose(),{unsubscribe:o(()=>{h=!0,r||this.unsubscribe(t)},"unsubscribe"),terminal:r}}report(e){this.settledRevision!==void 0||this.publishedReports.has(e.id)||(this.publishedReports.add(e.id),this.publish({type:"node.report.pushed",node_id:this.nodeId,report:e}))}async start(){this.idleClose!==void 0&&(clearTimeout(this.idleClose),this.idleClose=void 0),this.poll===void 0&&(await this.check(),this.settledRevision===void 0&&(await this.seedReports(),this.poll=setInterval(()=>this.checkDetached(),T)))}async seedReports(){if(!this.reportsSeeded){this.reportsSeeded=!0;for(const e of(await this.storedReports()).reverse())this.report(e)}}async storedReports(){const e=(await p(this.nodeId))?.sub;return e?await G(e,()=>x(this.nodeId)):await x(this.nodeId)}async refreshReports(){if(!(!this.reportsSeeded||this.settledRevision!==void 0))for(const e of(await this.storedReports()).reverse())this.report(e)}async check(){const e=await p(this.nodeId);if(e===null){this.fail("stream_error",`node ${this.nodeId} no longer exists`);return}const t=await j(e);if(t!==null){this.settledRevision!==t.revision&&(this.settledRevision=t.revision,this.settledOutcome=t,this.settledSequence=this.publish({type:"node.settled",node_id:this.nodeId,outcome:t}).sequence_number,this.stopObserver(),this.stopPoll());return}const s=e.pi_pid===null?"dormant":e.status;if(s==="dormant"){this.observerErrorAt=void 0,this.status!=="dormant"&&(this.status=s,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s}));return}this.status===void 0?this.status=s:this.status!=="dormant"&&this.status!==s&&(this.status=s,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s})),await this.openObserver()}async openObserver(){if(this.observer!==void 0||this.subscribers.size===0||this.opening)return;this.opening=!0;let e;try{e=await L(this.nodeId)}finally{this.opening=!1}if(this.observer!==void 0||this.subscribers.size===0){e.destroy();return}const t=new B(this.nodeId,{transport:e});this.observer=t,t.on("connect",()=>{(async()=>{this.observerErrorAt=void 0;const s=await p(this.nodeId);this.status==="dormant"&&s!==null&&s.pi_pid!==null&&(this.status=s.status,this.publish({type:"node.status.changed",node_id:this.nodeId,status:s.status})),t.send({type:"hello",role:"observer",client_id:k(),attends:!1})})().catch(s=>this.fail("stream_error",s instanceof Error?s.message:String(s)))}),t.on("frame",s=>{try{s.type==="welcome"&&this.seedSnapshot(s.snapshot);for(const r of U(this.nodeId,s,this.translationState))this.publish(r)}catch(r){this.fail("stream_error",r instanceof Error?r.message:String(r))}}),t.on("error",()=>{(async()=>{const s=await p(this.nodeId),r=Date.now();if(s!==null&&s.pi_pid!==null&&D(s.pi_pid)){if(this.observerErrorAt??=r,r-this.observerErrorAt<M)return;this.fail("stream_error","observer connection failed");return}this.observerErrorAt=void 0})().catch(s=>this.fail("stream_error",s instanceof Error?s.message:String(s)))}),t.on("close",()=>{this.observer===t&&(this.observer=void 0,!(this.subscribers.size===0||this.settledRevision!==void 0)&&(this.status!=="dormant"&&(this.publish({type:"node.status.changed",node_id:this.nodeId,status:"dormant"}),this.status="dormant"),this.scheduleReconnect()))}),t.connect()}seedSnapshot(e){if(this.snapshotSeeded)return;this.snapshotSeeded=!0;const t=e.messages.filter(r=>r.role==="assistant"),s=e.state.isStreaming?t.pop():void 0;for(const r of t)this.publish({type:"node.output_text.done",node_id:this.nodeId,text:m(r)});s!==void 0&&this.publish({type:"node.output_text.delta",node_id:this.nodeId,delta:this.translationState.seedAssistantText(s)})}scheduleReconnect(){this.reconnect===void 0&&(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.checkDetached()},T))}checkDetached(){this.check().catch(e=>w({level:"error",event:"api.node_events.check_failed",node_id:this.nodeId,error:e}))}publish(e){const t=this.ring.append(e);for(const s of[...this.subscribers])s(t);return t}fail(e,t){const s={type:"error",error:{code:e,message:t}};for(const r of[...this.subscribers])r(s);this.stopObserver(),this.stopPoll()}unsubscribe(e){this.subscribers.delete(e),this.subscribers.size===0&&this.scheduleIdleClose()}scheduleIdleClose(){this.idleClose===void 0&&(this.idleClose=setTimeout(()=>{this.stopObserver(),this.stopPoll(),this.remove()},V))}stopObserver(){this.reconnect!==void 0&&(clearTimeout(this.reconnect),this.reconnect=void 0);const e=this.observer;this.observer=void 0,e?.close()}stopPoll(){this.poll!==void 0&&(clearInterval(this.poll),this.poll=void 0)}}class Q{static{o(this,"NodeEventStreams")}hubs=new Map;unsubscribeBus;refresh(e){this.hubs.get(e)?.refreshReports().catch(t=>w({level:"error",event:"api.node_events.report_refresh_failed",node_id:e,error:t}))}listen(){this.unsubscribeBus??=P.subscribe(e=>this.refresh(e),{kinds:["report"],onListenStart:o(()=>{for(const e of[...this.hubs.keys()])this.refresh(e)},"onListenStart")})}remove(e){if(this.hubs.delete(e),this.hubs.size===0){const t=this.unsubscribeBus;this.unsubscribeBus=void 0,t?.then(s=>s())}}async subscribe(e,t,s){let r=this.hubs.get(e);return r===void 0&&(r=new Y(e,()=>this.remove(e)),this.hubs.set(e,r),this.listen()),await r.subscribe(t,s)}report(e,t){this.hubs.get(e)?.report(t),$().then(s=>s.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`report:${e}`)).catch(s=>w({level:"error",event:"api.node_events.report_signal_failed",node_id:e,error:s}))}}const X=new Q;function Z(n){const e=n.get("after");if(e===null||e==="")return{};if(!/^(?:0|[1-9]\d*)$/.test(e))throw new E(400,"invalid_request","`after` must be a non-negative integer");const t=Number(e);if(!Number.isSafeInteger(t))throw new E(400,"invalid_request","`after` must be a safe integer");return{after:t}}o(Z,"parseQuery");function I(n){const{type:e,...t}=n;return`event: ${e}
2
2
  data: ${JSON.stringify(t)}
3
3
 
4
- `}o(I,"sseRecord");async function Z(r){const e=r.params.id??"";if(await p(e)===null)throw new E(404,"node_not_found",`no node ${e}`);const{after:t}=X(r.query),{req:s,res:n}=r;n.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"});let a=!1,h=!1,u=!1,c=0;const d=[];let v,f;const _=o(()=>{n.writableEnded||n.end()},"finish"),b=o(()=>{if(!a){if(a=!0,f!==void 0&&clearInterval(f),v?.(),n.destroyed){d.length=0,c=0,_();return}if(u||d.length>0){h=!0;return}_()}},"close"),y=o(()=>{for(u=!1;d.length>0;){const i=d.shift();if(c-=Buffer.byteLength(i,"utf8"),!n.write(i)){u=!0,n.once("drain",y);return}}h&&_()},"flush"),O=o(()=>{if(a)return;d.length=0,c=0;const i=I({type:"error",error:{code:"stream_dropped",message:"stream reader is too slow"}});d.push(i),c=Buffer.byteLength(i,"utf8"),a=!0,h=!0,f!==void 0&&clearInterval(f),v?.(),u||y()},"dropSlowReader"),g=o(i=>{if(a)return!1;if(u||d.length>0){const l=Buffer.byteLength(i,"utf8");return d.length>=H||c+l>J?(O(),!1):(d.push(i),c+=l,!0)}return n.write(i)||(u=!0,n.once("drain",y)),!0},"write"),S=o((i,l)=>{a||g(I({type:"error",error:{code:i,message:l}})),b()},"fail"),q=o(i=>{try{if(!g(I(i)))return;(i.type==="node.settled"||i.type==="error"&&i.error.code!=="stream_gap")&&b()}catch(l){S("stream_error",l instanceof Error?l.message:String(l))}},"onEvent");f=setInterval(()=>{try{a||g(`: keepalive
4
+ `}o(I,"sseRecord");async function ee(n){const e=n.params.id??"";if(await p(e)===null)throw new E(404,"node_not_found",`no node ${e}`);const{after:t}=Z(n.query),{req:s,res:r}=n;r.writeHead(200,{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache",connection:"keep-alive"});let a=!1,h=!1,u=!1,c=0;const d=[];let v,f;const _=o(()=>{r.writableEnded||r.end()},"finish"),b=o(()=>{if(!a){if(a=!0,f!==void 0&&clearInterval(f),v?.(),r.destroyed){d.length=0,c=0,_();return}if(u||d.length>0){h=!0;return}_()}},"close"),g=o(()=>{for(u=!1;d.length>0;){const i=d.shift();if(c-=Buffer.byteLength(i,"utf8"),!r.write(i)){u=!0,r.once("drain",g);return}}h&&_()},"flush"),O=o(()=>{if(a)return;d.length=0,c=0;const i=I({type:"error",error:{code:"stream_dropped",message:"stream reader is too slow"}});d.push(i),c=Buffer.byteLength(i,"utf8"),a=!0,h=!0,f!==void 0&&clearInterval(f),v?.(),u||g()},"dropSlowReader"),y=o(i=>{if(a)return!1;if(u||d.length>0){const l=Buffer.byteLength(i,"utf8");return d.length>=J||c+l>W?(O(),!1):(d.push(i),c+=l,!0)}return r.write(i)||(u=!0,r.once("drain",g)),!0},"write"),S=o((i,l)=>{a||y(I({type:"error",error:{code:i,message:l}})),b()},"fail"),q=o(i=>{try{if(!y(I(i)))return;(i.type==="node.settled"||i.type==="error"&&i.error.code!=="stream_gap")&&b()}catch(l){S("stream_error",l instanceof Error?l.message:String(l))}},"onEvent");f=setInterval(()=>{try{a||y(`: keepalive
5
5
 
6
- `)}catch(i){S("stream_error",i instanceof Error?i.message:String(i))}},G),s.once("close",b);try{const i=await Q.subscribe(e,t,q);v=i.unsubscribe,i.terminal&&queueMicrotask(b)}catch(i){S("stream_error",i instanceof Error?i.message:String(i))}return{status:200}}o(Z,"handleEvents");const fe=[{method:"GET",pattern:"/v1/nodes/:id/events",handler:Z}];export{W as NodeEventRing,N as NodeEventTranslationState,fe as nodeEventRoutes,Q as nodeEventStreams,K as translateBrokerFrame};
6
+ `)}catch(i){S("stream_error",i instanceof Error?i.message:String(i))}},z),s.once("close",b);try{const i=await X.subscribe(e,t,q);v=i.unsubscribe,i.terminal&&queueMicrotask(b)}catch(i){S("stream_error",i instanceof Error?i.message:String(i))}return{status:200}}o(ee,"handleEvents");const be=[{method:"GET",pattern:"/v1/nodes/:id/events",handler:ee}];export{F as NodeEventRing,N as NodeEventTranslationState,be as nodeEventRoutes,X as nodeEventStreams,U as translateBrokerFrame};
@@ -1,13 +1,13 @@
1
- var I=Object.defineProperty;var m=(i,e)=>I(i,"name",{value:e,configurable:!0});import{randomUUID as x}from"node:crypto";import{withCanvasWrite as T}from"../../core/canvas/db.js";import{enqueueNodeMail as R}from"../../core/feed/messages.js";import{readNodeMessagesPage as q}from"../../core/runtime/node-read.js";import{interruptLive as P}from"../../core/runtime/interactive-deliver.js";import{isBrokerLive as C}from"../../core/runtime/model-swap.js";import{reviveNode as S}from"../../core/runtime/revive.js";import{BrokerUnreachableError as A}from"../../core/runtime/broker-request.js";import{nodeEventStreams as N}from"./handlers/node-events.js";import{getNode as h}from"../../core/canvas/canvas.js";import{personId as B}from"../../core/canvas/person.js";import{createComment as G,getComment as D,deleteComment as O,editComment as U,listComments as L,reopenComment as W,resolveComment as $}from"../../core/review/comments.js";import{anchorInDocument as j,renderedText as H,resolveAnchor as J}from"../../core/review/anchors.js";import{currentReviewText as M}from"../../core/review/document.js";import{requireVisibleReview as V}from"../../core/review/store.js";import{ReviewOperationError as k}from"../../core/review/types.js";import{cancelReview as z,submitReviewApproval as F}from"../review/finish.js";import{notifyComment as X}from"../review/comment-notify.js";import{brokerSignalBus as K}from"../broker-signals/bus.js";import{toReviewCommentDTO as b}from"./map.js";import{documentShell as Q,documentSnapshot as Y,error as l,json as f,requestBody as Z,resolveDocument as g}from"./document-page.js";const w=m(i=>(l(i,404,"not_found","review not found"),!0),"notFound");async function v(i){if(i===null||i==="")return null;let e;try{e=await V(i)}catch(r){if(r instanceof k)return null;throw r}if(e.document_id===null)return null;const a=await h(e.origin_node_id);return a===null||a.sub!==void 0&&a.sub!==null&&a.sub!==B()||await g(e.document_id)===null?null:e}m(v,"visibleReview");function ee(i,e){if(!(e instanceof k))throw e;const a=e.code==="unknown_comment"||e.code==="unknown_review"?404:e.code==="invalid_anchor"||e.code==="text_too_long"?400:409;return l(i,a,e.code,e.message),!0}m(ee,"failure");async function te(i){const e=await g(i.document_id),a=e&&await Y(e);if(!a)return null;const r=H(a.body),p=(await L(i.review_id,{status:"all"})).filter(c=>c.status!=="deleted").map(c=>({...b(c),location:J(r,c.anchor)}));return{review:{id:i.review_id,state:i.state,title:i.document_name,subtitle:i.subtitle,submit_requested_at:i.submit_requested_at},document:a,comments:p,companion:{node_id:i.companion_node_id}}}m(te,"reviewPayload");async function ke(i,e,a){const r=a.pathname;if(i.method==="GET"&&r.startsWith("/review/")){const n=await v(decodeURIComponent(r.slice(8))),t=n&&await g(n.document_id);return!n||!t?w(e):(Q(e,t.id,t,n.review_id),!0)}if(!r.startsWith("/api/review"))return!1;if(i.method==="GET"&&r==="/api/review"){const n=await v(a.searchParams.get("id")),t=n&&await te(n);return t?(f(e,200,t),!0):w(e)}if(i.method==="GET"&&r==="/api/review/chat"){const n=await v(a.searchParams.get("id"));if(!n)return w(e);const t=a.searchParams.get("cursor"),o=await q(n.companion_node_id,{...t?{cursor:t}:{},limit:200});return f(e,200,{messages:o.messages,message_ids:o.messageIds??[],message_visibility:o.messageVisibility,next_cursor:o.nextCursor}),!0}if(i.method==="GET"&&r==="/api/review/chat/stream"){const n=await v(a.searchParams.get("id"));if(!n)return w(e);e.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"});const t=m(d=>{if(e.writableEnded)return;const{type:_,...E}=d;e.write(`event: ${_}
1
+ var T=Object.defineProperty;var m=(i,e)=>T(i,"name",{value:e,configurable:!0});import{randomUUID as y}from"node:crypto";import{withCanvasWrite as I}from"../../core/canvas/db.js";import{enqueueNodeMail as R}from"../../core/feed/messages.js";import{readNodeMessagesPage as q}from"../../core/runtime/node-read.js";import{interruptLive as P}from"../../core/runtime/interactive-deliver.js";import{liveExecutionForNode as x}from"../../core/canvas/executions.js";import{viewTransport as S}from"../runs/observer.js";import{reviveNode as N}from"../../core/runtime/revive.js";import{BrokerUnreachableError as A}from"../../core/runtime/broker-request.js";import{nodeEventStreams as G}from"./handlers/node-events.js";import{getNode as C}from"../../core/canvas/canvas.js";import{personId as B}from"../../core/canvas/person.js";import{createComment as D,getComment as O,deleteComment as U,editComment as W,listComments as $,reopenComment as j,resolveComment as F}from"../../core/review/comments.js";import{anchorInDocument as H,renderedText as J,resolveAnchor as L}from"../../core/review/anchors.js";import{currentReviewText as M}from"../../core/review/document.js";import{requireVisibleReview as V}from"../../core/review/store.js";import{ReviewOperationError as k}from"../../core/review/types.js";import{cancelReview as z,submitReviewApproval as X}from"../review/finish.js";import{notifyComment as K}from"../review/comment-notify.js";import{brokerSignalBus as Q}from"../broker-signals/bus.js";import{toReviewCommentDTO as h}from"./map.js";import{documentShell as Y,documentSnapshot as Z,error as l,json as f,requestBody as ee,resolveDocument as b}from"./document-page.js";const w=m(i=>(l(i,404,"not_found","review not found"),!0),"notFound");async function v(i){if(i===null||i==="")return null;let e;try{e=await V(i)}catch(r){if(r instanceof k)return null;throw r}if(e.document_id===null)return null;const a=await C(e.origin_node_id);return a===null||a.sub!==void 0&&a.sub!==null&&a.sub!==B()||await b(e.document_id)===null?null:e}m(v,"visibleReview");function te(i,e){if(!(e instanceof k))throw e;const a=e.code==="unknown_comment"||e.code==="unknown_review"?404:e.code==="invalid_anchor"||e.code==="text_too_long"?400:409;return l(i,a,e.code,e.message),!0}m(te,"failure");async function ie(i){const e=await b(i.document_id),a=e&&await Z(e);if(!a)return null;const r=J(a.body),p=(await $(i.review_id,{status:"all"})).filter(c=>c.status!=="deleted").map(c=>({...h(c),location:L(r,c.anchor)}));return{review:{id:i.review_id,state:i.state,title:i.document_name,subtitle:i.subtitle,submit_requested_at:i.submit_requested_at},document:a,comments:p,companion:{node_id:i.companion_node_id}}}m(ie,"reviewPayload");async function Te(i,e,a){const r=a.pathname;if(i.method==="GET"&&r.startsWith("/review/")){const n=await v(decodeURIComponent(r.slice(8))),t=n&&await b(n.document_id);return!n||!t?w(e):(Y(e,t.id,t,n.review_id),!0)}if(!r.startsWith("/api/review"))return!1;if(i.method==="GET"&&r==="/api/review"){const n=await v(a.searchParams.get("id")),t=n&&await ie(n);return t?(f(e,200,t),!0):w(e)}if(i.method==="GET"&&r==="/api/review/chat"){const n=await v(a.searchParams.get("id"));if(!n)return w(e);const t=a.searchParams.get("cursor"),o=await q(n.companion_node_id,{...t?{cursor:t}:{},limit:200});return f(e,200,{messages:o.messages,message_ids:o.messageIds??[],message_visibility:o.messageVisibility,next_cursor:o.nextCursor}),!0}if(i.method==="GET"&&r==="/api/review/chat/stream"){const n=await v(a.searchParams.get("id"));if(!n)return w(e);e.writeHead(200,{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"});const t=m(d=>{if(e.writableEnded)return;const{type:_,...E}=d;e.write(`event: ${_}
2
2
  data: ${JSON.stringify(E)}
3
3
 
4
4
  `)},"send"),o=setInterval(()=>{e.writableEnded||e.write(`: keepalive
5
5
 
6
- `)},15e3);let s=m(()=>{},"unsubscribe");e.on("close",()=>{clearInterval(o),s()});try{s=(await N.subscribe(n.companion_node_id,void 0,t)).unsubscribe}catch(d){throw clearInterval(o),e.end(),d}return e.destroyed&&s(),!0}if(i.method==="GET"&&r==="/api/review/events"){const n=await v(a.searchParams.get("id"));if(!n)return w(e);e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),e.write(`: connected
6
+ `)},15e3);let s=m(()=>{},"unsubscribe");e.on("close",()=>{clearInterval(o),s()});try{s=(await G.subscribe(n.companion_node_id,void 0,t)).unsubscribe}catch(d){throw clearInterval(o),e.end(),d}return e.destroyed&&s(),!0}if(i.method==="GET"&&r==="/api/review/events"){const n=await v(a.searchParams.get("id"));if(!n)return w(e);e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),e.write(`: connected
7
7
 
8
8
  `);const t=m(()=>{e.writableEnded||e.write(`event: changed
9
9
  data: {}
10
10
 
11
- `)},"changed"),o=await K.subscribe(d=>{(d===n.review_id||d===n.document_id)&&t()},{kinds:["review","document"],onListenStart:t}),s=setInterval(()=>{e.writableEnded||e.write(`: keepalive
11
+ `)},"changed"),o=await Q.subscribe(d=>{(d===n.review_id||d===n.document_id)&&t()},{kinds:["review","document"],onListenStart:t}),s=setInterval(()=>{e.writableEnded||e.write(`: keepalive
12
12
 
13
- `)},3e4);return e.on("close",()=>{clearInterval(s),o()}),!0}if(i.method!=="POST")return!1;const p=await Z(i);if(!p||typeof p!="object"||Array.isArray(p))return l(e,400,"invalid_request","invalid body"),!0;const c=p,u=await v(typeof c.review_id=="string"?c.review_id:null);if(!u)return w(e);const y={kind:"human",node_id:null};try{if(r==="/api/review/comments"){const t=c.anchor;if(typeof c.text!="string"||!t||typeof t.quote!="string")return l(e,400,"invalid_request","text and anchor.quote are required"),!0;if(u.state!=="open")return l(e,409,"review_terminal","review already has a terminal outcome"),!0;const o=x(),s=j(await T(_=>M(_,u)),{quote:t.quote,...typeof t.prefix=="string"?{prefix:t.prefix}:{},...typeof t.suffix=="string"?{suffix:t.suffix}:{},...typeof t.offset=="number"?{offset:t.offset}:{}}),d=await G({review_id:u.review_id,text:c.text,anchor:s,actor:y,operation_id:o});return await X({review:u,comment:d.comment,verb:"create",actor_node_id:null,deliver:void 0,operation_id:o}).catch(()=>{}),f(e,200,{comment:b(d.comment)}),!0}const n=/^\/api\/review\/comments\/([a-f0-9]{32})\/(edit|resolve|reopen|delete)$/.exec(r);if(n){const t=n[1];if((await D(t))?.review_id!==u.review_id)return w(e);const o={actor:y,operation_id:x(),...typeof c.if_revision=="number"?{if_revision:c.if_revision}:{}},s=n[2]==="edit"?await U(t,{...o,text:String(c.text??"")}):n[2]==="resolve"?await $(t,o):n[2]==="reopen"?await W(t,o):await O(t,o);return f(e,200,{comment:b(s.comment),changed:s.changed}),!0}if(r==="/api/review/chat"){const t=typeof c.text=="string"?c.text.trim():"";if(t==="")return l(e,400,"invalid_request","text is required"),!0;if(u.state!=="open")return l(e,409,"review_terminal","review already has a terminal outcome"),!0;const o=u.companion_node_id;await R(o,{kind:"message",label:t.slice(0,120),senderNodeId:"human",urgency:"normal",wake:1,bodyJson:{body:t,steer:!0}});const s=await h(o);return s!==null&&!C(s)&&await S(o,{resume:!0,capacity:"freeze"}),f(e,200,{accepted:!0}),!0}if(r==="/api/review/interrupt"){const t=await h(u.companion_node_id);let o="idle";if(t!==null&&C(t))try{o=await P(u.companion_node_id)}catch(s){if(!(s instanceof A))throw s}return f(e,200,{outcome:o}),!0}if(r==="/api/review/submit"){const t=await F(u.review_id);return f(e,200,{outcome:t.outcome,state:t.record.state}),!0}if(r==="/api/review/cancel"){const t=await z(u.review_id,typeof c.reason=="string"?{reason:c.reason}:{});return f(e,200,{outcome:t.outcome,state:t.record.state}),!0}}catch(n){return ee(e,n)}return!1}m(ke,"serveReviewApi");export{ke as serveReviewApi};
13
+ `)},3e4);return e.on("close",()=>{clearInterval(s),o()}),!0}if(i.method!=="POST")return!1;const p=await ee(i);if(!p||typeof p!="object"||Array.isArray(p))return l(e,400,"invalid_request","invalid body"),!0;const c=p,u=await v(typeof c.review_id=="string"?c.review_id:null);if(!u)return w(e);const g={kind:"human",node_id:null};try{if(r==="/api/review/comments"){const t=c.anchor;if(typeof c.text!="string"||!t||typeof t.quote!="string")return l(e,400,"invalid_request","text and anchor.quote are required"),!0;if(u.state!=="open")return l(e,409,"review_terminal","review already has a terminal outcome"),!0;const o=y(),s=H(await I(_=>M(_,u)),{quote:t.quote,...typeof t.prefix=="string"?{prefix:t.prefix}:{},...typeof t.suffix=="string"?{suffix:t.suffix}:{},...typeof t.offset=="number"?{offset:t.offset}:{}}),d=await D({review_id:u.review_id,text:c.text,anchor:s,actor:g,operation_id:o});return await K({review:u,comment:d.comment,verb:"create",actor_node_id:null,deliver:void 0,operation_id:o}).catch(()=>{}),f(e,200,{comment:h(d.comment)}),!0}const n=/^\/api\/review\/comments\/([a-f0-9]{32})\/(edit|resolve|reopen|delete)$/.exec(r);if(n){const t=n[1];if((await O(t))?.review_id!==u.review_id)return w(e);const o={actor:g,operation_id:y(),...typeof c.if_revision=="number"?{if_revision:c.if_revision}:{}},s=n[2]==="edit"?await W(t,{...o,text:String(c.text??"")}):n[2]==="resolve"?await F(t,o):n[2]==="reopen"?await j(t,o):await U(t,o);return f(e,200,{comment:h(s.comment),changed:s.changed}),!0}if(r==="/api/review/chat"){const t=typeof c.text=="string"?c.text.trim():"";if(t==="")return l(e,400,"invalid_request","text is required"),!0;if(u.state!=="open")return l(e,409,"review_terminal","review already has a terminal outcome"),!0;const o=u.companion_node_id;return await R(o,{kind:"message",label:t.slice(0,120),senderNodeId:"human",urgency:"normal",wake:1,bodyJson:{body:t,steer:!0}}),await C(o)!==null&&await x(o)===null&&await N(o,{resume:!0,capacity:"freeze"}),f(e,200,{accepted:!0}),!0}if(r==="/api/review/interrupt"){let t="idle";if(await x(u.companion_node_id)!==null){const o=await S(u.companion_node_id);try{t=await P(u.companion_node_id,o)}catch(s){if(!(s instanceof A))throw s}}return f(e,200,{outcome:t}),!0}if(r==="/api/review/submit"){const t=await X(u.review_id);return f(e,200,{outcome:t.outcome,state:t.record.state}),!0}if(r==="/api/review/cancel"){const t=await z(u.review_id,typeof c.reason=="string"?{reason:c.reason}:{});return f(e,200,{outcome:t.outcome,state:t.record.state}),!0}}catch(n){return te(e,n)}return!1}m(Te,"serveReviewApi");export{Te as serveReviewApi};