@north-light/cli 0.3.692 → 0.3.693

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
- var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});import{prepared as m}from"../sqlite-statements.js";import{existsSync as I,readFileSync as O}from"node:fs";import{randomBytes as C}from"node:crypto";import{withCanvasWrite as T,openDb as N}from"./db.js";import{inboxPath as w,passivePath as D}from"./paths.js";import{withRetryBudget as X}from"./delivery-contract.js";import{emitEvent as H}from"../events/emit.js";import{mapAsync as F}from"../async-array.js";function R(e){return{deliveryId:e.delivery_id,messageId:e.message_id,destinationId:e.destination_id,urgency:e.urgency,wake:e.wake===1?1:0,state:e.state,attempts:e.attempts,nextAttemptAt:e.next_attempt_at,claimedAt:e.claimed_at,claimOwner:e.claim_owner,acknowledgedAt:e.acknowledged_at,failedAt:e.failed_at,lastFailure:e.last_failure_json===null?null:JSON.parse(e.last_failure_json),idempotencyKey:e.idempotency_key,canceledAt:e.canceled_at,createdAt:e.created_at,updatedAt:e.updated_at}}o(R,"deliveryFrom");async function L(e,a,r,d){return await e.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
2
- WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited'${d?" AND n.intent IS DISTINCT FROM 'refresh'":""}`).get(a,r)!==void 0}o(L,"executionIsLive");async function A(e,a,r,d,s,E=!1){return(await e.prepare(`SELECT d.*, m.message_id AS m_message_id, m.seq, m.operation_id, m.created_at AS message_created_at,
1
+ var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});import{prepared as m}from"../sqlite-statements.js";import{existsSync as I,readFileSync as O}from"node:fs";import{randomBytes as C}from"node:crypto";import{withCanvasWrite as T,openDb as N}from"./db.js";import{inboxPath as w,passivePath as R}from"./paths.js";import{withRetryBudget as X}from"./delivery-contract.js";import{emitEvent as F}from"../events/emit.js";import{mapAsync as H}from"../async-array.js";function D(e){return{deliveryId:e.delivery_id,messageId:e.message_id,destinationId:e.destination_id,urgency:e.urgency,wake:e.wake===1?1:0,state:e.state,attempts:e.attempts,nextAttemptAt:e.next_attempt_at,claimedAt:e.claimed_at,claimOwner:e.claim_owner,acknowledgedAt:e.acknowledged_at,failedAt:e.failed_at,lastFailure:e.last_failure_json===null?null:JSON.parse(e.last_failure_json),idempotencyKey:e.idempotency_key,canceledAt:e.canceled_at,createdAt:e.created_at,updatedAt:e.updated_at}}o(D,"deliveryFrom");async function L(e,a,r,d){return await e.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
2
+ WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${d?" AND n.intent IS DISTINCT FROM 'refresh'":""}`).get(a,r)!==void 0}o(L,"executionIsLive");async function A(e,a,r,d,s,E=!1){return(await e.prepare(`SELECT d.*, m.message_id AS m_message_id, m.seq, m.operation_id, m.created_at AS message_created_at,
3
3
  m.sender_node_id, m.sender_name, m.kind, m.label, m.body_ref, m.body_json, m.disposition
4
4
  FROM deliveries d JOIN messages m ON m.message_id = d.message_id
5
5
  WHERE d.destination_id = ? AND d.wake = ?
6
6
  ${E?"AND m.kind = 'message' AND m.body_json ->> 'start_turn' = 'false'":d===0?"AND NOT (m.kind = 'message' AND coalesce(m.body_json ->> 'start_turn', 'true') = 'false')":""}
7
7
  AND d.canceled_at IS NULL
8
8
  AND d.state = 'handed_off' AND d.claim_owner = ?
9
- ORDER BY m.seq`).all(a,d,r)).map(i=>({...R(i),message:{messageId:i.m_message_id,seq:Number(i.seq),operationId:i.operation_id,createdAt:i.message_created_at,senderNodeId:i.sender_node_id,senderName:i.sender_name,kind:i.kind,label:i.label,bodyRef:i.body_ref,bodyJson:i.body_json===null?null:JSON.parse(i.body_json),disposition:i.disposition},handoff:s?.has(i.delivery_id)===!0?"fresh":"inherited"}))}o(A,"nodeMailRows");const v=`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
9
+ ORDER BY m.seq`).all(a,d,r)).map(i=>({...D(i),message:{messageId:i.m_message_id,seq:Number(i.seq),operationId:i.operation_id,createdAt:i.message_created_at,senderNodeId:i.sender_node_id,senderName:i.sender_name,kind:i.kind,label:i.label,bodyRef:i.body_ref,bodyJson:i.body_json===null?null:JSON.parse(i.body_json),disposition:i.disposition},handoff:s?.has(i.delivery_id)===!0?"fresh":"inherited"}))}o(A,"nodeMailRows");const v=`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
10
10
  WHERE d.destination_id = ? AND d.wake = ? AND d.state = 'pending' AND d.canceled_at IS NULL
11
11
  AND NOT (d.wake = 0 AND m.kind = 'message' AND coalesce(m.body_json ->> 'start_turn', 'true') = 'false')`,M=`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
12
12
  WHERE delivery_id IN (${v}) RETURNING delivery_id`;async function Z(e,a,r,d=Date.now()){const s=r==="wake"?1:0;if(r==="deferred_run")return await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=await c.prepare(`SELECT d.delivery_id FROM deliveries d JOIN messages m ON m.message_id = d.message_id
@@ -17,18 +17,18 @@ var x=Object.defineProperty;var o=(e,a)=>x(e,"name",{value:a,configurable:!0});i
17
17
  WHERE destination_id = ? AND wake = 1 AND state = 'pending' AND canceled_at IS NULL RETURNING delivery_id`).all(a,r,r,e)).map(E=>E.delivery_id));return await A(d,e,a,1,s)})}o(ee,"claimKickoffMail");function W(e){return e.state==="accepted"?{state:"acknowledged"}:e}o(W,"normalizedSettlement");async function j(e,a,r,d,s=Date.now()){const E=[],c=await T(async i=>{const n=(await i.prepare("SELECT canceled_at FROM deliveries WHERE delivery_id = ? AND next_attempt_at IS NOT NULL").get(e))?.canceled_at!=null?{state:"acknowledged"}:W(d),l=X(n,a),_=l.settlement,S=_.state==="pending"||_.state==="permanent_failed"?JSON.stringify(_.failure):null,g=_.state==="released"?"pending":_.state,p=_.state==="pending"?_.nextAttemptAt:g==="pending"?s:null,f=Number((await i.prepare(`UPDATE deliveries
18
18
  SET state = ?, next_attempt_at = ?, claimed_at = NULL, claim_owner = NULL,
19
19
  acknowledged_at = ?, failed_at = ?, last_failure_json = ?, updated_at = ?
20
- WHERE delivery_id = ? AND state = 'handed_off' AND attempts = ? AND claim_owner = ?`).run(g,p,g==="acknowledged"?s:null,g==="permanent_failed"?s:null,S,s,e,a,r)).changes)===1;if(f&&l.exhausted&&_.state==="permanent_failed"){const y=await i.prepare("SELECT destination_id, message_id FROM deliveries WHERE delivery_id = ?").get(e);E.push({failure:_.failure,destinationId:y.destination_id,messageId:y.message_id})}return f});for(const i of E)H({level:"error",event:"delivery.exhausted",outcome:"failed",attempt:a,fields:{delivery_id:e,destination_id:i.destinationId,message_id:i.messageId,failure:i.failure,retry:`crtr sys retry-delivery ${e}`}});return c}o(j,"settleDelivery");async function te(e,a=Date.now()){return Number((await(await N()).prepare(`UPDATE deliveries
20
+ WHERE delivery_id = ? AND state = 'handed_off' AND attempts = ? AND claim_owner = ?`).run(g,p,g==="acknowledged"?s:null,g==="permanent_failed"?s:null,S,s,e,a,r)).changes)===1;if(f&&l.exhausted&&_.state==="permanent_failed"){const y=await i.prepare("SELECT destination_id, message_id FROM deliveries WHERE delivery_id = ?").get(e);E.push({failure:_.failure,destinationId:y.destination_id,messageId:y.message_id})}return f});for(const i of E)F({level:"error",event:"delivery.exhausted",outcome:"failed",attempt:a,fields:{delivery_id:e,destination_id:i.destinationId,message_id:i.messageId,failure:i.failure,retry:`crtr sys retry-delivery ${e}`}});return c}o(j,"settleDelivery");async function te(e,a=Date.now()){return Number((await(await N()).prepare(`UPDATE deliveries
21
21
  SET state = 'pending', attempts = 0, next_attempt_at = ?, failed_at = NULL, updated_at = ?
22
- WHERE delivery_id = ? AND state = 'permanent_failed' AND canceled_at IS NULL AND last_failure_json IS NOT NULL`).run(a,a,e)).changes)===1}o(te,"retryFailedDelivery");async function ae(e,a,r,d=Date.now()){return await T(async s=>await L(s,e,a,!1)?{action:"acknowledged",results:await F(r,async c=>{const i=await s.prepare("SELECT 1 FROM deliveries WHERE delivery_id = ? AND destination_id = ?").get(c.deliveryId,e)!==void 0;return{deliveryId:c.deliveryId,outcome:i&&await j(c.deliveryId,c.attempts,a,{state:c.disposition},d)?c.disposition:"stale"}})}:{action:"hold",results:[]})}o(ae,"acknowledgeNodeMail");async function ne(e){const a=await(await N()).prepare(`SELECT m.body_json FROM deliveries d JOIN messages m ON m.message_id = d.message_id
22
+ WHERE delivery_id = ? AND state = 'permanent_failed' AND canceled_at IS NULL AND last_failure_json IS NOT NULL`).run(a,a,e)).changes)===1}o(te,"retryFailedDelivery");async function ae(e,a,r,d=Date.now()){return await T(async s=>await L(s,e,a,!1)?{action:"acknowledged",results:await H(r,async c=>{const i=await s.prepare("SELECT 1 FROM deliveries WHERE delivery_id = ? AND destination_id = ?").get(c.deliveryId,e)!==void 0;return{deliveryId:c.deliveryId,outcome:i&&await j(c.deliveryId,c.attempts,a,{state:c.disposition},d)?c.disposition:"stale"}})}:{action:"hold",results:[]})}o(ae,"acknowledgeNodeMail");async function ne(e){const a=await(await N()).prepare(`SELECT m.body_json FROM deliveries d JOIN messages m ON m.message_id = d.message_id
23
23
  WHERE d.delivery_id = ?`).get(e);return a===void 0||a.body_json===null?null:JSON.parse(a.body_json)}o(ne,"messageBodyForDelivery");async function ie(e){return(await(await N()).prepare(`SELECT * FROM deliveries
24
24
  WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at <= ?
25
- ORDER BY next_attempt_at, created_at, delivery_id`).all(e)).map(R)}o(ie,"duePushDeliveries");async function de(e,a,r){return await T(async d=>{const s=await d.prepare(`UPDATE deliveries AS d SET state = 'handed_off', attempts = attempts + 1, claimed_at = ?, claim_owner = ?, updated_at = ?
25
+ ORDER BY next_attempt_at, created_at, delivery_id`).all(e)).map(D)}o(ie,"duePushDeliveries");async function de(e,a,r){return await T(async d=>{const s=await d.prepare(`UPDATE deliveries AS d SET state = 'handed_off', attempts = attempts + 1, claimed_at = ?, claim_owner = ?, updated_at = ?
26
26
  WHERE d.delivery_id = ? AND d.state = 'pending' AND d.canceled_at IS NULL AND d.next_attempt_at <= ?
27
27
  AND NOT EXISTS (SELECT 1 FROM deliveries old JOIN messages prior ON prior.message_id = old.message_id
28
28
  JOIN messages next ON next.message_id = d.message_id
29
29
  WHERE old.destination_id = d.destination_id AND old.delivery_id != d.delivery_id
30
30
  AND old.state = 'handed_off' AND old.canceled_at IS NOT NULL
31
- AND prior.event = 'outcome' AND next.event = 'outcome' AND prior.object_id = next.object_id)`).run(a,r,a,e,a);return Number(s.changes)===0?null:R(await d.prepare("SELECT * FROM deliveries WHERE delivery_id = ?").get(e))})}o(de,"claimPushDelivery");async function se(e){return await T(async a=>{const r=await a.prepare(`UPDATE deliveries SET state = 'permanent_failed', next_attempt_at = NULL,
31
+ AND prior.event = 'outcome' AND next.event = 'outcome' AND prior.object_id = next.object_id)`).run(a,r,a,e,a);return Number(s.changes)===0?null:D(await d.prepare("SELECT * FROM deliveries WHERE delivery_id = ?").get(e))})}o(de,"claimPushDelivery");async function se(e){return await T(async a=>{const r=await a.prepare(`UPDATE deliveries SET state = 'permanent_failed', next_attempt_at = NULL,
32
32
  claimed_at = NULL, claim_owner = NULL, failed_at = ?, updated_at = ?
