@north-light/cli 0.3.710 → 0.3.712

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/clients/attach/input/controller.d.ts +1 -1
  4. package/dist/clients/attach/input/controller.js +2 -2
  5. package/dist/clients/attach/render/chat-view.d.ts +13 -2
  6. package/dist/clients/attach/render/chat-view.js +2 -2
  7. package/dist/clients/attach/session/input-wiring.d.ts +2 -2
  8. package/dist/clients/attach/session/layout-record.d.ts +4 -2
  9. package/dist/clients/attach/session/layout-record.js +1 -1
  10. package/dist/clients/attach/session/reconnect.d.ts +8 -1
  11. package/dist/clients/attach/session/reconnect.js +1 -1
  12. package/dist/clients/attach/slash/recover.js +3 -2
  13. package/dist/clients/attach/viewer.js +405 -404
  14. package/dist/commands/human/prompts.js +1 -1
  15. package/dist/commands/human/request.js +1 -1
  16. package/dist/commands/sys/doctor.js +1 -1
  17. package/dist/commands/sys/tutorial/scenario.js +2 -2
  18. package/dist/core/broker-client/client.d.ts +2 -0
  19. package/dist/core/broker-client/client.js +1 -1
  20. package/dist/core/broker-client/transport-relay.d.ts +6 -0
  21. package/dist/core/broker-client/transport-relay.js +1 -1
  22. package/dist/core/broker-client/transport.d.ts +4 -0
  23. package/dist/core/canvas/daemon-actions.d.ts +1 -1
  24. package/dist/core/canvas/daemon-actions.js +7 -7
  25. package/dist/core/canvas/deliveries.d.ts +1 -1
  26. package/dist/core/canvas/deliveries.js +21 -21
  27. package/dist/core/canvas/executions.d.ts +1 -1
  28. package/dist/core/canvas/executions.js +1 -1
  29. package/dist/core/canvas/reconciler-leases.d.ts +4 -0
  30. package/dist/core/canvas/reconciler-leases.js +5 -5
  31. package/dist/core/conversation-store/client.js +2 -2
  32. package/dist/core/conversation-store/index.d.ts +5 -2
  33. package/dist/core/conversation-store/row-store.js +14 -12
  34. package/dist/core/graph/package-docs.js +5 -5
  35. package/dist/core/graph/package-publish.js +4 -3
  36. package/dist/core/graph/reader.js +3 -3
  37. package/dist/core/human/requests.js +19 -19
  38. package/dist/core/import/load/run.js +2 -2
  39. package/dist/core/permissions/evaluator.js +2 -2
  40. package/dist/core/runtime/broker/client-registry.d.ts +1 -1
  41. package/dist/core/runtime/broker/client-registry.js +1 -1
  42. package/dist/core/runtime/broker/turn-replies.js +3 -1
  43. package/dist/core/runtime/broker-protocol.d.ts +4 -4
  44. package/dist/core/runtime/broker-protocol.js +3 -3
  45. package/dist/core/runtime/broker.js +1 -1
  46. package/dist/core/runtime/placement-tmux.d.ts +1 -0
  47. package/dist/core/runtime/placement-tmux.js +1 -1
  48. package/dist/core/runtime/session-cycles.d.ts +21 -0
  49. package/dist/core/runtime/session-cycles.js +1 -1
  50. package/dist/daemon/api/app-listener.js +1 -1
  51. package/dist/daemon/api/handlers/charges.d.ts +1 -1
  52. package/dist/daemon/api/handlers/charges.js +1 -1
  53. package/dist/daemon/api/handlers/conversations.js +4 -3
  54. package/dist/daemon/api/handlers/environments.d.ts +1 -1
  55. package/dist/daemon/api/handlers/environments.js +1 -1
  56. package/dist/daemon/api/handlers/limits.js +1 -1
  57. package/dist/daemon/api/handlers/nodes.js +1 -1
  58. package/dist/daemon/api/operations.js +1 -1
  59. package/dist/daemon/api/router.js +1 -1
  60. package/dist/daemon/cron/live-runs.d.ts +3 -0
  61. package/dist/daemon/cron/live-runs.js +1 -1
  62. package/dist/daemon/cron/machine-fire.js +1 -1
  63. package/dist/daemon/crtrd.js +12 -12
  64. package/dist/daemon/due-sources.d.ts +1 -1
  65. package/dist/daemon/due-sources.js +1 -1
  66. package/dist/daemon/due.js +7 -7
  67. package/dist/daemon/human/finish.js +3 -3
  68. package/dist/daemon/human/settle.js +1 -1
  69. package/dist/daemon/machine-daemon.js +1 -1
  70. package/dist/daemon/reconcilers/action-lane.js +1 -1
  71. package/dist/daemon/reconcilers/delivery-lane.js +2 -2
  72. package/dist/daemon/reconcilers/grant-effects.js +1 -1
  73. package/dist/daemon/reconcilers/node-lifecycle/requested-stops.js +2 -2
  74. package/package.json +4 -3
  75. package/packages/crouter-api/dist/api/contract.js +1 -1
  76. package/packages/crouter-api/dist/clients/attach/input/controller.js +2 -2
  77. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +40 -3
  78. package/packages/crouter-api/dist/clients/attach/session/layout-record.js +7 -7
  79. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +41 -2
  80. package/packages/crouter-api/dist/clients/attach/slash/recover.js +23 -1
  81. package/packages/crouter-api/dist/clients/attach/viewer.js +21 -10
  82. package/packages/crouter-api/dist/commands/human/prompts.js +11 -18
  83. package/packages/crouter-api/dist/commands/human/request.js +3 -0
  84. package/packages/crouter-api/dist/commands/sys/doctor.js +17 -0
  85. package/packages/crouter-api/dist/commands/sys/tutorial/scenario.js +1 -0
  86. package/packages/crouter-api/dist/core/broker-client/client.js +4 -0
  87. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +45 -0
  88. package/packages/crouter-api/dist/core/canvas/daemon-actions.js +3 -2
  89. package/packages/crouter-api/dist/core/canvas/deliveries.js +7 -3
  90. package/packages/crouter-api/dist/core/canvas/executions.js +8 -7
  91. package/packages/crouter-api/dist/core/canvas/reconciler-leases.js +4 -0
  92. package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
  93. package/packages/crouter-api/dist/core/conversation-store/row-store.js +14 -1
  94. package/packages/crouter-api/dist/core/graph/package-docs.js +8 -3
  95. package/packages/crouter-api/dist/core/graph/package-publish.js +8 -1
  96. package/packages/crouter-api/dist/core/graph/reader.js +7 -1
  97. package/packages/crouter-api/dist/core/human/requests.js +2 -2
  98. package/packages/crouter-api/dist/core/permissions/evaluator.js +12 -6
  99. package/packages/crouter-api/dist/core/runtime/broker-protocol.js +4 -4
  100. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +2 -2
  101. package/packages/crouter-api/dist/core/runtime/session-cycles.js +90 -8
  102. package/packages/crouter-api/dist/daemon/api/operations.js +3 -3
  103. package/packages/crouter-api/dist/daemon/api/router.js +1 -4
  104. package/packages/crouter-api/dist/daemon/cron/live-runs.js +4 -5
  105. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +3 -3
  106. package/packages/crouter-api/dist/daemon/human/finish.js +2 -1
  107. package/packages/crouter-api/dist/daemon/human/settle.js +1 -6
  108. package/packages/crouter-api/package.json +1 -1
  109. package/packages/crouter-identity/package.json +1 -1
  110. package/packages/crouter-plugin/package.json +3 -3
  111. package/runtime.lock.json +14 -14
  112. package/scripts/install-runtime.mjs +18 -1
  113. package/scripts/lib/install-source.mjs +49 -0
  114. package/dist/daemon/reconcilers/idle-sandbox.d.ts +0 -18
  115. package/dist/daemon/reconcilers/idle-sandbox.js +0 -7
