@north-light/cli 0.3.712 → 0.3.713

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/clients/attach/input/controller.d.ts +6 -0
  2. package/dist/clients/attach/input/controller.js +3 -3
  3. package/dist/clients/attach/input/local-files.d.ts +16 -0
  4. package/dist/clients/attach/input/local-files.js +6 -0
  5. package/dist/clients/attach/session/editor-frame.d.ts +2 -2
  6. package/dist/clients/attach/session/editor-frame.js +1 -1
  7. package/dist/clients/attach/viewer.js +406 -402
  8. package/dist/commands/node/bash.js +1 -1
  9. package/dist/core/bash-guard.d.ts +10 -0
  10. package/dist/core/bash-guard.js +4 -4
  11. package/dist/core/broker-client/client.d.ts +2 -2
  12. package/dist/core/conversation-store/row-store.js +1 -1
  13. package/dist/core/graph/documents.d.ts +5 -5
  14. package/dist/core/graph/documents.js +9 -9
  15. package/dist/core/graph/kinds/custom.js +2 -2
  16. package/dist/core/graph/kinds/document.js +4 -4
  17. package/dist/core/graph/kinds/environment.js +2 -2
  18. package/dist/core/graph/kinds/job.js +2 -2
  19. package/dist/core/graph/kinds/kind.d.ts +9 -1
  20. package/dist/core/graph/kinds/live-read.d.ts +4 -2
  21. package/dist/core/graph/kinds/live-read.js +1 -1
  22. package/dist/core/graph/kinds/node.js +5 -5
  23. package/dist/core/graph/kinds/owner.js +2 -2
  24. package/dist/core/runtime/bearings-render.d.ts +3 -0
  25. package/dist/core/runtime/bearings-render.js +7 -7
  26. package/dist/core/runtime/bearings.js +5 -5
  27. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  28. package/dist/core/runtime/broker/frame-read.d.ts +5 -1
  29. package/dist/core/runtime/broker/frame-read.js +1 -1
  30. package/dist/core/runtime/broker-protocol.d.ts +37 -2
  31. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  32. package/dist/daemon/api/handlers/llm.js +3 -3
  33. package/dist/daemon/api/handlers/objects.js +3 -3
  34. package/dist/daemon/api/handlers/reviews.js +1 -1
  35. package/dist/daemon/api/map.d.ts +6 -0
  36. package/dist/daemon/api/map.js +1 -1
  37. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  38. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  39. package/docs/ci-runner.md +4 -4
  40. package/package.json +3 -3
  41. package/packages/crouter-api/dist/clients/attach/input/controller.js +43 -12
  42. package/packages/crouter-api/dist/clients/attach/input/local-files.js +97 -0
  43. package/packages/crouter-api/dist/clients/attach/session/editor-frame.js +27 -8
  44. package/packages/crouter-api/dist/commands/node/bash.js +2 -2
  45. package/packages/crouter-api/dist/core/bash-guard.js +1 -1
  46. package/packages/crouter-api/dist/core/conversation-store/row-store.js +1 -1
  47. package/packages/crouter-api/dist/core/graph/documents.js +12 -24
  48. package/packages/crouter-api/dist/core/graph/kinds/custom.js +1 -3
  49. package/packages/crouter-api/dist/core/graph/kinds/document.js +8 -25
  50. package/packages/crouter-api/dist/core/graph/kinds/environment.js +1 -3
  51. package/packages/crouter-api/dist/core/graph/kinds/job.js +1 -3
  52. package/packages/crouter-api/dist/core/graph/kinds/node.js +1 -3
  53. package/packages/crouter-api/dist/core/graph/kinds/owner.js +1 -3
  54. package/packages/crouter-api/dist/core/runtime/bearings-render.js +11 -0
  55. package/packages/crouter-api/dist/core/runtime/bearings.js +6 -2
  56. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +5 -5
  57. package/packages/crouter-api/dist/daemon/api/map.js +1 -1
  58. package/packages/crouter-api/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +5 -5
  59. package/packages/crouter-api/package.json +1 -1
  60. package/packages/crouter-identity/package.json +1 -1
  61. package/packages/crouter-plugin/package.json +3 -3
  62. package/runtime.lock.json +14 -14
  63. package/packages/crouter-api/dist/core/graph/kinds/live-read.js +0 -11
  64. /package/dist/{clients/attach/chrome/git-info.d.ts → shared/git-status.d.ts} +0 -0
  65. /package/dist/{clients/attach/chrome/git-info.js → shared/git-status.js} +0 -0