33
33
  WHERE state = 'handed_off' AND canceled_at IS NOT NULL AND next_attempt_at IS NOT NULL`).run(e,e),d=await a.prepare(`UPDATE deliveries SET state = 'pending', next_attempt_at = CASE WHEN next_attempt_at IS NOT NULL THEN ?::bigint ELSE NULL END,
34
34
  claimed_at = NULL, claim_owner = NULL, updated_at = ?
@@ -95,4 +95,4 @@ CREATE TABLE IF NOT EXISTS waits (
95
95
  );
96
96
  CREATE UNIQUE INDEX IF NOT EXISTS waits_live ON waits(node_id) WHERE satisfied_at IS NULL;
97
97
  CREATE INDEX IF NOT EXISTS waits_node ON waits(node_id);
98
- `);const a=[];for(const t of m(e,"SELECT node_id FROM nodes").all()){const n=t.node_id,l=U(w(n)),_=I(`${w(n)}.cursor`)?O(`${w(n)}.cursor`,"utf8").trim():"",S=l.findIndex(p=>p.entry_id===_),g=q(`${w(n)}.canceled`);l.forEach((p,f)=>a.push({nodeId:n,wake:1,source:"inbox",fileRank:0,physicalIndex:f,entry:p,acknowledged:S>=0&&f<=S,canceled:g.has(p.entry_id),seq:0}));for(const[p,f]of[[0,`${D(n)}.draining`],[1,D(n)]])U(f).forEach((y,h)=>a.push({nodeId:n,wake:0,source:"passive",fileRank:p,physicalIndex:h,entry:y,acknowledged:!1,canceled:!1,seq:0}))}a.sort((t,n)=>t.entry.ts.localeCompare(n.entry.ts)||t.nodeId.localeCompare(n.nodeId)||t.fileRank-n.fileRank||t.physicalIndex-n.physicalIndex),a.forEach((t,n)=>{t.seq=n+1});const r=new Map;for(const t of a){const n=`${t.nodeId}\0${t.source}`,l=r.get(n)??[];l.push(t),r.set(n,l)}for(const t of r.values()){const n=t.map(l=>l.seq).sort((l,_)=>l-_);t.sort((l,_)=>l.fileRank-_.fileRank||l.physicalIndex-_.physicalIndex).forEach((l,_)=>{l.seq=n[_]})}const d=m(e,"INSERT INTO messages (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),s=m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, acknowledged_at, canceled_at, created_at, updated_at) VALUES (?, ?, 'node_inbox', ?, ?, ?, ?, 0, ?, ?, ?, ?)");for(const t of a){const n=t.entry;d.run(n.entry_id,t.seq,n.operation_id,n.ts,n.from,n.from_name??null,n.kind,n.label,n.ref??null,n.data===void 0?null:JSON.stringify(n.data),n.disposition??null);const l=Date.parse(n.ts),_=Number.isFinite(l)?l:0;s.run(u(),n.entry_id,t.nodeId,n.tier,t.wake,t.acknowledged?"acknowledged":"pending",t.acknowledged?_:null,t.canceled?_:null,_,_)}const E=m(e,"SELECT * FROM human_action_deliveries").all();for(const t of E){const n=u();d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.request_id,null,t.completion_json,null);const l=t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', 'human_action', 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd}),`human-action:${t.request_id}`,t.created_at,t.updated_at)}const c=m(e,"SELECT * FROM node_outcome_deliveries").all();for(const t of c){const n=t.document_json===null?null:u();n!==null&&d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.node_id,null,t.document_json,null);const l=t.document_json===null?"armed":t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', ?, 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,t.action_name,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd,config_origin:t.config_origin,payload:t.payload_json===null?null:JSON.parse(t.payload_json)}),`node-outcome:${t.node_id}`,t.created_at,t.updated_at)}const i=m(e,"SELECT node_id, waiting_for, waiting_for_generation FROM nodes WHERE waiting_for IS NOT NULL").all();for(const t of i)m(e,"INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at) VALUES (?, ?, 'controller', ?, ?, ?, NULL)").run(u(),t.node_id,t.waiting_for,t.waiting_for_generation,Date.now())}o(me,"migrateMessagingState");function k(e){return Number(m(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}o(k,"nextSeq");export{b as UNSEEN_WAKE_MAIL_SQL,$ as WAKE_MAIL_SQL,ae as acknowledgeNodeMail,Ee as acknowledgedNodeMailCount,ee as claimKickoffMail,Z as claimNodeMail,de as claimPushDelivery,R as deliveryFrom,ie as duePushDeliveries,_e as hasUnseenWakeMail,ce as hasWakeMailSince,ne as messageBodyForDelivery,me as migrateMessagingState,W as normalizedSettlement,re as pushDeliveryClaimIsCurrent,oe as releaseExecutionMail,se as resetHandedOffDeliveries,le as resetStaleExecutionMail,te as retryFailedDelivery,j as settleDelivery};
98
+ `);const a=[];for(const t of m(e,"SELECT node_id FROM nodes").all()){const n=t.node_id,l=U(w(n)),_=I(`${w(n)}.cursor`)?O(`${w(n)}.cursor`,"utf8").trim():"",S=l.findIndex(p=>p.entry_id===_),g=q(`${w(n)}.canceled`);l.forEach((p,f)=>a.push({nodeId:n,wake:1,source:"inbox",fileRank:0,physicalIndex:f,entry:p,acknowledged:S>=0&&f<=S,canceled:g.has(p.entry_id),seq:0}));for(const[p,f]of[[0,`${R(n)}.draining`],[1,R(n)]])U(f).forEach((y,h)=>a.push({nodeId:n,wake:0,source:"passive",fileRank:p,physicalIndex:h,entry:y,acknowledged:!1,canceled:!1,seq:0}))}a.sort((t,n)=>t.entry.ts.localeCompare(n.entry.ts)||t.nodeId.localeCompare(n.nodeId)||t.fileRank-n.fileRank||t.physicalIndex-n.physicalIndex),a.forEach((t,n)=>{t.seq=n+1});const r=new Map;for(const t of a){const n=`${t.nodeId}\0${t.source}`,l=r.get(n)??[];l.push(t),r.set(n,l)}for(const t of r.values()){const n=t.map(l=>l.seq).sort((l,_)=>l-_);t.sort((l,_)=>l.fileRank-_.fileRank||l.physicalIndex-_.physicalIndex).forEach((l,_)=>{l.seq=n[_]})}const d=m(e,"INSERT INTO messages (message_id, seq, operation_id, created_at, sender_node_id, sender_name, kind, label, body_ref, body_json, disposition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),s=m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, acknowledged_at, canceled_at, created_at, updated_at) VALUES (?, ?, 'node_inbox', ?, ?, ?, ?, 0, ?, ?, ?, ?)");for(const t of a){const n=t.entry;d.run(n.entry_id,t.seq,n.operation_id,n.ts,n.from,n.from_name??null,n.kind,n.label,n.ref??null,n.data===void 0?null:JSON.stringify(n.data),n.disposition??null);const l=Date.parse(n.ts),_=Number.isFinite(l)?l:0;s.run(u(),n.entry_id,t.nodeId,n.tier,t.wake,t.acknowledged?"acknowledged":"pending",t.acknowledged?_:null,t.canceled?_:null,_,_)}const E=m(e,"SELECT * FROM human_action_deliveries").all();for(const t of E){const n=u();d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.request_id,null,t.completion_json,null);const l=t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', 'human_action', 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd}),`human-action:${t.request_id}`,t.created_at,t.updated_at)}const c=m(e,"SELECT * FROM node_outcome_deliveries").all();for(const t of c){const n=t.document_json===null?null:u();n!==null&&d.run(n,k(e),u(),new Date(t.created_at).toISOString(),null,null,"completed",t.node_id,null,t.document_json,null);const l=t.document_json===null?"armed":t.state==="running"?"handed_off":t.state==="accepted"?"acknowledged":t.state;m(e,"INSERT INTO deliveries (delivery_id, message_id, destination_kind, destination_id, urgency, wake, state, attempts, next_attempt_at, claimed_at, claim_owner, acknowledged_at, failed_at, last_failure_json, adapter_json, idempotency_key, created_at, updated_at) VALUES (?, ?, 'external_action', ?, 'normal', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(u(),n,t.action_name,l,t.attempt,t.next_attempt_at,t.claimed_at,t.claim_owner,t.accepted_at,t.permanent_failed_at,t.last_failure_json,JSON.stringify({adapter:"subprocess",argv:JSON.parse(t.argv_json),cwd:t.cwd,config_origin:t.config_origin,payload:t.payload_json===null?null:JSON.parse(t.payload_json)}),`node-outcome:${t.node_id}`,t.created_at,t.updated_at)}const i=m(e,"SELECT node_id, waiting_for, waiting_for_generation FROM nodes WHERE waiting_for IS NOT NULL").all();for(const t of i)m(e,"INSERT INTO waits (wait_id, node_id, kind, target_id, generation, created_at, satisfied_at) VALUES (?, ?, 'controller', ?, ?, ?, NULL)").run(u(),t.node_id,t.waiting_for,t.waiting_for_generation,Date.now())}o(me,"migrateMessagingState");function k(e){return Number(m(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}o(k,"nextSeq");export{b as UNSEEN_WAKE_MAIL_SQL,$ as WAKE_MAIL_SQL,ae as acknowledgeNodeMail,Ee as acknowledgedNodeMailCount,ee as claimKickoffMail,Z as claimNodeMail,de as claimPushDelivery,D as deliveryFrom,ie as duePushDeliveries,_e as hasUnseenWakeMail,ce as hasWakeMailSince,ne as messageBodyForDelivery,me as migrateMessagingState,W as normalizedSettlement,re as pushDeliveryClaimIsCurrent,oe as releaseExecutionMail,se as resetHandedOffDeliveries,le as resetStaleExecutionMail,te as retryFailedDelivery,j as settleDelivery};
@@ -22,8 +22,8 @@ export declare class EnvironmentImagePending extends Error {
22
22
  /** D95: the image a new sandbox is created from. `pending` means the environment has a recipe and no image has built. */
23
23
  export declare function imageForWake(environmentId: string): Promise<EnvironmentImage>;
24
24
  /** Step 3: a `running` Blaxel execution is a resident broker, possibly frozen. On the accepted release it is woken and nothing else
25
- * is written. On another release it is asked to stop for the release first, so the thawed broker exits and the next claim starts
26
- * a new attempt on the accepted one. `lost` means no broker answered: the execution is ended and the caller starts a new attempt. */
25
+ * is written. On another release it is stopped and ended without being woken, so the next tick starts a new attempt on the
26
+ * accepted one. `lost` means no broker answered: the execution is ended and the caller starts a new attempt. */
27
27
  export declare function wakeResident(execution: Execution): Promise<'woken' | 'lost'>;
28
28
  /** A `running` remote execution is live while its runner reports the broker process running, frozen or not. When the runner
29
29
  * reports it gone (or ended non-zero), that exact execution is ended; a runner that cannot tell leaves it as it is. An idle
@@ -1,2 +1,2 @@
1
- var h=Object.defineProperty;var a=(e,n)=>h(e,"name",{value:n,configurable:!0});import{liveExecutionForNode as _,endExecution as p,recordExecutionAwake as x,endLaunchingExecution as d,requestExecutionStop as v}from"../../../core/canvas/executions.js";import{openDb as E}from"../../../core/canvas/db.js";import{isCloudRole as g}from"../../../core/canvas/person-state.js";import{getRow as b}from"../../../core/canvas/index.js";import{fullName as k}from"../../../core/canvas/labels.js";import{publishNotice as y}from"../../../core/runtime/close.js";import{emitEvent as s}from"../../../core/events/emit.js";import{findRefusal as $,refusalError as L,refusedMark as N,writeCharge as S}from"../../../core/ledger/index.js";import{transition as w}from"../../../core/runtime/lifecycle.js";import{runnerForExecution as f}from"../../../core/runtime/runner/index.js";import{machineEnvironmentOfProfile as A}from"../../../core/runtime/runner/machine/environment.js";import{startCandidateOf as R}from"../../../core/runtime/start-check.js";import{settleSandboxBeforeWake as D}from"../ledger-sandbox.js";import{crtrVersion as C}from"../../../shared/crtr-version.js";import{resolveEnvironmentImage as I}from"../recipe-image.js";import{recordRespawnPolicy as O}from"./respawn-policy.js";import{recordLaunchFailure as T}from"./launch-failure.js";const P=45*6e4,U=12e4,W=a(()=>C(),"acceptedRelease");async function re(e){return e===null||!g()?null:await A(e)}a(re,"remoteMachineEnvironmentOf");async function ae(e){const n=await R(e);if(n===null)return;const t={scope:"call",payer:n.payer,funding:"bill",sub:n.sub,grantee:n.grantee,provider:"blaxel"},r=await $(t),o=await E();if(r===null){await o.prepare("UPDATE nodes SET spend_refusal = NULL WHERE node_id = ? AND spend_refusal IS NOT NULL").run(e.node_id);return}throw await o.prepare("UPDATE nodes SET spend_refusal = ? WHERE node_id = ?").run(JSON.stringify({limit:r.limit.id,usd:r.usd,reset_at:r.reset_at,at:new Date().toISOString()}),e.node_id),await S({id:`refused:sandbox:${e.node_id}:${r.limit.id}:${r.month}`,kind:"sandbox",what:"wake",usd:null,payer:t.payer,funding:"bill",sub:t.sub,grantee:t.grantee,node:e.node_id,run:e.run_id??null,provider:"blaxel",refused:N(r)}),L(r)}a(ae,"checkBilledWake");class ie extends Error{static{a(this,"EnvironmentImagePending")}environmentId;imageError;constructor(n,t){super(`environment ${n} has no built image yet${t===null?"":` (${t})`}; the wake waits for the build.`),this.environmentId=n,this.imageError=t,this.name="EnvironmentImagePending"}}async function oe(e){return await I(e)}a(oe,"imageForWake");async function se(e){return e.release!==W()&&await v(e.nodeId,{afterTurn:!1,reason:"release"}),await f(e.runner).wake(e)==="no_broker"?(await p(e.executionId,{reason:"lost"}),"lost"):(await D(e.executionId,Date.now()),await x(e.executionId),"woken")}a(se,"wakeResident");async function ue(e){const n=await f(e.runner).status(e,{idle:e.idleAt!==null});if(n.state!=="gone"&&n.state!=="failed")return!1;const t=await p(e.executionId,{reason:"lost"});return t&&s({level:"warn",event:"execution.lost",node_id:e.nodeId}),t}a(ue,"endRemoteExecutionIfGone");async function le(e,n){const t=await _(e);if(t===null||t.state!=="launching"||t.runner==="process")return!1;const r=f(t.runner),o=n-Date.parse(t.startedAt),i=await r.status(t);if(i.state==="unknown")return!1;if(i.state==="running")return o<=P||!await d(t.executionId,{reason:"launch_timeout"})?!1:(await r.stop(t,{reason:"launch_timeout"}),await w(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:"the sandbox launch did not report within the launch deadline"}}}),s({level:"warn",event:"execution.launch_timeout",node_id:e}),!0);if(i.state==="failed"){if(!await d(t.executionId,{reason:"launch_failed"}))return!1;const l=`the sandbox start script failed: ${i.reason}`;await T(t.executionId,new Error(i.output===void 0?l:`${l}
2
- ${i.output}`));const c=await b(e);if(c!==null){const u=await O(c,n);if(!u.exhausted)s({level:"warn",event:"execution.launch_failed",node_id:e,fields:{reason:i.reason,consecutive_failures:u.failures}});else{const m=`Child crashed \u2014 ${k(c)} (${e}) failed ${u.failures} consecutive sandbox launches (${l}) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;s({level:"error",event:"broker.respawn.exhausted",node_id:e}),await w(e,"crash",{reason:"crash_looped",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:m,respawn_failures:u.failures}}}),await y(e,"notice.crash",m,{reason:"child-crashed",child:e})}}return await r.deleteExecution?.(t),!0}if(o>U){if(!await d(t.executionId,{reason:"launch_lost"}))return!1;s({level:"warn",event:"execution.launch_lost",node_id:e})}return!1}a(le,"recoverLaunching");export{ie as EnvironmentImagePending,P as LAUNCH_DEADLINE_MS,U as LAUNCH_LOST_GRACE_MS,W as acceptedRelease,ae as checkBilledWake,ue as endRemoteExecutionIfGone,oe as imageForWake,le as recoverLaunching,re as remoteMachineEnvironmentOf,se as wakeResident};
1
+ var h=Object.defineProperty;var a=(e,r)=>h(e,"name",{value:r,configurable:!0});import{liveExecutionForNode as _,endExecution as f,recordExecutionAwake as v,endLaunchingExecution as m,requestExecutionStop as x}from"../../../core/canvas/executions.js";import{openDb as E}from"../../../core/canvas/db.js";import{isCloudRole as g}from"../../../core/canvas/person-state.js";import{getRow as b}from"../../../core/canvas/index.js";import{fullName as k}from"../../../core/canvas/labels.js";import{publishNotice as y}from"../../../core/runtime/close.js";import{emitEvent as i}from"../../../core/events/emit.js";import{findRefusal as $,refusalError as A,refusedMark as L,writeCharge as N}from"../../../core/ledger/index.js";import{transition as w}from"../../../core/runtime/lifecycle.js";import{runnerForExecution as u}from"../../../core/runtime/runner/index.js";import{machineEnvironmentOfProfile as R}from"../../../core/runtime/runner/machine/environment.js";import{startCandidateOf as S}from"../../../core/runtime/start-check.js";import{settleSandboxBeforeWake as D}from"../ledger-sandbox.js";import{crtrVersion as I}from"../../../shared/crtr-version.js";import{resolveEnvironmentImage as C}from"../recipe-image.js";import{recordRespawnPolicy as O}from"./respawn-policy.js";import{recordLaunchFailure as T}from"./launch-failure.js";const P=45*6e4,U=12e4,W=a(()=>I(),"acceptedRelease");async function ne(e){return e===null||!g()?null:await R(e)}a(ne,"remoteMachineEnvironmentOf");async function ae(e){const r=await S(e);if(r===null)return;const t={scope:"call",payer:r.payer,funding:"bill",sub:r.sub,grantee:r.grantee,provider:"blaxel"},n=await $(t),s=await E();if(n===null){await s.prepare("UPDATE nodes SET spend_refusal = NULL WHERE node_id = ? AND spend_refusal IS NOT NULL").run(e.node_id);return}throw await s.prepare("UPDATE nodes SET spend_refusal = ? WHERE node_id = ?").run(JSON.stringify({limit:n.limit.id,usd:n.usd,reset_at:n.reset_at,at:new Date().toISOString()}),e.node_id),await N({id:`refused:sandbox:${e.node_id}:${n.limit.id}:${n.month}`,kind:"sandbox",what:"wake",usd:null,payer:t.payer,funding:"bill",sub:t.sub,grantee:t.grantee,node:e.node_id,run:e.run_id??null,provider:"blaxel",refused:L(n)}),A(n)}a(ae,"checkBilledWake");class oe extends Error{static{a(this,"EnvironmentImagePending")}environmentId;imageError;constructor(r,t){super(`environment ${r} has no built image yet${t===null?"":` (${t})`}; the wake waits for the build.`),this.environmentId=r,this.imageError=t,this.name="EnvironmentImagePending"}}async function ie(e){return await C(e)}a(ie,"imageForWake");async function se(e){if(e.release!==W()){if(await x(e.nodeId,{afterTurn:!1,reason:"release"}),e.stopRequestedAt!==null)return"lost";const r=await u(e.runner).stop(e,{reason:"release"});return r.confirmed?(await f(e.executionId,{reason:"release"}),"lost"):(i({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:r.error}),"lost")}return await u(e.runner).wake(e)==="no_broker"?(await f(e.executionId,{reason:"lost"}),"lost"):(await D(e.executionId,Date.now()),await v(e.executionId),"woken")}a(se,"wakeResident");async function le(e){const r=await u(e.runner).status(e,{idle:e.idleAt!==null});if(r.state!=="gone"&&r.state!=="failed")return!1;const t=await f(e.executionId,{reason:"lost"});return t&&i({level:"warn",event:"execution.lost",node_id:e.nodeId}),t}a(le,"endRemoteExecutionIfGone");async function ue(e,r){const t=await _(e);if(t===null||t.state!=="launching"||t.runner==="process")return!1;const n=u(t.runner),s=r-Date.parse(t.startedAt),o=await n.status(t);if(o.state==="unknown")return!1;if(o.state==="running")return s<=P||!await m(t.executionId,{reason:"launch_timeout"})?!1:(await n.stop(t,{reason:"launch_timeout"}),await w(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:"the sandbox launch did not report within the launch deadline"}}}),i({level:"warn",event:"execution.launch_timeout",node_id:e}),!0);if(o.state==="failed"){if(!await m(t.executionId,{reason:"launch_failed"}))return!1;const d=`the sandbox start script failed: ${o.reason}`;await T(t.executionId,new Error(o.output===void 0?d:`${d}
2
+ ${o.output}`));const c=await b(e);if(c!==null){const l=await O(c,r);if(!l.exhausted)i({level:"warn",event:"execution.launch_failed",node_id:e,fields:{reason:o.reason,consecutive_failures:l.failures}});else{const p=`Child crashed \u2014 ${k(c)} (${e}) failed ${l.failures} consecutive sandbox launches (${d}) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;i({level:"error",event:"broker.respawn.exhausted",node_id:e}),await w(e,"crash",{reason:"crash_looped",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:p,respawn_failures:l.failures}}}),await y(e,"notice.crash",p,{reason:"child-crashed",child:e})}}return await n.deleteExecution?.(t),!0}if(s>U){if(!await m(t.executionId,{reason:"launch_lost"}))return!1;i({level:"warn",event:"execution.launch_lost",node_id:e})}return!1}a(ue,"recoverLaunching");export{oe as EnvironmentImagePending,P as LAUNCH_DEADLINE_MS,U as LAUNCH_LOST_GRACE_MS,W as acceptedRelease,ae as checkBilledWake,le as endRemoteExecutionIfGone,ie as imageForWake,ue as recoverLaunching,ne as remoteMachineEnvironmentOf,se as wakeResident};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.692",
3
+ "version": "0.3.693",
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.692",
160
- "@north-light/plugin": "0.3.692",
159
+ "@north-light/identity": "0.3.693",
160
+ "@north-light/plugin": "0.3.693",
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",
@@ -29,7 +29,7 @@ export function deliveryFrom(row) {
29
29
  }
30
30
  async function executionIsLive(db, nodeId, executionId, rejectRefresh) {
31
31
  const row = await db.prepare(`SELECT 1 FROM nodes n JOIN executions e ON e.node_id = n.node_id
32
- WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited'${rejectRefresh ? " AND n.intent IS DISTINCT FROM 'refresh'" : ''}`).get(nodeId, executionId);
32
+ WHERE n.node_id = ? AND e.execution_id = ? AND e.state != 'exited' AND e.stop_reason IS DISTINCT FROM 'release'${rejectRefresh ? " AND n.intent IS DISTINCT FROM 'refresh'" : ''}`).get(nodeId, executionId);
33
33
  return row !== undefined;
34
34
  }
35
35
  async function nodeMailRows(db, nodeId, executionId, wake, freshIds, deferredRun = false) {
@@ -67,11 +67,24 @@ export async function imageForWake(environmentId) {
67
67
  return await resolveEnvironmentImage(environmentId);
68
68
  }
69
69
  /** Step 3: a `running` Blaxel execution is a resident broker, possibly frozen. On the accepted release it is woken and nothing else
70
- * is written. On another release it is asked to stop for the release first, so the thawed broker exits and the next claim starts
71
- * a new attempt on the accepted one. `lost` means no broker answered: the execution is ended and the caller starts a new attempt. */
70
+ * is written. On another release it is stopped and ended without being woken, so the next tick starts a new attempt on the
71
+ * accepted one. `lost` means no broker answered: the execution is ended and the caller starts a new attempt. */
72
72
  export async function wakeResident(execution) {
73
- if (execution.release !== acceptedRelease())
73
+ if (execution.release !== acceptedRelease()) {
74
+ // The outdated broker is never woken: its stop is recorded, the runner stops it, and only a confirmed stop ends the execution.
75
+ // Until then the wake mail is unclaimable by it (`claimNodeMail` refuses an execution whose stop reason is `release`), and the next tick asks again.
74
76
  await requestExecutionStop(execution.nodeId, { afterTurn: false, reason: 'release' });
77
+ // A stop already tried and unconfirmed is retried by `enactRequestedStops`, not on every tick.
78
+ if (execution.stopRequestedAt !== null)
79
+ return 'lost';
80
+ const stopped = await runnerForExecution(execution.runner).stop(execution, { reason: 'release' });
81
+ if (!stopped.confirmed) {
82
+ emitEvent({ level: 'error', event: 'broker.teardown.unconfirmed', node_id: execution.nodeId, error: stopped.error });
83
+ return 'lost';
84
+ }
85
+ await endExecution(execution.executionId, { reason: 'release' });
86
+ return 'lost';
87
+ }
75
88
  if (await runnerForExecution(execution.runner).wake(execution) === 'no_broker') {
76
89
  await endExecution(execution.executionId, { reason: 'lost' });
77
90
  return 'lost';
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.692",
3
+ "version": "0.3.693",
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.692",
3
+ "version": "0.3.693",
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.692",
3
+ "version": "0.3.693",
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.692",
31
- "@north-light/identity": "0.3.692"
30
+ "@north-light/api": "0.3.693",
31
+ "@north-light/identity": "0.3.693"
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.692",
3
+ "version": "0.3.693",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.692",
9
+ "version": "0.3.693",
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.692",
32
- "@north-light/plugin": "0.3.692",
31
+ "@north-light/identity": "0.3.693",
32
+ "@north-light/plugin": "0.3.693",
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.692",
10670
+ "version": "0.3.693",
10671
10671
  "license": "UNLICENSED"
10672
10672
  },
10673
10673
  "packages/crouter-env-docker": {
10674
10674
  "name": "@north-light/env-docker",
10675
- "version": "0.3.692",
10675
+ "version": "0.3.693",
10676
10676
  "license": "UNLICENSED"
10677
10677
  },
10678
10678
  "packages/crouter-identity": {
10679
10679
  "name": "@north-light/identity",
10680
- "version": "0.3.692",
10680
+ "version": "0.3.693",
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.692",
10688
+ "version": "0.3.693",
10689
10689
  "license": "UNLICENSED",
10690
10690
  "dependencies": {
10691
- "@north-light/api": "0.3.692",
10692
- "@north-light/identity": "0.3.692"
10691
+ "@north-light/api": "0.3.693",
10692
+ "@north-light/identity": "0.3.693"
10693
10693
  }
10694
10694
  },
10695
10695
  "packages/crouter-sdk": {
10696
10696
  "name": "@north-light/sdk",
10697
- "version": "0.3.692",
10697
+ "version": "0.3.693",
10698
10698
  "license": "UNLICENSED",
10699
10699
  "dependencies": {
10700
- "@north-light/api": "0.3.692",
10701
- "@north-light/identity": "0.3.692",
10702
- "@north-light/plugin": "0.3.692",
10700
+ "@north-light/api": "0.3.693",
10701
+ "@north-light/identity": "0.3.693",
10702
+ "@north-light/plugin": "0.3.693",
10703
10703
  "jose": "^6.2.1"
10704
10704
  },
10705
10705
  "bin": {