@north-light/cli 0.3.710 → 0.3.711

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/clients/attach/input/controller.d.ts +1 -1
  4. package/dist/clients/attach/input/controller.js +2 -2
  5. package/dist/clients/attach/render/chat-view.d.ts +13 -2
  6. package/dist/clients/attach/render/chat-view.js +2 -2
  7. package/dist/clients/attach/session/input-wiring.d.ts +2 -2
  8. package/dist/clients/attach/session/layout-record.d.ts +4 -2
  9. package/dist/clients/attach/session/layout-record.js +1 -1
  10. package/dist/clients/attach/session/reconnect.d.ts +8 -1
  11. package/dist/clients/attach/session/reconnect.js +1 -1
  12. package/dist/clients/attach/slash/recover.js +3 -2
  13. package/dist/clients/attach/viewer.js +405 -404
  14. package/dist/commands/human/prompts.js +1 -1
  15. package/dist/commands/human/request.js +1 -1
  16. package/dist/commands/sys/doctor.js +1 -1
  17. package/dist/commands/sys/tutorial/scenario.js +2 -2
  18. package/dist/core/broker-client/client.d.ts +2 -0
  19. package/dist/core/broker-client/client.js +1 -1
  20. package/dist/core/broker-client/transport-relay.d.ts +6 -0
  21. package/dist/core/broker-client/transport-relay.js +1 -1
  22. package/dist/core/broker-client/transport.d.ts +4 -0
  23. package/dist/core/canvas/daemon-actions.d.ts +1 -1
  24. package/dist/core/canvas/daemon-actions.js +7 -7
  25. package/dist/core/canvas/deliveries.d.ts +1 -1
  26. package/dist/core/canvas/deliveries.js +21 -21
  27. package/dist/core/canvas/executions.d.ts +1 -1
  28. package/dist/core/canvas/executions.js +1 -1
  29. package/dist/core/canvas/reconciler-leases.d.ts +4 -0
  30. package/dist/core/canvas/reconciler-leases.js +5 -5
  31. package/dist/core/conversation-store/client.js +2 -2
  32. package/dist/core/conversation-store/index.d.ts +5 -2
  33. package/dist/core/conversation-store/row-store.js +14 -12
  34. package/dist/core/graph/package-docs.js +5 -5
  35. package/dist/core/graph/package-publish.js +4 -3
  36. package/dist/core/human/requests.js +19 -19
  37. package/dist/core/import/load/run.js +2 -2
  38. package/dist/core/runtime/broker/client-registry.d.ts +1 -1
  39. package/dist/core/runtime/broker/client-registry.js +1 -1
  40. package/dist/core/runtime/broker/turn-replies.js +3 -1
  41. package/dist/core/runtime/broker-protocol.d.ts +4 -4
  42. package/dist/core/runtime/broker-protocol.js +3 -3
  43. package/dist/core/runtime/broker.js +1 -1
  44. package/dist/core/runtime/placement-tmux.d.ts +1 -0
  45. package/dist/core/runtime/placement-tmux.js +1 -1
  46. package/dist/core/runtime/session-cycles.d.ts +21 -0
  47. package/dist/core/runtime/session-cycles.js +1 -1
  48. package/dist/daemon/api/app-listener.js +1 -1
  49. package/dist/daemon/api/handlers/charges.d.ts +1 -1
  50. package/dist/daemon/api/handlers/charges.js +1 -1
  51. package/dist/daemon/api/handlers/conversations.js +4 -3
  52. package/dist/daemon/api/handlers/environments.d.ts +1 -1
  53. package/dist/daemon/api/handlers/environments.js +1 -1
  54. package/dist/daemon/api/handlers/limits.js +1 -1
  55. package/dist/daemon/api/handlers/nodes.js +1 -1
  56. package/dist/daemon/api/operations.js +1 -1
  57. package/dist/daemon/api/router.js +1 -1
  58. package/dist/daemon/cron/live-runs.d.ts +3 -0
  59. package/dist/daemon/cron/live-runs.js +1 -1
  60. package/dist/daemon/cron/machine-fire.js +1 -1
  61. package/dist/daemon/crtrd.js +12 -12
  62. package/dist/daemon/due-sources.d.ts +1 -1
  63. package/dist/daemon/due-sources.js +1 -1
  64. package/dist/daemon/due.js +7 -7
  65. package/dist/daemon/human/finish.js +3 -3
  66. package/dist/daemon/human/settle.js +1 -1
  67. package/dist/daemon/reconcilers/action-lane.js +1 -1
  68. package/dist/daemon/reconcilers/delivery-lane.js +2 -2
  69. package/dist/daemon/reconcilers/grant-effects.js +1 -1
  70. package/dist/daemon/reconcilers/node-lifecycle/requested-stops.js +2 -2
  71. package/package.json +4 -3
  72. package/packages/crouter-api/dist/api/contract.js +1 -1
  73. package/packages/crouter-api/dist/clients/attach/input/controller.js +2 -2
  74. package/packages/crouter-api/dist/clients/attach/render/chat-view.js +40 -3
  75. package/packages/crouter-api/dist/clients/attach/session/layout-record.js +7 -7
  76. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +41 -2
  77. package/packages/crouter-api/dist/clients/attach/slash/recover.js +23 -1
  78. package/packages/crouter-api/dist/clients/attach/viewer.js +21 -10
  79. package/packages/crouter-api/dist/commands/human/prompts.js +11 -18
  80. package/packages/crouter-api/dist/commands/human/request.js +3 -0
  81. package/packages/crouter-api/dist/commands/sys/doctor.js +17 -0
  82. package/packages/crouter-api/dist/commands/sys/tutorial/scenario.js +1 -0
  83. package/packages/crouter-api/dist/core/broker-client/client.js +4 -0
  84. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +45 -0
  85. package/packages/crouter-api/dist/core/canvas/daemon-actions.js +3 -2
  86. package/packages/crouter-api/dist/core/canvas/deliveries.js +7 -3
  87. package/packages/crouter-api/dist/core/canvas/executions.js +8 -7
  88. package/packages/crouter-api/dist/core/canvas/reconciler-leases.js +4 -0
  89. package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
  90. package/packages/crouter-api/dist/core/conversation-store/row-store.js +14 -1
  91. package/packages/crouter-api/dist/core/graph/package-docs.js +8 -3
  92. package/packages/crouter-api/dist/core/graph/package-publish.js +8 -1
  93. package/packages/crouter-api/dist/core/human/requests.js +2 -2
  94. package/packages/crouter-api/dist/core/runtime/broker-protocol.js +4 -4
  95. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +2 -2
  96. package/packages/crouter-api/dist/core/runtime/session-cycles.js +90 -8
  97. package/packages/crouter-api/dist/daemon/api/operations.js +3 -3
  98. package/packages/crouter-api/dist/daemon/api/router.js +1 -4
  99. package/packages/crouter-api/dist/daemon/cron/live-runs.js +4 -5
  100. package/packages/crouter-api/dist/daemon/cron/machine-fire.js +3 -3
  101. package/packages/crouter-api/dist/daemon/human/finish.js +2 -1
  102. package/packages/crouter-api/dist/daemon/human/settle.js +1 -6
  103. package/packages/crouter-api/package.json +1 -1
  104. package/packages/crouter-identity/package.json +1 -1
  105. package/packages/crouter-plugin/package.json +3 -3
  106. package/runtime.lock.json +14 -14
  107. package/scripts/install-runtime.mjs +18 -1
  108. package/scripts/lib/install-source.mjs +49 -0
  109. package/dist/daemon/reconcilers/idle-sandbox.d.ts +0 -18
  110. package/dist/daemon/reconcilers/idle-sandbox.js +0 -7