@@ -1,2 +1,2 @@
1
1
  var k=Object.defineProperty;var d=(e,t)=>k(e,"name",{value:t,configurable:!0});import{join as g}from"node:path";import{liveExecutionForNode as b}from"../../core/canvas/executions.js";import{readOutputResult as h}from"../../core/runtime/output-result.js";import{ReviewOperationError as _}from"../../core/review/types.js";import{cronSinkDisplay as y}from"../../core/canvas/crons.js";import{isProfilePaused as x,profileDir as O,sanitizeProfileMetadata as D}from"../../core/profiles/manifest.js";import{nodeMetaPath as T,transcriptPath as E,viewSocketPath as S}from"../../core/canvas/paths.js";import{appForNode as c,contextDir as A,nodeAgentDir as R}from"../../core/canvas/node-agent-paths.js";import{readControllerWaits as N}from"../../core/canvas/waits.js";import{FinalizationError as z}from"../../core/feed/feed.js";import{NodeIdConflictError as C}from"../../core/runtime/nodes.js";import{ScopeDeniedError as j}from"../../core/scopes.js";import{isBeneathRefusal as q}from"../../core/spaces/open-beneath.js";import{CrtrError as a}from"../../core/errors.js";import{WorktreeError as F}from"../../core/worktree.js";import{ApiError as I}from"../../api/errors.js";import{RunError as s}from"../../core/runs/operations.js";import{ExitCode as o}from"../../types.js";function ve(e,t){const{report:n}=e;return{stores:n.stores.map(i=>({root:i.root,owner:{...i.owner},docs:i.docs,...i.skipped===void 0?{}:{skipped:i.skipped}})),counts:n.counts,rewrites:n.rewrites,dropped_fields:n.droppedFields,skipped:n.skipped,resolutions:n.resolutions.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),blockers:e.blockers.map(i=>({kind:i.kind,message:i.message,paths:i.paths})),dryRun:e.dryRun,pending:e.pending,resumed:t.resumed,...t.resumeError===void 0?{}:{resume_error:t.resumeError}}}d(ve,"toMigrateStateDTO");async function P(e){try{return await h(e)??null}catch{return null}}d(P,"readStructuredResult");function U(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}d(U,"toNodeOutcomeSummaryDTO");async function f(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const n=e.final_report??null,i={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:n===null?null:`${e.node_id}/${n}`,structured_result:e.outcome_kind==="result"?await P(e.node_id):null,detail:t};return e.outcome_kind==="result"?{...i,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...i,kind:"failure",reason:"declined",declined:t?.declined??null}:{...i,kind:"failure",reason:e.outcome_reason,declined:null}}d(f,"toNodeOutcomeDTO");async function ke(e){const t=await f(e);return t===null||t.reason==="parked"?null:t.kind==="result"||t.reason==="finished"?{...t,kind:"result",reason:"finalized",declined:null}:t.reason==="declined"?{...t,reason:"declined",details:t.declined}:t.reason==="deadline_exceeded"?{...t,reason:"deadline_exceeded",declined:null}:t.reason==="cap_exhausted"?{...t,reason:"cap_exhausted",declined:null}:t.reason==="closed"||t.reason==="stranded"||t.reason==="retired"?{...t,reason:"canceled",declined:null}:{...t,reason:"runtime_error",declined:null,details:{crouter_reason:t.reason}}}d(ke,"toRunOutcomeDTO");function ge(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}d(ge,"toOutcomeDeliveryDTO");function be(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,status:e.status,frozen_at:e.frozen_at,pi_pid:e.pi_pid,telemetry_context_tokens:e.telemetry_context_tokens,telemetry_last_activity:e.telemetry_last_activity,fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming}}d(be,"toGraphNodeDTO");async function he(e,t,n){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,scopes:e.scopes,isolated:e.isolated,grantee:e.grantee??await c(e.node_id),profile_paused:t,parent:e.parent,created:e.created,intent:e.intent,waiting_for:n,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,last_settled_at:e.last_settled_at??null,outcome:U(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}d(he,"toNodeSummaryDTO");function G(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(n=>n.node_id),subscribers:t.subscribers.map(n=>n.node_id),children:[...t.children]}}d(G,"toNodeEdgesDTO");async function M(e,t){return{node_dir:await R(e,t),context_dir:await A(e,t),meta_path:T(e),transcript_path:E(e),view_socket:S(e)}}d(M,"toNodePathsDTO");function W(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}d(W,"toNodeWorktreeDTO");async function ye(e,t){const n=await c(e.node_id),i={node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:n,profile_paused:x(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:(await N([e.node_id])).get(e.node_id)?.controllerId??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,runner:(await b(e.node_id))?.runner??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,last_settled_at:e.last_settled_at??null,outcome:await f(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:G(e,t),paths:await M(e.node_id,n)};return e.description!==void 0&&(i.description=e.description),e.title!==void 0&&(i.title=e.title),e.icon!==void 0&&(i.icon=e.icon),e.cycles!==void 0&&(i.cycles=e.cycles),i.context_tokens=e.telemetry_context_tokens??e.telemetry_tokens_in??null,e.pi_session_id!==void 0&&(i.pi_session_id=e.pi_session_id??null),i.model_override=e.model_override??null,e.pi_session_file!==void 0&&(i.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(i.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(i.worktree=W(e.managed_worktree)),i}d(ye,"toNodeDetailDTO");function xe(e,t,n,i){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:n,outcome:t.outcome,ready:i}}d(xe,"toReviveResultDTO");function Oe(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}d(Oe,"toCloseResultDTO");function De(e,t,n){const i={report:e.report,notified:[...e.deliveredTo]};return t!==void 0&&(i.transitioned=t),n!==void 0&&(i.worktree_auto_dropped=!0,i.worktree_auto_dropped_path=n),i}d(De,"toReportResultDTO");function Te(e){return{node_id:e.node_id,active:e.active,created:e.created}}d(Te,"toSubscriptionDTO");function B(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}d(B,"envKeys");function Ee(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,grant_id:e.grant_id,scopes:e.scopes,origin_run_id:e.origin_run_id,isolated:e.isolated,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:B(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:y(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}d(Ee,"toCronDTO");function Se(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}d(Se,"toCronRunDTO");function Ae(e){return{id:e.profileId,app:e.manifest.grantee??"app:terminal",name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),delivery_limits:{...e.manifest.delivery_limits},paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:D(e.manifest.metadata),default_dir:null,created_at:e.manifest.created_at,last_used_at:e.manifest.last_used_at,repositories:[],profile_path:O(e.profileId)}}d(Ae,"toProfileDTO");function p(e,t={}){const n={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.document_name!==null&&(n.document=e.document_name),e.opened_at!==null&&(n.opened_at=e.opened_at),e.submit_requested_at!==null&&(n.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(n.approved_at=e.approved_at),e.changed!==null&&(n.changed=e.changed),e.comments_total!==null&&(n.comments_total=e.comments_total),e.comments_unresolved!==null&&(n.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(n.canceled_at=e.canceled_at),e.cancel_reason!==null&&(n.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(n.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(n.result_path=t.result_path),e.delivery_error!==null&&(n.delivery_error=e.delivery_error),e.projection_error!==null&&(n.projection_error=e.projection_error),n}d(p,"toReviewDTO");function Re(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}d(Re,"toReviewCommentDTO");function L(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}d(L,"toPageFeedbackCommentDTO");function Ne(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(L)}}d(Ne,"toPageFeedbackDTO");function ze(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}d(ze,"toReviewCommentEventDTO");function Ce(e){return{document:e.document,file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(n=>({...n})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}d(Ce,"toFeedbackResultDTO");const $=!0,w=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},stale_revision:{status:409,code:"stale_revision"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},quote_not_found:{status:409,code:"quote_not_found"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"}});function K(e){const t=m(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof z)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof C)return{status:409,code:"node_id_exists"};if(t instanceof j)return{status:403,code:"scope_denied"};if(q(t))return{status:400,code:"invalid_request"};if(t instanceof _)return w[t.code];if(t instanceof a)return["kind_owned","name_taken","hop_limit","not_a_queue"].includes(t.code)?{status:409,code:t.code}:t.code==="invalid_publish_token"?{status:401,code:t.code}:t.code==="forbidden"||t.code==="argv_forbidden"||t.code==="scope_missing"?{status:403,code:t.code}:{status:J(t.exitCode),code:t.code};if(t instanceof Error){const n=t.message;if(/unknown node/i.test(n))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(n))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(n))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}d(K,"errorToStatus");function m(e){if(!(e instanceof F))return e;const t=e.code==="unknown_node"?o.NOT_FOUND:o.GENERAL,n={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(n.received=e.detail),new a(e.code,e.message,t,n)}d(m,"normalizeThrow");function V(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...n}=e.detail;return{...n,review:H(t)}}d(V,"reviewErrorDetails");function H(e){return e.state!=="approved"?p(e):p(e,{result_path:g(e.review_dir,"result.json")})}d(H,"terminalConflictReviewDTO");function J(e){switch(e){case o.NOT_FOUND:return 404;case o.USAGE:return 400;case o.AMBIGUOUS:return 400;case o.NETWORK:return 503;case o.GENERAL:return 400;default:return 500}}d(J,"statusForExitCode");function Q(e){const n=(e instanceof Error?e.message:String(e)).split(`
2
- `,1)[0].trim();return n===""?"internal error":n.length>500?`${n.slice(0,497)}\u2026`:n}d(Q,"boundedCause");function je(e){const t=m(e),{status:n,code:i}=K(t);if(n>=500){const u={error:{code:i,message:Q(t),origin:"runtime"}};return t instanceof s&&(u.error.retryable=t.retryable),{status:n,body:u}}const v=t instanceof Error?t.message:String(t),l=t instanceof _?V(t):(t instanceof a||t instanceof I||t instanceof s)&&t.details!==void 0?t.details:void 0,r={error:{code:i,message:v,origin:"runtime"}};return l!==void 0&&(r.error.details=l),t instanceof s&&(t.param&&(r.error.param=t.param),t.scope&&(r.error.scope=t.scope),r.error.retryable=t.retryable),{status:n,body:r}}d(je,"toErrorBody");export{w as REVIEW_ERROR_MAP,K as errorToStatus,Oe as toCloseResultDTO,Ee as toCronDTO,Se as toCronRunDTO,je as toErrorBody,Ce as toFeedbackResultDTO,be as toGraphNodeDTO,ve as toMigrateStateDTO,ye as toNodeDetailDTO,G as toNodeEdgesDTO,f as toNodeOutcomeDTO,U as toNodeOutcomeSummaryDTO,M as toNodePathsDTO,he as toNodeSummaryDTO,W as toNodeWorktreeDTO,ge as toOutcomeDeliveryDTO,L as toPageFeedbackCommentDTO,Ne as toPageFeedbackDTO,Ae as toProfileDTO,De as toReportResultDTO,Re as toReviewCommentDTO,ze as toReviewCommentEventDTO,p as toReviewDTO,xe as toReviveResultDTO,ke as toRunOutcomeDTO,Te as toSubscriptionDTO};
2
+ `,1)[0].trim();return n===""?"internal error":n.length>500?`${n.slice(0,497)}\u2026`:n}d(Q,"boundedCause");function je(e){const t=m(e),{status:n,code:i}=K(t);if(n>=500){const u={error:{code:i,message:Q(t),origin:"runtime"}};return t instanceof s&&(u.error.retryable=t.retryable),{status:n,body:u}}const v=t instanceof Error?t.message:String(t),l=t instanceof _?V(t):(t instanceof a||t instanceof I||t instanceof s)&&t.details!==void 0?t.details:void 0,r={error:{code:i,message:v,origin:"runtime"}};return l!==void 0&&(r.error.details=l),t instanceof s&&(t.param&&(r.error.param=t.param),t.scope&&(r.error.scope=t.scope),r.error.retryable=t.retryable),{status:n,body:r}}d(je,"toErrorBody");export{w as REVIEW_ERROR_MAP,Q as boundedCause,K as errorToStatus,Oe as toCloseResultDTO,Ee as toCronDTO,Se as toCronRunDTO,je as toErrorBody,Ce as toFeedbackResultDTO,be as toGraphNodeDTO,ve as toMigrateStateDTO,ye as toNodeDetailDTO,G as toNodeEdgesDTO,f as toNodeOutcomeDTO,U as toNodeOutcomeSummaryDTO,M as toNodePathsDTO,he as toNodeSummaryDTO,W as toNodeWorktreeDTO,ge as toOutcomeDeliveryDTO,L as toPageFeedbackCommentDTO,Ne as toPageFeedbackDTO,Ae as toProfileDTO,De as toReportResultDTO,Re as toReviewCommentDTO,ze as toReviewCommentEventDTO,p as toReviewDTO,xe as toReviveResultDTO,ke as toRunOutcomeDTO,Te as toSubscriptionDTO};
@@ -1 +1 @@
1
- var g=Object.defineProperty;var d=(s,t)=>g(s,"name",{value:t,configurable:!0});import{MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as p}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as F}from"../../../core/events/operation-id.js";import{readInterruptedTurn as A}from"../../../core/canvas/recovery.js";import{isProfilePaused as f}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as m}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as C,isParkedResident as S}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as O}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as k}from"./respawn-policy.js";import{asNodePerson as G,NodePersonUnresolvedError as R}from"./node-person.js";import{handleTerminatingRow as H}from"./terminating.js";import{wantsExecution as q}from"./wants-execution.js";import{enactRequestedStops as j}from"./requested-stops.js";import{endRemoteExecutionIfGone as J,recoverLaunching as K,wakeResident as Q}from"./remote-wake.js";import{isDrained as V}from"../../drain.js";function X(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}d(X,"isTerminal");const Y=12e4;function Z(s,t,e){const i=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return i>0&&t-i<Y&&e?.state!=="exited"}d(Z,"isLaunchInFlight");async function b(s){const t=await p(s);return t!==null&&t.state==="running"&&t.pid!=null&&N(t.pid,t.processIdentity)==="dead"?t:null}d(b,"executionWithDeadPid");class Ie{static{d(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(t,e){return await j(t),await this.pass(t,e)}async runNode(t,e,i){await this.pass(t,{rows:[e],fleet:i})}async pass(t,e){const i=[];for(const n of e.rows)await F.fresh(async()=>{try{await G(n,()=>this.classifyRow(t,n,e,i))}catch(a){const l=n.node_id;E({level:a instanceof R?"warn":"error",event:a instanceof R?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...L(l)?{node_id:l}:{fields:{affected_node_id:l}},error:a})}});return await V()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(t,{fleet:e.fleet,candidates:i})}async classifyRow(t,e,i,n){const a=e.node_id;if(X(e)){if(H(e,await i.fleet.has(a)))return;if(S(e)&&!await i.fleet.has(a)&&!f(e.profile_id)&&!await I(a)&&!k(e,t)&&await m(a)){n.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const r=await b(a);r!==null&&await P(r.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await w(a):n.push({row:e,enact:"thaw"}));return}if(await i.fleet.has(a)){const r=await p(a);if(r?.runner!==void 0&&r.runner!=="process"&&r.state==="running"&&!f(e.profile_id)&&await m(a))try{if(await Q(r)==="lost")return}catch(o){if(o instanceof x)return;throw o}else r?.runner==="blaxel"&&r.state==="running"&&await J(r);if(await i.fleet.has(a)){f(e.profile_id)?await i.fleet.interruptForProfilePause(a):await this.thawMark(e);return}}if(await K(a,t))return;if(f(e.profile_id)){await this.freezeLane.endEpisode(a);return}if(await I(a))return;const l=e.pi_pid==null?await v(a):null,u=l!==null&&D(l),h=l!==null&&!u&&M(l),_=e.pi_pid!=null?await b(a):null,y=u||h||_!==null;if(y&&!await i.fleet.hasProfilePauseInterruption(a)){const r=_??l;r!==null&&await P(r.executionId,{reason:"observed-dead"});const o=await p(a);if(o!==null&&o.executionId!==r?.executionId)return}if(!await q(e)){await this.thawMark(e),await this.settleParked(e);return}if(k(e,t))return;if(e.status==="idle"&&C(e)&&await m(a)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!u||e.frozen_at!=null)&&!h){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){n.push({row:e,enact:"thaw"});return}if(await i.fleet.isClaimed(a)||Z(e,t,await v(a)))return;E({level:"warn",event:"node.lifecycle.stranded_launch",node_id:a}),n.push({row:e,enact:"thaw"});return}if(!y)return;const c=O(await z(a),(await A(a))?.interrupted===!0,await U(a));if(c==="respawn-fresh"||c==="respawn-cycle"||c==="respawn-resume"){n.push({row:e,enact:"policy"});return}await i.fleet.applyDeadRowPolicy(a),await this.thawMark(e)}async thawMark(t){t.frozen_at!=null&&await w(t.node_id)}async settleParked(t){if(t.status!=="idle")return;await this.freezeLane.endEpisode(t.node_id);const e=await W(t.node_id,t.lifecycle);e!=="release"&&await T(t.node_id,e)}}export{Y as LAUNCH_GRACE_MS,Ie as NodeLifecycleReconciler,Z as isLaunchInFlight};
1
+ var g=Object.defineProperty;var d=(s,t)=>g(s,"name",{value:t,configurable:!0});import{MachineOfflineError as x}from"../../../core/runtime/runner/machine/ops.js";import{clearFrozen as w,getNode as z}from"../../../core/canvas/index.js";import{isSafeNodeId as L}from"../../../core/canvas/paths.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{endExecution as P,hasAbsorbedProfilePauseStop as M,hasObservedExit as D,latestExecutionForNode as v,liveExecutionForNode as p}from"../../../core/canvas/executions.js";import{emitEvent as E}from"../../../core/events/emit.js";import{operationIdContext as F}from"../../../core/events/operation-id.js";import{readInterruptedTurn as A}from"../../../core/canvas/recovery.js";import{isProfilePaused as f}from"../../../core/profiles/manifest.js";import{isRecoveryHeld as I}from"../../../core/runtime/recovery-hold.js";import{hasUnseenWakeMail as m}from"../../../core/canvas/deliveries.js";import{hasIdleReleaseIntent as C,isParkedResident as S}from"../../../core/runtime/lifecycle.js";import{classifyDeadNode as O}from"../../fleet.js";import{applyParkEvent as T,hasPendingWake as U,parkEvent as W}from"../live-obligation.js";import{FreezeLaneReconciler as B}from"./freeze-lane.js";import{isInBackoff as k}from"./respawn-policy.js";import{asNodePerson as G,NodePersonUnresolvedError as R}from"./node-person.js";import{handleTerminatingRow as H}from"./terminating.js";import{wantsExecution as q}from"./wants-execution.js";import{enactRequestedStops as j}from"./requested-stops.js";import{endRemoteExecutionIfGone as J,recoverLaunching as K,wakeResident as Q}from"./remote-wake.js";import{isDrained as V}from"../../drain.js";function X(s){return s.status==="done"||s.status==="canceled"||s.status==="dead"}d(X,"isTerminal");const Y=12e4;function Z(s,t,e){const i=Math.max(...[s.created,s.launched_at].map(n=>n==null?0:Date.parse(n)||0));return i>0&&t-i<Y&&e?.state!=="exited"}d(Z,"isLaunchInFlight");async function b(s){const t=await p(s);return t?.runner==="process"&&t.state==="running"&&t.pid!=null&&N(t.pid,t.processIdentity)==="dead"?t:null}d(b,"executionWithDeadPid");class Ie{static{d(this,"NodeLifecycleReconciler")}freezeLane=new B;async run(t,e){return await j(t),await this.pass(t,e)}async runNode(t,e,i){await this.pass(t,{rows:[e],fleet:i})}async pass(t,e){const i=[];for(const n of e.rows)await F.fresh(async()=>{try{await G(n,()=>this.classifyRow(t,n,e,i))}catch(a){const o=n.node_id;E({level:a instanceof R?"warn":"error",event:a instanceof R?"node.lifecycle.person_unresolved":"node.lifecycle.classify_failed",...L(o)?{node_id:o}:{fields:{affected_node_id:o}},error:a})}});return await V()?{stalled:0,waitingOnMail:0}:this.freezeLane.run(t,{fleet:e.fleet,candidates:i})}async classifyRow(t,e,i,n){const a=e.node_id;if(X(e)){if(H(e,await i.fleet.has(a)))return;if(S(e)&&!await i.fleet.has(a)&&!f(e.profile_id)&&!await I(a)&&!k(e,t)&&await m(a)){n.push({row:e,enact:"reopen"});return}if(e.pi_pid!=null){const r=await b(a);r!==null&&await P(r.executionId,{reason:"observed-dead"})}e.frozen_at!=null&&(e.final_report!=null||e.status==="dead"?await w(a):n.push({row:e,enact:"thaw"}));return}if(await i.fleet.has(a)){const r=await p(a);if(r?.runner!==void 0&&r.runner!=="process"&&r.state==="running"&&!f(e.profile_id)&&await m(a))try{if(await Q(r)==="lost")return}catch(l){if(l instanceof x)return;throw l}else r?.runner==="blaxel"&&r.state==="running"&&await J(r);if(await i.fleet.has(a)){f(e.profile_id)?await i.fleet.interruptForProfilePause(a):await this.thawMark(e);return}}if(await K(a,t))return;if(f(e.profile_id)){await this.freezeLane.endEpisode(a);return}if(await I(a))return;const o=e.pi_pid==null?await v(a):null,u=o!==null&&D(o),h=o!==null&&!u&&M(o),_=e.pi_pid!=null?await b(a):null,y=u||h||_!==null;if(y&&!await i.fleet.hasProfilePauseInterruption(a)){const r=_??o;r!==null&&await P(r.executionId,{reason:"observed-dead"});const l=await p(a);if(l!==null&&l.executionId!==r?.executionId)return}if(!await q(e)){await this.thawMark(e),await this.settleParked(e);return}if(k(e,t))return;if(e.status==="idle"&&C(e)&&await m(a)){n.push({row:e,enact:"idle-release"});return}if(e.pi_pid==null&&(!u||e.frozen_at!=null)&&!h){if(e.respawn_not_before!=null){n.push({row:e,enact:"policy"});return}if(e.frozen_at!=null){n.push({row:e,enact:"thaw"});return}if(await i.fleet.isClaimed(a)||Z(e,t,await v(a)))return;E({level:"warn",event:"node.lifecycle.stranded_launch",node_id:a}),n.push({row:e,enact:"thaw"});return}if(!y)return;const c=O(await z(a),(await A(a))?.interrupted===!0,await U(a));if(c==="respawn-fresh"||c==="respawn-cycle"||c==="respawn-resume"){n.push({row:e,enact:"policy"});return}await i.fleet.applyDeadRowPolicy(a),await this.thawMark(e)}async thawMark(t){t.frozen_at!=null&&await w(t.node_id)}async settleParked(t){if(t.status!=="idle")return;await this.freezeLane.endEpisode(t.node_id);const e=await W(t.node_id,t.lifecycle);e!=="release"&&await T(t.node_id,e)}}export{Y as LAUNCH_GRACE_MS,Ie as NodeLifecycleReconciler,Z as isLaunchInFlight};
@@ -1,2 +1,2 @@
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 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};
1
+ var W=Object.defineProperty;var h=(r,t)=>W(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as J,envNodeId as $,envProfileId as G,envWatcherDebounceMs as X,envWatcherTickMs as j,envWatcherBackstopMs as z}from"../shared/env.js";import{coalesceBrokerInbox as L,entryCards as V}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Y,claimBrokerMail as K,brokerExtensionState as Q,recordConversationWriteFault as Z}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ee}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as N}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 k}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as ae,generateAndCommitInitialName as de}from"./broker-local.js";import{emitEvent as P}from"../core/events/emit.js";import{errorClassFromError as oe}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as C}from"../shared/generated-context.js";import{isProfilePaused as fe}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as D,brokerIdleTurnStart as le,brokerRunTurnBusy as he,brokerRunSteer as w,HELD_DEFERRED_INBOX_PROMPT_JOIN as ue}from"../core/runtime/broker/held-deferred-inbox.js";const _=64,O=16;let b,ce=0;class H extends Error{static{h(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function me(){return{tickMs:j(),debounceMs:X()}}h(me,"resolveCadence");function x(){const r=$();return r===void 0||r.trim()===""?void 0:r}h(x,"currentNodeId");function U(){const r=G();return r!==void 0&&r!==""&&fe(r)}h(U,"profilePaused");function T(r){try{return oe(r)}catch{return{class:"unknown"}}}h(T,"safeErrorClass");function v(r){try{P(r)}catch{}}h(v,"emitBestEffort");function E(r){try{y.fresh(t=>{v({...r,operation_id:t})})}catch{}}h(E,"emitFreshBestEffort");function S(r,t){try{y.run(r,()=>{v({...t,operation_id:r})})}catch{}}h(S,"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}}))}}h(pe,"deliveryOrigin");function I(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-O;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,O),...i>0?{sourceOperationIdsOmitted:i}:{}}}h(I,"deliveryFacts");function g(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}}}h(g,"deliveryFields");function ye(r){S(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:g(r)})}h(ye,"emitDeliveryCompleted");function F(r,t,e,i){S(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:T(i),fields:{stage:e,...g(t)}})}h(F,"emitDeliveryFailure");function M(r,t){S(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...g(r)}})}h(M,"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
+ `):""}h(ge,"messageText");function B(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(B,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(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}h(ve,"boundedRuntimeReason");class we{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=J();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=h((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=k(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=x();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=B(i)?be(i):"reload";B(i)||E({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=N();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=x();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()&&(b=void 0);for(const a of d)M(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return b===this&&b.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=N().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"),z()),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 H(e,i),this.clearTimer(),E({level:"error",event:t,outcome:"failed",error:i,error_class:T(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 H)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}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,E({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:T(i),fields:{stage:"poll"}});return}if(se(i)){this.clearTimer(),E({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),D()?.("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(l=>l.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const l=a.entry.entry_id;this.claims.has(l)||(a.entry=ee(a.entry,t),this.claims.set(l,a),a.handoff==="inherited"&&!i?y.fresh(o=>{this.pendingHandoffs.push({...I([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=x();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||U()||this.pendingHandoffs.length>=_||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))&&w()?.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=w()?.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))&&w()?.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(f=>f.entry_id)),s=new Set(i.map(f=>f.entry_id)),d=t.filter(f=>n.has(f.entry_id)||s.has(f.entry_id)),a=this.isIdle()&&d.length>0&&d.every(f=>f.tier==="deferred"),l=this.visibleRoute(i)==="critical",o=!a&&!l&&e.length>0,c=!a&&!l&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(c)}}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 Q(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(...V(n));return i}digest(t,e){try{return L(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=_&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=I(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{y.fresh(o=>{a=o,v({level:"info",event:"inbox.delivery.started",operation_id:o,fields:g(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),F(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const l={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(l),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&M(l,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",l=a===void 0||i.length===0?void 0:k(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,c)=>{const f=s&&c===i.length-1;this.pi.sendMessage({customType:C,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:f?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,l)}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:C,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(l=>l.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?k(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((u,p)=>{this.isRunSteer(u)&&(o=p)});const c=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||c.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const f=this.digest(c,i),m=f.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(w()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of f){const p=I(u.entries,"visible");y.fresh(R=>{v({level:"info",event:"inbox.delivery.started",operation_id:R,fields:g(p)}),this.pendingHandoffs.push({...p,operationId:R,settlesThroughBridge:!0})})}const q=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)q.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...l]=d;for(const o of l)for(const c of o.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const f of e.hiddenEntries)n.add(f.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 c of a.entries)n.add(c.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>_)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||U())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>_)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=I(i,e)}catch(l){this.raiseReadFatal("poll",l)}let d;try{await y.fresh(async l=>{d=l,v({level:"info",event:"inbox.delivery.started",operation_id:l,fields:g(s)});for(const o of n)await t.sendCustomMessage({customType:C,content:o,display:!0})})}catch(l){throw d===void 0&&this.raiseReadFatal("poll",l),F(d,s,"send",l),l}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&&M(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(l=>l.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)F(d.operationId,d,"receipt_commit",s);return P({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),D()?.("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=new Set(this.buffer.map(f=>f.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(f=>f.awaitingDequeue!==void 0).flatMap(f=>[...f.entryIds])),l=this.pendingHandoffs.filter(f=>(n||f.settleAtAgentSettled!==!0)&&f.entryIds.every(m=>!a.has(m))),o=new Set(l.flatMap(f=>[...f.entryIds])),c=[...this.claims.keys()].filter(f=>s||o.has(f)&&!d.has(f));return c.length===0?"settled":(this.pendingCommit={handoffs:l,entryIds:c,receipts:c.map(f=>{const m=this.claims.get(f);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}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){b?.dispose("reload",!1);const e=new we(r,t,++ce);b=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}h(Ee,"registerCanvasInboxWatcher");var qe=Ee;export{qe as default,Ee as registerCanvasInboxWatcher};
package/docs/ci-runner.md CHANGED
@@ -36,7 +36,7 @@ gh variable set CRTR_CI_RUNNER --body self-hosted -R Northlight-Systems/crouter
36
36
  gh variable delete CRTR_CI_RUNNER -R Northlight-Systems/crouter # fall back to macos-latest
37
37
  ```
38
38
 
39
- It takes effect on the next run; no commit is needed. **Without the `CI_RUNNER_READ_TOKEN` secret (below), routing cannot see the minis: if they are offline, jobs queue until they return — delete the variable.** Cancel and re-run anything already queued. There is one `macos` job; it runs, in sequence, each lane that has a selected laptop-only file.
39
+ It takes effect on the next run; no commit is needed. **Without the `CI_RUNNER_READ_TOKEN` secret (below), routing cannot see the minis: if they are offline, jobs queue until they return — delete the variable.** Cancel and re-run anything already queued. There is one `macos` job per lane that has a selected laptop-only file (`macos unit`, `macos integration`, `macos seam`), plus `macos build-output` (the macOS concurrent-build test) only when the diff reaches the build (`scripts/build*`, `atomic-swap.c`, `pack-minify.mjs`, `runtime-lock.mjs`, `ensure-native-linux.mjs`, the patch and `check-*` scripts the build runs, `package.json`, the lockfile, `runtime.lock.json`, package manifests, tsconfigs, `test.yml`; the selector's `macos_build_output` output) or when there is no release tag to diff against; they run in parallel. Each macOS lane runs only the tests tagged `laptopOnly`, not whole files (a preload, `scripts/laptop-only-filter.mjs`, skips the rest), and fails if it ran none.
40
40
 
41
41
  ### Routing: minis first, hosted when none is free
42
42
 
@@ -83,7 +83,7 @@ Installing and upgrading: get a registration token (`gh api -X POST repos/Northl
83
83
 
84
84
  ## No double run on `main`
85
85
 
86
- `publish.yml` starts with a `gate` job. It reads the pushed commit's **git tree** and looks for a workflow artifact named `tested-tree-<tree>`. `test.yml`'s final `tested` job creates that artifact only in mode `full`, after `checks` and every `linux` shard pass and every `macos` job passed (or was skipped because this is a pull request, where macOS never runs), on every such pull request run and on every run of Publish's own `tests` job. A tree released from a pull request's record therefore never ran its `laptopOnly` tests on macOS.
86
+ `publish.yml` starts with a `gate` job. It reads the pushed commit's **git tree** and looks for a workflow artifact named `tested-tree-<tree>`. `test.yml`'s final `tested` job creates that artifact only in mode `full`, after `build`, `checks` and every `linux` shard pass and every `macos` job (including `macos build-output`) passed (or was skipped because this is a pull request, where macOS never runs), on every such pull request run and on every run of Publish's own `tests` job. A tree released from a pull request's record therefore never ran its `laptopOnly` tests on macOS.
87
87
 
88
88
  - Rebase-merging a PR whose tested merge ref has the same tree as the resulting `main` commit → artifact found → `tests` is skipped and `publish` proceeds.
89
89
  - A direct push to `main`, or a merge after `main` moved (a different tree from the one the PR run tested) → no artifact → the full suite runs exactly as before. A release commit (`chore: release …`, pushed by Publish itself) changes the tree, so a PR not updated since before the latest release runs the suite once on merge; update the branch to avoid it.
@@ -116,8 +116,8 @@ The hourly `17 * * * *` schedule and the `promote`, `api_ref`, `env_docker_ref`
116
116
  - Selected tests run on every push with no label. Add `full-ci` to force the whole suite (`gh pr edit <n> --add-label full-ci`). Labels other than `full-ci` start nothing and cancel nothing.
117
117
  - On a pull request each matrix (`linux`; `macos` never runs there) is `fail-fast`: the first failing job cancels that matrix's other jobs, the matrix result is `failure`, and `full suite` still runs and is red. On main, merge queue and dispatch runs every job finishes. A Linux failure does not cancel the macOS matrix.
118
118
  - `record tested tree` runs only in mode `full`, so a partial run never lets Publish skip the suite.
119
- - The `full suite` job is the single result to require. It fails if `checks` or `select` did not succeed or any job failed or was cancelled; in mode `full` it also fails unless every `linux` and `macos` job succeeded (skipped is not enough, except `macos` on a pull request, where it never runs), so Publish (which calls this file) can only release a tree whose full suite passed. In mode `none` it passes and says no tests are affected.
120
- - `checks` builds once on ubuntu and uploads the JS output; the `linux` jobs unpack it and compile the Linux native addon in the container (the build is glibc, the image musl), and the `macos` jobs unpack it as is.
119
+ - The `full suite` job is the single result to require. It fails if `build`, `checks` or `select` did not succeed or any job failed or was cancelled; in mode `full` it also fails unless every `linux` and `macos` job succeeded (skipped is not enough, except `macos` on a pull request, where it never runs), so Publish (which calls this file) can only release a tree whose full suite passed. In mode `none` it passes and says no tests are affected.
120
+ - `build` builds once on ubuntu and uploads the JS output; `checks` (typecheck of examples, contract check, script tests, the concurrent-build test) runs beside the lanes on that build, and the lanes wait only for `build`. The `linux` jobs unpack it and compile the Linux native addon in the container (the build is glibc, the image musl), and the `macos` jobs unpack it as is.
121
121
 
122
122
  ## The selector: `scripts/ci-select.mjs`
123
123
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.712",
3
+ "version": "0.3.713",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.712",
162
- "@north-light/plugin": "0.3.712",
161
+ "@north-light/identity": "0.3.713",
162
+ "@north-light/plugin": "0.3.713",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -12,6 +12,7 @@ import { dispatchSlashCommand, isSlashCommand } from '../slash/dispatch.js';
12
12
  import { viewerOperationForFrame } from './capabilities.js';
13
13
  import { readClipboardImage, writeClipboardImageToFile } from './clipboard-image.js';
14
14
  import { InputOverlayOwner } from './overlay-owner.js';
15
+ import { attachLocalFiles, hasLocalPaths } from './local-files.js';
15
16
  import { announceFallbackEditor, NO_EDITOR_MESSAGE, resolveEditor } from '../../../core/editor-resolver.js';
16
17
  const DOUBLE_ESCAPE_MS = 500;
17
18
  const MAX_FRAME_BYTES = BROKER_READ_CAPS.maxLineBytes - 4 * 1024 * 1024;
@@ -257,26 +258,56 @@ export class InputController {
257
258
  if (delivery !== 'steer' && delivery !== 'prompt')
258
259
  return;
259
260
  const expanded = this.expandImagePlaceholders(classification.kind === 'slash' ? text : classification.text);
260
- if (!this.emitDrive(delivery === 'steer' ? { type: 'steer', text: expanded } : { type: 'prompt', text: expanded }))
261
+ const sent = () => {
262
+ this.recordCompletionUse(text);
263
+ this.editor.addToHistory(classification.trimmed);
264
+ this.clearPastedImages();
265
+ };
266
+ const deliver = (final) => {
267
+ if (!this.emitDrive(delivery === 'steer' ? { type: 'steer', text: final } : { type: 'prompt', text: final }))
268
+ return false;
269
+ if (delivery === 'prompt')
270
+ this.hooks.onMessageSent?.(final, true);
271
+ this.hooks.onPromptSent?.();
272
+ return true;
273
+ };
274
+ this.sendMessage(expanded, text, classification.kind !== 'slash', sent, deliver);
275
+ }
276
+ /** Send one message through `deliver`, with `sent` run and the editor cleared
277
+ * exactly once it is accepted. A message naming files on this machine (when
278
+ * `files` allows it and a broker can take them) clears the editor first, sends
279
+ * each file to the node, then delivers the rewritten text; a refused delivery
280
+ * puts the typed text back. */
281
+ sendMessage(expanded, typed, files, sent, deliver) {
282
+ const request = this.hooks.onRequest;
283
+ if (!files || request === undefined || !hasLocalPaths(expanded)) {
284
+ if (!deliver(expanded))
285
+ return;
286
+ sent();
287
+ this.editor.setText('');
261
288
  return;
262
- this.recordCompletionUse(text);
263
- this.editor.addToHistory(classification.trimmed);
289
+ }
290
+ sent();
264
291
  this.editor.setText('');
265
- this.clearPastedImages();
266
- if (delivery === 'prompt')
267
- this.hooks.onMessageSent?.(expanded, true);
268
- this.hooks.onPromptSent?.();
292
+ this.tui.requestRender();
293
+ void attachLocalFiles(expanded, request).then((final) => {
294
+ if (!deliver(final) && this.editor.getText().trim() === '') {
295
+ this.editor.setText(typed);
296
+ this.tui.requestRender();
297
+ }
298
+ });
269
299
  }
270
300
  handleFollowUp() {
271
301
  const text = this.editor.getText();
272
302
  const trimmed = text.trim();
273
303
  if (!trimmed)
274
304
  return;
275
- if (!this.emitDrive({ type: 'follow_up', text: this.expandImagePlaceholders(text) }))
276
- return;
277
- this.editor.addToHistory(trimmed);
278
- this.editor.setText('');
279
- this.clearPastedImages();
305
+ const expanded = this.expandImagePlaceholders(text);
306
+ const sent = () => {
307
+ this.editor.addToHistory(trimmed);
308
+ this.clearPastedImages();
309
+ };
310
+ this.sendMessage(expanded, text, true, sent, (final) => this.emitDrive({ type: 'follow_up', text: final }));
280
311
  }
281
312
  async handleDequeue() {
282
313
  if (this.refuseStarting())
@@ -0,0 +1,97 @@
1
+ // input/local-files.ts — file paths in a message the person sends. A path they
2
+ // typed or pasted (or a pasted image's temp file) names a file on the viewer's
3
+ // machine, which the node may not share. Before the message leaves, each such
4
+ // file is sent to the node's broker (`upload_file`) and its path in the text is
5
+ // replaced with the path the node can read. Nothing here blocks the send: a file
6
+ // that is missing, too large or fails to upload stays as typed and the message
7
+ // gains a `<runtime>` note saying why.
8
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ /** Base64 grows the bytes by a third and the frame must fit the broker's read cap, so a file above this stays on the viewer. */
11
+ export const LOCAL_FILE_MAX_BYTES = 16 * 1024 * 1024;
12
+ /** An absolute or `~/` path, with shell-escaped spaces (`a\ b`) as a terminal drag-and-drop writes them. */
13
+ const PATH_TOKEN = /(?<![\w/~.:-])(~?\/(?:\\ |[^\s'"`<>()[\]{}])+)/g;
14
+ /** Every path token in `text`, with sentence punctuation trimmed and escapes undone. Exported for tests. */
15
+ export function findLocalPaths(text) {
16
+ const out = [];
17
+ for (const m of text.matchAll(PATH_TOKEN)) {
18
+ const raw = m[1].replace(/[.,;:!?]+$/, '');
19
+ if (raw === '/' || raw === '~/' || raw.startsWith('//'))
20
+ continue;
21
+ const unescaped = raw.replace(/\\ /g, ' ');
22
+ const path = unescaped.startsWith('~/') ? `${homedir()}${unescaped.slice(1)}` : unescaped;
23
+ out.push({ start: m.index, end: m.index + raw.length, raw, path });
24
+ }
25
+ return out;
26
+ }
27
+ function readLocal(path) {
28
+ let fd;
29
+ try {
30
+ fd = openSync(path, constants.O_RDONLY);
31
+ }
32
+ catch {
33
+ return { kind: 'missing' };
34
+ }
35
+ try {
36
+ const stat = fstatSync(fd);
37
+ if (!stat.isFile())
38
+ return { kind: 'not-file' };
39
+ if (stat.size > LOCAL_FILE_MAX_BYTES)
40
+ return { kind: 'too-large', size: stat.size };
41
+ return { kind: 'file', bytes: readFileSync(fd) };
42
+ }
43
+ finally {
44
+ closeSync(fd);
45
+ }
46
+ }
47
+ function mib(bytes) {
48
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
49
+ }
50
+ /** True when `text` names any path, so the caller can keep the plain synchronous send otherwise. */
51
+ export function hasLocalPaths(text) {
52
+ return findLocalPaths(text).length > 0;
53
+ }
54
+ /** Send each local file `text` names to the node and rewrite its path; append a `<runtime>` note for every file that could not go. */
55
+ export async function attachLocalFiles(text, request) {
56
+ const matches = findLocalPaths(text);
57
+ if (matches.length === 0)
58
+ return text;
59
+ const notes = [];
60
+ const sent = new Map();
61
+ const replaced = [];
62
+ for (const match of matches) {
63
+ const done = sent.get(match.path);
64
+ if (done !== undefined) {
65
+ replaced.push({ match, to: done });
66
+ continue;
67
+ }
68
+ const read = readLocal(match.path);
69
+ if (read.kind === 'not-file')
70
+ continue;
71
+ if (read.kind === 'missing') {
72
+ notes.push(`${match.raw} does not exist on the person's machine, so it was not sent to you.`);
73
+ continue;
74
+ }
75
+ if (read.kind === 'too-large') {
76
+ notes.push(`file ${match.raw} is too large (${mib(read.size)}; the limit is ${mib(LOCAL_FILE_MAX_BYTES)}), not uploaded.`);
77
+ continue;
78
+ }
79
+ try {
80
+ const reply = await request({ type: 'upload_file', source_path: match.path, data: read.bytes.toString('base64') });
81
+ if (reply.kind !== 'upload_file')
82
+ throw new Error('unexpected reply');
83
+ sent.set(match.path, reply.path);
84
+ replaced.push({ match, to: reply.path });
85
+ }
86
+ catch (error) {
87
+ notes.push(`file ${match.raw} could not be uploaded (${error instanceof Error ? error.message : String(error)}).`);
88
+ }
89
+ }
90
+ let out = text;
91
+ for (const { match, to } of replaced.reverse()) {
92
+ if (to === match.path && match.raw === to)
93
+ continue;
94
+ out = `${out.slice(0, match.start)}${to}${out.slice(match.end)}`;
95
+ }
96
+ return notes.length === 0 ? out : `${out}\n\n<runtime>\n${notes.join('\n')}\n</runtime>`;
97
+ }
@@ -8,7 +8,7 @@
8
8
  import { basename } from 'node:path';
9
9
  import { modeIcon, personaLabel } from '../../../core/canvas/labels.js';
10
10
  import { colorChipStyle, defaultTitleStyle, thinkingBorderColor, thinkingTitleStyle } from '../input/titled-editor.js';
11
- import { fetchGitInfo } from '../chrome/git-info.js';
11
+ import { loadProfileManifest } from '../../../core/profiles/manifest.js';
12
12
  /** Nerd Font terminal glyph marks a one-shot node; resident nodes need no
13
13
  * lifecycle glyph because they persist by default. */
14
14
  const TERMINAL_NODE_ICON = '\uf489';
@@ -62,7 +62,7 @@ export function displayEditorTitle(sessionName, identity) {
62
62
  * and paints every frame-attached adornment — border hue, title chip, context
63
63
  * badge, and git context. */
64
64
  export function createEditorChrome(ctx, hooks) {
65
- const { meta, tui, pal, editor } = ctx;
65
+ const { meta, tui, pal, editor, socket } = ctx;
66
66
  // Shell/bash mode: the editor text leads with `!`. Tracks pi's interactive
67
67
  // `isBashMode`, which recolors the editor border green as a visual cue (#7).
68
68
  // Three levels: 0 = off, 1 = `!` (output goes to the agent's context), 2 = `!!`
@@ -72,11 +72,24 @@ export function createEditorChrome(ctx, hooks) {
72
72
  // `/color` override for the name chip — null means the default (thinking-
73
73
  // tracking) chip. Bash mode still wins: the green frame is a live safety cue.
74
74
  let chipColor = null;
75
- const syncContextBadge = (dir = basename(meta.cwd) || meta.cwd) => {
75
+ // The badge names the node's profile; a node without one (or whose manifest
76
+ // will not load here) falls back to the folder it runs in.
77
+ const profileLabel = (() => {
78
+ const id = meta.profile_id;
79
+ if (!id)
80
+ return basename(meta.cwd) || meta.cwd;
81
+ try {
82
+ return loadProfileManifest(id).manifest.name;
83
+ }
84
+ catch {
85
+ return id;
86
+ }
87
+ })();
88
+ const syncContextBadge = () => {
76
89
  const identity = hooks.nodeIdentity();
77
90
  const lifecycle = identity?.lifecycle === 'terminal' ? `${TERMINAL_NODE_ICON} ` : '';
78
91
  const persona = identity ? ` · ${personaLabel(identity)}` : '';
79
- editor.contextBadge = `${lifecycle}${dir}${persona}`;
92
+ editor.contextBadge = `${lifecycle}${profileLabel}${persona}`;
80
93
  };
81
94
  // Paint the editor border + title chip. Shell/bash mode (leading `!`) wins and
82
95
  // forces the whole frame green (#7); otherwise the hue tracks the thinking
@@ -105,8 +118,9 @@ export function createEditorChrome(ctx, hooks) {
105
118
  tui.requestRender();
106
119
  };
107
120
  // Git context painted into the RIGHT of the editor's top border: branch and
108
- // status symbols (● dirty, ⇡ ahead, ⇣ behind). The cwd leaf lives in the
109
- // editor's bottom-right node and workspace badge. Refreshed by the poll.
121
+ // status symbols (● dirty, ⇡ ahead, ⇣ behind) of the node's own working
122
+ // directory, read by its broker (the viewer may run on another machine).
123
+ // Refreshed by the poll.
110
124
  const renderGitInfo = (info) => {
111
125
  const parts = [];
112
126
  if (info.branch)
@@ -122,9 +136,14 @@ export function createEditorChrome(ctx, hooks) {
122
136
  parts.push(sym.join(''));
123
137
  // A trailing space keeps the symbols off the very last border cell.
124
138
  editor.info = parts.length > 0 ? ` ${parts.join(pal.muted(' · '))} ` : '';
125
- syncContextBadge(info.dir);
126
139
  tui.requestRender();
127
140
  };
141
+ const pollGit = () => {
142
+ socket.request({ type: 'get_git_status' }).then((reply) => {
143
+ if (reply.kind === 'git_status')
144
+ renderGitInfo(reply);
145
+ }, () => { });
146
+ };
128
147
  return {
129
148
  bashMode: () => bashMode,
130
149
  setChipColor: (color) => {
@@ -137,6 +156,6 @@ export function createEditorChrome(ctx, hooks) {
137
156
  editor.title = displayEditorTitle(sessionName, hooks.nodeIdentity());
138
157
  },
139
158
  syncContextBadge: () => syncContextBadge(),
140
- pollGit: () => fetchGitInfo(meta.cwd, renderGitInfo),
159
+ pollGit,
141
160
  };
142
161
  }
@@ -69,8 +69,8 @@ const nodeBashRun = defineLeaf({
69
69
  throw new InputError({ error: 'no_node', message: '`node bash run` starts a job for the calling node and works only inside a node’s bash tool', next: 'Run it from a node’s bash tool call.' });
70
70
  }
71
71
  const cwd = process.cwd();
72
- const { bashCommandRefusal } = await import('../../core/bash-guard.js');
73
- const refusal = bashCommandRefusal(command, cwd);
72
+ const { destructiveCommandRefusal } = await import('../../core/bash-guard.js');
73
+ const refusal = destructiveCommandRefusal(command, cwd);
74
74
  if (refusal !== null) {
75
75
  throw new InputError({ error: 'refused', message: refusal, next: 'Run a different command.' });
76
76
  }
@@ -436,7 +436,7 @@ function broadSearchRefusalMessage(segment, target, reason) {
436
436
  * `rm -rf "$HOME"` is a scratch directory and runs. A `HOME=/tmp/x cmd`
437
437
  * PREFIX applies to that one command only, so a later `rm -rf "$HOME"` is the
438
438
  * real home — which is precisely the mistake that destroyed one. */
439
- function destructiveCommandRefusal(command, cwd, home) {
439
+ export function destructiveCommandRefusal(command, cwd, home = homedir()) {
440
440
  const vars = initialVariables(home, cwd);
441
441
  // Every directory a relative operand might be resolved from. A `cd` ADDS its
442
442
  // destination rather than replacing the previous one, because the guard
@@ -332,9 +332,9 @@ export function createRowStore() {
332
332
  const db = await openDb();
333
333
  const old = await parts(db, id);
334
334
  await withCanvasWrite(async (tx) => {
335
+ await tx.prepare('DELETE FROM sessions WHERE session_id = ?').run(id);
335
336
  await tx.prepare('DELETE FROM conversation_entries WHERE conversation_id = ?').run(id);
336
337
  await tx.prepare('DELETE FROM conversation_parts WHERE conversation_id = ?').run(id);
337
- await tx.prepare('DELETE FROM sessions WHERE session_id = ?').run(id);
338
338
  });
339
339
  for (const part of old)
340
340
  await (await blobStore()).delete(part.blob_key);
@@ -99,7 +99,7 @@ export async function heads(db, doc) {
99
99
  AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id) ORDER BY r.number DESC, r.rev_id`).all(doc.id);
100
100
  return (await mapAsync(raws, async (r) => await toRevision(db, r)));
101
101
  }
102
- function headsKeyOf(revs) {
102
+ export function headsKeyOf(revs) {
103
103
  return revs.map((r) => r.rev_id).sort().join(',');
104
104
  }
105
105
  export async function documentRecord(db, doc) {
@@ -447,32 +447,20 @@ export async function setDocumentRecord(db, reader, doc, fields, rationale) {
447
447
  }, { savepoint: true });
448
448
  }
449
449
  // ── read and history ───────────────────────────────────────────────────────
450
- /** Record that the reader holds the document's current heads: a `read` watch with that read
451
- * base, and a `read` push. Delivery's content load calls this without reading the body. */
452
- export async function recordRead(db, reader, doc, reposFn) {
453
- const actor = actorOf(reader);
454
- const { heads_key } = await documentRecord(db, doc);
455
- await recordWatch(db, actor, doc, 'read', { readHeadsKey: heads_key });
456
- await publish(db, { event: 'read', object: doc, actor, attrs: {} }, reposFn);
457
- }
458
450
  /** The document's record, each head with its body (several = needs merge) and its links under
459
- * their current names; records the read. */
460
- export async function readDocument(db, reader, doc, reposFn) {
451
+ * their current names. Records nothing. */
452
+ export async function readDocument(db, reader, doc) {
461
453
  assertDocument(doc);
462
454
  await readable(db, reader, doc);
463
- return await withCanvasWrite(async () => {
464
- const record = await documentRecord(db, doc);
465
- const headRows = await heads(db, doc);
466
- const texts = await getBodies(db, headRows.map((h) => h.body_hash));
467
- const current = await mapAsync(headRows, async (h) => ({ ...h, body: await withCurrentNames(db, doc, texts.get(h.body_hash)) }));
468
- const read = await readableOrDeleted(db, await resolveReader(db, reader), 'o');
469
- const linked = await db.prepareUncached(`SELECT e.written_as AS _written_as, o.* FROM edges e JOIN objects o ON o.id = e.dst
470
- WHERE e.type = 'links-to' AND e.src = ? AND (${read.sql}) ORDER BY e.written_as`).all(doc.id, ...read.params);
471
- const links = linked.map(({ _written_as, ...object }) => ({ written_as: _written_as ?? '', object: object, deleted: object.deleted_at !== null }));
472
- if (!doc.deleted_at)
473
- await recordRead(db, reader, doc, reposFn);
474
- return { object: doc, record, heads: current, needsMerge: current.length > 1, links };
475
- }, { savepoint: true });
455
+ const record = await documentRecord(db, doc);
456
+ const headRows = await heads(db, doc);
457
+ const texts = await getBodies(db, headRows.map((h) => h.body_hash));
458
+ const current = await mapAsync(headRows, async (h) => ({ ...h, body: await withCurrentNames(db, doc, texts.get(h.body_hash)) }));
459
+ const read = await readableOrDeleted(db, await resolveReader(db, reader), 'o');
460
+ const linked = await db.prepareUncached(`SELECT e.written_as AS _written_as, o.* FROM edges e JOIN objects o ON o.id = e.dst
461
+ WHERE e.type = 'links-to' AND e.src = ? AND (${read.sql}) ORDER BY e.written_as`).all(doc.id, ...read.params);
462
+ const links = linked.map(({ _written_as, ...object }) => ({ written_as: _written_as ?? '', object: object, deleted: object.deleted_at !== null }));
463
+ return { object: doc, record, heads: current, needsMerge: current.length > 1, links };
476
464
  }
477
465
  /** Every revision, newest first, with authors, rationales and parents. Records nothing. */
478
466
  export async function history(db, reader, doc) {