@north-light/cli 0.3.709 → 0.3.711
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.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +1 -1
- package/dist/clients/attach/input/controller.js +2 -2
- package/dist/clients/attach/render/chat-view.d.ts +13 -2
- package/dist/clients/attach/render/chat-view.js +2 -2
- package/dist/clients/attach/session/input-wiring.d.ts +2 -2
- package/dist/clients/attach/session/layout-record.d.ts +15 -0
- package/dist/clients/attach/session/layout-record.js +1 -0
- package/dist/clients/attach/session/reconnect.d.ts +8 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/session/teardown.d.ts +2 -0
- package/dist/clients/attach/session/teardown.js +3 -3
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/slash/recover.d.ts +10 -0
- package/dist/clients/attach/slash/recover.js +3 -0
- package/dist/clients/attach/viewer.js +520 -516
- package/dist/commands/human/prompts.js +1 -1
- package/dist/commands/human/request.js +1 -1
- package/dist/commands/sys/doctor.js +1 -1
- package/dist/commands/sys/tutorial/scenario.js +2 -2
- package/dist/core/broker-client/client.d.ts +2 -0
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/broker-client/transport-relay.d.ts +6 -0
- package/dist/core/broker-client/transport-relay.js +1 -1
- package/dist/core/broker-client/transport.d.ts +4 -0
- package/dist/core/canvas/daemon-actions.d.ts +1 -1
- package/dist/core/canvas/daemon-actions.js +7 -7
- package/dist/core/canvas/deliveries.d.ts +1 -1
- package/dist/core/canvas/deliveries.js +21 -21
- package/dist/core/canvas/executions.d.ts +1 -1
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
- package/dist/core/canvas/reconciler-leases.d.ts +4 -0
- package/dist/core/canvas/reconciler-leases.js +5 -5
- package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/conversation-store/client.js +2 -2
- package/dist/core/conversation-store/index.d.ts +5 -2
- package/dist/core/conversation-store/row-store.js +14 -12
- package/dist/core/graph/package-docs.js +5 -5
- package/dist/core/graph/package-publish.js +4 -3
- package/dist/core/human/requests.js +19 -19
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/runtime/broker/client-registry.d.ts +1 -1
- package/dist/core/runtime/broker/client-registry.js +1 -1
- package/dist/core/runtime/broker/turn-replies.js +3 -1
- package/dist/core/runtime/broker-protocol.d.ts +4 -4
- package/dist/core/runtime/broker-protocol.js +3 -3
- package/dist/core/runtime/broker-request.d.ts +2 -0
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/model-swap.d.ts +2 -1
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +2 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/session-cycles.d.ts +21 -0
- package/dist/core/runtime/session-cycles.js +1 -1
- package/dist/core/runtime/tmux-driver.d.ts +7 -0
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/worktree-machine.d.ts +4 -1
- package/dist/core/worktree-machine.js +1 -1
- package/dist/core/worktree-sweep.d.ts +14 -3
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/app-listener.js +1 -1
- package/dist/daemon/api/handlers/charges.d.ts +1 -1
- package/dist/daemon/api/handlers/charges.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +4 -3
- package/dist/daemon/api/handlers/environments.d.ts +1 -1
- package/dist/daemon/api/handlers/environments.js +1 -1
- package/dist/daemon/api/handlers/limits.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/cron/live-runs.d.ts +3 -0
- package/dist/daemon/cron/live-runs.js +1 -1
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/due-sources.d.ts +1 -1
- package/dist/daemon/due-sources.js +1 -1
- package/dist/daemon/due.js +7 -7
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +4 -4
- package/dist/daemon/human/finish.js +3 -3
- package/dist/daemon/human/settle.js +1 -1
- package/dist/daemon/reconcilers/action-lane.js +1 -1
- package/dist/daemon/reconcilers/delivery-lane.js +2 -2
- package/dist/daemon/reconcilers/grant-effects.js +1 -1
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/requested-stops.js +2 -2
- package/dist/daemon/runs/observer.d.ts +4 -0
- package/dist/daemon/runs/observer.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/package.json +4 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/capabilities.js +1 -0
- package/packages/crouter-api/dist/clients/attach/input/controller.js +2 -2
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +40 -3
- package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +41 -2
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +2 -0
- package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +133 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +24 -5
- package/packages/crouter-api/dist/commands/human/prompts.js +11 -18
- package/packages/crouter-api/dist/commands/human/request.js +3 -0
- package/packages/crouter-api/dist/commands/sys/doctor.js +17 -0
- package/packages/crouter-api/dist/commands/sys/tutorial/scenario.js +1 -0
- package/packages/crouter-api/dist/core/broker-client/client.js +4 -0
- package/packages/crouter-api/dist/core/broker-client/transport-relay.js +45 -0
- package/packages/crouter-api/dist/core/canvas/daemon-actions.js +3 -2
- package/packages/crouter-api/dist/core/canvas/deliveries.js +7 -3
- package/packages/crouter-api/dist/core/canvas/executions.js +8 -7
- package/packages/crouter-api/dist/core/canvas/reconciler-leases.js +4 -0
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +14 -1
- package/packages/crouter-api/dist/core/graph/package-docs.js +8 -3
- package/packages/crouter-api/dist/core/graph/package-publish.js +8 -1
- package/packages/crouter-api/dist/core/human/requests.js +2 -2
- package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
- package/packages/crouter-api/dist/core/runtime/broker-protocol.js +4 -4
- package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
- package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +3 -3
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/runtime/session-cycles.js +90 -8
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
- package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +3 -3
- package/packages/crouter-api/dist/daemon/api/router.js +1 -4
- package/packages/crouter-api/dist/daemon/cron/live-runs.js +4 -5
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +3 -3
- package/packages/crouter-api/dist/daemon/human/finish.js +2 -1
- package/packages/crouter-api/dist/daemon/human/settle.js +1 -6
- package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/install-runtime.mjs +18 -1
- package/scripts/lib/install-source.mjs +49 -0
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +0 -18
- package/dist/daemon/reconcilers/idle-sandbox.js +0 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var _=Object.defineProperty;var d=(e,o)=>_(e,"name",{value:o,configurable:!0});import{withCanvasWrite as u}from"../../core/canvas/db.js";import{enqueueDaemonAction as f}from"../../core/canvas/daemon-actions.js";import{cancelDelivery as w,enqueueNodeMail as p}from"../../core/feed/messages.js";import{getRequest as s,markCompanionRetired as y,markProjected as q,markProjectionError as v,setSettlementDeliveryMarksLocked as j,settleRequestLocked as k}from"../../core/human/requests.js";import{appendQuestionAnswered as b}from"../../core/runs/questions.js";import{notifyProviderApproval as h}from"../../core/providers/approval.js";import{signalInboxActivity as g}from"../../core/human/root.js";async function O(e){const o=await u(async i=>{const m=e.settled_at??new Date().toISOString(),t=await k(i,{request_id:e.request_id,outcome:e.outcome,result_json:e.result_json,settled_at:m});if(t===null){const l=await s(e.request_id);if(l===null)throw new Error(`human request disappeared while settling: ${e.request_id}`);return{outcome:"already_settled",request:l}}const n=typeof e.notification=="function"?await e.notification(t):e.notification;if(t.action_json!==null&&t.kind==="page"&&e.completion_action===void 0)throw new Error(`request ${t.request_id} needs its frozen completion action`);if(t.kind==="review"&&t.projected_at===null&&e.post_commit?.project===void 0)throw new Error(`review ${t.request_id} needs a projection effect`);if(t.companion_node_id!==null&&t.companion_retired_at===null&&e.post_commit?.retire===void 0)throw new Error(`request ${t.request_id} needs a companion retirement effect`);let a=null,c=null;t.requester_node_id!==null&&n!==void 0&&(a=(await p(t.requester_node_id,{kind:"completed",label:n.label,senderName:"crtrd",...n.body_ref===void 0?{}:{bodyRef:n.body_ref},...n.body_json===void 0?{}:{bodyJson:n.body_json},disposition:n.disposition,urgency:"normal",wake:1})).deliveryId),t.action_json!==null&&e.completion_action!==void 0&&t.kind==="page"&&(c=await f({adapter:e.completion_action.adapter,bodyJson:e.completion_action.bodyJson,idempotencyKey:`human-action:${t.inbox_ticket_id}`})),t.submit_note_delivery_id!==null&&await w(t.submit_note_delivery_id),await j(i,t.request_id,{settlement_delivery_id:a,action_delivery_id:c});const r=await s(t.request_id);if(r===null)throw new Error(`settled human request disappeared: ${t.request_id}`);return await b(i,r),{outcome:"settled",request:r}});return o.outcome==="settled"&&(h(o.request.request_id),g(),e.post_commit!==void 0&&await D(o.request,e.post_commit)),o}d(O,"settleHumanRequest");async function D(e,o){if(e.kind==="review"&&e.projected_at===null&&o.project!==void 0)try{await o.project(e),await q(e.request_id,new Date().toISOString())}catch(i){await v(e.request_id,i instanceof Error?i.message:String(i))}if(e.companion_node_id!==null&&e.companion_retired_at===null&&o.retire!==void 0)try{await o.retire(e.companion_node_id,e.outcome==="canceled"||e.outcome==="dismissed"?"canceled":"approved"),await y(e.request_id,new Date().toISOString())}catch{}}d(D,"projectAndRetire");export{D as projectAndRetire,O as settleHumanRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var p=Object.defineProperty;var d=(n,r)=>p(n,"name",{value:r,configurable:!0});import{rmSync as
|
|
1
|
+
var p=Object.defineProperty;var d=(n,r)=>p(n,"name",{value:r,configurable:!0});import{rmSync as w}from"node:fs";import{claimDaemonAction as g,dueDaemonActions as h,settleDaemonAction as _}from"../../core/canvas/daemon-actions.js";import{getNode as y}from"../../core/canvas/canvas.js";import{emitEvent as l}from"../../core/events/emit.js";import{operationIdContext as c}from"../../core/events/operation-id.js";import{createPageRequest as I,getRequest as u}from"../../core/human/requests.js";import{synthesizedPageDocument as v,writeSynthesizedPage as k}from"../../core/human/page-synth.js";import{preparePage as $}from"../../core/human/page-authoring.js";import{resolvePageComponents as b}from"../../core/config.js";import{spawnChild as q}from"../../core/runtime/spawn.js";import{isStartRefusal as D}from"../../core/runtime/start-check.js";import{runDelivery as P}from"../delivery/run-delivery.js";import{ensureCronOwnerLease as S}from"../cron/live-runs.js";import{deliveryDaemonInstanceId as m}from"./delivery-lane.js";import{cronBirthPlacement as C}from"../cron/armed-context.js";import{asPerson as N}from"./node-lifecycle/node-person.js";import{checkCronBirth as z}from"../cron/authority.js";async function o(n,r,e){await _(n.actionId,n.attempts,r,e,Date.now())}d(o,"settle");async function f(n,r,e){await o(n,r,{state:"permanent_failed",failure:{kind:"spawn_error",message:e}})}d(f,"failed");async function A(n,r,e){const a=await y(e.nodeId);if(a!==null){if(a.frozen_at!==null||a.pi_session_id!==null||a.status==="idle"||a.status==="done"||a.status==="canceled"){await o(n,r,{state:"acknowledged"});return}await f(n,r,a.status==="dead"?`cron spawn ${e.nodeId} recorded a failed birth`:`cron spawn ${e.nodeId} found an incomplete birth`);return}const t=e.principal;if(t===void 0){c.fresh(()=>l({level:"warn",event:"cron.birth.refused",node_id:e.nodeId,fields:{cron_id:e.cronId??null,action_id:n.actionId,reason:"grant_missing",stage:"delivery"}})),await o(n,r,{state:"permanent_failed",failure:{kind:"grant_refused",message:"grant_missing: the queued birth carries no cron principal"}});return}const i=await z(t,{kind:e.kind,cwd:e.cwd,profile:e.profile});if(!i.allowed){c.fresh(()=>l({level:"warn",event:"cron.birth.refused",node_id:e.nodeId,fields:{cron_id:t.cron_id,action_id:n.actionId,grant_id:t.grant_id,reason:i.reason,stage:"delivery"}})),await o(n,r,{state:"permanent_failed",failure:{kind:"grant_refused",message:`${i.reason}: ${i.message}`}});return}try{await N(t.sub,async()=>await q({nodeId:e.nodeId,kind:e.kind,cwd:e.cwd,prompt:e.prompt,...await C({...t,scopes:i.scopes},e.nodeId),readiness:"launch",profile:e.profile,isolated:e.isolated===!0,wakeOrigin:e.wakeOrigin})),await o(n,r,{state:"acknowledged"})}catch(s){if(D(s)){await o(n,r,{state:"permanent_failed",failure:{kind:"grant_refused",message:s.message}});return}await f(n,r,`cron spawn ${e.nodeId} failed: ${s instanceof Error?s.message:String(s)}`),c.fresh(()=>l({level:"error",event:"delivery.cron_spawn_failed",node_id:e.nodeId,error:s,fields:{action_id:n.actionId}}))}}d(A,"deliverSpawn");function E(n,r){const e=k(v(n.title,n.summary,r,!1));try{return $({sourceFile:e.path,source:{sessionName:n.sessionName,...n.profileName===null?{}:{profileName:n.profileName}},productKinds:b(),delivery:{placement:"inline",inbox:!0,reply:!1}})}finally{w(e.dir,{recursive:!0,force:!0})}}d(E,"preparedCronPage");async function R(n,r,e){if(await u(e.requestId)!==null){await o(n,r,{state:"acknowledged"});return}const a=n.body,t=typeof a?.stdout=="string"?a.stdout:null;if(t===null){await f(n,r,`cron human ${e.requestId} has no frozen stdout`);return}try{await I({request_id:e.requestId,prepared:E(e,t)}),await o(n,r,{state:"acknowledged"})}catch(i){await f(n,r,`cron human ${e.requestId} failed: ${i instanceof Error?i.message:String(i)}`)}}d(R,"deliverHuman");async function x(n,r){const e=n.adapter;if(n.body===null){await f(n,r,`daemon action ${n.actionId} has no body`);return}if(e.adapter==="subprocess"){let a=e.node_id;if(a===void 0){const t=n.idempotencyKey;if(!t.startsWith("human-action:"))throw new Error(`daemon action ${n.actionId} has no originating app`);const i=await u(t.slice(13));if(!i)throw new Error(`daemon action ${n.actionId} has no originating human request`);a=i.requester_node_id}await P({argv:e.argv,cwd:e.cwd,document:n.body,attempt:n.attempts,nodeId:a,...e.app?{app:e.app}:{}},async t=>await o(n,r,t));return}if(e.adapter==="cron_spawn"){await A(n,r,e);return}if(e.adapter==="cron_human"){await R(n,r,e);return}await f(n,r,`daemon action ${n.actionId} has unknown adapter ${String(e.adapter)}`)}d(x,"deliverAction");class ee{static{d(this,"ActionLaneReconciler")}async run(r,e){if(!e.lifecycle.acceptsDetachedWork())return;let a;try{a=await h(r)}catch(t){c.fresh(()=>l({level:"error",event:"daemon_action.scan_failed",error:t}));return}await S();for(const t of a)try{const i=await g(t.actionId,r,m);if(i===null)continue;e.lifecycle.registerDetached(x(i,m).catch(s=>{c.fresh(()=>l({level:"error",event:"daemon_action.failed",error:s,fields:{action_id:i.actionId}}))}))}catch(i){c.fresh(()=>l({level:"error",event:"daemon_action.claim_failed",error:i,fields:{action_id:t.actionId}}))}}}export{ee as ActionLaneReconciler};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var g=Object.defineProperty;var p=(e,t)=>g(e,"name",{value:t,configurable:!0});import{
|
|
1
|
+
var g=Object.defineProperty;var p=(e,t)=>g(e,"name",{value:t,configurable:!0});import{claimPushDelivery as D,duePushDeliveries as h,messageBodyForDelivery as j,pushDeliveryClaimIsCurrent as O,settleDelivery as d}from"../../core/canvas/deliveries.js";import{deliveryBackoffMs as f}from"../../core/canvas/delivery-contract.js";import{openDb as c}from"../../core/canvas/db.js";import{pushLineFor as u}from"../../core/graph/custom.js";import{postReceiverUrl as N}from"../../core/graph/receiver-url.js";import{emitEvent as l}from"../../core/events/emit.js";import{operationIdContext as m}from"../../core/events/operation-id.js";import{runDelivery as w,DELIVERY_TIMEOUT_MS as b}from"../delivery/run-delivery.js";import{cronDaemonInstanceId as E,ensureCronOwnerLease as T}from"../cron/live-runs.js";import{isDrained as A}from"../drain.js";const v=E;async function o(e,t,a){await d(e.deliveryId,e.attempts,t,{state:"permanent_failed",failure:{kind:"spawn_error",message:a}},Date.now())}p(o,"failed");async function J(e,t){const a=await(await c()).prepare(`SELECT o.type, o.name, c.receiver_json, c.payload_json, m.object_id, i.external_id AS app,
|
|
2
2
|
d.message_id, owner.type AS owner_type, parent.external_id AS parent_app
|
|
3
3
|
FROM deliveries d JOIN objects o ON o.id = d.destination_id
|
|
4
4
|
JOIN custom_objects c ON c.object = o.id JOIN messages m ON m.message_id = d.message_id
|
|
5
5
|
LEFT JOIN objects owner ON owner.id = o.owner
|
|
6
6
|
LEFT JOIN identities i ON i.object = o.owner AND i.scheme = 'app'
|
|
7
7
|
LEFT JOIN identities parent ON parent.object = owner.owner AND parent.scheme = 'app'
|
|
8
|
-
WHERE d.delivery_id = ?`).get(e.deliveryId);if(!a||!a.receiver_json){await o(e,t,`delivery ${e.deliveryId} has no supported receiver`);return}const i=JSON.parse(a.receiver_json);if(!await O(e,t)){await d(e.deliveryId,e.attempts,t,{state:"acknowledged"},Date.now());return}if(typeof i=="object"&&typeof i.url=="string"&&a.type!=="action"){const n=await u(await c(),e.deliveryId);if(!n){await o(e,t,`delivery ${e.deliveryId} has no event document`);return}try{const r=await
|
|
8
|
+
WHERE d.delivery_id = ?`).get(e.deliveryId);if(!a||!a.receiver_json){await o(e,t,`delivery ${e.deliveryId} has no supported receiver`);return}const i=JSON.parse(a.receiver_json);if(!await O(e,t)){await d(e.deliveryId,e.attempts,t,{state:"acknowledged"},Date.now());return}if(typeof i=="object"&&typeof i.url=="string"&&a.type!=="action"){const n=await u(await c(),e.deliveryId);if(!n){await o(e,t,`delivery ${e.deliveryId} has no event document`);return}try{const r=await N(i.url,JSON.stringify(n),{"Content-Type":"application/json","X-Crtr-Delivery":e.deliveryId,"X-Crtr-Event":a.message_id},b);r>=200&&r<300?await d(e.deliveryId,e.attempts,t,{state:"acknowledged"},Date.now()):r>=300&&r<400?await o(e,t,`url receiver returned HTTP ${r}; redirects are not followed \u2014 register the final URL`):r>=400&&r<500&&r!==408&&r!==429?await o(e,t,`url receiver returned HTTP ${r}`):await d(e.deliveryId,e.attempts,t,{state:"pending",nextAttemptAt:Date.now()+f(e.attempts),failure:{kind:"spawn_error",message:`url receiver returned HTTP ${r}`}},Date.now())}catch(r){await d(e.deliveryId,e.attempts,t,{state:"pending",nextAttemptAt:Date.now()+f(e.attempts),failure:{kind:"spawn_error",message:String(r)}},Date.now())}return}if(typeof i!="object"||!Array.isArray(i.argv)||typeof i.cwd!="string"){await o(e,t,`delivery ${e.deliveryId} has an invalid argv receiver`);return}if(a.type==="action"){if(typeof i.name!="string"||!a.object_id){await o(e,t,`delivery ${e.deliveryId} has an invalid argv receiver`);return}const n=await j(e.deliveryId);if(n===null){await o(e,t,`delivery ${e.deliveryId} has no message body`);return}const{push:r,...I}=n,y={...I,action:{name:i.name,payload:a.payload_json===null?null:JSON.parse(a.payload_json)}};await w({argv:i.argv,cwd:i.cwd,document:y,attempt:e.attempts,nodeId:a.object_id,...a.app??a.parent_app?{app:a.app??a.parent_app}:{}},async _=>{await d(e.deliveryId,e.attempts,t,_,Date.now())});return}const s=await u(await c(),e.deliveryId);if(!s){await o(e,t,`delivery ${e.deliveryId} has no event document`);return}await w({argv:i.argv,cwd:i.cwd,document:s,attempt:e.attempts,app:a.app??a.parent_app??"app:terminal",custom:{deliveryId:e.deliveryId,messageId:a.message_id}},async n=>{await d(e.deliveryId,e.attempts,t,n,Date.now())})}p(J,"deliverExternal");class U{static{p(this,"DeliveryLaneReconciler")}async run(t,a){if(!a.lifecycle.acceptsDetachedWork()||await A())return;let i;try{i=await h(t)}catch(s){m.fresh(()=>l({level:"error",event:"delivery.scan_failed",error:s}));return}await T();for(const s of i)try{const n=await D(s.deliveryId,t,v);if(n===null)continue;a.lifecycle.registerDetached(J(n,v).catch(r=>{m.fresh(()=>l({level:"error",event:"delivery.failed",error:r,fields:{delivery_id:n.deliveryId}}))}))}catch(n){m.fresh(()=>l({level:"error",event:"delivery.claim_failed",error:n,fields:{delivery_id:s.deliveryId}}))}}}export{U as DeliveryLaneReconciler,v as deliveryDaemonInstanceId};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var x=Object.defineProperty;var a=(t,e)=>x(t,"name",{value:e,configurable:!0});import{canvasPoolSize as T,openDb as v}from"../../core/canvas/db.js";import{isCloudRole as L}from"../../core/canvas/person.js";import{endExecution as O,liveExecutionForNode as R}from"../../core/canvas/executions.js";import{emitEvent as m}from"../../core/events/emit.js";import{afterRevocationStop as D}from"../../core/grants/on-sync.js";import{activeGrants as y,grantIdsWhere as S,grantStanding as E,mirrorOnly as M}from"../../core/grants/mirror.js";import{removeApp as A,removePersonData as P}from"../../core/grants/remove.js";import{wakeAllGrantWaiters as G,wakeGrantWaiters as C}from"../../core/grants/watch.js";import{discardOrphanedTokens as g,discardTokensForGrant as F}from"../../core/providers/token-cache.js";import{isUnsandboxedMachine as W}from"../../core/runtime/unsandboxed.js";import{runnerForExecution as U}from"../../core/runtime/runner/index.js";import{closeGrantStreams as B,heldGrantIds as $}from"../../core/runs/events.js";import{stopNodeSandboxes as H}from"../../core/spaces/stop.js";import{holdRecovery as J}from"../../core/runtime/recovery-hold.js";import{brokerSignalBus as z}from"../broker-signals/bus.js";import{withRowClaim as K}from"./row-claim.js";const V=6e4,X=a(()=>Math.max(1,Math.floor(T()/3)),"grantSlotLimit");let _=0;const b=[];async function Y(t){for(;_>=X();)await new Promise(e=>{b.push(e)});_+=1;try{return await t()}finally{_-=1,b.shift()?.()}}a(Y,"withGrantSlot");const j=3e4,q=5;function w(t,e,r){m({level:"error",event:`daemon.grants.${t}`,error:e,fields:r})}a(w,"failed");function Q(t,e,r){try{const n=e.sub===null||e.grantee===null?g(r):F({sub:e.sub,grantee:e.grantee,active:e.standing==="active"},r);n.tokens>0&&m({level:"info",event:"daemon.grants.outbound_tokens_discarded",fields:{grant:t,tokens:n.tokens}})}catch(n){w("outbound_tokens_discard_failed",n,{grant:t})}}a(Q,"discardTokens");async function N(){try{await(await import("../../core/providers/bundles.js")).syncProviderBundles()}catch(t){m({level:"error",event:"daemon.providers.bundle_sync_failed",error:t})}}a(N,"reconcileProviderBundles");async function Z(t,e){if(C(t),e.standing==="inactive"){const r=B(t);r>0&&m({level:"info",event:"daemon.grants.streams_closed",fields:{grant:t,grantee:e.grantee,streams:r}})}await N()}a(Z,"serveEffects");async function I(t,e){const r=await K("nodes",t,V,async n=>{const o=await R(t);if(o===null)return;await n.assertOwned(),m({level:"info",event:"daemon.grants.node_stop",node_id:t,fields:{grant:e,execution_id:o.executionId}});const c=a(async()=>{await n.assertOwned(),await O(o.executionId,{reason:"permission_revoked"}),await D(t)},"finish");if(o.runner==="process"){const u=await H(t,"permission_revoked",{holdRecovery:!0,after:c});if(!u.confirmed)throw u.error??new Error(`stop of ${t} was not confirmed`);return}const d=await J(t);if(d!==null)try{const u=await U(o.runner).stop(o,{reason:"permission_revoked"});if(!u.confirmed)throw u.error??new Error(`stop of ${t} was not confirmed`);await c()}finally{await d.release()}},{waitForLock:!0})}a(I,"stopRevokedNode");async function ee(t,e){if(!(e.grantee!==null&&M({grantee:e.grantee}))){if(e.standing==="inactive"){const r=await(await v()).prepare("SELECT DISTINCT n.node_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id = ?").all(t);for(const{node_id:n}of r)try{await I(n,t)}catch(o){w("node_stop_failed",o,{grant:t,node_id:n})}}if(e.status==="removed"&&e.removal_done_at===null&&e.grantee!==null&&e.sub!==null)try{e.grantee!=="app:terminal"?await A(e.grantee,e.sub):L()?await P(e.grantee,e.sub):m({level:"info",event:"daemon.grants.removal_settled_without_cleanup",fields:{grant:t,grantee:e.grantee,sub:e.sub}}),await(await v()).prepare("UPDATE grants SET removal_done_at = ? WHERE id = ? AND rev = ? AND removal_done_at IS NULL").run(new Date().toISOString(),t,e.rev)}catch(r){w("removal_failed",r,{grant:t,grantee:e.grantee})}}}a(ee,"laneEffects");async function te(t,e,r){let n;await Y(async()=>{const o=await E(e);Q(e,o,r??await y(o.sub??void 0)),t.serves&&(n=Z(e,o)),t.runsLanes&&o.standing!=="lagging"&&await ee(e,o)}),await n}a(te,"applyGrantEffects");async function re(t){const e=new Set;if(t.serves)for(const n of $())e.add(n);if(t.runsLanes){const n=await(await v()).prepare("SELECT DISTINCT n.grant_id FROM nodes n JOIN executions e ON e.node_id = n.node_id AND e.state != 'exited' WHERE n.grant_id IS NOT NULL").all();for(const{grant_id:o}of n)e.add(o)}const r=[];for(const n of e)(await E(n)).status===null&&r.push(n);return r}a(re,"goneGrantIds");async function Se(t,e={}){const r=new Map,n=a((s,l)=>{const i=(r.get(s)??Promise.resolve()).then(()=>te(t,s,l)).catch(f=>w("effects_failed",f,{grant:s})).finally(()=>{r.get(s)===i&&r.delete(s)});return r.set(s,i),i},"run"),o=a(async()=>{const s=t.serves?N():void 0;try{t.serves&&G();const l=await y();g(l);const i=new Set(await S(`status <> 'active' OR expires_at <= '${new Date().toISOString()}'`));for(const f of await re(t))i.add(f);await Promise.all([...i].map(f=>n(f,l)))}catch(l){w("catch_up_failed",l,{})}await s},"catchUp"),c=new Map;let d=!1;const u=a(async()=>{if(!d){d=!0;try{const s=new Set(await S(`status = 'removed' AND removal_done_at IS NULL${W()?" AND grantee = 'app:terminal'":""}`));for(const i of c.keys())s.has(i)||c.delete(i);const l=[...s].filter(i=>!r.has(i)&&(c.get(i)?.notBefore??0)<=Date.now());await Promise.all(l.map(async i=>{await n(i);const f=(c.get(i)?.failures??0)+1;c.set(i,{failures:f,notBefore:Date.now()+h*2**Math.min(f,q)})}))}catch(s){w("removal_sweep_failed",s,{})}finally{d=!1}}},"sweepRemovals"),h=e.sweepMs??j,p=t.runsLanes?setInterval(()=>{u()},h):void 0;p?.unref();const k=await z.subscribe(s=>{n(s)},{kinds:["grant"],onListenStart:a(()=>{o()},"onListenStart")});return()=>{p!==void 0&&clearInterval(p),k()}}a(Se,"startGrantEffects");export{te as applyGrantEffects,Se as startGrantEffects};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var o=(e,t)=>k(e,"name",{value:t,configurable:!0});import{getNode as _,getRow as h}from"../../core/canvas/index.js";import{managedWorktreeSweepCandidates as y}from"../../core/canvas/managed-worktree-sweep-candidates.js";import{isSafeNodeId as w}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as S,recordedPidLiveness as v}from"../../core/canvas/pid.js";import{emitEvent as u}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{reconcileManagedWorktree as R}from"../../core/worktree-sweep.js";import{sweepOnMachine as T,worktreeMachineOf as W}from"../../core/worktree-machine.js";import{runThrottledLane as I}from"./throttled-lane.js";const M=60*1e3,O=300*1e3,L=3,N=["done","dead","canceled"];function g(e){return N.includes(e.status)}o(g,"isTerminal");function E(e,t){return t?.state==="closed"||t?.state==="open"&&e.status==="done"&&e.final_report!==null}o(E,"hasSweepDisposition");async function b(e,t,r,s){return await t.isClaimed(e.node_id)||e.frozen_at!==null||!g(e)||!E(e,(await _(e.node_id))?.managed_worktree)?!1:s||v(e.pi_pid,e.pi_pid_identity,r)==="dead"}o(b,"engineIsGone");function A(e,t){const r=e.node_id,s=e.pi_pid,i=e.pi_pid_identity;return{stillEligible:o(async()=>{if(await t.isClaimed(r))return!1;const n=await h(r);return n===null||!g(n)||n.frozen_at!==null||!E(n,(await _(r))?.managed_worktree)?!1:n.pi_pid===s&&n.pi_pid_identity===i},"stillEligible")}}o(A,"eligibilityGuard");class j{static{o(this,"ManagedWorktreeSweepReconciler")}run(t,r){if(!r.lifecycle.acceptsDetachedWork())return;const s=I("managed-worktree-sweep","",t,M,O,i=>this.sweep(t,r.fleet,i)).then(()=>{}).catch(i=>{p.fresh(()=>u({level:"error",event:"worktree.sweep.failed",error:i}))});r.lifecycle.registerDetached(s)}async candidates(t){try{return await y(t)}catch(r){return p.fresh(()=>{u({level:"error",event:"worktree.sweep.scan_failed",error:r})}),null}}async sweep(t,r,s){const i=await this.candidates(t);if(i===null||i.length===0)return;let n=Number(s.state??0);(!Number.isInteger(n)||n>=i.length)&&(n=0);const d=Math.min(L,i.length),l=[];for(let c=0;c<d;c+=1)l.push(i[(n+c)%i.length]);if(!await s.save(String((n+d)%i.length)))return;const a=await S();if(a!==null)for(const c of l){const f=await h(c),m=f===null?null:await W(f.profile_id);if(!(f===null||!await b(f,r,a,m!==null))){if(!await s.holds())return;await this.reconcileOne(f,t,r,m)}}}async reconcileOne(t,r,s,i){const n=t.node_id,d=w(n)?{node_id:n}:{},l=w(n)?{}:{affected_node_id:n};try{const a=await R(n,A(t,s),r,i===null?void 0:T(i,n));p.fresh(()=>{if(a.status==="complete"){u({level:"info",event:"worktree.sweep.reconciled",outcome:"succeeded",...d,fields:l});return}a.status!=="skipped"&&(a.status==="refused"&&a.unchanged===!0||u({level:a.status==="failed"?"error":"warn",event:a.status==="failed"?"worktree.sweep.failed":"worktree.sweep.refused",outcome:a.status==="failed"?"failed":"skipped",...d,fields:{...l,reason:a.reason,...a.detail===void 0?{}:{detail:a.detail}}}))})}catch(a){p.fresh(()=>{u({level:"error",event:"worktree.sweep.failed",...d,error:a,fields:l})})}}}export{j as ManagedWorktreeSweepReconciler,L as WORKTREE_SWEEP_BUDGET,M as WORKTREE_SWEEP_INTERVAL_MS};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var d=Object.defineProperty;var t=(e,r)=>d(e,"name",{value:r,configurable:!0});import{
|
|
2
|
-
ORDER BY sequence_number DESC LIMIT 1`).get(e))?.type==="node.turn.started"}t(
|
|
1
|
+
var d=Object.defineProperty;var t=(e,r)=>d(e,"name",{value:r,configurable:!0});import{getNode as s}from"../../../core/canvas/index.js";import{endExecution as p,executionsWithStopRequestedBefore as i}from"../../../core/canvas/executions.js";import{openDb as f}from"../../../core/canvas/db.js";import{emitEvent as o}from"../../../core/events/emit.js";import{runnerForExecution as u}from"../../../core/runtime/runner/index.js";const l=3e4;async function c(e,r){return r==null?!1:(await(await f()).prepare(`SELECT type FROM run_events WHERE node_id = ? AND type IN ('node.turn.started', 'node.turn.completed')
|
|
2
|
+
ORDER BY sequence_number DESC LIMIT 1`).get(e))?.type==="node.turn.started"}t(c,"turnIsOpen");async function m(e){const r=await s(e.nodeId);if(r===null||e.stopAfterTurn&&await c(e.nodeId,r.run_id))return;const a=await u(e.runner).stop(e,{reason:e.stopReason??"stopped"});if(!a.confirmed){o({level:"error",event:"broker.teardown.unconfirmed",node_id:e.nodeId,error:a.error});return}await p(e.executionId,{reason:e.stopReason??"stopped"}),o({level:"info",event:"broker.stop.enacted_from_row",node_id:e.nodeId,fields:{reason:e.stopReason,after_turn:e.stopAfterTurn}})}t(m,"enact");async function S(e){for(const r of await i(new Date(e-l).toISOString()))try{await m(r)}catch(n){o({level:"error",event:"broker.stop.enact_failed",node_id:r.nodeId,error:n})}}t(S,"enactRequestedStops");export{l as ORPHANED_STOP_AGE_MS,S as enactRequestedStops};
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import type { Transport } from '../../core/broker-client/transport.js';
|
|
2
|
+
/** The transport to the node's live broker, from where its runner says viewers connect: this machine's `view.sock`, or
|
|
3
|
+
* the `/view` WebSocket behind a sandbox's preview. */
|
|
4
|
+
export declare function viewTransport(nodeId: string): Promise<Transport>;
|
|
1
5
|
/** What the model is streaming now in a node's open assistant message. */
|
|
2
6
|
export type OpenAssistantBlock = {
|
|
3
7
|
kind: 'thinking' | 'text';
|
|
@@ -3,4 +3,4 @@ var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});i
|
|
|
3
3
|
FROM node_rows n
|
|
4
4
|
LEFT JOIN run_events e ON n.pi_pid IS NULL AND e.run_id = n.run_id AND e.node_id = n.node_id
|
|
5
5
|
AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
|
|
6
|
-
WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers};
|
|
6
|
+
WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers,$ as viewTransport};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var J=Object.defineProperty;var l=(r,t)=>J(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as $,envNodeId as G,envProfileId as X,envWatcherDebounceMs as j,envWatcherTickMs as z,envWatcherBackstopMs as L}from"../shared/env.js";import{coalesceBrokerInbox as V,entryCards as Q}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Y,claimBrokerMail as K,brokerExtensionState as O,recordConversationWriteFault as Z}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ee}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as P}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as te,startupClaimsHeld as ie}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as ne}from"../core/runtime/broker/extension-abort.js";import{isDaemonTransportApiError as A,isTokenRevokedApiError as se}from"../api/errors.js";import{announceMessageOrigin as re,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as ae,generateAndCommitInitialName as de}from"./broker-local.js";import{emitEvent as D}from"../core/events/emit.js";import{errorClassFromError as oe}from"../core/events/errors.js";import{operationIdContext as g}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as x}from"../shared/generated-context.js";import{isProfilePaused as fe}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as H,brokerIdleTurnStart as le,brokerRunTurnBusy as he,brokerRunSteer as _,HELD_DEFERRED_INBOX_PROMPT_JOIN as ue}from"../core/runtime/broker/held-deferred-inbox.js";const E=64,U=16;let v,ce=0;class q extends Error{static{l(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function me(){return{tickMs:z(),debounceMs:j()}}l(me,"resolveCadence");function T(){const r=G();return r===void 0||r.trim()===""?void 0:r}l(T,"currentNodeId");function B(){const r=X();return r!==void 0&&r!==""&&fe(r)}l(B,"profilePaused");function S(r){try{return oe(r)}catch{return{class:"unknown"}}}l(S,"safeErrorClass");function w(r){try{D(r)}catch{}}l(w,"emitBestEffort");function I(r){try{g.fresh(t=>{w({...r,operation_id:t})})}catch{}}l(I,"emitFreshBestEffort");function F(r,t){try{g.run(r,()=>{w({...t,operation_id:r})})}catch{}}l(F,"emitStoredBestEffort");function pe(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}l(pe,"deliveryOrigin");function k(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-U;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,U),...i>0?{sourceOperationIdsOmitted:i}:{}}}l(k,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}l(b,"deliveryFields");function ye(r){F(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}l(ye,"emitDeliveryCompleted");function M(r,t,e,i){F(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:e,...b(t)}})}l(M,"emitDeliveryFailure");function R(r,t){F(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}l(R,"emitDeliveryAbandoned");function ge(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
|
|
2
|
-
`):""}l(ge,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}l(W,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}l(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}l(ve,"boundedRuntimeReason");class we{static{l(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;polledOk=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=$();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=l((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=C(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=T();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?be(i):"reload";W(i)||I({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=P();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=T();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of d)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=P().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),L()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),I({level:"error",event:t,outcome:"failed",error:i,error_class:S(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1,this.polledOk=!0}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,I({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:"poll"}});return}if(this.polledOk&&se(i)){this.clearTimer(),I({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ee(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?g.fresh(o=>{this.pendingHandoffs.push({...k([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=T();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||B()||this.pendingHandoffs.length>=E||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&_()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=_()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&_()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(u=>u.entry_id)),s=new Set(i.map(u=>u.entry_id)),d=t.filter(u=>n.has(u.entry_id)||s.has(u.entry_id)),a=this.isIdle()&&d.length>0&&d.every(u=>u.tier==="deferred"),f=this.visibleRoute(i)==="critical",o=!a&&!f&&e.length>0,m=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(m)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await O(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return V(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=E&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=k(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{g.fresh(o=>{a=o,w({level:"info",event:"inbox.delivery.started",operation_id:o,fields:b(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),M(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,m)=>{const u=s&&m===i.length-1;this.pi.sendMessage({customType:x,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:u?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,f)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:x,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((h,y)=>{this.isRunSteer(h)&&(o=y)});const m=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||m.some(h=>h.kind!=="message"||h.tier==="deferred"||(h.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};const u=this.digest(m,i),c=u.map(h=>({text:h.text,messageIds:h.entries.map(y=>y.entry_id),cards:h.cards}));if(_()?.accept(c)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};for(const h of u){const y=k(h.entries,"visible");g.fresh(N=>{w({level:"info",event:"inbox.delivery.started",operation_id:N,fields:b(y)}),this.pendingHandoffs.push({...y,operationId:N,settlesThroughBridge:!0})})}const p=new Set(m.map(h=>h.entry_id));for(const h of e.visibleEntries)p.has(h.entry_id)||n.add(h.entry_id);for(const h of e.hiddenEntries)n.add(h.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=d;for(const o of f)for(const m of o.entries)n.add(m.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),m=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(m==="inactive")return{inactive:!0,requeueEntryIds:n};if(m==="failed")for(const u of e.hiddenEntries)n.add(u.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const m of a.entries)n.add(m.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>E)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||B())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>E)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=k(i,e)}catch(f){this.raiseReadFatal("poll",f)}let d;try{await g.fresh(async f=>{d=f,w({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const o of n)await t.sendCustomMessage({customType:x,content:o,display:!0})})}catch(f){throw d===void 0&&this.raiseReadFatal("poll",f),M(d,s,"send",f),f}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(f=>f.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)M(d.operationId,d,"receipt_commit",s);return String(s?.message).startsWith("conversation_write_failed")&&(D({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"conversation_write_failed"}}),await Z(t,s),H()?.("conversation_write_failed",1)),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=!s&&this.pendingHandoffs.some(c=>c.awaitingDequeue!==void 0)&&await this.nodeRefreshing(t);if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const a=new Set(this.buffer.map(c=>c.entry_id)),f=new Set(d?this.pendingHandoffs.filter(c=>c.awaitingDequeue!==void 0).flatMap(c=>[...c.entryIds]):[]),o=this.pendingHandoffs.filter(c=>(n||c.settleAtAgentSettled!==!0)&&c.entryIds.every(p=>!f.has(p))),m=new Set(o.flatMap(c=>[...c.entryIds])),u=[...this.claims.keys()].filter(c=>s||m.has(c)&&!a.has(c));return u.length===0?"settled":(this.pendingCommit={handoffs:o,entryIds:u,receipts:u.map(c=>{const p=this.claims.get(c);return{delivery_id:p.delivery_id,attempts:p.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}async nodeRefreshing(t){try{return(await O(t)).node.intent==="refresh"}catch{return!0}}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){v?.dispose("reload",!1);const e=new we(r,t,++ce);v=e;const i=l(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}l(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}l(Ee,"registerCanvasInboxWatcher");var Be=Ee;export{Be as default,Ee as registerCanvasInboxWatcher};
|
|
2
|
+
`):""}l(ge,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}l(W,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}l(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}l(ve,"boundedRuntimeReason");class we{static{l(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;polledOk=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=$();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=l((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=C(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=T();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?be(i):"reload";W(i)||I({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=P();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=T();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of d)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=P().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),L()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),I({level:"error",event:t,outcome:"failed",error:i,error_class:S(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1,this.polledOk=!0}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,I({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:"poll"}});return}if(this.polledOk&&se(i)){this.clearTimer(),I({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ee(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?g.fresh(o=>{this.pendingHandoffs.push({...k([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=T();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||B()||this.pendingHandoffs.length>=E||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&_()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=_()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&_()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(u=>u.entry_id)),s=new Set(i.map(u=>u.entry_id)),d=t.filter(u=>n.has(u.entry_id)||s.has(u.entry_id)),a=this.isIdle()&&d.length>0&&d.every(u=>u.tier==="deferred"),f=this.visibleRoute(i)==="critical",o=!a&&!f&&e.length>0,m=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(m)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await O(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return V(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=E&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=k(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{g.fresh(o=>{a=o,w({level:"info",event:"inbox.delivery.started",operation_id:o,fields:b(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),M(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,m)=>{const u=s&&m===i.length-1;this.pi.sendMessage({customType:x,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:u?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,f)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:x,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((h,y)=>{this.isRunSteer(h)&&(o=y)});const m=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||m.some(h=>h.kind!=="message"||h.tier==="deferred"||(h.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};const u=this.digest(m,i),c=u.map(h=>({text:h.text,messageIds:h.entries.map(y=>y.entry_id),cards:h.cards}));if(_()?.accept(c)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};for(const h of u){const y=k(h.entries,"visible");g.fresh(N=>{w({level:"info",event:"inbox.delivery.started",operation_id:N,fields:b(y)}),this.pendingHandoffs.push({...y,operationId:N,settlesThroughBridge:!0})})}const p=new Set(m.map(h=>h.entry_id));for(const h of e.visibleEntries)p.has(h.entry_id)||n.add(h.entry_id);for(const h of e.hiddenEntries)n.add(h.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=d;for(const o of f)for(const m of o.entries)n.add(m.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),m=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(m==="inactive")return{inactive:!0,requeueEntryIds:n};if(m==="failed")for(const u of e.hiddenEntries)n.add(u.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const m of a.entries)n.add(m.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>E)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||B())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>E)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=k(i,e)}catch(f){this.raiseReadFatal("poll",f)}let d;try{await g.fresh(async f=>{d=f,w({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const o of n)await t.sendCustomMessage({customType:x,content:o,display:!0})})}catch(f){throw d===void 0&&this.raiseReadFatal("poll",f),M(d,s,"send",f),f}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(f=>f.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)M(d.operationId,d,"receipt_commit",s);return D({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await Z(t,s),H()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=!s&&this.pendingHandoffs.some(c=>c.awaitingDequeue!==void 0)&&await this.nodeRefreshing(t);if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const a=new Set(this.buffer.map(c=>c.entry_id)),f=new Set(d?this.pendingHandoffs.filter(c=>c.awaitingDequeue!==void 0).flatMap(c=>[...c.entryIds]):[]),o=this.pendingHandoffs.filter(c=>(n||c.settleAtAgentSettled!==!0)&&c.entryIds.every(p=>!f.has(p))),m=new Set(o.flatMap(c=>[...c.entryIds])),u=[...this.claims.keys()].filter(c=>s||m.has(c)&&!a.has(c));return u.length===0?"settled":(this.pendingCommit={handoffs:o,entryIds:u,receipts:u.map(c=>{const p=this.claims.get(c);return{delivery_id:p.delivery_id,attempts:p.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}async nodeRefreshing(t){try{return(await O(t)).node.intent==="refresh"}catch{return!0}}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){v?.dispose("reload",!1);const e=new we(r,t,++ce);v=e;const i=l(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}l(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}l(Ee,"registerCanvasInboxWatcher");var Be=Ee;export{Be as default,Ee as registerCanvasInboxWatcher};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.711",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -75,6 +75,7 @@
|
|
|
75
75
|
"scripts/git-credential-crtr",
|
|
76
76
|
"scripts/lib/isolation-env.mjs",
|
|
77
77
|
"scripts/lib/canvas-schema-gate.mjs",
|
|
78
|
+
"scripts/lib/install-source.mjs",
|
|
78
79
|
"scripts/lib/pack-args.mjs",
|
|
79
80
|
"scripts/lib/update-target.mjs",
|
|
80
81
|
"scripts/lib/runtime-deps-key.mjs",
|
|
@@ -157,8 +158,8 @@
|
|
|
157
158
|
},
|
|
158
159
|
"license": "UNLICENSED",
|
|
159
160
|
"dependencies": {
|
|
160
|
-
"@north-light/identity": "0.3.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.711",
|
|
162
|
+
"@north-light/plugin": "0.3.711",
|
|
162
163
|
"@earendil-works/chord": "1.5.2",
|
|
163
164
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
164
165
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
//
|
|
13
13
|
// PURITY (spec §3.1): Node built-ins + `src/api/*` only.
|
|
14
14
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
15
|
-
export const CONTRACT_LEVEL = '1.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.69';
|
|
16
16
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
17
17
|
export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
|
|
18
18
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
|
@@ -92,6 +92,7 @@ export function viewerOperationForSlash(name, builtin, canvas) {
|
|
|
92
92
|
case 'tutorial': return 'engine-drive';
|
|
93
93
|
// These run local `crtr node …`, rewrite this machine's tmux titles, or read this machine's MCP config:
|
|
94
94
|
// with --canvas they would act on a same-id local node or local state, not the remote node.
|
|
95
|
+
case 'recover':
|
|
95
96
|
case 'promote':
|
|
96
97
|
case 'rename':
|
|
97
98
|
case 'mcp': return 'local-host';
|
|
@@ -240,7 +240,7 @@ export class InputController {
|
|
|
240
240
|
this.editor.addToHistory(classification.trimmed);
|
|
241
241
|
this.editor.setText('');
|
|
242
242
|
this.clearPastedImages();
|
|
243
|
-
this.hooks.onMessageSent?.(expanded);
|
|
243
|
+
this.hooks.onMessageSent?.(expanded, false);
|
|
244
244
|
this.hooks.onPromptSent?.();
|
|
245
245
|
return;
|
|
246
246
|
}
|
|
@@ -264,7 +264,7 @@ export class InputController {
|
|
|
264
264
|
this.editor.setText('');
|
|
265
265
|
this.clearPastedImages();
|
|
266
266
|
if (delivery === 'prompt')
|
|
267
|
-
this.hooks.onMessageSent?.(expanded);
|
|
267
|
+
this.hooks.onMessageSent?.(expanded, true);
|
|
268
268
|
this.hooks.onPromptSent?.();
|
|
269
269
|
}
|
|
270
270
|
handleFollowUp() {
|
|
@@ -253,6 +253,9 @@ export class ChatView {
|
|
|
253
253
|
* welcome snapshot rebuild never drops them. */
|
|
254
254
|
pendingContainer = new MeasuredContainer();
|
|
255
255
|
pendingSends = [];
|
|
256
|
+
/** True while the viewer is redialing a closed connection. */
|
|
257
|
+
pendingUndelivered = false;
|
|
258
|
+
undeliveredNote;
|
|
256
259
|
/** Optional banner, above history and status in the viewport's flat source. */
|
|
257
260
|
bannerContainer;
|
|
258
261
|
/** Add one line to the banner after construction: a new root learns its id only when its create returns. */
|
|
@@ -1675,8 +1678,9 @@ export class ChatView {
|
|
|
1675
1678
|
this.bashComponent = undefined;
|
|
1676
1679
|
}
|
|
1677
1680
|
/** Show a message the person just sent as pending: gray text, no background,
|
|
1678
|
-
* until the engine echoes it as a user message.
|
|
1679
|
-
|
|
1681
|
+
* until the engine echoes it as a user message. `resend`: it went to the broker
|
|
1682
|
+
* socket, so a reconnect sends it again when the fresh snapshot does not hold it. */
|
|
1683
|
+
addPendingSend(text, resend = false) {
|
|
1680
1684
|
const trimmed = text.trim();
|
|
1681
1685
|
if (!trimmed)
|
|
1682
1686
|
return;
|
|
@@ -1686,9 +1690,40 @@ export class ChatView {
|
|
|
1686
1690
|
];
|
|
1687
1691
|
for (const part of parts)
|
|
1688
1692
|
this.pendingContainer.addChild(part);
|
|
1689
|
-
this.pendingSends.push({ text: trimmed, parts });
|
|
1693
|
+
this.pendingSends.push({ text: trimmed, parts, resend });
|
|
1694
|
+
this.refreshUndeliveredNote();
|
|
1690
1695
|
this.tui.requestRender();
|
|
1691
1696
|
}
|
|
1697
|
+
/** While the viewer redials, say under the pending messages that they were not delivered. */
|
|
1698
|
+
setPendingUndelivered(on) {
|
|
1699
|
+
this.pendingUndelivered = on;
|
|
1700
|
+
this.refreshUndeliveredNote();
|
|
1701
|
+
this.tui.requestRender();
|
|
1702
|
+
}
|
|
1703
|
+
refreshUndeliveredNote() {
|
|
1704
|
+
if (this.undeliveredNote !== undefined)
|
|
1705
|
+
this.pendingContainer.removeChild(this.undeliveredNote);
|
|
1706
|
+
this.undeliveredNote = undefined;
|
|
1707
|
+
if (!this.pendingUndelivered || !this.pendingSends.some((sent) => sent.resend))
|
|
1708
|
+
return;
|
|
1709
|
+
this.undeliveredNote = new Text(this.dimStyle('✗ not delivered — reconnecting; it is sent again when the connection is back'), 1, 0);
|
|
1710
|
+
this.pendingContainer.addChild(this.undeliveredNote);
|
|
1711
|
+
}
|
|
1712
|
+
/** After a reconnect: the pending messages sent to the broker socket that the fresh snapshot holds neither as a user message nor in its queue, oldest first. */
|
|
1713
|
+
unconfirmedSends(snapshot) {
|
|
1714
|
+
const seen = new Set([...(snapshot.queued?.steering ?? []), ...(snapshot.queued?.followUp ?? [])].map((text) => text.trim()));
|
|
1715
|
+
for (const message of snapshot.messages.slice(-50)) {
|
|
1716
|
+
if (message.role === 'user')
|
|
1717
|
+
seen.add(this.userMessageText(message).trim());
|
|
1718
|
+
}
|
|
1719
|
+
return this.pendingSends.filter((sent) => sent.resend && !seen.has(sent.text)).map((sent) => sent.text);
|
|
1720
|
+
}
|
|
1721
|
+
/** The pending messages were handed to a parked node's wake message, so a reconnect must not send them again. */
|
|
1722
|
+
stopResendingPendingSends() {
|
|
1723
|
+
for (const sent of this.pendingSends)
|
|
1724
|
+
sent.resend = false;
|
|
1725
|
+
this.refreshUndeliveredNote();
|
|
1726
|
+
}
|
|
1692
1727
|
/** The engine echoed a user message: the matching pending send landed. */
|
|
1693
1728
|
confirmPendingSend(text) {
|
|
1694
1729
|
// The engine may reshape the text (image blocks, wrapping); with no exact
|
|
@@ -1700,6 +1735,7 @@ export class ChatView {
|
|
|
1700
1735
|
const [sent] = this.pendingSends.splice(index, 1);
|
|
1701
1736
|
for (const part of sent.parts)
|
|
1702
1737
|
this.pendingContainer.removeChild(part);
|
|
1738
|
+
this.refreshUndeliveredNote();
|
|
1703
1739
|
}
|
|
1704
1740
|
/** A snapshot rebuild: drop pending sends whose text the history now holds. */
|
|
1705
1741
|
confirmPendingSendsIn(messages) {
|
|
@@ -1717,6 +1753,7 @@ export class ChatView {
|
|
|
1717
1753
|
for (const part of sent.parts)
|
|
1718
1754
|
this.pendingContainer.removeChild(part);
|
|
1719
1755
|
}
|
|
1756
|
+
this.refreshUndeliveredNote();
|
|
1720
1757
|
}
|
|
1721
1758
|
/** Swap the single active activity indicator (working/compaction/retry). */
|
|
1722
1759
|
setActivity(loader) {
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// session/layout-record.ts — one small file per viewed node recording where its viewer pane sits in tmux
|
|
2
|
+
// (session, window, pane position, cwd), so `/recover` can rebuild the viewer layout after a crash or
|
|
3
|
+
// reboot has taken the tmux server with it. This is machine-local tmux state, not canvas state: the
|
|
4
|
+
// daemon never reads it. A viewer rewrites its file whenever it starts or gains focus and deletes it only
|
|
5
|
+
// when the person detaches or the node finishes — a SIGHUP from a dying tmux server leaves it in place.
|
|
6
|
+
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { runtimeRoot } from '../../../core/layout.js';
|
|
9
|
+
import { paneCoordinates } from '../../../core/runtime/placement-tmux.js';
|
|
10
|
+
function recordsDir() { return join(runtimeRoot(), 'viewer-panes'); }
|
|
11
|
+
function recordPath(nodeId, canvas) { return join(recordsDir(), canvas === undefined ? `${nodeId}.json` : `${canvas.replace(/[^A-Za-z0-9._-]/g, '_')}--${nodeId}.json`); }
|
|
12
|
+
export function writeLayoutRecord(nodeId, pane, cwd, canvas) {
|
|
13
|
+
if (pane === undefined || pane === '')
|
|
14
|
+
return;
|
|
15
|
+
const where = paneCoordinates(pane);
|
|
16
|
+
if (where === null)
|
|
17
|
+
return;
|
|
18
|
+
const record = { nodeId, session: where.session, windowIndex: where.windowIndex, windowName: where.windowName, paneIndex: where.paneIndex, cwd, pane, ...(canvas === undefined ? {} : { canvas }) };
|
|
19
|
+
try {
|
|
20
|
+
mkdirSync(recordsDir(), { recursive: true });
|
|
21
|
+
writeFileSync(recordPath(nodeId, canvas), JSON.stringify(record));
|
|
22
|
+
}
|
|
23
|
+
catch { /* best-effort: a missing record only costs the recovery one pane */ }
|
|
24
|
+
}
|
|
25
|
+
/** Delete this node's record unless another viewer pane has since claimed it. */
|
|
26
|
+
export function removeLayoutRecord(nodeId, pane, canvas) {
|
|
27
|
+
try {
|
|
28
|
+
const current = JSON.parse(readFileSync(recordPath(nodeId, canvas), 'utf8'));
|
|
29
|
+
if (pane === undefined || current.pane === pane)
|
|
30
|
+
rmSync(recordPath(nodeId, canvas), { force: true });
|
|
31
|
+
}
|
|
32
|
+
catch { /* no record */ }
|
|
33
|
+
}
|
|
34
|
+
export function readLayoutRecords() {
|
|
35
|
+
let names;
|
|
36
|
+
try {
|
|
37
|
+
names = readdirSync(recordsDir());
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
const records = [];
|
|
43
|
+
for (const name of names) {
|
|
44
|
+
if (!name.endsWith('.json'))
|
|
45
|
+
continue;
|
|
46
|
+
try {
|
|
47
|
+
records.push(JSON.parse(readFileSync(join(recordsDir(), name), 'utf8')));
|
|
48
|
+
}
|
|
49
|
+
catch { /* skip a torn file */ }
|
|
50
|
+
}
|
|
51
|
+
return records;
|
|
52
|
+
}
|
|
@@ -12,6 +12,11 @@ import { AttachRefusedError, reconnectShouldGiveUp } from '../../../core/broker-
|
|
|
12
12
|
const RECONNECT_ACTIVE_DELAY_CAP_MS = 1_000;
|
|
13
13
|
/** Dormant by choice — low-rate patience. */
|
|
14
14
|
const RECONNECT_DORMANT_DELAY_MS = 3_000;
|
|
15
|
+
/** How long a probed connection has to answer before it is dropped and redialed. */
|
|
16
|
+
const PROBE_TIMEOUT_MS = 5_000;
|
|
17
|
+
/** The sleep check runs this often and sends nothing; a run that comes this much later than scheduled means the computer slept. */
|
|
18
|
+
const SLEEP_CHECK_MS = 5_000;
|
|
19
|
+
const SLEEP_GAP_MS = 15_000;
|
|
15
20
|
export function createReconnect(ctx, hooks) {
|
|
16
21
|
const { socket, canvasSource } = ctx;
|
|
17
22
|
let lastSocketError;
|
|
@@ -53,6 +58,18 @@ export function createReconnect(ctx, hooks) {
|
|
|
53
58
|
// `welcomed`: this session has been welcomed at least once. `refusedByRelay`: the relay closed the current connection as unavailable.
|
|
54
59
|
let welcomed = false;
|
|
55
60
|
let refusedByRelay = false;
|
|
61
|
+
// A probe went unanswered, so the close that follows is a lost connection, not a broker being replaced.
|
|
62
|
+
let connectionLost = false;
|
|
63
|
+
// A redial succeeded and its welcome has not arrived yet.
|
|
64
|
+
let awaitingRedialWelcome = false;
|
|
65
|
+
const probe = () => {
|
|
66
|
+
if (stopped || reconnecting || viewerDormant || !welcomed || hooks.isTornDown())
|
|
67
|
+
return;
|
|
68
|
+
void socket.probe(PROBE_TIMEOUT_MS).then((answered) => {
|
|
69
|
+
if (!answered)
|
|
70
|
+
connectionLost = true;
|
|
71
|
+
});
|
|
72
|
+
};
|
|
56
73
|
const sendHello = () => {
|
|
57
74
|
refusedByRelay = false;
|
|
58
75
|
socket.send({
|
|
@@ -75,8 +92,11 @@ export function createReconnect(ctx, hooks) {
|
|
|
75
92
|
const attemptReconnect = async (quiet = false) => {
|
|
76
93
|
reconnecting = true;
|
|
77
94
|
let noticed = !quiet;
|
|
95
|
+
const reconnectingNotice = connectionLost ? '↻ connection lost — reconnecting…' : '↻ node refreshing — reconnecting…';
|
|
78
96
|
if (noticed)
|
|
79
|
-
hooks.setNotice(
|
|
97
|
+
hooks.setNotice(reconnectingNotice, { sticky: true });
|
|
98
|
+
if (!quiet)
|
|
99
|
+
hooks.onReconnecting?.();
|
|
80
100
|
let delay = 200;
|
|
81
101
|
try {
|
|
82
102
|
while (!stopped && !hooks.isTornDown()) {
|
|
@@ -111,7 +131,7 @@ export function createReconnect(ctx, hooks) {
|
|
|
111
131
|
if (enteredDormancy)
|
|
112
132
|
hooks.onEnterDormancy();
|
|
113
133
|
if (noticed || !dormant) {
|
|
114
|
-
hooks.setNotice(deadOrCanceled ? `node is ${row?.status} — waiting for a revive` : dormant ? '' :
|
|
134
|
+
hooks.setNotice(deadOrCanceled ? `node is ${row?.status} — waiting for a revive` : dormant ? '' : reconnectingNotice, { sticky: !dormant });
|
|
115
135
|
noticed = !dormant;
|
|
116
136
|
}
|
|
117
137
|
try {
|
|
@@ -121,6 +141,8 @@ export function createReconnect(ctx, hooks) {
|
|
|
121
141
|
]);
|
|
122
142
|
if (!redialed || stopped || hooks.isTornDown())
|
|
123
143
|
return;
|
|
144
|
+
awaitingRedialWelcome = true;
|
|
145
|
+
connectionLost = false;
|
|
124
146
|
sendHello();
|
|
125
147
|
viewerDormant = false;
|
|
126
148
|
hooks.setNotice('');
|
|
@@ -146,10 +168,26 @@ export function createReconnect(ctx, hooks) {
|
|
|
146
168
|
};
|
|
147
169
|
const install = async () => {
|
|
148
170
|
socket.on('frame', (frame) => {
|
|
171
|
+
// The session's first welcome delivers the frames the viewer held for it, so only a later one is a reconnect.
|
|
172
|
+
const firstWelcome = !welcomed;
|
|
149
173
|
if (frame.type === 'welcome')
|
|
150
174
|
welcomed = true;
|
|
151
175
|
hooks.onFrame(frame);
|
|
176
|
+
if (frame.type === 'welcome' && awaitingRedialWelcome) {
|
|
177
|
+
awaitingRedialWelcome = false;
|
|
178
|
+
if (!firstWelcome)
|
|
179
|
+
hooks.onReconnected?.(frame.snapshot);
|
|
180
|
+
}
|
|
152
181
|
});
|
|
182
|
+
let checkedAt = Date.now();
|
|
183
|
+
const sleepCheck = setInterval(() => {
|
|
184
|
+
const now = Date.now();
|
|
185
|
+
if (now - checkedAt > SLEEP_CHECK_MS + SLEEP_GAP_MS)
|
|
186
|
+
probe();
|
|
187
|
+
checkedAt = now;
|
|
188
|
+
}, SLEEP_CHECK_MS);
|
|
189
|
+
sleepCheck.unref();
|
|
190
|
+
void stoppedSignal.then(() => clearInterval(sleepCheck));
|
|
153
191
|
socket.on('error', (err) => {
|
|
154
192
|
// Stash the reason; a 'close' follows and teardown converges there, where
|
|
155
193
|
// a broker-gone message prefers this over the generic text.
|
|
@@ -185,6 +223,7 @@ export function createReconnect(ctx, hooks) {
|
|
|
185
223
|
void attemptReconnect(true);
|
|
186
224
|
},
|
|
187
225
|
isDormant: () => viewerDormant,
|
|
226
|
+
probe,
|
|
188
227
|
lastSocketError: () => lastSocketError,
|
|
189
228
|
install,
|
|
190
229
|
stop: () => {
|
|
@@ -55,6 +55,8 @@ export function createTeardown(s, hooks) {
|
|
|
55
55
|
if (reason === 'detach')
|
|
56
56
|
socket.send({ type: 'bye' });
|
|
57
57
|
socket.close();
|
|
58
|
+
if (reason === 'detach' || reason === 'node-done')
|
|
59
|
+
hooks.forgetLayout();
|
|
58
60
|
restore();
|
|
59
61
|
// A clean detach leaves the broker running (the engine runs on) — the
|
|
60
62
|
// documented "detach leaves the broker running" contract. Teardown reaps
|