@@ -1 +1 @@
1
- var I=Object.defineProperty;var i=(n,e)=>I(n,"name",{value:e,configurable:!0});import{envNodeId as A}from"../../shared/env.js";import{defineLeaf as x}from"../../core/command.js";import{InputError as o}from"../../core/io.js";import{cliClient as l,rethrowAsCliError as S}from"../api-client.js";import{join as v}from"node:path";import{mkdtempSync as N,rmSync as j,writeFileSync as F}from"node:fs";import{tmpdir as W}from"node:os";import{productComponents as C}from"./components.js";import{preparePage as _}from"../../core/human/page-authoring.js";import{PageAuthoringError as E}from"../../core/human/page.js";import{isResponseBearingSlot as D,validateAuthoredPageManifest as U}from"../../core/human/page-schema.js";import{display as $}from"../../core/termrender/display.js";import{pageHelpText as q,resolveMaxPanes as M}from"./shared.js";const K=q().pageHint;function P(){return A()??null}i(P,"askingNode");async function Q(){const n=P();if(n===null||n==="")return{source:{},lifecycle:null};try{const e=l(),t=await e.getNode(n),a=t.name.trim(),r=t.profile_id===null?void 0:(await e.getProfile(t.profile_id)).name;return{source:{nodeId:n,...a===""?{}:{sessionName:a},...r===void 0?{}:{profileName:r}},lifecycle:t.lifecycle}}catch{return{source:{nodeId:n},lifecycle:null}}}i(Q,"sender");function B(n,e,t){const a=t==="terminal"||n.inbox===!0?!0:n.noInbox===!0?!1:e;return{placement:n.placement??"inline",inbox:a,reply:e}}i(B,"deliveryFrom");function g(n){try{return n()}catch(e){throw e instanceof E?new o({error:"invalid_page",message:e.message,field:"page",next:"Fix the authored page and submit again; the reported location is in the authored `.tsx` source."}):e}}i(g,"submitAuthoredPage");async function G(n){try{const e=await l().getHumanRequest(n);if(e.kind!=="page")throw new o({error:"unknown_page",message:`no page ${n} on this canvas`,field:"replace",next:"Pass the page_id a previous send returned, or omit --replace to raise a new page."});return(await l().getHumanInboxPage(e.inbox_ticket_id)).page}catch(e){if(e instanceof o)throw e;S(e,"Pass the page_id a previous send returned, or omit --replace to raise a new page.")}}i(G,"replacedPage");function L(n){const e=N(v(W(),"crtr-human-page-")),t=v(e,"page.tsx");return F(t,n,{encoding:"utf8",mode:384}),{dir:e,path:t}}i(L,"writePipedPage");function z(n){const e=n.page,t=n.document,a=typeof t=="string"&&t.trim()!==""?t:void 0;if(e!==void 0&&a!==void 0)throw new o({error:"bad_invocation",message:"received both --page and a piped page document",field:"page, document",next:"Pass exactly one page source: --page PATH or the document on stdin."});if(e===void 0&&a===void 0)throw new o({error:"missing_parameter",message:"a page source is required",field:"page, document",next:"Pass exactly one page source: --page PATH or the document on stdin."});if(e!==void 0){if(typeof e!="string")throw new o({error:"invalid_type",message:"--page must be a path",field:"page",next:"Retry with --page PATH."});return{sourceFile:e}}if(typeof a!="string")throw new o({error:"invalid_type",message:"stdin must contain a page document",field:"document",next:"Pipe the page document on stdin."});const r=L(a);return{sourceFile:r.path,tempDir:r.dir}}i(z,"pageInput");function J(){return"Queued for the user. Their answer is pushed to your inbox and wakes you when they respond \u2014 never poll, verify it opened, or block."}i(J,"queuedFollowUp");function ce(n=!1){const e=q(n);return x({name:"send",description:"send a durable page with explicit delivery",whenToUse:e.sendWhenToUse,help:{name:"human send",summary:e.sendSummary,guide:"Page authoring: `crtr human -h`.",params:[{kind:"stdin",name:"document",required:!1,allowPositional:!1,constraint:e.stdinConstraint},{kind:"flag",name:"page",type:"path",required:!1,constraint:`${K} ${e.pageFlagConstraint}`},{kind:"flag",name:"placement",type:"enum",choices:["inline","panel"],required:!1,default:"inline",constraint:"Where the page is delivered. inline renders in this conversation's transcript; panel opens from the inbox beside it."},{kind:"flag",name:"inbox",type:"bool",required:!1,constraint:"Project this page into the inbox. Mutually exclusive with --no-inbox."},{kind:"flag",name:"no-inbox",type:"bool",required:!1,constraint:"Do not project this page into the inbox, leaving this conversation's transcript as its only route to the user. Mutually exclusive with --inbox, and refused from a terminal node, whose transcript nobody reads once it finishes."},{kind:"flag",name:"replace",type:"string",required:!1,constraint:"Page id returned by an earlier send. Rewrites source in place while retaining its delivery and transcript anchor. Refused once the page is settled or canceled. Not combinable with delivery flags."}],output:[{name:"page_id",type:"string",required:!0,constraint:"Identifier for the page; pass it as --replace to revise source in place."},{name:"dir",type:"string",required:!0,constraint:e.dirConstraint},{name:"placement",type:"inline | panel",required:!0,constraint:"Resolved page placement."},{name:"inbox",type:"boolean",required:!0,constraint:"Whether the page is projected into the inbox."},{name:"reply",type:"boolean",required:!0,constraint:"Whether completion is delivered to the asking request identity. Not a flag: true exactly when the page has response-bearing components."},{name:"follow_up",type:"string",required:!0,constraint:"What happens next; never instructs the caller to poll."}],outputKind:"object",effects:["Writes one durable page request. Inbox projection follows the delivery flags, except from a terminal node, which always projects; completion delivery follows the page's own components.","A display-only page's inbox entry is a notice, not a task: it clears itself once the person has actually seen the page, wherever they see it.","A reply-bearing page records the asking node on the request and delivers completion directly to that node.","--replace rewrites source in place while retaining delivery and emitted time; open surfaces reload it without creating another page."]},run:i(async(t,a)=>{const{sourceFile:r,tempDir:f}=z(t),c=t.replace,k=["placement","inbox","noInbox"];if(t.inbox===!0&&t.noInbox===!0)throw new o({error:"bad_invocation",message:"received conflicting delivery flags",field:"inbox",next:"Pass at most one of --inbox and --no-inbox."});if(c!==void 0&&k.some(p=>a?.providedParams.has(p)===!0))throw new o({error:"bad_invocation",message:"--replace cannot change delivery",field:"replace",next:"Remove delivery flags: replacement retains the page placement, inbox, reply, and emitted time."});try{const p=await C();if(c!==void 0){const u=await G(c);if((await l().getHumanRequest(c)).state!=="pending")throw new o({error:"page_settled",message:`page ${c} already has a terminal outcome`,field:"replace",next:"The page was answered or canceled; nothing on it can change now. Raise a new page if more is needed."});const m=g(()=>_({sourceFile:r,source:u.source,productKinds:p,delivery:u.delivery})),H=await l().replaceHumanRequest(c,{page:{dialect:m.manifest.dialect,source:m.document}});return{page_id:c,dir:H.request_dir,...u.delivery,follow_up:"Replaced in place. Every open surface reloads it; delivery and emitted time are unchanged."}}const{source:T,lifecycle:w}=await Q();if(w==="terminal"&&t.noInbox===!0)throw new o({error:"invalid_page_delivery",message:"a terminal node cannot send a page --no-inbox",field:"inbox",next:"Drop --no-inbox. This node finishes, and nobody reads a finished node's transcript, so a page kept out of the inbox reaches no one."});const d=g(()=>_({sourceFile:r,source:T,productKinds:p})),R=d.manifest.slots.some(D),s=B(t,R,w);if(d.manifest=g(()=>U({...d.manifest,delivery:s},p)),!s.reply){const u=await l().createHumanRequest({page:{dialect:d.manifest.dialect,source:d.document},delivery:s,source:d.manifest.source,requester_node_id:null,creator_cwd:process.cwd()}),b=u.request_dir,m=s.placement==="inline"&&s.inbox?"Shown in this conversation and queued in the user's inbox.":s.placement==="inline"?"Shown in this conversation as passive page content with no inbox entry.":s.inbox?"Queued in the inbox; it opens in the panel and waits until dismissed.":"Published as passive page content with no inbox or response lifecycle.";return{page_id:u.request_id,dir:b,...s,follow_up:m}}const h=P();if(h===null||h==="")throw new o({error:"no_requester",message:"a response-bearing page must be sent from a crouter node",field:"page",next:"Run `crtr human send` from the node that should receive the answer."});const y=await l().createHumanRequest({page:{dialect:d.manifest.dialect,source:d.document},delivery:s,source:d.manifest.source,requester_node_id:h,creator_cwd:process.cwd()});return{page_id:y.request_id,dir:y.request_dir,...s,follow_up:J()}}finally{f!==void 0&&j(f,{recursive:!0,force:!0})}},"run")})}i(ce,"humanSend");const le=x({name:"show",description:"put a file live on the user's screen",whenToUse:"displaying a doc on screen while the user comments",help:{name:"human show",summary:"put a file live on screen in a tmux pane with crouter's renderer",guide:"The pane always watches the file and live-updates on every save \u2014 a displayed doc is a live view by definition, so point it at a file something keeps rewriting (a status board, a running summary) and it stays current. The file is directive-flavored markdown rendered by termrender (panels, columns, trees, callouts, mermaid). To put a rich document in front of the user as a durable inbox page, use `crtr human send --page PATH`; a page with no response-bearing components is a standalone announcement.",params:[{kind:"positional",name:"path",type:"path",required:!0,constraint:"Path to the file to render."},{kind:"flag",name:"window",type:"enum",choices:["auto","split","new"],required:!1,default:"auto",constraint:"Placement. Default auto."}],output:[{name:"pane_id",type:"string | null",required:!0,constraint:"Tmux pane id, or null when not displayed."},{name:"reason",type:"string | null",required:!0,constraint:"Why no pane was created, or null on success."}],outputKind:"object",effects:["Spawns a live-watch tmux pane when possible. No job. Always exits 0."]},run:i(async n=>{const e=n.path,t=n.window,a=t!==void 0?t:"auto";try{const r=$(e,{window:a,maxPanes:M()});return r.paneId!==void 0?{pane_id:r.paneId,reason:null}:{pane_id:null,reason:r.reason}}catch(r){return{pane_id:null,reason:`display failed: ${r instanceof Error?r.message:String(r)}`}}},"run")});export{ce as humanSend,le as humanShow,Q as sender};
1
+ var A=Object.defineProperty;var i=(n,e)=>A(n,"name",{value:e,configurable:!0});import{envNodeId as H}from"../../shared/env.js";import{defineLeaf as x}from"../../core/command.js";import{InputError as o}from"../../core/io.js";import{cliClient as c,rethrowAsCliError as S}from"../api-client.js";import{join as v}from"node:path";import{mkdtempSync as N,rmSync as j,writeFileSync as F}from"node:fs";import{tmpdir as W}from"node:os";import{productComponents as C}from"./components.js";import{preparePage as _}from"../../core/human/page-authoring.js";import{PageAuthoringError as E}from"../../core/human/page.js";import{isResponseBearingSlot as D,validateAuthoredPageManifest as U}from"../../core/human/page-schema.js";import{display as $}from"../../core/termrender/display.js";import{pageHelpText as q,resolveMaxPanes as M}from"./shared.js";const K=q().pageHint;function P(){return H()??null}i(P,"askingNode");async function Q(){const n=P();if(n===null||n==="")return{source:{},lifecycle:null};try{const e=c(),t=await e.getNode(n),a=t.name.trim(),r=t.profile_id===null?void 0:(await e.getProfile(t.profile_id)).name;return{source:{nodeId:n,...a===""?{}:{sessionName:a},...r===void 0?{}:{profileName:r}},lifecycle:t.lifecycle}}catch{return{source:{nodeId:n},lifecycle:null}}}i(Q,"sender");function B(n,e,t){const a=t==="terminal"||n.inbox===!0?!0:n.noInbox===!0?!1:e;return{placement:n.placement??"inline",inbox:a,reply:e}}i(B,"deliveryFrom");function g(n){try{return n()}catch(e){throw e instanceof E?new o({error:"invalid_page",message:e.message,field:"page",next:"Fix the authored page and submit again; the reported location is in the authored `.tsx` source."}):e}}i(g,"submitAuthoredPage");async function G(n){try{const e=await c().getHumanRequest(n);if(e.kind!=="page")throw new o({error:"unknown_page",message:`no page ${n} on this canvas`,field:"replace",next:"Pass the page_id a previous send returned, or omit --replace to raise a new page."});return(await c().getHumanInboxPage(e.inbox_ticket_id)).page}catch(e){if(e instanceof o)throw e;S(e,"Pass the page_id a previous send returned, or omit --replace to raise a new page.")}}i(G,"replacedPage");function L(n){const e=N(v(W(),"crtr-human-page-")),t=v(e,"page.tsx");return F(t,n,{encoding:"utf8",mode:384}),{dir:e,path:t}}i(L,"writePipedPage");function z(n){const e=n.page,t=n.document,a=typeof t=="string"&&t.trim()!==""?t:void 0;if(e!==void 0&&a!==void 0)throw new o({error:"bad_invocation",message:"received both --page and a piped page document",field:"page, document",next:"Pass exactly one page source: --page PATH or the document on stdin."});if(e===void 0&&a===void 0)throw new o({error:"missing_parameter",message:"a page source is required",field:"page, document",next:"Pass exactly one page source: --page PATH or the document on stdin."});if(e!==void 0){if(typeof e!="string")throw new o({error:"invalid_type",message:"--page must be a path",field:"page",next:"Retry with --page PATH."});return{sourceFile:e}}if(typeof a!="string")throw new o({error:"invalid_type",message:"stdin must contain a page document",field:"document",next:"Pipe the page document on stdin."});const r=L(a);return{sourceFile:r.path,tempDir:r.dir}}i(z,"pageInput");function J(){return"Queued for the user. Their answer is pushed to your inbox and wakes you when they respond \u2014 never poll, verify it opened, or block."}i(J,"queuedFollowUp");function le(n=!1){const e=q(n);return x({name:"send",description:"send a durable page with explicit delivery",whenToUse:e.sendWhenToUse,help:{name:"human send",summary:e.sendSummary,guide:"Page authoring: `crtr human -h`.",params:[{kind:"stdin",name:"document",required:!1,allowPositional:!1,constraint:e.stdinConstraint},{kind:"flag",name:"page",type:"path",required:!1,constraint:`${K} ${e.pageFlagConstraint}`},{kind:"flag",name:"placement",type:"enum",choices:["inline","panel"],required:!1,default:"inline",constraint:"Where the page is delivered. inline renders in this conversation's transcript; panel opens from the inbox beside it."},{kind:"flag",name:"inbox",type:"bool",required:!1,constraint:"Project this page into the inbox. Mutually exclusive with --no-inbox."},{kind:"flag",name:"no-inbox",type:"bool",required:!1,constraint:"Do not project this page into the inbox, leaving this conversation's transcript as its only route to the user. Mutually exclusive with --inbox, and refused from a terminal node, whose transcript nobody reads once it finishes."},{kind:"flag",name:"replace",type:"string",required:!1,constraint:"Page id returned by an earlier send. Rewrites source in place while retaining its delivery and transcript anchor. Refused once the page is settled or canceled. Not combinable with delivery flags."}],output:[{name:"page_id",type:"string",required:!0,constraint:"Identifier for the page; pass it as --replace to revise source in place."},{name:"dir",type:"string",required:!0,constraint:e.dirConstraint},{name:"placement",type:"inline | panel",required:!0,constraint:"Resolved page placement."},{name:"inbox",type:"boolean",required:!0,constraint:"Whether the page is projected into the inbox."},{name:"reply",type:"boolean",required:!0,constraint:"Whether completion is delivered to the asking request identity. Not a flag: true exactly when the page has response-bearing components."},{name:"follow_up",type:"string",required:!0,constraint:"What happens next; never instructs the caller to poll."}],outputKind:"object",effects:["Writes one durable page request. Inbox projection follows the delivery flags, except from a terminal node, which always projects; completion delivery follows the page's own components.","A display-only page's inbox entry is a notice, not a task: it clears itself once the person has actually seen the page, wherever they see it.","A reply-bearing page records the asking node on the request and delivers completion directly to that node.","--replace rewrites source in place while retaining delivery and emitted time; open surfaces reload it without creating another page."]},run:i(async(t,a)=>{const{sourceFile:r,tempDir:h}=z(t),d=t.replace,k=["placement","inbox","noInbox"];if(t.inbox===!0&&t.noInbox===!0)throw new o({error:"bad_invocation",message:"received conflicting delivery flags",field:"inbox",next:"Pass at most one of --inbox and --no-inbox."});if(d!==void 0&&k.some(p=>a?.providedParams.has(p)===!0))throw new o({error:"bad_invocation",message:"--replace cannot change delivery",field:"replace",next:"Remove delivery flags: replacement retains the page placement, inbox, reply, and emitted time."});try{const p=await C();if(d!==void 0){const u=await G(d);if((await c().getHumanRequest(d)).state!=="pending")throw new o({error:"page_settled",message:`page ${d} already has a terminal outcome`,field:"replace",next:"The page was answered or canceled; nothing on it can change now. Raise a new page if more is needed."});const b=g(()=>_({sourceFile:r,source:u.source,productKinds:p,delivery:u.delivery})),R=await c().replaceHumanRequest(d,{page:{dialect:b.manifest.dialect,source:b.document}});return{page_id:d,dir:R.request_dir,...u.delivery,follow_up:"Replaced in place. Every open surface reloads it; delivery and emitted time are unchanged."}}const{source:T,lifecycle:w}=await Q();if(w==="terminal"&&t.noInbox===!0)throw new o({error:"invalid_page_delivery",message:"a terminal node cannot send a page --no-inbox",field:"inbox",next:"Drop --no-inbox. This node finishes, and nobody reads a finished node's transcript, so a page kept out of the inbox reaches no one."});const l=g(()=>_({sourceFile:r,source:T,productKinds:p})),I=l.manifest.slots.some(D),s=B(t,I,w);l.manifest=g(()=>U({...l.manifest,delivery:s},p));const f=P();if(s.reply&&(f===null||f===""))throw new o({error:"no_requester",message:"a response-bearing page must be sent from a crouter node",field:"page",next:"Run `crtr human send` from the node that should receive the answer."});const m=await c().createHumanRequest({page:{dialect:l.manifest.dialect,source:l.document},delivery:s,source:l.manifest.source,requester_node_id:f||null,creator_cwd:process.cwd()});if(!s.reply){const u=m.request_dir,y=s.placement==="inline"&&s.inbox?"Shown in this conversation and queued in the user's inbox.":s.placement==="inline"?"Shown in this conversation as passive page content with no inbox entry.":s.inbox?"Queued in the inbox; it opens in the panel and waits until dismissed.":"Published as passive page content with no inbox or response lifecycle.";return{page_id:m.request_id,dir:u,...s,follow_up:y}}return{page_id:m.request_id,dir:m.request_dir,...s,follow_up:J()}}finally{h!==void 0&&j(h,{recursive:!0,force:!0})}},"run")})}i(le,"humanSend");const ce=x({name:"show",description:"put a file live on the user's screen",whenToUse:"displaying a doc on screen while the user comments",help:{name:"human show",summary:"put a file live on screen in a tmux pane with crouter's renderer",guide:"The pane always watches the file and live-updates on every save \u2014 a displayed doc is a live view by definition, so point it at a file something keeps rewriting (a status board, a running summary) and it stays current. The file is directive-flavored markdown rendered by termrender (panels, columns, trees, callouts, mermaid). To put a rich document in front of the user as a durable inbox page, use `crtr human send --page PATH`; a page with no response-bearing components is a standalone announcement.",params:[{kind:"positional",name:"path",type:"path",required:!0,constraint:"Path to the file to render."},{kind:"flag",name:"window",type:"enum",choices:["auto","split","new"],required:!1,default:"auto",constraint:"Placement. Default auto."}],output:[{name:"pane_id",type:"string | null",required:!0,constraint:"Tmux pane id, or null when not displayed."},{name:"reason",type:"string | null",required:!0,constraint:"Why no pane was created, or null on success."}],outputKind:"object",effects:["Spawns a live-watch tmux pane when possible. No job. Always exits 0."]},run:i(async n=>{const e=n.path,t=n.window,a=t!==void 0?t:"auto";try{const r=$(e,{window:a,maxPanes:M()});return r.paneId!==void 0?{pane_id:r.paneId,reason:null}:{pane_id:null,reason:r.reason}}catch(r){return{pane_id:null,reason:`display failed: ${r instanceof Error?r.message:String(r)}`}}},"run")});export{le as humanSend,ce as humanShow,Q as sender};
@@ -1 +1 @@
1
- var y=Object.defineProperty;var a=(e,t)=>y(e,"name",{value:t,configurable:!0});import{existsSync as p,readFileSync as f}from"node:fs";import{defineBranch as w,defineLeaf as o}from"../../core/command.js";import{InputError as s}from"../../core/io.js";import{cliClient as d,rethrowAsCliError as c}from"../api-client.js";function g(e,t,n){if(!p(e))throw new s({error:"not_found",message:`no such file: ${e}`,field:t,next:`Pass --${t} PATH pointing at a JSON file holding ${n}.`});let r;try{r=f(e,"utf8")}catch(m){throw new s({error:"unreadable_file",message:`could not read ${e}: ${String(m)}`,field:t,next:"Pass a readable JSON file."})}let i;try{i=JSON.parse(r)}catch(m){throw new s({error:"invalid_json",message:`${e} is not valid JSON: ${String(m)}`,field:t,next:`Write ${n} into the file as JSON.`})}if(typeof i!="object"||i===null||Array.isArray(i))throw new s({error:"invalid_field",message:`${e} must hold a JSON object`,field:t,next:`Write ${n} into the file as a JSON object.`});return i}a(g,"readJsonFile");function q(e){const t=/\.html?$/i.test(e);if(!t&&!e.endsWith(".tsx"))throw new s({error:"invalid_field",message:`page source file must be .tsx, .html, or .htm: ${e}`,field:"page",next:"Author the page as a .tsx module or a complete .html document."});if(!p(e))throw new s({error:"not_found",message:`page source file does not exist: ${e}`,field:"page",next:"Pass --page PATH pointing at the authored page."});return{dialect:t?"html":"jsx",source:f(e,"utf8")}}a(q,"readPageFile");function u(e){const t=typeof e.request_id=="string"?e.request_id.trim():"";if(t==="")throw new s({error:"missing_request_id",message:"a request id is required",field:"request_id",next:"Pass the request_id returned by `crtr human request create`."});return t}a(u,"requestId");function l(e,t=!0){return{...t?{request_id:e.request_id}:{},state:e.state,title:e.title,...e.subtitle===void 0?{}:{subtitle:e.subtitle},source:e.source,emitted_at:e.emitted_at,...e.settled_at===void 0?{}:{settled_at:e.settled_at},...e.responses===void 0?{}:{responses:e.responses},...e.reason===void 0?{}:{reason:e.reason},...e.actor===void 0?{}:{actor:e.actor},...e.action===void 0?{}:{action:e.action},...e.delivery===void 0?{}:{delivery:e.delivery}}}a(l,"requestResult");const h=[{name:"state",type:"pending | answered | dismissed | canceled",required:!0,constraint:"answered: the person (or an authorized responder) submitted the typed responses. dismissed: the recipient surface closed it unanswered. canceled: the requester withdrew it."},{name:"title",type:"string",required:!0,constraint:"Page title as currently published."},{name:"subtitle",type:"string",required:!1,constraint:"Page subtitle when the page carries one."},{name:"source",type:"object",required:!0,constraint:"Stored provenance from the request creator: sessionName?, askedBy?, emittedAt?, profileName?, nodeId?."},{name:"emitted_at",type:"string",required:!0,constraint:"UTC ISO instant of creation; a replace never changes it."},{name:"settled_at",type:"string",required:!1,constraint:"UTC ISO instant of the terminal result. Absent while pending."},{name:"responses",type:"object",required:!1,constraint:"The typed slot map, keyed by response-bearing component id. Present only when state is answered."},{name:"reason",type:"string",required:!1,constraint:"Note recorded by the dismissal or the withdrawal."},{name:"actor",type:"string",required:!1,constraint:"Who settled it, when the settling surface named itself."},{name:"action",type:"object",required:!1,constraint:"{name, payload} frozen at creation; an omitted payload is frozen as null. Absent when no action is bound."},{name:"delivery",type:"object",required:!1,constraint:"Completion-delivery state for the bound action: {state: none | pending | running | accepted | permanent_failed, attempt, next_attempt_at?, accepted_at?, permanent_failed_at?, last_failure?}. Absent when no action is bound."}],b=[{name:"request_id",type:"string",required:!0,constraint:"The request \u2014 the same 64-hex id the human inbox lists it under."},...h],v=o({name:"create",description:"create a durable request from a JSON request file",whenToUse:"a script or backend needs a human decision that must survive its own exit, rather than an answer routed back to a live node.",help:{name:"human request create",summary:"create one durable human request from the typed create object",params:[{kind:"flag",name:"request-file",type:"path",required:!0,constraint:'JSON file holding the create object: {"page":{"dialect":"jsx"|"html","source":"<the authored page text, inline>"}, "delivery"?:{"placement":"inline"|"panel"}, "source"?:{"sessionName"?,"askedBy"?,"emittedAt"?,"profileName"?,"nodeId"?}, "creator_cwd"?:"<absolute dir>", "action"?:{"name":"<declared action>","payload":<any JSON, null when omitted>}}. The page text is inline, never a path \u2014 the request must stay readable after the creating process is gone. creator_cwd defaults to this directory and is the scope the action name resolves from. delivery.inbox and delivery.reply are pinned: a programmatic request is always answerable from the inbox and never routes to an agent bridge. Unknown fields are rejected.'}],output:[{name:"request_id",type:"string",required:!0,constraint:"The created request \u2014 pass it to get/replace/respond/cancel. Stable, and the deduplication key every completion destination keys on."},{name:"action",type:"object",required:!1,constraint:"{name} of the frozen action binding. Absent when the request carries no action."}],outputKind:"object",effects:["Publishes one durable page ticket into the human inbox. It has no reply bridge and outlives this process.","An action name is resolved from the humanActions map in scope config (project ancestors, then user) BEFORE anything is written \u2014 an unknown or unusable name is rejected and leaves no inbox row for a person to answer.","A resolved action is frozen onto the ticket: name, payload, resolved argv, and cwd. replace can never change it; a different effect needs a cancel and a new request."]},run:a(async e=>{const t=e.requestFile,n=g(t,"request-file","the create object");n.creator_cwd===void 0&&(n.creator_cwd=process.cwd());try{const r=await d().createHumanRequest(n);return{request_id:r.request_id,...r.action===void 0?{}:{action:r.action}}}catch(r){c(r)}},"run")}),_=o({name:"get",description:"read one request, its terminal result, and its delivery state",whenToUse:"you need the current state of a request you created \u2014 including the answers, once someone has settled it.",help:{name:"human request get",summary:"read one durable request",params:[{kind:"positional",name:"request_id",type:"string",required:!0,constraint:"request_id returned by `human request create`."}],output:[...b],outputKind:"object",effects:["None. Read-only."]},run:a(async e=>{try{return l(await d().getHumanRequest(u(e)))}catch(t){c(t)}},"run")}),x=o({name:"replace",description:"revise a pending request's page in place",whenToUse:"what you are asking changed while the request is still pending, and the same request should keep its identity and its frozen action.",help:{name:"human request replace",summary:"republish a pending request's page",params:[{kind:"positional",name:"request_id",type:"string",required:!0,constraint:"request_id returned by `human request create`."},{kind:"flag",name:"page",type:"path",required:!0,constraint:"The revised page: a .tsx module or a complete .html/.htm document. Read here and sent inline."}],output:[...h],outputKind:"object",effects:["Rewrites the page and its typed response contract in place; open surfaces reload it without a second request.","Identity is untouched: request id, provenance, emitted time, delivery, and the frozen action binding all survive verbatim.","Refused with already_settled once the request has a terminal result \u2014 a settled request is revised by cancelling and creating a new one."]},run:a(async e=>{const t=u(e),n={page:q(e.page)};try{return l(await d().replaceHumanRequest(t,n),!1)}catch(r){c(r)}},"run")}),k=o({name:"respond",description:"settle a pending request with typed answers",whenToUse:"an authorized host is submitting the answers on the person's behalf, rather than the person answering in their inbox.",help:{name:"human request respond",summary:"answer a pending request",params:[{kind:"positional",name:"request_id",type:"string",required:!0,constraint:"request_id returned by `human request create`."},{kind:"flag",name:"response-file",type:"path",required:!0,constraint:'JSON file holding the respond object: {"responses":{"<component_id>":{...}}, "actor"?:"<who answered>"}. One typed response per response-bearing component; the daemon validates the complete map against the currently published page.'}],output:[...h],outputKind:"object",effects:["Settles the request as answered and drops it from the human inbox.","Competes with the person's own answer, a recipient dismissal, and a requester cancel through one first-writer-wins store: a losing attempt returns already_settled and changes nothing.","When an action is bound, the winning settlement enqueues one at-least-once completion delivery keyed on the request id."]},run:a(async e=>{const t=u(e),n=g(e.responseFile,"response-file","the respond object");try{return l(await d().respondHumanRequest(t,n),!1)}catch(r){c(r)}},"run")}),j=o({name:"cancel",description:"withdraw a pending request",whenToUse:"the decision you asked for stopped mattering, or the effect must change \u2014 the action binding is immutable, so a new effect needs a new request.",help:{name:"human request cancel",summary:"withdraw a pending request",params:[{kind:"positional",name:"request_id",type:"string",required:!0,constraint:"request_id returned by `human request create`."},{kind:"flag",name:"reason",type:"string",required:!1,constraint:"Short note recorded on the terminal result and carried in the completion document."}],output:[...h],outputKind:"object",effects:["Settles the request as canceled and drops it from the human inbox \u2014 the person is no longer asked.","Races the person's answer through the same first-writer-wins store; whoever lands first is authoritative and the loser returns already_settled.","When an action is bound, the winning settlement enqueues one completion delivery carrying the canceled event."]},run:a(async e=>{const t=u(e),n=typeof e.reason=="string"&&e.reason!==""?e.reason:void 0;try{return l(await d().cancelHumanRequest(t,n===void 0?{}:{reason:n}),!1)}catch(r){c(r)}},"run")}),N=w({name:"request",description:"durable requests that outlive the process that made them",whenToUse:"a script or backend needs a human decision whose outcome must survive its own exit, instead of an answer pushed back to a live node.",help:{name:"human request",summary:"durable programmatic human requests \u2014 create, read, revise, and settle",model:"A request is the same page ticket `human send` publishes, minus the agent bridge: nothing waits on it, and the outcome is read with `get` or carried to a local command by a named action. Reach for it when the caller will be gone before the person answers; when a live node should receive the answer, use `crtr human send` instead.\n\nThe page and its typed response contract stay revisable with `replace` while pending. The action binding does not: name, payload, resolved argv, and cwd are frozen at creation, so a different effect means `cancel` plus a new request. An action is a name declared in the humanActions map of scope config \u2014 there is no command, shell string, or callback URL anywhere in this surface.\n\nA request ends exactly once. `respond` (an authorized host answering), the person answering in their own inbox, a recipient dismissal, and `cancel` all compete through one first-writer-wins settlement; the loser gets already_settled and no second delivery. Only the winner enqueues the completion document, delivered at least once \u2014 the receiving command must deduplicate on the request id."},children:[v,_,x,k,j]});export{N as humanRequestBranch};
1
+ var y=Object.defineProperty;var a=(e,t)=>y(e,"name",{value:t,configurable:!0});import{existsSync as p,readFileSync as f}from"node:fs";import{envNodeId as w}from"../../shared/env.js";import{defineBranch as q,defineLeaf as o}from"../../core/command.js";import{InputError as s}from"../../core/io.js";import{cliClient as d,rethrowAsCliError as c}from"../api-client.js";function g(e,t,n){if(!p(e))throw new s({error:"not_found",message:`no such file: ${e}`,field:t,next:`Pass --${t} PATH pointing at a JSON file holding ${n}.`});let r;try{r=f(e,"utf8")}catch(m){throw new s({error:"unreadable_file",message:`could not read ${e}: ${String(m)}`,field:t,next:"Pass a readable JSON file."})}let i;try{i=JSON.parse(r)}catch(m){throw new s({error:"invalid_json",message:`${e} is not valid JSON: ${String(m)}`,field:t,next:`Write ${n} into the file as JSON.`})}if(typeof i!="object"||i===null||Array.isArray(i))throw new s({error:"invalid_field",message:`${e} must hold a JSON object`,field:t,next:`Write ${n} into the file as a JSON object.`});return i}a(g,"readJsonFile");function b(e){const t=/\.html?$/i.test(e);if(!t&&!e.endsWith(".tsx"))throw new s({error:"invalid_field",message:`page source file must be .tsx, .html, or .htm: ${e}`,field:"page",next:"Author the page as a .tsx module or a complete .html document."});if(!p(e))throw new s({error:"not_found",message:`page source file does not exist: ${e}`,field:"page",next:"Pass --page PATH pointing at the authored page."});return{dialect:t?"html":"jsx",source:f(e,"utf8")}}a(b,"readPageFile");function u(e){const t=typeof e.request_id=="string"?e.request_id.trim():"";if(t==="")throw new s({error:"missing_request_id",message:"a request id is required",field:"request_id",next:"Pass the request_id returned by `crtr human request create`."});return t}a(u,"requestId");function l(e,t=!0){return{...t?{request_id:e.request_id}:{},state:e.state,title:e.title,...e.subtitle===void 0?{}:{subtitle:e.subtitle},source:e.source,emitted_at:e.emitted_at,...e.settled_at===void 0?{}:{settled_at:e.settled_at},...e.responses===void 0?{}:{responses:e.responses},...e.reason===void 0?{}:{reason:e.reason},...e.actor===void 0?{}:{actor:e.actor},...e.action===void 0?{}:{action:e.action},...e.delivery===void 0?{}:{delivery:e.delivery}}}a(l,"requestResult");const h=[{name:"state",type:"pending | answered | dismissed | canceled",required:!0,constraint:"answered: the person (or an authorized responder) submitted the typed responses. dismissed: the recipient surface closed it unanswered. canceled: the requester withdrew it."},{name:"title",type:"string",required:!0,constraint:"Page title as currently published."},{name:"subtitle",type:"string",required:!1,constraint:"Page subtitle when the page carries one."},{name:"source",type:"object",required:!0,constraint:"Stored provenance from the request creator: sessionName?, askedBy?, emittedAt?, profileName?, nodeId?."},{name:"emitted_at",type:"string",required:!0,constraint:"UTC ISO instant of creation; a replace never changes it."},{name:"settled_at",type:"string",required:!1,constraint:"UTC ISO instant of the terminal result. Absent while pending."},{name:"responses",type:"object",required:!1,constraint:"The typed slot map, keyed by response-bearing component id. Present only when state is answered."},{name:"reason",type:"string",required:!1,constraint:"Note recorded by the dismissal or the withdrawal."},{name:"actor",type:"string",required:!1,constraint:"Who settled it, when the settling surface named itself."},{name:"action",type:"object",required:!1,constraint:"{name, payload} frozen at creation; an omitted payload is frozen as null. Absent when no action is bound."},{name:"delivery",type:"object",required:!1,constraint:"Completion-delivery state for the bound action: {state: none | pending | running | accepted | permanent_failed, attempt, next_attempt_at?, accepted_at?, permanent_failed_at?, last_failure?}. Absent when no action is bound."}],v=[{name:"request_id",type:"string",required:!0,constraint:"The request \u2014 the same 64-hex id the human inbox lists it under."},...h],_=o({name:"create",description:"create a durable request from a JSON request file",whenToUse:"a script or backend needs a human decision that must survive its own exit, rather than an answer routed back to a live node.",help:{name:"human request create",summary:"create one durable human request from the typed create object",params:[{kind:"flag",name:"request-file",type:"path",required:!0,constraint:'JSON file holding the create object: {"page":{"dialect":"jsx"|"html","source":"<the authored page text, inline>"}, "delivery"?:{"placement":"inline"|"panel"}, "source"?:{"sessionName"?,"askedBy"?,"emittedAt"?,"profileName"?,"nodeId"?}, "creator_cwd"?:"<absolute dir>", "action"?:{"name":"<declared action>","payload":<any JSON, null when omitted>}}. The page text is inline, never a path \u2014 the request must stay readable after the creating process is gone. creator_cwd defaults to this directory and is the scope the action name resolves from. delivery.inbox and delivery.reply are pinned: a programmatic request is always answerable from the inbox and never routes to an agent bridge. Unknown fields are rejected.'}],output:[{name:"request_id",type:"string",required:!0,constraint:"The created request \u2014 pass it to get/replace/respond/cancel. Stable, and the deduplication key every completion destination keys on."},{name:"action",type:"object",required:!1,constraint:"{name} of the frozen action binding. Absent when the request carries no action."}],outputKind:"object",effects:["Publishes one durable page ticket into the human inbox. It has no reply bridge and outlives this process.","An action name is resolved from the humanActions map in scope config (project ancestors, then user) BEFORE anything is written \u2014 an unknown or unusable name is rejected and leaves no inbox row for a person to answer.","A resolved action is frozen onto the ticket: name, payload, resolved argv, and cwd. replace can never change it; a different effect needs a cancel and a new request."]},run:a(async e=>{const t=e.requestFile,n=g(t,"request-file","the create object");n.creator_cwd===void 0&&(n.creator_cwd=process.cwd()),n.requester_node_id===void 0&&(n.requester_node_id=w()??null);try{const r=await d().createHumanRequest(n);return{request_id:r.request_id,...r.action===void 0?{}:{action:r.action}}}catch(r){c(r)}},"run")}),x=o({name:"get",description:"read one request, its terminal result, and its delivery state",whenToUse:"you need the current state of a request you created \u2014 including the answers, once someone has settled it.",help:{name:"human request get",summary:"read one durable request",params:[{kind:"positional",name:"request_id",type:"string",required:!0,constraint:"request_id returned by `human request create`."}],output:[...v],outputKind:"object",effects:["None. Read-only."]},run:a(async e=>{try{return l(await d().getHumanRequest(u(e)))}catch(t){c(t)}},"run")}),k=o({name:"replace",description:"revise a pending request's page in place",whenToUse:"what you are asking changed while the request is still pending, and the same request should keep its identity and its frozen action.",help:{name:"human request replace",summary:"republish a pending request's page",params:[{kind:"positional",name:"request_id",type:"string",required:!0,constraint:"request_id returned by `human request create`."},{kind:"flag",name:"page",type:"path",required:!0,constraint:"The revised page: a .tsx module or a complete .html/.htm document. Read here and sent inline."}],output:[...h],outputKind:"object",effects:["Rewrites the page and its typed response contract in place; open surfaces reload it without a second request.","Identity is untouched: request id, provenance, emitted time, delivery, and the frozen action binding all survive verbatim.","Refused with already_settled once the request has a terminal result \u2014 a settled request is revised by cancelling and creating a new one."]},run:a(async e=>{const t=u(e),n={page:b(e.page)};try{return l(await d().replaceHumanRequest(t,n),!1)}catch(r){c(r)}},"run")}),j=o({name:"respond",description:"settle a pending request with typed answers",whenToUse:"an authorized host is submitting the answers on the person's behalf, rather than the person answering in their inbox.",help:{name:"human request respond",summary:"answer a pending request",params:[{kind:"positional",name:"request_id",type:"string",required:!0,constraint:"request_id returned by `human request create`."},{kind:"flag",name:"response-file",type:"path",required:!0,constraint:'JSON file holding the respond object: {"responses":{"<component_id>":{...}}, "actor"?:"<who answered>"}. One typed response per response-bearing component; the daemon validates the complete map against the currently published page.'}],output:[...h],outputKind:"object",effects:["Settles the request as answered and drops it from the human inbox.","Competes with the person's own answer, a recipient dismissal, and a requester cancel through one first-writer-wins store: a losing attempt returns already_settled and changes nothing.","When an action is bound, the winning settlement enqueues one at-least-once completion delivery keyed on the request id."]},run:a(async e=>{const t=u(e),n=g(e.responseFile,"response-file","the respond object");try{return l(await d().respondHumanRequest(t,n),!1)}catch(r){c(r)}},"run")}),S=o({name:"cancel",description:"withdraw a pending request",whenToUse:"the decision you asked for stopped mattering, or the effect must change \u2014 the action binding is immutable, so a new effect needs a new request.",help:{name:"human request cancel",summary:"withdraw a pending request",params:[{kind:"positional",name:"request_id",type:"string",required:!0,constraint:"request_id returned by `human request create`."},{kind:"flag",name:"reason",type:"string",required:!1,constraint:"Short note recorded on the terminal result and carried in the completion document."}],output:[...h],outputKind:"object",effects:["Settles the request as canceled and drops it from the human inbox \u2014 the person is no longer asked.","Races the person's answer through the same first-writer-wins store; whoever lands first is authoritative and the loser returns already_settled.","When an action is bound, the winning settlement enqueues one completion delivery carrying the canceled event."]},run:a(async e=>{const t=u(e),n=typeof e.reason=="string"&&e.reason!==""?e.reason:void 0;try{return l(await d().cancelHumanRequest(t,n===void 0?{}:{reason:n}),!1)}catch(r){c(r)}},"run")}),P=q({name:"request",description:"durable requests that outlive the process that made them",whenToUse:"a script or backend needs a human decision whose outcome must survive its own exit, instead of an answer pushed back to a live node.",help:{name:"human request",summary:"durable programmatic human requests \u2014 create, read, revise, and settle",model:"A request is the same page ticket `human send` publishes, minus the agent bridge: nothing waits on it, and the outcome is read with `get` or carried to a local command by a named action. Reach for it when the caller will be gone before the person answers; when a live node should receive the answer, use `crtr human send` instead.\n\nThe page and its typed response contract stay revisable with `replace` while pending. The action binding does not: name, payload, resolved argv, and cwd are frozen at creation, so a different effect means `cancel` plus a new request. An action is a name declared in the humanActions map of scope config \u2014 there is no command, shell string, or callback URL anywhere in this surface.\n\nA request ends exactly once. `respond` (an authorized host answering), the person answering in their own inbox, a recipient dismissal, and `cancel` all compete through one first-writer-wins settlement; the loser gets already_settled and no second delivery. Only the winner enqueues the completion document, delivered at least once \u2014 the receiving command must deduplicate on the request id."},children:[_,x,k,j,S]});export{P as humanRequestBranch};
@@ -1 +1 @@
1
- var F=Object.defineProperty;var p=(e,a)=>F(e,"name",{value:a,configurable:!0});import{envGrantee as q,envProfileId as b}from"../../shared/env.js";import{requiredPluginEnv as I}from"../../core/plugin-env.js";import{createHash as x}from"node:crypto";import{lstat as w,readFile as T,readdir as _,readlink as E}from"node:fs/promises";import{dirname as C,isAbsolute as A,join as h,relative as H,resolve as j,sep as M}from"node:path";import{defineLeaf as L}from"../../core/command.js";import{normalizeRequires as B,readConfig as G,updateConfig as K}from"../../core/config.js";import{scopeRoot as S,listScopes as z,marketplacesDir as W,pluginsDir as J}from"../../core/scope.js";import{readMarketplaceManifest as V,readPluginManifest as U}from"../../core/manifest.js";import{pathExists as $,listDirs as O,removePath as Z}from"../../core/fs-utils.js";import{lsRemote as Q}from"../../core/git.js";import{cliClient as P}from"../api-client.js";import{detectNerdFont as X,nerdFontInstallCommand as Y,NERD_FONT_SELECT_HINT as R}from"../../core/runtime/nerd-font.js";import{detectPackageManager as ee}from"./setup-core.js";import{validateEffectiveCommandPlugins as ne}from"../../core/command-plugins/discovery.js";import{adaptPluginContributions as te}from"../../core/command-plugins/compose.js";import{resolveCommandRegistry as ie}from"../../core/command-manifests/registry.js";import{applyCommandExtensions as oe,orphanCommandExtensionValidations as ae}from"../../core/command-plugins/extensions.js";import{discoverHookRegistry as se}from"../../core/command-hooks/discovery.js";import{resolveBinContributions as re}from"../../core/runtime/bin-contributions.js";import{inspectHumanActions as ce}from"../../core/human-actions.js";import{composeAppProcessEnv as le,overlayBrokerEnv as ue,resolvePathExecutable as me}from"../../core/runtime/spawn-env.js";import{listAllPlugins as de}from"../../core/resolver.js";import{SUBTREE_NAMES as pe,coreCommandPaths as fe,coreHookCatalog as he,extensibleCoreBranches as ge}from"../../build-root.js";import{processGeneration as $e,processLocatedGeneration as ye,runtimeManifest as y,selectedGeneration as ve}from"./shared.js";import{CONFIG_FILE as ke}from"../../types.js";function f(e,a,i){return{scope:e,name:a,status:"pass",message:i}}p(f,"pass");function d(e,a,i,l){return{scope:e,name:a,status:"fail",message:i,...l?{remediation:l}:{}}}p(d,"failCheck");async function k(e){try{switch(e.kind){case"remove_config_key":{if(!e.scope||!e.configKey)return!1;const a=e.configKey.split(".");return await K(e.scope,i=>{let l=i;for(let s=0;s<a.length-1;s++){const n=l[a[s]];if(typeof n!="object"||n===null)return;l=n}delete l[a[a.length-1]]}),!0}case"rm_path":return e.path?(Z(e.path),!0):!1;case"human_action":return!1;default:return!1}}catch{return!1}}p(k,"applyRemediation");function we(e){return[`${e.link} ${e.kind}`,`disposition=${e.retry.disposition}`,typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`attempt=${e.retry.attempt}/${e.retry.max}`:void 0,typeof e.retry.nextAt=="string"?`nextAt=${e.retry.nextAt}`:void 0].filter(i=>i!==void 0).join(" \xB7 ")}p(we,"faultMessage");function N(e){return/^[A-Za-z0-9._:/@%+=,-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}p(N,"shellArgument");function be(e,a){const i={connection:"restore connectivity","rate-limit":"wait for the rate limit to clear",overloaded:"wait for load to drop",auth:"re-authenticate",protocol:"fix the protocol mismatch","context-overflow":"shrink the task or loaded context, or choose a larger-context model before spawning the node again",other:"fix the underlying issue",wedged:"read `crtr canvas read wedged-child-on-runaway-bash` \u2014 if a runaway subprocess is to blame, kill it (not the node); if the broker had no subprocess, the daemon SIGTERM-kicks it and starts a fresh recovery cycle automatically","model-not-found":"pass a valid `--model provider/id` or configure credentials for an authenticated provider, then revive the node (`crtr node lifecycle revive <id>`)"},l=e.retry.disposition==="auto"?e.retry.by==="client"?"client redialing":typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`auto-retrying, attempt ${e.retry.attempt}/${e.retry.max}`:"auto-retrying":e.retry.disposition==="fatal"?"parked fatal":"manual",s=`crtr sys logs --node ${N(a)} --operation ${N(e.operation_id)}`;return{kind:"human_action",description:`${i[e.kind]}; ${l}; inspect the correlated operation with ${s}`,command:s}}p(be,"faultRemediation");async function xe(e){const a=[],i=new Set(e),l=new Set(pe),[s,n]=await Promise.all([fe(),ge()]),u=ne(l,void 0,void 0,s,n);for(const c of u){const t=c.plugin;if(!i.has(t.scope))continue;const r=c.issues.filter(o=>o.code!=="command_collision");if(r.length===0){const o=c.contributions.map(m=>m.node.name).join(", ");a.push(f(t.scope,`plugin:${t.name}:commands`,o.length>0?`contributes top-level command(s): ${o}`:"command manifest valid"));continue}r.forEach((o,m)=>{const g={kind:"human_action",description:`${o.next} Inspect with \`pkg plugin show ${t.name}\`; then update (\`pkg plugin update --name ${t.name}\`) or remove (\`pkg plugin remove ${t.name}\`) the plugin.`},v=o.path!==void 0?` at ${o.path}`:"";a.push(d(t.scope,`plugin:${t.name}:commands[${m}]`,`${o.code}${v}: ${o.message} (received ${o.received}, expected ${o.expected})`,g))})}if(i.has("project")){const c=ie(te(u.flatMap(o=>o.contributions)).contributions,l),r=[...oe(c.contributions).validations,...ae(c.contributions)];for(const o of r){if(o.issue===void 0){a.push(f("project",`extension:${o.branch}`,`repository fragment valid: ${o.fragmentPath}`));continue}const m=o.issue;a.push(d("project",`extension:${o.branch}`,`${m.code} at ${m.path??o.fragmentPath}: ${m.message} (received ${m.received}, expected ${m.expected})`,{kind:"human_action",description:m.next}))}}return a}p(xe,"runCommandPluginChecks");async function _e(e){const a=new Set(e),i=se(await he()),l=[];for(const s of i.validations){const n=s.plugin;if(!a.has(n.scope))continue;const u=i.issues.filter(c=>c.plugin===n.name&&c.scope===n.scope);if(u.length===0){const c=s.hooks.map(r=>`${r.target} [${r.phase} ${r.op}]`),t=(s.manifest?.schemaVersion===2?s.manifest.lifecycle:[]).map(r=>`${r.event} [${r.phase} ${r.op}; effects: ${r.effects.join(", ")}]`);l.push(f(n.scope,`plugin:${n.name}:hooks`,`effective hook declaration(s): ${[...c,...t].join("; ")}`));continue}u.forEach((c,t)=>{const r=s.manifestPath??h(n.root,".crouter-plugin","plugin.json"),o=c.path!==void 0?`${r}:${c.path}`:r;l.push(d(n.scope,`plugin:${n.name}:hooks[${t}]`,`${c.code} at ${o}: ${c.message} (received ${c.received}, expected ${c.expected})`,{kind:"human_action",description:`${c.next} Inspect with \`crtr pkg plugin show ${n.name}\`; then disable (\`crtr pkg plugin disable ${n.name} --scope ${n.scope}\`), update (\`crtr pkg plugin update --name ${n.name}\`), or remove (\`crtr pkg plugin remove ${n.name}\`) the plugin.`}))})}return l}p(_e,"runHookPluginChecks");function Ee(e){const a=new Set(e),{bins:i,issues:l}=re(process.cwd(),b()||null),s=[];for(const n of l)a.has(n.scope)&&s.push(d(n.scope,`bin:${n.name}`,`${n.origin}: ${n.message}`,{kind:"human_action",description:`Fix the \`bin.${n.name}\` declaration in ${n.origin} \u2014 point it at an executable regular file inside that contributor's own root, or remove it. A same-precedence collision is resolved by renaming one of the claimants.`}));for(const n of i.values())a.has(n.scope)&&s.push(f(n.scope,`bin:${n.name}`,`${n.origin} \u2192 ${n.target}`));return s}p(Ee,"runBinContributionChecks");function Ce(e){const a=new Set(e),i=h(S("user"),ke),l=[],s=new Map;for(const n of ce(process.cwd())){if("kind"in n){if(n.kind==="unknown_action")continue;const r=n.configOrigin===i?"user":"project",o=n.block===!0,m=o?void 0:s.get(n.name);if(!o&&m===void 0&&s.set(n.name,n.configOrigin),!a.has(r))continue;const g=o?`humanActions:block@${n.configOrigin}`:`humanActions:${n.name}@${n.configOrigin}`,v={kind:"human_action",description:o?`Fix or remove the \`humanActions\` block in ${n.configOrigin}. Actions run argv directly without a shell.`:`Fix or remove the \`humanActions.${n.name}\` declaration in ${n.configOrigin}. Actions run argv directly without a shell.`};m!==void 0?l.push({scope:r,name:g,status:"pass",message:`warning: shadowed by ${m}; ${n.configOrigin}: ${n.reason}`,remediation:v}):l.push(d(r,g,`${n.configOrigin}: ${n.reason}`,v));continue}const u=n.configOrigin===i?"user":"project",c=s.get(n.name);if(c===void 0&&s.set(n.name,n.configOrigin),!a.has(u))continue;const t=c===void 0?"":`shadowed by ${c}; `;l.push(f(u,`humanActions:${n.name}@${n.configOrigin}`,`${t}${n.configOrigin} \u2192 ${n.argv[0]} (cwd ${n.cwd})`))}return l}p(Ce,"runHumanActionChecks");async function Ae(e){const a=new Set(e),i=b()??null,l=q()??"app:terminal",s=P(),n=p(t=>Object.fromEntries(t.map(r=>[r,""])),"present"),u=ue({argv:[],env:{CRTR_NODE_CWD:process.cwd(),CRTR_PROFILE_ID:i??"",CRTR_GRANTEE:l}},le(process.cwd(),i,l,n((await s.listAppEnv()).names),i===null?{}:n((await s.listProfileEnv(i)).names))),c=[];for(const t of de())if(!(!a.has(t.scope)||!t.enabled)){for(const r of I(t.manifest.env))u[r]!==void 0?c.push(f(t.scope,`env:${r}`,`plugin "${t.name}" has ${r}`)):c.push(d(t.scope,`env:${r}`,`plugin "${t.name}" needs ${r}`,{kind:"human_action",description:`crtr sys env set --name ${r}`}));if(t.manifest.requires!==void 0)for(const[r,o]of Object.entries(B(t.manifest.requires))){const m=me(r,u,process.cwd());m!==null?c.push(f(t.scope,`requires:${r}`,`plugin "${t.name}" \u2192 ${m}`)):c.push(d(t.scope,`requires:${r}`,`plugin "${t.name}" requires executable "${r}" on PATH`,{kind:"human_action",description:o}))}}return c}p(Ae,"runRequiresChecks");async function je(e){const a=[];async function i(l){for(const s of await _(l)){const n=h(l,s),u=H(e,n).replaceAll(M,"/");if(u==="generation.json")continue;const c=await w(n);if(c.isDirectory())await i(n);else if(c.isFile()){const t=await T(n);a.push({path:u,size:c.size,sha256:x("sha256").update(t).digest("hex")})}else if(c.isSymbolicLink()){const t=await E(n);if(A(t)||!y.contained(e,j(C(n),t)))throw new Error(`generation symlink escapes root: ${u}`);a.push({path:u,size:Buffer.byteLength(t),sha256:x("sha256").update(t).digest("hex"),symlink:!0})}else throw new Error(`unsupported generation file: ${u}`)}}return p(i,"walk"),await i(e),y.sortInventory(a)}p(je,"inventory");async function Se(e){async function a(i){const l=await w(i);if(!l.isDirectory()||l.isSymbolicLink())throw new Error(`generation directory is invalid: ${i}`);if((l.mode&146)!==0)throw new Error(`generation path is writable: ${i}`);for(const s of await _(i)){const n=h(i,s),u=await w(n);if(u.isDirectory())await a(n);else if(u.isFile()){if((u.mode&146)!==0)throw new Error(`generation path is writable: ${n}`)}else if(u.isSymbolicLink()){const c=await E(n);if(A(c)||!y.contained(e,j(C(n),c)))throw new Error(`generation symlink escapes root: ${n}`)}else throw new Error(`unsupported generation file: ${n}`)}}p(a,"walk"),await a(e)}p(Se,"verifySealed");function Oe(){const e=X();if(e.installed)return f("user","terminal:nerd-font",`installed (${e.evidence}) \u2014 if icons still render as boxes, ${R}`);const a=Y(ee());return d("user","terminal:nerd-font","no Nerd Font installed \u2014 viewer tool/command icons will render as tofu boxes",{kind:"human_action",description:`Install a Nerd Font (${a.hint}), ${R}`,...a.command?{command:a.command}:{}})}p(Oe,"runNerdFontCheck");async function D(e,a,i){if(a.generation===null){const u=a.error??"no runtime generation";return[i?f("canvas",`runtime:${e}`,u):d("canvas",`runtime:${e}`,u)]}const l=a.generation,s=[],n=y.validateManifestShape(l.manifest,{id:l.id,entryName:"cli"});if(!n.ok)return[d("canvas",`runtime:${e}:manifest`,n.error)];s.push(f("canvas",`runtime:${e}:manifest`,`${l.id} ${l.manifest.packageVersion}`));try{await Se(l.root),s.push(f("canvas",`runtime:${e}:sealing`,"generation tree is sealed and contained"))}catch(u){s.push(d("canvas",`runtime:${e}:sealing`,u instanceof Error?u.message:String(u)))}try{const u=await je(l.root),c=y.sortInventory(l.manifest.files);JSON.stringify(l.manifest.files)!==JSON.stringify(c)?s.push(d("canvas",`runtime:${e}:inventory`,"manifest inventory is not in canonical runtime-generation-manifest order")):JSON.stringify(u)!==JSON.stringify(c)?s.push(d("canvas",`runtime:${e}:inventory`,"full generation inventory hash does not match generation.json")):s.push(f("canvas",`runtime:${e}:inventory`,`${u.length} files hash-verified`))}catch(u){s.push(d("canvas",`runtime:${e}:inventory`,u instanceof Error?u.message:String(u)))}return s}p(D,"generationChecks");async function Pe(){const e=[];for(const a of await P().listNodes()){const i=a.fault??null;if(i===null)continue;const l=`fault:${a.node_id}:${i.link}`,s=be(i,a.node_id);e.push(d("canvas",l,we(i),s))}return e}p(Pe,"runFaultChecks");async function Re(e,a){const i=[];if(!S(e))return i;const s=G(e),n=W(e);for(const t of Object.keys(s.marketplaces)){if(!n){i.push(d(e,`marketplace:${t}:dir`,"marketplaces directory unavailable"));continue}const r=h(n,t);if($(r))i.push(f(e,`marketplace:${t}:dir`,"directory exists"));else{const o={kind:"remove_config_key",description:`Drop stale config entry config.${e}.marketplaces.${t}`,scope:e,configKey:`marketplaces.${t}`};a.fix&&await k(o)?i.push({scope:e,name:`marketplace:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:o}):i.push(d(e,`marketplace:${t}:dir`,`directory missing: ${r}`,o))}}const u=J(e);for(const t of Object.keys(s.plugins)){if(!u){i.push(d(e,`plugin:${t}:dir`,"plugins directory unavailable"));continue}const r=h(u,t);if($(r))i.push(f(e,`plugin:${t}:dir`,"directory exists"));else{const o={kind:"remove_config_key",description:`Drop stale config entry config.${e}.plugins.${t}`,scope:e,configKey:`plugins.${t}`};a.fix&&await k(o)?i.push({scope:e,name:`plugin:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:o}):i.push(d(e,`plugin:${t}:dir`,`directory missing: ${r}`,o))}}if(n&&$(n))for(const t of O(n)){const r=h(n,t),o=V(r);if(o){i.push(f(e,`marketplace:${t}:manifest`,"manifest valid"));for(const m of o.plugins){if(m.source.startsWith("http://")||m.source.startsWith("https://")||m.source.startsWith("git@"))continue;const g=h(r,m.source);$(g)?i.push(f(e,`marketplace:${t}:plugin-source:${m.name}`,"source resolves")):i.push(d(e,`marketplace:${t}:plugin-source:${m.name}`,`source path does not resolve: ${g}`))}}else{const m={kind:"rm_path",description:"Remove dangling marketplace directory (no valid .crouter-marketplace/marketplace.json)",path:r};a.fix&&await k(m)?i.push({scope:e,name:`marketplace:${t}:manifest`,status:"fail",message:"no valid marketplace.json \u2014 removed dangling directory",fixed:!0,remediation:m}):i.push(d(e,`marketplace:${t}:manifest`,`no valid marketplace.json in ${r}`,m))}}const c=new Map;if(u&&$(u))for(const t of O(u)){const r=h(u,t),o=U(r);if(!o){const m={kind:"rm_path",description:"Remove dangling plugin directory (no valid .crouter-plugin/plugin.json)",path:r};a.fix&&await k(m)?i.push({scope:e,name:`plugin:${t}:manifest`,status:"fail",message:"no valid plugin.json \u2014 removed dangling directory",fixed:!0,remediation:m}):i.push(d(e,`plugin:${t}:manifest`,`no valid plugin.json in ${r}`,m));continue}i.push(f(e,`plugin:${t}:manifest`,"manifest valid")),c.has(t)?i.push(d(e,`plugin:${t}:duplicate`,`duplicate plugin name within scope (also at ${c.get(t)})`)):c.set(t,r),a.remote&&o.source&&(Q(o.source).status!==0?i.push(d(e,`plugin:${t}:remote`,`git remote unreachable: ${o.source}`)):i.push(f(e,`plugin:${t}:remote`,"git remote reachable")))}return i}p(Re,"runChecksForScope");const rn=L({name:"doctor",description:"diagnose installation health",whenToUse:"something in your crtr install looks off and you want it diagnosed \u2014 a plugin or marketplace manifest is missing, a config entry points at a directory that no longer exists, or a plugin command/hook declaration is malformed. Reports each problem with a structured remediation, and can apply the safe repairs for you.",help:{name:"sys doctor",summary:"diagnose runtime integrity, missing manifests, and broken config entries",params:[{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Scope to check. Default: all scopes."},{kind:"flag",name:"fix",type:"bool",required:!1,constraint:"Apply each non-pass check's remediation and report what was fixed."},{kind:"flag",name:"remote",type:"bool",required:!1,constraint:"Check git remotes with ls-remote (slow \u2014 makes network calls)."}],output:[{name:"checks",type:"object[]",required:!0,constraint:"Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. humanActions:<name>@<config-origin> checks validate each user/project scope completion-action declaration: action-name and argv shape, cwd directory, argv[0] regular-file existence, and execute permission; they never execute an action. A malformed effective declaration fails; a malformed shadowed declaration is a pass-level warning that names the winning and shadowed origins. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer's icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/event/collision problems and carry disable/update/remove/show remediation; healthy command hooks list effective target, phase, and op, while lifecycle hooks list event, phase, op, and effects. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name."},{name:"ok",type:"boolean",required:!0,constraint:"True when no unresolved fail checks remain."}],outputKind:"object",effects:["Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, humanActions declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.","With --fix: applies each non-pass check's `remediation` \u2014 removes stale config entries and deletes dangling plugin/marketplace directories; canvas fault findings and plugin command/hook findings stay read-only (--fix never chmods or rewrites third-party plugin content).","Each non-pass result carries a structured `remediation` describing the fix action (absolute paths, exact config keys, or a human_action with its command) so callers can apply it directly without --fix."]},run:p(async e=>{const a=e.scope,i=e.fix,l=e.remote,s=z(a),n=[];for(const o of s){const m=await Re(o,{fix:i,remote:l});n.push(...m)}s.includes("user")&&n.push(Oe()),n.push(...await xe(s)),n.push(...await _e(s)),n.push(...Ee(s)),n.push(...Ce(s)),n.push(...await Ae(s)),n.push(...await Pe());const u=$e();n.push(...await D("selected",ve(),u===null)),n.push(...await D("process",ye(),!0));const c={user:0,project:1,builtin:2,canvas:3};n.sort((o,m)=>o.scope!==m.scope?c[o.scope]-c[m.scope]:o.name.localeCompare(m.name));const t=!n.some(o=>o.status==="fail"&&o.fixed!==!0),r=n.filter(o=>o.status==="fail"&&o.fixed!==!0).length;return{checks:n,ok:t,failed:r}},"run")});export{xe as runCommandPluginChecks,rn as sysDoctorLeaf};
1
+ var D=Object.defineProperty;var p=(e,o)=>D(e,"name",{value:o,configurable:!0});import{envGrantee as q,envProfileId as x}from"../../shared/env.js";import{requiredPluginEnv as I}from"../../core/plugin-env.js";import{createHash as _}from"node:crypto";import{lstat as w,readFile as T,readdir as E,readlink as C}from"node:fs/promises";import{readFileSync as H}from"node:fs";import{dirname as b,isAbsolute as S,join as h,relative as L,resolve as j,sep as M}from"node:path";import{defineLeaf as B}from"../../core/command.js";import{normalizeRequires as G,readConfig as K,updateConfig as z}from"../../core/config.js";import{scopeRoot as A,listScopes as J,marketplacesDir as W,pluginsDir as V}from"../../core/scope.js";import{readMarketplaceManifest as U,readPluginManifest as Z}from"../../core/manifest.js";import{pathExists as $,listDirs as O,removePath as Q}from"../../core/fs-utils.js";import{lsRemote as X}from"../../core/git.js";import{cliClient as P}from"../api-client.js";import{detectNerdFont as Y,nerdFontInstallCommand as ee,NERD_FONT_SELECT_HINT as R}from"../../core/runtime/nerd-font.js";import{detectPackageManager as ne}from"./setup-core.js";import{validateEffectiveCommandPlugins as te}from"../../core/command-plugins/discovery.js";import{adaptPluginContributions as ie}from"../../core/command-plugins/compose.js";import{resolveCommandRegistry as oe}from"../../core/command-manifests/registry.js";import{applyCommandExtensions as ae,orphanCommandExtensionValidations as se}from"../../core/command-plugins/extensions.js";import{discoverHookRegistry as re}from"../../core/command-hooks/discovery.js";import{resolveBinContributions as ce}from"../../core/runtime/bin-contributions.js";import{inspectHumanActions as le}from"../../core/human-actions.js";import{composeAppProcessEnv as de,overlayBrokerEnv as ue,resolvePathExecutable as me}from"../../core/runtime/spawn-env.js";import{listAllPlugins as pe}from"../../core/resolver.js";import{SUBTREE_NAMES as fe,coreCommandPaths as he,coreHookCatalog as ge,extensibleCoreBranches as $e}from"../../build-root.js";import{processGeneration as ye,processLocatedGeneration as ve,runtimeManifest as y,selectedGeneration as ke}from"./shared.js";import{CONFIG_FILE as we}from"../../types.js";function f(e,o,i){return{scope:e,name:o,status:"pass",message:i}}p(f,"pass");function m(e,o,i,a){return{scope:e,name:o,status:"fail",message:i,...a?{remediation:a}:{}}}p(m,"failCheck");async function k(e){try{switch(e.kind){case"remove_config_key":{if(!e.scope||!e.configKey)return!1;const o=e.configKey.split(".");return await z(e.scope,i=>{let a=i;for(let r=0;r<o.length-1;r++){const n=a[o[r]];if(typeof n!="object"||n===null)return;a=n}delete a[o[o.length-1]]}),!0}case"rm_path":return e.path?(Q(e.path),!0):!1;case"human_action":return!1;default:return!1}}catch{return!1}}p(k,"applyRemediation");function be(e){return[`${e.link} ${e.kind}`,`disposition=${e.retry.disposition}`,typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`attempt=${e.retry.attempt}/${e.retry.max}`:void 0,typeof e.retry.nextAt=="string"?`nextAt=${e.retry.nextAt}`:void 0].filter(i=>i!==void 0).join(" \xB7 ")}p(be,"faultMessage");function N(e){return/^[A-Za-z0-9._:/@%+=,-]+$/u.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}p(N,"shellArgument");function xe(e,o){const i={connection:"restore connectivity","rate-limit":"wait for the rate limit to clear",overloaded:"wait for load to drop",auth:"re-authenticate",protocol:"fix the protocol mismatch","context-overflow":"shrink the task or loaded context, or choose a larger-context model before spawning the node again",other:"fix the underlying issue",wedged:"read `crtr canvas read wedged-child-on-runaway-bash` \u2014 if a runaway subprocess is to blame, kill it (not the node); if the broker had no subprocess, the daemon SIGTERM-kicks it and starts a fresh recovery cycle automatically","model-not-found":"pass a valid `--model provider/id` or configure credentials for an authenticated provider, then revive the node (`crtr node lifecycle revive <id>`)"},a=e.retry.disposition==="auto"?e.retry.by==="client"?"client redialing":typeof e.retry.attempt=="number"&&typeof e.retry.max=="number"?`auto-retrying, attempt ${e.retry.attempt}/${e.retry.max}`:"auto-retrying":e.retry.disposition==="fatal"?"parked fatal":"manual",r=`crtr sys logs --node ${N(o)} --operation ${N(e.operation_id)}`;return{kind:"human_action",description:`${i[e.kind]}; ${a}; inspect the correlated operation with ${r}`,command:r}}p(xe,"faultRemediation");async function _e(e){const o=[],i=new Set(e),a=new Set(fe),[r,n]=await Promise.all([he(),$e()]),d=te(a,void 0,void 0,r,n);for(const l of d){const t=l.plugin;if(!i.has(t.scope))continue;const c=l.issues.filter(s=>s.code!=="command_collision");if(c.length===0){const s=l.contributions.map(u=>u.node.name).join(", ");o.push(f(t.scope,`plugin:${t.name}:commands`,s.length>0?`contributes top-level command(s): ${s}`:"command manifest valid"));continue}c.forEach((s,u)=>{const g={kind:"human_action",description:`${s.next} Inspect with \`pkg plugin show ${t.name}\`; then update (\`pkg plugin update --name ${t.name}\`) or remove (\`pkg plugin remove ${t.name}\`) the plugin.`},v=s.path!==void 0?` at ${s.path}`:"";o.push(m(t.scope,`plugin:${t.name}:commands[${u}]`,`${s.code}${v}: ${s.message} (received ${s.received}, expected ${s.expected})`,g))})}if(i.has("project")){const l=oe(ie(d.flatMap(s=>s.contributions)).contributions,a),c=[...ae(l.contributions).validations,...se(l.contributions)];for(const s of c){if(s.issue===void 0){o.push(f("project",`extension:${s.branch}`,`repository fragment valid: ${s.fragmentPath}`));continue}const u=s.issue;o.push(m("project",`extension:${s.branch}`,`${u.code} at ${u.path??s.fragmentPath}: ${u.message} (received ${u.received}, expected ${u.expected})`,{kind:"human_action",description:u.next}))}}return o}p(_e,"runCommandPluginChecks");async function Ee(e){const o=new Set(e),i=re(await ge()),a=[];for(const r of i.validations){const n=r.plugin;if(!o.has(n.scope))continue;const d=i.issues.filter(l=>l.plugin===n.name&&l.scope===n.scope);if(d.length===0){const l=r.hooks.map(c=>`${c.target} [${c.phase} ${c.op}]`),t=(r.manifest?.schemaVersion===2?r.manifest.lifecycle:[]).map(c=>`${c.event} [${c.phase} ${c.op}; effects: ${c.effects.join(", ")}]`);a.push(f(n.scope,`plugin:${n.name}:hooks`,`effective hook declaration(s): ${[...l,...t].join("; ")}`));continue}d.forEach((l,t)=>{const c=r.manifestPath??h(n.root,".crouter-plugin","plugin.json"),s=l.path!==void 0?`${c}:${l.path}`:c;a.push(m(n.scope,`plugin:${n.name}:hooks[${t}]`,`${l.code} at ${s}: ${l.message} (received ${l.received}, expected ${l.expected})`,{kind:"human_action",description:`${l.next} Inspect with \`crtr pkg plugin show ${n.name}\`; then disable (\`crtr pkg plugin disable ${n.name} --scope ${n.scope}\`), update (\`crtr pkg plugin update --name ${n.name}\`), or remove (\`crtr pkg plugin remove ${n.name}\`) the plugin.`}))})}return a}p(Ee,"runHookPluginChecks");function Ce(e){const o=new Set(e),{bins:i,issues:a}=ce(process.cwd(),x()||null),r=[];for(const n of a)o.has(n.scope)&&r.push(m(n.scope,`bin:${n.name}`,`${n.origin}: ${n.message}`,{kind:"human_action",description:`Fix the \`bin.${n.name}\` declaration in ${n.origin} \u2014 point it at an executable regular file inside that contributor's own root, or remove it. A same-precedence collision is resolved by renaming one of the claimants.`}));for(const n of i.values())o.has(n.scope)&&r.push(f(n.scope,`bin:${n.name}`,`${n.origin} \u2192 ${n.target}`));return r}p(Ce,"runBinContributionChecks");function Se(e){const o=new Set(e),i=h(A("user"),we),a=[],r=new Map;for(const n of le(process.cwd())){if("kind"in n){if(n.kind==="unknown_action")continue;const c=n.configOrigin===i?"user":"project",s=n.block===!0,u=s?void 0:r.get(n.name);if(!s&&u===void 0&&r.set(n.name,n.configOrigin),!o.has(c))continue;const g=s?`humanActions:block@${n.configOrigin}`:`humanActions:${n.name}@${n.configOrigin}`,v={kind:"human_action",description:s?`Fix or remove the \`humanActions\` block in ${n.configOrigin}. Actions run argv directly without a shell.`:`Fix or remove the \`humanActions.${n.name}\` declaration in ${n.configOrigin}. Actions run argv directly without a shell.`};u!==void 0?a.push({scope:c,name:g,status:"pass",message:`warning: shadowed by ${u}; ${n.configOrigin}: ${n.reason}`,remediation:v}):a.push(m(c,g,`${n.configOrigin}: ${n.reason}`,v));continue}const d=n.configOrigin===i?"user":"project",l=r.get(n.name);if(l===void 0&&r.set(n.name,n.configOrigin),!o.has(d))continue;const t=l===void 0?"":`shadowed by ${l}; `;a.push(f(d,`humanActions:${n.name}@${n.configOrigin}`,`${t}${n.configOrigin} \u2192 ${n.argv[0]} (cwd ${n.cwd})`))}return a}p(Se,"runHumanActionChecks");async function je(e){const o=new Set(e),i=x()??null,a=q()??"app:terminal",r=P(),n=p(t=>Object.fromEntries(t.map(c=>[c,""])),"present"),d=ue({argv:[],env:{CRTR_NODE_CWD:process.cwd(),CRTR_PROFILE_ID:i??"",CRTR_GRANTEE:a}},de(process.cwd(),i,a,n((await r.listAppEnv()).names),i===null?{}:n((await r.listProfileEnv(i)).names))),l=[];for(const t of pe())if(!(!o.has(t.scope)||!t.enabled)){for(const c of I(t.manifest.env))d[c]!==void 0?l.push(f(t.scope,`env:${c}`,`plugin "${t.name}" has ${c}`)):l.push(m(t.scope,`env:${c}`,`plugin "${t.name}" needs ${c}`,{kind:"human_action",description:`crtr sys env set --name ${c}`}));if(t.manifest.requires!==void 0)for(const[c,s]of Object.entries(G(t.manifest.requires))){const u=me(c,d,process.cwd());u!==null?l.push(f(t.scope,`requires:${c}`,`plugin "${t.name}" \u2192 ${u}`)):l.push(m(t.scope,`requires:${c}`,`plugin "${t.name}" requires executable "${c}" on PATH`,{kind:"human_action",description:s}))}}return l}p(je,"runRequiresChecks");async function Ae(e){const o=[];async function i(a){for(const r of await E(a)){const n=h(a,r),d=L(e,n).replaceAll(M,"/");if(d==="generation.json")continue;const l=await w(n);if(l.isDirectory())await i(n);else if(l.isFile()){const t=await T(n);o.push({path:d,size:l.size,sha256:_("sha256").update(t).digest("hex")})}else if(l.isSymbolicLink()){const t=await C(n);if(S(t)||!y.contained(e,j(b(n),t)))throw new Error(`generation symlink escapes root: ${d}`);o.push({path:d,size:Buffer.byteLength(t),sha256:_("sha256").update(t).digest("hex"),symlink:!0})}else throw new Error(`unsupported generation file: ${d}`)}}return p(i,"walk"),await i(e),y.sortInventory(o)}p(Ae,"inventory");async function Oe(e){async function o(i){const a=await w(i);if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`generation directory is invalid: ${i}`);if((a.mode&146)!==0)throw new Error(`generation path is writable: ${i}`);for(const r of await E(i)){const n=h(i,r),d=await w(n);if(d.isDirectory())await o(n);else if(d.isFile()){if((d.mode&146)!==0)throw new Error(`generation path is writable: ${n}`)}else if(d.isSymbolicLink()){const l=await C(n);if(S(l)||!y.contained(e,j(b(n),l)))throw new Error(`generation symlink escapes root: ${n}`)}else throw new Error(`unsupported generation file: ${n}`)}}p(o,"walk"),await o(e)}p(Oe,"verifySealed");function Pe(){const e=Y();if(e.installed)return f("user","terminal:nerd-font",`installed (${e.evidence}) \u2014 if icons still render as boxes, ${R}`);const o=ee(ne());return m("user","terminal:nerd-font","no Nerd Font installed \u2014 viewer tool/command icons will render as tofu boxes",{kind:"human_action",description:`Install a Nerd Font (${o.hint}), ${R}`,...o.command?{command:o.command}:{}})}p(Pe,"runNerdFontCheck");function Re(e,o){const i=`runtime:${e}:source`;let a;try{a=JSON.parse(H(h(b(o.root),`${o.id}.source.json`),"utf8"))}catch{return f("canvas",i,"not recorded (installed from a package, or before install sources were recorded)")}const r=`${a.branch??"?"} @ ${a.commit?.slice(0,9)??"?"} from ${a.checkout??"?"}${a.node?` by node ${a.node}`:""}, ${a.installedAt??""}`;return a.unlanded===void 0||a.unlanded.length===0?f("canvas",i,`origin/main: ${r}`):m("canvas",i,`unlanded code is installed (${a.unlanded.join("; ")}): ${r}. Land it and reinstall from origin/main.`)}p(Re,"installSourceCheck");async function F(e,o,i){if(o.generation===null){const d=o.error??"no runtime generation";return[i?f("canvas",`runtime:${e}`,d):m("canvas",`runtime:${e}`,d)]}const a=o.generation,r=[],n=y.validateManifestShape(a.manifest,{id:a.id,entryName:"cli"});if(!n.ok)return[m("canvas",`runtime:${e}:manifest`,n.error)];r.push(f("canvas",`runtime:${e}:manifest`,`${a.id} ${a.manifest.packageVersion}`)),r.push(Re(e,a));try{await Oe(a.root),r.push(f("canvas",`runtime:${e}:sealing`,"generation tree is sealed and contained"))}catch(d){r.push(m("canvas",`runtime:${e}:sealing`,d instanceof Error?d.message:String(d)))}try{const d=await Ae(a.root),l=y.sortInventory(a.manifest.files);JSON.stringify(a.manifest.files)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"manifest inventory is not in canonical runtime-generation-manifest order")):JSON.stringify(d)!==JSON.stringify(l)?r.push(m("canvas",`runtime:${e}:inventory`,"full generation inventory hash does not match generation.json")):r.push(f("canvas",`runtime:${e}:inventory`,`${d.length} files hash-verified`))}catch(d){r.push(m("canvas",`runtime:${e}:inventory`,d instanceof Error?d.message:String(d)))}return r}p(F,"generationChecks");async function Ne(){const e=[];for(const o of await P().listNodes()){const i=o.fault??null;if(i===null)continue;const a=`fault:${o.node_id}:${i.link}`,r=xe(i,o.node_id);e.push(m("canvas",a,be(i),r))}return e}p(Ne,"runFaultChecks");async function Fe(e,o){const i=[];if(!A(e))return i;const r=K(e),n=W(e);for(const t of Object.keys(r.marketplaces)){if(!n){i.push(m(e,`marketplace:${t}:dir`,"marketplaces directory unavailable"));continue}const c=h(n,t);if($(c))i.push(f(e,`marketplace:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.marketplaces.${t}`,scope:e,configKey:`marketplaces.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`marketplace:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`marketplace:${t}:dir`,`directory missing: ${c}`,s))}}const d=V(e);for(const t of Object.keys(r.plugins)){if(!d){i.push(m(e,`plugin:${t}:dir`,"plugins directory unavailable"));continue}const c=h(d,t);if($(c))i.push(f(e,`plugin:${t}:dir`,"directory exists"));else{const s={kind:"remove_config_key",description:`Drop stale config entry config.${e}.plugins.${t}`,scope:e,configKey:`plugins.${t}`};o.fix&&await k(s)?i.push({scope:e,name:`plugin:${t}:dir`,status:"fail",message:"directory missing \u2014 removed stale config entry",fixed:!0,remediation:s}):i.push(m(e,`plugin:${t}:dir`,`directory missing: ${c}`,s))}}if(n&&$(n))for(const t of O(n)){const c=h(n,t),s=U(c);if(s){i.push(f(e,`marketplace:${t}:manifest`,"manifest valid"));for(const u of s.plugins){if(u.source.startsWith("http://")||u.source.startsWith("https://")||u.source.startsWith("git@"))continue;const g=h(c,u.source);$(g)?i.push(f(e,`marketplace:${t}:plugin-source:${u.name}`,"source resolves")):i.push(m(e,`marketplace:${t}:plugin-source:${u.name}`,`source path does not resolve: ${g}`))}}else{const u={kind:"rm_path",description:"Remove dangling marketplace directory (no valid .crouter-marketplace/marketplace.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`marketplace:${t}:manifest`,status:"fail",message:"no valid marketplace.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`marketplace:${t}:manifest`,`no valid marketplace.json in ${c}`,u))}}const l=new Map;if(d&&$(d))for(const t of O(d)){const c=h(d,t),s=Z(c);if(!s){const u={kind:"rm_path",description:"Remove dangling plugin directory (no valid .crouter-plugin/plugin.json)",path:c};o.fix&&await k(u)?i.push({scope:e,name:`plugin:${t}:manifest`,status:"fail",message:"no valid plugin.json \u2014 removed dangling directory",fixed:!0,remediation:u}):i.push(m(e,`plugin:${t}:manifest`,`no valid plugin.json in ${c}`,u));continue}i.push(f(e,`plugin:${t}:manifest`,"manifest valid")),l.has(t)?i.push(m(e,`plugin:${t}:duplicate`,`duplicate plugin name within scope (also at ${l.get(t)})`)):l.set(t,c),o.remote&&s.source&&(X(s.source).status!==0?i.push(m(e,`plugin:${t}:remote`,`git remote unreachable: ${s.source}`)):i.push(f(e,`plugin:${t}:remote`,"git remote reachable")))}return i}p(Fe,"runChecksForScope");const dn=B({name:"doctor",description:"diagnose installation health",whenToUse:"something in your crtr install looks off and you want it diagnosed \u2014 a plugin or marketplace manifest is missing, a config entry points at a directory that no longer exists, or a plugin command/hook declaration is malformed. Reports each problem with a structured remediation, and can apply the safe repairs for you.",help:{name:"sys doctor",summary:"diagnose runtime integrity, missing manifests, and broken config entries",params:[{kind:"flag",name:"scope",type:"enum",choices:["user","project"],required:!1,constraint:"Scope to check. Default: all scopes."},{kind:"flag",name:"fix",type:"bool",required:!1,constraint:"Apply each non-pass check's remediation and report what was fixed."},{kind:"flag",name:"remote",type:"bool",required:!1,constraint:"Check git remotes with ls-remote (slow \u2014 makes network calls)."}],output:[{name:"checks",type:"object[]",required:!0,constraint:"Each: {scope, name, status, message, fixed?, remediation?}. status: pass | fail. scope may be user | project | canvas. bin:<name> checks report bare-binary contributions (a `bin` block in a plugin manifest or a scope config.json): a pass names the contributor and the resolved target, a fail names an unsafe/reserved command name, malformed target declaration, missing/non-executable/escaping target, or same-precedence name collision that installed nothing; their remediation is always a human_action. humanActions:<name>@<config-origin> checks validate each user/project scope completion-action declaration: action-name and argv shape, cwd directory, argv[0] regular-file existence, and execute permission; they never execute an action. A malformed effective declaration fails; a malformed shadowed declaration is a pass-level warning that names the winning and shadowed origins. requires:<name> checks report each enabled plugin manifest PATH requirement: a pass names the plugin and resolved executable path; a fail names the plugin and carries its declared install hint as remediation. Runtime checks validate selected and process generation manifests, sealing/containment, and full SHA-256 inventories. terminal:nerd-font (user scope) reports whether a Nerd Font is installed for the viewer's icon glyphs; its remediation is always a human_action carrying the platform install command, never auto-fixed. Plugin checks appear as plugin:<name>:commands and plugin:<name>:hooks; both are validated statically and never execute plugin code. Hook failures identify manifest/path/target/event/collision problems and carry disable/update/remove/show remediation; healthy command hooks list effective target, phase, and op, while lifecycle hooks list event, phase, op, and effects. remediation (when present) is {kind, description, ...payload} where kind is remove_config_key | rm_path | human_action; fault human_action remediations include the canonical logs command. Sorted by scope then name."},{name:"ok",type:"boolean",required:!0,constraint:"True when no unresolved fail checks remain."}],outputKind:"object",effects:["Read-only unless --fix is passed. Runtime verification reads and hashes every selected/process generation file; plugin command and hook manifests, bare-binary (`bin`) declarations, humanActions declarations, and advisory `requires` PATH checks never execute plugin or contributed binaries.","With --fix: applies each non-pass check's `remediation` \u2014 removes stale config entries and deletes dangling plugin/marketplace directories; canvas fault findings and plugin command/hook findings stay read-only (--fix never chmods or rewrites third-party plugin content).","Each non-pass result carries a structured `remediation` describing the fix action (absolute paths, exact config keys, or a human_action with its command) so callers can apply it directly without --fix."]},run:p(async e=>{const o=e.scope,i=e.fix,a=e.remote,r=J(o),n=[];for(const s of r){const u=await Fe(s,{fix:i,remote:a});n.push(...u)}r.includes("user")&&n.push(Pe()),n.push(...await _e(r)),n.push(...await Ee(r)),n.push(...Ce(r)),n.push(...Se(r)),n.push(...await je(r)),n.push(...await Ne());const d=ye();n.push(...await F("selected",ke(),d===null)),n.push(...await F("process",ve(),!0));const l={user:0,project:1,builtin:2,canvas:3};n.sort((s,u)=>s.scope!==u.scope?l[s.scope]-l[u.scope]:s.name.localeCompare(u.name));const t=!n.some(s=>s.status==="fail"&&s.fixed!==!0),c=n.filter(s=>s.status==="fail"&&s.fixed!==!0).length;return{checks:n,ok:t,failed:c}},"run")});export{_e as runCommandPluginChecks,dn as sysDoctorLeaf};
@@ -1,3 +1,3 @@
1
- var S=Object.defineProperty;var i=(r,t)=>S(r,"name",{value:t,configurable:!0});import{randomUUID as O}from"node:crypto";import{mkdirSync as q,readFileSync as T}from"node:fs";import{dirname as k,join as E}from"node:path";import{ApiError as g}from"../../../api/index.js";import{withMetaLock as x,writeMetaObjectLocked as I}from"../../../core/canvas/meta-file.js";import{defineBranch as C,defineLeaf as y}from"../../../core/command.js";import{InputError as h}from"../../../core/io.js";import{userScopeRoot as P}from"../../../core/scope.js";import{envNodeId as $}from"../../../shared/env.js";import{cliClient as d,getNodeOrNull as j,rethrowAsCliError as u}from"../../api-client.js";const m={"idle-nodes":{title:"Three practice children of a tutorial conversation",teaches:"the graph lesson \u2014 navigate a parent and its children",builds:"three child nodes without tasks under the specified parent; their brokers run until cleanup"},"pending-ask":{title:"A question waiting in the inbox",teaches:"the inbox lesson \u2014 reading a pending item and answering it",builds:"one durable pending request in the human inbox"},"review-doc":{title:"A short practice document waiting for review",teaches:"the review lesson \u2014 commenting on a document alongside an agent",builds:"one practice document owned by the calling node and one document review of it in the human inbox, with its companion agent"}},v=["nodes","requests","documents","reviews"],L=["# Team offsite plan","","A one-day offsite to plan next quarter.","","## Goal","","Leave with a clear plan for the quarter.","","## Agenda","","1. Review last quarter \u2014 what shipped and what slipped.","2. Pick the three projects that matter most.","3. Assign an owner to each project.","","## Logistics","","Somewhere near the office, sometime next month. Lunch is provided.","","## Open questions","","- Should remote teammates join by video, or travel in?",""].join(`
1
+ var S=Object.defineProperty;var i=(r,e)=>S(r,"name",{value:e,configurable:!0});import{randomUUID as O}from"node:crypto";import{mkdirSync as q,readFileSync as T}from"node:fs";import{dirname as k,join as E}from"node:path";import{ApiError as g}from"../../../api/index.js";import{withMetaLock as x,writeMetaObjectLocked as I}from"../../../core/canvas/meta-file.js";import{defineBranch as C,defineLeaf as y}from"../../../core/command.js";import{InputError as h}from"../../../core/io.js";import{userScopeRoot as P}from"../../../core/scope.js";import{envNodeId as $}from"../../../shared/env.js";import{cliClient as d,getNodeOrNull as j,rethrowAsCliError as u}from"../../api-client.js";const m={"idle-nodes":{title:"Three practice children of a tutorial conversation",teaches:"the graph lesson \u2014 navigate a parent and its children",builds:"three child nodes without tasks under the specified parent; their brokers run until cleanup"},"pending-ask":{title:"A question waiting in the inbox",teaches:"the inbox lesson \u2014 reading a pending item and answering it",builds:"one durable pending request in the human inbox"},"review-doc":{title:"A short practice document waiting for review",teaches:"the review lesson \u2014 commenting on a document alongside an agent",builds:"one practice document owned by the calling node and one document review of it in the human inbox, with its companion agent"}},v=["nodes","requests","documents","reviews"],L=["# Team offsite plan","","A one-day offsite to plan next quarter.","","## Goal","","Leave with a clear plan for the quarter.","","## Agenda","","1. Review last quarter \u2014 what shipped and what slipped.","2. Pick the three projects that matter most.","3. Assign an owner to each project.","","## Logistics","","Somewhere near the office, sometime next month. Lunch is provided.","","## Open questions","","- Should remote teammates join by video, or travel in?",""].join(`
2
2
  `),D=["export default function TutorialAsk() {"," return (",' <Page title="A question from the tutorial" subtitle="Practice choosing and commenting on an option.">'," <UserQuestion",' id="answer"',' label="Which crouter topics would you like to explore?"',' body="Select one or more topics with Space and add a comment to an option with c. This is practice; no agent acts on your answer."',' mode="multi"'," options={["," { id: 'orchestration', label: 'Delegating work to other agents' },"," { id: 'memory', label: 'Teaching it my preferences' },"," { id: 'navigation', label: 'Finding conversations and navigating the canvas' },"," ]}"," />"," </Page>"," );","}"].join(`
3
- `);function f(){return E(P(),"tutorial-scenarios.json")}i(f,"ledgerPath");function U(r){return Array.isArray(r)&&r.every(t=>typeof t=="string")}i(U,"isStringArray");function R(){let r;try{r=JSON.parse(T(f(),"utf8"))}catch(e){if(e.code==="ENOENT")return{};throw e}if(typeof r!="object"||r===null||Array.isArray(r))throw new h({error:"invalid_scenario_ledger",message:`tutorial scenario ledger at ${f()} must be an object`,next:"Remove or repair the ledger file, then retry the scenario command."});const t={};for(const e of Object.keys(m)){const n=r[e];if(n===void 0)continue;if(typeof n!="object"||n===null||typeof n.started!="string")throw new h({error:"invalid_scenario_ledger",message:`tutorial scenario ledger has an invalid ${e} record`,next:"Remove or repair the ledger file, then retry the scenario command."});const o=n;if(v.some(l=>o[l]!==void 0&&!U(o[l])))throw new h({error:"invalid_scenario_ledger",message:`tutorial scenario ledger has invalid ids for ${e}`,next:"Remove or repair the ledger file, then retry the scenario command."});const s={started:o.started};for(const l of v)o[l]!==void 0&&(s[l]=o[l]);t[e]=s}return t}i(R,"readLedger");function N(r){const t=f();return q(k(t),{recursive:!0}),x(t,()=>r(R()))}i(N,"withLedger");function b(r){const t=f();return q(k(t),{recursive:!0}),x(t,()=>{const e=R(),n=r(e);return I(t,e),n})}i(b,"updateLedger");function B(r){return b(t=>{if(t[r]!==void 0)throw new h({error:"scenario_already_standing",message:`the '${r}' scenario is already standing (started ${t[r].started})`,field:"scenario",next:`Run \`crtr sys tutorial scenario clean ${r}\` first, then start it again.`});const e={started:new Date().toISOString(),...r==="idle-nodes"?{nodes:[]}:r==="pending-ask"?{requests:[]}:{documents:[],reviews:[]}};return t[r]=e,e})}i(B,"reserveScenario");async function w(r,t,e){if(!b(o=>{const s=o[r];return s===void 0?!1:(s[t]=[...s[t]??[],e],!0)})){try{t==="nodes"?await d().closeNode(e):t==="requests"?await d().cancelHumanRequest(e,{reason:"Tutorial scenario start interrupted."}):t==="reviews"?await d().cancelReview(e,{reason:"Tutorial scenario start interrupted."}):await d().docs.delete(e)}catch(o){p(o)||u(o)}throw new Error(`tutorial scenario '${r}' disappeared while it was starting`)}}i(w,"appendScenarioId");function p(r){return r instanceof g&&(r.status===404||r.code==="already_settled")}i(p,"isAlreadyCleaned");function K(r){return r==="done"||r==="dead"||r==="canceled"}i(K,"isTerminalNode");function A(r){const t=r.scenario;if(typeof t=="string"&&Object.hasOwn(m,t))return t;throw new h({error:"unknown_scenario",message:`no tutorial scenario named '${String(t)}'`,field:"scenario",next:`Use one of: ${Object.keys(m).join(", ")}. Run \`crtr sys tutorial scenario list\` for what each one builds.`})}i(A,"scenario");async function M(r,t){const e=["tutorial-demo-one","tutorial-demo-two","tutorial-demo-three"];for(const n of e){const o=await d().createNode({parent:t,creator:t,root_lifecycle:"resident",no_kickoff:!0,prompt:"",cwd:process.cwd(),name:n}).catch(u);await w("idle-nodes","nodes",o.node_id),r.nodes.push(o.node_id)}}i(M,"startIdleNodes");async function F(r,t){const e=await d().createHumanRequest({page:{dialect:"jsx",source:D},delivery:{placement:"inline",inbox:!0,reply:!1},source:{askedBy:"crtr sys tutorial",sessionName:"tutorial",nodeId:t},creator_cwd:process.cwd()}).catch(u);await w("pending-ask","requests",e.request_id),r.requests.push(e.request_id)}i(F,"startPendingAsk");async function H(r,t){const e=await d().docs.write({name:`tutorial-review-practice-${Date.now().toString(36)}`,body:L,preview:"A short practice plan for the crouter tutorial\u2019s document-review lesson; safe to delete.",unlisted:!0,cwd:process.cwd()}).catch(u);await w("review-doc","documents",e.name),r.documents.push(e.name);const n=await d().createReview({origin_kind:"ticket",origin_node_id:t,document:e.name,idempotency_key:O(),subtitle:"Practice reviewing a document with an agent: comment on anything, then approve."}).catch(u);await w("review-doc","reviews",n.review_id),r.reviews.push(n.review_id)}i(H,"startReviewDoc");const G=y({name:"list",description:"list the tutorial practice scenarios",whenToUse:"you need to choose a disposable canvas scenario for a lesson or see whether one is already standing.",help:{name:"sys tutorial scenario list",summary:"list the tutorial practice scenarios and their standing state",inputNote:"No input parameters.",output:[{name:"scenarios",type:"object[]",required:!0,constraint:"One row per scenario: {id, title, teaches, builds, standing}."},{name:"standing",type:"number",required:!0,constraint:"Number of scenarios currently recorded as standing."}],outputKind:"object",effects:["None. Read-only."]},run:i(async()=>{const r=N(e=>e),t=Object.entries(m).map(([e,n])=>({id:e,title:n.title,teaches:n.teaches,builds:n.builds,standing:r[e]!==void 0}));return{scenarios:t,standing:t.filter(e=>e.standing).length}},"run")}),W=y({name:"start",description:"create a tutorial practice scenario",whenToUse:"a tutorial lesson needs its disposable graph rows or inbox request before the user can practice against a real canvas surface.",help:{name:"sys tutorial scenario start",summary:"create one tutorial practice scenario",params:[{kind:"positional",name:"scenario",type:"string",required:!0,constraint:"idle-nodes (three children without tasks), pending-ask (one durable inbox request) or review-doc (a practice document and a review of it)."},{kind:"flag",name:"parent",type:"string",required:!0,constraint:"Node id of the tutorial conversation; children, the inbox request and the review are linked to this node. For review-doc it must be the calling node."}],output:[{name:"nodes",type:"string[]",required:!1,constraint:"Created child node ids for idle-nodes."},{name:"requests",type:"string[]",required:!1,constraint:"Created human request ids for pending-ask."},{name:"documents",type:"string[]",required:!1,constraint:"Created practice document names for review-doc."},{name:"reviews",type:"string[]",required:!1,constraint:"Created review ids for review-doc."},{name:"clean_with",type:"string",required:!0,constraint:"Exact command that removes this scenario."},{name:"look_at",type:"string",required:!0,constraint:"Viewer surface that shows the created state."}],outputKind:"object",effects:["idle-nodes creates three resident children of --parent with no kickoff turn; their brokers run until cleanup. Their ids are recorded in ~/.crouter/tutorial-scenarios.json.","pending-ask publishes one durable human request with --parent as its source; answering it does not wake that node. Its id is recorded in ~/.crouter/tutorial-scenarios.json.","review-doc writes one unlisted practice document owned by the calling node and queues a document review of it with --parent as origin: a companion agent forked from --parent joins the review, and submitting it pushes the approval to --parent. Both ids are recorded in ~/.crouter/tutorial-scenarios.json.","Refuses a scenario already recorded as standing; clean it before starting it again."]},run:i(async r=>{const t=A(r),e=r.parent;if(e===void 0||e.trim()==="")throw new h({error:"parent_required",message:`${t} needs the tutorial conversation node id in --parent`,field:"parent",next:"Pass the node id of the conversation the user is viewing."});if(await j(e)===null)throw new h({error:"unknown_parent",message:`no local node exists for --parent ${e}`,field:"parent",next:"Pass the node id of a conversation on this canvas."});if(t==="review-doc"&&$()!==e)throw new h({error:"parent_not_caller",message:"review-doc writes the practice document as the calling node, so --parent must be that node",field:"parent",next:'Run it from the tutorial conversation with --parent "$CRTR_NODE_ID".'});const n=B(t);t==="idle-nodes"?await M(n,e):t==="pending-ask"?await F(n,e):await H(n,e);const o={};for(const s of v)n[s]!==void 0&&(o[s]=n[s]);return{...o,clean_with:`crtr sys tutorial scenario clean ${t}`,look_at:t==="idle-nodes"?"Open the graph with `Alt+g`.":t==="pending-ask"?"Open the inbox with `Alt+I`.":"Open the inbox with `Alt+I` and select the review; it opens in its own window."}},"run")}),J=y({name:"clean",description:"remove a tutorial practice scenario",whenToUse:"the lesson has finished with a scenario and you need to remove exactly the nodes or request it recorded.",help:{name:"sys tutorial scenario clean",summary:"remove exactly the rows recorded for one tutorial practice scenario",params:[{kind:"positional",name:"scenario",type:"string",required:!0,constraint:"Scenario to remove: idle-nodes, pending-ask or review-doc."}],output:[{name:"was_standing",type:"boolean",required:!0,constraint:"Whether this scenario had a ledger record to remove."},{name:"closed_nodes",type:"number",required:!1,constraint:"Number of ledger-recorded node ids closed. Present when the scenario was standing."},{name:"canceled_requests",type:"number",required:!1,constraint:"Number of ledger-recorded request ids canceled. Present when the scenario was standing."},{name:"already_settled_requests",type:"number",required:!1,constraint:"Number of ledger-recorded request or review ids already terminal when clean processed them. Present when the scenario was standing."},{name:"deleted_documents",type:"number",required:!1,constraint:"Number of ledger-recorded practice documents deleted. Present when the scenario was standing."}],outputKind:"object",effects:["Closes, cancels or deletes only ids recorded for this scenario in ~/.crouter/tutorial-scenarios.json, then removes that scenario record. A review is canceled before its practice document is deleted."]},run:i(async r=>{const t=A(r),e=N(c=>c[t]);if(e===void 0)return{was_standing:!1};let n=0,o=0,s=0;for(const c of e.nodes??[]){const a=await j(c);if(!(a===null||K(a.status)))try{await d().closeNode(c),n++}catch(_){p(_)||u(_)}}for(const c of e.requests??[])try{await d().cancelHumanRequest(c,{reason:"Tutorial scenario cleaned up."}),o++}catch(a){a instanceof g&&a.code==="already_settled"?s++:p(a)||u(a)}for(const c of e.reviews??[])try{(await d().cancelReview(c,{reason:"Tutorial scenario cleaned up."})).outcome==="already_settled"?s++:o++}catch(a){a instanceof g&&(a.code==="already_settled"||a.code==="review_terminal_conflict")?s++:p(a)||u(a)}let l=0;for(const c of e.documents??[])try{await d().docs.delete(c),l++}catch(a){p(a)||u(a)}return b(c=>{delete c[t]}),{was_standing:!0,closed_nodes:n,canceled_requests:o,...e.documents===void 0?{}:{deleted_documents:l},...s===0?{}:{already_settled_requests:s}}},"run")}),ae=C({name:"scenario",description:"create and remove disposable tutorial practice state",whenToUse:"a tutorial lesson needs real but disposable canvas rows or an inbox request to inspect and practice against.",help:{name:"sys tutorial scenario",summary:"create and remove disposable canvas state for tutorial lessons",model:"Each scenario records only the ids it creates. Start refuses an already-standing scenario, and clean acts only on that recorded list."},children:[G,W,J]});export{ae as scenarioBranch};
3
+ `);function f(){return E(P(),"tutorial-scenarios.json")}i(f,"ledgerPath");function U(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}i(U,"isStringArray");function R(){let r;try{r=JSON.parse(T(f(),"utf8"))}catch(t){if(t.code==="ENOENT")return{};throw t}if(typeof r!="object"||r===null||Array.isArray(r))throw new h({error:"invalid_scenario_ledger",message:`tutorial scenario ledger at ${f()} must be an object`,next:"Remove or repair the ledger file, then retry the scenario command."});const e={};for(const t of Object.keys(m)){const n=r[t];if(n===void 0)continue;if(typeof n!="object"||n===null||typeof n.started!="string")throw new h({error:"invalid_scenario_ledger",message:`tutorial scenario ledger has an invalid ${t} record`,next:"Remove or repair the ledger file, then retry the scenario command."});const o=n;if(v.some(l=>o[l]!==void 0&&!U(o[l])))throw new h({error:"invalid_scenario_ledger",message:`tutorial scenario ledger has invalid ids for ${t}`,next:"Remove or repair the ledger file, then retry the scenario command."});const s={started:o.started};for(const l of v)o[l]!==void 0&&(s[l]=o[l]);e[t]=s}return e}i(R,"readLedger");function N(r){const e=f();return q(k(e),{recursive:!0}),x(e,()=>r(R()))}i(N,"withLedger");function b(r){const e=f();return q(k(e),{recursive:!0}),x(e,()=>{const t=R(),n=r(t);return I(e,t),n})}i(b,"updateLedger");function B(r){return b(e=>{if(e[r]!==void 0)throw new h({error:"scenario_already_standing",message:`the '${r}' scenario is already standing (started ${e[r].started})`,field:"scenario",next:`Run \`crtr sys tutorial scenario clean ${r}\` first, then start it again.`});const t={started:new Date().toISOString(),...r==="idle-nodes"?{nodes:[]}:r==="pending-ask"?{requests:[]}:{documents:[],reviews:[]}};return e[r]=t,t})}i(B,"reserveScenario");async function w(r,e,t){if(!b(o=>{const s=o[r];return s===void 0?!1:(s[e]=[...s[e]??[],t],!0)})){try{e==="nodes"?await d().closeNode(t):e==="requests"?await d().cancelHumanRequest(t,{reason:"Tutorial scenario start interrupted."}):e==="reviews"?await d().cancelReview(t,{reason:"Tutorial scenario start interrupted."}):await d().docs.delete(t)}catch(o){p(o)||u(o)}throw new Error(`tutorial scenario '${r}' disappeared while it was starting`)}}i(w,"appendScenarioId");function p(r){return r instanceof g&&(r.status===404||r.code==="already_settled")}i(p,"isAlreadyCleaned");function K(r){return r==="done"||r==="dead"||r==="canceled"}i(K,"isTerminalNode");function A(r){const e=r.scenario;if(typeof e=="string"&&Object.hasOwn(m,e))return e;throw new h({error:"unknown_scenario",message:`no tutorial scenario named '${String(e)}'`,field:"scenario",next:`Use one of: ${Object.keys(m).join(", ")}. Run \`crtr sys tutorial scenario list\` for what each one builds.`})}i(A,"scenario");async function M(r,e){const t=["tutorial-demo-one","tutorial-demo-two","tutorial-demo-three"];for(const n of t){const o=await d().createNode({parent:e,creator:e,root_lifecycle:"resident",no_kickoff:!0,prompt:"",cwd:process.cwd(),name:n}).catch(u);await w("idle-nodes","nodes",o.node_id),r.nodes.push(o.node_id)}}i(M,"startIdleNodes");async function F(r,e){const t=await d().createHumanRequest({page:{dialect:"jsx",source:D},delivery:{placement:"inline",inbox:!0,reply:!1},source:{askedBy:"crtr sys tutorial",sessionName:"tutorial",nodeId:e},requester_node_id:e,creator_cwd:process.cwd()}).catch(u);await w("pending-ask","requests",t.request_id),r.requests.push(t.request_id)}i(F,"startPendingAsk");async function H(r,e){const t=await d().docs.write({name:`tutorial-review-practice-${Date.now().toString(36)}`,body:L,preview:"A short practice plan for the crouter tutorial\u2019s document-review lesson; safe to delete.",unlisted:!0,cwd:process.cwd()}).catch(u);await w("review-doc","documents",t.name),r.documents.push(t.name);const n=await d().createReview({origin_kind:"ticket",origin_node_id:e,document:t.name,idempotency_key:O(),subtitle:"Practice reviewing a document with an agent: comment on anything, then approve."}).catch(u);await w("review-doc","reviews",n.review_id),r.reviews.push(n.review_id)}i(H,"startReviewDoc");const G=y({name:"list",description:"list the tutorial practice scenarios",whenToUse:"you need to choose a disposable canvas scenario for a lesson or see whether one is already standing.",help:{name:"sys tutorial scenario list",summary:"list the tutorial practice scenarios and their standing state",inputNote:"No input parameters.",output:[{name:"scenarios",type:"object[]",required:!0,constraint:"One row per scenario: {id, title, teaches, builds, standing}."},{name:"standing",type:"number",required:!0,constraint:"Number of scenarios currently recorded as standing."}],outputKind:"object",effects:["None. Read-only."]},run:i(async()=>{const r=N(t=>t),e=Object.entries(m).map(([t,n])=>({id:t,title:n.title,teaches:n.teaches,builds:n.builds,standing:r[t]!==void 0}));return{scenarios:e,standing:e.filter(t=>t.standing).length}},"run")}),W=y({name:"start",description:"create a tutorial practice scenario",whenToUse:"a tutorial lesson needs its disposable graph rows or inbox request before the user can practice against a real canvas surface.",help:{name:"sys tutorial scenario start",summary:"create one tutorial practice scenario",params:[{kind:"positional",name:"scenario",type:"string",required:!0,constraint:"idle-nodes (three children without tasks), pending-ask (one durable inbox request) or review-doc (a practice document and a review of it)."},{kind:"flag",name:"parent",type:"string",required:!0,constraint:"Node id of the tutorial conversation; children, the inbox request and the review are linked to this node. For review-doc it must be the calling node."}],output:[{name:"nodes",type:"string[]",required:!1,constraint:"Created child node ids for idle-nodes."},{name:"requests",type:"string[]",required:!1,constraint:"Created human request ids for pending-ask."},{name:"documents",type:"string[]",required:!1,constraint:"Created practice document names for review-doc."},{name:"reviews",type:"string[]",required:!1,constraint:"Created review ids for review-doc."},{name:"clean_with",type:"string",required:!0,constraint:"Exact command that removes this scenario."},{name:"look_at",type:"string",required:!0,constraint:"Viewer surface that shows the created state."}],outputKind:"object",effects:["idle-nodes creates three resident children of --parent with no kickoff turn; their brokers run until cleanup. Their ids are recorded in ~/.crouter/tutorial-scenarios.json.","pending-ask publishes one durable human request with --parent as its source; answering it does not wake that node. Its id is recorded in ~/.crouter/tutorial-scenarios.json.","review-doc writes one unlisted practice document owned by the calling node and queues a document review of it with --parent as origin: a companion agent forked from --parent joins the review, and submitting it pushes the approval to --parent. Both ids are recorded in ~/.crouter/tutorial-scenarios.json.","Refuses a scenario already recorded as standing; clean it before starting it again."]},run:i(async r=>{const e=A(r),t=r.parent;if(t===void 0||t.trim()==="")throw new h({error:"parent_required",message:`${e} needs the tutorial conversation node id in --parent`,field:"parent",next:"Pass the node id of the conversation the user is viewing."});if(await j(t)===null)throw new h({error:"unknown_parent",message:`no local node exists for --parent ${t}`,field:"parent",next:"Pass the node id of a conversation on this canvas."});if(e==="review-doc"&&$()!==t)throw new h({error:"parent_not_caller",message:"review-doc writes the practice document as the calling node, so --parent must be that node",field:"parent",next:'Run it from the tutorial conversation with --parent "$CRTR_NODE_ID".'});const n=B(e);e==="idle-nodes"?await M(n,t):e==="pending-ask"?await F(n,t):await H(n,t);const o={};for(const s of v)n[s]!==void 0&&(o[s]=n[s]);return{...o,clean_with:`crtr sys tutorial scenario clean ${e}`,look_at:e==="idle-nodes"?"Open the graph with `Alt+g`.":e==="pending-ask"?"Open the inbox with `Alt+I`.":"Open the inbox with `Alt+I` and select the review; it opens in its own window."}},"run")}),J=y({name:"clean",description:"remove a tutorial practice scenario",whenToUse:"the lesson has finished with a scenario and you need to remove exactly the nodes or request it recorded.",help:{name:"sys tutorial scenario clean",summary:"remove exactly the rows recorded for one tutorial practice scenario",params:[{kind:"positional",name:"scenario",type:"string",required:!0,constraint:"Scenario to remove: idle-nodes, pending-ask or review-doc."}],output:[{name:"was_standing",type:"boolean",required:!0,constraint:"Whether this scenario had a ledger record to remove."},{name:"closed_nodes",type:"number",required:!1,constraint:"Number of ledger-recorded node ids closed. Present when the scenario was standing."},{name:"canceled_requests",type:"number",required:!1,constraint:"Number of ledger-recorded request ids canceled. Present when the scenario was standing."},{name:"already_settled_requests",type:"number",required:!1,constraint:"Number of ledger-recorded request or review ids already terminal when clean processed them. Present when the scenario was standing."},{name:"deleted_documents",type:"number",required:!1,constraint:"Number of ledger-recorded practice documents deleted. Present when the scenario was standing."}],outputKind:"object",effects:["Closes, cancels or deletes only ids recorded for this scenario in ~/.crouter/tutorial-scenarios.json, then removes that scenario record. A review is canceled before its practice document is deleted."]},run:i(async r=>{const e=A(r),t=N(c=>c[e]);if(t===void 0)return{was_standing:!1};let n=0,o=0,s=0;for(const c of t.nodes??[]){const a=await j(c);if(!(a===null||K(a.status)))try{await d().closeNode(c),n++}catch(_){p(_)||u(_)}}for(const c of t.requests??[])try{await d().cancelHumanRequest(c,{reason:"Tutorial scenario cleaned up."}),o++}catch(a){a instanceof g&&a.code==="already_settled"?s++:p(a)||u(a)}for(const c of t.reviews??[])try{(await d().cancelReview(c,{reason:"Tutorial scenario cleaned up."})).outcome==="already_settled"?s++:o++}catch(a){a instanceof g&&(a.code==="already_settled"||a.code==="review_terminal_conflict")?s++:p(a)||u(a)}let l=0;for(const c of t.documents??[])try{await d().docs.delete(c),l++}catch(a){p(a)||u(a)}return b(c=>{delete c[e]}),{was_standing:!0,closed_nodes:n,canceled_requests:o,...t.documents===void 0?{}:{deleted_documents:l},...s===0?{}:{already_settled_requests:s}}},"run")}),ae=C({name:"scenario",description:"create and remove disposable tutorial practice state",whenToUse:"a tutorial lesson needs real but disposable canvas rows or an inbox request to inspect and practice against.",help:{name:"sys tutorial scenario",summary:"create and remove disposable canvas state for tutorial lessons",model:"Each scenario records only the ids it creates. Start refuses an already-standing scenario, and clean acts only on that recorded list."},children:[G,W,J]});export{ae as scenarioBranch};
@@ -76,6 +76,8 @@ export declare class BrokerClient extends EventEmitter {
76
76
  * to the SAME target. Resolves on `connect` (caller re-sends `hello`);
77
77
  * rejects on a retryable dial failure. */
78
78
  redial(options?: RedialOptions): Promise<void>;
79
+ /** Check that the connection still answers; see {@link Transport.probe}. True for a transport that has no probe. */
80
+ probe(timeoutMs: number): Promise<boolean>;
79
81
  /** Encode + send one client→broker frame. No-op on a dead/absent
80
82
  * connection; never throws. */
81
83
  send(frame: ClientToBroker): void;
@@ -1 +1 @@
1
- var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as w}from"./transport.js";import{SocketTransport as v}from"./transport-socket.js";import{RelayTransport as U}from"./transport-relay.js";const d=1e4;function E(r){return r===null||r.status==="done"&&r.final_report!=null}s(E,"reconnectShouldGiveUp");class g extends l{static{s(this,"BrokerClient")}transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(e,t={}){super();const n=t.transport??(e===void 0?void 0:new a(e));n!==void 0&&this.bindTransport(n)}bindTransport(e){if(this.transport!==void 0)throw new Error("BrokerClient already has a transport");this.transport=e,e.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),e.on("frame",t=>this.onFrame(t)),e.on("error",t=>{this.lastTransportError=t.message,this.emitError(t)}),e.on("close",()=>this.onClose())}request(e){const t=p();return new Promise((n,o)=>{if(!this.connected){o(new Error(`cannot issue '${e.type}': no live broker connection`));return}const i=setTimeout(()=>{this.pending.delete(t),o(new Error(`request '${e.type}' timed out after ${d}ms`))},d);typeof i.unref=="function"&&i.unref(),this.pending.set(t,{resolve:n,reject:o,timer:i}),this.send({...e,id:t})})}rejectAllPending(e){for(const{reject:t,timer:n}of this.pending.values())clearTimeout(n),t(new Error(e));this.pending.clear()}connect(){this.transport?.connect()}redial(e){return this.transport===void 0?Promise.reject(new Error("no node to redial yet")):this.transport.redial(e)}send(e){this.transport?.send(e)}close(){this.transport?.destroy()}onFrame(e){if(e.type==="data"){const t=typeof e.id=="string"?this.pending.get(e.id):void 0;t&&(this.pending.delete(e.id),clearTimeout(t.timer),t.resolve(e));return}if(e.type==="error"&&typeof e.id=="string"&&this.pending.has(e.id)){const t=this.pending.get(e.id);this.pending.delete(e.id),clearTimeout(t.timer),t.reject(new Error(e.message||`request failed: ${e.code}`));return}this.emit("frame",e)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}export{g as BrokerClient,w as BrokerUnavailableError,U as RelayTransport,v as SocketTransport,E as reconnectShouldGiveUp};
1
+ var c=Object.defineProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});import{EventEmitter as l}from"node:events";import{randomUUID as p}from"node:crypto";import{SocketTransport as a}from"./transport-socket.js";import{BrokerUnavailableError as w}from"./transport.js";import{SocketTransport as k}from"./transport-socket.js";import{RelayTransport as x}from"./transport-relay.js";const d=1e4;function E(r){return r===null||r.status==="done"&&r.final_report!=null}s(E,"reconnectShouldGiveUp");class g extends l{static{s(this,"BrokerClient")}transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;constructor(e,t={}){super();const n=t.transport??(e===void 0?void 0:new a(e));n!==void 0&&this.bindTransport(n)}bindTransport(e){if(this.transport!==void 0)throw new Error("BrokerClient already has a transport");this.transport=e,e.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),e.on("frame",t=>this.onFrame(t)),e.on("error",t=>{this.lastTransportError=t.message,this.emitError(t)}),e.on("close",()=>this.onClose())}request(e){const t=p();return new Promise((n,o)=>{if(!this.connected){o(new Error(`cannot issue '${e.type}': no live broker connection`));return}const i=setTimeout(()=>{this.pending.delete(t),o(new Error(`request '${e.type}' timed out after ${d}ms`))},d);typeof i.unref=="function"&&i.unref(),this.pending.set(t,{resolve:n,reject:o,timer:i}),this.send({...e,id:t})})}rejectAllPending(e){for(const{reject:t,timer:n}of this.pending.values())clearTimeout(n),t(new Error(e));this.pending.clear()}connect(){this.transport?.connect()}redial(e){return this.transport===void 0?Promise.reject(new Error("no node to redial yet")):this.transport.redial(e)}probe(e){return this.transport?.probe?.(e)??Promise.resolve(!0)}send(e){this.transport?.send(e)}close(){this.transport?.destroy()}onFrame(e){if(e.type==="data"){const t=typeof e.id=="string"?this.pending.get(e.id):void 0;t&&(this.pending.delete(e.id),clearTimeout(t.timer),t.resolve(e));return}if(e.type==="error"&&typeof e.id=="string"&&this.pending.has(e.id)){const t=this.pending.get(e.id);this.pending.delete(e.id),clearTimeout(t.timer),t.reject(new Error(e.message||`request failed: ${e.code}`));return}this.emit("frame",e)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(e){this.listenerCount("error")>0&&this.emit("error",e)}}export{g as BrokerClient,w as BrokerUnavailableError,x as RelayTransport,k as SocketTransport,E as reconnectShouldGiveUp};
@@ -29,12 +29,18 @@ export declare class RelayTransport extends EventEmitter implements Transport {
29
29
  wakeParked?: boolean);