@@ -1,47 +1,47 @@
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,
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{CLAIM_OWNER_EXPIRED_SQL as X}from"./reconciler-leases.js";import{inboxPath as w,passivePath as R}from"./paths.js";import{withRetryBudget as M}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 y(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=>({...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
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(y,"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
- 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
- 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
11
+ AND NOT (d.wake = 0 AND m.kind = 'message' AND coalesce(m.body_json ->> 'start_turn', 'true') = 'false')`,W=`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
12
+ WHERE delivery_id IN (${v}) RETURNING delivery_id`;async function te(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
13
13
  WHERE d.destination_id = ? AND d.wake = 0 AND d.canceled_at IS NULL
14
14
  AND m.kind = 'message' AND m.body_json ->> 'start_turn' = 'false'
15
15
  AND (d.state = 'pending' OR (d.state = 'handed_off' AND d.claim_owner = ?))`).all(e,a),t=new Set(i.length===0?[]:(await c.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
16
- WHERE delivery_id IN (${i.map(()=>"?").join(",")}) AND state = 'pending' RETURNING delivery_id`).all(a,d,d,...i.map(n=>n.delivery_id))).map(n=>n.delivery_id));return{action:"claimed",deliveries:await A(c,e,a,0,t,!0)}});const E=await N();return!E.inTransaction&&await E.prepare(v).get(e,s)===void 0?await L(E,e,a,!0)?{action:"claimed",deliveries:await A(E,e,a,s)}:{action:"hold",deliveries:[]}:await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=new Set((await c.prepare(M).all(a,d,d,e,s)).map(t=>t.delivery_id));return{action:"claimed",deliveries:await A(c,e,a,s,i)}})}o(Z,"claimNodeMail");async function ee(e,a,r=Date.now()){return await T(async d=>{if(!await L(d,e,a,!1))throw new Error(`execution ${a} is not live for node ${e}`);const s=new Set((await d.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
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
16
+ WHERE delivery_id IN (${i.map(()=>"?").join(",")}) AND state = 'pending' RETURNING delivery_id`).all(a,d,d,...i.map(n=>n.delivery_id))).map(n=>n.delivery_id));return{action:"claimed",deliveries:await y(c,e,a,0,t,!0)}});const E=await N();return!E.inTransaction&&await E.prepare(v).get(e,s)===void 0?await L(E,e,a,!0)?{action:"claimed",deliveries:await y(E,e,a,s)}:{action:"hold",deliveries:[]}:await T(async c=>{if(!await L(c,e,a,!0))return{action:"hold",deliveries:[]};const i=new Set((await c.prepare(W).all(a,d,d,e,s)).map(t=>t.delivery_id));return{action:"claimed",deliveries:await y(c,e,a,s,i)}})}o(te,"claimNodeMail");async function ae(e,a,r=Date.now()){return await T(async d=>{if(!await L(d,e,a,!1))throw new Error(`execution ${a} is not live for node ${e}`);const s=new Set((await d.prepare(`UPDATE deliveries SET state = 'handed_off', attempts = attempts + 1, claim_owner = ?, claimed_at = ?, updated_at = ?
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 y(d,e,a,1,s)})}o(ae,"claimKickoffMail");function j(e){return e.state==="accepted"?{state:"acknowledged"}:e}o(j,"normalizedSettlement");async function $(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"}:j(d),l=M(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)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
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 A=await i.prepare("SELECT destination_id, message_id FROM deliveries WHERE delivery_id = ?").get(e);E.push({failure:_.failure,destinationId:A.destination_id,messageId:A.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($,"settleDelivery");async function ne(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 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
- 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
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(ne,"retryFailedDelivery");async function ie(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 $(c.deliveryId,c.attempts,a,{state:c.disposition},d)?c.disposition:"stale"}})}:{action:"hold",results:[]})}o(ie,"acknowledgeNodeMail");async function de(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
+ WHERE d.delivery_id = ?`).get(e);return a===void 0||a.body_json===null?null:JSON.parse(a.body_json)}o(de,"messageBodyForDelivery");async function se(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(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 = ?
25
+ ORDER BY next_attempt_at, created_at, delivery_id`).all(e)).map(D)}o(se,"duePushDeliveries");async function re(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: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,
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(re,"claimPushDelivery");async function oe(e,a=!1){return await T(async r=>{const d=a?` AND ${X}`:"",s=a?[new Date(e).toISOString()]:[],E=await r.prepare(`UPDATE deliveries SET state = 'permanent_failed', next_attempt_at = NULL,
32
32
  claimed_at = NULL, claim_owner = NULL, failed_at = ?, updated_at = ?
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,
33
+ WHERE state = 'handed_off' AND canceled_at IS NOT NULL AND next_attempt_at IS NOT NULL${d}`).run(e,e,...s),c=await r.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 = ?
35
- WHERE state = 'handed_off' AND (canceled_at IS NULL OR next_attempt_at IS NULL)`).run(e,e);return Number(r.changes)+Number(d.changes)})}o(se,"resetHandedOffDeliveries");async function re(e,a){return await(await N()).prepare(`SELECT 1 FROM deliveries WHERE delivery_id = ? AND state = 'handed_off'
36
- AND attempts = ? AND claim_owner = ? AND canceled_at IS NULL`).get(e.deliveryId,e.attempts,a)!==void 0}o(re,"pushDeliveryClaimIsCurrent");async function oe(e,a,r=Date.now()){return Number((await(await N()).prepare(`UPDATE deliveries SET state = 'pending', claimed_at = NULL, claim_owner = NULL, updated_at = ?
37
- WHERE destination_id = ? AND claim_owner = ? AND state = 'handed_off' AND next_attempt_at IS NULL`).run(r,e,a)).changes)}o(oe,"releaseExecutionMail");async function le(e){return Number((await(await N()).prepare(`UPDATE deliveries AS d SET state = 'pending', claimed_at = NULL, claim_owner = NULL, updated_at = ?
35
+ WHERE state = 'handed_off' AND (canceled_at IS NULL OR next_attempt_at IS NULL)${d}`).run(e,e,...s);return Number(E.changes)+Number(c.changes)})}o(oe,"resetHandedOffDeliveries");async function le(e,a){return await(await N()).prepare(`SELECT 1 FROM deliveries WHERE delivery_id = ? AND state = 'handed_off'
36
+ AND attempts = ? AND claim_owner = ? AND canceled_at IS NULL`).get(e.deliveryId,e.attempts,a)!==void 0}o(le,"pushDeliveryClaimIsCurrent");async function _e(e,a,r=Date.now()){return Number((await(await N()).prepare(`UPDATE deliveries SET state = 'pending', claimed_at = NULL, claim_owner = NULL, updated_at = ?
37
+ WHERE destination_id = ? AND claim_owner = ? AND state = 'handed_off' AND next_attempt_at IS NULL`).run(r,e,a)).changes)}o(_e,"releaseExecutionMail");async function ce(e){return Number((await(await N()).prepare(`UPDATE deliveries AS d SET state = 'pending', claimed_at = NULL, claim_owner = NULL, updated_at = ?
38
38
  WHERE d.state = 'handed_off' AND d.next_attempt_at IS NULL
39
39
  AND NOT EXISTS (
40
40
  SELECT 1 FROM executions e WHERE e.node_id = d.destination_id AND e.execution_id = d.claim_owner AND e.state != 'exited'
41
- )`).run(e)).changes)}o(le,"resetStaleExecutionMail");const $=o((e,a)=>`${e}.wake = 1 AND ${e}.canceled_at IS NULL AND ${e}.urgency != 'deferred' AND ${e}.state IN (${a})`,"WAKE_MAIL_SQL"),b=o(e=>$(e,"'pending', 'handed_off'"),"UNSEEN_WAKE_MAIL_SQL");async function _e(e){return await(await N()).prepare(`SELECT 1 FROM deliveries d WHERE d.destination_id = ? AND ${b("d")} LIMIT 1`).get(e)!==void 0}o(_e,"hasUnseenWakeMail");async function ce(e,a){return await(await N()).prepare(`SELECT 1 FROM deliveries WHERE destination_id = ? AND wake = 1
42
- AND urgency != 'deferred' AND created_at >= ? LIMIT 1`).get(e,a)!==void 0}o(ce,"hasWakeMailSince");async function Ee(e){return Number((await(await N()).prepare("SELECT COUNT(*) AS count FROM deliveries WHERE destination_id = ? AND acknowledged_at IS NOT NULL").get(e)).count)}o(Ee,"acknowledgedNodeMailCount");function u(){let e;do e=C(16).toString("hex");while(e==="00000000000000000000000000000000");return e}o(u,"newId");function U(e){if(!I(e))return[];const a=O(e,"utf8");return a.trim()===""?[]:a.split(`
43
- `).filter(r=>r.trim()!=="").map((r,d)=>{let s;try{s=JSON.parse(r)}catch(E){throw new Error(`invalid mailbox JSON at ${e}:${d+1}: ${E.message}`)}if(!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.entry_id)||!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.operation_id))throw new Error(`invalid mailbox identity at ${e}:${d+1}`);if(typeof s.ts!="string"||typeof s.label!="string")throw new Error(`incomplete mailbox entry at ${e}:${d+1}`);return s})}o(U,"readJsonLines");function q(e){return I(e)?new Set(O(e,"utf8").split(`
44
- `).map(a=>a.trim()).filter(Boolean)):new Set}o(q,"readCanceled");function me(e){e.exec(`
41
+ )`).run(e)).changes)}o(ce,"resetStaleExecutionMail");const b=o((e,a)=>`${e}.wake = 1 AND ${e}.canceled_at IS NULL AND ${e}.urgency != 'deferred' AND ${e}.state IN (${a})`,"WAKE_MAIL_SQL"),q=o(e=>b(e,"'pending', 'handed_off'"),"UNSEEN_WAKE_MAIL_SQL");async function Ee(e){return await(await N()).prepare(`SELECT 1 FROM deliveries d WHERE d.destination_id = ? AND ${q("d")} LIMIT 1`).get(e)!==void 0}o(Ee,"hasUnseenWakeMail");async function me(e,a){return await(await N()).prepare(`SELECT 1 FROM deliveries WHERE destination_id = ? AND wake = 1
42
+ AND urgency != 'deferred' AND created_at >= ? LIMIT 1`).get(e,a)!==void 0}o(me,"hasWakeMailSince");async function Ne(e){return Number((await(await N()).prepare("SELECT COUNT(*) AS count FROM deliveries WHERE destination_id = ? AND acknowledged_at IS NOT NULL").get(e)).count)}o(Ne,"acknowledgedNodeMailCount");function u(){let e;do e=C(16).toString("hex");while(e==="00000000000000000000000000000000");return e}o(u,"newId");function U(e){if(!I(e))return[];const a=O(e,"utf8");return a.trim()===""?[]:a.split(`
43
+ `).filter(r=>r.trim()!=="").map((r,d)=>{let s;try{s=JSON.parse(r)}catch(E){throw new Error(`invalid mailbox JSON at ${e}:${d+1}: ${E.message}`)}if(!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.entry_id)||!/^(?!0{32}$)[0-9a-f]{32}$/.test(s.operation_id))throw new Error(`invalid mailbox identity at ${e}:${d+1}`);if(typeof s.ts!="string"||typeof s.label!="string")throw new Error(`incomplete mailbox entry at ${e}:${d+1}`);return s})}o(U,"readJsonLines");function J(e){return I(e)?new Set(O(e,"utf8").split(`
44
+ `).map(a=>a.trim()).filter(Boolean)):new Set}o(J,"readCanceled");function pe(e){e.exec(`
45
45
  CREATE TABLE IF NOT EXISTS messages (
46
46
  message_id TEXT PRIMARY KEY,
47
47
  seq INTEGER NOT NULL UNIQUE,
@@ -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,`${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};
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=J(`${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((A,h)=>a.push({nodeId:n,wake:0,source:"passive",fileRank:p,physicalIndex:h,entry:A,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(pe,"migrateMessagingState");function k(e){return Number(m(e,"SELECT COALESCE(MAX(seq), 0) AS seq FROM messages").get().seq)+1}o(k,"nextSeq");export{q as UNSEEN_WAKE_MAIL_SQL,b as WAKE_MAIL_SQL,ie as acknowledgeNodeMail,Ne as acknowledgedNodeMailCount,ae as claimKickoffMail,te as claimNodeMail,re as claimPushDelivery,D as deliveryFrom,se as duePushDeliveries,Ee as hasUnseenWakeMail,me as hasWakeMailSince,de as messageBodyForDelivery,pe as migrateMessagingState,j as normalizedSettlement,le as pushDeliveryClaimIsCurrent,_e as releaseExecutionMail,oe as resetHandedOffDeliveries,ce as resetStaleExecutionMail,ne as retryFailedDelivery,$ as settleDelivery};
@@ -45,7 +45,7 @@ export declare class ExecutionCapReached extends Error {
45
45
  constructor(cap: number, live: number);
46
46
  }
47
47
  /** Thrown by `beginExecution` when the node already holds a live execution another caller owns: a remote one, or a process
48
- * one this daemon epoch began. The holder keeps its row and token; the caller adopts it or backs off, never replaces it. */
48
+ * one this daemon epoch began (launching or running). The holder keeps its row and token; the caller adopts it or backs off, never replaces it. */
49
49
  export declare class ExecutionAlreadyLive extends Error {
50
50
  readonly nodeId: string;
51
51
  readonly executionId: string;
@@ -1 +1 @@
1
- var g=Object.defineProperty;var a=(e,t)=>g(e,"name",{value:t,configurable:!0});import{randomUUID as L}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as m,captureLivenessSnapshot as D,identitiesMatch as y,isBootScopedIdentity as O,isLegacyTicksIdentity as C}from"./pid.js";import{existsSync as P,readFileSync as U}from"node:fs";import{LAUNCHER_SOCKET as W}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as R}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,sandboxName:e.sandbox_name??null,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function j(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(j,"liveExecutionForNode");class H extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class b extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const F=7340001;async function J(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${F})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new H(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.state==="launching"?u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch:u.runner!=="process");if(s!==void 0)throw new b(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=L(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, sandbox_name, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",t.sandboxName??null,E,t.release??null,t.launchJson??null),p})}a(J,"beginExecution");async function G(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(G,"setExecutionLaunchJson");async function V(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(V,"recordExecutionIdle");async function z(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(z,"recordExecutionAwake");async function Q(e,t,n){const i=m([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&P(W)&&s?.pid!=null){const S=D(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=U(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Q,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),R(o.node_id)),o!==void 0})}a(I,"endExecution");async function Z(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(Z,"endLaunchingExecution");async function ee(e,t){return await I(e,t)}a(ee,"abortExecution");async function te(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),R(e)),Number(o.changes)===1})}a(te,"endLiveExecution");async function ne(e=t=>m([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!C(c.process_identity))continue;const s=e(c.pid);s===void 0||!O(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ne,"migrateLegacyExecutionIdentities");async function ae(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ae,"requestExecutionStop");async function ie(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(ie,"executionsWithStopRequestedBefore");async function w(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(w,"latestExecutionForNode");async function oe(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(oe,"hasRunningRemoteExecution");async function re(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(re,"hasLaunchingExecution");async function se(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(se,"liveProcessExecutionNodeIds");async function ce(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ce,"liveExecutionNodeIds");const A="profile_pause",T="profile_pause_absorbed";async function ue(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(ue,"markProfilePauseStop");async function de(e){return(await w(e))?.stopReason===A}a(de,"hasProfilePauseStop");async function pe(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(T,e,A);return Number(t.changes)>0}a(pe,"absorbProfilePauseStop");function Ee(e){return e.stopReason===T}a(Ee,"hasAbsorbedProfilePauseStop");const f="exited:";async function _e(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(_e,"recordExecutionExit");function xe(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(xe,"hasObservedExit");async function le(e){const t=await w(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(le,"takeObservedExit");export{b as ExecutionAlreadyLive,H as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,ee as abortExecution,pe as absorbProfilePauseStop,J as beginExecution,I as endExecution,Z as endLaunchingExecution,te as endLiveExecution,ie as executionsWithStopRequestedBefore,Ee as hasAbsorbedProfilePauseStop,re as hasLaunchingExecution,xe as hasObservedExit,de as hasProfilePauseStop,oe as hasRunningRemoteExecution,w as latestExecutionForNode,j as liveExecutionForNode,ce as liveExecutionNodeIds,se as liveProcessExecutionNodeIds,ue as markProfilePauseStop,ne as migrateLegacyExecutionIdentities,z as recordExecutionAwake,_e as recordExecutionExit,V as recordExecutionIdle,Q as recordExecutionPid,ae as requestExecutionStop,G as setExecutionLaunchJson,le as takeObservedExit};
1
+ var g=Object.defineProperty;var a=(e,t)=>g(e,"name",{value:t,configurable:!0});import{randomUUID as D}from"node:crypto";import{openDb as r,withCanvasWrite as _}from"./db.js";import{capturePidIdentities as m,captureLivenessSnapshot as R,identitiesMatch as y,recordedPidLiveness as O,isBootScopedIdentity as C,isLegacyTicksIdentity as P}from"./pid.js";import{existsSync as U,readFileSync as W}from"node:fs";import{LAUNCHER_SOCKET as H}from"../../launcher/spec.js";import{revokeNodeTokens as x}from"./node-tokens.js";import{clearPendingParkIn as l}from"../../daemon/park-pending.js";import{deleteSandboxOfEndedNode as w}from"../runtime/runner/delete-sandboxes.js";function d(){return new Date().toISOString()}a(d,"now");function N(e){return{executionId:e.execution_id,nodeId:e.node_id,daemonEpoch:e.daemon_epoch??null,pid:e.pid??null,processIdentity:e.process_identity??null,state:e.state,startedAt:e.started_at,endedAt:e.ended_at??null,exitReason:e.exit_reason??null,runner:e.runner,sandboxName:e.sandbox_name??null,attempt:Number(e.attempt),release:e.release??null,heartbeatAt:e.heartbeat_at??null,awakeSince:e.awake_since??null,idleAt:e.idle_at??null,exitedAt:e.exited_at??null,launchJson:e.launch_json??null,stopRequestedAt:e.stop_requested_at??null,stopAfterTurn:Number(e.stop_after_turn)===1,stopReason:e.stop_reason??null}}a(N,"hydrate");async function J(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? AND state != 'exited'").get(e);return t===void 0?null:N(t)}a(J,"liveExecutionForNode");class b extends Error{static{a(this,"ExecutionCapReached")}cap;live;constructor(t,n){super(`no broker slot is free \u2014 ${n} live executions at the cap of ${t}.`),this.cap=t,this.live=n,this.name="ExecutionCapReached"}}class F extends Error{static{a(this,"ExecutionAlreadyLive")}nodeId;executionId;constructor(t,n){super(`${t} already has a live execution ${n}.`),this.nodeId=t,this.executionId=n,this.name="ExecutionAlreadyLive"}}const v=7340001;async function G(e,t){return await _(async n=>{const i=d();if(!await n.prepare("SELECT node_id FROM nodes WHERE node_id = ? FOR UPDATE").get(e))throw new Error(`cannot begin execution: missing node ${e}`);if(t.cap!==void 0){await n.prepare(`SELECT pg_advisory_xact_lock(${v})`).get();const u=Number((await n.prepare("SELECT COUNT(*) AS n FROM executions WHERE state != 'exited' AND node_id != ?").get(e)).n);if(u>=t.cap)throw new b(t.cap,u)}const s=(await n.prepare("SELECT execution_id, runner, daemon_epoch, state, pid, process_identity FROM executions WHERE node_id = ? AND state != 'exited'").all(e)).find(u=>u.runner!=="process"||t.daemonEpoch!==null&&u.daemon_epoch===t.daemonEpoch&&(u.state==="launching"||O(u.pid,u.process_identity,R())!=="dead"));if(s!==void 0)throw new F(e,s.execution_id);(await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = 'superseded' WHERE node_id = ? AND state != 'exited'").run(i,i,e)).changes>0&&await l(n,e),await x(n,"node_id",e,i);const p=D(),E=t.attempt??Number((await n.prepare("SELECT COALESCE(MAX(attempt), 0) + 1 AS next FROM executions WHERE node_id = ?").get(e)).next);return await n.prepare("INSERT INTO executions (execution_id, node_id, daemon_epoch, pid, process_identity, state, started_at, ended_at, exit_reason, runner, sandbox_name, attempt, release, launch_json) VALUES (?, ?, ?, NULL, NULL, 'launching', ?, NULL, NULL, ?, ?, ?, ?, ?)").run(p,e,t.daemonEpoch,i,t.runner??"process",t.sandboxName??null,E,t.release??null,t.launchJson??null),p})}a(G,"beginExecution");async function V(e,t){const n=await(await r()).prepare("UPDATE executions SET launch_json = ? WHERE execution_id = ? AND state = 'launching'").run(t,e);if(Number(n.changes)!==1)throw new Error(`cannot set launch recipe for execution ${e}: no launching execution`)}a(V,"setExecutionLaunchJson");async function z(e){const t=await(await r()).prepare("UPDATE executions SET idle_at = ? WHERE execution_id = ? AND state = 'running' AND idle_at IS NULL").run(d(),e);return Number(t.changes)===1}a(z,"recordExecutionIdle");async function Q(e){await(await r()).prepare("UPDATE executions SET awake_since = ?, idle_at = NULL WHERE execution_id = ? AND state = 'running'").run(d(),e)}a(Q,"recordExecutionAwake");async function Z(e,t,n){const i=m([n])?.get(n)??null;return await _(async o=>{if((await o.prepare("UPDATE executions SET pid = ?, process_identity = ?, state = 'running', awake_since = ? WHERE execution_id = ? AND node_id = ? AND state = 'launching'").run(n,i,d(),e,t)).changes>0)return"recorded";const s=await o.prepare("SELECT pid FROM executions WHERE execution_id = ? AND node_id = ? AND state = 'running'").get(e,t);if(s?.pid===n)return"recorded";if(process.platform==="linux"&&U(H)&&s?.pid!=null){const S=R(),p=[s.pid];for(let E=0;E<p.length;E++)p.push(...S?.childrenOf.get(p[E])??[]);if(p.includes(n))return"recorded";for(const E of p)try{const u=W(`/proc/${E}/status`,"utf8"),h=/^NSpid:\s*(.+)$/m.exec(u)?.[1]?.trim().split(/\s+/).map(Number)??[];if(h.length>1&&h.at(-1)===n)return"recorded"}catch{}}return"shutdown"})}a(Z,"recordExecutionPid");async function I(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state != 'exited' RETURNING node_id").get(i,i,t.reason,e);return await x(n,"broker_process_id",e,i),o!==void 0&&(await l(n,o.node_id),w(o.node_id)),o!==void 0})}a(I,"endExecution");async function ee(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE execution_id = ? AND state = 'launching' RETURNING node_id").get(i,i,t.reason,e);return o===void 0?!1:(await x(n,"broker_process_id",e,i),await l(n,o.node_id),!0)})}a(ee,"endLaunchingExecution");async function te(e,t){return await I(e,t)}a(te,"abortExecution");async function ne(e,t){return await _(async n=>{const i=d(),o=await n.prepare("UPDATE executions SET state = 'exited', ended_at = ?, exited_at = ?, exit_reason = COALESCE(exit_reason, ?) WHERE node_id = ? AND state != 'exited'").run(i,i,t.reason,e);return await x(n,"node_id",e,i),Number(o.changes)>0&&(await l(n,e),w(e)),Number(o.changes)===1})}a(ne,"endLiveExecution");async function ae(e=t=>m([t])?.get(t)){const t=await r(),n=await t.prepare("SELECT execution_id, pid, process_identity FROM executions WHERE state = 'running' AND pid IS NOT NULL AND process_identity IS NOT NULL").all(),i=t.prepare("UPDATE executions SET process_identity = ? WHERE execution_id = ? AND pid = ? AND process_identity = ? AND state = 'running'"),o=[];for(const c of n){if(!P(c.process_identity))continue;const s=e(c.pid);s===void 0||!C(s)||!y(s,c.process_identity)||(await i.run(s,c.execution_id,c.pid,c.process_identity)).changes>0&&o.push(c.execution_id)}return{migrated:o}}a(ae,"migrateLegacyExecutionIdentities");async function ie(e,t){const n=await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_after_turn = CASE WHEN stop_requested_at IS NULL THEN ? ELSE stop_after_turn END, stop_reason = COALESCE(stop_reason, ?) WHERE node_id = ? AND state != 'exited'").run(d(),t.afterTurn?1:0,t.reason,e);return Number(n.changes)>0}a(ie,"requestExecutionStop");async function oe(e){return(await(await r()).prepare("SELECT * FROM executions WHERE state != 'exited' AND stop_requested_at IS NOT NULL AND stop_requested_at <= ? ORDER BY stop_requested_at").all(e)).map(N)}a(oe,"executionsWithStopRequestedBefore");async function T(e){const t=await(await r()).prepare("SELECT * FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1").get(e);return t===void 0?null:N(t)}a(T,"latestExecutionForNode");async function re(e){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'running' AND runner != 'process'").get(e)!==void 0}a(re,"hasRunningRemoteExecution");async function se(e,t){return await(await r()).prepare("SELECT 1 AS x FROM executions WHERE node_id = ? AND state = 'launching' AND (runner != 'process' OR daemon_epoch = ?)").get(e,t)!==void 0}a(se,"hasLaunchingExecution");async function ce(e){const t=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited' AND runner = 'process' AND daemon_epoch = ?").all(e);return new Set(t.map(n=>n.node_id))}a(ce,"liveProcessExecutionNodeIds");async function ue(){const e=await(await r()).prepare("SELECT node_id FROM executions WHERE state != 'exited'").all();return new Set(e.map(t=>t.node_id))}a(ue,"liveExecutionNodeIds");const A="profile_pause",L="profile_pause_absorbed";async function de(e){await(await r()).prepare("UPDATE executions SET stop_requested_at = COALESCE(stop_requested_at, ?), stop_reason = ? WHERE node_id = ? AND state != 'exited'").run(d(),A,e)}a(de,"markProfilePauseStop");async function pe(e){return(await T(e))?.stopReason===A}a(pe,"hasProfilePauseStop");async function Ee(e){const t=await(await r()).prepare("UPDATE executions SET stop_reason = ? WHERE execution_id = (SELECT execution_id FROM executions WHERE node_id = ? ORDER BY started_at DESC, attempt DESC LIMIT 1) AND stop_reason = ?").run(L,e,A);return Number(t.changes)>0}a(Ee,"absorbProfilePauseStop");function _e(e){return e.stopReason===L}a(_e,"hasAbsorbedProfilePauseStop");const f="exited:";async function xe(e,t){const n=t.oomKilled===!0?"out_of_memory":`${f}${t.code??""}:${t.signal??""}`;await(await r()).prepare("UPDATE executions SET exit_reason = ? WHERE execution_id = ? AND exit_reason IS NULL").run(n,e)}a(xe,"recordExecutionExit");function le(e){const t=e.exitReason;return t!=null&&(t==="out_of_memory"||t.startsWith(f))}a(le,"hasObservedExit");async function fe(e){const t=await T(e),n=t?.exitReason;if(t===null||n==null)return;const i=n==="out_of_memory";if(!i&&!n.startsWith(f))return;const o=await(await r()).prepare("UPDATE executions SET exit_reason = 'exit_handled' WHERE execution_id = ? AND exit_reason = ?").run(t.executionId,n);if(Number(o.changes)===0)return;if(i)return{code:null,signal:null,oomKilled:!0};const[c,s]=n.slice(f.length).split(":");return{code:c===""?null:Number(c),signal:s===""?null:s}}a(fe,"takeObservedExit");export{F as ExecutionAlreadyLive,b as ExecutionCapReached,A as PROFILE_PAUSE_STOP_REASON,te as abortExecution,Ee as absorbProfilePauseStop,G as beginExecution,I as endExecution,ee as endLaunchingExecution,ne as endLiveExecution,oe as executionsWithStopRequestedBefore,_e as hasAbsorbedProfilePauseStop,se as hasLaunchingExecution,le as hasObservedExit,pe as hasProfilePauseStop,re as hasRunningRemoteExecution,T as latestExecutionForNode,J as liveExecutionForNode,ue as liveExecutionNodeIds,ce as liveProcessExecutionNodeIds,de as markProfilePauseStop,ae as migrateLegacyExecutionIdentities,Q as recordExecutionAwake,xe as recordExecutionExit,z as recordExecutionIdle,Z as recordExecutionPid,ie as requestExecutionStop,V as setExecutionLaunchJson,fe as takeObservedExit};
@@ -1,3 +1,7 @@
1
+ /** The lane whose rows are live daemon instances: a delivery or daemon-action claim is held by an instance id with an unexpired row here. */
2
+ export declare const DAEMON_OWNER_LANE = "cron-owner";
3
+ /** SQL (parameter: now ISO) true for a claim whose owner has no live heartbeat. */
4
+ export declare const CLAIM_OWNER_EXPIRED_SQL = "NOT EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = 'cron-owner' AND key = claim_owner AND expires_at > ?)";
1
5
  /** A claim owner is a fresh token for each attempt, not a process id: a timed-out worker cannot renew a successor's claim. */
2
6
  export interface ReconcilerLease {
3
7
  cursor: string | null;
@@ -1,8 +1,8 @@
1
- var u=Object.defineProperty;var a=(e,r)=>u(e,"name",{value:r,configurable:!0});import{openDb as i}from"./db.js";function c(e){if(!Number.isFinite(e)||e<=0)throw new Error("reconciler lease duration must be positive");return new Date(Date.now()+e).toISOString()}a(c,"expiry");async function E(e,r,n,t){const o=c(t),s=new Date().toISOString();return(await i()).prepare(`INSERT INTO reconciler_leases (lane, key, owner, expires_at)
1
+ var l=Object.defineProperty;var a=(e,r)=>l(e,"name",{value:r,configurable:!0});import{openDb as c}from"./db.js";const D="cron-owner",N=`NOT EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = '${D}' AND key = claim_owner AND expires_at > ?)`;function i(e){if(!Number.isFinite(e)||e<=0)throw new Error("reconciler lease duration must be positive");return new Date(Date.now()+e).toISOString()}a(i,"expiry");async function S(e,r,n,t){const o=i(t),s=new Date().toISOString();return(await c()).prepare(`INSERT INTO reconciler_leases (lane, key, owner, expires_at)
2
2
  VALUES (?, ?, ?, ?)
3
3
  ON CONFLICT (lane, key) DO UPDATE SET owner = EXCLUDED.owner, expires_at = EXCLUDED.expires_at
4
4
  WHERE reconciler_leases.expires_at <= ?
5
- RETURNING cursor`).get(e,r,n,o,s)}a(E,"claimReconcilerLease");async function S(e,r,n,t){const o=c(t),s=new Date().toISOString();return(await(await i()).prepare(`UPDATE reconciler_leases SET expires_at = ?
6
- WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?`).run(o,e,r,n,s)).changes===1}a(S,"renewReconcilerLease");async function N(e,r,n,t){return(await(await i()).prepare(`UPDATE reconciler_leases SET cursor = ?
7
- WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?`).run(t,e,r,n,new Date().toISOString())).changes===1}a(N,"advanceReconcilerCursor");async function x(e,r,n){return(await(await i()).prepare(`UPDATE reconciler_leases SET expires_at = ?
8
- WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?`).run(new Date(0).toISOString(),e,r,n,new Date().toISOString())).changes===1}a(x,"releaseReconcilerLease");export{N as advanceReconcilerCursor,E as claimReconcilerLease,x as releaseReconcilerLease,S as renewReconcilerLease};
5
+ RETURNING cursor`).get(e,r,n,o,s)}a(S,"claimReconcilerLease");async function _(e,r,n,t){const o=i(t),s=new Date().toISOString();return(await(await c()).prepare(`UPDATE reconciler_leases SET expires_at = ?
6
+ WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?`).run(o,e,r,n,s)).changes===1}a(_,"renewReconcilerLease");async function A(e,r,n,t){return(await(await c()).prepare(`UPDATE reconciler_leases SET cursor = ?
7
+ WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?`).run(t,e,r,n,new Date().toISOString())).changes===1}a(A,"advanceReconcilerCursor");async function x(e,r,n){return(await(await c()).prepare(`UPDATE reconciler_leases SET expires_at = ?
8
+ WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?`).run(new Date(0).toISOString(),e,r,n,new Date().toISOString())).changes===1}a(x,"releaseReconcilerLease");export{N as CLAIM_OWNER_EXPIRED_SQL,D as DAEMON_OWNER_LANE,A as advanceReconcilerCursor,S as claimReconcilerLease,x as releaseReconcilerLease,_ as renewReconcilerLease};
@@ -1,2 +1,2 @@
1
- var _=Object.defineProperty;var n=(l,m)=>_(l,"name",{value:m,configurable:!0});import{MessageChannel as g,Worker as y,receiveMessageOnPort as N}from"node:worker_threads";import{ConversationNotFoundError as q}from"./index.js";let $;function D(l){$=l}n(D,"setConversationRequestMark");function x(l,m){const c=new y(new URL(import.meta.url.endsWith(".ts")?"./client-worker.ts":"./client-worker.js",import.meta.url),{workerData:{address:l,token:m}});c.unref();const k=Date.now();let b=0,s;c.on("error",e=>{s=e}),c.on("exit",e=>{s=new Error(`conversation store worker exited with ${e}`)});function w(e,r,t){if(!t)throw new Error("conversation store worker returned no reply");if(t.error)throw new Error(t.error);if(t.status===404)throw new q(r.split("/")[2]??r);if(!t.status||t.status>=400)throw new Error(`conversation store ${e} ${r} failed (${t.status}): ${t.body}`);return{body:t.body??"",...t.path?{path:t.path}:{},...t.tail?{tail:Number(t.tail)}:{}}}n(w,"settle");function u(e,r,t){if(s)throw s;const o=new SharedArrayBuffer(4),{port1:a,port2:d}=new g,p=process.hrtime.bigint(),h=b++===0;try{c.postMessage({method:e,path:r,data:t,signal:o,reply:d},[d]);const f=Atomics.wait(new Int32Array(o),0,0,3e4);if($?.({method:e,route:r.replace(/\/[0-9a-f-]{36}/gi,"/:id"),durationMs:Number(process.hrtime.bigint()-p)/1e6,firstRequest:h,workerAgeMs:Date.now()-k}),f==="timed-out")throw a.postMessage("cancel"),new Error(`conversation store request timed out: ${e} ${r}`);return w(e,r,N(a)?.message)}finally{a.close()}}n(u,"call");function E(e,r,t){if(s)return Promise.reject(s);const{port1:o,port2:a}=new g,d=process.hrtime.bigint(),p=b++===0;return new Promise((h,f)=>{const M=setTimeout(()=>{o.postMessage("cancel"),o.close(),f(new Error(`conversation store request timed out: ${e} ${r}`))},3e4);M.unref(),o.once("message",P=>{clearTimeout(M),o.close(),$?.({method:e,route:r.replace(/\/[0-9a-f-]{36}/gi,"/:id"),durationMs:Number(process.hrtime.bigint()-d)/1e6,firstRequest:p,workerAgeMs:Date.now()-k});try{h(w(e,r,P))}catch(A){f(A)}}),c.postMessage({method:e,path:r,data:t,reply:a},[a])})}n(E,"callAsync");const i=n(e=>`/conversations/${encodeURIComponent(e)}`,"url");function T(e,r){if(s)throw s;c.postMessage({kind:"append",method:"POST",path:`${i(e)}/entries`,data:{entries:r}})}n(T,"enqueueAppend");function O(){if(s)return Promise.reject(s);const{port1:e,port2:r}=new g;return new Promise((t,o)=>{e.once("message",a=>{e.close();try{w("POST","/commit",a),t()}catch(d){o(d)}}),c.postMessage({kind:"flush",method:"POST",path:"/commit",reply:r},[r])})}n(O,"flush");const S=n(e=>{const[r,...t]=e.body.trimEnd().split(`
2
- `).map(a=>JSON.parse(a)),o=t;return e.tail===void 0?{header:r,entries:o,path:e.path??""}:{header:r,entries:o.slice(0,e.tail-1),tail:o.slice(e.tail-1),path:e.path??""}},"parseRead"),v=n((e,r)=>r==="cycle"?`${i(e)}?from=cycle`:r?`${i(e)}?head=${r.head}&tail=${r.tail}`:i(e),"readPath");return{create(e,r,t,o){return JSON.parse(u("POST","/conversations",{node_id:e,header:r,entries:t,path:o}).body)},async createAsync(e,r,t,o){return JSON.parse((await E("POST","/conversations",{node_id:e,header:r,entries:t,path:o})).body)},append(e,r){T(e,r)},flush:O,replace(e,r,t){u("PUT",i(e),{header:r,entries:t})},read(e,r){return S(u("GET",v(e,r)))},async readAsync(e,r){return S(await E("GET",v(e,r)))},header(e){return JSON.parse(u("GET",`${i(e)}/header`).body)},fork(e,r,t,o){return JSON.parse(u("POST",`${i(e)}/fork`,{node_id:r,leaf_id:t,cwd:o}).body).conversation_id},list(e){const r=e===void 0?"":`?node_id=${encodeURIComponent(e)}`;return JSON.parse(u("GET",`/conversations${r}`).body).conversations},delete(e){u("DELETE",i(e))}}}n(x,"createStoreClient");export{x as createStoreClient,D as setConversationRequestMark};
1
+ var A=Object.defineProperty;var n=(l,m)=>A(l,"name",{value:m,configurable:!0});import{MessageChannel as $,Worker as _,receiveMessageOnPort as N}from"node:worker_threads";import{ConversationNotFoundError as q}from"./index.js";let b;function D(l){b=l}n(D,"setConversationRequestMark");function x(l,m){const c=new _(new URL(import.meta.url.endsWith(".ts")?"./client-worker.ts":"./client-worker.js",import.meta.url),{workerData:{address:l,token:m}});c.unref();const g=Date.now();let k=0,s;c.on("error",e=>{s=e}),c.on("exit",e=>{s=new Error(`conversation store worker exited with ${e}`)});function p(e,r,t){if(!t)throw new Error("conversation store worker returned no reply");if(t.error)throw new Error(t.error);if(t.status===404)throw new q(r.split("/")[2]??r);if(!t.status||t.status>=400)throw new Error(`conversation store ${e} ${r} failed (${t.status}): ${t.body}`);return{body:t.body??"",...t.path?{path:t.path}:{},...t.tail?{tail:Number(t.tail)}:{}}}n(p,"settle");function u(e,r,t){if(s)throw s;const o=new SharedArrayBuffer(4),{port1:a,port2:d}=new $,w=process.hrtime.bigint(),h=k++===0;try{c.postMessage({method:e,path:r,data:t,signal:o,reply:d},[d]);const f=Atomics.wait(new Int32Array(o),0,0,3e4);if(b?.({method:e,route:r.replace(/\/[0-9a-f-]{36}/gi,"/:id"),durationMs:Number(process.hrtime.bigint()-w)/1e6,firstRequest:h,workerAgeMs:Date.now()-g}),f==="timed-out")throw a.postMessage("cancel"),new Error(`conversation store request timed out: ${e} ${r}`);return p(e,r,N(a)?.message)}finally{a.close()}}n(u,"call");function E(e,r,t){if(s)return Promise.reject(s);const{port1:o,port2:a}=new $,d=process.hrtime.bigint(),w=k++===0;return new Promise((h,f)=>{const y=setTimeout(()=>{o.postMessage("cancel"),o.close(),f(new Error(`conversation store request timed out: ${e} ${r}`))},3e4);y.unref(),o.once("message",O=>{clearTimeout(y),o.close(),b?.({method:e,route:r.replace(/\/[0-9a-f-]{36}/gi,"/:id"),durationMs:Number(process.hrtime.bigint()-d)/1e6,firstRequest:w,workerAgeMs:Date.now()-g});try{h(p(e,r,O))}catch(P){f(P)}}),c.postMessage({method:e,path:r,data:t,reply:a},[a])})}n(E,"callAsync");const i=n(e=>`/conversations/${encodeURIComponent(e)}`,"url");function M(e,r){if(s)throw s;c.postMessage({kind:"append",method:"POST",path:`${i(e)}/entries`,data:{entries:r}})}n(M,"enqueueAppend");function T(){if(s)return Promise.reject(s);const{port1:e,port2:r}=new $;return new Promise((t,o)=>{e.once("message",a=>{e.close();try{p("POST","/commit",a),t()}catch(d){o(d)}}),c.postMessage({kind:"flush",method:"POST",path:"/commit",reply:r},[r])})}n(T,"flush");const S=n(e=>{const[r,...t]=e.body.trimEnd().split(`
2
+ `).map(a=>JSON.parse(a)),o=t;return e.tail===void 0?{header:r,entries:o,path:e.path??""}:{header:r,entries:o.slice(0,e.tail-1),tail:o.slice(e.tail-1),path:e.path??""}},"parseRead"),v=n((e,r)=>r==="cycle"?`${i(e)}?from=cycle`:r&&"beforeCycle"in r?`${i(e)}?before=cycle&bytes=${r.beforeCycle}`:r?`${i(e)}?head=${r.head}&tail=${r.tail}`:i(e),"readPath");return{create(e,r,t,o){return JSON.parse(u("POST","/conversations",{node_id:e,header:r,entries:t,path:o}).body)},async createAsync(e,r,t,o){return JSON.parse((await E("POST","/conversations",{node_id:e,header:r,entries:t,path:o})).body)},append(e,r){M(e,r)},flush:T,replace(e,r,t){u("PUT",i(e),{header:r,entries:t})},read(e,r){return S(u("GET",v(e,r)))},async readAsync(e,r){return S(await E("GET",v(e,r)))},header(e){return JSON.parse(u("GET",`${i(e)}/header`).body)},fork(e,r,t,o){return JSON.parse(u("POST",`${i(e)}/fork`,{node_id:r,leaf_id:t,cwd:o}).body).conversation_id},list(e){const r=e===void 0?"":`?node_id=${encodeURIComponent(e)}`;return JSON.parse(u("GET",`/conversations${r}`).body).conversations},delete(e){u("DELETE",i(e))}}}n(x,"createStoreClient");export{x as createStoreClient,D as setConversationRequestMark};
@@ -14,11 +14,14 @@ export interface ConversationInfo {
14
14
  size: number;
15
15
  path: string;
16
16
  }
17
- /** Byte budgets for a bounded read of a conversation's two ends, or `'cycle'`: the entries from the last `crtr-cycle` entry on. */
17
+ /** Byte budgets for a bounded read of a conversation's two ends; `'cycle'`: the entries from the last `crtr-cycle` entry on;
18
+ * `{ beforeCycle }`: the entries wholly inside the last `beforeCycle` bytes before that entry (the earlier cycles' ends). */
18
19
  export type ConversationWindow = {
19
20
  head: number;
20
21
  tail: number;
21
- } | 'cycle';
22
+ } | 'cycle' | {
23
+ beforeCycle: number;
24
+ };
22
25
  /** The synchronous shape pi's `SessionManager` statics need (`patch.ts`). The broker's client
23
26
  * (`client.ts`: an `Atomics.wait` worker, no db) implements it. It is declared apart from
24
27
  * `ConversationStore` so a change to the daemon's store never changes pi's contract. */
@@ -1,13 +1,15 @@
1
- var j=Object.defineProperty;var f=(i,e)=>j(i,"name",{value:e,configurable:!0});import{randomUUID as S}from"node:crypto";import{existsSync as J,readFileSync as x,rmSync as P}from"node:fs";import{join as Y}from"node:path";import{SessionManager as V}from"@earendil-works/pi-coding-agent";import{blobStore as E}from"../blobs/index.js";import{openDb as l,withCanvasWrite as y}from"../canvas/db.js";import{appSpace as G}from"../layout.js";import{timedSpan as L}from"../logged-step-timings.js";import{addStepTiming as z}from"../step-timings.js";import{appendConversationEvents as D,rootRepromptPending as M}from"../../daemon/runs/append-section.js";import{ConversationNotFoundError as v}from"./index.js";const R="s.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC",A=f((i,e,r)=>`conversations/${i}/${e}/${r}.jsonl`,"keyFor"),U=f(i=>i.map(e=>JSON.stringify(e)+`
2
- `).join(""),"encode"),F=f(i=>i.split(`
3
- `).filter(Boolean).map(e=>JSON.parse(e)),"decode"),N=f(()=>new Date().toISOString(),"at");async function m(i,e,r=!1){const a=await i.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${R} LIMIT 1${r?" FOR UPDATE OF s":""}`).get(e);if(!a)throw new v(e);return a}f(m,"binding");async function b(i,e){return await i.prepare("SELECT seq, blob_key, bytes, entries, created FROM conversation_parts WHERE conversation_id = ? ORDER BY seq").all(e)}f(b,"parts");async function W(i,e){return await i.prepare("SELECT seq, body, bytes, created FROM conversation_entries WHERE conversation_id = ? ORDER BY seq").all(e)}f(W,"tail");async function H(i,e){const r=await i.prepare(`SELECT 'part' AS kind, seq, blob_key, NULL AS body, bytes, entries, created FROM conversation_parts WHERE conversation_id = ?
4
- UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(e,e);return{parts:r.filter(a=>a.kind==="part").map(({seq:a,blob_key:t,bytes:s,entries:n,created:o})=>({seq:Number(a),blob_key:t,bytes:Number(s),entries:Number(n),created:o})),tail:r.filter(a=>a.kind==="tail").map(({seq:a,body:t,bytes:s,created:n})=>({seq:Number(a),body:t,bytes:Number(s),created:n}))}}f(H,"snapshot");const I=4*1024*1024,K=4,Q=16;async function*$(i,e,r){const a=[];let t=0;const s=f(()=>{for(;t<i&&a.length<r;){const n=e(t++);n.catch(()=>{}),a.push(n)}},"fill");for(s();a.length>0;){const n=await a.shift();s(),yield n}}f($,"readAhead");async function O(i,e,r){const a=[];let t=0;const s=await E(),n=[];for(const o of i.parts){const c=Math.max(e,t),d=Math.min(r,t+o.bytes);c<d&&n.push({key:o.blob_key,range:{start:c-t,length:d-c}}),t+=o.bytes}for await(const o of $(n.length,async c=>{const d=await s.get(n[c].key,n[c].range);if(!d)throw new Error(`missing conversation object: ${n[c].key}`);return d},Q))a.push(o);for(const o of i.tail){const c=Math.max(e,t),d=Math.min(r,t+o.bytes);c<d&&a.push(Buffer.from(o.body+`
5
- `).subarray(c-t,d-t)),t+=o.bytes}return Buffer.concat(a)}f(O,"bytesOf");async function*q(i){const e=i.parts.reduce((a,t)=>a+t.bytes,0)+i.tail.reduce((a,t)=>a+t.bytes,0);let r="";for await(const a of $(Math.ceil(e/I),t=>O(i,t*I,Math.min(e,(t+1)*I)),K)){const t=r+a.toString("latin1"),s=t.lastIndexOf(`
6
- `);r=t.slice(s+1);for(const n of t.slice(0,s+1).split(`
7
- `))n&&(yield Buffer.from(n,"latin1").toString("utf8"))}r&&(yield Buffer.from(r,"latin1").toString("utf8"))}f(q,"linesOf");const C=new Map;async function B(i,e,r){const a=await l();if(await a.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(i)||!J(r))return;let t=x(r);const s=t.lastIndexOf(10);if(s<0)return;t=t.subarray(0,s+1);const n=await a.prepare("SELECT s.binding_id, s.node_id, s.event_offset, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY "+R+" LIMIT 1").get(i);let o=[];if(n?.run_id&&n.event_offset!==null){const p=Number(n.event_offset);if(t.length<p)throw new Error(`conversation shorter than indexed offset: ${i}`);o=F(t.subarray(p).toString("utf8")).filter(w=>w.type!=="session")}const c=n?.run_id?await M(n.run_id,n.node_id,o):!1,d=A(e,i,0);await(await E()).put(d,t),await y(async p=>{if(!await p.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING seq").get(i,d,t.length,Math.max(0,t.toString("utf8").split(`
8
- `).filter(Boolean).length-1),N())||!n?.run_id||n.event_offset===null)return;const _=n.source_session_id?[]:await D(p,n.run_id,n.node_id,o,JSON.parse(n.input_ids_json),c);await p.prepare("UPDATE sessions SET event_offset = ?, indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(t.length,o.at(-1)?.id??null,JSON.stringify(_),n.binding_id)})}f(B,"importOne");async function T(i,e){const r=await e.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${R} LIMIT 1`).get(i),a=C.get(i);if(!r&&!a)throw new v(i);let t=(await b(e,i))[0];if(!t){const c=a?.path??r?.transcript_path??void 0;c&&await B(i,a?.node??r.node_id,c),t=(await b(e,i))[0]}if(!t||t.seq!==0)throw new v(i);const s=await(await E()).get(t.blob_key,{start:0,length:Math.min(t.bytes,256*1024)});if(!s)throw new Error(`missing conversation object: ${t.blob_key}`);const n=s.indexOf(10);if(n<0)throw new Error(`invalid conversation header: ${i}`);const o=JSON.parse(s.subarray(0,n).toString("utf8"));if(o.type!=="session"||o.id!==i)throw new Error(`invalid conversation header: ${i}`);return{header:o,path:r?.transcript_path??a?.path??"",binding:r}}f(T,"initial");function _e(){const i={async create(e,r,a,t){const s=await l(),n=await L("owner_read",async()=>await s.prepare("SELECT grantee, run_id FROM node_rows WHERE node_id = ?").get(e));if(!n)throw new Error(`missing conversation owner ${e}`);const o=r.id,c=Y(G(n.grantee).conversations,e,`${r.timestamp.replace(/[:.]/g,"-")}_${o}.jsonl`),d=U([r,...a]),p=A(e,o,0),w=n.run_id?await M(n.run_id,e,a):!1;return z("blob_bytes",Buffer.byteLength(d)),await L("blob_put",async()=>await(await E()).put(p,d)),await L("transaction",()=>y(async _=>{if(await _.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ?").get(o))throw new Error(`conversation already exists: ${o}`);const u=N(),g=r.parentSession?await _.prepare("SELECT session_id FROM sessions WHERE transcript_path = ? LIMIT 1").get(r.parentSession):void 0;if(await _.prepare("INSERT INTO sessions (binding_id, session_id, node_id, transcript_path, source_session_id, fork_entry_id, created_at, bound_at, unbound_at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)").run(S(),o,e,c,g?g.session_id:null,u,u,u),await _.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(o,p,Buffer.byteLength(d),a.length,u),n.run_id&&!g){const h=await D(_,n.run_id,e,a,[],w);await _.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?").run(a.at(-1)?.id??null,JSON.stringify(h),o,e)}},{timingName:"create_tx"})),{conversation_id:o,path:c}},async append(e,r){if(!r.length)return;const a=await m(await l(),e),t=a.run_id?await M(a.run_id,a.node_id,r):!1;await y(async s=>{const n=await m(s,e,!0);if(!(await b(s,e)).length)throw new v(e);const o=[];for(const c of r){const d=JSON.stringify(c);if(await s.prepare("INSERT INTO conversation_entries (conversation_id, entry_id, body, bytes, execution_id, created) VALUES (?, ?, ?, ?, NULL, ?) ON CONFLICT (conversation_id, entry_id) DO NOTHING RETURNING entry_id").get(e,c.id,d,Buffer.byteLength(d)+1,N())&&(o.push(c),c.type==="custom"&&c.customType==="crtr-cycle")){await s.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0 FOR UPDATE").get(e);const w=[...await b(s,e),...await W(s,e)].reduce((_,u)=>_+Number(u.bytes),0)-Buffer.byteLength(d)-1;await s.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0").run(w,e)}}if(n.run_id&&o.length){const c=await D(s,n.run_id,n.node_id,o,JSON.parse(n.input_ids_json??"[]"),t);await s.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(o.at(-1).id,JSON.stringify(c),n.binding_id)}})},async readLines(e){const r=await l(),{path:a}=await T(e,r);return{path:a,lines:q(await H(r,e))}},async read(e,r){const a=await l(),{header:t,path:s}=await T(e,a),n=await H(a,e),o=n.parts.reduce((_,u)=>_+u.bytes,0)+n.tail.reduce((_,u)=>_+u.bytes,0),c=f(_=>F(_).filter(u=>u.type!=="session"),"entriesOf");if(r==="cycle"){const _=await a.prepare("SELECT cycle_offset FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(e);let u=_?.cycle_offset==null?null:Number(_.cycle_offset);if(u===null){u=0;let g=0;for await(const h of q(n)){if(h.includes('"crtr-cycle"')){const k=JSON.parse(h);k.type==="custom"&&k.customType==="crtr-cycle"&&(u=g)}g+=Buffer.byteLength(h)+1}await y(async h=>{await h.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0 AND cycle_offset IS NULL").run(u,e)})}return{header:t,entries:c((await O(n,u,o)).toString("utf8")),path:s}}if(!r||o<=r.head+r.tail)return{header:t,entries:c((await O(n,0,o)).toString("utf8")),path:s};const d=(await O(n,0,Math.max(0,r.head))).toString("utf8").split(`
9
- `);d.pop();const p=Math.max(0,o-r.tail),w=(await O(n,p>0?p-1:0,o)).toString("utf8").split(`
10
- `);return p>0&&w.shift(),{header:t,entries:c(d.join(`
1
+ var J=Object.defineProperty;var f=(i,e)=>J(i,"name",{value:e,configurable:!0});import{randomUUID as v}from"node:crypto";import{existsSync as x,readFileSync as P,rmSync as Y}from"node:fs";import{join as V}from"node:path";import{SessionManager as G}from"@earendil-works/pi-coding-agent";import{blobStore as y}from"../blobs/index.js";import{openDb as E,withCanvasWrite as b}from"../canvas/db.js";import{appSpace as z}from"../layout.js";import{timedSpan as D}from"../logged-step-timings.js";import{addStepTiming as K}from"../step-timings.js";import{appendConversationEvents as M,rootRepromptPending as A}from"../../daemon/runs/append-section.js";import{ConversationNotFoundError as T}from"./index.js";const S="s.unbound_at IS NULL DESC, s.created_at DESC, s.seq DESC",C=f((i,e,s)=>`conversations/${i}/${e}/${s}.jsonl`,"keyFor"),F=f(i=>i.map(e=>JSON.stringify(e)+`
2
+ `).join(""),"encode"),W=f(i=>i.split(`
3
+ `).filter(Boolean).map(e=>JSON.parse(e)),"decode"),N=f(()=>new Date().toISOString(),"at");async function m(i,e,s=!1){const a=await i.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${S} LIMIT 1${s?" FOR UPDATE OF s":""}`).get(e);if(!a)throw new T(e);return a}f(m,"binding");async function h(i,e){return await i.prepare("SELECT seq, blob_key, bytes, entries, created FROM conversation_parts WHERE conversation_id = ? ORDER BY seq").all(e)}f(h,"parts");async function $(i,e){return await i.prepare("SELECT seq, body, bytes, created FROM conversation_entries WHERE conversation_id = ? ORDER BY seq").all(e)}f($,"tail");async function H(i,e){const s=await i.prepare(`SELECT 'part' AS kind, seq, blob_key, NULL AS body, bytes, entries, created FROM conversation_parts WHERE conversation_id = ?
4
+ UNION ALL SELECT 'tail', seq, NULL, body, bytes, NULL, created FROM conversation_entries WHERE conversation_id = ? ORDER BY 1, 2`).all(e,e);return{parts:s.filter(a=>a.kind==="part").map(({seq:a,blob_key:t,bytes:r,entries:n,created:o})=>({seq:Number(a),blob_key:t,bytes:Number(r),entries:Number(n),created:o})),tail:s.filter(a=>a.kind==="tail").map(({seq:a,body:t,bytes:r,created:n})=>({seq:Number(a),body:t,bytes:Number(r),created:n}))}}f(H,"snapshot");const I=4*1024*1024,Q=4,X=16;async function*q(i,e,s){const a=[];let t=0;const r=f(()=>{for(;t<i&&a.length<s;){const n=e(t++);n.catch(()=>{}),a.push(n)}},"fill");for(r();a.length>0;){const n=await a.shift();r(),yield n}}f(q,"readAhead");async function O(i,e,s){const a=[];let t=0;const r=await y(),n=[];for(const o of i.parts){const c=Math.max(e,t),d=Math.min(s,t+o.bytes);c<d&&n.push({key:o.blob_key,range:{start:c-t,length:d-c}}),t+=o.bytes}for await(const o of q(n.length,async c=>{const d=await r.get(n[c].key,n[c].range);if(!d)throw new Error(`missing conversation object: ${n[c].key}`);return d},X))a.push(o);for(const o of i.tail){const c=Math.max(e,t),d=Math.min(s,t+o.bytes);c<d&&a.push(Buffer.from(o.body+`
5
+ `).subarray(c-t,d-t)),t+=o.bytes}return Buffer.concat(a)}f(O,"bytesOf");async function*B(i){const e=i.parts.reduce((a,t)=>a+t.bytes,0)+i.tail.reduce((a,t)=>a+t.bytes,0);let s="";for await(const a of q(Math.ceil(e/I),t=>O(i,t*I,Math.min(e,(t+1)*I)),Q)){const t=s+a.toString("latin1"),r=t.lastIndexOf(`
6
+ `);s=t.slice(r+1);for(const n of t.slice(0,r+1).split(`
7
+ `))n&&(yield Buffer.from(n,"latin1").toString("utf8"))}s&&(yield Buffer.from(s,"latin1").toString("utf8"))}f(B,"linesOf");const k=new Map;async function j(i,e,s){const a=await E();if(await a.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(i)||!x(s))return;let t=P(s);const r=t.lastIndexOf(10);if(r<0)return;t=t.subarray(0,r+1);const n=await a.prepare("SELECT s.binding_id, s.node_id, s.event_offset, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY "+S+" LIMIT 1").get(i);let o=[];if(n?.run_id&&n.event_offset!==null){const _=Number(n.event_offset);if(t.length<_)throw new Error(`conversation shorter than indexed offset: ${i}`);o=W(t.subarray(_).toString("utf8")).filter(l=>l.type!=="session")}const c=n?.run_id?await A(n.run_id,n.node_id,o):!1,d=C(e,i,0);await(await y()).put(d,t),await b(async _=>{if(!await _.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING seq").get(i,d,t.length,Math.max(0,t.toString("utf8").split(`
8
+ `).filter(Boolean).length-1),N())||!n?.run_id||n.event_offset===null)return;const w=n.source_session_id?[]:await M(_,n.run_id,n.node_id,o,JSON.parse(n.input_ids_json),c);await _.prepare("UPDATE sessions SET event_offset = ?, indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(t.length,o.at(-1)?.id??null,JSON.stringify(w),n.binding_id)})}f(j,"importOne");async function L(i,e){const s=await e.prepare(`SELECT s.binding_id, s.node_id, s.transcript_path, s.input_ids_json, s.source_session_id, n.run_id FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id = ? ORDER BY ${S} LIMIT 1`).get(i),a=k.get(i);if(!s&&!a)throw new T(i);let t=(await h(e,i))[0];if(!t){const c=a?.path??s?.transcript_path??void 0;c&&await j(i,a?.node??s.node_id,c),t=(await h(e,i))[0]}if(!t||t.seq!==0)throw new T(i);const r=await(await y()).get(t.blob_key,{start:0,length:Math.min(t.bytes,256*1024)});if(!r)throw new Error(`missing conversation object: ${t.blob_key}`);const n=r.indexOf(10);if(n<0)throw new Error(`invalid conversation header: ${i}`);const o=JSON.parse(r.subarray(0,n).toString("utf8"));if(o.type!=="session"||o.id!==i)throw new Error(`invalid conversation header: ${i}`);return{header:o,path:s?.transcript_path??a?.path??"",binding:s}}f(L,"initial");function _e(){const i={async create(e,s,a,t){const r=await E(),n=await D("owner_read",async()=>await r.prepare("SELECT grantee, run_id FROM node_rows WHERE node_id = ?").get(e));if(!n)throw new Error(`missing conversation owner ${e}`);const o=s.id,c=V(z(n.grantee).conversations,e,`${s.timestamp.replace(/[:.]/g,"-")}_${o}.jsonl`),d=F([s,...a]),_=C(e,o,0),l=n.run_id?await A(n.run_id,e,a):!1;return K("blob_bytes",Buffer.byteLength(d)),await D("blob_put",async()=>await(await y()).put(_,d)),await D("transaction",()=>b(async w=>{if(await w.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ?").get(o))throw new Error(`conversation already exists: ${o}`);const p=N(),u=s.parentSession?await w.prepare("SELECT session_id FROM sessions WHERE transcript_path = ? LIMIT 1").get(s.parentSession):void 0;if(await w.prepare("INSERT INTO sessions (binding_id, session_id, node_id, transcript_path, source_session_id, fork_entry_id, created_at, bound_at, unbound_at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)").run(v(),o,e,c,u?u.session_id:null,p,p,p),await w.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(o,_,Buffer.byteLength(d),a.length,p),n.run_id&&!u){const g=await M(w,n.run_id,e,a,[],l);await w.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE session_id = ? AND node_id = ?").run(a.at(-1)?.id??null,JSON.stringify(g),o,e)}},{timingName:"create_tx"})),{conversation_id:o,path:c}},async append(e,s){if(!s.length)return;const a=await m(await E(),e),t=a.run_id?await A(a.run_id,a.node_id,s):!1;await b(async r=>{const n=await m(r,e,!0);if(!(await h(r,e)).length)throw new T(e);const o=[];for(const c of s){const d=JSON.stringify(c);if(await r.prepare("INSERT INTO conversation_entries (conversation_id, entry_id, body, bytes, execution_id, created) VALUES (?, ?, ?, ?, NULL, ?) ON CONFLICT (conversation_id, entry_id) DO NOTHING RETURNING entry_id").get(e,c.id,d,Buffer.byteLength(d)+1,N())&&(o.push(c),c.type==="custom"&&c.customType==="crtr-cycle")){await r.prepare("SELECT 1 FROM conversation_parts WHERE conversation_id = ? AND seq = 0 FOR UPDATE").get(e);const l=[...await h(r,e),...await $(r,e)].reduce((w,p)=>w+Number(p.bytes),0)-Buffer.byteLength(d)-1;await r.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0").run(l,e)}}if(n.run_id&&o.length){const c=await M(r,n.run_id,n.node_id,o,JSON.parse(n.input_ids_json??"[]"),t);await r.prepare("UPDATE sessions SET indexed_entry_id = ?, input_ids_json = ? WHERE binding_id = ?").run(o.at(-1).id,JSON.stringify(c),n.binding_id)}})},async readLines(e){const s=await E(),{path:a}=await L(e,s);return{path:a,lines:B(await H(s,e))}},async read(e,s){const a=await E(),{header:t,path:r}=await L(e,a),n=await H(a,e),o=n.parts.reduce((p,u)=>p+u.bytes,0)+n.tail.reduce((p,u)=>p+u.bytes,0),c=f(p=>W(p).filter(u=>u.type!=="session"),"entriesOf"),d=f(async()=>{const p=await a.prepare("SELECT cycle_offset FROM conversation_parts WHERE conversation_id = ? AND seq = 0").get(e);let u=p?.cycle_offset==null?null:Number(p.cycle_offset);if(u===null){u=0;let g=0;for await(const R of B(n)){if(R.includes('"crtr-cycle"')){const U=JSON.parse(R);U.type==="custom"&&U.customType==="crtr-cycle"&&(u=g)}g+=Buffer.byteLength(R)+1}await b(async R=>{await R.prepare("UPDATE conversation_parts SET cycle_offset = ? WHERE conversation_id = ? AND seq = 0 AND cycle_offset IS NULL").run(u,e)})}return u},"cycleOffset");if(s==="cycle"){const p=await d();return{header:t,entries:c((await O(n,p,o)).toString("utf8")),path:r}}if(s&&"beforeCycle"in s){const p=await d(),u=Math.max(0,p-s.beforeCycle),g=(await O(n,u>0?u-1:0,p)).toString("utf8").split(`
9
+ `);return u>0&&g.shift(),{header:t,entries:c(g.join(`
10
+ `)),path:r}}if(!s||o<=s.head+s.tail)return{header:t,entries:c((await O(n,0,o)).toString("utf8")),path:r};const _=(await O(n,0,Math.max(0,s.head))).toString("utf8").split(`
11
+ `);_.pop();const l=Math.max(0,o-s.tail),w=(await O(n,l>0?l-1:0,o)).toString("utf8").split(`
12
+ `);return l>0&&w.shift(),{header:t,entries:c(_.join(`
11
13
  `)),tail:c(w.join(`
12
- `)),path:s}},async header(e){const r=await l(),{header:a,path:t}=await T(e,r),s=await H(r,e);return{header:a,path:t,mtime:Date.parse(s.tail.at(-1)?.created??s.parts.at(-1).created),size:s.parts.reduce((n,o)=>n+o.bytes,0)+s.tail.reduce((n,o)=>n+o.bytes,0)}},async list(e){const a=await(await l()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${R}`).all(),t=[];for(const s of a){if(e&&s.node_id!==e)continue;const n=await i.header(s.session_id);t.push({conversation_id:s.session_id,node_id:s.node_id,...n})}return t.sort((s,n)=>n.mtime-s.mtime)},async replace(e,r,a){if(r.id!==e)throw new Error("replacement header id differs from conversation id");const t=await l(),s=await m(t,e);if(s.run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const n=`conversations/${s.node_id}/${e}/0-${S()}.jsonl`,o=U([r,...a]);await(await E()).put(n,o);const c=await y(async d=>{if((await m(d,e,!0)).run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const w=await b(d,e);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(e,n,Buffer.byteLength(o),a.length,N()),w});for(const d of c)await(await E()).delete(d.blob_key)},async fork(e,r,a,t){const s=await i.read(e);let n=s.entries;if(a!==void 0){const o=V.inMemory(s.header.cwd,void 0,[s.header,...n]);o.createBranchedSession(a),n=o.getEntries()}return(await i.create(r??(await T(e,await l())).binding?.node_id??C.get(e).node,{...s.header,id:S(),timestamp:N(),cwd:t??s.header.cwd,parentSession:s.path},n)).conversation_id},async delete(e,r){const a=await l(),t=await b(a,e);await y(async s=>{await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await s.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await s.prepare("DELETE FROM sessions WHERE session_id = ?").run(e)});for(const s of t)await(await E()).delete(s.blob_key);r&&P(r,{force:!0})},async commit(e){return await y(async r=>{const a=await m(r,e,!0),t=await W(r,e),s=await b(r,e);if(!t.length)return s.at(-1)?.seq??0;const n=(s.at(-1)?.seq??0)+1,o=A(a.node_id,e,n),c=t.map(d=>d.body+`
13
- `).join("");return await(await E()).put(o,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await r.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,o,Buffer.byteLength(c),t.length,N()),await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(e,t.at(-1).seq),n})},async importLegacy(e){const a=await(await l()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id, s.transcript_path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ${e?"AND n.run_id = ?":""} ORDER BY s.session_id, ${R}`).all(...e?[e]:[]);for(const t of a)await B(t.session_id,t.node_id,t.transcript_path)},recover(e){for(const r of e)r.transcript_path&&C.set(r.session_id,{node:r.node_id,path:r.transcript_path})}};return i}f(_e,"createRowStore");function X(i,e,r){const a=i.indexOf(10);if(a<0)throw new Error(`invalid conversation header: ${e}`);const t=JSON.parse(i.subarray(0,a).toString("utf8"));if(t.type!=="session"||t.id!==e)throw new Error(`invalid conversation header: ${e}`);const s=r(t.cwd);return s===t.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...t,cwd:s})),i.subarray(a)])}f(X,"withHeaderCwd");async function fe(i,e,r){const a=await l(),t=await m(a,i),s=(await b(a,i))[0];if(!s||s.seq!==0)return!1;const n=await(await E()).get(s.blob_key);if(!n)throw new Error(`missing conversation object: ${s.blob_key}`);const o=X(n,i,p=>p===e?r:p);if(o===null)return!1;const c=`conversations/${t.node_id}/${i}/0-${S()}.jsonl`;await(await E()).put(c,o);const d=await y(async p=>await p.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ?, cycle_offset = CASE WHEN cycle_offset > 0 THEN cycle_offset + ? - bytes ELSE cycle_offset END WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,o.length,o.length,i,s.blob_key)!==void 0);if(await(await E()).delete(d?s.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${i}`);return!0}f(fe,"relocateConversationHeader");export{_e as createRowStore,$ as readAhead,fe as relocateConversationHeader,X as withHeaderCwd};
14
+ `)),path:r}},async header(e){const s=await E(),{header:a,path:t}=await L(e,s),r=await H(s,e);return{header:a,path:t,mtime:Date.parse(r.tail.at(-1)?.created??r.parts.at(-1).created),size:r.parts.reduce((n,o)=>n+o.bytes,0)+r.tail.reduce((n,o)=>n+o.bytes,0)}},async list(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id FROM sessions s JOIN conversation_parts p ON p.conversation_id = s.session_id WHERE s.session_id IS NOT NULL ORDER BY s.session_id, ${S}`).all(),t=[];for(const r of a){if(e&&r.node_id!==e)continue;const n=await i.header(r.session_id);t.push({conversation_id:r.session_id,node_id:r.node_id,...n})}return t.sort((r,n)=>n.mtime-r.mtime)},async replace(e,s,a){if(s.id!==e)throw new Error("replacement header id differs from conversation id");const t=await E(),r=await m(t,e);if(r.run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const n=`conversations/${r.node_id}/${e}/0-${v()}.jsonl`,o=F([s,...a]);await(await y()).put(n,o);const c=await b(async d=>{if((await m(d,e,!0)).run_id)throw new Error(`run conversation ${e} is append-only; replace refused`);const l=await h(d,e);return await d.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await d.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await d.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, 0, ?, ?, ?, ?)").run(e,n,Buffer.byteLength(o),a.length,N()),l});for(const d of c)await(await y()).delete(d.blob_key)},async fork(e,s,a,t){const r=await i.read(e);let n=r.entries;if(a!==void 0){const o=G.inMemory(r.header.cwd,void 0,[r.header,...n]);o.createBranchedSession(a),n=o.getEntries()}return(await i.create(s??(await L(e,await E())).binding?.node_id??k.get(e).node,{...r.header,id:v(),timestamp:N(),cwd:t??r.header.cwd,parentSession:r.path},n)).conversation_id},async delete(e,s){const a=await E(),t=await h(a,e);await b(async r=>{await r.prepare("DELETE FROM conversation_entries WHERE conversation_id = ?").run(e),await r.prepare("DELETE FROM conversation_parts WHERE conversation_id = ?").run(e),await r.prepare("DELETE FROM sessions WHERE session_id = ?").run(e)});for(const r of t)await(await y()).delete(r.blob_key);s&&Y(s,{force:!0})},async commit(e){return await b(async s=>{const a=await m(s,e,!0),t=await $(s,e),r=await h(s,e);if(!t.length)return r.at(-1)?.seq??0;const n=(r.at(-1)?.seq??0)+1,o=C(a.node_id,e,n),c=t.map(d=>d.body+`
15
+ `).join("");return await(await y()).put(o,c),process.env.CRTR_FAULT_CONVERSATION==="commit_exit_after_put"&&process.exit(1),await s.prepare("INSERT INTO conversation_parts (conversation_id, seq, blob_key, bytes, entries, created) VALUES (?, ?, ?, ?, ?, ?)").run(e,n,o,Buffer.byteLength(c),t.length,N()),await s.prepare("DELETE FROM conversation_entries WHERE conversation_id = ? AND seq <= ?").run(e,t.at(-1).seq),n})},async importLegacy(e){const a=await(await E()).prepare(`SELECT DISTINCT ON (s.session_id) s.session_id, s.node_id, s.transcript_path FROM sessions s JOIN nodes n ON n.node_id = s.node_id WHERE s.session_id IS NOT NULL AND s.transcript_path IS NOT NULL ${e?"AND n.run_id = ?":""} ORDER BY s.session_id, ${S}`).all(...e?[e]:[]);for(const t of a)await j(t.session_id,t.node_id,t.transcript_path)},recover(e){for(const s of e)s.transcript_path&&k.set(s.session_id,{node:s.node_id,path:s.transcript_path})}};return i}f(_e,"createRowStore");function Z(i,e,s){const a=i.indexOf(10);if(a<0)throw new Error(`invalid conversation header: ${e}`);const t=JSON.parse(i.subarray(0,a).toString("utf8"));if(t.type!=="session"||t.id!==e)throw new Error(`invalid conversation header: ${e}`);const r=s(t.cwd);return r===t.cwd?null:Buffer.concat([Buffer.from(JSON.stringify({...t,cwd:r})),i.subarray(a)])}f(Z,"withHeaderCwd");async function ue(i,e,s){const a=await E(),t=await m(a,i),r=(await h(a,i))[0];if(!r||r.seq!==0)return!1;const n=await(await y()).get(r.blob_key);if(!n)throw new Error(`missing conversation object: ${r.blob_key}`);const o=Z(n,i,_=>_===e?s:_);if(o===null)return!1;const c=`conversations/${t.node_id}/${i}/0-${v()}.jsonl`;await(await y()).put(c,o);const d=await b(async _=>await _.prepare("UPDATE conversation_parts SET blob_key = ?, bytes = ?, cycle_offset = CASE WHEN cycle_offset > 0 THEN cycle_offset + ? - bytes ELSE cycle_offset END WHERE conversation_id = ? AND seq = 0 AND blob_key = ? RETURNING seq").get(c,o.length,o.length,i,r.blob_key)!==void 0);if(await(await y()).delete(d?r.blob_key:c).catch(()=>{}),!d)throw new Error(`conversation header changed during relocation: ${i}`);return!0}f(ue,"relocateConversationHeader");export{_e as createRowStore,q as readAhead,ue as relocateConversationHeader,Z as withHeaderCwd};
@@ -1,8 +1,8 @@
1
- var S=Object.defineProperty;var p=(e,a)=>S(e,"name",{value:a,configurable:!0});import{randomUUID as I}from"node:crypto";import{documentFields as _}from"../../migrations/004-canvas-documents/fields.js";import{get as D,put as L}from"./bodies.js";import{applyDocumentFields as R,deleteDocument as v,documentRecord as g,heads as h,importDocument as A,linksIn as T,moveDocument as x}from"./documents.js";import{deleteShippedReader as j,writeShippedReader as k}from"../permissions/facts.js";import{setLinks as U}from"./edges.js";import{publish as F}from"./events.js";import{getById as l,setObjectKind as J}from"./objects.js";import{rulesOf as C}from"./rules.js";async function H(e,a,i){const d=/^(?:app:)?([^/:]+)\/(.+)$/.exec(i),s=[{app:null,doc:i}];d!==null&&s.push({app:d[1],doc:d[2]});for(const{app:t,doc:o}of s){const r=await e.prepare(`SELECT o.id FROM objects o JOIN documents d ON d.object = o.id AND d.source_path IS NOT NULL JOIN objects a ON a.id = o.owner AND a.type = 'app'
1
+ var S=Object.defineProperty;var p=(e,a)=>S(e,"name",{value:a,configurable:!0});import{randomUUID as _}from"node:crypto";import{documentFields as I}from"../../migrations/004-canvas-documents/fields.js";import{findMany as D,put as L}from"./bodies.js";import{applyDocumentFields as R,deleteDocument as v,documentRecord as g,heads as h,importDocument as A,linksIn as T,moveDocument as x}from"./documents.js";import{deleteShippedReader as j,writeShippedReader as k}from"../permissions/facts.js";import{setLinks as U}from"./edges.js";import{publish as F}from"./events.js";import{getById as l,setObjectKind as J}from"./objects.js";import{rulesOf as M}from"./rules.js";async function C(e,a,i){const d=/^(?:app:)?([^/:]+)\/(.+)$/.exec(i),s=[{app:null,doc:i}];d!==null&&s.push({app:d[1],doc:d[2]});for(const{app:t,doc:o}of s){const r=await e.prepare(`SELECT o.id FROM objects o JOIN documents d ON d.object = o.id AND d.source_path IS NOT NULL JOIN objects a ON a.id = o.owner AND a.type = 'app'
2
2
  WHERE o.type = 'document' AND o.deleted_at IS NULL AND o.home_machine IS NULL AND o.name = ? AND (?::text IS NULL OR a.name = ?)
3
- ORDER BY (o.owner = ?) DESC, a.name = 'crtr', a.name LIMIT 1`).get(o,t,t,a.id);if(r!==void 0)return await l(e,r.id)??void 0}}p(H,"shippedNamed");async function M(e,a,i,d){if(i.deleted_at!==null)return;const s=[];for(const r of T(d)){const n=await H(e,a,r);n!==void 0&&n.id!==i.id&&s.push({written_as:r,dst:n})}const t=p(r=>JSON.stringify(r.map(n=>[n.dst,n.written_as]).sort()),"key"),o=await e.prepare("SELECT dst, written_as FROM edges WHERE type = 'links-to' AND src = ?").all(i.id);t(o)!==t(s.map(r=>({dst:r.dst.id,written_as:r.written_as})))&&await U(e,i,s)}p(M,"deriveLinks");async function Q(e){const a=await e.prepare(`SELECT o.id, o.owner FROM objects o JOIN documents d ON d.object = o.id
4
- WHERE o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL ORDER BY o.id`).all();for(const{id:i,owner:d}of a){const s=await l(e,i),[t]=await h(e,s);t!==void 0&&await M(e,await l(e,d),s,await D(e,t.body_hash))}}p(Q,"relinkAllShipped");async function V(e,a,i,d,s){const t=_(i.frontmatter,i.body,{missingPrivacy:"public"}),o={preview:t.preview.trim()===""?i.name:t.preview,summary:t.summary,whyItExists:t.whyItExists,unlisted:t.unlisted,rules:t.rules,lintIgnore:Array.isArray(t.lintIgnore)?t.lintIgnore.filter(c=>typeof c=="string"):null,extensions:t.extensions!==null&&typeof t.extensions=="object"&&!Array.isArray(t.extensions)?t.extensions:null},r=await L(e,i.body);let n=await e.prepare(`SELECT o.* FROM objects o JOIN documents d ON d.object = o.id
3
+ ORDER BY (o.owner = ?) DESC, a.name = 'crtr', a.name LIMIT 1`).get(o,t,t,a.id);if(r!==void 0)return await l(e,r.id)??void 0}}p(C,"shippedNamed");async function H(e,a,i,d){if(i.deleted_at!==null)return;const s=[];for(const r of T(d)){const n=await C(e,a,r);n!==void 0&&n.id!==i.id&&s.push({written_as:r,dst:n})}const t=p(r=>JSON.stringify(r.map(n=>[n.dst,n.written_as]).sort()),"key"),o=await e.prepare("SELECT dst, written_as FROM edges WHERE type = 'links-to' AND src = ?").all(i.id);t(o)!==t(s.map(r=>({dst:r.dst.id,written_as:r.written_as})))&&await U(e,i,s)}p(H,"deriveLinks");async function Q(e){const a=await e.prepare(`SELECT o.id, o.owner FROM objects o JOIN documents d ON d.object = o.id
4
+ WHERE o.type = 'document' AND o.deleted_at IS NULL AND d.source_path IS NOT NULL ORDER BY o.id`).all();for(const{id:i,owner:d}of a){const s=await l(e,i),[t]=await h(e,s);if(t===void 0)continue;const o=(await D(e,[t.body_hash])).get(t.body_hash);o!==void 0&&await H(e,await l(e,d),s,o)}}p(Q,"relinkAllShipped");async function V(e,a,i,d,s){const t=I(i.frontmatter,i.body,{missingPrivacy:"public"}),o={preview:t.preview.trim()===""?i.name:t.preview,summary:t.summary,whyItExists:t.whyItExists,unlisted:t.unlisted,rules:t.rules,lintIgnore:Array.isArray(t.lintIgnore)?t.lintIgnore.filter(c=>typeof c=="string"):null,extensions:t.extensions!==null&&typeof t.extensions=="object"&&!Array.isArray(t.extensions)?t.extensions:null},r=await L(e,i.body);let n=await e.prepare(`SELECT o.* FROM objects o JOIN documents d ON d.object = o.id
5
5
  WHERE o.type = 'document' AND o.owner = ? AND o.deleted_at IS NULL AND o.name = ? AND d.source_path IS NOT NULL`).get(a.id,i.name);if(n?await e.prepare("UPDATE documents SET source_path = ? WHERE object = ? AND source_path IS DISTINCT FROM ?").run(i.path,n.id,i.path):n=await e.prepare(`SELECT o.* FROM objects o JOIN documents d ON d.object = o.id
6
- WHERE o.type = 'document' AND o.owner = ? AND o.deleted_at IS NULL AND d.source_path = ?`).get(a.id,i.path),!n){const c=await A(e,{owner:a,name:i.name,kind:t.kind,privacy:"public",...o,revisions:[{body_hash:r,author:a,rationale:null,created_at:new Date().toISOString()}]});return await e.prepare("UPDATE documents SET source_path = ? WHERE object = ?").run(i.path,c.id),await k(e,c.id),d.created+=1,c.id}const f=n.name!==i.name||n.kind!==t.kind;n.name!==i.name&&(n=await x(e,null,n,{name:i.name})),n.kind!==t.kind&&(await J(e,n,t.kind),n=await l(e,n.id));const m=await g(e,n),[u]=await h(e,n),w=u?.body_hash!==r,O=n.preview!==o.preview||m.summary!==o.summary||m.why_it_exists!==o.whyItExists||m.unlisted!==o.unlisted||JSON.stringify(m.lint_ignore)!==JSON.stringify(o.lintIgnore)||JSON.stringify(m.extensions)!==JSON.stringify(o.extensions)||JSON.stringify((await C(e,n)).map(y))!==JSON.stringify(o.rules.map(y));if(!w&&!O&&!f)return n.id;const N=await R(e,n,o);if(w&&u){const c=I(),E=u.number+1;await e.prepare(`INSERT INTO revisions (rev_id, document, number, body_hash, author, rationale, verbatim, created_at)
6
+ WHERE o.type = 'document' AND o.owner = ? AND o.deleted_at IS NULL AND d.source_path = ?`).get(a.id,i.path),!n){const c=await A(e,{owner:a,name:i.name,kind:t.kind,privacy:"public",...o,revisions:[{body_hash:r,author:a,rationale:null,created_at:new Date().toISOString()}]});return await e.prepare("UPDATE documents SET source_path = ? WHERE object = ?").run(i.path,c.id),await k(e,c.id),d.created+=1,c.id}const f=n.name!==i.name||n.kind!==t.kind;n.name!==i.name&&(n=await x(e,null,n,{name:i.name})),n.kind!==t.kind&&(await J(e,n,t.kind),n=await l(e,n.id));const m=await g(e,n),[u]=await h(e,n),w=u?.body_hash!==r,O=n.preview!==o.preview||m.summary!==o.summary||m.why_it_exists!==o.whyItExists||m.unlisted!==o.unlisted||JSON.stringify(m.lint_ignore)!==JSON.stringify(o.lintIgnore)||JSON.stringify(m.extensions)!==JSON.stringify(o.extensions)||JSON.stringify((await M(e,n)).map(y))!==JSON.stringify(o.rules.map(y));if(!w&&!O&&!f)return n.id;const N=await R(e,n,o);if(w&&u){const c=_(),E=u.number+1;await e.prepare(`INSERT INTO revisions (rev_id, document, number, body_hash, author, rationale, verbatim, created_at)
7
7
  SELECT ?, document, ?, ?, author, rationale, verbatim, ? FROM revisions WHERE rev_id = ?`).run(c,E,r,new Date().toISOString(),u.rev_id),await e.prepare("INSERT INTO revision_parents (child, parent) SELECT ?, parent FROM revision_parents WHERE child = ?").run(c,u.rev_id),await e.prepare("DELETE FROM revisions WHERE rev_id = ?").run(u.rev_id),await e.prepare("UPDATE documents SET heads_key = ?, revision = ? WHERE object = ?").run(c,E,N.id),await F(e,{event:"edited",object:N,actor:a,pointer:c,attrs:{revision:E,from_revision:u.number,rationale:"package file changed"}},s)}return d.updated+=1,N.id}p(V,"convergeFile");function y(e){return[e.on,e.deliver,e.match??null,e.matchFrontmatter??null,e.if??null]}p(y,"ruleKey");async function X(e,a,i,d,s){const t=await e.prepare(`SELECT o.* FROM objects o JOIN documents d ON d.object = o.id
8
- WHERE o.type = 'document' AND o.owner = ? AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).all(a.id);for(const o of t)i.has(o.id)||(await v(e,null,o,s),await j(e,o.id),d.deleted+=1)}p(X,"deleteMissing");export{V as convergeFile,X as deleteMissing,M as deriveLinks,Q as relinkAllShipped};
8
+ WHERE o.type = 'document' AND o.owner = ? AND o.deleted_at IS NULL AND d.source_path IS NOT NULL`).all(a.id);for(const o of t)i.has(o.id)||(await v(e,null,o,s),await j(e,o.id),d.deleted+=1)}p(X,"deleteMissing");export{V as convergeFile,X as deleteMissing,H as deriveLinks,Q as relinkAllShipped};
@@ -1,3 +1,4 @@
1
- var j=Object.defineProperty;var d=(e,i)=>j(e,"name",{value:i,configurable:!0});import{createHash as g}from"node:crypto";import{readdirSync as T,readFileSync as b,statSync as K}from"node:fs";import{join as N,relative as f,sep as m}from"node:path";import{compareReleaseVersions as R}from"../../api/runtime-version.js";import{upsertKind as F}from"./custom.js";import{crtrVersion as D}from"../../shared/crtr-version.js";import{emitEvent as v}from"../events/emit.js";import{builtinMemoryRoot as A}from"../scope.js";import{deleteMissing as E,convergeFile as $,relinkAllShipped as I}from"./package-docs.js";import{packageFiles as L}from"./package-files.js";import{ensureOwner as y}from"./objects.js";import{checkoutsForCwd as k}from"./repo-sync/repos.js";function P(e){if(!K(e,{throwIfNoEntry:!1})?.isDirectory())throw new Error(`package folder is missing or not a directory: ${e}`);const i=[],t=[e];for(;t.length>0;){const r=t.pop();for(const s of T(r,{withFileTypes:!0})){const o=N(r,s.name);s.isDirectory()?s.name.startsWith(".")||t.push(o):s.isFile()&&s.name.endsWith(".md")&&s.name!=="SKILL.md"&&i.push([f(e,o).split(m).join("/"),b(o)])}}return i.sort((r,s)=>r[0]<s[0]?-1:1)}d(P,"strictPackageBytes");function H(e,i){const t=P(e),{files:r,invalid:s}=L(e),o=r.map(n=>({...n,path:`${i.app}/${f(e,n.path).split(m).join("/")}`})),a=g("sha256");for(const[n,c]of t)a.update(n).update("\0").update(c).update("\0");const p=s.map(n=>({...n,path:`${i.app}/${f(e,n.path).split(m).join("/")}`}));return S({revision:null,source:null,launchKinds:null,objectKinds:null,...i},o,p,a)}d(H,"readPackageSnapshot");function l(e){if(Array.isArray(e))return`[${e.map(l).join(",")}]`;if(e!==null&&typeof e=="object"){const i=e;return`{${Object.keys(i).sort().filter(t=>i[t]!==void 0).map(t=>`${JSON.stringify(t)}:${l(i[t])}`).join(",")}}`}return JSON.stringify(e)??"null"}d(l,"canonicalJson");function S(e,i,t,r){return r.update(l({launchKinds:e.launchKinds,objectKinds:e.objectKinds,source:e.source})),{...e,digest:r.digest("hex"),files:i,invalid:t}}d(S,"snapshotOf");function ee(){return H(A(),{app:"crtr",origin:"builtin",version:D()})}d(ee,"readBuiltinSnapshot");function W(e,i){return e.revision!==null?i.revision!==null&&e.revision<Number(i.revision):e.origin==="builtin"?R(e.version,i.version)<0:!1}d(W,"olderThanPublished");async function ne(e,i,t){const{app:r,origin:s}=i,o=await y(e,"app","app",`app:${r}`,r),a=new Date().toISOString();await e.prepare(`INSERT INTO package_publications (app, origin, version, digest, published_at, published_by)
2
- VALUES (?, ?, '', '', ?, ?) ON CONFLICT (app) DO NOTHING`).run(o.id,s,a,t);const p=await e.prepare("SELECT version, digest, revision, withdrawn_at FROM package_publications WHERE app = ? FOR UPDATE").get(o.id),n="capture"in i?i.capture():i,c={created:0,updated:0,deleted:0,conflicts:[],invalid:[...n.invalid],quarantined:[],superseded:!1,kinds:{applied:[],refused:[]}};if(W(n,p))return c.superseded=!0,v({level:"warn",event:"daemon.packages.superseded",fields:{app:n.app,snapshot_version:n.version,published_version:p.version,snapshot_revision:n.revision??"none",published_revision:p.revision===null?"none":Number(p.revision)}}),c;if(p.digest===n.digest&&p.withdrawn_at===null){if(p.version===n.version&&String(p.revision??"")===String(n.revision??""))return c}else{const h=d(async(u,O)=>await k(e,u,O),"reposFn"),w=new Set;for(const u of n.files)w.add(await $(e,o,u,c,h));n.invalid.length===0&&await E(e,o,w,c,h),c.kinds=await _(e,o,n.objectKinds),c.created+c.updated+c.deleted>0&&await I(e)}return await e.prepare(`UPDATE package_publications SET origin = ?, version = ?, revision = ?, source = ?, launch_kinds_json = ?, digest = ?, published_at = ?, published_by = ?, withdrawn_at = NULL
3
- WHERE app = ?`).run(n.origin,n.version,n.revision,n.source,n.launchKinds===null?null:l(n.launchKinds),n.digest,a,t,o.id),c}d(ne,"publish");function ie(e){return S({revision:null,source:null,launchKinds:null,objectKinds:null,...e},[],[],g("sha256"))}d(ie,"emptyPackageSnapshot");async function _(e,i,t){const r={applied:[],refused:[]},s=new Set;for(const[a,p]of Object.entries(t??{}))try{const n=await F(e,{name:a,owner:i,description:p.description,events:p.events,read:p.read===void 0?null:{command:p.read.command},source:"manifest"});n.outcome!=="skipped"&&(s.add(a),r.applied.push({kind:a,outcome:n.outcome}))}catch(n){if(n.code!=="kind_owned")throw n;r.refused.push({kind:a,message:n.message}),v({level:"warn",event:"daemon.packages.kind_owned",fields:{app:i.id,kind:a}})}const o=await e.prepare("SELECT name FROM object_kinds WHERE owner = ? AND source = 'manifest' AND declared = 1").all(i.id);for(const{name:a}of o)s.has(a)||await e.prepare("UPDATE object_kinds SET declared = 0 WHERE name = ?").run(a);return r}d(_,"convergeKinds");async function te(e,i){const t={created:0,updated:0,deleted:0,conflicts:[],invalid:[],quarantined:[],superseded:!1,kinds:{applied:[],refused:[]}},r=await y(e,"app","app",`app:${i}`,i),s=await e.prepare("SELECT withdrawn_at FROM package_publications WHERE app = ? FOR UPDATE").get(r.id);return s===void 0||s.withdrawn_at!==null||(await E(e,r,new Set,t,async(o,a)=>await k(e,o,a)),await _(e,r,null),await e.prepare("UPDATE package_publications SET withdrawn_at = ?, digest = '' WHERE app = ?").run(new Date().toISOString(),r.id)),t}d(te,"withdraw");export{l as canonicalJson,ie as emptyPackageSnapshot,ne as publish,ee as readBuiltinSnapshot,H as readPackageSnapshot,te as withdraw};
1
+ var O=Object.defineProperty;var d=(e,i)=>O(e,"name",{value:i,configurable:!0});import{createHash as g}from"node:crypto";import{readdirSync as T,readFileSync as b,statSync as j}from"node:fs";import{join as R,relative as f,sep as m}from"node:path";import{compareReleaseVersions as D}from"../../api/runtime-version.js";import{upsertKind as I}from"./custom.js";import{crtrVersion as L}from"../../shared/crtr-version.js";import{emitEvent as v}from"../events/emit.js";import{builtinMemoryRoot as A}from"../scope.js";import{deleteMissing as E,convergeFile as F,relinkAllShipped as K}from"./package-docs.js";import{packageFiles as $}from"./package-files.js";import{ensureOwner as S}from"./objects.js";import{checkoutsForCwd as y}from"./repo-sync/repos.js";function H(e){if(!j(e,{throwIfNoEntry:!1})?.isDirectory())throw new Error(`package folder is missing or not a directory: ${e}`);const i=[],t=[e];for(;t.length>0;){const r=t.pop();for(const o of T(r,{withFileTypes:!0})){const s=R(r,o.name);o.isDirectory()?o.name.startsWith(".")||t.push(s):o.isFile()&&o.name.endsWith(".md")&&o.name!=="SKILL.md"&&i.push([f(e,s).split(m).join("/"),b(s)])}}return i.sort((r,o)=>r[0]<o[0]?-1:1)}d(H,"strictPackageBytes");function W(e,i){const t=H(e),{files:r,invalid:o}=$(e),s=r.map(n=>({...n,path:`${i.app}/${f(e,n.path).split(m).join("/")}`})),a=g("sha256");for(const[n,c]of t)a.update(n).update("\0").update(c).update("\0");const p=o.map(n=>({...n,path:`${i.app}/${f(e,n.path).split(m).join("/")}`}));return _({revision:null,source:null,launchKinds:null,objectKinds:null,...i},s,p,a)}d(W,"readPackageSnapshot");function u(e){if(Array.isArray(e))return`[${e.map(u).join(",")}]`;if(e!==null&&typeof e=="object"){const i=e;return`{${Object.keys(i).sort().filter(t=>i[t]!==void 0).map(t=>`${JSON.stringify(t)}:${u(i[t])}`).join(",")}}`}return JSON.stringify(e)??"null"}d(u,"canonicalJson");function _(e,i,t,r){return r.update(u({launchKinds:e.launchKinds,objectKinds:e.objectKinds,source:e.source})),{...e,digest:r.digest("hex"),files:i,invalid:t}}d(_,"snapshotOf");function ne(){return W(A(),{app:"crtr",origin:"builtin",version:L()})}d(ne,"readBuiltinSnapshot");function P(e,i){return e.revision!==null?i.revision!==null&&e.revision<Number(i.revision):e.origin==="builtin"?D(e.version,i.version)<0:!1}d(P,"olderThanPublished");async function ie(e,i,t){const{app:r,origin:o}=i,s=await S(e,"app","app",`app:${r}`,r),a=new Date().toISOString();await e.prepare(`INSERT INTO package_publications (app, origin, version, digest, published_at, published_by)
2
+ VALUES (?, ?, '', '', ?, ?) ON CONFLICT (app) DO NOTHING`).run(s.id,o,a,t);const p=await e.prepare("SELECT version, digest, revision, withdrawn_at FROM package_publications WHERE app = ? FOR UPDATE").get(s.id),n="capture"in i?i.capture():i,c={created:0,updated:0,deleted:0,conflicts:[],invalid:[...n.invalid],quarantined:[],superseded:!1,kinds:{applied:[],refused:[]}};if(P(n,p))return c.superseded=!0,v({level:"warn",event:"daemon.packages.superseded",fields:{app:n.app,snapshot_version:n.version,published_version:p.version,snapshot_revision:n.revision??"none",published_revision:p.revision===null?"none":Number(p.revision)}}),c;if(p.digest===n.digest&&p.withdrawn_at===null&&!await U(e,s.id)){if(p.version===n.version&&String(p.revision??"")===String(n.revision??""))return c}else{const h=d(async(l,N)=>await y(e,l,N),"reposFn"),w=new Set;for(const l of n.files)w.add(await F(e,s,l,c,h));n.invalid.length===0&&await E(e,s,w,c,h),c.kinds=await k(e,s,n.objectKinds),c.created+c.updated+c.deleted>0&&await K(e)}return await e.prepare(`UPDATE package_publications SET origin = ?, version = ?, revision = ?, source = ?, launch_kinds_json = ?, digest = ?, published_at = ?, published_by = ?, withdrawn_at = NULL
3
+ WHERE app = ?`).run(n.origin,n.version,n.revision,n.source,n.launchKinds===null?null:u(n.launchKinds),n.digest,a,t,s.id),c}d(ie,"publish");async function U(e,i){return await e.prepare(`SELECT 1 FROM objects o JOIN documents d ON d.object = o.id AND d.source_path IS NOT NULL JOIN revisions r ON r.document = o.id
4
+ WHERE o.type = 'document' AND o.owner = ? AND o.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM bodies b WHERE b.hash = r.body_hash) LIMIT 1`).get(i)!==void 0}d(U,"missesBody");function te(e){return _({revision:null,source:null,launchKinds:null,objectKinds:null,...e},[],[],g("sha256"))}d(te,"emptyPackageSnapshot");async function k(e,i,t){const r={applied:[],refused:[]},o=new Set;for(const[a,p]of Object.entries(t??{}))try{const n=await I(e,{name:a,owner:i,description:p.description,events:p.events,read:p.read===void 0?null:{command:p.read.command},source:"manifest"});n.outcome!=="skipped"&&(o.add(a),r.applied.push({kind:a,outcome:n.outcome}))}catch(n){if(n.code!=="kind_owned")throw n;r.refused.push({kind:a,message:n.message}),v({level:"warn",event:"daemon.packages.kind_owned",fields:{app:i.id,kind:a}})}const s=await e.prepare("SELECT name FROM object_kinds WHERE owner = ? AND source = 'manifest' AND declared = 1").all(i.id);for(const{name:a}of s)o.has(a)||await e.prepare("UPDATE object_kinds SET declared = 0 WHERE name = ?").run(a);return r}d(k,"convergeKinds");async function re(e,i){const t={created:0,updated:0,deleted:0,conflicts:[],invalid:[],quarantined:[],superseded:!1,kinds:{applied:[],refused:[]}},r=await S(e,"app","app",`app:${i}`,i),o=await e.prepare("SELECT withdrawn_at FROM package_publications WHERE app = ? FOR UPDATE").get(r.id);return o===void 0||o.withdrawn_at!==null||(await E(e,r,new Set,t,async(s,a)=>await y(e,s,a)),await k(e,r,null),await e.prepare("UPDATE package_publications SET withdrawn_at = ?, digest = '' WHERE app = ?").run(new Date().toISOString(),r.id)),t}d(re,"withdraw");export{u as canonicalJson,te as emptyPackageSnapshot,ie as publish,ne as readBuiltinSnapshot,W as readPackageSnapshot,re as withdraw};
@@ -1,3 +1,3 @@
1
- var T=Object.defineProperty;var s=(o,e)=>T(o,"name",{value:e,configurable:!0});import{coveredByAny as _,isSandboxedNode as $}from"../../shared/env.js";import{projectPaths as H}from"../../api/dto/profiles.js";import{existsSync as y}from"node:fs";import{CrtrError as W}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as F}from"@north-light/identity";import{activeGrant as b,grantFor as C,runtimeScope as D}from"../grants/mirror.js";import{withCanvasWrite as B}from"../canvas/db.js";import{ApiError as J}from"../../api/errors.js";import{pluginAppToken as P}from"../secrets.js";import{loadExactProfileManifest as k}from"../profiles/manifest.js";import{ensureOwner as x,getById as G,nodeObject as q,ownerForGrantee as U,profileHandle as Y}from"./objects.js";import{personId as z,personIdAsync as K}from"../canvas/person.js";import{OBJECT_TYPE as Q}from"../permissions/builtin.js";import{warmCheckoutDirs as A}from"../checkout-identities.js";import{fillProfileProjectRepo as V}from"../profiles/manifest.js";import{emitEvent as X}from"../events/emit.js";import{isCloudRole as R}from"../canvas/person-state.js";import{loadReadAccess as Z,readableAmong as I,prefetchRepoReads as ee,reposForCwd as oe,warmCheckoutIdentities as O}from"./repo-sync/repos.js";async function L(o,e,t,r,n,a){const l=t===null?[]:n.projects(t),p=l.length===0?void 0:a??await K(),c=p===void 0?void 0:await Z(o,p);c!==void 0&&p!==void 0&&await ee(o,p,[e,...l.flatMap(i=>i.path!==void 0&&(R()||y(i.path))?[i.path]:[])],c);const f=l.flatMap(i=>i.repo===void 0?[]:[i.repo]),w=p===void 0?new Set:await I(o,p,f,c),g=await r(e,a,c),d=new Set(g.map(i=>i.repo.id)),m=[],E=[];for(const i of l){if(i.repo!==void 0&&!d.has(i.repo)){const u=await n.object(i.repo);u!==null&&u.type==="repo"&&u.deleted_at===null&&w.has(u.id)&&(d.add(u.id),m.push(u))}if(i.path===void 0||!R()&&!y(i.path))continue;let h;try{h=await r(i.path,a,c)}catch(u){if(u instanceof W&&u.code==="git-lookup-failed")continue;throw u}for(const u of h)d.has(u.repo.id)||(d.add(u.repo.id),m.push(u.repo),E.push(u))}return{repos:g.map(i=>i.repo),checkouts:g,projectRepos:m,projectCheckouts:E}}s(L,"viewRepos");async function Fe(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?H(j(o).projects(t.profile_id)):[];if(R()){await te(t.profile_id,[t.cwd,...r]);return}await O(t.cwd);for(const n of r)y(n)&&await O(n)}s(Fe,"warmNodeRepos");async function te(o,e){if(await A(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await B(async n=>await oe(n,t.path)))[0];r!==void 0&&await V(o,t.path,r.id)}catch(r){X({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(te,"warmCloudNodeCheckouts");async function be(o,e,t){if(!R()){for(const n of t)await O(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await A(r?.profile_id,t)}s(be,"warmNodeDirs");async function Ce(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await N(o)};if(e.class==="app")return{class:"app",app:await S(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await N(o)};const p=await C(e.actor.app,e.sub);if(!p)throw new J(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const c=e.actor.node_scopes;return{class:"app",app:await S(o,e.actor.app),place:e.actor.place,launched:c,scopes:c===null?p.resolved:c.filter(f=>_(p.resolved,f))}}if(e.class==="cron"){const p=e.grant?(await b(e.grant))?.resolved??[]:[],c=e.scopes;return{class:"app",app:await S(o,e.app),scopes:c===null?p:c.filter(f=>_(p,f)),launched:c,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=j(o),n=await q(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),l=a.app===null?null:await r.object(a.app);if(!l)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:l,scopes:await M(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await L(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,l)}}s(Ce,"readerFor");async function ne(o,e,t,r=j(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),l=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
2
- sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!l)throw new Error(`no node ${e}`);const{grantee:p,sub:c,grant_id:f,scopes_json:w,cwd:g,profile_id:d,app:m}=l,E=m===null?null:await r.object(m);if(!E)throw new Error(`node ${e} has no app`);const i=w===null?null:JSON.parse(w);return{class:"node",node:a,app:E,scopes:await M(p,c??"",f,i,r,n),launched:i,cwd:g,...await L(o,g,d,t,r,c||void 0),profile:d===null?null:await r.profile(d,E)}}s(ne,"readerForNode");class re extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function xe(o,e,t=async()=>[],r=j(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await ae(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ne(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const p=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!p)throw new re;const c=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",f=D(),w=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${f.sql}`).all(c,...f.args),g=s(h=>JSON.parse(h.resolved_scopes_json).filter(u=>u.mode==="always").map(u=>F(u.scope)),"always"),d=w.length>1&&a.type==="app"?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(Q,e.id)).map(h=>h.subject_id)):null,m=d===null?void 0:w.find(h=>d.has(h.sub.replace(/^user:/,"")))?.sub,E=m===void 0?null:await r.grantFor(c,m),i=a.type==="person"?null:w.length===0?r.pluginScopes(c):w.length===1?g(w[0]):E?.resolved??null;return{class:"object",object:e,node:e,owner:a,app:p,scopes:i,...E===null?{}:{sub:E.sub},repos:a.type==="repo"?[a]:[]}}s(xe,"readerForObject");async function Ae(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>F(a.scope))}s(Ae,"appScopesNow");async function ae(o,e,t,r){const n=await N(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await S(o,t.app),l=t?.app==null?null:await r.grantFor(t.app,t.sub),p=t===null||l===null?null:t.node_scopes===null?l.resolved:t.node_scopes.filter(f=>_(l.resolved,f)),c=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:c,app:c,scopes:p,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(ae,"readerForStub");function j(o){return{grantById:b,grantFor:C,pluginScopes:s(e=>P(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await G(o,e),"object"),profile:s(async(e,t)=>await se(o,e,t),"profile"),projects:s(e=>$()?[]:v(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function Le(o){const e=j(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(Le,"publishLookups");async function M(o,e,t,r,n,a=!1){const l=t?await n.grantById(t):await n.grantFor(o,e),p=l&&l.grantee===o?l.resolved:null;if(p===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?p:r.filter(c=>_(p,c))}s(M,"nodeScopes");async function N(o){return await U(o,z())}s(N,"personObject");async function S(o,e){return await x(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function se(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
- WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await x(o,"profile","profile",e,Y(e,k(e).manifest.name),t)}s(se,"profileObject");export{re as NoOwningAppError,Ae as appScopesNow,j as liveLookups,se as profileObject,Le as publishLookups,Ce as readerFor,ne as readerForNode,xe as readerForObject,L as viewRepos,te as warmCloudNodeCheckouts,be as warmNodeDirs,Fe as warmNodeRepos};
1
+ var W=Object.defineProperty;var s=(o,e)=>W(o,"name",{value:e,configurable:!0});import{coveredByAny as _,isSandboxedNode as $}from"../../shared/env.js";import{projectPaths as D}from"../../api/dto/profiles.js";import{existsSync as N}from"node:fs";import{CrtrError as B}from"../errors.js";import{getCachedProfile as v}from"../scoped-state/person-store.js";import{parseScope as C}from"@north-light/identity";import{activeGrant as x,grantFor as A,runtimeScope as J}from"../grants/mirror.js";import{withCanvasWrite as P}from"../canvas/db.js";import{ApiError as k}from"../../api/errors.js";import{pluginAppToken as G}from"../secrets.js";import{loadExactProfileManifest as q}from"../profiles/manifest.js";import{ensureOwner as L,getById as U,nodeObject as Y,ownerForGrantee as z,profileHandle as K}from"./objects.js";import{personId as Q,personIdAsync as V}from"../canvas/person.js";import{OBJECT_TYPE as X}from"../permissions/builtin.js";import{warmCheckoutDirs as M}from"../checkout-identities.js";import{fillProfileProjectRepo as Z}from"../profiles/manifest.js";import{emitEvent as I}from"../events/emit.js";import{isCloudRole as R}from"../canvas/person-state.js";import{loadReadAccess as ee,readableAmong as oe,prefetchRepoReads as te,reposForCwd as ne,warmCheckoutIdentities as b}from"./repo-sync/repos.js";async function T(o,e,t,r,n,a){const l=t===null?[]:n.projects(t),p=l.length===0?void 0:a??await V(),c=p===void 0?void 0:await ee(o,p);c!==void 0&&p!==void 0&&await te(o,p,[e,...l.flatMap(i=>i.path!==void 0&&(R()||N(i.path))?[i.path]:[])],c);const d=l.flatMap(i=>i.repo===void 0?[]:[i.repo]),f=p===void 0?new Set:await oe(o,p,d,c),g=await r(e,a,c),w=new Set(g.map(i=>i.repo.id)),E=[],m=[];for(const i of l){if(i.repo!==void 0&&!w.has(i.repo)){const u=await n.object(i.repo);u!==null&&u.type==="repo"&&u.deleted_at===null&&f.has(u.id)&&(w.add(u.id),E.push(u))}if(i.path===void 0||!R()&&!N(i.path))continue;let y;try{y=await r(i.path,a,c)}catch(u){if(u instanceof B&&u.code==="git-lookup-failed")continue;throw u}for(const u of y)w.has(u.repo.id)||(w.add(u.repo.id),E.push(u.repo),m.push(u))}return{repos:g.map(i=>i.repo),checkouts:g,projectRepos:E,projectCheckouts:m}}s(T,"viewRepos");async function Ce(o,e){const t=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(t===void 0)return;const r=t.profile_id?D(j(o).projects(t.profile_id)):[];if(R()){await re(t.profile_id,[t.cwd,...r]);return}await b(t.cwd);for(const n of r)N(n)&&await b(n)}s(Ce,"warmNodeRepos");async function re(o,e){if(await M(o,e),o!==null){for(const t of v(o)?.manifest.projects??[])if(!(t.path===void 0||t.repo!==void 0))try{const r=(await P(async n=>await ne(n,t.path)))[0];r!==void 0&&await Z(o,t.path,r.id)}catch(r){I({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:t.path}})}}}s(re,"warmCloudNodeCheckouts");async function xe(o,e,t){if(!R()){for(const n of t)await b(n);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await M(r?.profile_id,t)}s(xe,"warmNodeDirs");async function Ae(o,e,t){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await F(o)};if(e.class==="app")return{class:"app",app:await S(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await F(o)};const p=await A(e.actor.app,e.sub);if(!p)throw new k(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const c=e.actor.node_scopes;return{class:"app",app:await S(o,e.actor.app),place:e.actor.place,launched:c,scopes:c===null?p.resolved:c.filter(d=>_(p.resolved,d))}}if(e.class==="cron"){const p=e.grant?(await x(e.grant))?.resolved??[]:[],c=e.scopes;return{class:"app",app:await S(o,e.app),scopes:c===null?p:c.filter(d=>_(p,d)),launched:c,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=j(o),n=await Y(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),l=a.app===null?null:await r.object(a.app);if(!l)throw new Error(`node ${e.node} has no app`);return{class:"node",node:n,app:l,scopes:await H(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await T(o,a.cwd,a.profile_id,t,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,l)}}s(Ae,"readerFor");async function ae(o,e,t,r=j(o),n=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),l=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
2
+ sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!l)throw new Error(`no node ${e}`);const{grantee:p,sub:c,grant_id:d,scopes_json:f,cwd:g,profile_id:w,app:E}=l,m=E===null?null:await r.object(E);if(!m)throw new Error(`node ${e} has no app`);const i=f===null?null:JSON.parse(f);return{class:"node",node:a,app:m,scopes:await H(p,c??"",d,i,r,n),launched:i,cwd:g,...await T(o,g,w,t,r,c||void 0),profile:w===null?null:await r.profile(w,m)}}s(ae,"readerForNode");class se extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function Le(o,e,t=async()=>[],r=j(o)){const n=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(n!==void 0)return await pe(o,e,n.envelope_json===null?null:JSON.parse(n.envelope_json),r);if(e.type==="node")return await ae(o,e.id,t,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const p=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!p)throw new se;const c=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",d=J(),f=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${d.sql}`).all(c,...d.args),g=s(h=>JSON.parse(h.resolved_scopes_json).filter(O=>O.mode==="always").map(O=>C(O.scope)),"always"),w=f.length>1&&a.type==="app"?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(X,e.id)).map(h=>h.subject_id)):null,E=w===null?void 0:f.find(h=>w.has(h.sub.replace(/^user:/,"")))?.sub,m=E===void 0?null:await r.grantFor(c,E),i=a.type==="person"?null:f.length===0?r.pluginScopes(c):f.length===1?g(f[0]):m?.resolved??null,u=(a.type==="person"?(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(a.id))?.external_id:void 0)??(f.length===1?f[0].sub:m?.sub);return{class:"object",object:e,node:e,owner:a,app:p,scopes:i,...u===void 0?{}:{sub:u},repos:a.type==="repo"?[a]:[]}}s(Le,"readerForObject");async function Me(o,e,t){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const n=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return n.length===0?t.pluginScopes(r):n.length>1?null:JSON.parse(n[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>C(a.scope))}s(Me,"appScopesNow");async function pe(o,e,t,r){const n=await F(o);if(t!==null&&t.app===null)return{class:"object",object:e,node:e,owner:n,app:n,scopes:null,repos:[]};const a=t?.app==null?null:await S(o,t.app),l=t?.app==null?null:await r.grantFor(t.app,t.sub),p=t===null||l===null?null:t.node_scopes===null?l.resolved:t.node_scopes.filter(d=>_(l.resolved,d)),c=a??(e.owner===null?n:await r.object(e.owner)??n);return{class:"object",object:e,node:e,owner:c,app:c,scopes:p,launched:t?.node_scopes??null,repos:[],...t?.place==null?{}:{place:t.place}}}s(pe,"readerForStub");function j(o){return{grantById:x,grantFor:A,pluginScopes:s(e=>G(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await U(o,e),"object"),profile:s(async(e,t)=>await ce(o,e,t),"profile"),projects:s(e=>$()?[]:v(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function Te(o){const e=j(o),t=new Map,r=s((n,a)=>(t.has(n)||t.set(n,a()),t.get(n)),"memo");return{grantById:s(n=>r(`g\0${n}`,()=>e.grantById(n)),"grantById"),grantFor:s((n,a)=>r(`a\0${n}\0${a}`,()=>e.grantFor(n,a)),"grantFor"),pluginScopes:s(n=>r(`t\0${n}`,()=>e.pluginScopes(n)),"pluginScopes"),object:s(async n=>await r(`o\0${n}`,async()=>await e.object(n)),"object"),profile:s(async(n,a)=>await r(`p\0${n}\0${a.id}`,async()=>await e.profile(n,a)),"profile"),projects:s(n=>r(`j\0${n}`,()=>e.projects(n)),"projects")}}s(Te,"publishLookups");async function H(o,e,t,r,n,a=!1){const l=t?await n.grantById(t):await n.grantFor(o,e),p=l&&l.grantee===o?l.resolved:null;if(p===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?p:r.filter(c=>_(p,c))}s(H,"nodeScopes");async function F(o){return await z(o,Q())}s(F,"personObject");async function S(o,e){return await L(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function ce(o,e,t){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
3
+ WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await L(o,"profile","profile",e,K(e,q(e).manifest.name),t)}s(ce,"profileObject");export{se as NoOwningAppError,Me as appScopesNow,j as liveLookups,ce as profileObject,Te as publishLookups,Ae as readerFor,ae as readerForNode,Le as readerForObject,T as viewRepos,re as warmCloudNodeCheckouts,xe as warmNodeDirs,Ce as warmNodeRepos};