30
30
  private refusal;
31
31
  private refusalError;
32
+ /** When this connection last received a frame or a pong. */
33
+ private heardAt;
34
+ private probing;
32
35
  private get url();
33
36
  private dial;
34
37
  connect(): void;
35
38
  /** Re-dial the same daemon attach endpoint after a broker replacement. */
36
39
  redial(_options?: RedialOptions): Promise<void>;
37
40
  send(frame: ClientToBroker): void;
41
+ /** A WebSocket whose network path went away (the computer slept, the wifi changed) stays OPEN and reports no close for minutes, and a
42
+ * frame sent on it is lost. Ping it; with no pong inside `timeoutMs`, terminate it so 'close' fires and the caller redials. */
43
+ probe(timeoutMs: number): Promise<boolean>;
38
44
  destroy(): void;
39
45
  private onMessage;
40
46
  private onError;
@@ -1 +1 @@
1
- var f=Object.defineProperty;var c=(o,t)=>f(o,"name",{value:t,configurable:!0});import{EventEmitter as u}from"node:events";import{WebSocket as d}from"ws";import{mark as h}from"../timing.js";import{classify as m}from"../fault-classifier.js";import{AttachRefusedError as p,BrokerUnavailableError as g}from"./transport.js";function w(o,t,e){if("socketPath"in o)return`ws+unix://${o.socketPath}:/v1/nodes/${encodeURIComponent(t)}/attach?revive=0`;const r=new URL(o.previewEndpoint);return r.protocol=r.protocol==="http:"?"ws:":"wss:",r.pathname=`/v1/nodes/${encodeURIComponent(t)}/attach`,r.search=e?"?wakeParked=1":"",r.hash="",r.toString()}c(w,"relayUrl");class $ extends u{static{c(this,"RelayTransport")}nodeId;target;wakeParked;ws;closeEmitted=!1;constructor(t,e,r=!0){super(),this.nodeId=t,this.target=e,this.wakeParked=r}refusal;refusalError;get url(){return w(this.target,this.nodeId,this.wakeParked)}dial(){const t=performance.now(),e=c(()=>(performance.now()-t).toFixed(1),"since"),r="socketPath"in this.target?"local":"remote";h("relay.dial_start",{node:this.nodeId,target:r});const s=new d(this.url,{..."relayToken"in this.target?{headers:{authorization:`Bearer ${this.target.relayToken}`}}:{},perMessageDeflate:!1});return s.once("upgrade",()=>h("relay.upgrade_response",{node:this.nodeId,target:r,since_dial_ms:e()})),s.once("open",()=>h("relay.ws_open",{node:this.nodeId,target:r,since_dial_ms:e()})),s.on("unexpected-response",(i,n)=>{let a="";n.on("data",l=>{a.length<2048&&(a+=l.toString())}),n.on("end",()=>{this.refusal=E(n.statusCode,a),this.refusalError=y(n.statusCode,a),s.terminate()})}),this.ws=s,s}connect(){const t=this.dial();t.on("open",()=>{this.emit("connect")}),t.on("message",e=>this.onMessage(e)),t.on("error",e=>this.onError(e)),t.on("close",(e,r)=>this.onClose(e,r.toString()))}redial(t){return this.wakeParked=!0,this.destroy(),this.closeEmitted=!1,new Promise((e,r)=>{const s=this.dial();let i=!1;s.on("open",()=>{i||(i=!0,this.emit("connect"),e())}),s.on("message",n=>this.onMessage(n)),s.on("error",n=>{if(i){this.onError(n);return}i=!0;try{s.terminate()}catch{}r(this.refusal===void 0?n:Object.assign(new Error(this.refusal),{refusal:this.refusalError}))}),s.on("close",(n,a)=>{i&&this.onClose(n,a.toString())})})}send(t){const e=this.ws;if(!(e===void 0||e.readyState!==d.OPEN))try{e.send(JSON.stringify(t))}catch{}}destroy(){const t=this.ws;if(t!==void 0&&t.readyState<=d.OPEN)try{t.close(1e3)}catch{}}onMessage(t){let e;try{e=JSON.parse(t.toString())}catch{return}this.emit("frame",e)}onError(t){this.emitError(Object.assign(new Error(`relay transport error: ${this.refusal??t.message}`),{refusal:this.refusalError}))}onClose(t,e){if(this.closeEmitted)return;this.closeEmitted=!0;const r=m("viewer\u2194broker",{code:t,reason:e}),s=t===1008||r.kind==="protocol"||t===1011&&(/^no running broker/.test(e)||/^no node /.test(e));t===1008?this.emitError(new p(this.nodeId,e)):s&&this.emitError(new g(this.nodeId)),this.emit("close")}emitError(t){this.listenerCount("error")>0&&this.emit("error",t)}}function y(o,t){try{const e=JSON.parse(t).error;if(o!==void 0&&typeof e?.code=="string")return{status:o,code:e.code,message:typeof e.message=="string"?e.message:""}}catch{}}c(y,"refusalOf");function E(o,t){try{const e=JSON.parse(t).error;if(typeof e?.code=="string")return`attach refused (${o??"?"} ${e.code}): ${typeof e.message=="string"?e.message:""}`}catch{}return`attach refused (${o??"?"})`}c(E,"refusalMessage");export{$ as RelayTransport,E as refusalMessage};
1
+ var m=Object.defineProperty;var a=(n,t)=>m(n,"name",{value:t,configurable:!0});import{EventEmitter as p}from"node:events";import{WebSocket as h}from"ws";import{mark as l}from"../timing.js";import{classify as g}from"../fault-classifier.js";import{AttachRefusedError as w,BrokerUnavailableError as E}from"./transport.js";function y(n,t,e){if("socketPath"in n)return`ws+unix://${n.socketPath}:/v1/nodes/${encodeURIComponent(t)}/attach?revive=0`;const r=new URL(n.previewEndpoint);return r.protocol=r.protocol==="http:"?"ws:":"wss:",r.pathname=`/v1/nodes/${encodeURIComponent(t)}/attach`,r.search=e?"?wakeParked=1":"",r.hash="",r.toString()}a(y,"relayUrl");const k=1e3;class $ extends p{static{a(this,"RelayTransport")}nodeId;target;wakeParked;ws;closeEmitted=!1;constructor(t,e,r=!0){super(),this.nodeId=t,this.target=e,this.wakeParked=r}refusal;refusalError;heardAt=0;probing;get url(){return y(this.target,this.nodeId,this.wakeParked)}dial(){const t=performance.now(),e=a(()=>(performance.now()-t).toFixed(1),"since"),r="socketPath"in this.target?"local":"remote";l("relay.dial_start",{node:this.nodeId,target:r});const s=new h(this.url,{..."relayToken"in this.target?{headers:{authorization:`Bearer ${this.target.relayToken}`}}:{},perMessageDeflate:!1});return s.once("upgrade",()=>l("relay.upgrade_response",{node:this.nodeId,target:r,since_dial_ms:e()})),s.once("open",()=>l("relay.ws_open",{node:this.nodeId,target:r,since_dial_ms:e()})),s.on("pong",()=>{this.heardAt=Date.now()}),s.on("unexpected-response",(i,o)=>{let c="";o.on("data",d=>{c.length<2048&&(c+=d.toString())}),o.on("end",()=>{this.refusal=S(o.statusCode,c),this.refusalError=P(o.statusCode,c),s.terminate()})}),this.ws=s,s}connect(){const t=this.dial();t.on("open",()=>{this.emit("connect")}),t.on("message",e=>this.onMessage(e)),t.on("error",e=>this.onError(e)),t.on("close",(e,r)=>this.onClose(e,r.toString()))}redial(t){return this.wakeParked=!0,this.destroy(),this.closeEmitted=!1,new Promise((e,r)=>{const s=this.dial();let i=!1;s.on("open",()=>{i||(i=!0,this.emit("connect"),e())}),s.on("message",o=>this.onMessage(o)),s.on("error",o=>{if(i){this.onError(o);return}i=!0;try{s.terminate()}catch{}r(this.refusal===void 0?o:Object.assign(new Error(this.refusal),{refusal:this.refusalError}))}),s.on("close",(o,c)=>{i&&this.onClose(o,c.toString())})})}send(t){const e=this.ws;if(!(e===void 0||e.readyState!==h.OPEN))try{e.send(JSON.stringify(t))}catch{}}probe(t){const e=this.ws;if(e===void 0||e.readyState!==h.OPEN||Date.now()-this.heardAt<k)return Promise.resolve(!0);if(this.probing!==void 0)return this.probing;const r=new Promise(s=>{const i=a(u=>{clearTimeout(f),e.off("pong",o),e.off("close",c),this.probing=void 0,s(u)},"settle"),o=a(()=>i(!0),"onPong"),c=a(()=>i(!1),"onClose"),d=a(()=>{i(!1),e.terminate()},"drop"),f=setTimeout(d,t);e.on("pong",o),e.on("close",c);try{e.ping()}catch{d()}});return this.probing=r,r}destroy(){const t=this.ws;if(t!==void 0&&t.readyState<=h.OPEN)try{t.close(1e3)}catch{}}onMessage(t){let e;try{e=JSON.parse(t.toString())}catch{return}this.heardAt=Date.now(),this.emit("frame",e)}onError(t){this.emitError(Object.assign(new Error(`relay transport error: ${this.refusal??t.message}`),{refusal:this.refusalError}))}onClose(t,e){if(this.closeEmitted)return;this.closeEmitted=!0;const r=g("viewer\u2194broker",{code:t,reason:e}),s=t===1008||r.kind==="protocol"||t===1011&&(/^no running broker/.test(e)||/^no node /.test(e));t===1008?this.emitError(new w(this.nodeId,e)):s&&this.emitError(new E(this.nodeId)),this.emit("close")}emitError(t){this.listenerCount("error")>0&&this.emit("error",t)}}function P(n,t){try{const e=JSON.parse(t).error;if(n!==void 0&&typeof e?.code=="string")return{status:n,code:e.code,message:typeof e.message=="string"?e.message:""}}catch{}}a(P,"refusalOf");function S(n,t){try{const e=JSON.parse(t).error;if(typeof e?.code=="string")return`attach refused (${n??"?"} ${e.code}): ${typeof e.message=="string"?e.message:""}`}catch{}return`attach refused (${n??"?"})`}a(S,"refusalMessage");export{$ as RelayTransport,S as refusalMessage};
@@ -17,6 +17,10 @@ export interface Transport extends EventEmitter {
17
17
  send(frame: ClientToBroker): void;
18
18
  /** Tear down the connection. 'close' fires if it has not already. */
19
19
  destroy(): void;
20
+ /** Check that the peer still answers. Resolves true when it does, or when there is no open connection to check. With no answer inside
21
+ * `timeoutMs` the transport drops the connection ('close' fires) and resolves false. A transport whose connection cannot die without
22
+ * a close (a local unix socket) leaves this out. */
23
+ probe?(timeoutMs: number): Promise<boolean>;
20
24
  on(event: 'connect', listener: () => void): this;
21
25
  on(event: 'frame', listener: (frame: BrokerToClient) => void): this;
22
26
  on(event: 'close', listener: () => void): this;
@@ -39,4 +39,4 @@ export declare function settleDaemonAction(actionId: string, attempts: number, c
39
39
  /** Deliberate operator retry of a daemon action that failed for good: pending, due now, fresh attempt budget. */
40
40
  export declare function retryFailedDaemonAction(actionId: string, now?: number): Promise<boolean>;
41
41
  /** Daemon startup: an action a previous daemon handed off is due again now. */
42
- export declare function resetHandedOffDaemonActions(now: number): Promise<number>;
42
+ export declare function resetHandedOffDaemonActions(now: number, onlyExpired?: boolean): Promise<number>;
@@ -1,11 +1,11 @@
1
- var f=Object.defineProperty;var a=(t,e)=>f(t,"name",{value:e,configurable:!0});import{randomBytes as y}from"node:crypto";import{withCanvasWrite as l,openDb as r}from"./db.js";import{normalizedSettlement as E}from"./deliveries.js";import{withRetryBudget as A}from"./delivery-contract.js";import{emitEvent as N}from"../events/emit.js";function _(t){return{actionId:t.action_id,adapter:JSON.parse(t.adapter_json),body:t.body_json===null?null:JSON.parse(t.body_json),idempotencyKey:t.idempotency_key,state:t.state,attempts:t.attempts,nextAttemptAt:t.next_attempt_at,claimedAt:t.claimed_at,claimOwner:t.claim_owner,acknowledgedAt:t.acknowledged_at,failedAt:t.failed_at,lastFailure:t.last_failure_json===null?null:JSON.parse(t.last_failure_json),canceledAt:t.canceled_at,createdAt:t.created_at,updatedAt:t.updated_at}}a(_,"actionFrom");function g(){return y(16).toString("hex")}a(g,"newId");async function T(t){return await l(async e=>{const o=await e.prepare("SELECT action_id FROM daemon_actions WHERE idempotency_key = ?").get(t.idempotencyKey);if(o!==void 0)return o.action_id;const d=Date.now(),n=g(),c=t.bodyJson===void 0?null:JSON.stringify(t.bodyJson);return await e.prepare(`INSERT INTO daemon_actions (action_id, adapter_json, body_json, idempotency_key, state, attempts, next_attempt_at, created_at, updated_at)
2
- VALUES (?, ?, ?, ?, 'pending', 0, ?, ?, ?)`).run(n,JSON.stringify(t.adapter),c,t.idempotencyKey,d,d,d),n})}a(T,"enqueueDaemonAction");async function w(t){const e=await(await r()).prepare("SELECT * FROM daemon_actions WHERE idempotency_key = ?").get(t);return e===void 0?null:_(e)}a(w,"readDaemonAction");async function U(t){const e=await(await r()).prepare("SELECT * FROM daemon_actions WHERE action_id = ?").get(t);return e===void 0?null:_(e)}a(U,"readDaemonActionById");async function h(t){return(await(await r()).prepare(`SELECT * FROM daemon_actions
1
+ var f=Object.defineProperty;var a=(t,e)=>f(t,"name",{value:e,configurable:!0});import{randomBytes as E}from"node:crypto";import{withCanvasWrite as p,openDb as r}from"./db.js";import{CLAIM_OWNER_EXPIRED_SQL as y}from"./reconciler-leases.js";import{normalizedSettlement as A}from"./deliveries.js";import{withRetryBudget as N}from"./delivery-contract.js";import{emitEvent as D}from"../events/emit.js";function _(t){return{actionId:t.action_id,adapter:JSON.parse(t.adapter_json),body:t.body_json===null?null:JSON.parse(t.body_json),idempotencyKey:t.idempotency_key,state:t.state,attempts:t.attempts,nextAttemptAt:t.next_attempt_at,claimedAt:t.claimed_at,claimOwner:t.claim_owner,acknowledgedAt:t.acknowledged_at,failedAt:t.failed_at,lastFailure:t.last_failure_json===null?null:JSON.parse(t.last_failure_json),canceledAt:t.canceled_at,createdAt:t.created_at,updatedAt:t.updated_at}}a(_,"actionFrom");function g(){return E(16).toString("hex")}a(g,"newId");async function U(t){return await p(async e=>{const o=await e.prepare("SELECT action_id FROM daemon_actions WHERE idempotency_key = ?").get(t.idempotencyKey);if(o!==void 0)return o.action_id;const d=Date.now(),n=g(),c=t.bodyJson===void 0?null:JSON.stringify(t.bodyJson);return await e.prepare(`INSERT INTO daemon_actions (action_id, adapter_json, body_json, idempotency_key, state, attempts, next_attempt_at, created_at, updated_at)
2
+ VALUES (?, ?, ?, ?, 'pending', 0, ?, ?, ?)`).run(n,JSON.stringify(t.adapter),c,t.idempotencyKey,d,d,d),n})}a(U,"enqueueDaemonAction");async function h(t){const e=await(await r()).prepare("SELECT * FROM daemon_actions WHERE idempotency_key = ?").get(t);return e===void 0?null:_(e)}a(h,"readDaemonAction");async function b(t){const e=await(await r()).prepare("SELECT * FROM daemon_actions WHERE action_id = ?").get(t);return e===void 0?null:_(e)}a(b,"readDaemonActionById");async function W(t){return(await(await r()).prepare(`SELECT * FROM daemon_actions
3
3
  WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at <= ?
4
- ORDER BY next_attempt_at, created_at, action_id`).all(t)).map(_)}a(h,"dueDaemonActions");async function b(t,e,o){return await l(async d=>{const n=await d.prepare(`UPDATE daemon_actions SET state = 'handed_off', attempts = attempts + 1, claimed_at = ?, claim_owner = ?, updated_at = ?
5
- WHERE action_id = ? AND state = 'pending' AND canceled_at IS NULL AND next_attempt_at <= ?`).run(e,o,e,t,e);return Number(n.changes)===0?null:_(await d.prepare("SELECT * FROM daemon_actions WHERE action_id = ?").get(t))})}a(b,"claimDaemonAction");async function H(t,e,o,d,n=Date.now()){const c=A(E(d),e),i=c.settlement,m=i.state==="pending"||i.state==="permanent_failed"?JSON.stringify(i.failure):null,s=i.state==="released"?"pending":i.state,u=i.state==="pending"?i.nextAttemptAt:s==="pending"?n:null,p=Number((await(await r()).prepare(`UPDATE daemon_actions
4
+ ORDER BY next_attempt_at, created_at, action_id`).all(t)).map(_)}a(W,"dueDaemonActions");async function H(t,e,o){return await p(async d=>{const n=await d.prepare(`UPDATE daemon_actions SET state = 'handed_off', attempts = attempts + 1, claimed_at = ?, claim_owner = ?, updated_at = ?
5
+ WHERE action_id = ? AND state = 'pending' AND canceled_at IS NULL AND next_attempt_at <= ?`).run(e,o,e,t,e);return Number(n.changes)===0?null:_(await d.prepare("SELECT * FROM daemon_actions WHERE action_id = ?").get(t))})}a(H,"claimDaemonAction");async function I(t,e,o,d,n=Date.now()){const c=N(A(d),e),i=c.settlement,l=i.state==="pending"||i.state==="permanent_failed"?JSON.stringify(i.failure):null,s=i.state==="released"?"pending":i.state,u=i.state==="pending"?i.nextAttemptAt:s==="pending"?n:null,m=Number((await(await r()).prepare(`UPDATE daemon_actions
6
6
  SET state = ?, next_attempt_at = ?, claimed_at = NULL, claim_owner = NULL,
7
7
  acknowledged_at = ?, failed_at = ?, last_failure_json = ?, updated_at = ?
8
- WHERE action_id = ? AND state = 'handed_off' AND attempts = ? AND claim_owner = ?`).run(s,u,s==="acknowledged"?n:null,s==="permanent_failed"?n:null,m,n,t,e,o)).changes)===1;return p&&c.exhausted&&i.state==="permanent_failed"&&N({level:"error",event:"daemon_action.exhausted",outcome:"failed",attempt:e,fields:{action_id:t,failure:i.failure,retry:`crtr sys retry-delivery ${t}`}}),p}a(H,"settleDaemonAction");async function W(t,e=Date.now()){return Number((await(await r()).prepare(`UPDATE daemon_actions
8
+ WHERE action_id = ? AND state = 'handed_off' AND attempts = ? AND claim_owner = ?`).run(s,u,s==="acknowledged"?n:null,s==="permanent_failed"?n:null,l,n,t,e,o)).changes)===1;return m&&c.exhausted&&i.state==="permanent_failed"&&D({level:"error",event:"daemon_action.exhausted",outcome:"failed",attempt:e,fields:{action_id:t,failure:i.failure,retry:`crtr sys retry-delivery ${t}`}}),m}a(I,"settleDaemonAction");async function j(t,e=Date.now()){return Number((await(await r()).prepare(`UPDATE daemon_actions
9
9
  SET state = 'pending', attempts = 0, next_attempt_at = ?, failed_at = NULL, updated_at = ?
10
- WHERE action_id = ? AND state = 'permanent_failed' AND canceled_at IS NULL AND last_failure_json IS NOT NULL`).run(e,e,t)).changes)===1}a(W,"retryFailedDaemonAction");async function j(t){return Number((await(await r()).prepare(`UPDATE daemon_actions SET state = 'pending', next_attempt_at = ?, claimed_at = NULL, claim_owner = NULL, updated_at = ?
11
- WHERE state = 'handed_off'`).run(t,t)).changes)}a(j,"resetHandedOffDaemonActions");export{b as claimDaemonAction,h as dueDaemonActions,T as enqueueDaemonAction,w as readDaemonAction,U as readDaemonActionById,j as resetHandedOffDaemonActions,W as retryFailedDaemonAction,H as settleDaemonAction};
10
+ WHERE action_id = ? AND state = 'permanent_failed' AND canceled_at IS NULL AND last_failure_json IS NOT NULL`).run(e,e,t)).changes)===1}a(j,"retryFailedDaemonAction");async function J(t,e=!1){return Number((await(await r()).prepare(`UPDATE daemon_actions SET state = 'pending', next_attempt_at = ?, claimed_at = NULL, claim_owner = NULL, updated_at = ?
11
+ WHERE state = 'handed_off'${e?` AND ${y}`:""}`).run(t,t,...e?[new Date(t).toISOString()]:[])).changes)}a(J,"resetHandedOffDaemonActions");export{H as claimDaemonAction,W as dueDaemonActions,U as enqueueDaemonAction,h as readDaemonAction,b as readDaemonActionById,J as resetHandedOffDaemonActions,j as retryFailedDaemonAction,I as settleDaemonAction};
@@ -105,7 +105,7 @@ export declare function acknowledgeNodeMail(nodeId: string, executionId: string,
105
105
  export declare function messageBodyForDelivery(deliveryId: string): Promise<unknown | null>;
106
106
  export declare function duePushDeliveries(now: number): Promise<DeliveryRecord[]>;
107
107
  export declare function claimPushDelivery(deliveryId: string, now: number, claimOwner: string): Promise<DeliveryRecord | null>;
108
- export declare function resetHandedOffDeliveries(now: number): Promise<number>;
108
+ export declare function resetHandedOffDeliveries(now: number, onlyExpired?: boolean): Promise<number>;
109
109
  /** The lane checks the claim immediately before launching the action. An action
110
110
  * superseded after claim but before dispatch must not start with stale input. */
111
111
  export declare function pushDeliveryClaimIsCurrent(delivery: DeliveryRecord, owner: string): Promise<boolean>;