@north-light/cli 0.3.548 → 0.3.550

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 (160) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/custom-objects.d.ts +1 -1
  4. package/dist/api/dto/docs.d.ts +12 -0
  5. package/dist/api/dto/objects.d.ts +17 -1
  6. package/dist/api/dto/objects.js +1 -1
  7. package/dist/api/dto/permissions.d.ts +76 -0
  8. package/dist/api/dto/permissions.js +1 -0
  9. package/dist/api/index.d.ts +3 -2
  10. package/dist/api/index.js +1 -1
  11. package/dist/api/routes.d.ts +4 -0
  12. package/dist/api/routes.js +1 -1
  13. package/dist/builtin-memory/crouter-concepts/documents.md +1 -1
  14. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +2 -2
  15. package/dist/builtin-memory/crouter-sdk/release-notes.md +11 -0
  16. package/dist/builtin-memory/internal/INDEX.md +2 -1
  17. package/dist/builtin-memory/internal/agent-shaping.md +1 -1
  18. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  19. package/dist/builtin-memory/northlight-apps/guides/files-and-documents.md +3 -3
  20. package/dist/builtin-memory/northlight-apps/guides/many-users.md +1 -1
  21. package/dist/builtin-memory/northlight-apps/guides/test-your-app.md +1 -1
  22. package/dist/clients/attach/viewer.js +9 -9
  23. package/dist/commands/canvas/list.js +2 -2
  24. package/dist/commands/canvas/share.d.ts +2 -0
  25. package/dist/commands/canvas/share.js +2 -0
  26. package/dist/commands/canvas.js +1 -1
  27. package/dist/commands/doc/edit.js +1 -1
  28. package/dist/commands/doc/shared.js +1 -1
  29. package/dist/commands/doc/write.js +1 -1
  30. package/dist/commands/sys/sync-skills.js +2 -2
  31. package/dist/core/canvas/canvas.js +20 -20
  32. package/dist/core/canvas/db.js +4 -4
  33. package/dist/core/canvas/export-sqlite.js +2 -2
  34. package/dist/core/canvas/import-sqlite.js +5 -5
  35. package/dist/core/canvas/outcome-actions.js +3 -3
  36. package/dist/core/canvas/person.js +11 -9
  37. package/dist/core/canvas/schema-pg.sql +49 -5
  38. package/dist/core/environments.js +1 -1
  39. package/dist/core/feed/feed.js +1 -1
  40. package/dist/core/grants/mirror.d.ts +9 -1
  41. package/dist/core/grants/mirror.js +2 -2
  42. package/dist/core/grants/sync.js +1 -1
  43. package/dist/core/graph/access.d.ts +8 -49
  44. package/dist/core/graph/access.js +4 -7
  45. package/dist/core/graph/custom.d.ts +5 -2
  46. package/dist/core/graph/custom.js +9 -9
  47. package/dist/core/graph/deletion.js +5 -4
  48. package/dist/core/graph/documents.d.ts +12 -3
  49. package/dist/core/graph/documents.js +13 -7
  50. package/dist/core/graph/edges.js +3 -3
  51. package/dist/core/graph/events.js +12 -8
  52. package/dist/core/graph/kinds/document.js +4 -4
  53. package/dist/core/graph/kinds/kind.js +1 -1
  54. package/dist/core/graph/kinds/node.js +5 -5
  55. package/dist/core/graph/names.d.ts +16 -1
  56. package/dist/core/graph/names.js +11 -3
  57. package/dist/core/graph/objects.d.ts +19 -2
  58. package/dist/core/graph/objects.js +16 -10
  59. package/dist/core/graph/package-docs.js +5 -5
  60. package/dist/core/graph/package-files.js +2 -2
  61. package/dist/core/graph/reader.js +3 -3
  62. package/dist/core/graph/repo-sync/exchange.js +2 -2
  63. package/dist/core/graph/rules.d.ts +7 -5
  64. package/dist/core/graph/rules.js +3 -3
  65. package/dist/core/graph/types.d.ts +12 -1
  66. package/dist/core/graph/types.js +1 -1
  67. package/dist/core/graph/watches.d.ts +1 -1
  68. package/dist/core/graph/watches.js +9 -8
  69. package/dist/core/peer/envelope.d.ts +1 -1
  70. package/dist/core/peer/envelope.js +1 -1
  71. package/dist/core/peer/stubs.d.ts +1 -1
  72. package/dist/core/peer/stubs.js +1 -1
  73. package/dist/core/permissions/boot.d.ts +17 -0
  74. package/dist/core/permissions/boot.js +18 -0
  75. package/dist/core/permissions/builtin.d.ts +8 -0
  76. package/dist/core/permissions/builtin.js +20 -0
  77. package/dist/core/permissions/ceiling.d.ts +57 -0
  78. package/dist/core/permissions/ceiling.js +22 -0
  79. package/dist/core/permissions/compile.d.ts +14 -0
  80. package/dist/core/permissions/compile.js +1 -0
  81. package/dist/core/permissions/errors.d.ts +7 -0
  82. package/dist/core/permissions/errors.js +1 -0
  83. package/dist/core/permissions/evaluator.d.ts +28 -0
  84. package/dist/core/permissions/evaluator.js +6 -0
  85. package/dist/core/permissions/facts.d.ts +56 -0
  86. package/dist/core/permissions/facts.js +2 -0
  87. package/dist/core/permissions/schema-parser.d.ts +29 -0
  88. package/dist/core/permissions/schema-parser.js +2 -0
  89. package/dist/core/permissions/schemas.d.ts +21 -0
  90. package/dist/core/permissions/schemas.js +2 -0
  91. package/dist/core/permissions/sql.d.ts +16 -0
  92. package/dist/core/permissions/sql.js +1 -0
  93. package/dist/core/runtime/broker/frame-client.d.ts +1 -1
  94. package/dist/core/runtime/broker/frame-client.js +1 -1
  95. package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
  96. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  97. package/dist/core/runtime/broker/frame-read.d.ts +4 -3
  98. package/dist/core/runtime/broker/frame-read.js +1 -1
  99. package/dist/core/runtime/broker-protocol.d.ts +1 -1
  100. package/dist/core/runtime/host.js +3 -3
  101. package/dist/core/runtime/placement.js +1 -1
  102. package/dist/core/runtime/roadmap.js +1 -1
  103. package/dist/core/substrate/delivery/corpus.d.ts +2 -2
  104. package/dist/core/substrate/delivery/corpus.js +3 -3
  105. package/dist/core/substrate/delivery/deliver.js +2 -2
  106. package/dist/core/substrate/delivery/render-event.js +6 -6
  107. package/dist/core/substrate/subject-fields.d.ts +2 -0
  108. package/dist/core/substrate/subject.js +1 -1
  109. package/dist/daemon/api/app-listener.js +12 -12
  110. package/dist/daemon/api/bridge.d.ts +1 -1
  111. package/dist/daemon/api/bridge.js +4 -4
  112. package/dist/daemon/api/handlers/attach.d.ts +4 -1
  113. package/dist/daemon/api/handlers/attach.js +1 -1
  114. package/dist/daemon/api/handlers/canvas.js +5 -5
  115. package/dist/daemon/api/handlers/check.d.ts +2 -0
  116. package/dist/daemon/api/handlers/check.js +1 -0
  117. package/dist/daemon/api/handlers/custom-objects.js +2 -2
  118. package/dist/daemon/api/handlers/docs.js +1 -1
  119. package/dist/daemon/api/handlers/files.js +1 -1
  120. package/dist/daemon/api/handlers/memory.js +7 -6
  121. package/dist/daemon/api/handlers/nodes.js +1 -1
  122. package/dist/daemon/api/handlers/objects.js +3 -3
  123. package/dist/daemon/api/handlers/relations.d.ts +2 -0
  124. package/dist/daemon/api/handlers/relations.js +1 -0
  125. package/dist/daemon/api/handlers/schemas.d.ts +12 -0
  126. package/dist/daemon/api/handlers/schemas.js +1 -0
  127. package/dist/daemon/api/handlers/shares.d.ts +2 -0
  128. package/dist/daemon/api/handlers/shares.js +1 -0
  129. package/dist/daemon/api/operations.js +1 -1
  130. package/dist/daemon/api/router.d.ts +10 -6
  131. package/dist/daemon/api/router.js +1 -1
  132. package/dist/daemon/api/server.js +1 -1
  133. package/dist/daemon/api/vendor-signin.js +21 -24
  134. package/dist/daemon/crtrd.js +12 -12
  135. package/dist/daemon/reconcilers/delivery-lane.js +2 -2
  136. package/dist/migrations/004-canvas-documents/fields.d.ts +1 -1
  137. package/dist/migrations/004-canvas-documents/fields.js +2 -2
  138. package/docs/apps/guides/files-and-documents.md +3 -3
  139. package/docs/apps/guides/many-users.md +1 -1
  140. package/docs/apps/guides/test-your-app.md +1 -1
  141. package/docs/cli/documents-and-preferences.md +1 -1
  142. package/docs/concepts/documents.md +1 -1
  143. package/docs/concepts/scopes-and-trust.md +2 -2
  144. package/docs/sdk/release-notes.md +11 -0
  145. package/package.json +2 -2
  146. package/packages/crouter-identity/dist/index.js +14 -1
  147. package/packages/crouter-identity/package.json +1 -1
  148. package/runtime.lock.json +13 -13
  149. package/dist/core/graph/spaces/app.d.ts +0 -3
  150. package/dist/core/graph/spaces/app.js +0 -1
  151. package/dist/core/graph/spaces/index.d.ts +0 -18
  152. package/dist/core/graph/spaces/index.js +0 -1
  153. package/dist/core/graph/spaces/own-memory.d.ts +0 -18
  154. package/dist/core/graph/spaces/own-memory.js +0 -1
  155. package/dist/core/graph/spaces/person.d.ts +0 -5
  156. package/dist/core/graph/spaces/person.js +0 -3
  157. package/dist/core/graph/spaces/repo.d.ts +0 -14
  158. package/dist/core/graph/spaces/repo.js +0 -1
  159. package/dist/core/runs/confinement.d.ts +0 -25
  160. package/dist/core/runs/confinement.js +0 -2
@@ -1488,7 +1488,7 @@ ${r}`),e}}});function mGr(t,e){let n=Math.max(0,e-lGr),r=t.reduce((a,c)=>Math.ma
1488
1488
  `)||e.includes("\r")||Buffer.byteLength(e,"utf8")+1>$Ke?!1:FKe(t,[e])}var Dd,NKe=!1;function UKe(t,e){if(e.includes(`
1489
1489
  `)||e.includes("\r"))return!1;let n=Buffer.byteLength(e,"utf8")+1;return n>$Ke?!1:(Dd!==void 0&&Dd.path!==t&&D3(),Dd===void 0&&(Dd={path:t,records:[],bytes:0},NKe||(process.on("exit",D3),NKe=!0)),Dd.path=t,Dd.records.push(e),Dd.bytes+=n,Dd.bytes>=rwn?D3():Dd.timer===void 0&&(Dd.timer=setTimeout(D3,iwn),Dd.timer.unref()),!0)}function D3(){let t=Dd;if(!(t===void 0||t.records.length===0)&&(t.timer!==void 0&&clearTimeout(t.timer),Dd=void 0,!FKe(t.path,t.records)))for(let e of t.records)process.stderr.write(`[crtrd] event log append failed: ${e}
1490
1490
  `)}var Ghe=["rate_limit","overloaded","connection","auth","protocol","context_overflow","wedged","model_not_found","unknown"];function own(t){return typeof t=="object"&&t!==null?t:void 0}function QKe(t){return typeof t=="string"?t:""}function WKe(t){if(t instanceof Error){let n={type:t.name||"Error",message:t.message};return typeof t.stack=="string"&&(n.stack=t.stack),t.cause!==void 0&&(n.cause=t.cause instanceof Error?t.cause.message:String(t.cause)),n}if(typeof t=="string")return{type:"Error",message:t};let e=own(t);return{type:QKe(e?.name)||"Error",message:QKe(e?.message)||String(t)}}import{AsyncLocalStorage as swn}from"node:async_hooks";import{randomBytes as awn}from"node:crypto";var cwn=/^(?!0{32}$)[0-9a-f]{32}$/,jhe=new swn;function L3(t){if(typeof t!="string"||!cwn.test(t))throw new TypeError("operation_id must be 32 lowercase non-zero hexadecimal characters");return t}function zhe(){let t;do t=awn(16).toString("hex");while(t==="00000000000000000000000000000000");return L3(t)}var HKe={current:()=>jhe.getStore(),run:(t,e)=>jhe.run(L3(t),e),fresh:t=>{let e=zhe();return jhe.run(e,()=>t(e))}};var uwn=/^[a-z][a-z0-9]*(?:[._][a-z0-9]+)*$/,lwn=new Set(["error","warn","info","debug"]),dwn=new Set(["daemon","broker","control-plane","front","sentinel"]),pwn=new Set(["succeeded","failed","skipped"]),hwn=new Set(["auto","manual","fatal"]),fwn=new Set(Ghe);function mwn(t){return Buffer.byteLength(t,"utf8")}function O3(t,e,n=128){if(typeof t!="string"||t===""||mwn(t)>n)throw new TypeError(`${e} must be a non-empty string of at most ${n} UTF-8 bytes`);return t}function gwn(t){if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(t))throw new TypeError("ts must be an ISO 8601 timestamp");let e=new Date(t);if(Number.isNaN(e.getTime()))throw new TypeError("ts must be an ISO 8601 timestamp");return e.toISOString()}function Awn(t){if(!fwn.has(t.class))throw new TypeError("error_class.class is invalid");let e={class:t.class};if(t.status!==void 0){if(!Number.isInteger(t.status))throw new TypeError("error_class.status must be an integer");e.status=t.status}if(t.provider!==void 0&&(e.provider=O3(t.provider,"error_class.provider")),t.retry_disposition!==void 0){if(!hwn.has(t.retry_disposition))throw new TypeError("error_class.retry_disposition is invalid");e.retry_disposition=t.retry_disposition}return e}function qKe(t){if(!lwn.has(t.level))throw new TypeError("level is invalid");if(!dwn.has(t.component))throw new TypeError("component is invalid");let e=O3(t.event,"event");if(!uwn.test(e))throw new TypeError("event must be a lowercase dotted identifier");let n=t.operation_id===void 0?HKe.current()??zhe():L3(t.operation_id),r={v:1,ts:t.ts===void 0?new Date().toISOString():gwn(t.ts),level:t.level,event:e,component:t.component,operation_id:n};if(t.node_id!==void 0&&(r.node_id=O3(t.node_id,"node_id")),t.stream_id!==void 0&&(r.stream_id=O3(t.stream_id,"stream_id")),t.duration_ms!==void 0){if(!Number.isFinite(t.duration_ms)||t.duration_ms<0)throw new TypeError("duration_ms must be finite and non-negative");r.duration_ms=t.duration_ms}if(t.outcome!==void 0){if(!pwn.has(t.outcome))throw new TypeError("outcome is invalid");r.outcome=t.outcome}if(t.attempt!==void 0){if(!Number.isInteger(t.attempt)||t.attempt<=0)throw new TypeError("attempt must be a positive integer");r.attempt=t.attempt}return t.error_class!==void 0&&(r.error_class=Awn(t.error_class)),t.error!==void 0&&(r.error=WKe(t.error)),t.fields!==void 0&&(r.fields=t.fields),r}function pS(t){return Buffer.byteLength(t,"utf8")}function dS(t,e){if(pS(t)<=e)return{value:t,altered:!1};let n="\u2026",r=e-pS(n),i=0,o="";for(let s of t){let a=pS(s);if(i+a>r)break;o+=s,i+=a}return{value:o+n,altered:!0}}function ywn(t){return t===void 0?"[Unsupported undefined]":typeof t=="function"?`[Unsupported function${t.name?` ${t.name}`:""}]`:typeof t=="symbol"?`[Unsupported ${String(t)}]`:`[Unsupported ${t?.constructor?.name??typeof t}]`}function Vhe(t,e,n,r){if(r.remaining<=0)return{value:"[Omitted]",altered:!0,dropped:0};if(r.remaining-=1,t===null||typeof t=="boolean")return{value:t,altered:!1,dropped:0};if(typeof t=="string"){let i=dS(t,4096);return{value:i.value,altered:i.altered,dropped:0}}if(typeof t=="number")return Number.isFinite(t)?{value:t,altered:!1,dropped:0}:{value:String(t),altered:!0,dropped:0};if(typeof t=="bigint")return{value:t.toString(),altered:!0,dropped:0};if(t instanceof Date)return{value:Number.isNaN(t.getTime())?"Invalid Date":t.toISOString(),altered:!0,dropped:0};if(typeof t!="object"||t===void 0)return{value:ywn(t),altered:!0,dropped:0};if(n.has(t))return{value:"[Circular]",altered:!0,dropped:0};if(e>=4)return{value:"[Max depth]",altered:!0,dropped:0};n.add(t);try{if(Array.isArray(t)){let u=Math.min(t.length,64),l=[],d=t.length>u,p=t.length-u;for(let h=0;h<u;h+=1){if(r.remaining<=0){d=!0,p+=u-h;break}let f=Vhe(t[h],e+1,n,r);l.push(f.value),d||=f.altered,p+=f.dropped}return{value:l,altered:d,dropped:p}}let i;try{i=Object.keys(t).sort()}catch{return{value:"[Unsupported object]",altered:!0,dropped:0}}let o=i.slice(0,64),s={},a=i.length>o.length,c=i.length-o.length;for(let u=0;u<o.length;u+=1){let l=o[u];if(r.remaining<=0){a=!0,c+=o.length-u;break}let d=dS(l,128),p;try{p=Vhe(t[l],e+1,n,r)}catch{p={value:"[Unsupported property]",altered:!0,dropped:0}}if(Object.prototype.hasOwnProperty.call(s,d.value)){a=!0,c+=1;continue}s[d.value]=p.value,a||=d.altered||p.altered,c+=p.dropped}return{value:s,altered:a,dropped:c}}finally{n.delete(t)}}function xwn(t){let e=dS(String(t.type),128),n=dS(String(t.message),4096),r={type:e.value,message:n.value},i=e.altered||n.altered;if(t.stack!==void 0){let o=dS(String(t.stack),16384);r.stack=o.value,i||=o.altered}if(t.cause!==void 0){let o=dS(String(t.cause),4096);r.cause=o.value,i||=o.altered}return{value:r,altered:i}}function N3(t){return JSON.stringify(t)}function u$(t){return pS(N3(t))+1}function GKe(t){let e=t.fields===void 0?void 0:Vhe(t.fields,0,new WeakSet,{remaining:5e3}),n=t.error===void 0?void 0:xwn(t.error),r={v:1,ts:t.ts,level:t.level,event:t.event,component:t.component,operation_id:t.operation_id,...t.node_id===void 0?{}:{node_id:t.node_id},...t.stream_id===void 0?{}:{stream_id:t.stream_id},...t.duration_ms===void 0?{}:{duration_ms:t.duration_ms},...t.outcome===void 0?{}:{outcome:t.outcome},...t.attempt===void 0?{}:{attempt:t.attempt},...t.error_class===void 0?{}:{error_class:t.error_class},...n===void 0?{}:{error:n.value},...e===void 0?{}:{fields:e.value}},i=u$(r),o=e?.altered===!0||n?.altered===!0||i>65536,s=e?.dropped??0;for(o&&Object.assign(r,{record_truncated:!0,original_bytes:i,dropped_fields_count:s});u$(r)>65536&&r.fields!==void 0;){let u=r.fields,l=Object.keys(u);if(l.length===0){delete r.fields;break}l.sort((d,p)=>{let h=pS(N3(u[p]))-pS(N3(u[d]));return h!==0?h:p<d?-1:p>d?1:0}),delete u[l[0]],s+=1,r.record_truncated=!0,r.original_bytes=i,r.dropped_fields_count=s}let a=r.error;u$(r)>65536&&a?.stack!==void 0&&delete a.stack,u$(r)>65536&&a?.cause!==void 0&&delete a.cause,u$(r)>65536&&a!==void 0&&(a.message=dS(a.message,64).value);let c=N3(r);if(pS(c)+1>65536)throw new RangeError("event record cannot fit within 64 KiB");return c}import{join as obn}from"node:path";import{join as rg}from"node:path";import{existsSync as d$,mkdirSync as Oui,readFileSync as Lwn,statSync as Nui}from"node:fs";import{homedir as Own,userInfo as Nwn}from"node:os";import{basename as $wn,dirname as Uui,isAbsolute as Qui,join as gc,resolve as JKe}from"node:path";import{existsSync as $3,lstatSync as Cui,mkdirSync as wwn,readdirSync as bwn,readFileSync as jKe,rmSync as Ewn,statSync as vwn,symlinkSync as Iui,writeFileSync as Swn,cpSync as kui,readlinkSync as Tui,renameSync as _wn,chmodSync as Cwn,realpathSync as Iwn,closeSync as Yhe,fsyncSync as Jhe,openSync as Xhe,linkSync as kwn,unlinkSync as Twn,writeSync as Rwn}from"node:fs";import{dirname as Khe,join as Mwn,relative as Mui,sep as Pui}from"node:path";import{homedir as Pwn,platform as Dwn}from"node:os";function Sf(t){try{return Iwn(t)}catch{return t}}function zKe(t,e=Pwn()){return t==="~"?e:t.startsWith("~/")||Dwn()==="win32"&&t.startsWith("~\\")?Mwn(e,t.slice(2)):t}function F3(t){wwn(t,{recursive:!0})}function U3(t,e,n){VKe(t,JSON.stringify(e,null,2)+`
1491
- `,n)}function Zhe(t){let e=Xhe(t,"r");try{Jhe(e)}finally{Yhe(e)}}function l$(t){let e=Xhe(t,"r");try{Jhe(e)}finally{Yhe(e)}}function VKe(t,e,n){n?.createParent!==!1&&F3(Khe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??($3(t)?vwn(t).mode&511:384);try{Swn(r,e,{mode:i}),Cwn(r,i),n?.durable===!0&&Zhe(r),_wn(r,t),n?.durable===!0&&l$(Khe(t))}finally{$3(r)&&Ewn(r,{force:!0})}}function efe(t,e,n){let r=`${t}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,i=Xhe(r,"wx",n);try{try{let o=Buffer.from(e,"utf8");for(let s=0;s<o.length;)s+=Rwn(i,o,s,o.length-s);Jhe(i)}finally{Yhe(i)}try{kwn(r,t)}catch(o){if(o.code==="EEXIST")return!1;throw o}return l$(Khe(t)),!0}finally{try{Twn(r)}catch{}}}function Bwn(t){return JSON.parse(jKe(t,"utf8"))}function hS(t){try{return Bwn(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function ZT(t){try{return JSON.parse(jKe(t,"utf8"))}catch{return null}}function tfe(t){return $3(t)}function nfe(t){return $3(t)?bwn(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var KKe="1";function p$(){let t=JKe(by()||(process.platform==="linux"?"/":gc(Own(),".crouter")));if(Fwn()&&t===Uwn())throw new Error(`refusing to use the account's real crouter root ${t} from a node --test process; point CRTR_HOME (not only HOME) at a temporary directory`);return t}function Fwn(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}var Q3;function Uwn(){if(Q3===void 0)try{Q3=JKe(Nwn().homedir,".crouter")}catch{Q3=null}return Q3}function vy(){return gc(p$(),"runtime")}function rfe(){return gc(p$(),"apps")}function Sy(){return gc(vy(),"secrets")}function h$(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=f$(t);return{dir:gc(n.profiles,e),env:gc(Sy(),"env",$wn(n.root),e),home:n.home}}function ife(){return process.platform==="linux"?"/run/crtr":vy()}function YKe(){return gc(vy(),"layout")}function f$(t){let e=t.startsWith("app:")?t.slice(4):t;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)||e==="."||e==="..")throw new Error(`invalid app id: ${t}`);let n=gc(rfe(),e);return{root:n,profiles:gc(n,"profiles"),conversations:gc(n,"conversations"),nodes:gc(n,"nodes"),files:gc(n,"files"),home:gc(n,"home"),cache:gc(n,"cache")}}function Qwn(t){let e=Array.from(t.subarray(0,32),n=>n===92?"\\\\":n===34?'\\"':n===10?"\\n":n===13?"\\r":n===9?"\\t":n>=32&&n<127?String.fromCharCode(n):`\\x${n.toString(16).padStart(2,"0")}`).join("");return`${t.length} bytes, preview "${e}"${t.length>32?"\u2026":""}`}function Wwn(t){let e=Lwn(t);if(e.toString("utf8").trim()!==KKe)throw new Error(`unsupported runtime layout version: ${t} holds ${Qwn(e)}; expected "${KKe}"`)}function XKe(){if(process.env.CRTR_LAYOUT_REFUSE==="1")return!0;if(d$(YKe()))return Wwn(YKe()),!1;let t=p$(),e=process.platform==="linux"&&t==="/"&&d$("/volume")?"/volume":t;return d$(gc(e,"canvas"))||d$(gc(e,"canvas.db"))?!0:d$(gc(vy(),"canvas.db"))}import{chmodSync as zui,chownSync as Vui,closeSync as _f,constants as W3,fchmodSync as Kui,fchownSync as Yui,fstatSync as ufe,fsyncSync as Jui,linkSync as Xui,lstatSync as Zui,mkdirSync as ZKe,openSync as sfe,readdirSync as Hwn,readFileSync as qwn,readlinkSync as eli,readSync as tli,realpathSync as nli,renameSync as rli,rmdirSync as ili,rmSync as oli,statSync as Gwn,symlinkSync as sli,unlinkSync as ali,writeSync as cli}from"node:fs";import{basename as lli,dirname as dli,join as jwn,relative as lfe,resolve as H3,sep as afe}from"node:path";import{loadLinuxNative as zwn,O_CLOEXEC as cfe,O_PATH as G3,RESOLVE_BENEATH as Vwn,RESOLVE_NO_SYMLINKS as Kwn}from"../../native/linux.js";var Ywn=Vwn|Kwn,m$=G3|W3.O_DIRECTORY|cfe,ofe=null;function j3(){return ofe===null&&(ofe=zwn()),ofe}function q3(t){return t.code}var fS=class extends Error{};function Jwn(t,e){switch(q3(t)){case"ELOOP":case"EXDEV":return new fS(`path meets a symlink: ${e}`);case"ENXIO":return new fS(`path is not a regular file: ${e}`);case"EAGAIN":return new fS(`path is held by a lease: ${e}`);default:return t}}function g$(t,e,n,r,i){try{return t.openat2(e,n,r,Ywn)}catch(o){throw Jwn(o,i)}}function Xwn(t,e,n){let r;try{r=ufe(t)}catch(i){throw _f(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw _f(t),new fS(`path is not a regular file: ${e}`)}var Zwn=new Set(["ENOENT","ENOTDIR","EACCES"]);function tYe(t,e){let n=lfe(H3(t),H3(e));if(n===".."||n.startsWith(`..${afe}`)||n.startsWith(afe))throw new Error(`${e} is outside ${t}`);return n}function eYe(t){if(t===""||t===".."||t.includes("/"))throw new Error(`not one path component: ${t}`);return t}function dfe(t,e,n){if(n&W3.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=tYe(t,e),i=j3();if(!i)return sfe(e,n);let o=sfe("/",m$),s;try{s=g$(i,o,lfe("/",H3(t))||".",m$,t)}finally{_f(o)}try{return n&G3?g$(i,s,r||".",n|cfe,e):Xwn(g$(i,s,r||".",n|cfe|W3.O_NONBLOCK,e),e,!0)}finally{_f(s)}}function z3(t,e){let n=dfe(t,e,W3.O_RDONLY);try{return qwn(n)}finally{_f(n)}}function ebn(t,e){if(!j3())return Gwn(e);let n=dfe(t,e,G3);try{return ufe(n)}finally{_f(n)}}function nYe(t,e){try{return ebn(t,e),!0}catch(n){if(Zwn.has(q3(n)??""))return!1;throw n}}function rYe(t,e,n,r=!1){tYe(t,e);let i=j3();if(!i)return r&&ZKe(e,{recursive:!0}),n(s=>s===void 0?e:jwn(e,eYe(s)));let o=sfe("/",m$);try{for(let a of lfe("/",H3(e)).split(afe).filter(Boolean)){let c;try{c=g$(i,o,a,m$,e)}catch(u){if(!r||q3(u)!=="ENOENT")throw u;try{ZKe(`/proc/self/fd/${o}/${a}`)}catch(l){if(q3(l)!=="EEXIST")throw l}c=g$(i,o,a,m$,e)}_f(o),o=c}let s=`/proc/self/fd/${o}`;return n(a=>a===void 0?s:`${s}/${eYe(a)}`)}finally{_f(o)}}function iYe(t,e){return rYe(t,e,n=>Hwn(n(),{withFileTypes:!0}))}function oYe(t,e){if(!j3())return{path:e,release:()=>{}};let n=dfe(t,e,G3),r;try{r=ufe(n)}catch(o){throw _f(n),o}if(!r.isSocket())throw _f(n),new fS(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,_f(n))}}}function Na(){return vy()}function sYe(){return rg(Na(),"on-disk-migration.lock")}function eR(t){return rg(tR(t),"view.sock")}function tbn(){return rg(Na(),"nodes")}function aYe(){return rg(ife(),"api.sock")}var nbn=128;function cYe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=nbn}function pfe(t){if(!cYe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function rbn(t){return pfe(t),rg(tbn(),t)}function ibn(t,e){pfe(t);let n=e??(che()===t?X7e():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return rg(f$(n).nodes,t)}function tR(t){return pfe(t),process.platform==="linux"?rg(ife(),"nodes",t):rg(rbn(t),"run")}var uYe="broker-released",lYe="cli-relay-generation";function V3(t,e){return rg(ibn(t,e),"context")}function dYe(t){return rg(tR(t),"job")}var K3;function sbn(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function abn(t){if(K3===void 0){K3=t;return}if(!sbn(K3,t))throw new Error("event source is already bound for this process")}function pYe(){abn({component:"daemon",path:obn(Na(),"crtrd.log")})}function Y3(){return K3}import{request as Abn}from"node:http";import{homedir as ybn}from"node:os";import{join as gfe}from"node:path";var ln=class extends Error{status;code;details;headers;type;param;origin;retryable;retryAfterS;resetAt;requestId;runId;questionId;scope;userAction;constructor(e,n,r,i,o,s){super(r),this.name="APIError",this.status=e,this.code=n,this.headers=new Headers(o),i!==void 0&&(this.details=i),this.type=s?.type,this.param=s?.param,this.origin=s?.origin,this.retryable=s?.retryable,this.retryAfterS=s?.retry_after_s,this.resetAt=s?.reset_at,this.requestId=s?.request_id??this.headers.get("Request-Id")??void 0,this.runId=s?.run_id,this.questionId=s?.question_id,this.scope=s?.scope,this.userAction=s?.user_action}};function hYe(t){return t instanceof ln?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted")||t.status===504&&(t.code==="request_timeout"||t.code==="deadline_exceeded")||t.status>=500&&t.code==="daemon_health_unavailable":!1}function hfe(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let{code:n,message:r}=e;return typeof n=="string"&&typeof r=="string"}var me={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,nodeJobs:t=>`/v1/nodes/${t}/jobs`,nodeJob:(t,e)=>`/v1/nodes/${t}/jobs/${e}`,nodeJobBackground:(t,e)=>`/v1/nodes/${t}/jobs/${e}/background`,nodeDelivery:t=>`/v1/nodes/${t}/delivery`,deliveryDryRun:()=>"/v1/delivery/dry-run",deliveryRetry:t=>`/v1/deliveries/${encodeURIComponent(t)}/retry`,nodeMessages:t=>`/v1/nodes/${t}/messages`,nodeInterrupt:t=>`/v1/nodes/${t}/interrupt`,nodeFork:t=>`/v1/nodes/${t}/fork`,nodeRevive:t=>`/v1/nodes/${t}/revive`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,nodeBrokerParkComplete:t=>`/v1/nodes/${t}/broker/park-complete`,nodeBrokerParkActivity:t=>`/v1/nodes/${t}/broker/park-activity`,nodeBrokerTelemetry:t=>`/v1/nodes/${t}/broker/telemetry`,nodeLog:t=>`/v1/nodes/${t}/records/log`,nodeTelemetry:t=>`/v1/nodes/${t}/records/telemetry`,nodeRecap:t=>`/v1/nodes/${t}/records/recap`,nodeInboxReport:t=>`/v1/nodes/${t}/records/inbox`,nodePassiveMessage:t=>`/v1/nodes/${t}/records/passive`,nodePushedFinal:t=>`/v1/nodes/${t}/records/pushed-final`,nodeMailClaim:t=>`/v1/nodes/${t}/mail/claim`,nodeMailAcknowledge:t=>`/v1/nodes/${t}/mail/acknowledge`,nodeBrokerModel:t=>`/v1/nodes/${t}/broker/model`,nodeBrokerExtensionState:t=>`/v1/nodes/${t}/broker/extension-state`,nodeBrokerSignals:t=>`/v1/nodes/${t}/broker/signals`,nodeBrokerGeneratedName:t=>`/v1/nodes/${t}/broker/generated-name`,nodeBrokerPersonaAck:t=>`/v1/nodes/${t}/broker/persona-ack`,brokerTurn:t=>`/v1/broker/${t}/turn`,brokerProviderRetry:t=>`/v1/broker/${t}/provider-retry`,brokerFault:t=>`/v1/broker/${t}/fault`,brokerRecovery:t=>`/v1/broker/${t}/recovery`,nodeFault:t=>`/v1/nodes/${t}/fault`,nodeClose:t=>`/v1/nodes/${t}/close`,nodeRead:t=>`/v1/nodes/${t}/read`,nodeRecycle:t=>`/v1/nodes/${t}/recycle`,nodeDemote:t=>`/v1/nodes/${t}/demote`,nodePromote:t=>`/v1/nodes/${t}/promote`,nodeYield:t=>`/v1/nodes/${t}/yield`,nodeWait:t=>`/v1/nodes/${t}/wait`,nodeConfig:t=>`/v1/nodes/${t}/config`,kinds:()=>"/v1/kinds",nodeWorktreeClose:t=>`/v1/nodes/${t}/worktree/close`,nodeWorktreeAbandon:t=>`/v1/nodes/${t}/worktree/abandon`,quarantinedWorktrees:()=>"/v1/worktrees/quarantined",spaces:()=>"/v1/spaces",limits:()=>"/v1/limits",limitsApp:t=>`/v1/limits/apps/${encodeURIComponent(t)}`,nodeAttach:t=>`/v1/nodes/${t}/attach`,focuses:()=>"/v1/focuses",focusByNode:()=>"/v1/focuses/by-node",focusByPane:()=>"/v1/focuses/by-pane",focus:t=>`/v1/focuses/${t}`,nodeSubscriptions:t=>`/v1/nodes/${t}/subscriptions`,nodeSubscription:(t,e)=>`/v1/nodes/${t}/subscriptions/${e}`,crons:()=>"/v1/crons",cron:t=>`/v1/crons/${t}`,cronPause:t=>`/v1/crons/${t}/pause`,cronResume:t=>`/v1/crons/${t}/resume`,cronRun:t=>`/v1/crons/${t}/run`,cronsPoke:()=>"/v1/crons/poke",canvasAttention:()=>"/v1/canvas/attention",canvasAttentionCounts:()=>"/v1/canvas/attention/counts",canvasHistorySearch:()=>"/v1/canvas/history/search",canvasHistoryGrep:()=>"/v1/canvas/history/grep",canvasHistoryRead:()=>"/v1/canvas/history/read",canvasHistoryStats:()=>"/v1/canvas/history/stats",canvasSnapshot:()=>"/v1/canvas/snapshot",canvasLiveRoots:()=>"/v1/canvas/live-roots",canvasRoster:()=>"/v1/canvas/roster",canvasBrowse:()=>"/v1/canvas/browse",canvasAnalytics:()=>"/v1/canvas/analytics",canvasGraph:()=>"/v1/canvas/graph",canvasPrune:()=>"/v1/canvas/prune",humanReviews:()=>"/v1/human/reviews",humanReview:t=>`/v1/human/reviews/${t}`,humanReviewSubmit:t=>`/v1/human/reviews/${t}/submit`,humanReviewCancel:t=>`/v1/human/reviews/${t}/cancel`,humanReviewDocument:t=>`/v1/human/reviews/${t}/document`,humanReviewComments:t=>`/v1/human/reviews/${t}/comments`,humanReviewCommentEvents:t=>`/v1/human/reviews/${t}/comment-events`,humanReviewCommentRanges:t=>`/v1/human/reviews/${t}/comment-ranges`,humanComment:t=>`/v1/human/comments/${t}`,humanCommentEdit:t=>`/v1/human/comments/${t}/edit`,humanCommentResolve:t=>`/v1/human/comments/${t}/resolve`,humanCommentReopen:t=>`/v1/human/comments/${t}/reopen`,humanCommentDelete:t=>`/v1/human/comments/${t}/delete`,humanCommentFork:t=>`/v1/human/comments/${t}/fork`,humanInbox:()=>"/v1/human/inbox",humanInboxTicket:t=>`/v1/human/inbox/${t}`,humanInboxRespond:t=>`/v1/human/inbox/${t}/respond`,humanInboxProgress:t=>`/v1/human/inbox/${t}/progress`,humanInboxResponse:t=>`/v1/human/inbox/${t}/response`,humanInboxCancel:t=>`/v1/human/inbox/${t}/cancel`,humanInboxFeedbackResolve:(t,e)=>`/v1/human/inbox/${t}/feedback-comments/${e}/resolve`,humanRequests:()=>"/v1/human/requests",humanComponents:()=>"/v1/human/components",humanRequest:t=>`/v1/human/requests/${t}`,humanRequestReplace:t=>`/v1/human/requests/${t}/replace`,humanRequestRespond:t=>`/v1/human/requests/${t}/respond`,humanRequestDismiss:t=>`/v1/human/requests/${t}/dismiss`,humanRequestCancel:t=>`/v1/human/requests/${t}/cancel`,profiles:()=>"/v1/profiles",profile:t=>`/v1/profiles/${t}`,profilePause:t=>`/v1/profiles/${t}/pause`,profileResume:t=>`/v1/profiles/${t}/resume`,profileMetadata:t=>`/v1/profiles/${t}/metadata`,appEnv:()=>"/v1/apps/self/env",appEnvVar:t=>`/v1/apps/self/env/${encodeURIComponent(t)}`,profileEnv:t=>`/v1/profiles/${t}/env`,profileEnvVar:(t,e)=>`/v1/profiles/${t}/env/${e}`,modelAuths:()=>"/v1/model-auth",modelAuthReadiness:()=>"/v1/model-auth/readiness",modelAuth:t=>`/v1/model-auth/${t}`,modelAuthFlows:()=>"/v1/model-auth/flows",modelAuthFlow:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}`,modelAuthFlowComplete:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/complete`,modelAuthFlowCancel:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/cancel`,filePeek:()=>"/v1/files/peek",fileWrite:()=>"/v1/files/write",fileList:()=>"/v1/files/list",bash:()=>"/v1/bash",objects:()=>"/v1/objects",object:t=>`/v1/objects/${encodeURIComponent(t)}`,objectsSearch:()=>"/v1/objects/search",objectWatch:t=>`/v1/objects/${encodeURIComponent(t)}/watch`,customObjects:()=>"/v1/custom-objects",customObject:t=>`/v1/custom-objects/${encodeURIComponent(t)}`,customObjectEvents:t=>`/v1/custom-objects/${encodeURIComponent(t)}/events`,customObjectDeliveries:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries`,customObjectAck:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries/ack`,objectEdges:t=>`/v1/objects/${encodeURIComponent(t)}/edges`,docs:()=>"/v1/docs",doc:t=>`/v1/docs/${encodeURIComponent(t)}`,docMove:t=>`/v1/docs/${encodeURIComponent(t)}/move`,docHistory:t=>`/v1/docs/${encodeURIComponent(t)}/history`,docsLint:()=>"/v1/docs/lint",pluginAppToken:t=>`/v1/plugins/${encodeURIComponent(t)}/app-token`,pluginCallHeaders:t=>`/v1/plugins/${encodeURIComponent(t)}/call-headers`,documentsBrowserAccess:()=>"/v1/documents/browser-access",documentsReconcilePackages:()=>"/v1/documents/reconcile-packages"};function J3(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}function fYe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}function mYe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var cbn=3e4,ubn=Symbol.for("@north-light/api/local-socket-fetch"),lbn=1e4,dbn=200;async function X3({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=dbn,retry:i=()=>!0,now:o=Date.now,sleep:s=xYe}){let a=o()+t,c=n;for(;;){let u=a-o();if(u<=0)throw c??new Error("crtrd availability window expired without a probe failure");try{await e(u);return}catch(d){if(c=d,!i(d))throw d}let l=a-o();if(l<=0)throw c;await s(Math.min(r,l))}}var y$=2147483647;function rR(t,e="elapsed",n){let r=e==="retry_after"?`the server asked to retry after ${n}s, which is later than the call's deadline (${new Date(t).toISOString()}); not waiting`:`the call's deadline (${new Date(t).toISOString()}) passed`;return new ln(504,"deadline_exceeded",r,{deadline_at:t,reason:e,...n===void 0?{}:{retry_after_s:n}})}var A$=t=>rR(t??Date.now()),x$=class{baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;availabilityFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??cbn,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[ubn]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??lbn}healthz(){return this.request("GET",me.healthz())}async probeHealthz(e){let n=await this.transport("GET",me.healthz(),void 0,{timeout:e});if(n.status===503)try{let r=await n.clone().json();if(typeof r.startup_blocked=="string")return r}catch{}return nR(n)}async ready(){let e=await this.transport("GET",me.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return nR(e)}status(){return this.request("GET",me.status())}due(){return this.request("GET",me.due())}restartDaemon(){return this.request("POST",me.daemonRestart())}admitDaemon(){return this.request("POST",me.daemonAdmit())}migrateState(e){return this.request("POST",me.daemonMigrate(),e)}appendNodeLog(e,n){return this.request("POST",me.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",me.nodeTelemetry(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",me.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",Tr(me.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}readNodePassiveMessage(e,n){return this.request("GET",Tr(me.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",me.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",me.nodes(),e)}listNodes(e){return this.request("GET",Tr(me.nodes(),e))}getNode(e){return this.request("GET",me.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:n}={}){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",Tr(me.nodeOutcome(this.nodePath(e)),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}getNodeEvents(e,n={},r={}){if(n.after!==void 0&&(!Number.isSafeInteger(n.after)||n.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",Tr(me.nodeEvents(this.nodePath(e)),n),void 0,{...r,headers:{accept:"text/event-stream",...r.headers??{}},timeout:0})}async*getBrokerSignals(e,n,r={}){let i=await this.send("GET",Tr(me.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await nR(i);return}if(i.body===null)throw new ln(i.status,"invalid_response","broker signal stream has no body");let o=i.body.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await o.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
1491
+ `,n)}function Zhe(t){let e=Xhe(t,"r");try{Jhe(e)}finally{Yhe(e)}}function l$(t){let e=Xhe(t,"r");try{Jhe(e)}finally{Yhe(e)}}function VKe(t,e,n){n?.createParent!==!1&&F3(Khe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??($3(t)?vwn(t).mode&511:384);try{Swn(r,e,{mode:i}),Cwn(r,i),n?.durable===!0&&Zhe(r),_wn(r,t),n?.durable===!0&&l$(Khe(t))}finally{$3(r)&&Ewn(r,{force:!0})}}function efe(t,e,n){let r=`${t}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,i=Xhe(r,"wx",n);try{try{let o=Buffer.from(e,"utf8");for(let s=0;s<o.length;)s+=Rwn(i,o,s,o.length-s);Jhe(i)}finally{Yhe(i)}try{kwn(r,t)}catch(o){if(o.code==="EEXIST")return!1;throw o}return l$(Khe(t)),!0}finally{try{Twn(r)}catch{}}}function Bwn(t){return JSON.parse(jKe(t,"utf8"))}function hS(t){try{return Bwn(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function ZT(t){try{return JSON.parse(jKe(t,"utf8"))}catch{return null}}function tfe(t){return $3(t)}function nfe(t){return $3(t)?bwn(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var KKe="1";function p$(){let t=JKe(by()||(process.platform==="linux"?"/":gc(Own(),".crouter")));if(Fwn()&&t===Uwn())throw new Error(`refusing to use the account's real crouter root ${t} from a node --test process; point CRTR_HOME (not only HOME) at a temporary directory`);return t}function Fwn(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}var Q3;function Uwn(){if(Q3===void 0)try{Q3=JKe(Nwn().homedir,".crouter")}catch{Q3=null}return Q3}function vy(){return gc(p$(),"runtime")}function rfe(){return gc(p$(),"apps")}function Sy(){return gc(vy(),"secrets")}function h$(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=f$(t);return{dir:gc(n.profiles,e),env:gc(Sy(),"env",$wn(n.root),e),home:n.home}}function ife(){return process.platform==="linux"?"/run/crtr":vy()}function YKe(){return gc(vy(),"layout")}function f$(t){let e=t.startsWith("app:")?t.slice(4):t;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)||e==="."||e==="..")throw new Error(`invalid app id: ${t}`);let n=gc(rfe(),e);return{root:n,profiles:gc(n,"profiles"),conversations:gc(n,"conversations"),nodes:gc(n,"nodes"),files:gc(n,"files"),home:gc(n,"home"),cache:gc(n,"cache")}}function Qwn(t){let e=Array.from(t.subarray(0,32),n=>n===92?"\\\\":n===34?'\\"':n===10?"\\n":n===13?"\\r":n===9?"\\t":n>=32&&n<127?String.fromCharCode(n):`\\x${n.toString(16).padStart(2,"0")}`).join("");return`${t.length} bytes, preview "${e}"${t.length>32?"\u2026":""}`}function Wwn(t){let e=Lwn(t);if(e.toString("utf8").trim()!==KKe)throw new Error(`unsupported runtime layout version: ${t} holds ${Qwn(e)}; expected "${KKe}"`)}function XKe(){if(process.env.CRTR_LAYOUT_REFUSE==="1")return!0;if(d$(YKe()))return Wwn(YKe()),!1;let t=p$(),e=process.platform==="linux"&&t==="/"&&d$("/volume")?"/volume":t;return d$(gc(e,"canvas"))||d$(gc(e,"canvas.db"))?!0:d$(gc(vy(),"canvas.db"))}import{chmodSync as zui,chownSync as Vui,closeSync as _f,constants as W3,fchmodSync as Kui,fchownSync as Yui,fstatSync as ufe,fsyncSync as Jui,linkSync as Xui,lstatSync as Zui,mkdirSync as ZKe,openSync as sfe,readdirSync as Hwn,readFileSync as qwn,readlinkSync as eli,readSync as tli,realpathSync as nli,renameSync as rli,rmdirSync as ili,rmSync as oli,statSync as Gwn,symlinkSync as sli,unlinkSync as ali,writeSync as cli}from"node:fs";import{basename as lli,dirname as dli,join as jwn,relative as lfe,resolve as H3,sep as afe}from"node:path";import{loadLinuxNative as zwn,O_CLOEXEC as cfe,O_PATH as G3,RESOLVE_BENEATH as Vwn,RESOLVE_NO_SYMLINKS as Kwn}from"../../native/linux.js";var Ywn=Vwn|Kwn,m$=G3|W3.O_DIRECTORY|cfe,ofe=null;function j3(){return ofe===null&&(ofe=zwn()),ofe}function q3(t){return t.code}var fS=class extends Error{};function Jwn(t,e){switch(q3(t)){case"ELOOP":case"EXDEV":return new fS(`path meets a symlink: ${e}`);case"ENXIO":return new fS(`path is not a regular file: ${e}`);case"EAGAIN":return new fS(`path is held by a lease: ${e}`);default:return t}}function g$(t,e,n,r,i){try{return t.openat2(e,n,r,Ywn)}catch(o){throw Jwn(o,i)}}function Xwn(t,e,n){let r;try{r=ufe(t)}catch(i){throw _f(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw _f(t),new fS(`path is not a regular file: ${e}`)}var Zwn=new Set(["ENOENT","ENOTDIR","EACCES"]);function tYe(t,e){let n=lfe(H3(t),H3(e));if(n===".."||n.startsWith(`..${afe}`)||n.startsWith(afe))throw new Error(`${e} is outside ${t}`);return n}function eYe(t){if(t===""||t===".."||t.includes("/"))throw new Error(`not one path component: ${t}`);return t}function dfe(t,e,n){if(n&W3.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=tYe(t,e),i=j3();if(!i)return sfe(e,n);let o=sfe("/",m$),s;try{s=g$(i,o,lfe("/",H3(t))||".",m$,t)}finally{_f(o)}try{return n&G3?g$(i,s,r||".",n|cfe,e):Xwn(g$(i,s,r||".",n|cfe|W3.O_NONBLOCK,e),e,!0)}finally{_f(s)}}function z3(t,e){let n=dfe(t,e,W3.O_RDONLY);try{return qwn(n)}finally{_f(n)}}function ebn(t,e){if(!j3())return Gwn(e);let n=dfe(t,e,G3);try{return ufe(n)}finally{_f(n)}}function nYe(t,e){try{return ebn(t,e),!0}catch(n){if(Zwn.has(q3(n)??""))return!1;throw n}}function rYe(t,e,n,r=!1){tYe(t,e);let i=j3();if(!i)return r&&ZKe(e,{recursive:!0}),n(s=>s===void 0?e:jwn(e,eYe(s)));let o=sfe("/",m$);try{for(let a of lfe("/",H3(e)).split(afe).filter(Boolean)){let c;try{c=g$(i,o,a,m$,e)}catch(u){if(!r||q3(u)!=="ENOENT")throw u;try{ZKe(`/proc/self/fd/${o}/${a}`)}catch(l){if(q3(l)!=="EEXIST")throw l}c=g$(i,o,a,m$,e)}_f(o),o=c}let s=`/proc/self/fd/${o}`;return n(a=>a===void 0?s:`${s}/${eYe(a)}`)}finally{_f(o)}}function iYe(t,e){return rYe(t,e,n=>Hwn(n(),{withFileTypes:!0}))}function oYe(t,e){if(!j3())return{path:e,release:()=>{}};let n=dfe(t,e,G3),r;try{r=ufe(n)}catch(o){throw _f(n),o}if(!r.isSocket())throw _f(n),new fS(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,_f(n))}}}function Na(){return vy()}function sYe(){return rg(Na(),"on-disk-migration.lock")}function eR(t){return rg(tR(t),"view.sock")}function tbn(){return rg(Na(),"nodes")}function aYe(){return rg(ife(),"api.sock")}var nbn=128;function cYe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=nbn}function pfe(t){if(!cYe(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function rbn(t){return pfe(t),rg(tbn(),t)}function ibn(t,e){pfe(t);let n=e??(che()===t?X7e():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return rg(f$(n).nodes,t)}function tR(t){return pfe(t),process.platform==="linux"?rg(ife(),"nodes",t):rg(rbn(t),"run")}var uYe="broker-released",lYe="cli-relay-generation";function V3(t,e){return rg(ibn(t,e),"context")}function dYe(t){return rg(tR(t),"job")}var K3;function sbn(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function abn(t){if(K3===void 0){K3=t;return}if(!sbn(K3,t))throw new Error("event source is already bound for this process")}function pYe(){abn({component:"daemon",path:obn(Na(),"crtrd.log")})}function Y3(){return K3}import{request as Abn}from"node:http";import{homedir as ybn}from"node:os";import{join as gfe}from"node:path";var ln=class extends Error{status;code;details;headers;type;param;origin;retryable;retryAfterS;resetAt;requestId;runId;questionId;scope;userAction;constructor(e,n,r,i,o,s){super(r),this.name="APIError",this.status=e,this.code=n,this.headers=new Headers(o),i!==void 0&&(this.details=i),this.type=s?.type,this.param=s?.param,this.origin=s?.origin,this.retryable=s?.retryable,this.retryAfterS=s?.retry_after_s,this.resetAt=s?.reset_at,this.requestId=s?.request_id??this.headers.get("Request-Id")??void 0,this.runId=s?.run_id,this.questionId=s?.question_id,this.scope=s?.scope,this.userAction=s?.user_action}};function hYe(t){return t instanceof ln?t.status===503&&(t.code==="daemon_unavailable"||t.code==="transport_error"||t.code==="daemon_request_interrupted")||t.status===504&&(t.code==="request_timeout"||t.code==="deadline_exceeded")||t.status>=500&&t.code==="daemon_health_unavailable":!1}function hfe(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let{code:n,message:r}=e;return typeof n=="string"&&typeof r=="string"}var me={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,nodeJobs:t=>`/v1/nodes/${t}/jobs`,nodeJob:(t,e)=>`/v1/nodes/${t}/jobs/${e}`,nodeJobBackground:(t,e)=>`/v1/nodes/${t}/jobs/${e}/background`,nodeDelivery:t=>`/v1/nodes/${t}/delivery`,deliveryDryRun:()=>"/v1/delivery/dry-run",deliveryRetry:t=>`/v1/deliveries/${encodeURIComponent(t)}/retry`,nodeMessages:t=>`/v1/nodes/${t}/messages`,nodeInterrupt:t=>`/v1/nodes/${t}/interrupt`,nodeFork:t=>`/v1/nodes/${t}/fork`,nodeRevive:t=>`/v1/nodes/${t}/revive`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,nodeBrokerParkComplete:t=>`/v1/nodes/${t}/broker/park-complete`,nodeBrokerParkActivity:t=>`/v1/nodes/${t}/broker/park-activity`,nodeBrokerTelemetry:t=>`/v1/nodes/${t}/broker/telemetry`,nodeLog:t=>`/v1/nodes/${t}/records/log`,nodeTelemetry:t=>`/v1/nodes/${t}/records/telemetry`,nodeRecap:t=>`/v1/nodes/${t}/records/recap`,nodeInboxReport:t=>`/v1/nodes/${t}/records/inbox`,nodePassiveMessage:t=>`/v1/nodes/${t}/records/passive`,nodePushedFinal:t=>`/v1/nodes/${t}/records/pushed-final`,nodeMailClaim:t=>`/v1/nodes/${t}/mail/claim`,nodeMailAcknowledge:t=>`/v1/nodes/${t}/mail/acknowledge`,nodeBrokerModel:t=>`/v1/nodes/${t}/broker/model`,nodeBrokerExtensionState:t=>`/v1/nodes/${t}/broker/extension-state`,nodeBrokerSignals:t=>`/v1/nodes/${t}/broker/signals`,nodeBrokerGeneratedName:t=>`/v1/nodes/${t}/broker/generated-name`,nodeBrokerPersonaAck:t=>`/v1/nodes/${t}/broker/persona-ack`,brokerTurn:t=>`/v1/broker/${t}/turn`,brokerProviderRetry:t=>`/v1/broker/${t}/provider-retry`,brokerFault:t=>`/v1/broker/${t}/fault`,brokerRecovery:t=>`/v1/broker/${t}/recovery`,nodeFault:t=>`/v1/nodes/${t}/fault`,nodeClose:t=>`/v1/nodes/${t}/close`,nodeRead:t=>`/v1/nodes/${t}/read`,nodeRecycle:t=>`/v1/nodes/${t}/recycle`,nodeDemote:t=>`/v1/nodes/${t}/demote`,nodePromote:t=>`/v1/nodes/${t}/promote`,nodeYield:t=>`/v1/nodes/${t}/yield`,nodeWait:t=>`/v1/nodes/${t}/wait`,nodeConfig:t=>`/v1/nodes/${t}/config`,kinds:()=>"/v1/kinds",nodeWorktreeClose:t=>`/v1/nodes/${t}/worktree/close`,nodeWorktreeAbandon:t=>`/v1/nodes/${t}/worktree/abandon`,quarantinedWorktrees:()=>"/v1/worktrees/quarantined",spaces:()=>"/v1/spaces",limits:()=>"/v1/limits",limitsApp:t=>`/v1/limits/apps/${encodeURIComponent(t)}`,nodeAttach:t=>`/v1/nodes/${t}/attach`,focuses:()=>"/v1/focuses",focusByNode:()=>"/v1/focuses/by-node",focusByPane:()=>"/v1/focuses/by-pane",focus:t=>`/v1/focuses/${t}`,nodeSubscriptions:t=>`/v1/nodes/${t}/subscriptions`,nodeSubscription:(t,e)=>`/v1/nodes/${t}/subscriptions/${e}`,crons:()=>"/v1/crons",cron:t=>`/v1/crons/${t}`,cronPause:t=>`/v1/crons/${t}/pause`,cronResume:t=>`/v1/crons/${t}/resume`,cronRun:t=>`/v1/crons/${t}/run`,cronsPoke:()=>"/v1/crons/poke",canvasAttention:()=>"/v1/canvas/attention",canvasAttentionCounts:()=>"/v1/canvas/attention/counts",canvasHistorySearch:()=>"/v1/canvas/history/search",canvasHistoryGrep:()=>"/v1/canvas/history/grep",canvasHistoryRead:()=>"/v1/canvas/history/read",canvasHistoryStats:()=>"/v1/canvas/history/stats",canvasSnapshot:()=>"/v1/canvas/snapshot",canvasLiveRoots:()=>"/v1/canvas/live-roots",canvasRoster:()=>"/v1/canvas/roster",canvasBrowse:()=>"/v1/canvas/browse",canvasAnalytics:()=>"/v1/canvas/analytics",canvasGraph:()=>"/v1/canvas/graph",canvasPrune:()=>"/v1/canvas/prune",humanReviews:()=>"/v1/human/reviews",humanReview:t=>`/v1/human/reviews/${t}`,humanReviewSubmit:t=>`/v1/human/reviews/${t}/submit`,humanReviewCancel:t=>`/v1/human/reviews/${t}/cancel`,humanReviewDocument:t=>`/v1/human/reviews/${t}/document`,humanReviewComments:t=>`/v1/human/reviews/${t}/comments`,humanReviewCommentEvents:t=>`/v1/human/reviews/${t}/comment-events`,humanReviewCommentRanges:t=>`/v1/human/reviews/${t}/comment-ranges`,humanComment:t=>`/v1/human/comments/${t}`,humanCommentEdit:t=>`/v1/human/comments/${t}/edit`,humanCommentResolve:t=>`/v1/human/comments/${t}/resolve`,humanCommentReopen:t=>`/v1/human/comments/${t}/reopen`,humanCommentDelete:t=>`/v1/human/comments/${t}/delete`,humanCommentFork:t=>`/v1/human/comments/${t}/fork`,humanInbox:()=>"/v1/human/inbox",humanInboxTicket:t=>`/v1/human/inbox/${t}`,humanInboxRespond:t=>`/v1/human/inbox/${t}/respond`,humanInboxProgress:t=>`/v1/human/inbox/${t}/progress`,humanInboxResponse:t=>`/v1/human/inbox/${t}/response`,humanInboxCancel:t=>`/v1/human/inbox/${t}/cancel`,humanInboxFeedbackResolve:(t,e)=>`/v1/human/inbox/${t}/feedback-comments/${e}/resolve`,humanRequests:()=>"/v1/human/requests",humanComponents:()=>"/v1/human/components",humanRequest:t=>`/v1/human/requests/${t}`,humanRequestReplace:t=>`/v1/human/requests/${t}/replace`,humanRequestRespond:t=>`/v1/human/requests/${t}/respond`,humanRequestDismiss:t=>`/v1/human/requests/${t}/dismiss`,humanRequestCancel:t=>`/v1/human/requests/${t}/cancel`,profiles:()=>"/v1/profiles",profile:t=>`/v1/profiles/${t}`,profilePause:t=>`/v1/profiles/${t}/pause`,profileResume:t=>`/v1/profiles/${t}/resume`,profileMetadata:t=>`/v1/profiles/${t}/metadata`,appEnv:()=>"/v1/apps/self/env",appEnvVar:t=>`/v1/apps/self/env/${encodeURIComponent(t)}`,profileEnv:t=>`/v1/profiles/${t}/env`,profileEnvVar:(t,e)=>`/v1/profiles/${t}/env/${e}`,modelAuths:()=>"/v1/model-auth",modelAuthReadiness:()=>"/v1/model-auth/readiness",modelAuth:t=>`/v1/model-auth/${t}`,modelAuthFlows:()=>"/v1/model-auth/flows",modelAuthFlow:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}`,modelAuthFlowComplete:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/complete`,modelAuthFlowCancel:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/cancel`,filePeek:()=>"/v1/files/peek",fileWrite:()=>"/v1/files/write",fileList:()=>"/v1/files/list",bash:()=>"/v1/bash",objects:()=>"/v1/objects",object:t=>`/v1/objects/${encodeURIComponent(t)}`,objectsSearch:()=>"/v1/objects/search",objectWatch:t=>`/v1/objects/${encodeURIComponent(t)}/watch`,customObjects:()=>"/v1/custom-objects",customObject:t=>`/v1/custom-objects/${encodeURIComponent(t)}`,customObjectEvents:t=>`/v1/custom-objects/${encodeURIComponent(t)}/events`,customObjectDeliveries:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries`,customObjectAck:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries/ack`,objectShares:t=>`/v1/objects/${encodeURIComponent(t)}/shares`,objectEdges:t=>`/v1/objects/${encodeURIComponent(t)}/edges`,docs:()=>"/v1/docs",doc:t=>`/v1/docs/${encodeURIComponent(t)}`,docMove:t=>`/v1/docs/${encodeURIComponent(t)}/move`,docHistory:t=>`/v1/docs/${encodeURIComponent(t)}/history`,docsLint:()=>"/v1/docs/lint",schemas:()=>"/v1/schemas",relations:()=>"/v1/relations",check:()=>"/v1/check",pluginAppToken:t=>`/v1/plugins/${encodeURIComponent(t)}/app-token`,pluginCallHeaders:t=>`/v1/plugins/${encodeURIComponent(t)}/call-headers`,documentsBrowserAccess:()=>"/v1/documents/browser-access",documentsReconcilePackages:()=>"/v1/documents/reconcile-packages"};function J3(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}function fYe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}function mYe(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var cbn=3e4,ubn=Symbol.for("@north-light/api/local-socket-fetch"),lbn=1e4,dbn=200;async function X3({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=dbn,retry:i=()=>!0,now:o=Date.now,sleep:s=xYe}){let a=o()+t,c=n;for(;;){let u=a-o();if(u<=0)throw c??new Error("crtrd availability window expired without a probe failure");try{await e(u);return}catch(d){if(c=d,!i(d))throw d}let l=a-o();if(l<=0)throw c;await s(Math.min(r,l))}}var y$=2147483647;function rR(t,e="elapsed",n){let r=e==="retry_after"?`the server asked to retry after ${n}s, which is later than the call's deadline (${new Date(t).toISOString()}); not waiting`:`the call's deadline (${new Date(t).toISOString()}) passed`;return new ln(504,"deadline_exceeded",r,{deadline_at:t,reason:e,...n===void 0?{}:{retry_after_s:n}})}var A$=t=>rR(t??Date.now()),x$=class{baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;availabilityFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??cbn,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[ubn]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??lbn}healthz(){return this.request("GET",me.healthz())}async probeHealthz(e){let n=await this.transport("GET",me.healthz(),void 0,{timeout:e});if(n.status===503)try{let r=await n.clone().json();if(typeof r.startup_blocked=="string")return r}catch{}return nR(n)}async ready(){let e=await this.transport("GET",me.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return nR(e)}status(){return this.request("GET",me.status())}due(){return this.request("GET",me.due())}restartDaemon(){return this.request("POST",me.daemonRestart())}admitDaemon(){return this.request("POST",me.daemonAdmit())}migrateState(e){return this.request("POST",me.daemonMigrate(),e)}appendNodeLog(e,n){return this.request("POST",me.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",me.nodeTelemetry(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",me.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",Tr(me.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}readNodePassiveMessage(e,n){return this.request("GET",Tr(me.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",me.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",me.nodes(),e)}listNodes(e){return this.request("GET",Tr(me.nodes(),e))}getNode(e){return this.request("GET",me.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:n}={}){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",Tr(me.nodeOutcome(this.nodePath(e)),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}getNodeEvents(e,n={},r={}){if(n.after!==void 0&&(!Number.isSafeInteger(n.after)||n.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",Tr(me.nodeEvents(this.nodePath(e)),n),void 0,{...r,headers:{accept:"text/event-stream",...r.headers??{}},timeout:0})}async*getBrokerSignals(e,n,r={}){let i=await this.send("GET",Tr(me.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await nR(i);return}if(i.body===null)throw new ln(i.status,"invalid_response","broker signal stream has no body");let o=i.body.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await o.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
1492
1492
  `))!==-1;){let d=a.slice(0,l);a=a.slice(l+1),d!==""&&(yield JSON.parse(d))}}if(a+=s.decode(),a.trim()!=="")throw new ln(502,"invalid_response","broker signal stream ended mid-line")}finally{await o.cancel().catch(()=>{})}}createStructuredRequest(e,n){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,n):this.request("POST","/v1/structured-requests",e,n)}getStructuredRequest(e,{wait:n=0,budgetMs:r}={}){if(!Number.isInteger(n)||n<0||n>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",Tr(`/v1/structured-requests/${this.requestPath(e)}`,{wait:n}),void 0,{budgetMs:r})}cancelStructuredRequest(e,n){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},n)}registerOutcomeDelivery(e,n){return this.request("PUT",me.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",me.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",me.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",me.nodeJobs(this.nodePath(e)))}stopBashJob(e,n){return this.request("DELETE",me.nodeJob(this.nodePath(e),this.jobPath(n)))}sendMessage(e,n){return this.request("POST",me.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",me.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",me.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",me.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",me.nodeFork(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",me.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",me.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",me.nodeBrokerSessionBound(this.nodePath(e)),n)}settleBroker(e,n){return this.request("POST",me.nodeBrokerSettle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",me.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",me.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",me.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",me.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",me.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",me.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",me.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",me.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${me.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",me.nodeFault(this.nodePath(e)),n)}clearNodeFault(e,n={}){let r=new URLSearchParams;n.link!==void 0&&r.set("link",n.link),n.preserve_episode!==void 0&&r.set("preserve_episode",String(n.preserve_episode));let i=r.size===0?"":`?${r.toString()}`;return this.request("DELETE",`${me.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",me.nodeBrokerModel(this.nodePath(e)),n)}brokerExtensionState(e){return this.request("GET",me.nodeBrokerExtensionState(this.nodePath(e)))}commitBrokerGeneratedName(e,n){return this.request("POST",me.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",me.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",me.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",me.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",me.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",me.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",me.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",me.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",me.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",me.kinds())}patchConfig(e,n){return this.request("PATCH",me.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",me.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",me.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",me.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",me.quarantinedWorktrees())}showLimits(){return this.request("GET",me.limits())}setAppLimits(e,n){return this.request("PUT",me.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",Tr(me.limitsApp(e),{fields:n.join(",")}))}listSpaces(){return this.request("GET",me.spaces())}subscribe(e,n){return this.request("POST",me.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",me.focuses())}focusOf(e){return this.request("GET",Tr(me.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",Tr(me.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",me.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",me.focus(e),n)}async closeFocus(e){await this.request("DELETE",me.focus(e))}async unsubscribe(e,n){await this.request("DELETE",me.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",me.crons(),e)}listCrons(e){return this.request("GET",Tr(me.crons(),e))}showCron(e,n){return this.request("GET",Tr(me.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",Tr(me.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",Tr(me.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",Tr(me.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",Tr(me.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",me.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",me.nodeAttach(this.nodePath(e)),n??{})}getReports(e,n){return this.request("GET",Tr(me.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",Tr(me.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",me.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",me.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",Tr(me.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",me.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",me.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",Tr(me.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",me.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",Tr(me.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",me.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",Tr(me.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",me.bash(),e,n)}objects={read:(e,n)=>this.request("GET",Tr(me.object(e),n)),list:e=>this.request("GET",Tr(me.objects(),e)),search:e=>this.request("POST",me.objectsSearch(),e),watch:(e,n={})=>this.request("POST",me.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",Tr(me.objectWatch(e),n)),edges:(e,n)=>this.request("GET",Tr(me.objectEdges(e),n))};docs={write:e=>this.request("POST",me.docs(),e),edit:(e,n)=>this.request("PATCH",me.doc(e),n),move:(e,n)=>this.request("POST",me.docMove(e),n),delete:e=>this.request("DELETE",me.doc(e)),history:(e,n)=>this.request("GET",Tr(me.docHistory(e),n)),lint:(e={})=>this.request("POST",me.docsLint(),e)};documents={browserAccess:()=>this.request("GET",me.documentsBrowserAccess()),reconcilePackages:()=>this.request("POST",me.documentsReconcilePackages())};plugins={appToken:e=>this.request("GET",me.pluginAppToken(e)),callHeaders:(e,n)=>this.request("POST",me.pluginCallHeaders(e),n)};nodeDelivery(e,n){return this.request("POST",me.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",me.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",me.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",me.profile(e),n??{})}createProfile(e){return this.request("POST",me.profiles(),e)}listProfiles(){return this.request("GET",me.profiles())}updateProfile(e,n){return this.request("PATCH",me.profile(e),n)}listAppEnv(){return this.request("GET",me.appEnv())}setAppEnv(e,n){return this.request("PUT",me.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",me.appEnvVar(e))}listProfileEnv(e){return this.request("GET",me.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",me.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",me.profileEnvVar(e,n))}getProfile(e){return this.request("GET",me.profile(e))}pauseProfile(e){return this.request("POST",me.profilePause(e),{})}resumeProfile(e){return this.request("POST",me.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",me.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",me.profile(e),n)}listModelAuth(){return this.request("GET",me.modelAuths())}getModelAuthReadiness(e){return this.request("GET",Tr(me.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",me.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",me.modelAuth(e))}startModelAuth(e){return this.request("POST",me.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",me.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",me.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",Tr(me.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",me.humanReviews(),e)}listReviews(e){return this.request("GET",Tr(me.humanReviews(),e))}getReview(e){return this.request("GET",me.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",me.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",me.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",me.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",me.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",Tr(me.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",Tr(me.humanReviewCommentEvents(this.reviewPath(e)),n))}updateReviewCommentRanges(e,n){return this.request("POST",me.humanReviewCommentRanges(this.reviewPath(e)),n)}getReviewComment(e){return this.request("GET",me.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",me.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",me.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",me.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",me.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",me.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",me.humanInbox())}getHumanInboxPage(e){return this.request("GET",me.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,n={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",Tr(me.humanInbox()+"/history",{node_id:e,state:n.state}))}respondHumanInboxPage(e,n){return this.request("POST",me.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",me.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",me.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",me.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",me.humanRequests(),e)}listPageComponents(){return this.request("GET",me.humanComponents())}getHumanRequest(e){return this.request("GET",me.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",me.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",me.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",me.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",me.humanRequestCancel(this.requestPath(e)),n)}resolvePageFeedbackComment(e,n,r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(n)}`);return this.request("POST",me.humanInboxFeedbackResolve(this.ticketId(e),n),{node_id:r})}async dashboard(e){let n=e?.under!==void 0?{under:e.under}:void 0,[r,i]=await Promise.all([this.listNodes(n),this.status()]);return{nodes:r,counts:i.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",me.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",me.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",me.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",me.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",Tr(me.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",me.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",me.canvasSnapshot())}analytics(e){return this.request("GET",Tr(me.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",me.nodeMemoryReads(this.nodePath(e)),n)}liveRoots(e={}){return this.request("GET",Tr(me.canvasLiveRoots(),e))}canvasRoster(){return this.request("GET",me.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",me.canvasBrowse());return e.ok||await nR(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",me.canvasGraph())}prune(e){return this.request("POST",me.canvasPrune(),e)}async request(e,n,r,i){try{let o=i===void 0?void 0:this.resolveBudget(i),s=await this.send(e,n,r,o);return await nR(s,o?.deadlineAt)}catch(o){throw qx(o,i?.signal)}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw qx(i,r?.signal)}}async send(e,n,r,i={}){let o=this.resolveBudget(i),s=e==="GET"||e==="HEAD"||e==="DELETE",a=o.maxRetries??this.maxRetries;for(let c=0;;c++){let u;try{u=await this.transport(e,n,r,o)}catch(l){if(this.isColdSocketError(l)||this.isInterruptedSocketError(l)){let d=this.availabilityFailure?.();if(d!==void 0)throw d}if(this.isColdSocketError(l))try{await this.handleColdSocket(l,o.deadlineAt),u=await this.transport(e,n,r,o)}catch(d){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!yYe(d,o.signal)?rR(o.deadlineAt):qx(d,o.signal)}else{if(this.isInterruptedSocketError(l)&&this.localSocketTransport&&(!s||c<a))return await this.rideOutInterruptedRequest(e,n,r,o);if(s&&c<a&&!yYe(l,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(l))){await mfe(AYe(c+1),o);continue}else throw qx(l,o.signal)}}if(s&&c<a&&pbn(u.status)){await gYe(u,o.deadlineAt),await mfe(AYe(c+1),o,fbn(u));continue}return u}}resolveBudget(e){let{budgetMs:n,deadlineAt:r,...i}=e;if(n===void 0&&r===void 0)return i;if(n!==void 0&&(!Number.isFinite(n)||n<=0||n>y$))throw new RangeError(`budgetMs must be a positive finite number of at most ${y$}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>y$))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${y$} ms from now`);return{...i,deadlineAt:Math.min(r??1/0,n===void 0?1/0:Date.now()+n)}}async awaitWithinBudget(e,n){if(n===void 0)return e;let r=n-Date.now();if(r<=0)throw A$(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(A$(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await nR(await this.transport(e,n,r,o))}catch(s){throw qx(s,o.signal)}}nodePath(e){if(!J3(e))throw new ln(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!fYe(e))throw new ln(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!mYe(e))throw new ln(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!J3(e))throw new ln(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!J3(e))throw new ln(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new ln(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,n,r,i={}){let o=i.deadlineAt===void 0?void 0:i.deadlineAt-Date.now();if(o!==void 0&&o<=0)return Promise.reject(A$(i.deadlineAt));let s=r===void 0?void 0:JSON.stringify(r),a={accept:"application/json",...this.headers,...i.headers};s!==void 0&&(a["content-type"]="application/json");let c=i.timeout??this.timeoutMs,u=o===void 0?c:c>0?Math.min(c,o):o,l=new AbortController,d=o!==void 0&&(c<=0||o<=c),p=u>0?setTimeout(()=>l.abort(d?A$(i.deadlineAt):new DOMException("request timed out","TimeoutError")),u):void 0,h=i.signal,f=()=>l.abort(h?.reason);h!==void 0&&(h.aborted?l.abort(h.reason):h.addEventListener("abort",f,{once:!0}));let m=()=>{p!==void 0&&clearTimeout(p),h?.removeEventListener("abort",f)};return mbn(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>this.retainRequestLifetime(g,m,()=>l.signal.aborted?l.signal.reason:void 0),g=>{throw m(),g})}retainRequestLifetime(e,n,r){if(e.body===null)return n(),e;let i=e.body.getReader(),o=!1,s=()=>{o||(o=!0,n())},a=new ReadableStream({async pull(c){try{let{done:u,value:l}=await i.read();u?(s(),c.close()):c.enqueue(l)}catch(u){s(),c.error(r()??u)}},async cancel(c){s(),await i.cancel(c)}});return new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){let n=ffe(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=ffe(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw qx(o,i.signal)}if(e!=="GET"&&e!=="HEAD")throw new ln(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,n,r,i)}catch(o){throw qx(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw A$(n);let i,o;try{await X3({windowMs:Math.min(this.coldStartPollWindowMs,r??this.coldStartPollWindowMs),initialError:e,retry:s=>s!==i&&s!==o,probe:async s=>{let a=this.availabilityFailure?.();if(a!==void 0)throw o=a,a;let c=this.coldStartFailure?.();if(c!==void 0)throw i=new ln(503,"daemon_unavailable",`crtrd failed to start: ${c}`),i;let u=await this.transport("GET",me.healthz(),void 0,{timeout:s});if(u.status>=200&&u.status<300){await gYe(u);return}let l=await u.text();try{if(typeof JSON.parse(l).startup_blocked=="string")return}catch{}throw new ln(u.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${u.status}: ${l.slice(0,500)}`)}})}catch(s){throw s===i&&(this.startupFailureReported=!0),s}}async handleColdSocket(e,n){let r=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;r&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),n));try{await this.awaitAvailability(e,n)}catch(i){if(r&&!this.startupFailureReported){let o=gbn(this.coldStartDiagnostic);if(o!==void 0){let s=qx(i);throw new ln(s.status,s.code,`${s.message}
1493
1493
  ${o}`)}}throw i}}};function Tr(t,e){if(e===void 0)return t;let n=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}async function nR(t,e){let n=t.status>=200&&t.status<300,r=(await hbn(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new ln(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw hfe(i)?new ln(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new ln(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function pbn(t){return t===429||t>=500}async function gYe(t,e){let n=(async()=>{try{await t.body?.cancel()}catch{}})();if(e===void 0)return n;let r;try{await Promise.race([n,new Promise(i=>{r=setTimeout(i,Math.max(0,e-Date.now()))})])}finally{r!==void 0&&clearTimeout(r)}}async function hbn(t,e){if(e===void 0)return t.text();let n=e-Date.now(),r=t.text();if(r.catch(()=>{}),n<=0)throw t.body?.cancel().catch(()=>{}),rR(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(rR(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function AYe(t){return Math.min(2e3,250*2**(t-1))}function ffe(t){if(typeof t!="object"||t===null)return;let e=t.code;if(typeof e=="string")return e;let n=t.cause;if(typeof n=="object"&&n!==null){let r=n.code;if(typeof r=="string")return r}}function yYe(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function qx(t,e){if(e?.aborted)return new ln(0,"request_aborted","request aborted by caller signal");if(t instanceof ln)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new ln(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new ln(0,"request_aborted","request aborted by caller signal");let n=ffe(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new ln(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new ln(504,"request_timeout",`crtrd request timed out: ${r}`):new ln(503,"transport_error",r)}function fbn(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function mfe(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new ln(0,"request_aborted","request aborted by caller signal");let s=i!==void 0&&n!==void 0?n*1e3:void 0,a=Math.max(t,s??0);if(i!==void 0&&Date.now()+a>=i){let c=rR(i,s!==void 0&&s>=t?"retry_after":"elapsed",s===void 0?void 0:n);throw r!==void 0&&Object.defineProperty(c,"cause",{value:r,configurable:!0,writable:!0}),c}if(o===void 0)return xYe(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new ln(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function mbn(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function xYe(t){return new Promise(e=>setTimeout(e,t))}function gbn(t){if(t!==void 0)try{return t()}catch{return}}var xbn=".crouter",wbn="api.sock",bbn=Symbol.for("@north-light/api/local-socket-fetch");function Ebn(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:gfe(ybn(),xbn);return gfe(process.platform==="linux"?"/run/crtr":gfe(n,"runtime"),wbn)}function vbn(t){let e=function(n,r={}){let i=n instanceof URL?n:new URL(typeof n=="string"?n:n.url),o=r.method??"GET",s={};if(r.headers!==void 0)for(let[c,u]of new Headers(r.headers).entries())s[c]=u;let a=typeof r.body=="string"?r.body:void 0;return a!==void 0&&(s["content-length"]=String(Buffer.byteLength(a))),new Promise((c,u)=>{let l=Abn({socketPath:t,path:i.pathname+i.search,method:o,headers:s},h=>{let f=new ReadableStream({start(y){h.on("data",w=>y.enqueue(new Uint8Array(w))),h.on("end",()=>y.close()),h.on("error",w=>y.error(w))},cancel(){h.destroy()}}),m=new Headers;for(let[y,w]of Object.entries(h.headers))if(w!==void 0)for(let E of Array.isArray(w)?w:[w])m.append(y,E);let g=h.statusCode??0;c(new Response(g===204?null:f,{status:g,statusText:h.statusMessage,headers:m}))});l.on("error",h=>u(new TypeError("fetch failed",{cause:h})));let d=r.signal,p=()=>{l.destroy(),u(d?.reason??new DOMException("The operation was aborted.","AbortError"))};if(d!=null){if(d.aborted){p();return}d.addEventListener("abort",p,{once:!0})}a!==void 0&&l.write(a),l.end()})};return e[bbn]=!0,e}function _y(t={}){let{socketPath:e,...n}=t;return new x$({baseUrl:"http://localhost",fetch:vbn(e??Ebn()),autostart:!0,...n})}var Od=zt(Ame(),1),Tdi=Od.default.Client,Rdi=Od.default.Pool,Mdi=Od.default.Connection,Pdi=Od.default.types,Ddi=Od.default.Query,Bdi=Od.default.DatabaseError,Ldi=Od.default.escapeIdentifier,Odi=Od.default.escapeLiteral,Ndi=Od.default.Result,$di=Od.default.TypeOverrides,Fdi=Od.default.defaults,lXe=Od.default;var wme=class{dirty=new Map;subscribers=new Set;scheduled;async subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}markMail(e){this.mark(e,1)}markNode(e){this.mark(e,2)}mark(e,n){this.dirty.set(e,(this.dirty.get(e)??0)|n),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty];this.dirty.clear();for(let[n,r]of e)for(let i of this.subscribers)try{r&1&&i(n,"mail"),r&2&&i(n,"node")}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;async connectListener(){let e=new lXe.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`});e.on("notification",i=>{let o=i.payload??"",s=o.indexOf(":");if(s<0)return;let a=o.slice(0,s),c=o.slice(s+1);a==="mail"?this.markMail(c):a==="node"&&this.markNode(c)});let n=()=>{this.listener===e&&(this.listener=void 0,e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),this.url!==void 0&&(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.connectListener().catch(()=>r())},1e3)))},r=()=>{this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.connectListener().catch(()=>r())},1e3))};e.on("error",n),e.on("end",n),await e.connect(),await e.query("LISTEN crtr_signal"),this.listener=e}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0;let e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.end().catch(()=>{}))}},Wdi=new wme;var VSn="crtr-context",KSn="crtr-situational-context",YSn="crtr-context-nudge",JSn="crtr-review-boundary";var dXe="Provider credentials were just updated (a new login landed). Your previous turn stopped on a provider authentication failure. Continue from where you left off and retry the work that failed.",pXe="The network connection is back online. Your previous turn stopped on a connection error (the network was down). Continue from where you left off and retry the work that failed.",hXe="Your previous turn stopped on a connection error reaching the model provider. Retrying now: continue from where you left off and retry the work that failed.",fXe="Your previous turn stopped on a provider fault. Continue from where you left off and retry the work that failed.";function XSn(t){switch(t){case YSn:return"context-nudge";case VSn:return"bearings";case JSn:return"review-boundary";case KSn:return"situational";default:return}}var gz=/\s+([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy;function Eme(t){return t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"})[e])}function bme(t){let e={};gz.lastIndex=0;let n=0;for(;n<t.length&&!/^\s*$/.test(t.slice(n));){gz.lastIndex=n;let r=gz.exec(t);if(r===null)return null;let[,i,o,s]=r;if(i===void 0||Object.hasOwn(e,i))return null;e[i]=Eme(o??s??""),n=gz.lastIndex}return e}function vme(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):""}function ZSn(t){let e=[],n=/<from\b([^>]*)>([\s\S]*?)<\/from>/g;for(let r of t.matchAll(n)){let i=bme(r[1]??"");if(i?.id===void 0)continue;let o=[],s=r[2]??"",a=/<entry\b([^>]*)>([\s\S]*?)<\/entry>/g;for(let u of s.matchAll(a)){let l=bme(u[1]??"");if(l?.kind===void 0)continue;let d=l.disposition==="human-answer"||l.disposition==="human-canceled"?l.disposition:"report";o.push({kind:l.kind,disposition:d,body:Eme(u[2]??""),...l.ref===void 0?{}:{ref:l.ref}})}let c=i.updates===void 0?Number.NaN:Number(i.updates);e.push({id:i.id,updates:Number.isFinite(c)?c:o.length,finished:i.finished==="true"||o.some(u=>u.kind==="final"),entries:o})}return e}function e_n(t,e,n,r){return{kind:t,facts:e,body:n,senders:r}}function mXe(t){let e=/^<runtime\b([^>]*)>/.exec(t);if(e===null||!t.endsWith("</runtime>"))return null;let n=bme(e[1]??"");if(n?.kind===void 0)return null;let r=t.slice(e[0].length,-10),{kind:i,...o}=n,s=Object.freeze(o),a=i.includes(":")?Eme(r):r;return e_n(i,s,a,i==="inbox"?ZSn(a):[])}function dR(t){let e=vme(t),n=mXe(e);if(n!==null)return n;if(t.role!=="custom")return null;let r=XSn(t.customType);return r===void 0?null:{kind:r,facts:Object.freeze({}),body:e,senders:[]}}function xS(t){return t.disposition==="human-answer"&&mXe(t.body.trim())===null}function Sme(){return _y({autostart:!1})}function gXe(t,e){return Sme().appendNodeLog(t,{record:e,expected_execution_id:t_n()})}function t_n(){let t=g3();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return t}function AXe(t,e){return Sme().recordNodeFault(t,e)}function yXe(t,e={}){return Sme().clearNodeFault(t,{...e.link===void 0?{}:{link:e.link},...e.preserveEpisode===void 0?{}:{preserve_episode:e.preserveEpisode}}).then(n=>n.cleared)}var xXe=Promise.resolve();function n_n(t,e){xXe=xXe.then(async()=>{try{let{appended:n}=await gXe(t,e);n||process.stderr.write(`[broker] log.jsonl refused record: ${e}
1494
1494
  `)}catch(n){process.stderr.write(`[broker] log.jsonl append failed (${n instanceof Error?n.message:String(n)}): ${e}
@@ -1623,9 +1623,9 @@ ${i}`}function Kun(t,e,n){return t.children.filter(i=>Ix(i)&&i.tag==="li").map((
1623
1623
  `)}done(){return this.buffers.join("").replace(/\n{3,}/g,`
1624
1624
 
1625
1625
  `).replace(/[ \t]+\n/g,`
1626
- `).trim()}};function hN(t){let e=new Qze,n=[],r=[],i=[],o=0,s=!1,a=!1,c=0,u=()=>" ".repeat(Math.max(0,n.length-1));for(let l of cKr(t)){if(l.kind==="text"){if(i.length>0)continue;if(o>0){e.write(l.text);continue}let m=Jun(l.text).replace(/\s+/g," ");if(m.trim()===""){/\s/.test(m)&&e.write(" ");continue}e.write(Yun(m));continue}let{name:d,closing:p,attrs:h}=l;if(tKr.has(d)){if(p){let m=i.lastIndexOf(d);m>=0&&(i.length=m)}else l.selfClosing||i.push(d);continue}if(i.length>0)continue;let f=/^h([1-6])$/.exec(d);if(f!==null){e.block(),p||e.write(`${"#".repeat(Number(f[1]))} `);continue}if(d==="pre"){p?(o=Math.max(0,o-1),e.line(),e.write("```"),e.block()):(e.block(),e.write("```\n"),o++);continue}if(d==="br"){e.line();continue}if(d==="hr"){e.block(),e.write("---"),e.block();continue}if(d==="ul"||d==="ol"){p?n.pop():(e.block(),n.push({ordered:d==="ol",index:0})),p&&e.block();continue}if(d==="li"){if(p)continue;let m=n[n.length-1];e.line(),m===void 0?e.write("- "):(m.index++,e.write(`${u()}${m.ordered?`${m.index}. `:"- "}`));continue}if(d==="dt"||d==="dd"){e.line(),p||e.write(d==="dt"?"":" ");continue}if(d==="tr"){p?(e.write(c>0?" |":""),a&&c>0&&(e.line(),e.write(`|${" --- |".repeat(c)}`)),e.line()):(e.line(),a=!1,c=0);continue}if(d==="td"||d==="th"){if(p){if(!s)continue;s=!1,e.write(e.pop().replace(/\s+/g," ").trim())}else d==="th"&&(a=!0),c++,e.write(c===1?"| ":" | "),e.push(),s=!0;continue}if(d==="a"){if(p){if(r.length===0)continue;let y=r.pop();if(y===null)continue;let w=e.pop().replace(/\s+/g," ").trim();w!==""&&e.write(`[${w}](${y})`);continue}let m=h.get("href"),g=m!==void 0&&m!==""&&!m.startsWith("#");r.push(g?m:null),g&&e.push();continue}if(d==="code"&&o===0){e.write("`");continue}if(d==="strong"||d==="b"){e.write("**");continue}if(d==="em"||d==="i"){e.write("*");continue}if(d==="img"){let m=h.get("alt");m!==void 0&&m!==""&&e.write(Yun(m));continue}if(d==="blockquote"){e.block(),p||e.write("> ");continue}if(nKr.has(d)&&!rKr.has(d)){e.block();continue}}return e.done()}import{closeSync as _Yr,existsSync as CYr,fstatSync as IYr,openSync as kYr,readFileSync as vln,readSync as TYr}from"node:fs";import{dirname as RYr,join as Xze}from"node:path";import{gunzipSync as MYr}from"node:zlib";var VTs=256*1024;var hf=class extends Lp{payload;constructor(e,n=Mu.USAGE){super(e.error,e.message,n,{...e}),this.name="InputError",this.payload=e}};function uKr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var lKr={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable"};function Wze(t,e,n={}){if(t.code==="daemon_restarting")return new Lp("daemon_restarting",t.message,Mu.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(t.code==="layout_migration_required")return new Lp("layout_migration_required",t.message,Mu.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(t.code==="daemon_unavailable")return new Lp("daemon_unavailable",t.message,Mu.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});let r=t.details,i=dKr(t,r,n.providerCall===!0);if(t.status===503||n.providerCall===!0&&t.status===504&&i.code!==void 0){let a=i.code??t.code,c={next:i.next??e??"Retry the command; if it persists, inspect the unavailable service named in the error."};return i.details!==void 0&&(c.details=i.details),i.code!==void 0&&(i.field!==void 0&&(c.field=i.field),i.received!==void 0&&(c.received=i.received),i.retryAfterS!==void 0&&(c.retry_after_s=i.retryAfterS)),new Lp(a,t.message,Mu.NETWORK,c)}let o=Array.isArray(r?.violations)?r.violations.map(a=>`${String(a.field)} ${String(a.problem)}${a.received!==void 0?` (received ${JSON.stringify(a.received)})`:""}`):[],s=r&&typeof r.error=="string"&&typeof r.message=="string"&&typeof r.next=="string"?r:{error:i.code??lKr[t.status]??t.code,...i.field!==void 0?{field:i.field}:{},...i.received!==void 0?{received:i.received}:{},...i.retryAfterS!==void 0?{retry_after_s:i.retryAfterS}:{},...i.details!==void 0?{details:i.details}:{},message:o.length>0?`${t.message}: ${o.join("; ")}`:t.message.trim()!==""?t.message:`request refused (HTTP ${t.status}, ${t.code}) with no message`,next:i.next??e??(i.retryAfterS!==void 0?`Wait ${i.retryAfterS}s, then retry; do not retry sooner.`:t.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":t.status===404?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new hf(s,pKr(s.error,t.status))}function dKr(t,e,n){let r=o=>typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o);if(n&&t.origin!==void 0&&t.origin!=="provider"&&r(t.code)){let o={code:t.code};return(t.status===503||t.status===504)&&(o.next=t.retryable===!0?"Retry the command; if it persists, the machine or service named in the error is unavailable.":"Read the error before retrying: the action may already have run."),uKr(t.details)&&(o.details=t.details),t.param!==void 0&&(o.field=t.param),typeof t.retryAfterS=="number"&&(o.retryAfterS=t.retryAfterS),o}if(t.origin!=="provider"||e===void 0||e===null||typeof e!="object")return{};let i={};return typeof e.status=="number"&&r(e.code)&&(i.code=e.code),typeof e.next=="string"&&e.next.trim()!==""&&(i.next=e.next),typeof e.field=="string"&&e.field!==""?i.field=e.field:t.param!==void 0&&(i.field=t.param),e.received!==void 0&&e.received!==null&&(i.received=e.received),typeof t.retryAfterS=="number"&&(i.retryAfterS=t.retryAfterS),i}function pKr(t,e){return t==="not_found"||e===404?Mu.NOT_FOUND:t==="ambiguous"?Mu.AMBIGUOUS:Mu.USAGE}import{spawn as jKr,execFileSync as xRs}from"node:child_process";import{createRequire as zKr}from"node:module";import{dirname as Gze,join as gN}from"node:path";import{fileURLToPath as VKr,pathToFileURL as jze}from"node:url";import{existsSync as hln,lstatSync as KKr,mkdirSync as YKr,openSync as fln,closeSync as mln,fstatSync as gln,readSync as JKr}from"node:fs";import{copyFileSync as hKr,mkdirSync as Mle,existsSync as Rle,readFileSync as fKr,writeFileSync as eln,chmodSync as mKr,readdirSync as gKr,renameSync as xT,realpathSync as ij,unlinkSync as AKr,rmSync as yKr,linkSync as Xun}from"node:fs";import{homedir as tln}from"node:os";import{dirname as nln,join as us}from"node:path";import{execFile as xKr,spawn as wKr,spawnSync as Dle}from"node:child_process";var Ble="crouter";function mN(){return us(tln(),sS,"host")}function rln(){return us(mN(),Ble)}function qze(){return us(mN(),".source.json")}function bKr(t){let e=nln(t);for(let n of[e,us(e,"..","lib")]){if(!Rle(n))continue;let r=gKr(n).find(i=>i.startsWith("libnode.")&&i.endsWith(".dylib"));if(r!==void 0)return us(n,r)}return null}function Zun(t,e,n){let r=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;hKr(t,r),n!==void 0&&mKr(r,n),xT(r,e)}function Hze(t=qze()){try{return JSON.parse(fKr(t,"utf8"))}catch{return null}}var EKr=3e4;function vKr(t){let e=us(tln(),sS),n=us(e,"host.lock");return Mle(e,{recursive:!0}),Kc(n,t,{timeoutMs:EKr,timeoutError:()=>new Error(`timed out waiting for branded host lock: ${n}`)})}function SKr(t={}){let e=t.configured?.trim();return e?[e]:[t.discovered?.trim()||"-"]}function _Kr(){if(process.platform!=="darwin")return null;let t=Dle("security",["find-identity","-v","-p","codesigning"],{stdio:["pipe","pipe","pipe"]});if(t.status!==0)return null;let n=(t.stdout??"").toString().split(`
1626
+ `).trim()}};function hN(t){let e=new Qze,n=[],r=[],i=[],o=0,s=!1,a=!1,c=0,u=()=>" ".repeat(Math.max(0,n.length-1));for(let l of cKr(t)){if(l.kind==="text"){if(i.length>0)continue;if(o>0){e.write(l.text);continue}let m=Jun(l.text).replace(/\s+/g," ");if(m.trim()===""){/\s/.test(m)&&e.write(" ");continue}e.write(Yun(m));continue}let{name:d,closing:p,attrs:h}=l;if(tKr.has(d)){if(p){let m=i.lastIndexOf(d);m>=0&&(i.length=m)}else l.selfClosing||i.push(d);continue}if(i.length>0)continue;let f=/^h([1-6])$/.exec(d);if(f!==null){e.block(),p||e.write(`${"#".repeat(Number(f[1]))} `);continue}if(d==="pre"){p?(o=Math.max(0,o-1),e.line(),e.write("```"),e.block()):(e.block(),e.write("```\n"),o++);continue}if(d==="br"){e.line();continue}if(d==="hr"){e.block(),e.write("---"),e.block();continue}if(d==="ul"||d==="ol"){p?n.pop():(e.block(),n.push({ordered:d==="ol",index:0})),p&&e.block();continue}if(d==="li"){if(p)continue;let m=n[n.length-1];e.line(),m===void 0?e.write("- "):(m.index++,e.write(`${u()}${m.ordered?`${m.index}. `:"- "}`));continue}if(d==="dt"||d==="dd"){e.line(),p||e.write(d==="dt"?"":" ");continue}if(d==="tr"){p?(e.write(c>0?" |":""),a&&c>0&&(e.line(),e.write(`|${" --- |".repeat(c)}`)),e.line()):(e.line(),a=!1,c=0);continue}if(d==="td"||d==="th"){if(p){if(!s)continue;s=!1,e.write(e.pop().replace(/\s+/g," ").trim())}else d==="th"&&(a=!0),c++,e.write(c===1?"| ":" | "),e.push(),s=!0;continue}if(d==="a"){if(p){if(r.length===0)continue;let y=r.pop();if(y===null)continue;let w=e.pop().replace(/\s+/g," ").trim();w!==""&&e.write(`[${w}](${y})`);continue}let m=h.get("href"),g=m!==void 0&&m!==""&&!m.startsWith("#");r.push(g?m:null),g&&e.push();continue}if(d==="code"&&o===0){e.write("`");continue}if(d==="strong"||d==="b"){e.write("**");continue}if(d==="em"||d==="i"){e.write("*");continue}if(d==="img"){let m=h.get("alt");m!==void 0&&m!==""&&e.write(Yun(m));continue}if(d==="blockquote"){e.block(),p||e.write("> ");continue}if(nKr.has(d)&&!rKr.has(d)){e.block();continue}}return e.done()}import{closeSync as _Yr,existsSync as CYr,fstatSync as IYr,openSync as kYr,readFileSync as vln,readSync as TYr}from"node:fs";import{dirname as RYr,join as Xze}from"node:path";import{gunzipSync as MYr}from"node:zlib";var YTs=256*1024;var hf=class extends Lp{payload;constructor(e,n=Mu.USAGE){super(e.error,e.message,n,{...e}),this.name="InputError",this.payload=e}};function uKr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var lKr={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable"};function Wze(t,e,n={}){if(t.code==="daemon_restarting")return new Lp("daemon_restarting",t.message,Mu.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(t.code==="layout_migration_required")return new Lp("layout_migration_required",t.message,Mu.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(t.code==="daemon_unavailable")return new Lp("daemon_unavailable",t.message,Mu.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});let r=t.details,i=dKr(t,r,n.providerCall===!0);if(t.status===503||n.providerCall===!0&&t.status===504&&i.code!==void 0){let a=i.code??t.code,c={next:i.next??e??"Retry the command; if it persists, inspect the unavailable service named in the error."};return i.details!==void 0&&(c.details=i.details),i.code!==void 0&&(i.field!==void 0&&(c.field=i.field),i.received!==void 0&&(c.received=i.received),i.retryAfterS!==void 0&&(c.retry_after_s=i.retryAfterS)),new Lp(a,t.message,Mu.NETWORK,c)}let o=Array.isArray(r?.violations)?r.violations.map(a=>`${String(a.field)} ${String(a.problem)}${a.received!==void 0?` (received ${JSON.stringify(a.received)})`:""}`):[],s=r&&typeof r.error=="string"&&typeof r.message=="string"&&typeof r.next=="string"?r:{error:i.code??lKr[t.status]??t.code,...i.field!==void 0?{field:i.field}:{},...i.received!==void 0?{received:i.received}:{},...i.retryAfterS!==void 0?{retry_after_s:i.retryAfterS}:{},...i.details!==void 0?{details:i.details}:{},message:o.length>0?`${t.message}: ${o.join("; ")}`:t.message.trim()!==""?t.message:`request refused (HTTP ${t.status}, ${t.code}) with no message`,next:i.next??e??(i.retryAfterS!==void 0?`Wait ${i.retryAfterS}s, then retry; do not retry sooner.`:t.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":t.status===404?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new hf(s,pKr(s.error,t.status))}function dKr(t,e,n){let r=o=>typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o);if(n&&t.origin!==void 0&&t.origin!=="provider"&&r(t.code)){let o={code:t.code};return(t.status===503||t.status===504)&&(o.next=t.retryable===!0?"Retry the command; if it persists, the machine or service named in the error is unavailable.":"Read the error before retrying: the action may already have run."),uKr(t.details)&&(o.details=t.details),t.param!==void 0&&(o.field=t.param),typeof t.retryAfterS=="number"&&(o.retryAfterS=t.retryAfterS),o}if(t.origin!=="provider"||e===void 0||e===null||typeof e!="object")return{};let i={};return typeof e.status=="number"&&r(e.code)&&(i.code=e.code),typeof e.next=="string"&&e.next.trim()!==""&&(i.next=e.next),typeof e.field=="string"&&e.field!==""?i.field=e.field:t.param!==void 0&&(i.field=t.param),e.received!==void 0&&e.received!==null&&(i.received=e.received),typeof t.retryAfterS=="number"&&(i.retryAfterS=t.retryAfterS),i}function pKr(t,e){return t==="not_found"||e===404?Mu.NOT_FOUND:t==="ambiguous"?Mu.AMBIGUOUS:Mu.USAGE}import{spawn as jKr,execFileSync as bRs}from"node:child_process";import{createRequire as zKr}from"node:module";import{dirname as Gze,join as gN}from"node:path";import{fileURLToPath as VKr,pathToFileURL as jze}from"node:url";import{existsSync as hln,lstatSync as KKr,mkdirSync as YKr,openSync as fln,closeSync as mln,fstatSync as gln,readSync as JKr}from"node:fs";import{copyFileSync as hKr,mkdirSync as Mle,existsSync as Rle,readFileSync as fKr,writeFileSync as eln,chmodSync as mKr,readdirSync as gKr,renameSync as xT,realpathSync as ij,unlinkSync as AKr,rmSync as yKr,linkSync as Xun}from"node:fs";import{homedir as tln}from"node:os";import{dirname as nln,join as us}from"node:path";import{execFile as xKr,spawn as wKr,spawnSync as Dle}from"node:child_process";var Ble="crouter";function mN(){return us(tln(),sS,"host")}function rln(){return us(mN(),Ble)}function qze(){return us(mN(),".source.json")}function bKr(t){let e=nln(t);for(let n of[e,us(e,"..","lib")]){if(!Rle(n))continue;let r=gKr(n).find(i=>i.startsWith("libnode.")&&i.endsWith(".dylib"));if(r!==void 0)return us(n,r)}return null}function Zun(t,e,n){let r=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;hKr(t,r),n!==void 0&&mKr(r,n),xT(r,e)}function Hze(t=qze()){try{return JSON.parse(fKr(t,"utf8"))}catch{return null}}var EKr=3e4;function vKr(t){let e=us(tln(),sS),n=us(e,"host.lock");return Mle(e,{recursive:!0}),Kc(n,t,{timeoutMs:EKr,timeoutError:()=>new Error(`timed out waiting for branded host lock: ${n}`)})}function SKr(t={}){let e=t.configured?.trim();return e?[e]:[t.discovered?.trim()||"-"]}function _Kr(){if(process.platform!=="darwin")return null;let t=Dle("security",["find-identity","-v","-p","codesigning"],{stdio:["pipe","pipe","pipe"]});if(t.status!==0)return null;let n=(t.stdout??"").toString().split(`
1627
1627
  `).map(r=>r.match(/\)\s+[A-Fa-f0-9]{40}\s+"([^"]+)"/)?.[1]??null).filter(r=>r!==null);return n.find(r=>r.startsWith("Apple Development:"))??n.find(r=>r.startsWith("Developer ID Application:"))??n[0]??null}function CKr(t,e){let n=Dle("codesign",["-s",e,"--deep","--force",t],{stdio:["pipe","pipe","pipe"]});return{ok:n.status===0,stderr:(n.stderr??"").toString().trim()}}function IKr(t){if(process.platform!=="darwin")return;let e=SKr({configured:process.env.CRTR_CODESIGN_IDENTITY,discovered:_Kr()}),n="";for(let r of e){let i=CKr(t,r);if(i.ok)return;n=i.stderr}throw n&&!n.includes("valid on disk")&&Cf({event:"host.codesign.failed",level:"debug",error:n}),new Error(`codesign failed for ${t}: ${n||"codesign did not exit successfully"}`)}function kKr(t,e,n=IKr){e!==null&&n(e),n(t)}function fN(t,e=5e3){try{return Dle(t,["-e",""],{stdio:"ignore",timeout:e}).status===0}catch{return!1}}function TKr(t={}){return vKr(()=>{let e=mN(),n=rln(),r=ij(t.execPath??process.execPath);if(Rle(n)&&ij(n)===r){if(fN(n))return n;let h=DKr();if(h===null)throw new Error(`branded host cannot start and no working node was found to rebuild it from: ${n}`);r=h}let i=Hze(),o=bKr(r),s=o!==null?o.split("/").pop():null,a=h=>Rle(n)&&h!==null&&h.version===2&&(h.libnode===null||Rle(us(e,h.libnode))),c=h=>a(h)&&h.source===r&&h.libnode===s;if(c(i)&&fN(n))return n;Mle(e,{recursive:!0});let u=us(e,`.reconcile.${process.pid}.${Math.random().toString(36).slice(2)}`),l=us(u,"previous");Mle(u);let d=!1,p=a(i)&&fN(n);try{let h=us(u,Ble),f=s!==null?us(u,s):null;if(o!==null&&f!==null&&Zun(o,f),Zun(r,h,493),kKr(h,f),!fN(h))throw new Error(`rebuilt branded host failed its startup check: ${h}`);if(p&&MKr(l,n,i),d=!0,f!==null&&xT(f,us(e,s)),xT(h,n),RKr({version:2,source:r,libnode:s}),!c(Hze())||!fN(n))throw new Error(`published branded host tuple failed validation: ${n}`);if(i?.libnode!=null&&i.libnode!==s)try{AKr(us(e,i.libnode))}catch{}return n}catch(h){throw d&&p&&PKr(l,n,i),h}finally{yKr(u,{recursive:!0,force:!0})}})}function RKr(t){let e=qze(),n=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;eln(n,JSON.stringify(t)),xT(n,e)}function MKr(t,e,n){Mle(t),Xun(e,us(t,Ble)),n.libnode!==null&&Xun(us(mN(),n.libnode),us(t,n.libnode)),eln(us(t,".source.json"),JSON.stringify(n))}function PKr(t,e,n){if(n.libnode!==null&&xT(us(t,n.libnode),us(mN(),n.libnode)),xT(us(t,Ble),e),xT(us(t,".source.json"),qze()),!fN(e))throw new Error(`failed to restore previous branded host tuple: ${e}`)}function Ple(t){try{let e=ij(mN());return nln(ij(t))===e}catch{return!1}}function iln(){let t=["/opt/homebrew/bin/node","/usr/local/bin/node"];Ple(process.execPath)||t.push(process.execPath);for(let i of(process.env.PATH??"").split(":"))i!==""&&t.push(us(i,"node"));let e=Hze();e!==null&&typeof e.source=="string"&&t.push(e.source);let n=new Set,r=[];for(let i of t){let o;try{o=ij(i)}catch{continue}n.has(o)||Ple(o)||(n.add(o),r.push(o))}return r}var oln=["-p","process.versions.modules"];function sln(t){return t!==null&&t.trim()===process.versions.modules}function DKr(){for(let t of iln())try{let e=Dle(t,oln,{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]});if(e.status===0&&sln(e.stdout))return t}catch{}return null}function aln(t,e,n){return new Promise(r=>{try{xKr(t,e,{encoding:"utf8",timeout:n},(i,o)=>r(i===null?o:null))}catch{r(null)}})}async function BKr(){for(let t of iln())if(sln(await aln(t,oln,5e3)))return t;return null}var LKr=15e3,OKr=6e4,Cd={checkedAt:0,fallback:null,probing:null,lastHealAt:0};function NKr(t){if(import.meta.url.endsWith(".ts"))return;let e=Date.now();if(!(e-Cd.lastHealAt<OKr)){Cd.lastHealAt=e;try{let n=`import(${JSON.stringify(import.meta.url)}).then((m) => m.ensureBrandedHost())`,r=wKr(t,["--input-type=module","-e",n],{detached:!0,stdio:"ignore"});r.on("error",()=>{}),r.unref()}catch{}}}function $Kr(t){return Cd.probing!==null||(Cd.probing=(async()=>{try{if(await aln(t,["-e",""],5e3)!==null){Cd.fallback=null;return}let e=await BKr();e!==Cd.fallback&&e!==null&&Cf({event:"host.fallback.node",level:"warn",fields:{host:t,node:e}}),Cd.fallback=e,e!==null&&NKr(e)}finally{Cd.checkedAt=Date.now(),Cd.probing=null}})()),Cd.probing}function FKr(t=process.execPath){return Ple(t)?(Date.now()-Cd.checkedAt>LKr&&Cd.probing===null&&$Kr(t),Cd.fallback??t):t}function cln(){if(process.env.CRTR_BRANDED_HOST==="0"||process.platform!=="darwin"||import.meta.url.endsWith(".ts"))return process.execPath;if(Ple(process.execPath))return FKr();try{return TKr()}catch(t){return Cf({event:"host.fallback.node",level:"warn",error:t,fields:{host:rln(),node:process.execPath}}),process.execPath}}import{existsSync as UKr,readFileSync as QKr}from"node:fs";import{join as WKr}from"node:path";function HKr(){return Z7e()??WKr(Na(),"crtrd.pid")}function wT(){let t=HKr();if(!UKr(t))return null;let e=QKr(t,"utf8").trim(),n=Number(e);return Number.isFinite(n)&&n>0?n:null}function uln(){let t=wT();return t!==null&&Rf(t)}import{join as qKr}from"node:path";function GKr(){return qKr(Na(),"join.lock")}function Lle(){let t=yR(GKr());return t!==null&&Rf(t)?t:null}function lln(){return Lle()!==null}function dln(t){return new hf({error:"join_in_progress",message:t===null?"`crtr sys join` is running and holds the daemon down until it finishes":`\`crtr sys join\` (pid ${t}) is running and holds the daemon down until it finishes`,next:"Wait for the join to finish; it starts the daemon again itself. If it is stuck, `crtr sys daemon start --force`."})}async function pln(t,e=100){let n=Date.now()+t;for(;;){let r=Lle();if(r===null||r===process.pid||Date.now()>=n)return;await new Promise(i=>setTimeout(i,e))}}var XKr=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function ZKr(){let t={...process.env};for(let e of XKr)delete t[e];return t}function eYr(){for(let t=Gze(VKr(import.meta.url));;t=Gze(t)){if(hln(gN(t,"bin","runtime-generation-manifest.mjs")))return t;if(Gze(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}async function tYr(){let t=eYr(),e=jze(gN(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:n}=await import(e);try{KKr(gN(n(),"selected"))}catch(s){if(s.code!=="ENOENT")throw s;return["--conditions","crtr-src","--import",jze(zKr(import.meta.url).resolve("tsx/esm")).href,gN(t,"src","daemon","crtrd-cli.ts")]}let r=jze(gN(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:i}=await import(r),o=i("daemon");if(!o.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${o.error}`);return[o.runtime.entryPath]}var nYr=3*6e4,Aln=2e4,Kze=10,Vze=1e3;async function Yze(t=Vze){let e=Math.min(t,Vze);return _y({autostart:!1,timeoutMs:e}).probeHealthz(e)}function rYr(t){let e=t instanceof Error?t.message:String(t);if(typeof t!="object"||t===null)return e;let n=t.code,r=t.cause,i=typeof n=="string"?n:r?.code;return typeof i=="string"&&!e.includes(i)?`${e}: ${i}`:e}async function iYr(t=Vze){let e=await Yze(t);if(e.startup_phase==="blocked"){let n=wT()??process.pid;throw new AN(n,e.startup_blocked??"daemon startup is blocked")}if(!e.ok)throw new Error(e.startup_blocked??"crtrd health check reported not ready")}function Jze(t){return new Promise(e=>{setTimeout(e,t)})}var sj=class extends Error{stderrTail;constructor(e,n){super(n===""?e:`${e}
1628
- ${n}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=n}},AN=class extends Error{constructor(e,n){super(`daemon ${e} is running but normal startup is blocked: ${n}`),this.name="DaemonStartupBlockedError"}},aj=class extends Error{constructor(e,n){super(n===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${n}, not prepared`),this.name="DaemonNotPreparedError"}};async function oYr(t,e=3e5,n={},r="ready"){let i=n.readPidfile??wT,o=n.isPidAlive??Rf,s=n.childExited,a=n.isDaemonServing,c=n.probeDaemonServing??(async f=>{if(a!==void 0){if(await a())return;throw new Error("crtrd health check reported not ready")}await iYr(f)}),u=n.probeDaemonHealth??Yze,l=n.sleepMs??Jze,d=n.now??Date.now,p=null,h=null;return await X3({windowMs:e,pollIntervalMs:Kze,now:d,sleep:l,retry:f=>f!==h,probe:async f=>{let m=i();if(m===null||!o(m)){let y=s?.();throw y!=null&&(y.signal!==null?h=new sj(`daemon ${t} exited before becoming ready (by ${y.signal})`,n.childStderrTail?.()??""):y.code!==0&&(h=new sj(`daemon ${t} exited before becoming ready (with exit code ${y.code??"?"})`,n.childStderrTail?.()??"")),h!==null)?h:new Error(`daemon ${t} has no live pidfile owner`)}if(r==="ready"){try{await c(f)}catch(y){throw y instanceof AN&&(h=y),y}p=m;return}let g=await u(f);if(g.startup_phase==="prepared"){p=m;return}throw g.startup_phase==="blocked"?(h=new AN(m,g.startup_blocked??"on-disk migration is blocked"),h):g.startup_phase==="ready"?(h=new aj(m,g.startup_phase),h):new Error(`daemon ${m} is ${g.startup_phase??"not reporting a startup phase"}; waiting for prepared`)}}),p===t?null:p}async function sYr(t,e=Aln,n={}){let r=n.readPidfile??wT,i=n.isPidAlive??Rf,o=n.sleepMs??Jze,s=n.now??Date.now,a=s()+e;for(;s()<=a;){if(!i(t)&&r()!==t)return;await o(Kze)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}var aYr=2e3,cYr=5e3;async function uYr(t,e=Aln,n={}){let r=n.isPidAlive??Rf,i=n.sleepMs??Jze,o=n.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await sYr(t,e,n),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}let s=o()+aYr;for(;o()<=s;){if(!r(t))return"killed";await i(Kze)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}function lYr(t,e,n=2048){let r;try{r=fln(t,"r");let{size:i}=gln(r),o=Math.max(e,i-n),s=i-o;if(s<=0)return"";let a=Buffer.alloc(s);return JKr(r,a,0,s,o),a.toString("utf8").trim()}catch{return""}finally{if(r!==void 0)try{mln(r)}catch{}}}async function dYr(t={}){if(process.platform==="linux"&&hln("/run/crtr/launcher.sock")&&!Rf(wT()??-1))throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");let e=t.targetPhase??"ready",n=wT();if(n!==null&&Rf(n))try{let p=await Yze();if(e==="prepared"){if(p.startup_phase==="prepared")return{started:!1,existing_pid:n,startup_phase:p.startup_phase};throw new aj(n,p.startup_phase)}return p.ok?{started:!1,existing_pid:n,...p.startup_phase===void 0?{}:{startup_phase:p.startup_phase}}:{started:!1,existing_pid:n,running:!0,serving:!1,probe_error:p.startup_blocked??"crtrd health check reported not ready",...p.startup_phase===void 0?{}:{startup_phase:p.startup_phase}}}catch(p){if(p instanceof aj)throw p;return{started:!1,existing_pid:n,running:!0,serving:!1,probe_error:rYr(p)}}YKr(Na(),{recursive:!0});let r=await tYr();t.waitForJoinLock===!0&&await pln(nYr);let i=Lle();if(i!==null&&i!==process.pid&&t.ignoreJoinLock!==!0)throw dln(i);let o=gN(Na(),"crtrd.err"),s=fln(o,"a"),a=(()=>{try{return gln(s).size}catch{return 0}})();Y3()===void 0&&pYe();let c=jKr(cln(),[...r,"--canvas-home",Na(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:ZKr()});mln(s);let u=c.pid;if(u===void 0)throw new Error("daemon spawn did not return a pid");let l=null;c.once("exit",(p,h)=>{l={code:p,signal:h}}),c.unref();let d;try{d=await oYr(u,3e5,{childExited:()=>l,childStderrTail:()=>lYr(o,a)},e)}catch(p){let h=yR(sYe())===u;if(l===null&&!h&&!(p instanceof AN))try{await uYr(u,cYr)}catch{}throw p}return d!==null?{started:!1,existing_pid:d,startup_phase:e}:{started:!0,pid:u,startup_phase:e}}function $le(){return e9e()||process.argv.includes("--no-autostart")}var pYr=5e3,hYr=6e4,zze=!1,oj,Ole=0,Nle=0;function fYr(t){return Math.min(pYr*2**(t-1),hYr)}function mYr(){oj=void 0,Ole=0,Nle=0}function yln(){return oj}function xln(t={}){let e=t.isDaemonRunning??uln,n=t.spawnDaemon??dYr,r=t.now??Date.now;if(!$le()&&!lln()&&!zze&&!(r()<Nle)){if(e()){mYr();return}oj=void 0,zze=!0,n().then(()=>{oj=void 0,Ole=0,Nle=0},i=>{i instanceof sj&&(oj=i.message),Ole+=1,Nle=r()+fYr(Ole)}).finally(()=>{zze=!1})}}import{existsSync as gYr,readFileSync as AYr,statSync as $Rs}from"node:fs";import{join as yYr}from"node:path";var xYr="secrets.json";function wYr(t){return yYr(t===Yc()?Sy():t,xYr)}function bYr(t){let e=og(t);if(!e)return{relayTokens:{}};let n=wYr(e);if(!gYr(n))return{relayTokens:{}};try{let r=JSON.parse(AYr(n,"utf8")),i=Array.isArray(r.scopedApiTokens)?r.scopedApiTokens.filter(o=>typeof o?.token=="string"&&o.token!==""&&typeof o.grantee=="string"&&/^app:[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o.grantee)&&Array.isArray(o.scopes)&&typeof o.created=="string"):[];return{relayTokens:r.relayTokens??{},...typeof r.apiToken=="string"&&r.apiToken!==""?{apiToken:r.apiToken}:{},...i.length>0?{scopedApiTokens:i}:{}}}catch{return{relayTokens:{}}}}function wln(t,e){return bYr(e).relayTokens[t]}function Fle(t,e="user"){let n=zc(e),r=n.remoteCanvas.targets[t];if(r===void 0){let o=Object.keys(n.remoteCanvas.targets);throw lS(`no remote canvas target named '${t}'`+(o.length>0?` \u2014 configured: ${o.join(", ")}`:" \u2014 none configured yet")+`. Add one with \`crtr canvas config add ${t} --preview <url> --relay-token -\`.`)}let i=wln(r.relayTokenRef,e);if(i===void 0||i==="")throw lS(`target '${t}' has no stored relay token \u2014 add it with \`crtr canvas config add ${t} --relay-token -\`.`);return{previewEndpoint:r.previewEndpoint,relayToken:i}}function bln(t,e,n=5e3){let r=/^[\x20-\x7e]+$/.test(e);return async function(o,s){if(!r)return{ok:!1,stdout:"",stderr:"remote source: invalid stored relay token"};let a={kind:"exec",bin:o,args:s},c=new AbortController,u=setTimeout(()=>c.abort(),n),l;try{l=await fetch(new URL("/__crtr/source",t),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(a),signal:c.signal})}catch{return c.signal.aborted?{ok:!1,stdout:"",stderr:`remote source: timeout after ${n}ms`}:{ok:!1,stdout:"",stderr:"remote source: network error"}}finally{clearTimeout(u)}return l.ok?await l.json():{ok:!1,stdout:"",stderr:`remote source: HTTP ${l.status} ${l.statusText}`}}}var Ule=1e3;function bl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function EYr(t){if(!bl(t))return!1;let e=t.node;if(!bl(e)||typeof e.node_id!="string"||!Array.isArray(t.reports)||!Array.isArray(t.managers))return!1;let n=t.artifacts;if(!bl(n)||typeof n.report!="number"||typeof n.doc!="number"||typeof n.roadmap!="number"||typeof t.pending_crons!="number")return!1;let r=t.paths;if(!bl(r)||typeof r.context_dir!="string"||"session_file"in r&&r.session_file!==null&&typeof r.session_file!="string"||typeof t.follow_up!="string")return!1;let i=t.fault;if(i!=null){if(!bl(i)||typeof i.link!="string"||typeof i.kind!="string"||typeof i.since!="string")return!1;let o=i.retry;if(!bl(o)||typeof o.disposition!="string")return!1}return!0}function Eln(t){return bl(t)&&typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.status=="string"&&typeof t.active=="boolean"}function vYr(t){return bl(t)&&typeof t.from_id=="string"&&typeof t.to_id=="string"&&typeof t.active=="boolean"&&typeof t.created=="string"}function SYr(t){return bl(t)?typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.mode=="string"&&typeof t.lifecycle=="string"&&typeof t.status=="string"&&typeof t.cwd=="string"&&typeof t.created=="string":!1}var Nv=class{constructor(e,n){this.previewEndpoint=e;this.relayToken=n;this.exec=bln(e,n)}previewEndpoint;relayToken;exec;nodeCache=new Map;rosterCache=new Map;topologyCache=null;viewCache=new Map;async execJson(e){let n;try{n=await this.exec("crtr",["--json",...e])}catch{return null}if(!n.ok||n.exitCode!==void 0&&n.exitCode!==0)return null;try{return JSON.parse(n.stdout.trim())}catch{return null}}async fetchShow(e){let n=this.nodeCache.get(e);if(n&&Date.now()-n.at<Ule)return n.value;let r=await this.execJson(["node","inspect","show",e]),i=EYr(r)?{...r,fault:r.fault??null,reports:r.reports.filter(Eln),managers:r.managers.filter(Eln)}:null;return this.nodeCache.set(e,{value:i,at:Date.now()}),i}topology(){if(this.topologyCache!==null&&Date.now()-this.topologyCache.at<Ule)return this.topologyCache.value;let e=this.loadTopology();return this.topologyCache={value:e,at:Date.now()},e}async loadTopology(){let e=await this.exec("crtr",["--json","canvas","roster"]);if(!e.ok||e.exitCode!==void 0&&e.exitCode!==0)throw new Error("remote canvas topology is unavailable");let n;try{n=JSON.parse(e.stdout.trim())}catch{throw new Error("remote canvas topology is invalid")}if(!bl(n)||!Array.isArray(n.edges)||!n.edges.every(vYr))throw new Error("remote canvas topology is invalid");let r=n.edges,i={subscriptions:new Map,subscribers:new Map};for(let o of r){let s={node_id:o.to_id,active:o.active,created:o.created},a={node_id:o.from_id,active:o.active,created:o.created},c=i.subscriptions.get(o.from_id);c===void 0?i.subscriptions.set(o.from_id,[s]):c.push(s);let u=i.subscribers.get(o.to_id);u===void 0?i.subscribers.set(o.to_id,[a]):u.push(a)}return i}async rawShow(e){return this.fetchShow(e)}async getNode(e){return(await this.fetchShow(e))?.node??null}async getRow(e){let n=(await this.fetchShow(e))?.node;return n?{node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:n.host_kind??null,profile_id:n.profile_id??null,scopes:n.scopes??null,isolated:n.isolated===!0,parent:n.parent??null,created:n.created,intent:n.intent??null,frozen_at:n.frozen_at??null,terminal_reason:n.terminal_reason??null,pi_pid:n.pi_pid??null,pi_pid_identity:n.pi_pid_identity??null,window:n.window??null,tmux_session:n.tmux_session??null,pane:n.pane??null,fault:n.fault??null,streaming:n.streaming===!0}:null}async listNodes(e){let n=JSON.stringify([e?.status??null,e?.under??null]),r=this.rosterCache.get(n);if(r&&Date.now()-r.at<Ule)return r.value;let i=["node","inspect","list"];e?.status&&i.push("--status",(Array.isArray(e.status)?e.status:[e.status]).join(",")),e?.under&&i.push("--under",e.under);let o=await this.execJson(i),a=(bl(o)&&Array.isArray(o.nodes)?o.nodes:[]).filter(SYr).map(c=>({...c,isolated:c.isolated===!0}));return this.rosterCache.set(n,{value:a,at:Date.now()}),a}async subscriptionsOf(e){return(await this.topology()).subscriptions.get(e)??[]}async subscribersOf(e){return(await this.topology()).subscribers.get(e)??[]}async view(e){let n=this.viewCache.get(e);if(n&&Date.now()-n.at<Ule)return n.value;let r=new Set([e]),i=[],o=(await this.subscriptionsOf(e)).map(s=>s.node_id);for(;o.length>0;){let s=o.shift();if(!r.has(s)){r.add(s),i.push(s);for(let a of await this.subscriptionsOf(s))r.has(a.node_id)||o.push(a.node_id)}}return this.viewCache.set(e,{value:i,at:Date.now()}),i}async ticketCountsForNodes(e){if(e.length===0)return{};let n=await this.execJson(["canvas","attention","map","--nodes",e.join(",")]);return bl(n)&&bl(n.counts)?n.counts:{}}async ticketCountsForView(e){let n=await this.execJson(["canvas","attention","map","--view",e]);return bl(n)&&bl(n.counts)?n.counts:{}}async hasActiveLiveSubscription(e){let n=(await this.subscriptionsOf(e)).filter(r=>r.active);for(let r of n){let i=await this.getRow(r.node_id);if(i&&(i.status==="active"||i.status==="idle"))return!0}return!1}};function Qle(t){return{...t,fault:t.fault??null}}function Zze(t,e){throw t instanceof ln?Wze(t,e):t}var PYr=4096,DYr=20;function BYr(){let t;try{t=kYr(Xze(Na(),"crtrd.log"),"r");let{size:e}=IYr(t),n=Math.max(0,e-PYr),r=e-n;if(r<=0)return;let i=Buffer.alloc(r);TYr(t,i,0,r,n);let s=i.toString("utf8").split(`
1628
+ ${n}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=n}},AN=class extends Error{constructor(e,n){super(`daemon ${e} is running but normal startup is blocked: ${n}`),this.name="DaemonStartupBlockedError"}},aj=class extends Error{constructor(e,n){super(n===void 0?`daemon ${e} is serving but did not report the prepared startup phase`:`daemon ${e} reported startup phase ${n}, not prepared`),this.name="DaemonNotPreparedError"}};async function oYr(t,e=3e5,n={},r="ready"){let i=n.readPidfile??wT,o=n.isPidAlive??Rf,s=n.childExited,a=n.isDaemonServing,c=n.probeDaemonServing??(async f=>{if(a!==void 0){if(await a())return;throw new Error("crtrd health check reported not ready")}await iYr(f)}),u=n.probeDaemonHealth??Yze,l=n.sleepMs??Jze,d=n.now??Date.now,p=null,h=null;return await X3({windowMs:e,pollIntervalMs:Kze,now:d,sleep:l,retry:f=>f!==h,probe:async f=>{let m=i();if(m===null||!o(m)){let y=s?.();throw y!=null&&(y.signal!==null?h=new sj(`daemon ${t} exited before becoming ready (by ${y.signal})`,n.childStderrTail?.()??""):y.code!==0&&(h=new sj(`daemon ${t} exited before becoming ready (with exit code ${y.code??"?"})`,n.childStderrTail?.()??"")),h!==null)?h:new Error(`daemon ${t} has no live pidfile owner`)}if(r==="ready"){try{await c(f)}catch(y){throw y instanceof AN&&(h=y),y}p=m;return}let g=await u(f);if(g.startup_phase==="prepared"){p=m;return}throw g.startup_phase==="blocked"?(h=new AN(m,g.startup_blocked??"on-disk migration is blocked"),h):g.startup_phase==="ready"?(h=new aj(m,g.startup_phase),h):new Error(`daemon ${m} is ${g.startup_phase??"not reporting a startup phase"}; waiting for prepared`)}}),p===t?null:p}async function sYr(t,e=Aln,n={}){let r=n.readPidfile??wT,i=n.isPidAlive??Rf,o=n.sleepMs??Jze,s=n.now??Date.now,a=s()+e;for(;s()<=a;){if(!i(t)&&r()!==t)return;await o(Kze)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}var aYr=2e3,cYr=5e3;async function uYr(t,e=Aln,n={}){let r=n.isPidAlive??Rf,i=n.sleepMs??Jze,o=n.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await sYr(t,e,n),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}let s=o()+aYr;for(;o()<=s;){if(!r(t))return"killed";await i(Kze)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}function lYr(t,e,n=2048){let r;try{r=fln(t,"r");let{size:i}=gln(r),o=Math.max(e,i-n),s=i-o;if(s<=0)return"";let a=Buffer.alloc(s);return JKr(r,a,0,s,o),a.toString("utf8").trim()}catch{return""}finally{if(r!==void 0)try{mln(r)}catch{}}}async function dYr(t={}){if(process.platform==="linux"&&hln("/run/crtr/launcher.sock")&&!Rf(wT()??-1))throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");let e=t.targetPhase??"ready",n=wT();if(n!==null&&Rf(n))try{let p=await Yze();if(e==="prepared"){if(p.startup_phase==="prepared")return{started:!1,existing_pid:n,startup_phase:p.startup_phase};throw new aj(n,p.startup_phase)}return p.ok?{started:!1,existing_pid:n,...p.startup_phase===void 0?{}:{startup_phase:p.startup_phase}}:{started:!1,existing_pid:n,running:!0,serving:!1,probe_error:p.startup_blocked??"crtrd health check reported not ready",...p.startup_phase===void 0?{}:{startup_phase:p.startup_phase}}}catch(p){if(p instanceof aj)throw p;return{started:!1,existing_pid:n,running:!0,serving:!1,probe_error:rYr(p)}}YKr(Na(),{recursive:!0});let r=await tYr();t.waitForJoinLock===!0&&await pln(nYr);let i=Lle();if(i!==null&&i!==process.pid&&t.ignoreJoinLock!==!0)throw dln(i);let o=gN(Na(),"crtrd.err"),s=fln(o,"a"),a=(()=>{try{return gln(s).size}catch{return 0}})();Y3()===void 0&&pYe();let c=jKr(cln(),[...r,"--canvas-home",Na(),...e==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:ZKr()});mln(s);let u=c.pid;if(u===void 0)throw new Error("daemon spawn did not return a pid");let l=null;c.once("exit",(p,h)=>{l={code:p,signal:h}}),c.unref();let d;try{d=await oYr(u,3e5,{childExited:()=>l,childStderrTail:()=>lYr(o,a)},e)}catch(p){let h=yR(sYe())===u;if(l===null&&!h&&!(p instanceof AN))try{await uYr(u,cYr)}catch{}throw p}return d!==null?{started:!1,existing_pid:d,startup_phase:e}:{started:!0,pid:u,startup_phase:e}}function $le(){return e9e()||process.argv.includes("--no-autostart")}var pYr=5e3,hYr=6e4,zze=!1,oj,Ole=0,Nle=0;function fYr(t){return Math.min(pYr*2**(t-1),hYr)}function mYr(){oj=void 0,Ole=0,Nle=0}function yln(){return oj}function xln(t={}){let e=t.isDaemonRunning??uln,n=t.spawnDaemon??dYr,r=t.now??Date.now;if(!$le()&&!lln()&&!zze&&!(r()<Nle)){if(e()){mYr();return}oj=void 0,zze=!0,n().then(()=>{oj=void 0,Ole=0,Nle=0},i=>{i instanceof sj&&(oj=i.message),Ole+=1,Nle=r()+fYr(Ole)}).finally(()=>{zze=!1})}}import{existsSync as gYr,readFileSync as AYr,statSync as URs}from"node:fs";import{join as yYr}from"node:path";var xYr="secrets.json";function wYr(t){return yYr(t===Yc()?Sy():t,xYr)}function bYr(t){let e=og(t);if(!e)return{relayTokens:{}};let n=wYr(e);if(!gYr(n))return{relayTokens:{}};try{let r=JSON.parse(AYr(n,"utf8")),i=Array.isArray(r.scopedApiTokens)?r.scopedApiTokens.filter(o=>typeof o?.token=="string"&&o.token!==""&&typeof o.grantee=="string"&&/^app:[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(o.grantee)&&Array.isArray(o.scopes)&&typeof o.created=="string"):[];return{relayTokens:r.relayTokens??{},...typeof r.apiToken=="string"&&r.apiToken!==""?{apiToken:r.apiToken}:{},...i.length>0?{scopedApiTokens:i}:{}}}catch{return{relayTokens:{}}}}function wln(t,e){return bYr(e).relayTokens[t]}function Fle(t,e="user"){let n=zc(e),r=n.remoteCanvas.targets[t];if(r===void 0){let o=Object.keys(n.remoteCanvas.targets);throw lS(`no remote canvas target named '${t}'`+(o.length>0?` \u2014 configured: ${o.join(", ")}`:" \u2014 none configured yet")+`. Add one with \`crtr canvas config add ${t} --preview <url> --relay-token -\`.`)}let i=wln(r.relayTokenRef,e);if(i===void 0||i==="")throw lS(`target '${t}' has no stored relay token \u2014 add it with \`crtr canvas config add ${t} --relay-token -\`.`);return{previewEndpoint:r.previewEndpoint,relayToken:i}}function bln(t,e,n=5e3){let r=/^[\x20-\x7e]+$/.test(e);return async function(o,s){if(!r)return{ok:!1,stdout:"",stderr:"remote source: invalid stored relay token"};let a={kind:"exec",bin:o,args:s},c=new AbortController,u=setTimeout(()=>c.abort(),n),l;try{l=await fetch(new URL("/__crtr/source",t),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(a),signal:c.signal})}catch{return c.signal.aborted?{ok:!1,stdout:"",stderr:`remote source: timeout after ${n}ms`}:{ok:!1,stdout:"",stderr:"remote source: network error"}}finally{clearTimeout(u)}return l.ok?await l.json():{ok:!1,stdout:"",stderr:`remote source: HTTP ${l.status} ${l.statusText}`}}}var Ule=1e3;function bl(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function EYr(t){if(!bl(t))return!1;let e=t.node;if(!bl(e)||typeof e.node_id!="string"||!Array.isArray(t.reports)||!Array.isArray(t.managers))return!1;let n=t.artifacts;if(!bl(n)||typeof n.report!="number"||typeof n.doc!="number"||typeof n.roadmap!="number"||typeof t.pending_crons!="number")return!1;let r=t.paths;if(!bl(r)||typeof r.context_dir!="string"||"session_file"in r&&r.session_file!==null&&typeof r.session_file!="string"||typeof t.follow_up!="string")return!1;let i=t.fault;if(i!=null){if(!bl(i)||typeof i.link!="string"||typeof i.kind!="string"||typeof i.since!="string")return!1;let o=i.retry;if(!bl(o)||typeof o.disposition!="string")return!1}return!0}function Eln(t){return bl(t)&&typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.status=="string"&&typeof t.active=="boolean"}function vYr(t){return bl(t)&&typeof t.from_id=="string"&&typeof t.to_id=="string"&&typeof t.active=="boolean"&&typeof t.created=="string"}function SYr(t){return bl(t)?typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.mode=="string"&&typeof t.lifecycle=="string"&&typeof t.status=="string"&&typeof t.cwd=="string"&&typeof t.created=="string":!1}var Nv=class{constructor(e,n){this.previewEndpoint=e;this.relayToken=n;this.exec=bln(e,n)}previewEndpoint;relayToken;exec;nodeCache=new Map;rosterCache=new Map;topologyCache=null;viewCache=new Map;async execJson(e){let n;try{n=await this.exec("crtr",["--json",...e])}catch{return null}if(!n.ok||n.exitCode!==void 0&&n.exitCode!==0)return null;try{return JSON.parse(n.stdout.trim())}catch{return null}}async fetchShow(e){let n=this.nodeCache.get(e);if(n&&Date.now()-n.at<Ule)return n.value;let r=await this.execJson(["node","inspect","show",e]),i=EYr(r)?{...r,fault:r.fault??null,reports:r.reports.filter(Eln),managers:r.managers.filter(Eln)}:null;return this.nodeCache.set(e,{value:i,at:Date.now()}),i}topology(){if(this.topologyCache!==null&&Date.now()-this.topologyCache.at<Ule)return this.topologyCache.value;let e=this.loadTopology();return this.topologyCache={value:e,at:Date.now()},e}async loadTopology(){let e=await this.exec("crtr",["--json","canvas","roster"]);if(!e.ok||e.exitCode!==void 0&&e.exitCode!==0)throw new Error("remote canvas topology is unavailable");let n;try{n=JSON.parse(e.stdout.trim())}catch{throw new Error("remote canvas topology is invalid")}if(!bl(n)||!Array.isArray(n.edges)||!n.edges.every(vYr))throw new Error("remote canvas topology is invalid");let r=n.edges,i={subscriptions:new Map,subscribers:new Map};for(let o of r){let s={node_id:o.to_id,active:o.active,created:o.created},a={node_id:o.from_id,active:o.active,created:o.created},c=i.subscriptions.get(o.from_id);c===void 0?i.subscriptions.set(o.from_id,[s]):c.push(s);let u=i.subscribers.get(o.to_id);u===void 0?i.subscribers.set(o.to_id,[a]):u.push(a)}return i}async rawShow(e){return this.fetchShow(e)}async getNode(e){return(await this.fetchShow(e))?.node??null}async getRow(e){let n=(await this.fetchShow(e))?.node;return n?{node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:n.host_kind??null,profile_id:n.profile_id??null,scopes:n.scopes??null,isolated:n.isolated===!0,parent:n.parent??null,created:n.created,intent:n.intent??null,frozen_at:n.frozen_at??null,terminal_reason:n.terminal_reason??null,pi_pid:n.pi_pid??null,pi_pid_identity:n.pi_pid_identity??null,window:n.window??null,tmux_session:n.tmux_session??null,pane:n.pane??null,fault:n.fault??null,streaming:n.streaming===!0}:null}async listNodes(e){let n=JSON.stringify([e?.status??null,e?.under??null]),r=this.rosterCache.get(n);if(r&&Date.now()-r.at<Ule)return r.value;let i=["node","inspect","list"];e?.status&&i.push("--status",(Array.isArray(e.status)?e.status:[e.status]).join(",")),e?.under&&i.push("--under",e.under);let o=await this.execJson(i),a=(bl(o)&&Array.isArray(o.nodes)?o.nodes:[]).filter(SYr).map(c=>({...c,isolated:c.isolated===!0}));return this.rosterCache.set(n,{value:a,at:Date.now()}),a}async subscriptionsOf(e){return(await this.topology()).subscriptions.get(e)??[]}async subscribersOf(e){return(await this.topology()).subscribers.get(e)??[]}async view(e){let n=this.viewCache.get(e);if(n&&Date.now()-n.at<Ule)return n.value;let r=new Set([e]),i=[],o=(await this.subscriptionsOf(e)).map(s=>s.node_id);for(;o.length>0;){let s=o.shift();if(!r.has(s)){r.add(s),i.push(s);for(let a of await this.subscriptionsOf(s))r.has(a.node_id)||o.push(a.node_id)}}return this.viewCache.set(e,{value:i,at:Date.now()}),i}async ticketCountsForNodes(e){if(e.length===0)return{};let n=await this.execJson(["canvas","attention","map","--nodes",e.join(",")]);return bl(n)&&bl(n.counts)?n.counts:{}}async ticketCountsForView(e){let n=await this.execJson(["canvas","attention","map","--view",e]);return bl(n)&&bl(n.counts)?n.counts:{}}async hasActiveLiveSubscription(e){let n=(await this.subscriptionsOf(e)).filter(r=>r.active);for(let r of n){let i=await this.getRow(r.node_id);if(i&&(i.status==="active"||i.status==="idle"))return!0}return!1}};function Qle(t){return{...t,fault:t.fault??null}}function Zze(t,e){throw t instanceof ln?Wze(t,e):t}var PYr=4096,DYr=20;function BYr(){let t;try{t=kYr(Xze(Na(),"crtrd.log"),"r");let{size:e}=IYr(t),n=Math.max(0,e-PYr),r=e-n;if(r<=0)return;let i=Buffer.alloc(r);TYr(t,i,0,r,n);let s=i.toString("utf8").split(`
1629
1629
  `).filter(a=>a.trim()!=="").slice(-DYr).join(`
1630
1630
  `).trim();return s===""?void 0:`crtrd.log (tail):
1631
1631
  ${s}`}catch{return}finally{if(t!==void 0)try{_Yr(t)}catch{}}}function Ht(t){let e=process.env.CRTR_API_SOCKET;if(e){let n=()=>{if(!CYr(e))try{let i=RYr(e),o=vln(Xze(i,uYe),"utf8"),s=vln(Xze(i,lYe),"utf8");if(o===s&&o!=="")return new ln(503,"broker_released","This node's broker has been released, so crtr commands from its background jobs are not available.")}catch(i){if(i.code!=="ENOENT")throw i}},r=n();if(r!==void 0)throw Wze(r,"Run the command from the node's own turn instead.");return _y({autostart:!1,availabilityFailure:n,coldStartPollWindowMs:($le()?t9e():void 0)??3e5,...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}})}return $le()?_y({autostart:!1,...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}}):_y({...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{},onColdSocket:async()=>{xln()},coldStartDiagnostic:BYr,coldStartFailure:yln,coldStartPollWindowMs:3e5})}var LYr=2e3,yN=class{client;rosterCache=null;rosterInFlight=null;constructor(e=Ht()){this.client=e}async roster(){let e=Date.now();return this.rosterCache!==null&&e-this.rosterCache.at<LYr?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(n=>{let r={snapshot:n,subscriptions:new Map,subscribers:new Map};for(let i of n.edges){let o={node_id:i.to_id,active:i.active,created:i.created},s={node_id:i.from_id,active:i.active,created:i.created},a=r.subscriptions.get(i.from_id);a===void 0?r.subscriptions.set(i.from_id,[o]):a.push(o);let c=r.subscribers.get(i.to_id);c===void 0?r.subscribers.set(i.to_id,[s]):c.push(s)}return this.rosterCache={at:Date.now(),index:r},r}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(e){try{return await e()}catch(n){if(n instanceof ln&&n.status===404)return null;throw n}}async getNode(e){let n=await this.orNull(()=>this.client.getNode(e));return n===null?null:Qle(n)}async getRow(e){let n=await this.orNull(()=>this.client.getNode(e));return n===null?null:Qle(n)}async listNodes(e){let n=e?.status,r=e?.under===void 0?{}:{under:e.under,under_inclusive:!0},i;if(Array.isArray(n)){let o=new Set(n);i=(await this.client.listNodes(r)).filter(a=>o.has(a.status))}else i=await this.client.listNodes({...n!==void 0?{status:n}:{},...r});return i.map(o=>Qle(o))}async browseSnapshot(){let e=await this.client.canvasBrowseCompressed(),n=JSON.parse(MYr(e).toString("utf8")),r={subscriptions:new Map,subscribers:new Map};for(let i of n.edges){let o=r.subscriptions.get(i.from_id)??[];o.push({node_id:i.to_id,active:i.active,created:i.created}),r.subscriptions.set(i.from_id,o);let s=r.subscribers.get(i.to_id)??[];s.push({node_id:i.from_id,active:i.active,created:i.created}),r.subscribers.set(i.to_id,s)}return this.rosterCache={at:Date.now(),index:r},n.nodes.map(i=>Qle(i))}async panelRoster(){let e=await this.roster();return e.snapshot!==void 0?e.snapshot:(this.rosterCache=null,(await this.roster()).snapshot)}async subscriptionsOf(e){return this.roster().then(n=>n.subscriptions.get(e)??[])}async subscribersOf(e){return this.roster().then(n=>n.subscribers.get(e)??[])}async view(e){let n=new Set([e]),r=[],i=(await this.subscriptionsOf(e)).map(o=>o.node_id);for(;i.length>0;){let o=i.shift();if(!n.has(o)){n.add(o),r.push(o);for(let s of await this.subscriptionsOf(o))n.has(s.node_id)||i.push(s.node_id)}}return r}async ticketCountsForNodes(e){return(await this.client.attentionCounts([...e])).counts}async ticketCountsForView(e){return this.ticketCountsForNodes([e,...await this.view(e)])}async newestReport(e){return(await this.client.getReports(e,{limit:1}))[0]??null}async hasActiveLiveSubscription(e){let n=(await this.subscriptionsOf(e)).filter(r=>r.active);for(let r of n){let i=await this.getRow(r.node_id);if(i&&(i.status==="active"||i.status==="idle"))return!0}return!1}};function Sln(t,e=e$()){let n=t?.scope??"user";if(e){if(t?.canvasName!==void 0)throw DKe("--canvas selects the person's remote canvas targets, which an app's node cannot reach","Omit --canvas; this node reads its own runtime's canvas.");return new yN}let r=t?.canvasName??det(n).activeCanvas??null;if(!r)return new yN;let{previewEndpoint:i,relayToken:o}=Fle(r,n);return new Nv(i,o)}function OYr(t){return{dir:t.request_dir,id:t.request_id,inboxTicketId:t.ticket_id,kind:"page",title:t.title,subtitle:t.subtitle??"",dialect:t.dialect,placement:t.placement,inbox:t.inbox,steps:t.steps,slotKinds:t.slot_kinds,awaitsResponse:t.awaits_response,source:t.source,emittedAt:t.emitted_at,recommendedOptions:(t.recommended_options??[]).map(e=>({slotId:e.slot_id,optionId:e.option_id,label:e.label})),...t.fast_action===void 0?{}:{fastAction:{kind:t.fast_action.kind,responses:t.fast_action.responses}},state:t.state,...t.answer_digest===void 0?{}:{answerDigest:t.answer_digest}}}function NYr(t){return{dir:t.request_dir,id:t.request_id,inboxTicketId:t.ticket_id,kind:"review",title:t.title,subtitle:t.subtitle,blockedSince:t.blocked_since,source:t.source}}function Km(t){return t.kind==="page"?OYr(t):NYr(t)}function bT(t){return{manifest:yT(t.page),document:t.source_document,progress:t.progress===null?null:t.progress.responses,state:t.state,revision:t.revision}}function _ln(t){let e=t.result;if(!(e===null||e.kind!=="page"))return e.summary.replace(/\s+/g," ").trim()}function xN(t){let e=t.result;return e!==null&&e.kind==="canceled"?"ticket was already canceled":e!==null&&e.kind==="page"?"ticket was already resolved: page submitted":"ticket was already resolved"}function $v(t,e){let n=r=>r.kind==="page"?r.emittedAt:r.blockedSince;return n(e).localeCompare(n(t))||t.id.localeCompare(e.id)}var $Yr=new Set(["c","r","e","a","n","p","q","j","k","u","d"," "]);function wN(t){let e=t.config.label;return typeof e=="string"&&e!==""?e:t.unvalidated===!0?t.kind:t.kind==="options"?"Options":t.kind==="text"?"Text":t.kind==="table"?"Table":t.kind==="cards"?"Cards":t.kind==="chart"?"Chart":t.kind}function Ip(t){return!(t.unvalidated===!0||t.kind==="cards"&&t.config.cards===void 0)}function Wle(t){if(!Ip(t))return[];let e=[];if(t.kind==="options"){let r=t.config;e=r.options.map(i=>({kind:"select",group:"option",id:i.id,label:i.label,...i.description===void 0?{}:{description:i.description},mode:r.mode})),r.allowFreetext===!0&&e.push({kind:"freetext",label:r.freetextLabel??"Something else"})}else if(t.kind==="cards"){let r=t.config;e=(r.cards??[]).map(i=>({kind:"select",group:"card",id:i.id,label:i.subtitle===void 0?i.title:`${i.title} \u2014 ${i.subtitle}`,...i.body===void 0?{}:{description:i.body},mode:r.mode}))}else if(t.kind==="text")e.push({kind:"edit",label:"Edit"}),e.push({kind:"accept",label:"Accept as-is"});else if(t.kind==="table"){let r=t.config;if(r.rowSelect!=="none"){let i=r.columns[0];e.push(...(r.rows??[]).map(o=>({kind:"select",group:"row",id:o.id,label:i===void 0?o.id:String(o.cells[i.id]??o.id),mode:r.rowSelect})))}r.columnSelect!=="none"&&e.push(...r.columns.map(i=>({kind:"select",group:"column",id:i.id,label:i.label,mode:r.columnSelect})))}let n=new Set;return e.map(r=>{if(r.kind!=="select")return r;let i;for(let o of[...r.label.toLowerCase()].filter(s=>/[a-z]/.test(s)))if(!n.has(o)&&!$Yr.has(o)){i=o;break}if(i===void 0){for(let o=1;o<=9;o++)if(!n.has(String(o))){i=String(o);break}}return i!==void 0&&n.add(i),{...r,...i===void 0?{}:{shortcut:i}}})}function Cln(t,e=!1){if(t==null)return"";let n=String(t).replaceAll("|","\\|").replaceAll(`
@@ -1633,7 +1633,7 @@ ${s}`}catch{return}finally{if(t!==void 0)try{_Yr(t)}catch{}}}function Ht(t){let
1633
1633
  `)}function e6e(t,e,n){if(e.id===void 0)return!1;try{return Hun(t.manifest,{[e.id]:n}),!0}catch{return!1}}function kx(t,e){return!Ip(e)||e.id===void 0||!t.responses.has(e.id)?!1:e6e(t,e,t.responses.get(e.id))}function Fv(t){if(t.manifest.slots.some(e=>fc(e)&&!Ip(e)))return!1;try{return Wun(t.manifest,Object.fromEntries(t.responses)),!0}catch{return!1}}function bN(t){switch(t.kind){case"option":return`option:${t.optionId}`;case"row":return`row:${t.rowId}`}}function EN(t){return Ip(t)?t.kind==="options"?t.config.options.map(e=>({kind:"option",optionId:e.id})):t.kind==="table"?(t.config.rows??[]).map(e=>({kind:"row",rowId:e.id})):[]:[]}tt();var kp="\x1B[",Oe=`${kp}0m`,ls=`${kp}1m`,ut=`${kp}2m`,kln=`${kp}3m`,Tln=`${kp}31m`,ET=`${kp}32m`,Hs=`${kp}33m`,ds=`${kp}36m`,qle=`${kp}90m`,uj=`${kp}7m`,FYr=/\x1b\[[0-9;?]*[a-zA-Z]|\x1b[@-_]|[\x00-\x08\x0B\x0E-\x1F\x7F-\x9F]/g;function Vr(t){return typeof t!="string"?"":t.replace(FYr,"")}function El(t){return Vr(t).replace(/\s+/g," ").trim()}function Tx(t,e="\u2500"){return t<1?"":e.repeat(t)}function Tp(t,e){if(e<1)return"";if(Ws(t)<=e)return t;let n=[...t],r=0,i="";for(let o of n){let s=Ws(o);if(r+s+1>e)break;i+=o,r+=s}return i+"\u2026"}function Gle(t,e){let n=t.replace(/\n/g," ").replace(/✅/g,"\u2713").replace(/❌/g,"\u2717").replace(new RegExp("\\p{Emoji_Presentation}","gu"),"");if(e<4)return n.slice(0,e);if(Ws(n)<=e)return n;let i=n;for(;Ws(i)>e-1&&i.length>0;){let o=i.lastIndexOf(" ",i.length-2);o>e*.4?i=i.slice(0,o):i=i.slice(0,i.length-1)}return i+"\u2026"}function UYr(t,e){let n=0,r="";for(let i of t){let o=Ws(i);if(n+o>e)break;r+=i,n+=o}return r===""&&t.length>0&&(r=[...t][0]),r}function vl(t,e){if(e<1)return[t];let n=[],r=t.split(`
1634
1634
  `);for(let i=0;i<r.length;i++){let o=r[i];if(o===""){n.push("");continue}let s=o.split(/[ \t]+/).filter(Boolean),a="";for(let c of s){for(;Ws(c)>e;){a&&(n.push(a),a="");let l=UYr(c,e);n.push(l),c=c.slice(l.length)}let u=a?`${a} ${c}`:c;Ws(u)<=e?a=u:(a&&n.push(a),a=c)}a&&n.push(a)}return n.length>0?n:[""]}function py(t,e,n){let r=Math.max(0,Math.floor((e-n)/2));if(r===0)return t;let i=" ".repeat(r);return t.map(o=>o===""?"":i+o)}function zo(t){return Ce(t)}var t6e=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b_[^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[a-zA-Z]|\x1b[@-^]/g,n6e=/\x1b\]8;[^;\x07\x1b]*;([^\x07\x1b]*)(\x07|\x1b\\)/g,Iln=new Intl.Segmenter(void 0,{granularity:"grapheme"});function QYr(t){let e=[],n=0;t6e.lastIndex=0;for(let r=t6e.exec(t);r!==null;r=t6e.exec(t)){for(let i of Iln.segment(t.slice(n,r.index)))e.push({ansi:!1,text:i.segment,width:zo(i.segment)});e.push({ansi:!0,text:r[0]}),n=r.index+r[0].length}for(let r of Iln.segment(t.slice(n)))e.push({ansi:!1,text:r.segment,width:zo(r.segment)});return e}function Rln(t,e,n){if(n<1)return"";let r=Math.max(0,e),i=r+n,o="",s="",a=!1,c=0;for(let l of QYr(t)){if(l.ansi){c<r?o+=l.text:(s+=l.text,a=!0);continue}if(c>=i)break;let d=l.width;if(d===0){c>=r&&(s+=l.text);continue}if(c+d<=r){c+=d;continue}if(c<r){s+=" ".repeat(c+d-r),c+=d;continue}if(c+d>i){s+=" ".repeat(i-c),c=i;break}s+=l.text,c+=d}if(s==="")return"";o!==""&&(s=o+s,a=!0);let u=WYr(s);return a?s+u+Oe:s}function WYr(t){let e="";n6e.lastIndex=0;for(let n=n6e.exec(t);n!==null;n=n6e.exec(t))e=n[1]===""?"":`\x1B]8;;${n[2]}`;return e}function ma(t,e){return e<1?"":zo(t)<=e?t:Rln(t,0,e)}function jle(t,e,n){if(n<1)return"";let r=zo(t);if(r<=n)return t;let i=r-n,o=Math.max(0,Math.min(e,i)),s=o>0,a=o<i,c=n-(s?1:0)-(a?1:0),u=c>0?Rln(t,o+(s?1:0),c):"";return`${s?`${ut}\u2039${Oe}`:""}${u}${a?`${ut}\u203A${Oe}`:""}`}function zle(t,e,n,r){let i=a=>mce(yce(a),n,r);if(t.dialect==="html")return e===""?[`${ut}HTML page \u2014 open in Northlight to read this${Oe}`]:i(e);let o=e===""?[]:i(e),s=-1;for(let a of t.slots){t.steps>1&&a.step!==s&&(o.length>0&&o.push(""),o.push(`${ls}Step ${a.step+1}/${t.steps}${Oe}`),s=a.step),o.length>0&&o.push("");for(let u of vl(El(wN(a)),n))o.push(`${ls}${u}${Oe}`);let c=a.config.body;if(typeof c=="string"&&c!==""&&o.push(...i(c)),!Ip(a)){o.push(`${ut}${Vr(a.kind)} \u2014 open in Northlight to answer this${Oe}`);continue}if(a.kind==="text")o.push(...i(a.config.initialText));else if(a.kind==="table")o.push(...i(Hle(a.config)));else if(a.kind==="cards"){for(let u of a.config.cards??[])if(o.push(` \u2022 ${Tp(Vr(El(u.subtitle===void 0?u.title:`${u.title} \u2014 ${u.subtitle}`)),Math.max(10,n-4))}`),u.body!==void 0)for(let l of vl(Vr(u.body),Math.max(10,n-6)))o.push(` ${ut}${l}${Oe}`)}else if(a.kind==="options"){for(let u of a.config.options)if(o.push(` \u2022 ${Tp(Vr(El(u.label)),Math.max(10,n-4))}`),u.description!==void 0)for(let l of vl(Vr(u.description),Math.max(10,n-6)))o.push(` ${ut}${l}${Oe}`)}else if(a.kind==="chart"){let u=a.config,l=u.title??`${u.x??""} vs ${(u.y??[]).map(d=>d.label??d.field).join(", ")}`;o.push(`${ut}chart \u2014 ${Vr(u.kind??"chart")}: ${Vr(l)}${Oe}`)}}return o}var Mln=16;function Pln(t){if(t===null||typeof t!="object")return;let e=t.details;if(e===null||typeof e!="object")return;let n=e.crtrPreview;if(n===null||typeof n!="object")return;let r=n;if(r.path!=="human send")return;let i=r.result;if(i===null||typeof i!="object")return;let o=i,s=o.page_id;if(typeof s=="string"&&o.placement==="inline")return{pageId:s}}function HYr(t){return t.document_media_type==="text/html"?hN(t.source_document):pN(t.source_document,t.page)}var Vle=class{constructor(e,n){this.pageId=e;this.openHint=n}pageId;openHint;expanded=!1;generation=0;stamp;snapshot;status="loading";cache;get settled(){return this.snapshot?.state==="resolved"||this.snapshot?.state==="canceled"}async refresh(){let e;try{e=(await Ht().getHumanRequest(this.pageId)).page}catch{e=void 0}if(e===void 0)return this.settle("unavailable",void 0,void 0);let n=`${e.revision}|${e.state}`;if(this.status==="ready"&&n===this.stamp)return!1;let r;try{r={manifest:e.page,displayMarkdown:HYr(e),state:e.state,...e.state==="resolved"?qYr(_ln(e)):{}}}catch{return this.settle("unavailable",void 0,n)}return this.settle("ready",r,n)}setExpanded(e){e!==this.expanded&&(this.expanded=e,this.cache=void 0)}render(e){let n=e>0?e:80,r=this.cache;if(r!==void 0&&r.width===n&&r.generation===this.generation&&r.expanded===this.expanded)return r.lines;let i=this.compose(n);return this.cache={width:n,generation:this.generation,expanded:this.expanded,lines:i},i}invalidate(){this.cache=void 0}settle(e,n,r){return e===this.status&&e==="unavailable"?!1:(this.status=e,this.snapshot=n,this.stamp=r,this.generation++,this.cache=void 0,!0)}compose(e){let n=this.snapshot;if(n===void 0){let a=this.status==="loading"?"[page] loading\u2026":"[page] no longer available";return["",` ${ut}${a}${Oe}`,""]}let r=Math.min(Math.max(20,e-4),100),i=["",` ${ls}${ds}${Tp(Vr(El(n.manifest.title)),r)}${Oe}`];if(n.manifest.subtitle)for(let a of vl(Vr(n.manifest.subtitle),r))i.push(` ${ut}${a}${Oe}`);let o=zle(n.manifest,n.displayMarkdown,r,Math.max(20,e-4));if(o.length>0){i.push("");let a=this.expanded||o.length<=Mln?o:o.slice(0,Mln);for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} lines \u2014 ctrl+o to expand${Oe}`)}let s=this.footerLine(n,r);return s!==void 0&&i.push("",` ${s}`),i.push(""),i}footerLine(e,n){switch(e.state){case"pending":return Ile(e.manifest)?`${Hs}\u25B8 awaiting your answer${Oe} ${ut}\u2014 ${Vr(this.openHint())}${Oe}`:`${ut}\u25E6 queued in your inbox \u2014 ${Vr(this.openHint())}${Oe}`;case"resolved":return e.answerDigest===void 0?`${ET}\u2713 answered${Oe}`:`${ET}\u2713 answered${Oe} ${ut}\u2014 ${Tp(Vr(e.answerDigest),Math.max(10,n-12))}${Oe}`;case"canceled":return`${ut}\u2298 canceled${Oe}`;case"passive":return}}};function qYr(t){return t===void 0?{}:{answerDigest:t}}fa();tt();var GYr=new Set(["canvas roster","canvas snapshot","node inspect snapshot","node inspect show","sys context sysprompt"]);function Bln(t){for(let e of GYr){let n=e.split(" ");if(n.length<=t.length&&n.every((r,i)=>t[i]===r))return!0}return!1}var jYr=61529,Lln=String.fromCodePoint(jYr),mf={bash:String.fromCodePoint(61728),read:String.fromCodePoint(61788),write:String.fromCodePoint(61639),edit:String.fromCodePoint(61508)},zYr={canvas:61672,capture:61501,device:61705,doc:61485,human:61447,node:61842,pkg:61874,profile:62141,push:61678,"exa-search":61442,surface:61704,sys:61459},VYr={"canvas dashboard":61668,"canvas snapshot":61488,"canvas browse":61774,"canvas attention count":62098,"canvas attention list":61498,"canvas attention map":62073,"canvas revive":61473,"node lifecycle revive":61473,"canvas list":61498,"canvas read":61485,"canvas search":61442,"canvas history search":61442,"canvas history grep":61616,"sys daemon start":61515,"sys daemon status":61713,"sys daemon stop":61517,"canvas chord":61441,"surface tmux-spread":61449,"canvas issue new":61832,"canvas prune":61636,"human send":61529,"human review":61508,"human show":61704,"human cancel":61453,"human list":61498,"human resolve":61452,"doc write":61504,"doc edit":61508,"doc history":61914,"doc lint":61770,"node new":61543,"node message send":61664,"node message request":61664,"cron add":61463,"node wait deadline":61463,"node subscription add":61683,"node subscription remove":61942,"node promote":61698,"node yield":62093,"surface node focus":61531,"surface node cycle":61473,"node inspect list":61498,"node inspect show":61550,"node inspect snapshot":61488,"node inspect context":61564,"node lifecycle recycle":61880,"node lifecycle close":61453,"node lifecycle demote":61699,"node config":61459,"cron list":61463,"cron cancel":61534,"pkg plugin install":61465,"pkg plugin remove":61460,"pkg plugin enable":61452,"pkg plugin disable":61534,"pkg plugin update":61473,"pkg plugin list":61498,"pkg plugin show":61550,"pkg market add":61543,"pkg market remove":61460,"pkg market update":61473,"pkg market list":61498,"pkg market browse":61774,"push update":61587,"push final":61726,"exa-search web":61612,"exa-search answer":61557,"exa-search contents":61686,"surface attach to":61926,"sys config get":61465,"sys config set":61504,"sys config path":61563,"sys settings":61459,"sys setup":61613,"sys doctor":61681,"sys context sysprompt":61788,"sys context prompt-review":61442,"sys feedback":61557,"sys update":61473,"sys version":61483,"sys sync":61561};function Oln(t){let e;for(let[r,i]of Object.entries(VYr)){let o=r.split(" ");o.length<=t.length&&o.every((s,a)=>t[a]===s)&&(e===void 0||o.length>e.words)&&(e={words:o.length,cp:i})}if(e!==void 0)return String.fromCodePoint(e.cp);let n=t.length>0?zYr[t[0]]:void 0;return n!==void 0?String.fromCodePoint(n):"\u25C6"}function vN(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function Kle(t){let e=vN(vN(t)?.details);if(e===void 0)return[];let n=e.crtrPreviews;return(Array.isArray(n)?n:[e.crtrPreview]).flatMap(i=>{let o=vN(i);if(o===void 0||typeof o.path!="string")return[];let s=o.jsonl;return[{path:o.path,result:vN(o.result),jsonl:Array.isArray(s)?s.flatMap(a=>{let c=vN(a);return c===void 0?[]:[c]}):void 0,error:vN(o.error)}]})}var KYr=4;function Uv(t){return t.result}function ff(t,e){let n=t[e];return typeof n=="string"&&n!==""?n:void 0}function i6e(t,e){return typeof t[e]=="boolean"?t[e]:void 0}function vT(t,e){return typeof t[e]=="number"&&Number.isFinite(t[e])?t[e]:void 0}function YYr(t,e){let n=t[e];return Array.isArray(n)&&n.every(r=>r!==null&&typeof r=="object"&&!Array.isArray(r))?n:void 0}function JYr(t,e){return t.length>e?`${t.slice(0,e).trimEnd()}\u2026`:t}function XYr(t,e,n=5){let r=t.map(s=>ff(s,e));if(r.some(s=>s===void 0))return;let i=r.slice(0,n),o=r.length-i.length;return o>0?`${i.join(", ")}, \u2026 ${o} more`:i.join(", ")}function ZYr(t){let e=t.error;if(e===void 0)return null;let n=ff(e,"error"),r=ff(e,"message");return n===void 0||r===void 0?null:[{text:n,tone:"error"},{text:JYr(r,160),tone:"muted"}]}function eJr(t){let e=Uv(t);if(e===void 0)return null;let n=ff(e,"deleted")??ff(e,"remote");if(n!==void 0)return[{text:n.trim().split(`
1635
1635
  `)[0]??"",tone:"warning"}];let r=ff(e,"readMetadata")??ff(e,"object");if(r===void 0)return null;let i=r.split(`
1636
- `).filter(o=>o.trim()!==""&&!o.startsWith("<auto-loaded-context")&&!o.startsWith("</auto-loaded-context"));return i.length===0?null:[{text:i[0]},...i.slice(1,KYr).map(o=>({text:o,tone:"muted"}))]}function tJr(t,e=!1){return n=>{let r=Uv(n),i=r===void 0?void 0:vT(r,"count")??vT(r,"total");return i===void 0?null:i===0&&e?[{text:`PASS \xB7 no ${t}`,tone:"success"}]:[{text:`${i} ${t}`,tone:i===0?"muted":"plain"}]}}function Rx(t,e="items"){return n=>{let r=Uv(n);if(r===void 0)return null;let i=YYr(r,e),o=vT(r,"total")??i?.length;if(i===void 0||o===void 0)return null;let s=[{text:`${o} ${t}`,tone:o===0?"muted":"plain"}],a=XYr(i,"name");return a!==void 0&&a!==""&&s.push({text:a,tone:"muted"}),s}}function nJr(t){let n=Uv(t)?.counts;if(n===null||typeof n!="object"||Array.isArray(n))return null;let r=Object.entries(n);if(r.some(([,s])=>typeof s!="number"))return null;let i=r.reduce((s,[,a])=>s+a,0);if(i===0)return[{text:"PASS \xB7 no pending asks",tone:"success"}];let o=r.filter(([,s])=>s>0).sort((s,a)=>a[1]-s[1])[0];return o===void 0?null:[{text:`${i} asks`,tone:"warning"},{text:`hottest: ${o[0]} (${o[1]})`,tone:"muted"}]}function r6e(t,e,n){return r=>{let i=Uv(r);if(i===void 0)return null;let o=i6e(i,t);if(o===void 0)return null;let s=vT(i,"pid")??vT(i,"existing_pid");return[{text:o?`${e}${s===void 0?"":` \xB7 pid ${s}`}`:n,tone:o?"success":"muted"}]}}function rJr(t){let e=Uv(t);if(e===void 0||ff(e,"page_id")===void 0)return null;let n=i6e(e,"reply");return n===void 0?null:[{text:n?"page sent \u2192 waiting on human":"announcement sent",tone:n?"accent":"success"}]}function iJr(t){let e=Uv(t);if(e===void 0)return null;let n=i6e(e,"resolved"),r=ff(e,"job_id");return n===void 0||r===void 0?null:[{text:`${n?"resolved":"not resolved"} ${r}`,tone:n?"success":"warning"}]}function Dln(t){let e=Uv(t);if(e===void 0)return null;let n=ff(e,"status");return n===void 0?null:[{text:n,tone:["done","success","submitted","filed"].includes(n)?"success":n==="failed"?"error":"plain"}]}function oJr(t){let e=t.jsonl;if(e===void 0)return null;let n=e.filter(r=>ff(r,"name")!==void 0&&vT(r,"projects_count")!==void 0);return n.length===0&&e.length>0?null:[{text:`${n.length} profile${n.length===1?"":"s"}`},...n.slice(0,5).map(r=>({text:`${ff(r,"name")} \xB7 ${vT(r,"projects_count")} projects`,tone:"muted"}))]}var sJr=[{path:"canvas read",run:eJr},{path:"canvas list",run:Rx("objects")},{path:"canvas search",run:Rx("hits")},{path:"canvas attention count",run:tJr("pending asks",!0)},{path:"canvas attention list",run:Rx("pending asks")},{path:"canvas attention map",run:nJr},{path:"human send",run:rJr},{path:"human list",run:Rx("pending")},{path:"human resolve",run:iJr},{path:"pkg plugin list",run:Rx("plugins")},{path:"pkg market list",run:Rx("marketplaces")},{path:"pkg market browse",run:Rx("plugins")},{path:"canvas dashboard",run:Rx("nodes","rows")},{path:"node inspect list",run:Rx("nodes","nodes")},{path:"sys daemon start",run:r6e("started","started","already running")},{path:"sys daemon status",run:r6e("running","running","not running")},{path:"sys daemon stop",run:r6e("stopped","stopped","was not running")},{path:"sys update",run:Dln},{path:"sys feedback",run:Dln},{path:"profile list",run:oJr}];function Nln(t,e=[]){let n=ZYr(t);return n!==null?n:sJr.find(({path:i})=>i===t.path)?.run(t,e)??null}fa();tt();import{homedir as fJr}from"node:os";import{isAbsolute as mJr,resolve as gJr}from"node:path";import{pathToFileURL as AJr}from"node:url";import{dirname as s6e,join as gf}from"node:path";import{loadLinuxNative as cJr}from"../../native/linux.js";var $1s=cJr();var uJr=280;function a6e(t){if(typeof t!="string"||/[\p{Cc}\p{Cf}]/u.test(t))return null;let e=t.trim();return e===""?null:Buffer.byteLength(e,"utf8")<=uJr?e:null}function $ln(t){return gf(t,"jobs")}function c6e(t,e){return z3(s6e(t),e).toString("utf8")}function lJr(t){return iYe(s6e(t),$ln(t)).map(e=>e.name)}function o6e(t,e){return nYe(t.root,e)}function u6e(t,e){let n=gf($ln(t),e);return{jobId:e,root:s6e(t),dir:n,cmdSh:gf(n,"cmd.sh"),jobLog:gf(n,"job.log"),jobExit:gf(n,"job.exit"),jobRun:gf(n,"job.run"),jobBg:gf(n,"job.bg"),jobDone:gf(n,"job.done"),jobPgid:gf(n,"job.pgid"),jobPgidIdentity:gf(n,"job.pgid-identity"),jobPurpose:gf(n,"purpose"),jobDeadline:gf(n,"job.deadline")}}function dJr(t,e){try{return a6e(c6e(t,u6e(t,e).jobPurpose))}catch{return null}}function pJr(t,e){try{let n=Number(c6e(t,u6e(t,e).jobDeadline).trim());return Number.isFinite(n)?n:void 0}catch{return}}function hJr(t){let e=t.indexOf("-");if(e<=0||e===t.length-1)return;let n=Number(t.slice(0,e));return Number.isFinite(n)?n:void 0}function lj(t){let e=Math.max(0,Math.floor(t/1e3));if(e<60)return`${e}s`;let n=Math.floor(e/60),r=e%60;if(n<60)return`${n}m ${String(r).padStart(2,"0")}s`;let i=Math.floor(n/60),o=n%60;return`${i}h ${String(o).padStart(2,"0")}m`}function Fln(t){return(t.split(`
1636
+ `).filter(o=>o.trim()!==""&&!o.startsWith("<auto-loaded-context")&&!o.startsWith("</auto-loaded-context"));return i.length===0?null:[{text:i[0]},...i.slice(1,KYr).map(o=>({text:o,tone:"muted"}))]}function tJr(t,e=!1){return n=>{let r=Uv(n),i=r===void 0?void 0:vT(r,"count")??vT(r,"total");return i===void 0?null:i===0&&e?[{text:`PASS \xB7 no ${t}`,tone:"success"}]:[{text:`${i} ${t}`,tone:i===0?"muted":"plain"}]}}function Rx(t,e="items"){return n=>{let r=Uv(n);if(r===void 0)return null;let i=YYr(r,e),o=vT(r,"total")??i?.length;if(i===void 0||o===void 0)return null;let s=[{text:`${o} ${t}`,tone:o===0?"muted":"plain"}],a=XYr(i,"name");return a!==void 0&&a!==""&&s.push({text:a,tone:"muted"}),s}}function nJr(t){let n=Uv(t)?.counts;if(n===null||typeof n!="object"||Array.isArray(n))return null;let r=Object.entries(n);if(r.some(([,s])=>typeof s!="number"))return null;let i=r.reduce((s,[,a])=>s+a,0);if(i===0)return[{text:"PASS \xB7 no pending asks",tone:"success"}];let o=r.filter(([,s])=>s>0).sort((s,a)=>a[1]-s[1])[0];return o===void 0?null:[{text:`${i} asks`,tone:"warning"},{text:`hottest: ${o[0]} (${o[1]})`,tone:"muted"}]}function r6e(t,e,n){return r=>{let i=Uv(r);if(i===void 0)return null;let o=i6e(i,t);if(o===void 0)return null;let s=vT(i,"pid")??vT(i,"existing_pid");return[{text:o?`${e}${s===void 0?"":` \xB7 pid ${s}`}`:n,tone:o?"success":"muted"}]}}function rJr(t){let e=Uv(t);if(e===void 0||ff(e,"page_id")===void 0)return null;let n=i6e(e,"reply");return n===void 0?null:[{text:n?"page sent \u2192 waiting on human":"announcement sent",tone:n?"accent":"success"}]}function iJr(t){let e=Uv(t);if(e===void 0)return null;let n=i6e(e,"resolved"),r=ff(e,"job_id");return n===void 0||r===void 0?null:[{text:`${n?"resolved":"not resolved"} ${r}`,tone:n?"success":"warning"}]}function Dln(t){let e=Uv(t);if(e===void 0)return null;let n=ff(e,"status");return n===void 0?null:[{text:n,tone:["done","success","submitted","filed"].includes(n)?"success":n==="failed"?"error":"plain"}]}function oJr(t){let e=t.jsonl;if(e===void 0)return null;let n=e.filter(r=>ff(r,"name")!==void 0&&vT(r,"projects_count")!==void 0);return n.length===0&&e.length>0?null:[{text:`${n.length} profile${n.length===1?"":"s"}`},...n.slice(0,5).map(r=>({text:`${ff(r,"name")} \xB7 ${vT(r,"projects_count")} projects`,tone:"muted"}))]}var sJr=[{path:"canvas read",run:eJr},{path:"canvas list",run:Rx("objects")},{path:"canvas search",run:Rx("hits")},{path:"canvas attention count",run:tJr("pending asks",!0)},{path:"canvas attention list",run:Rx("pending asks")},{path:"canvas attention map",run:nJr},{path:"human send",run:rJr},{path:"human list",run:Rx("pending")},{path:"human resolve",run:iJr},{path:"pkg plugin list",run:Rx("plugins")},{path:"pkg market list",run:Rx("marketplaces")},{path:"pkg market browse",run:Rx("plugins")},{path:"canvas dashboard",run:Rx("nodes","rows")},{path:"node inspect list",run:Rx("nodes","nodes")},{path:"sys daemon start",run:r6e("started","started","already running")},{path:"sys daemon status",run:r6e("running","running","not running")},{path:"sys daemon stop",run:r6e("stopped","stopped","was not running")},{path:"sys update",run:Dln},{path:"sys feedback",run:Dln},{path:"profile list",run:oJr}];function Nln(t,e=[]){let n=ZYr(t);return n!==null?n:sJr.find(({path:i})=>i===t.path)?.run(t,e)??null}fa();tt();import{homedir as fJr}from"node:os";import{isAbsolute as mJr,resolve as gJr}from"node:path";import{pathToFileURL as AJr}from"node:url";import{dirname as s6e,join as gf}from"node:path";import{loadLinuxNative as cJr}from"../../native/linux.js";var U1s=cJr();var uJr=280;function a6e(t){if(typeof t!="string"||/[\p{Cc}\p{Cf}]/u.test(t))return null;let e=t.trim();return e===""?null:Buffer.byteLength(e,"utf8")<=uJr?e:null}function $ln(t){return gf(t,"jobs")}function c6e(t,e){return z3(s6e(t),e).toString("utf8")}function lJr(t){return iYe(s6e(t),$ln(t)).map(e=>e.name)}function o6e(t,e){return nYe(t.root,e)}function u6e(t,e){let n=gf($ln(t),e);return{jobId:e,root:s6e(t),dir:n,cmdSh:gf(n,"cmd.sh"),jobLog:gf(n,"job.log"),jobExit:gf(n,"job.exit"),jobRun:gf(n,"job.run"),jobBg:gf(n,"job.bg"),jobDone:gf(n,"job.done"),jobPgid:gf(n,"job.pgid"),jobPgidIdentity:gf(n,"job.pgid-identity"),jobPurpose:gf(n,"purpose"),jobDeadline:gf(n,"job.deadline")}}function dJr(t,e){try{return a6e(c6e(t,u6e(t,e).jobPurpose))}catch{return null}}function pJr(t,e){try{let n=Number(c6e(t,u6e(t,e).jobDeadline).trim());return Number.isFinite(n)?n:void 0}catch{return}}function hJr(t){let e=t.indexOf("-");if(e<=0||e===t.length-1)return;let n=Number(t.slice(0,e));return Number.isFinite(n)?n:void 0}function lj(t){let e=Math.max(0,Math.floor(t/1e3));if(e<60)return`${e}s`;let n=Math.floor(e/60),r=e%60;if(n<60)return`${n}m ${String(r).padStart(2,"0")}s`;let i=Math.floor(n/60),o=n%60;return`${i}h ${String(o).padStart(2,"0")}m`}function Fln(t){return(t.split(`
1637
1637
  `).map(n=>n.trim()).find(n=>n!=="")??"").replace(/\s+/g," ")}function Yle(t,e=!1){let n;try{n=lJr(t)}catch{return[]}let r=[];for(let i of n){let o=hJr(i);if(o===void 0)continue;let s=u6e(t,i),a;try{if(!o6e(s,s.jobBg)&&!(e&&o6e(s,s.jobRun))||o6e(s,s.jobExit))continue;a=c6e(t,s.cmdSh)}catch{continue}r.push({jobId:i,command:a,purpose:dJr(t,i),startedAtMs:o,logPath:s.jobLog,deadlineAtMs:pJr(t,i)??null})}return r.sort((i,o)=>i.startedAtMs-o.startedAtMs)}var Uln=/^cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/;function Qln(t){let e=t;for(;Uln.test(e);)e=e.replace(Uln,"");return e}function Jle(t){return typeof t=="string"?t:""}var yJr=5e3;function xJr(t,e,n,r){if(e===void 0||Date.now()-e<yJr)return[];let i=n?.()??null;return i===null?[]:[ot(` ${t.fg("muted",`\u29D7 ${i}`)}`,r,"\u2026")]}var Ym=class{folded=!1;component;setFolded(e){this.folded=e}capture(e){return this.component=e,e}callComponent(){return this.component}};function wJr(t){return t.length===0?0:(t.match(/\n/g)?.length??0)+(t.endsWith(`
1638
1638
  `)?0:1)}function bJr(t,e){if(!t)return"";let n=[];return t.added>0&&n.push(e.fg("toolDiffAdded",`+${t.added}`)),t.removed>0&&n.push(e.fg("toolDiffRemoved",`-${t.removed}`)),n.length>0?` ${n.join(" ")}`:""}function EJr(t,e){return t===void 0?"":` ${e.fg("toolDiffAdded",`+${t}`)}`}function d6e(t,e,n,r,i){return`${qln(mf[t],t,n)} ${Hln(e,n,r)}${bJr(i,n)}`}function vJr(t){let e=fJr();return t.startsWith(e)?`~${t.slice(e.length)}`:t}function Hln(t,e,n){if(!t)return e.fg("toolOutput","...");let r=vJr(t);if(!fo().hyperlinks)return r;let i=mJr(t)?t:gJr(n,t);return Pu(r,AJr(i).href)}function qln(t,e,n){return`${n.fg("accent",t)} ${n.fg("toolTitle",n.bold(e))}`}var l6e=class{child;prefix;constructor(e,n){this.child=e,this.prefix=n}update(e,n){this.child=e,this.prefix=n}invalidate(){this.child.invalidate()}render(e){let n=Ce(this.prefix),r=this.child.render(Math.max(1,e-n));return r.length===0?[ot(this.prefix.trimEnd(),e,"")]:r.map((i,o)=>o===0?ot(`${this.prefix}${i}`,e,""):i)}};function Gln(t,e=new Ym){let n=h8(t);return{name:"read",label:"read",description:"Render read calls with a crtr icon header in the attach viewer.",parameters:{},renderCall(r,i,o){let s=r,a=Jle(s?.file_path??s?.path),c="";if(s?.offset!==void 0||s?.limit!==void 0){let d=typeof s?.offset=="number"?s.offset:1,p=typeof s?.limit=="number"?d+s.limit-1:void 0;c=i.fg("warning",`:${d}${p!==void 0?`-${p}`:""}`)}let u=`${qln(mf.read,"read",i)} ${Hln(a,i,o.cwd??t)}${c}`,l=o.lastComponent??new ve("",0,0);return l.setText(u),e.capture(l)},renderResult(r,i,o,s){return n.renderResult(r,i,o,s)}}}function jln(t,e=new Ym){let n=f8(t),r,i;return{name:"write",label:"write",description:"Render write calls with a crtr icon header in the attach viewer.",parameters:{},renderCall(o,s,a){if(e.folded){let u=o,l=a.isError?void 0:wJr(Jle(u?.content)),d=d6e("write",Jle(u?.file_path??u?.path),s,a.cwd??t)+EJr(l,s);return e.capture(new ve(d,0,0))}r=n.renderCall(o,s,{...a,lastComponent:r});let c=`${s.fg("accent",mf.write)} `;return i?i.update(r,c):i=new l6e(r,c),e.capture(i)},renderResult(o,s,a,c){return n.renderResult(o,s,a,c)}}}var SJr=/^(&&|\|\||\||;|>>|>|<|2>&1|&)$/;function _Jr(t){return t.match(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+/g)??[]}function Wln(t,e){let n=_Jr(t),r=!0;return n.map(o=>SJr.test(o)?(r=!0,e.fg("syntaxOperator",o)):r&&!o.includes("=")?(r=!1,e.fg("syntaxFunction",e.bold(o))):(r=!1,o.startsWith("-")?e.fg("muted",o):/^["']/.test(o)?e.fg("syntaxString",o):e.fg("toolOutput",o))).join(" ")}var dj=class{command="";purpose;expanded=!1;folded=!1;timeout;theme;startedAt;hint;invalidate(){}update(e,n,r,i,o,s,a,c){this.theme=e,this.command=n,this.purpose=r,this.expanded=i,this.folded=o,this.timeout=s,this.startedAt=a,this.hint=c}backgroundHintLines(e){let n=this.theme;return n===void 0?[]:xJr(n,this.startedAt,this.hint,e)}render(e){let n=this.theme;if(!n)return[];let r=n.fg("accent",mf.bash);if(this.purpose!==void 0)return[ot(`${r} ${n.fg("toolOutput",this.purpose)}`,e,"\u2026")];let i=this.command.split(`
1639
1639
  `).map(p=>p.trim()).filter(p=>p.length>0),o=this.folded?i.map(Qln):i,s=this.timeout?n.fg("muted",` (timeout ${this.timeout}s)`):"";if(o.length===0)return[`${r} ${n.fg("toolOutput","...")}`];if(this.expanded){let p=Ce(`${r} `),h=" ".repeat(p),f=Math.max(1,e-p),m=[];for(let g=0;g<o.length;g++){let y=Wln(o[g],n);g===o.length-1&&(y+=s);let w=Bo(y,f);for(let E=0;E<w.length;E++)m.push(`${g===0&&E===0?`${r} `:h}${w[E]}`)}return m.map(g=>ot(g,e,""))}let a=o.length>1?n.fg("muted",` +${o.length-1} lines`):"",c=Ce(`${r} `)+Ce(a)+Ce(s),u=Math.max(8,e-c),l=o[0],d=l.length>u?`${l.slice(0,Math.max(1,u-1))}\u2026`:l;return[ot(`${r} ${Wln(d,n)}${a}${s}`,e)]}};function zln(t,e){return t instanceof dj?t.backgroundHintLines(e):[]}function Vln(t,e=new Ym,n){let r=u8(t);return{name:"bash",label:"bash",description:"Render plain bash calls as a compact styled command line in the attach viewer.",parameters:{},renderCall(i,o,s){let a=i,c=s.state;c&&s.executionStarted&&c.startedAt===void 0&&(c.startedAt=Date.now(),c.endedAt=void 0);let u=s.lastComponent instanceof dj?s.lastComponent:new dj,l=c?.startedAt!==void 0&&c.endedAt===void 0;return u.update(o,Jle(a?.command),e.folded?a6e(a?.purpose)??void 0:void 0,!!s.expanded&&!e.folded,e.folded,typeof a?.timeout=="number"?a.timeout:void 0,l?c?.startedAt:void 0,n),e.capture(u)},renderResult(i,o,s,a){return r.renderResult(i,o,s,a)}}}var CJr=20,p6e=CJr-3,Kln=/<<-?\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\1/g,rdn=/(?:^|[\n;&|()]\s*)(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)*(?:[^\s;&|()]+\/)?(?:crtr|crouter)(?=\s|$)/,idn="crtr-output";function odn(t){let e=t.split(`
@@ -1673,7 +1673,7 @@ ${dXr(e)}
1673
1673
 
1674
1674
  `)}registerCopyBlock(e,n,r){let i=this.condensedCopyBlocks.get(this.appendTarget);if(i){let s=i.findIndex(a=>a.block===e);s===-1?i.push({block:e,kind:n,text:r}):i[s].text=r;return}let o=this.copyIndex.get(e);o===void 0?(this.copyIndex.set(e,this.copyBlockRecords.length),this.copyBlockRecords.push({block:e,kind:n,text:r})):this.copyBlockRecords[o].text=r}unregisterCopyBlock(e){let n=this.condensedCopyBlocks.get(this.appendTarget);if(n){let i=n.findIndex(o=>o.block===e);i!==-1&&n.splice(i,1);return}let r=this.copyIndex.get(e);if(r!==void 0){this.copyBlockRecords.splice(r,1),this.copyIndex.delete(e);for(let i=r;i<this.copyBlockRecords.length;i++)this.copyIndex.set(this.copyBlockRecords[i].block,i)}}appendCondensedBlock({component:e,copyBlocks:n}){this.outsideTurns++;try{this.append(e)}finally{this.outsideTurns--}this.registerCopyBlock(e,"condensed",n.map(r=>r.text).filter(r=>r.trim()!=="").join(`
1675
1675
 
1676
- `))}toolResultText(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"content"in e){let n=e.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.filter(r=>typeof r=="object"&&r!==null&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("")}try{let n=JSON.stringify(e);return typeof n=="string"?n:""}catch{return""}}pushTranscriptText(e){let n=e.trim();if(n==="")return;let r=[...new Set(Pon(n).reverse())];if(r.length>0){let s=[...r,...this.transcriptDocRefs.filter(a=>!r.includes(a))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...s)}let i=x6e([n],this.cwd);if(i.length===0)return;let o=[...i,...this.transcriptFilePaths.filter(s=>!i.includes(s))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...o)}pushTranscriptValue(e){try{let n=typeof e=="string"?e:JSON.stringify(e);typeof n=="string"&&this.pushTranscriptText(n)}catch{}}userMessageText(e){let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.filter(r=>typeof r=="object"&&r!==null&&r.type==="text").map(r=>r.text).join(""):""}};var _Zr="\x1B[2m\u2338 image \u2014 scroll to view\x1B[22m",xj={first:-1,last:-1,lastFullyVisible:-1};function CZr(t){return t.some(e=>e.includes("\x1B_G")||e.includes("\x1B]1337;File="))}function IZr(t,e,n){let r=0,i=t.blockCount();for(;r<i;){let o=Math.floor((r+i)/2);t.blockStart(o,n)+t.blockHeight(o,n)>e?i=o:r=o+1}return r}function qdn(t,e){let n={follow:!0,anchor:void 0},r,i=0,o=xj,s;function a(l,d,p){let h=Math.max(0,p-d);if(n.follow)return h;if(!n.anchor)return n.follow=!0,h;let f=t.anchorLine(n.anchor,l);return f===void 0?(n.follow=!0,n.anchor=void 0,h):Math.min(Math.max(0,f),h)}function c(l,d,p,h){let f=Math.min(p,h+d);if(h>=f)return{top:h,bottom:f,total:p,blocks:xj};let m=t.blockCount(),g=IZr(t,h,l),y=-1,w=-1,E=-1;for(;g<m;){let S=t.blockStart(g,l);if(S>=f)break;let C=t.blockHeight(g,l),I=S+C;I>h&&(y===-1&&(y=g),w=g,S>=h&&I<=f&&(E=g)),g++}return{top:h,bottom:f,total:p,blocks:y===-1?xj:{first:y,last:w,lastFullyVisible:E}}}function u(){if(r===void 0||i<=0)return;let l=t.totalHeight(r),d=a(r,i,l);return c(r,i,l,d)}return{renderSlice(l,d){let p=Math.max(0,d);if(r=l,i=p,p===0)return o=xj,s=t.revision(),[];let h=t.totalHeight(l),f=a(l,p,h),m=c(l,p,h,f),g=[];for(let w=m.blocks.first;w!==-1&&w<=m.blocks.last;w++){let E=t.blockStart(w,l),S=t.blockLines(w,l),C=t.blockHeight(w,l),I=E+C,M=Math.max(0,m.top-E),D=Math.min(C,m.bottom-E);if(M>=D)continue;if((E<m.top||I>m.bottom)&&CZr(S))g.push(...Array(D-M).fill(_Zr));else if(e===void 0)g.push(...S.slice(M,D));else for(let L=M;L<D;L++)g.push(e(E+L,S[L],l))}let y=g.length>=p?g.slice(0,p):[...Array(p-g.length).fill(""),...g];return o=m.blocks,s=t.revision(),y},scrollBy(l){if(r===void 0||i<=0||l===0)return!1;let d=n.follow,p=n.anchor,h=t.totalHeight(r),f=a(r,i,h),m=Math.max(0,h-i),g=Math.min(Math.max(0,f+l),m);return g>=m?(n.follow=!0,n.anchor=void 0):(n.follow=!1,n.anchor=t.anchorAt(g,r),n.anchor||(n.follow=!0)),n.follow!==d||n.anchor!==p},pageRows(){return Math.max(0,i-1)},goLive(){n.follow=!0,n.anchor=void 0},scrollToLine(l){if(r===void 0||i<=0)return;let d=t.totalHeight(r),p=Math.max(0,d-i),h=Math.min(Math.max(0,l-Math.floor(i/3)),p);if(h>=p){n.follow=!0,n.anchor=void 0;return}n.follow=!1,n.anchor=t.anchorAt(h,r),n.anchor||(n.follow=!0)},topLine(){if(!(r===void 0||i<=0))return a(r,i,t.totalHeight(r))},isLive(){return n.follow},visibleBlocks(){let l=t.revision();return s===l||(o=u()?.blocks??xj,s=l),o},invalidate(){t.invalidate()}}}var kZr=new Intl.Segmenter(void 0,{granularity:"grapheme"}),TZr="\x1B[7m",RZr="\x1B[27m";function MZr(t,e){let n=t[e+1];if(n!==void 0){if(n==="]"||n==="_"||n==="P"||n==="^"){let r=t.indexOf("\x07",e+2),i=t.indexOf("\x1B\\",e+2),o=r===-1?i:i===-1?r:Math.min(r,i);return o===-1?void 0:{text:t.slice(e,o+(o===r?1:2)),end:o+(o===r?1:2)}}if(n==="["){let r=e+2;for(;r<t.length&&(t.charCodeAt(r)<64||t.charCodeAt(r)>126);)r++;return r>=t.length?void 0:{text:t.slice(e,r+1),end:r+1}}return{text:t.slice(e,e+2),end:e+2}}}function hde(t,e){let n=0,r=0;for(;r<t.length;){if(t[r]==="\x1B"){let s=MZr(t,r);if(s===void 0)break;e.onEscape?.(s.text),r=s.end;continue}let i=t.indexOf("\x1B",r),o=t.slice(r,i===-1?void 0:i);for(let s of kZr.segment(o)){let a=Ws(s.segment);e.onGlyph?.({text:s.segment,cell:n,width:a}),n+=a}r=i===-1?t.length:i}return n}function Gdn(t,e,n){let r="";return hde(t,{onGlyph:i=>{i.cell>=e&&i.cell<n&&(r+=i.text)}}),r}var PZr={on:TZr,off:RZr};function v6e(t,e,n,r,i=PZr){let o=Math.min(n,r);if(o<=e||e<0)return t;let s="",a=!1,c=[],u=()=>{a||(s+=i.on,a=!0)},l=()=>{a&&(s+=i.restore===!0?`\x1B[0m${c.join("")}`:i.off,a=!1)},d=hde(t,{onEscape:p=>{s+=p,p.endsWith("m")&&(p==="\x1B[0m"||p==="\x1B[m"?c.length=0:c.push(p),a&&(s+=i.on))},onGlyph:p=>{p.cell>=e&&p.cell<o?u():l(),s+=p.text}});if(l(),d<o){let p=Math.max(0,e-d),h=o-Math.max(e,d);s+=" ".repeat(p)+i.on+" ".repeat(h)+(i.restore===!0?"\x1B[0m":i.off)}return s}function jdn(t,e,n,r){return v6e(t,e,n,r)}var DZr={on:"\x1B[107m\x1B[30m",off:"",restore:!0},BZr={on:"\x1B[48;5;214m\x1B[30m",off:"",restore:!0};function LZr(t){let e="",n=[],r=hde(t,{onGlyph:i=>{for(let o=0;o<i.text.length;o++)n.push(i.cell);e+=i.text}});return{text:e,cells:n,width:r}}function OZr(t){return t!==t.toLowerCase()}function NZr(t,e,n,r,i){let o=n?t.text:t.text.toLowerCase(),s=n?e:e.toLowerCase(),a=o.indexOf(s);for(;a!==-1;){let c=a+s.length,u=t.cells[a]??0,l=c<t.cells.length?t.cells[c]:t.width;l>u&&i.push({line:r,from:u,to:l}),a=o.indexOf(s,a+Math.max(1,s.length))}}function zdn(t){let e="",n=0,r=[],i=new Map,o,s;function a(c){let u=`${c}:${t.revision()}:${e}`;if(o===u)return r;let l=[];if(e!==""){let p=OZr(e),h=t.blockCount();for(let f=0;f<h;f++){let m=t.blockStart(f,c),g=t.blockLines(f,c);for(let y=0;y<g.length;y++){let w=g[y];w.toLowerCase().includes(e.toLowerCase())&&NZr(LZr(w),e,p,m+y,l)}}}let d=new Map;for(let p of l){let h=d.get(p.line);h?h.push(p):d.set(p.line,[p])}if(r=l,i=d,o=u,s!==void 0){let p=s;s=void 0;let h=l.findIndex(f=>f.line>=p);n=h===-1?Math.max(0,l.length-1):h}else n>=l.length&&(n=Math.max(0,l.length-1));return r}return{setQuery(c,u){c!==e&&(e=c,s=u,o=void 0)},query(){return e},matches(c){return a(c)},current(c){return a(c)[n]},status(c){let u=a(c);return{index:u.length===0?0:n+1,total:u.length}},step(c,u){let l=a(c);if(l.length!==0)return n=(n+u+l.length)%l.length,l[n]},selectNear(c,u){let l=a(c);if(l.length===0)return;let d=l.findIndex(p=>p.line>=u);return n=d===-1?l.length-1:d,l[n]},decorate(c,u,l){if(e==="")return u;let d=a(l),p=i.get(c);if(p===void 0)return u;let h=d[n],f=u;for(let m of p)f=v6e(f,m.from,m.to,l,m===h?BZr:DZr);return f}}}tt();import{join as KZr}from"node:path";var Vdn="38;5;243";var $Zr={active:"\u25CF",idle:"\u25CB",done:"\u2713",dead:"\u2717",canceled:"\u2298"},FZr={active:"32",idle:"33",done:"36",dead:"31",canceled:Vdn},UZr="\u27F3",QZr="92",WZr="\u25CC",HZr="94",qZr="\u26A0",GZr="33";function Kdn(t){switch(t){case"rate-limit":return"rate-limited";case"overloaded":return"overloaded";case"connection":return"down";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"wedged":return"wedged";case"model-not-found":return"model-not-found";default:return"other"}}function Ydn(t){return t.frozen_at!=null&&t.pi_pid==null}function CT(t,e){return e.hanging!=null?{glyph:qZr,color:GZr,word:Kdn(e.hanging.kind),bold:!0}:e.frozen===!0?{glyph:WZr,color:HZr,word:"frozen"}:e.streaming===!0?{glyph:UZr,color:QZr,word:"live",bold:!0}:{glyph:$Zr[t]??"?",color:FZr[t]}}function jZr(t,e){let n=Date.parse(t);if(Number.isNaN(n))return"now";let r=n-e;return r<=0?"now":r>=6e4?`${Math.max(1,Math.round(r/6e4))}m`:`${Math.max(1,Math.ceil(r/1e3))}s`}function zZr(t){return t.retry.disposition!=="auto"}function VZr(t,e=Date.now()){let n=t.retry;if(!zZr(t)){if(n.by==="client")return"redialing";let r=typeof n.attempt=="number"&&typeof n.max=="number"?`auto-retry ${n.attempt}/${n.max}`:"auto-retrying";return n.nextAt?`${r}, next ${jZr(n.nextAt,e)}`:r}return"needs you"}function Jdn(t,e=Date.now()){return`${t.link} ${Kdn(t.kind)} \xB7 ${VZr(t,e)}`}var Xdn=30,Rp="\x1B[",Ur=`${Rp}0m`,wj=`${Rp}1m`,qc=`${Rp}2m`,Hv=`${Rp}7m`,Zdn=`${Rp}48;5;22m`,fde=`${Rp}32m`,jPs=`${Rp}31m`,bj=`${Rp}33m`,zPs=`${Rp}36m`,VPs=`${Rp}90m`;function YZr(t){return t.status!=="active"&&t.status!=="idle"?!1:t.streaming===!0}function mde(t){if(t===null)return"?";let e=CT(t.status,{streaming:YZr(t),frozen:Ydn(t),hanging:t.fault??null});return`${Rp}${e.color}m${e.glyph}${Ur}`}var epn=/\x1b\[[0-9;]*m/g;function IT(t){return t.replace(epn,"")}function kd(t){return t.replace(epn,"").length}function Px(t,e=yf()){if(kd(t)<=e)return t;let n="",r=0,i=0;for(;i<t.length&&r<e-1;){if(t[i]==="\x1B"){let o=/^\x1b\[[0-9;]*m/.exec(t.slice(i));if(o){n+=o[0],i+=o[0].length;continue}}n+=t[i],r++,i++}return`${n}\u2026${Ur}`}function yf(){return Math.max(20,Math.min((process.stdout.columns??80)-2,180))}function Dx(t,e,n){let r=Px(t,e),i=r.replace(/\x1b\[0m/g,`${Ur}${n}`),o=Math.max(0,e-kd(r));return`${n}${i}${" ".repeat(o)}${Ur}`}function JZr(t){return t<1e3?`${t}`:`${Math.round(t/1e3)}k`}function gde(t,e=!1){return JZr(e?0:t?.telemetry_context_tokens??0)}function Ade(t,e=!1){if(e||t?.status!=="active")return"";let n=(t.telemetry_last_activity??"").trim();return n===""?"":` ${qc}\xB7 ${n}${Ur}`}function yde(t){let e=t?.cycles??0;return e>0?` ${qc}\u27F3${e}${Ur}`:""}function kT(t,e){if(t===null)return xde(e);let n=t.name&&t.name!==t.kind?t.name:"";if(n!=="")return n;let r=(t.description??"").trim();return r!==""?r:t.name}function xde(t){return t.slice(0,8)}function XZr(t,e,n=!1){if(n||e?.status!=="active")return!1;try{let r=JSON.parse(z3(tR(t),KZr(dYe(t),"attach.json")).toString("utf8"));return typeof r.viewers=="number"&&r.viewers>0}catch{return!1}}function tpn(t,e,n,r=!1){return r?!1:n.has(t)?!0:XZr(t,e,r)}function wde(t,e){let n=e[t]??0;return n>0?` ${bj}\u2691${n}${Ur}`:""}var KPs=`${qc}jk move \xB7 hl fold \xB7 \u21B5 focus \xB7 e expand \xB7 x kill \xB7 m mgr \xB7 esc${Ur}`;tt();var ZZr=["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live","crtr.attach.mouse.toggle","crtr.attach.copy.message"];function TT(t,e,n){return IS(t,e,CS(n),(r,i)=>nt(r,i))}function S6e(t,e){e[t]()}function npn(t,e,n){for(let{actionId:r}of cg)if(TT(t,r,e))return S6e(r,n),!0;return!1}function rpn(t,e,n){for(let r of ZZr)if(TT(t,r,e))return n[r](),!0;return!1}function ipn(t){for(let e of["crtr.attach.clear-or-detach","crtr.attach.detach"])if(t.gestures(e).length>0)return Gs(t,e)}function opn(t){return t.gestures("crtr.attach.detach").length>0?Gs(t,"crtr.attach.detach"):void 0}function _6e(t,e,n,r){let i=t();if(e(i.bindings),n())try{r(i.bindings,i.tmuxPassthrough)}catch{}return i}function spn(t){if(t!==""){for(let e of t){let n=e.codePointAt(0);if(n<32||n===127)return}return t}}function apn(t,e,n,r,i){let o="closed",s=0,a="",c=()=>t.terminal.columns,u=g=>{g!==void 0&&n.scrollToLine(g.line),t.requestRender()},l=()=>{r.setQuery(a,s),u(r.current(c()))},d=()=>{o="closed",a="",r.setQuery("",void 0),t.requestRender()},p=()=>{o==="closed"&&(s=n.topLine()??0),o="editing",a=r.query(),t.requestRender()},h=g=>{let y=r.step(c(),g);if(y===void 0){i.setNotice(`No matches for \u201C${r.query()}\u201D`);return}u(y)};return{component:{render(g){if(o==="closed")return[];let{index:y,total:w}=r.status(g),E=o==="editing"?`${e.accent("\u2315")} ${a}${e.accent("\u258C")}`:`${e.accent("\u2315")} ${a}`,S=w===0?r.query()===""?e.faint("type to search what is on screen"):e.error("no matches"):e.info(`${y}/${w}`),C=o==="editing"?e.faint("enter browse \xB7 esc cancel"):e.faint([`${Gs(i.bindings(),"crtr.attach.search.next")} next`,`${Gs(i.bindings(),"crtr.attach.search.previous")} prev`,`${Gs(i.bindings(),"crtr.attach.search.edit")} edit`,`${Gs(i.bindings(),"crtr.attach.search.close")} close`].join(" \xB7 ")),I=`${S} ${C}`,M=g-kd(E)-kd(I)-2;return[M<1?ot(` ${E}`,g,"",!0):` ${E}${" ".repeat(M)}${I} `]},invalidate(){}},open:p,close:d,handleKey:g=>{if(o==="closed")return!1;let y=i.bindings();if(TT(y,"crtr.attach.search.close",g))return d(),!0;if(o==="editing"){if(g==="")return d(),!0;if(g==="\r"||g===`
1676
+ `))}toolResultText(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"content"in e){let n=e.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.filter(r=>typeof r=="object"&&r!==null&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("")}try{let n=JSON.stringify(e);return typeof n=="string"?n:""}catch{return""}}pushTranscriptText(e){let n=e.trim();if(n==="")return;let r=[...new Set(Pon(n).reverse())];if(r.length>0){let s=[...r,...this.transcriptDocRefs.filter(a=>!r.includes(a))].slice(0,50);this.transcriptDocRefs.splice(0,this.transcriptDocRefs.length,...s)}let i=x6e([n],this.cwd);if(i.length===0)return;let o=[...i,...this.transcriptFilePaths.filter(s=>!i.includes(s))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...o)}pushTranscriptValue(e){try{let n=typeof e=="string"?e:JSON.stringify(e);typeof n=="string"&&this.pushTranscriptText(n)}catch{}}userMessageText(e){let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.filter(r=>typeof r=="object"&&r!==null&&r.type==="text").map(r=>r.text).join(""):""}};var _Zr="\x1B[2m\u2338 image \u2014 scroll to view\x1B[22m",xj={first:-1,last:-1,lastFullyVisible:-1};function CZr(t){return t.some(e=>e.includes("\x1B_G")||e.includes("\x1B]1337;File="))}function IZr(t,e,n){let r=0,i=t.blockCount();for(;r<i;){let o=Math.floor((r+i)/2);t.blockStart(o,n)+t.blockHeight(o,n)>e?i=o:r=o+1}return r}function qdn(t,e){let n={follow:!0,anchor:void 0},r,i=0,o=xj,s;function a(l,d,p){let h=Math.max(0,p-d);if(n.follow)return h;if(!n.anchor)return n.follow=!0,h;let f=t.anchorLine(n.anchor,l);return f===void 0?(n.follow=!0,n.anchor=void 0,h):Math.min(Math.max(0,f),h)}function c(l,d,p,h){let f=Math.min(p,h+d);if(h>=f)return{top:h,bottom:f,total:p,blocks:xj};let m=t.blockCount(),g=IZr(t,h,l),y=-1,w=-1,E=-1;for(;g<m;){let S=t.blockStart(g,l);if(S>=f)break;let C=t.blockHeight(g,l),I=S+C;I>h&&(y===-1&&(y=g),w=g,S>=h&&I<=f&&(E=g)),g++}return{top:h,bottom:f,total:p,blocks:y===-1?xj:{first:y,last:w,lastFullyVisible:E}}}function u(){if(r===void 0||i<=0)return;let l=t.totalHeight(r),d=a(r,i,l);return c(r,i,l,d)}return{renderSlice(l,d){let p=Math.max(0,d);if(r=l,i=p,p===0)return o=xj,s=t.revision(),[];let h=t.totalHeight(l),f=a(l,p,h),m=c(l,p,h,f),g=[];for(let w=m.blocks.first;w!==-1&&w<=m.blocks.last;w++){let E=t.blockStart(w,l),S=t.blockLines(w,l),C=t.blockHeight(w,l),I=E+C,M=Math.max(0,m.top-E),D=Math.min(C,m.bottom-E);if(M>=D)continue;if((E<m.top||I>m.bottom)&&CZr(S))g.push(...Array(D-M).fill(_Zr));else if(e===void 0)g.push(...S.slice(M,D));else for(let L=M;L<D;L++)g.push(e(E+L,S[L],l))}let y=g.length>=p?g.slice(0,p):[...Array(p-g.length).fill(""),...g];return o=m.blocks,s=t.revision(),y},scrollBy(l){if(r===void 0||i<=0||l===0)return!1;let d=n.follow,p=n.anchor,h=t.totalHeight(r),f=a(r,i,h),m=Math.max(0,h-i),g=Math.min(Math.max(0,f+l),m);return g>=m?(n.follow=!0,n.anchor=void 0):(n.follow=!1,n.anchor=t.anchorAt(g,r),n.anchor||(n.follow=!0)),n.follow!==d||n.anchor!==p},pageRows(){return Math.max(0,i-1)},goLive(){n.follow=!0,n.anchor=void 0},scrollToLine(l){if(r===void 0||i<=0)return;let d=t.totalHeight(r),p=Math.max(0,d-i),h=Math.min(Math.max(0,l-Math.floor(i/3)),p);if(h>=p){n.follow=!0,n.anchor=void 0;return}n.follow=!1,n.anchor=t.anchorAt(h,r),n.anchor||(n.follow=!0)},topLine(){if(!(r===void 0||i<=0))return a(r,i,t.totalHeight(r))},isLive(){return n.follow},visibleBlocks(){let l=t.revision();return s===l||(o=u()?.blocks??xj,s=l),o},invalidate(){t.invalidate()}}}var kZr=new Intl.Segmenter(void 0,{granularity:"grapheme"}),TZr="\x1B[7m",RZr="\x1B[27m";function MZr(t,e){let n=t[e+1];if(n!==void 0){if(n==="]"||n==="_"||n==="P"||n==="^"){let r=t.indexOf("\x07",e+2),i=t.indexOf("\x1B\\",e+2),o=r===-1?i:i===-1?r:Math.min(r,i);return o===-1?void 0:{text:t.slice(e,o+(o===r?1:2)),end:o+(o===r?1:2)}}if(n==="["){let r=e+2;for(;r<t.length&&(t.charCodeAt(r)<64||t.charCodeAt(r)>126);)r++;return r>=t.length?void 0:{text:t.slice(e,r+1),end:r+1}}return{text:t.slice(e,e+2),end:e+2}}}function hde(t,e){let n=0,r=0;for(;r<t.length;){if(t[r]==="\x1B"){let s=MZr(t,r);if(s===void 0)break;e.onEscape?.(s.text),r=s.end;continue}let i=t.indexOf("\x1B",r),o=t.slice(r,i===-1?void 0:i);for(let s of kZr.segment(o)){let a=Ws(s.segment);e.onGlyph?.({text:s.segment,cell:n,width:a}),n+=a}r=i===-1?t.length:i}return n}function Gdn(t,e,n){let r="";return hde(t,{onGlyph:i=>{i.cell>=e&&i.cell<n&&(r+=i.text)}}),r}var PZr={on:TZr,off:RZr};function v6e(t,e,n,r,i=PZr){let o=Math.min(n,r);if(o<=e||e<0)return t;let s="",a=!1,c=[],u=()=>{a||(s+=i.on,a=!0)},l=()=>{a&&(s+=i.restore===!0?`\x1B[0m${c.join("")}`:i.off,a=!1)},d=hde(t,{onEscape:p=>{s+=p,p.endsWith("m")&&(p==="\x1B[0m"||p==="\x1B[m"?c.length=0:c.push(p),a&&(s+=i.on))},onGlyph:p=>{p.cell>=e&&p.cell<o?u():l(),s+=p.text}});if(l(),d<o){let p=Math.max(0,e-d),h=o-Math.max(e,d);s+=" ".repeat(p)+i.on+" ".repeat(h)+(i.restore===!0?"\x1B[0m":i.off)}return s}function jdn(t,e,n,r){return v6e(t,e,n,r)}var DZr={on:"\x1B[107m\x1B[30m",off:"",restore:!0},BZr={on:"\x1B[48;5;214m\x1B[30m",off:"",restore:!0};function LZr(t){let e="",n=[],r=hde(t,{onGlyph:i=>{for(let o=0;o<i.text.length;o++)n.push(i.cell);e+=i.text}});return{text:e,cells:n,width:r}}function OZr(t){return t!==t.toLowerCase()}function NZr(t,e,n,r,i){let o=n?t.text:t.text.toLowerCase(),s=n?e:e.toLowerCase(),a=o.indexOf(s);for(;a!==-1;){let c=a+s.length,u=t.cells[a]??0,l=c<t.cells.length?t.cells[c]:t.width;l>u&&i.push({line:r,from:u,to:l}),a=o.indexOf(s,a+Math.max(1,s.length))}}function zdn(t){let e="",n=0,r=[],i=new Map,o,s;function a(c){let u=`${c}:${t.revision()}:${e}`;if(o===u)return r;let l=[];if(e!==""){let p=OZr(e),h=t.blockCount();for(let f=0;f<h;f++){let m=t.blockStart(f,c),g=t.blockLines(f,c);for(let y=0;y<g.length;y++){let w=g[y];w.toLowerCase().includes(e.toLowerCase())&&NZr(LZr(w),e,p,m+y,l)}}}let d=new Map;for(let p of l){let h=d.get(p.line);h?h.push(p):d.set(p.line,[p])}if(r=l,i=d,o=u,s!==void 0){let p=s;s=void 0;let h=l.findIndex(f=>f.line>=p);n=h===-1?Math.max(0,l.length-1):h}else n>=l.length&&(n=Math.max(0,l.length-1));return r}return{setQuery(c,u){c!==e&&(e=c,s=u,o=void 0)},query(){return e},matches(c){return a(c)},current(c){return a(c)[n]},status(c){let u=a(c);return{index:u.length===0?0:n+1,total:u.length}},step(c,u){let l=a(c);if(l.length!==0)return n=(n+u+l.length)%l.length,l[n]},selectNear(c,u){let l=a(c);if(l.length===0)return;let d=l.findIndex(p=>p.line>=u);return n=d===-1?l.length-1:d,l[n]},decorate(c,u,l){if(e==="")return u;let d=a(l),p=i.get(c);if(p===void 0)return u;let h=d[n],f=u;for(let m of p)f=v6e(f,m.from,m.to,l,m===h?BZr:DZr);return f}}}tt();import{join as KZr}from"node:path";var Vdn="38;5;243";var $Zr={active:"\u25CF",idle:"\u25CB",done:"\u2713",dead:"\u2717",canceled:"\u2298"},FZr={active:"32",idle:"33",done:"36",dead:"31",canceled:Vdn},UZr="\u27F3",QZr="92",WZr="\u25CC",HZr="94",qZr="\u26A0",GZr="33";function Kdn(t){switch(t){case"rate-limit":return"rate-limited";case"overloaded":return"overloaded";case"connection":return"down";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"wedged":return"wedged";case"model-not-found":return"model-not-found";default:return"other"}}function Ydn(t){return t.frozen_at!=null&&t.pi_pid==null}function CT(t,e){return e.hanging!=null?{glyph:qZr,color:GZr,word:Kdn(e.hanging.kind),bold:!0}:e.frozen===!0?{glyph:WZr,color:HZr,word:"frozen"}:e.streaming===!0?{glyph:UZr,color:QZr,word:"live",bold:!0}:{glyph:$Zr[t]??"?",color:FZr[t]}}function jZr(t,e){let n=Date.parse(t);if(Number.isNaN(n))return"now";let r=n-e;return r<=0?"now":r>=6e4?`${Math.max(1,Math.round(r/6e4))}m`:`${Math.max(1,Math.ceil(r/1e3))}s`}function zZr(t){return t.retry.disposition!=="auto"}function VZr(t,e=Date.now()){let n=t.retry;if(!zZr(t)){if(n.by==="client")return"redialing";let r=typeof n.attempt=="number"&&typeof n.max=="number"?`auto-retry ${n.attempt}/${n.max}`:"auto-retrying";return n.nextAt?`${r}, next ${jZr(n.nextAt,e)}`:r}return"needs you"}function Jdn(t,e=Date.now()){return`${t.link} ${Kdn(t.kind)} \xB7 ${VZr(t,e)}`}var Xdn=30,Rp="\x1B[",Ur=`${Rp}0m`,wj=`${Rp}1m`,qc=`${Rp}2m`,Hv=`${Rp}7m`,Zdn=`${Rp}48;5;22m`,fde=`${Rp}32m`,VPs=`${Rp}31m`,bj=`${Rp}33m`,KPs=`${Rp}36m`,YPs=`${Rp}90m`;function YZr(t){return t.status!=="active"&&t.status!=="idle"?!1:t.streaming===!0}function mde(t){if(t===null)return"?";let e=CT(t.status,{streaming:YZr(t),frozen:Ydn(t),hanging:t.fault??null});return`${Rp}${e.color}m${e.glyph}${Ur}`}var epn=/\x1b\[[0-9;]*m/g;function IT(t){return t.replace(epn,"")}function kd(t){return t.replace(epn,"").length}function Px(t,e=yf()){if(kd(t)<=e)return t;let n="",r=0,i=0;for(;i<t.length&&r<e-1;){if(t[i]==="\x1B"){let o=/^\x1b\[[0-9;]*m/.exec(t.slice(i));if(o){n+=o[0],i+=o[0].length;continue}}n+=t[i],r++,i++}return`${n}\u2026${Ur}`}function yf(){return Math.max(20,Math.min((process.stdout.columns??80)-2,180))}function Dx(t,e,n){let r=Px(t,e),i=r.replace(/\x1b\[0m/g,`${Ur}${n}`),o=Math.max(0,e-kd(r));return`${n}${i}${" ".repeat(o)}${Ur}`}function JZr(t){return t<1e3?`${t}`:`${Math.round(t/1e3)}k`}function gde(t,e=!1){return JZr(e?0:t?.telemetry_context_tokens??0)}function Ade(t,e=!1){if(e||t?.status!=="active")return"";let n=(t.telemetry_last_activity??"").trim();return n===""?"":` ${qc}\xB7 ${n}${Ur}`}function yde(t){let e=t?.cycles??0;return e>0?` ${qc}\u27F3${e}${Ur}`:""}function kT(t,e){if(t===null)return xde(e);let n=t.name&&t.name!==t.kind?t.name:"";if(n!=="")return n;let r=(t.description??"").trim();return r!==""?r:t.name}function xde(t){return t.slice(0,8)}function XZr(t,e,n=!1){if(n||e?.status!=="active")return!1;try{let r=JSON.parse(z3(tR(t),KZr(dYe(t),"attach.json")).toString("utf8"));return typeof r.viewers=="number"&&r.viewers>0}catch{return!1}}function tpn(t,e,n,r=!1){return r?!1:n.has(t)?!0:XZr(t,e,r)}function wde(t,e){let n=e[t]??0;return n>0?` ${bj}\u2691${n}${Ur}`:""}var JPs=`${qc}jk move \xB7 hl fold \xB7 \u21B5 focus \xB7 e expand \xB7 x kill \xB7 m mgr \xB7 esc${Ur}`;tt();var ZZr=["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live","crtr.attach.mouse.toggle","crtr.attach.copy.message"];function TT(t,e,n){return IS(t,e,CS(n),(r,i)=>nt(r,i))}function S6e(t,e){e[t]()}function npn(t,e,n){for(let{actionId:r}of cg)if(TT(t,r,e))return S6e(r,n),!0;return!1}function rpn(t,e,n){for(let r of ZZr)if(TT(t,r,e))return n[r](),!0;return!1}function ipn(t){for(let e of["crtr.attach.clear-or-detach","crtr.attach.detach"])if(t.gestures(e).length>0)return Gs(t,e)}function opn(t){return t.gestures("crtr.attach.detach").length>0?Gs(t,"crtr.attach.detach"):void 0}function _6e(t,e,n,r){let i=t();if(e(i.bindings),n())try{r(i.bindings,i.tmuxPassthrough)}catch{}return i}function spn(t){if(t!==""){for(let e of t){let n=e.codePointAt(0);if(n<32||n===127)return}return t}}function apn(t,e,n,r,i){let o="closed",s=0,a="",c=()=>t.terminal.columns,u=g=>{g!==void 0&&n.scrollToLine(g.line),t.requestRender()},l=()=>{r.setQuery(a,s),u(r.current(c()))},d=()=>{o="closed",a="",r.setQuery("",void 0),t.requestRender()},p=()=>{o==="closed"&&(s=n.topLine()??0),o="editing",a=r.query(),t.requestRender()},h=g=>{let y=r.step(c(),g);if(y===void 0){i.setNotice(`No matches for \u201C${r.query()}\u201D`);return}u(y)};return{component:{render(g){if(o==="closed")return[];let{index:y,total:w}=r.status(g),E=o==="editing"?`${e.accent("\u2315")} ${a}${e.accent("\u258C")}`:`${e.accent("\u2315")} ${a}`,S=w===0?r.query()===""?e.faint("type to search what is on screen"):e.error("no matches"):e.info(`${y}/${w}`),C=o==="editing"?e.faint("enter browse \xB7 esc cancel"):e.faint([`${Gs(i.bindings(),"crtr.attach.search.next")} next`,`${Gs(i.bindings(),"crtr.attach.search.previous")} prev`,`${Gs(i.bindings(),"crtr.attach.search.edit")} edit`,`${Gs(i.bindings(),"crtr.attach.search.close")} close`].join(" \xB7 ")),I=`${S} ${C}`,M=g-kd(E)-kd(I)-2;return[M<1?ot(` ${E}`,g,"",!0):` ${E}${" ".repeat(M)}${I} `]},invalidate(){}},open:p,close:d,handleKey:g=>{if(o==="closed")return!1;let y=i.bindings();if(TT(y,"crtr.attach.search.close",g))return d(),!0;if(o==="editing"){if(g==="")return d(),!0;if(g==="\r"||g===`
1677
1677
  `)return r.status(c()).total===0?(i.setNotice(a===""?"Type something to search for":`No matches for \u201C${a}\u201D`),!0):(o="browsing",t.requestRender(),!0);if(g==="\x7F"||g==="\b")return a=[...a].slice(0,-1).join(""),l(),!0;let w=spn(g);return w===void 0?!1:(a+=w,l(),!0)}return TT(y,"crtr.attach.search.next",g)||g==="\r"||g===`
1678
1678
  `?(h(1),!0):TT(y,"crtr.attach.search.previous",g)?(h(-1),!0):TT(y,"crtr.attach.search.edit",g)?(p(),!0):(spn(g)!==void 0&&d(),!1)}}}import{performance as cpn}from"node:perf_hooks";var C6e=100,eei=25,tei=.5,nei=.15;function rei(t){return 1-(1-t)*(1-t)}function upn(t,e){let n,r=0,i=0,o=0,s=()=>{n!==void 0&&clearTimeout(n),n=void 0,i=0,o=0},a=u=>{let l=Math.max(0,r+C6e-u);n=setTimeout(()=>{n=void 0,c(cpn.now(),!0)},Math.min(eei,l))},c=(u,l)=>{let d=Math.min(1,(u-r)/C6e),p=Math.round(i*rei(d)),h=p-o;if(h!==0){if(!t.scrollBy(h))return s();o=p,e()}if(d===1)return s();l&&a(u)};return{page(u){let l=cpn.now();n!==void 0&&(clearTimeout(n),n=void 0,c(l,!1));let d=i-o,p=Math.max(1,Math.round(t.pageRows()*tei)),h=(u==="up"?-1:1)*p;if(i=d+h,o=0,i===0)return s();r=l-C6e*nei,c(l,!0)},cancel:s}}import{spawnSync as lpn}from"node:child_process";var dpn=3e3;function iei(){if(process.platform==="darwin")return[["pbcopy",[]]];let t=!!process.env.WAYLAND_DISPLAY||process.env.XDG_SESSION_TYPE==="wayland",e=["xclip",["-selection","clipboard"]],n=["wl-copy",[]];return t?[n,e]:[e,n]}function I6e(t){for(let[e,n]of iei()){let r=lpn(e,n,{input:t,timeout:dpn,encoding:"utf-8"});if(r.error){if(r.error.code==="ENOENT")continue;continue}if(r.status===0)return!0}return!1}function bde(t){let e=I6e(t),n=!1;if(process.env.TMUX!==void 0){let r=lpn("tmux",["load-buffer","-w","-"],{input:t,timeout:dpn,encoding:"utf-8"});n=!r.error&&r.status===0}return{system:e,tmux:n}}function IN(t){return t!==void 0&&t.trim()!==""}function oei(t){return t.split(`
1679
1679
  `).length}function sei(t,e){if(t&&e)return"clipboard + tmux buffer";if(t)return"clipboard";if(e)return"tmux buffer"}function aei(t,e,n){let{first:r,last:i,lastFullyVisible:o}=e.visibleBlocks(),s=a=>{let c=n.blockAt(a);return c?t.blockText(c):void 0};for(let a=Math.min(i,o);a>=r;a--){let c=s(a);if(IN(c))return c}for(let a=i;a>=r;a--){let c=s(a);if(IN(c))return c}}function ppn(t,e,n){return{copy(r){let i,o;switch(r){case"message":{let u=aei(t,e,n);IN(u)&&(i={text:u,label:"message"}),o="Nothing to copy \u2014 no visible message";break}case"last-assistant":{let u=t.getLastAssistantText();IN(u)&&(i={text:u,label:"last assistant message"}),o="Nothing to copy \u2014 no assistant message yet";break}case"tool":{let u=t.getLastToolOutputText();IN(u)&&(i={text:u,label:"tool output"}),o="Nothing to copy \u2014 no tool output yet";break}case"transcript":{let u=t.getTranscriptPlainText();IN(u)&&(i={text:u,label:"transcript"}),o="Nothing to copy \u2014 transcript is empty";break}}if(!i)return o;let{system:s,tmux:a}=bde(i.text),c=sei(s,a);return c?`Copied ${i.label} (${oei(i.text)} lines) \u2014 ${c}`:"Copy failed \u2014 no clipboard tool found"}}}tt();var Ede=class extends et{render(e){let n=super.render(e);return n[0]===""?n.slice(1):n}};import{spawn as Rni}from"node:child_process";import{readFileSync as Mni,unlinkSync as Pni,writeFileSync as Dni}from"node:fs";import{tmpdir as Bni}from"node:os";import{join as Lni}from"node:path";import{StringDecoder as cei}from"node:string_decoder";function vde(t){return JSON.stringify(t)+`
@@ -1703,7 +1703,7 @@ ${e.message}`,["Yes","No"],l=>c({type:"extension_ui_response",id:e.id,confirmed:
1703
1703
  `)?t.slice(0,-1):t;return`${r}${e}
1704
1704
  ${i}
1705
1705
  ${r}
1706
- `}function nti(t,e){let n=e+2,r=o=>Math.max(1,Math.min(o-1,e)),i=t.spans.map(o=>o!==null&&(o[0]<=1||o[1]>=n));return{lines:t.lines,rows:t.rows.map((o,s)=>i[s]===!0?null:o),spans:t.spans.map((o,s)=>o===null||i[s]===!0?null:[r(o[0]),r(o[1])]),blocks:t.blocks.map(o=>({type:o.type,start:r(o.start),end:r(o.end)}))}}function Zpn(t,e,n){let r=Mx(t).length;return nti(dce(tti(t,e),n),r)}function Ide(t){let e=[],n=new Array(t.lines.length).fill(null);for(let r=0;r<t.lines.length;r++){let i=t.spans[r]??null;if(i===null){let s=t.rows[r]??null,a=s!==null?t.blocks[s]:void 0;if(a===void 0)continue;i=[a.start,a.end]}let o=e[e.length-1];o!==void 0&&o.lastRow===r-1&&o.start===i[0]&&o.end===i[1]?o.lastRow=r:e.push({start:i[0],end:i[1],firstRow:r,lastRow:r}),n[r]=e.length-1}if(e.length===0){e.push({start:t.blocks[0]?.start??1,end:t.blocks[t.blocks.length-1]?.end??1,firstRow:0,lastRow:Math.max(0,t.lines.length-1)});for(let r=0;r<n.length;r++)n[r]=0}return{units:e,rowUnits:n}}function RT(t,e){let n=-1;for(let r=0;r<t.length;r++){let i=t[r];i.start<=e&&i.end>=e&&(n===-1||i.end-i.start<t[n].end-t[n].start)&&(n=r)}if(n!==-1)return n;for(let r=0;r<t.length;r++)if(t[r].start>e)return r;return Math.max(0,t.length-1)}function j6e(t,e){for(let n=0;n<t.length;n++)if(t[n].start===e.start&&t[n].end===e.end)return n;return RT(t,e.start)}function _j(t,e,n){let r=-1,i=-1;if(t.forEach((o,s)=>{o.start<=n&&o.end>=e&&(r===-1&&(r=s),i=s)}),r===-1){let o=RT(t,e);return{lo:o,hi:o}}return{lo:r,hi:i}}import{basename as rti,dirname as ehn,join as iti}from"node:path";import{mkdirSync as oti,watch as sti,writeFileSync as nBs}from"node:fs";function z6e(t){return iti(Na(),"signals",t)}function kde(t,e){let n=z6e(t);try{oti(ehn(n),{recursive:!0,mode:448});let r=sti(ehn(n),(i,o)=>{String(o)===rti(n)&&e()});return()=>r.close()}catch(r){return console.error(`activity-signal: failed to watch "${t}": ${r instanceof Error?r.message:String(r)}`),()=>{}}}function thn(t){return kde("review-activity",t)}var Cj=class extends Error{code;details;constructor(e,n,r){super(n),this.name="ReviewDocumentError",this.code=e,this.details=r}};function nhn(t,e){return{async anchorBase(){let n=await e(()=>Ht().getReviewDocumentBase(t));return{file:n.file,text:n.anchor_base_text,docHash:n.anchor_base_sha256}},async list(){return(await e(()=>Ht().listReviewComments(t,{status:"all"}))).comments.map(cti)},async create(n){return(await RN(()=>e(()=>Ht().createReviewComment(t,{text:n.text,anchor:{line:n.line,end_line:n.endLine},doc_hash:n.docHash,actor_node_id:null})))).comment.comment_id},async edit(n){await RN(()=>e(()=>Ht().editReviewComment(n.id,{text:n.text,if_revision:n.ifRevision,actor_node_id:null})))},async resolve(n){await RN(()=>e(()=>Ht().resolveReviewComment(n,{actor_node_id:null})))},async reopen(n){await RN(()=>e(()=>Ht().reopenReviewComment(n,{actor_node_id:null})))},async remove(n){await RN(()=>e(()=>Ht().deleteReviewComment(n,{actor_node_id:null})))},async remapRanges(n){await RN(()=>e(()=>Ht().updateReviewCommentRanges(t,{from_doc_hash:n.fromDocHash,to_doc_hash:n.toDocHash,entries:n.entries.map(r=>"detached"in r?{comment_id:r.id,detached:!0}:{comment_id:r.id,anchor:{line:r.anchor.line,end_line:r.anchor.endLine}})})))},async fork(n){let r=await e(()=>Ht().forkReviewComment(n));return{nodeId:r.node_id,cwd:r.cwd}},onChanged(n){return thn(n)}}}function cti(t){let e={line:t.anchor.line,endLine:t.anchor.end_line};return{id:t.comment_id,revision:t.revision,...e,lineText:t.anchor_line_text,comment:t.text,status:t.status,authorKind:t.author.kind,createdAt:t.created_at,anchorStatus:t.anchor_state==="detached"?"detached":"live",...t.anchor_state==="detached"?{originalRange:e}:{}}}async function RN(t){try{return await t()}catch(e){throw e instanceof ln&&uti(e.code)?new Cj(e.code,e.message,e.details):e}}function uti(t){return t==="stale_document"||t==="stale_comment"||t==="range_batch_incomplete"||t==="range_batch_stale"}function V6e(t){switch(t){case"active":return 0;case"idle":return 1;case"done":return 2;case"canceled":return 3;case"dead":return 4;default:return 5}}function rhn(t){return t==="active"||t==="idle"}function ihn(t){return t.lifecycle!=="resident"||t.finalized}function Ij(){let t=by();return t!==void 0?{CRTR_HOME:t}:{}}function shn(){return{...Ij(),CRTR_ATTACH_WAKE_PARKED:"0"}}function Tde(t){let e=Cge();if(e!==null){for(let n of e)if(Mf(n,"@crtr_node")===t)return n}}function ohn(t,e,n,r,i){let o=kS(t,{cwd:n,env:shn(),command:`crtr surface attach to ${e}`});if(o===null)return{focused:!1,session:null,inPlace:!1,revived:i};let s=Xx(o);return s!==null&&jz(s.window,"even-horizontal"),j$(o),{focused:!0,session:s?.session??r,inPlace:!1,revived:i}}async function Rde(t,e,n){let r=n.pane??process.env.TMUX_PANE??ug()?.pane;if(r===void 0||r==="")return{focused:!1,session:null,inPlace:!1,revived:!1};let o=(await t.ensureAttach(e,{resume:!0,revive:!0,wakeParked:!1})).revived,s=Xx(r)?.session??null;if(n.inPlace===!0){let c=Mf(r,"@crtr_node"),u=Tde(e);n.keepOtherViewers!==!0&&u!==void 0&&u!==r&&Zx(u)&&Ry(u);try{lg(r,"@crtr_node","")}catch{}let l=_ge(r),d={...shn(),...c!==void 0&&c!==""?{CRTR_ATTACH_ROSTER:c}:{},...n.openTicket!==void 0?{CRTR_ATTACH_OPEN_TICKET:n.openTicket}:{}},p=Gz({pane:r,cwd:n.cwd,env:d,command:`crtr surface attach to ${e}`});return p&&l!==null&&vge(l,n.name),{focused:p,session:s,inPlace:!0,revived:o}}if(n.newPane===!0){let c=Tde(e);return c!==void 0&&Zx(c)&&Ry(c),ohn(r,e,n.cwd,s,o)}let a=Tde(e);if(a!==void 0){let c=Xx(a);if(c!==null)return Mge(c.session),_R(c.session,c.window),j$(a),{focused:!0,session:c.session,inPlace:!0,revived:o}}return ohn(r,e,n.cwd,s,o)}async function Mde(t,e,n){let r=e.node_id;if(e.kind==="human")throw new hf({error:"not_focusable",message:`node ${r} is a human-ask (kind:human), not a conversation \u2014 it has no pi session to focus.`,next:`The pending question is queued for the user; see it with \`crtr human list\`, or retract it with \`crtr human cancel ${r}\`.`});return!rhn(e.status)&&ihn({lifecycle:e.lifecycle,finalized:e.final_report!=null})?{focused:await Sge(n.pane,e.cwd,`crtr node inspect transcript ${un(r)}`),session:null,revived:!1,inPlace:!1}:Rde(t,r,{cwd:e.cwd,name:e.name,pane:n.pane,...n.newPane===!0?{newPane:!0}:{},...n.inPlace===!0?{inPlace:!0}:{},...n.keepOtherViewers===!0?{keepOtherViewers:!0}:{},...n.openTicket!==void 0?{openTicket:n.openTicket}:{}})}var lti=99,dti=40,pti=12,hti=.42,fti=.4,mti=52;function ahn(t){let{companionNodeId:e,cwd:n,callerPane:r}=t;if(!Rs())return{ok:!1,reason:"no_tmux"};let o=Tge().filter(l=>l.nodeId===e&&Hz(l.pane)).sort((l,d)=>d.stampMs-l.stampMs);if(o.length>0)return{ok:!0,paneId:o[0].pane,origin:"adopted"};if(r===void 0||r==="")return{ok:!1,reason:"no_caller_pane"};let s=qz(r);if(s===null)return{ok:!1,reason:"split_refused"};let a,c;s.cols>=lti?(a=!1,c=Math.max(dti,Math.round(s.cols*hti))):(a=!0,c=Math.max(pti,Math.round(s.rows*fti)));let u=kS(r,{cwd:n,env:Ij(),command:`crtr surface attach to ${e}`,vertical:a,size:c});return u===null?{ok:!1,reason:"split_refused"}:{ok:!0,paneId:u,origin:"opened"}}function chn(t){let{nodeId:e,cwd:n,splitFrom:r}=t;if(!Rs())return{ok:!1,reason:"no_tmux"};if(r===void 0||r==="")return{ok:!1,reason:"no_caller_pane"};let i=qz(r);if(i===null)return{ok:!1,reason:"split_refused"};if(Math.floor(i.cols/2)<mti)return{ok:!1,reason:"no_room"};let o=kS(r,{cwd:n,env:Ij(),command:`crtr surface attach to ${e}`,vertical:!1,size:Math.floor(i.cols/2)});return o===null?{ok:!1,reason:"split_refused"}:{ok:!0,paneId:o}}function Pde(t){return Zx(t)&&Hz(t)}function K6e(t,e){!Zx(t)||Mf(t,"@crtr_node")!==e||Ry(t)}function lhn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function gti(t){return t!==null&&typeof t=="object"?t:{}}function Dde(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Ati(t){return Array.isArray(t)?t.filter(e=>e!==null&&typeof e=="object"&&"anchor"in e&&"text"in e):[]}function Y6e(t,e){let n=new Map(e.map(r=>[r.id,r.label]));return t.map(r=>({id:r,label:n.get(r)??r}))}function dhn(t,e){let n=t.rows?.find(i=>i.id===e),r=t.columns[0];return n===void 0||r===void 0||!lhn(n.cells,r.id)?e:String(n.cells[r.id])}function yti(t){let e=t.config.label;return typeof e=="string"&&e!==""?e:t.id??t.kind}function J6e(t,e){return e.kind==="whole"?yti(t):e.kind==="option"?t.config.options.find(n=>n.id===e.optionId)?.label??e.optionId:dhn(t.config,e.rowId)}function uhn(t,e){return Ati(e.comments).map(n=>({anchor:n.anchor,anchorLabel:J6e(t,n.anchor),text:n.text}))}function xti(t,e){let n=e===void 0?"unanswered":"answered",r=gti(e),i=t.config.label,o={id:t.id,kind:t.kind,...typeof i=="string"&&i!==""?{label:i}:{},state:n};if(t.unvalidated===!0)return{...o,blank:e===void 0,groups:[],comments:[],...e===void 0?{}:{raw:r}};if(t.kind==="options"){let s=t.config,a=typeof r.freetext=="string"&&r.freetext!==""?r.freetext:void 0,c={group:"option",mode:s.mode,total:s.options.length,picked:Y6e(Dde(r.selectedOptionIds),s.options)};return{...o,blank:c.picked.length===0&&a===void 0,groups:[c],...a===void 0?{}:{freetext:a},comments:uhn(t,r)}}if(t.kind==="text"){let s=r,a=typeof s.text=="string"?s.text:"",c=t.config.singleLine===!0;return{...o,blank:c&&a==="",groups:[],text:{value:a,edited:s.edited===!0,...c?{singleLine:!0}:{}},comments:[]}}if(t.kind==="table"){let s=t.config,a=[];return(s.rowSelect==="single"||s.rowSelect==="multi")&&a.push({group:"row",mode:s.rowSelect,total:s.rows?.length??0,picked:Dde(r.selectedRowIds).map(c=>({id:c,label:dhn(s,c)}))}),(s.columnSelect==="single"||s.columnSelect==="multi")&&a.push({group:"column",mode:s.columnSelect,total:s.columns.length,picked:Y6e(Dde(r.selectedColumnIds),s.columns)}),{...o,blank:a.every(c=>c.picked.length===0),groups:a,comments:uhn(t,r)}}if(t.kind==="cards"){let s=t.config,a=(s.cards??[]).map(u=>({id:u.id,label:u.title})),c={group:"card",mode:s.mode,total:a.length,picked:Y6e(Dde(r.selectedCardIds),a)};return{...o,blank:c.picked.length===0,groups:[c],comments:[]}}throw new Error(`slot "${t.id}" kind "${t.kind}" does not accept a response`)}function phn(t,e,n){let r=yT(t),i=r.slots.filter(fc).map(s=>xti(s,lhn(e,s.id)?e[s.id]:void 0)),o=i.filter(s=>s.state==="answered");return{title:r.title,...r.subtitle===void 0?{}:{subtitle:r.subtitle},completedAt:n.completedAt,kind:i.length===0?"acknowledgement":"answer",digest:bti(o),slots:i}}function wti(t){return t.picked.length===0?"no selection":t.group==="option"||t.group==="card"?t.picked.map(e=>e.label).join(", "):t.total>0?`${t.picked.length} of ${t.total} ${t.group}s`:`${t.picked.length} ${t.group}${t.picked.length===1?"":"s"}`}function bti(t){return t.map(e=>{if(e.raw!==void 0)return`${e.kind} response`;if(e.text!==void 0)return e.text.singleLine===!0?e.text.value===""?"empty":e.text.value:e.text.edited?"edited":"unchanged";let n=e.groups.map(wti);return e.freetext!==void 0&&n.push(e.freetext),n.join(", ")||"no selection"}).join(" \xB7 ")}var Eti=8,Bde=(t,e,n)=>mce(yce(t),e,n);function fhn(t){return phn(t.manifest,Object.fromEntries(t.responses),{completedAt:""})}function vti(t,e){return e.id===void 0?void 0:t.slots.find(n=>n.id===e.id)}function mhn(t){if(t===void 0||t.state==="unanswered")return"unanswered";if(t.raw!==void 0)return"custom response";let e=t.text!==void 0?[t.text.edited?"edited":"accepted"]:t.groups.map(n=>n.picked.length===0?"none":n.picked.map(r=>r.label).join(", "));return t.freetext!==void 0&&e.push(t.freetext),t.comments.length>0&&e.push(`${t.comments.length} comment${t.comments.length===1?"":"s"}`),e.join("; ")||"answered"}function hhn(t,e){return J6e(t,e)}function ghn(t,e,n){let r=Math.min(Math.max(20,e-4),120),i=Math.max(20,e-4),o=["",...Lde(El(t.manifest.title),r,"",0,`${ls}${ds}`)];if(t.manifest.subtitle)for(let p of vl(Vr(t.manifest.subtitle),r))o.push(` ${ut}${p}${Oe}`);if(t.displayMarkdown!==""){o.push("");for(let p of Bde(t.displayMarkdown,r,i))o.push(` ${p}`)}else t.manifest.dialect==="html"&&o.push("",` ${ut}HTML page \u2014 open in Northlight to read this${Oe}`);let s=t.slots.length>0;s&&o.push(` ${ut}${Tx(r)}${Oe}`,"");let a=fhn(t),c=-1,u;for(let p=0;p<t.slots.length;p++){let h=t.slots[p];t.manifest.steps>1&&h.step!==c&&(c!==-1&&o.push(""),o.push(` ${ls}Step ${h.step+1}/${t.manifest.steps}${Oe}`),c=h.step);let f=h.id===void 0?void 0:t.responses.get(h.id),m=fc(h)?kx(t,h)?`${ET}\u2713${Oe}`:`${ut}\u25CB${Oe}`:`${ut}\xB7${Oe}`,g=p===t.currentIndex?`${ds}\u25B8${Oe} `:" ";p===t.currentIndex&&(u=o.length),o.push(` ${g}${m} ${Tp(El(wN(h)),Math.max(10,e-16))}`),f!==void 0&&o.push(` ${ut}${Tp(El(mhn(vti(a,h))),Math.max(10,e-10))}${Oe}`)}if(t.manifest.slots.some(p=>fc(p)&&!Ip(p))){o.push("");for(let p of vl("This page must be answered in Northlight. Leaving it here keeps it in your inbox; x on the list cancels it.",r-2))o.push(` ${Hs}${p}${Oe}`)}s&&o.push(""),o.push(` ${ut}${Tx(r)}${Oe}`);let d=!t.manifest.slots.some(fc)?` ${ut}u/d${Oe} scroll ${ut}q${Oe} dismiss`:` ${ut}enter${Oe} review ${ut}\u2191\u2193/jk${Oe} navigate ${ut}u/d${Oe} scroll ${ut}q${Oe} close`;return _hn(o,d,t,e,n,r+2,t.followSelection?u:void 0)}function MN(t,e,n){let r=[...t],i=Math.max(0,Math.min(e,r.length)),o=Ahn(t,n),s=0;for(let u=0;u<o.length;u++)o[u].start<=i&&(s=u);let a=o.map((u,l)=>{if(l!==s)return r.slice(u.start,u.end).join("");let d=r.slice(u.start,i).join(""),p=i<u.end?r[i]:" ",h=i<u.end?r.slice(i+1,u.end).join(""):"";return`${d}${uj}${p}${Oe}${h}`}),c=o[s];return i===c.end&&Ws(r.slice(c.start,c.end).join(""))>=n&&(a[s]=r.slice(c.start,c.end).join(""),a.splice(s+1,0,`${uj} ${Oe}`)),a}function kj(t,e){let n=[...t],r=Math.max(0,Math.min(e,n.length));for(;r>0&&/\s/.test(n[r-1]);)r--;for(;r>0&&!/\s/.test(n[r-1]);)r--;return r}function Ode(t,e){let n=[...t],r=Math.max(0,Math.min(e,n.length));for(;r<n.length&&/\s/.test(n[r]);)r++;for(;r<n.length&&!/\s/.test(n[r]);)r++;return r}function Ahn(t,e){let n=[...t],r=Math.max(1,e),i=[],o=0,s=0;for(let a=0;a<n.length;a++){let c=n[a];if(c===`
1706
+ `}function nti(t,e){let n=e+2,r=o=>Math.max(1,Math.min(o-1,e)),i=t.spans.map(o=>o!==null&&(o[0]<=1||o[1]>=n));return{lines:t.lines,rows:t.rows.map((o,s)=>i[s]===!0?null:o),spans:t.spans.map((o,s)=>o===null||i[s]===!0?null:[r(o[0]),r(o[1])]),blocks:t.blocks.map(o=>({type:o.type,start:r(o.start),end:r(o.end)}))}}function Zpn(t,e,n){let r=Mx(t).length;return nti(dce(tti(t,e),n),r)}function Ide(t){let e=[],n=new Array(t.lines.length).fill(null);for(let r=0;r<t.lines.length;r++){let i=t.spans[r]??null;if(i===null){let s=t.rows[r]??null,a=s!==null?t.blocks[s]:void 0;if(a===void 0)continue;i=[a.start,a.end]}let o=e[e.length-1];o!==void 0&&o.lastRow===r-1&&o.start===i[0]&&o.end===i[1]?o.lastRow=r:e.push({start:i[0],end:i[1],firstRow:r,lastRow:r}),n[r]=e.length-1}if(e.length===0){e.push({start:t.blocks[0]?.start??1,end:t.blocks[t.blocks.length-1]?.end??1,firstRow:0,lastRow:Math.max(0,t.lines.length-1)});for(let r=0;r<n.length;r++)n[r]=0}return{units:e,rowUnits:n}}function RT(t,e){let n=-1;for(let r=0;r<t.length;r++){let i=t[r];i.start<=e&&i.end>=e&&(n===-1||i.end-i.start<t[n].end-t[n].start)&&(n=r)}if(n!==-1)return n;for(let r=0;r<t.length;r++)if(t[r].start>e)return r;return Math.max(0,t.length-1)}function j6e(t,e){for(let n=0;n<t.length;n++)if(t[n].start===e.start&&t[n].end===e.end)return n;return RT(t,e.start)}function _j(t,e,n){let r=-1,i=-1;if(t.forEach((o,s)=>{o.start<=n&&o.end>=e&&(r===-1&&(r=s),i=s)}),r===-1){let o=RT(t,e);return{lo:o,hi:o}}return{lo:r,hi:i}}import{basename as rti,dirname as ehn,join as iti}from"node:path";import{mkdirSync as oti,watch as sti,writeFileSync as iBs}from"node:fs";function z6e(t){return iti(Na(),"signals",t)}function kde(t,e){let n=z6e(t);try{oti(ehn(n),{recursive:!0,mode:448});let r=sti(ehn(n),(i,o)=>{String(o)===rti(n)&&e()});return()=>r.close()}catch(r){return console.error(`activity-signal: failed to watch "${t}": ${r instanceof Error?r.message:String(r)}`),()=>{}}}function thn(t){return kde("review-activity",t)}var Cj=class extends Error{code;details;constructor(e,n,r){super(n),this.name="ReviewDocumentError",this.code=e,this.details=r}};function nhn(t,e){return{async anchorBase(){let n=await e(()=>Ht().getReviewDocumentBase(t));return{file:n.file,text:n.anchor_base_text,docHash:n.anchor_base_sha256}},async list(){return(await e(()=>Ht().listReviewComments(t,{status:"all"}))).comments.map(cti)},async create(n){return(await RN(()=>e(()=>Ht().createReviewComment(t,{text:n.text,anchor:{line:n.line,end_line:n.endLine},doc_hash:n.docHash,actor_node_id:null})))).comment.comment_id},async edit(n){await RN(()=>e(()=>Ht().editReviewComment(n.id,{text:n.text,if_revision:n.ifRevision,actor_node_id:null})))},async resolve(n){await RN(()=>e(()=>Ht().resolveReviewComment(n,{actor_node_id:null})))},async reopen(n){await RN(()=>e(()=>Ht().reopenReviewComment(n,{actor_node_id:null})))},async remove(n){await RN(()=>e(()=>Ht().deleteReviewComment(n,{actor_node_id:null})))},async remapRanges(n){await RN(()=>e(()=>Ht().updateReviewCommentRanges(t,{from_doc_hash:n.fromDocHash,to_doc_hash:n.toDocHash,entries:n.entries.map(r=>"detached"in r?{comment_id:r.id,detached:!0}:{comment_id:r.id,anchor:{line:r.anchor.line,end_line:r.anchor.endLine}})})))},async fork(n){let r=await e(()=>Ht().forkReviewComment(n));return{nodeId:r.node_id,cwd:r.cwd}},onChanged(n){return thn(n)}}}function cti(t){let e={line:t.anchor.line,endLine:t.anchor.end_line};return{id:t.comment_id,revision:t.revision,...e,lineText:t.anchor_line_text,comment:t.text,status:t.status,authorKind:t.author.kind,createdAt:t.created_at,anchorStatus:t.anchor_state==="detached"?"detached":"live",...t.anchor_state==="detached"?{originalRange:e}:{}}}async function RN(t){try{return await t()}catch(e){throw e instanceof ln&&uti(e.code)?new Cj(e.code,e.message,e.details):e}}function uti(t){return t==="stale_document"||t==="stale_comment"||t==="range_batch_incomplete"||t==="range_batch_stale"}function V6e(t){switch(t){case"active":return 0;case"idle":return 1;case"done":return 2;case"canceled":return 3;case"dead":return 4;default:return 5}}function rhn(t){return t==="active"||t==="idle"}function ihn(t){return t.lifecycle!=="resident"||t.finalized}function Ij(){let t=by();return t!==void 0?{CRTR_HOME:t}:{}}function shn(){return{...Ij(),CRTR_ATTACH_WAKE_PARKED:"0"}}function Tde(t){let e=Cge();if(e!==null){for(let n of e)if(Mf(n,"@crtr_node")===t)return n}}function ohn(t,e,n,r,i){let o=kS(t,{cwd:n,env:shn(),command:`crtr surface attach to ${e}`});if(o===null)return{focused:!1,session:null,inPlace:!1,revived:i};let s=Xx(o);return s!==null&&jz(s.window,"even-horizontal"),j$(o),{focused:!0,session:s?.session??r,inPlace:!1,revived:i}}async function Rde(t,e,n){let r=n.pane??process.env.TMUX_PANE??ug()?.pane;if(r===void 0||r==="")return{focused:!1,session:null,inPlace:!1,revived:!1};let o=(await t.ensureAttach(e,{resume:!0,revive:!0,wakeParked:!1})).revived,s=Xx(r)?.session??null;if(n.inPlace===!0){let c=Mf(r,"@crtr_node"),u=Tde(e);n.keepOtherViewers!==!0&&u!==void 0&&u!==r&&Zx(u)&&Ry(u);try{lg(r,"@crtr_node","")}catch{}let l=_ge(r),d={...shn(),...c!==void 0&&c!==""?{CRTR_ATTACH_ROSTER:c}:{},...n.openTicket!==void 0?{CRTR_ATTACH_OPEN_TICKET:n.openTicket}:{}},p=Gz({pane:r,cwd:n.cwd,env:d,command:`crtr surface attach to ${e}`});return p&&l!==null&&vge(l,n.name),{focused:p,session:s,inPlace:!0,revived:o}}if(n.newPane===!0){let c=Tde(e);return c!==void 0&&Zx(c)&&Ry(c),ohn(r,e,n.cwd,s,o)}let a=Tde(e);if(a!==void 0){let c=Xx(a);if(c!==null)return Mge(c.session),_R(c.session,c.window),j$(a),{focused:!0,session:c.session,inPlace:!0,revived:o}}return ohn(r,e,n.cwd,s,o)}async function Mde(t,e,n){let r=e.node_id;if(e.kind==="human")throw new hf({error:"not_focusable",message:`node ${r} is a human-ask (kind:human), not a conversation \u2014 it has no pi session to focus.`,next:`The pending question is queued for the user; see it with \`crtr human list\`, or retract it with \`crtr human cancel ${r}\`.`});return!rhn(e.status)&&ihn({lifecycle:e.lifecycle,finalized:e.final_report!=null})?{focused:await Sge(n.pane,e.cwd,`crtr node inspect transcript ${un(r)}`),session:null,revived:!1,inPlace:!1}:Rde(t,r,{cwd:e.cwd,name:e.name,pane:n.pane,...n.newPane===!0?{newPane:!0}:{},...n.inPlace===!0?{inPlace:!0}:{},...n.keepOtherViewers===!0?{keepOtherViewers:!0}:{},...n.openTicket!==void 0?{openTicket:n.openTicket}:{}})}var lti=99,dti=40,pti=12,hti=.42,fti=.4,mti=52;function ahn(t){let{companionNodeId:e,cwd:n,callerPane:r}=t;if(!Rs())return{ok:!1,reason:"no_tmux"};let o=Tge().filter(l=>l.nodeId===e&&Hz(l.pane)).sort((l,d)=>d.stampMs-l.stampMs);if(o.length>0)return{ok:!0,paneId:o[0].pane,origin:"adopted"};if(r===void 0||r==="")return{ok:!1,reason:"no_caller_pane"};let s=qz(r);if(s===null)return{ok:!1,reason:"split_refused"};let a,c;s.cols>=lti?(a=!1,c=Math.max(dti,Math.round(s.cols*hti))):(a=!0,c=Math.max(pti,Math.round(s.rows*fti)));let u=kS(r,{cwd:n,env:Ij(),command:`crtr surface attach to ${e}`,vertical:a,size:c});return u===null?{ok:!1,reason:"split_refused"}:{ok:!0,paneId:u,origin:"opened"}}function chn(t){let{nodeId:e,cwd:n,splitFrom:r}=t;if(!Rs())return{ok:!1,reason:"no_tmux"};if(r===void 0||r==="")return{ok:!1,reason:"no_caller_pane"};let i=qz(r);if(i===null)return{ok:!1,reason:"split_refused"};if(Math.floor(i.cols/2)<mti)return{ok:!1,reason:"no_room"};let o=kS(r,{cwd:n,env:Ij(),command:`crtr surface attach to ${e}`,vertical:!1,size:Math.floor(i.cols/2)});return o===null?{ok:!1,reason:"split_refused"}:{ok:!0,paneId:o}}function Pde(t){return Zx(t)&&Hz(t)}function K6e(t,e){!Zx(t)||Mf(t,"@crtr_node")!==e||Ry(t)}function lhn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function gti(t){return t!==null&&typeof t=="object"?t:{}}function Dde(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function Ati(t){return Array.isArray(t)?t.filter(e=>e!==null&&typeof e=="object"&&"anchor"in e&&"text"in e):[]}function Y6e(t,e){let n=new Map(e.map(r=>[r.id,r.label]));return t.map(r=>({id:r,label:n.get(r)??r}))}function dhn(t,e){let n=t.rows?.find(i=>i.id===e),r=t.columns[0];return n===void 0||r===void 0||!lhn(n.cells,r.id)?e:String(n.cells[r.id])}function yti(t){let e=t.config.label;return typeof e=="string"&&e!==""?e:t.id??t.kind}function J6e(t,e){return e.kind==="whole"?yti(t):e.kind==="option"?t.config.options.find(n=>n.id===e.optionId)?.label??e.optionId:dhn(t.config,e.rowId)}function uhn(t,e){return Ati(e.comments).map(n=>({anchor:n.anchor,anchorLabel:J6e(t,n.anchor),text:n.text}))}function xti(t,e){let n=e===void 0?"unanswered":"answered",r=gti(e),i=t.config.label,o={id:t.id,kind:t.kind,...typeof i=="string"&&i!==""?{label:i}:{},state:n};if(t.unvalidated===!0)return{...o,blank:e===void 0,groups:[],comments:[],...e===void 0?{}:{raw:r}};if(t.kind==="options"){let s=t.config,a=typeof r.freetext=="string"&&r.freetext!==""?r.freetext:void 0,c={group:"option",mode:s.mode,total:s.options.length,picked:Y6e(Dde(r.selectedOptionIds),s.options)};return{...o,blank:c.picked.length===0&&a===void 0,groups:[c],...a===void 0?{}:{freetext:a},comments:uhn(t,r)}}if(t.kind==="text"){let s=r,a=typeof s.text=="string"?s.text:"",c=t.config.singleLine===!0;return{...o,blank:c&&a==="",groups:[],text:{value:a,edited:s.edited===!0,...c?{singleLine:!0}:{}},comments:[]}}if(t.kind==="table"){let s=t.config,a=[];return(s.rowSelect==="single"||s.rowSelect==="multi")&&a.push({group:"row",mode:s.rowSelect,total:s.rows?.length??0,picked:Dde(r.selectedRowIds).map(c=>({id:c,label:dhn(s,c)}))}),(s.columnSelect==="single"||s.columnSelect==="multi")&&a.push({group:"column",mode:s.columnSelect,total:s.columns.length,picked:Y6e(Dde(r.selectedColumnIds),s.columns)}),{...o,blank:a.every(c=>c.picked.length===0),groups:a,comments:uhn(t,r)}}if(t.kind==="cards"){let s=t.config,a=(s.cards??[]).map(u=>({id:u.id,label:u.title})),c={group:"card",mode:s.mode,total:a.length,picked:Y6e(Dde(r.selectedCardIds),a)};return{...o,blank:c.picked.length===0,groups:[c],comments:[]}}throw new Error(`slot "${t.id}" kind "${t.kind}" does not accept a response`)}function phn(t,e,n){let r=yT(t),i=r.slots.filter(fc).map(s=>xti(s,lhn(e,s.id)?e[s.id]:void 0)),o=i.filter(s=>s.state==="answered");return{title:r.title,...r.subtitle===void 0?{}:{subtitle:r.subtitle},completedAt:n.completedAt,kind:i.length===0?"acknowledgement":"answer",digest:bti(o),slots:i}}function wti(t){return t.picked.length===0?"no selection":t.group==="option"||t.group==="card"?t.picked.map(e=>e.label).join(", "):t.total>0?`${t.picked.length} of ${t.total} ${t.group}s`:`${t.picked.length} ${t.group}${t.picked.length===1?"":"s"}`}function bti(t){return t.map(e=>{if(e.raw!==void 0)return`${e.kind} response`;if(e.text!==void 0)return e.text.singleLine===!0?e.text.value===""?"empty":e.text.value:e.text.edited?"edited":"unchanged";let n=e.groups.map(wti);return e.freetext!==void 0&&n.push(e.freetext),n.join(", ")||"no selection"}).join(" \xB7 ")}var Eti=8,Bde=(t,e,n)=>mce(yce(t),e,n);function fhn(t){return phn(t.manifest,Object.fromEntries(t.responses),{completedAt:""})}function vti(t,e){return e.id===void 0?void 0:t.slots.find(n=>n.id===e.id)}function mhn(t){if(t===void 0||t.state==="unanswered")return"unanswered";if(t.raw!==void 0)return"custom response";let e=t.text!==void 0?[t.text.edited?"edited":"accepted"]:t.groups.map(n=>n.picked.length===0?"none":n.picked.map(r=>r.label).join(", "));return t.freetext!==void 0&&e.push(t.freetext),t.comments.length>0&&e.push(`${t.comments.length} comment${t.comments.length===1?"":"s"}`),e.join("; ")||"answered"}function hhn(t,e){return J6e(t,e)}function ghn(t,e,n){let r=Math.min(Math.max(20,e-4),120),i=Math.max(20,e-4),o=["",...Lde(El(t.manifest.title),r,"",0,`${ls}${ds}`)];if(t.manifest.subtitle)for(let p of vl(Vr(t.manifest.subtitle),r))o.push(` ${ut}${p}${Oe}`);if(t.displayMarkdown!==""){o.push("");for(let p of Bde(t.displayMarkdown,r,i))o.push(` ${p}`)}else t.manifest.dialect==="html"&&o.push("",` ${ut}HTML page \u2014 open in Northlight to read this${Oe}`);let s=t.slots.length>0;s&&o.push(` ${ut}${Tx(r)}${Oe}`,"");let a=fhn(t),c=-1,u;for(let p=0;p<t.slots.length;p++){let h=t.slots[p];t.manifest.steps>1&&h.step!==c&&(c!==-1&&o.push(""),o.push(` ${ls}Step ${h.step+1}/${t.manifest.steps}${Oe}`),c=h.step);let f=h.id===void 0?void 0:t.responses.get(h.id),m=fc(h)?kx(t,h)?`${ET}\u2713${Oe}`:`${ut}\u25CB${Oe}`:`${ut}\xB7${Oe}`,g=p===t.currentIndex?`${ds}\u25B8${Oe} `:" ";p===t.currentIndex&&(u=o.length),o.push(` ${g}${m} ${Tp(El(wN(h)),Math.max(10,e-16))}`),f!==void 0&&o.push(` ${ut}${Tp(El(mhn(vti(a,h))),Math.max(10,e-10))}${Oe}`)}if(t.manifest.slots.some(p=>fc(p)&&!Ip(p))){o.push("");for(let p of vl("This page must be answered in Northlight. Leaving it here keeps it in your inbox; x on the list cancels it.",r-2))o.push(` ${Hs}${p}${Oe}`)}s&&o.push(""),o.push(` ${ut}${Tx(r)}${Oe}`);let d=!t.manifest.slots.some(fc)?` ${ut}u/d${Oe} scroll ${ut}q${Oe} dismiss`:` ${ut}enter${Oe} review ${ut}\u2191\u2193/jk${Oe} navigate ${ut}u/d${Oe} scroll ${ut}q${Oe} close`;return _hn(o,d,t,e,n,r+2,t.followSelection?u:void 0)}function MN(t,e,n){let r=[...t],i=Math.max(0,Math.min(e,r.length)),o=Ahn(t,n),s=0;for(let u=0;u<o.length;u++)o[u].start<=i&&(s=u);let a=o.map((u,l)=>{if(l!==s)return r.slice(u.start,u.end).join("");let d=r.slice(u.start,i).join(""),p=i<u.end?r[i]:" ",h=i<u.end?r.slice(i+1,u.end).join(""):"";return`${d}${uj}${p}${Oe}${h}`}),c=o[s];return i===c.end&&Ws(r.slice(c.start,c.end).join(""))>=n&&(a[s]=r.slice(c.start,c.end).join(""),a.splice(s+1,0,`${uj} ${Oe}`)),a}function kj(t,e){let n=[...t],r=Math.max(0,Math.min(e,n.length));for(;r>0&&/\s/.test(n[r-1]);)r--;for(;r>0&&!/\s/.test(n[r-1]);)r--;return r}function Ode(t,e){let n=[...t],r=Math.max(0,Math.min(e,n.length));for(;r<n.length&&/\s/.test(n[r]);)r++;for(;r<n.length&&!/\s/.test(n[r]);)r++;return r}function Ahn(t,e){let n=[...t],r=Math.max(1,e),i=[],o=0,s=0;for(let a=0;a<n.length;a++){let c=n[a];if(c===`
1707
1707
  `){i.push({start:o,end:a}),o=a+1,s=0;continue}let u=Ws(c);s+u>r?(i.push({start:o,end:a}),o=a,s=u):s+=u}return i.push({start:o,end:n.length}),i}function Tj(t,e,n,r){let i=Ahn(t,r),o=Math.max(0,Math.min(e,[...t].length)),s=0;for(let c=0;c<i.length;c++)i[c].start<=o&&(s=c);let a=i[s+n];return a===void 0?o:Math.min(a.start+(o-i[s].start),a.end)}function Sti(t,e){return e.id===void 0?[]:t.responses.get(e.id)?.comments??[]}function Lde(t,e,n,r,i){return vl(t,Math.max(10,e-r)).map((o,s)=>` ${s===0?n:" ".repeat(r)}${i}${o}${Oe}`)}function _ti(t,e,n,r){if(e.id===void 0)return!1;let i=t.responses.get(e.id);return n==="option"?i?.selectedOptionIds?.includes(r)===!0:n==="card"?i?.selectedCardIds?.includes(r)===!0:n==="row"?i?.selectedRowIds?.includes(r)===!0:i?.selectedColumnIds?.includes(r)===!0}function yhn(t,e){let n=t.slots[t.currentIndex],r=Math.min(Math.max(20,e-4),120),i=Math.max(20,e-4),o=`[${t.currentIndex+1}/${t.slots.length}]`,s=["",...Lde(El(t.manifest.title),r,`${ls}${ds}${o}${Oe} `,Ws(o)+2,ut),` ${ut}${Tx(r)}${Oe}`,"",...Lde(El(wN(n)),r,"",0,ls)],a=n.config.body;if(typeof a=="string"&&a.length>0){s.push("");for(let l of Bde(a,r,i))s.push(` ${l}`)}if(Ip(n)){if(n.kind==="chart"){let l=n.config,d=l.title??`${l.x} vs ${(l.y??[]).map(p=>p.label??p.field).join(", ")}`;s.push("",` ${ut}chart \u2014 ${Vr(l.kind)}: ${Vr(d)}${Oe}`)}else if(n.kind==="table"){s.push("");for(let d of Bde(Hle(n.config),r,i))s.push(` ${d}`);let l=n.config.label;l&&s.push(` ${ut}${Vr(l)}${Oe}`)}else if(n.kind==="text"){let d=(n.id===void 0?void 0:t.responses.get(n.id))?.text??n.config.initialText;s.push("");for(let p of Bde(d,r,i))s.push(` ${p}`)}}else{s.push("");for(let l of vl(`${Vr(n.kind)} \u2014 must be answered in Northlight; the terminal cannot submit this page`,Math.max(10,r-2)))s.push(` ${Hs}${l}${Oe}`);s.push(` ${ut}q leaves it in your inbox; x on the list cancels it${Oe}`)}s.push("",` ${ut}${Tx(r)}${Oe}`);let c;if(t.inputMode!==null){let l=t.inputMode.kind==="comment"?`Comment on ${hhn(n,t.inputMode.anchor)}`:t.inputMode.kind==="text"?"Edit text":"Other response";s.push(` ${ls}${l}${Oe}`);for(let d of MN(t.inputMode.buffer,t.inputMode.cursor,Math.max(10,r-4)))s.push(` ${d}`);c=` ${ut}enter save esc cancel${t.editorAvailable?" ^o editor":""}${Oe}`}else{Wle(n).forEach((d,p)=>{let h=p===t.selectedAction?`${ds}\u25B8${Oe}`:" ";if(d.kind==="select"){let f=_ti(t,n,d.group,d.id)?`${ET}\u2713${Oe}`:" ";if(s.push(` ${h} [${f}] ${d.shortcut?`[${d.shortcut}] `:""}${Vr(d.label)}`),d.description)for(let m of vl(Vr(d.description),Math.max(10,r-6)))s.push(` ${ut}${m}${Oe}`)}else{let f=d.kind==="freetext"?"r":d.kind==="edit"?"e":"a";s.push(` ${h} [${f}] ${Vr(d.label)}`)}});for(let d of Sti(t,n))for(let p of vl(`attached: ${hhn(n,d.anchor)} \u2014 ${Vr(d.text)}`,Math.max(10,r-2)))s.push(` ${ut}${p}${Oe}`);t.hint&&s.push(` ${Hs}${Vr(t.hint)}${Oe}`),c=` ${ut}n/p next/previous \u2191\u2193/jk actions${EN(n).length>0?" c comment":""} u/d scroll \u2190\u2192/hl pan q close${Oe}`}let u=Math.max(0,...s.map(zo));return{lines:s,footer:c,maxW:r,maxH:Math.max(0,u-Math.max(1,e))}}function xhn(t,e,n){if(t.slots[t.currentIndex]===void 0){t.scrollOffset=0,t.hscrollOffset=0,t.hscrollMax=0;return}let r=yhn(t,e);t.hscrollMax=r.maxH,t.hscrollOffset=Math.max(0,Math.min(t.hscrollOffset,t.hscrollMax)),t.scrollOffset=Math.max(0,Math.min(t.scrollOffset,Math.max(0,r.lines.length-X6e(n))))}function whn(t,e){t.hscrollOffset=Math.max(0,Math.min(t.hscrollMax,t.hscrollOffset+e*Eti))}function bhn(t,e,n){let r=yhn(t,e),i=X6e(n),o=t.scrollOffset,s=r.lines.slice(o,o+i);for(;s.length<i;)s.push("");let a=t.hscrollOffset>0?s.map(u=>jle(u,t.hscrollOffset,e)):s,c=Math.min(e,r.maxW+2);return i<n&&a.push(Shn(r.footer,vhn(o,i,r.lines.length),r.maxW+2)),py(a.map(u=>ma(u,e)),e,c)}function Ehn(t,e,n){let r=Math.min(Math.max(20,e-4),120),i=["",...Lde(`${El(t.manifest.title)} \u2014 Summary`,r,"",0,`${ls}${ds}`),` ${ut}${Tx(r)}${Oe}`,""],o=fhn(t);for(let c of o.slots){let u=t.manifest.slots.find(p=>p.id===c.id),d=u!==void 0&&kx(t,u)?`${ET}\u2713${Oe}`:`${Hs}\u25CB${Oe}`;i.push(` ${d} ${ls}${Vr(u===void 0?c.kind:wN(u))}${Oe} ${ut}${Vr(mhn(c))}${Oe}`)}let s=Fv(t);if(!s){i.push("",` ${Hs}Cannot submit yet.${Oe}`);for(let c of t.slots.filter(fc))kx(t,c)||(i.push(` ${ut}${c.id??c.kind} is unanswered${Oe}`),Ip(c)||i.push(` ${ut}${c.id} must be answered in Northlight${Oe}`))}i.push("",` ${ut}${Tx(r)}${Oe}`);let a=s?` ${ut}enter${Oe} submit ${ut}u/d${Oe} scroll ${ut}q${Oe} back`:` ${ut}u/d${Oe} scroll ${ut}q${Oe} back`;return _hn(i,a,t,e,n,r+2)}function X6e(t){return t>=2?t-1:t}function vhn(t,e,n){if(e<=0||n<=e)return{marks:"",full:""};let r=Math.min(n,t+e),i=`${t>0?"\u25B4":" "}${r<n?"\u25BE":" "}`;return{marks:`${ut}${i}${Oe}`,full:`${ut}${i} ${t+1}\u2013${r}/${n}${Oe}`}}function Shn(t,e,n){if(e.full==="")return t;let r=i=>n-zo(t)-zo(i)-2;for(let i of[e.full,e.marks])if(r(i)>=2)return`${t}${" ".repeat(r(i))}${i}`;return` ${e.marks} ${t.trimStart()}`}function _hn(t,e,n,r,i,o,s){let a=X6e(i),c=Math.max(0,t.length-a);n.scrollOffset=Math.max(0,Math.min(n.scrollOffset,c)),s!==void 0&&a>0&&(s<n.scrollOffset?n.scrollOffset=s:s>=n.scrollOffset+a&&(n.scrollOffset=Math.min(c,s-a+1)));let u=t.slice(n.scrollOffset,n.scrollOffset+a);for(;u.length<a;)u.push("");return a<i&&u.push(Shn(e,vhn(n.scrollOffset,a,t.length),o)),py(u.map(l=>ma(l,r)),r,Math.min(r,o))}function Chn(t,e,n,r){let i=e.units.length>0?e:{units:[{start:1,end:Math.max(1,t.length),firstRow:0,lastRow:0}],rowUnits:e.rowUnits};return{sourceLines:t,units:i.units,rowUnits:i.rowUnits,comments:[...n],sourceRevision:r,detached:Object.fromEntries(n.flatMap(o=>o.anchorStatus==="detached"?[[o.id,o.originalRange??{line:o.line,endLine:o.endLine}]]:[])),activeUnit:n.length>0?RT(i.units,n[0].line):0,selectionAnchor:null,scroll:0,hscroll:0,mode:"view",compose:null,listIndex:0}}function Z6e(t){let e=t.selectionAnchor??t.activeUnit;return{lo:Math.min(t.activeUnit,e),hi:Math.max(t.activeUnit,e)}}function Cti(t){let{lo:e,hi:n}=Z6e(t),r=Number.POSITIVE_INFINITY,i=0;for(let o=e;o<=n;o++){let s=t.units[o];s!==void 0&&(r=Math.min(r,s.start),i=Math.max(i,s.end))}return Number.isFinite(r)?{line:r,endLine:Math.max(r,i)}:{line:1,endLine:Math.max(1,t.sourceLines.length)}}function eVe(t,e,n){let r=Math.max(0,t.units.length-1),i=Math.max(0,Math.min(r,t.activeUnit+e));return n?{...t,activeUnit:i,selectionAnchor:t.selectionAnchor??t.activeUnit}:{...t,activeUnit:i,selectionAnchor:null}}function Ihn(t){let e=new Set;for(let n of t.comments){if(n.status==="deleted"||n.anchorStatus==="detached")continue;let r=!1;t.units.forEach((i,o)=>{i.start<=n.endLine&&i.end>=n.line&&(e.add(o),r=!0)}),r||e.add(RT(t.units,n.line))}return e}function Iti(t,e,n){let r=t[e],i=t[n];return r===void 0||i===void 0?null:{first:r.firstRow,last:i.lastRow}}function kti(t,e,n,r,i,o=2){let s=Math.max(0,i-r),a=Math.max(0,Math.min(t,s));return n-e+1>=r?Math.max(0,Math.min(Math.max(0,e-1),s)):(e-o<a?a=Math.max(e-o,n-(r-1)):n+o>a+r-1&&(a=Math.min(n+o-(r-1),e)),Math.max(0,Math.min(a,s)))}function Gv(t,e,n){let r=Iti(t.units,t.activeUnit,t.activeUnit);if(r===null)return t;let i=kti(t.scroll,r.first,r.last,n,e.lines.length);return i===t.scroll?t:{...t,scroll:i}}function khn(t,e,n,r){let i=Math.max(0,r-n);return{...t,scroll:Math.max(0,Math.min(t.scroll+e,i))}}function Thn(t){return Math.max(1,Math.floor(t/2))}function Rhn(t,e,n,r){if(e===0)return t;let i=e>0?1:-1,o=Math.max(0,r-n),s=Math.max(0,Math.min(t.scroll+e,o)),a=s+(s>0?1:0),c=Math.max(a,s+n-1-(s+n<r?1:0)),u=t.units[t.activeUnit]?.firstRow??t.scroll,l=Math.max(a,Math.min(u+e,c)),d=Tti(t,l,a,c,i)??t.activeUnit;return s===t.scroll&&d===t.activeUnit?t:{...t,scroll:s,activeUnit:d,selectionAnchor:null}}function Tti(t,e,n,r,i){let o=Math.max(0,t.units.length-1);for(let s=0;s<=r-n;s++)for(let a of[e+s*i,e-s*i]){if(a<n||a>r)continue;let c=t.rowUnits[a];if(c!=null)return Math.max(0,Math.min(o,c))}return null}function Mhn(t){return{...t,mode:"compose",compose:{buffer:"",cursor:0,editingId:null,returnMode:"view",anchor:Cti(t)}}}function Phn(t,e){let n=t.comments[e];if(n===void 0)return t;let r=n.comment,{lo:i,hi:o}=_j(t.units,n.line,n.endLine);return{...t,activeUnit:o,selectionAnchor:i===o?null:i,mode:"compose",compose:{buffer:r,cursor:[...r].length,editingId:n.id,returnMode:"list",anchor:{line:n.line,endLine:n.endLine}}}}function Nde(t){let e=t.compose?.returnMode??"view";return{...t,mode:e,compose:null}}function Dhn(t){let e=t.compose;if(e==null)return{state:t,commit:null};let n=e.buffer.trim();return n.length===0?{state:Nde(t),commit:null}:{state:Nde(t),commit:{editingId:e.editingId,anchor:e.anchor,text:n}}}function Bhn(t){return{...t,mode:"list",listIndex:Math.max(0,Math.min(t.listIndex,t.comments.length-1))}}function tVe(t){return{...t,mode:"view"}}function nVe(t,e){if(t.comments.length===0)return t;let n=Math.max(0,Math.min(t.comments.length-1,t.listIndex+e));return{...t,listIndex:n}}function Lhn(t){let e=t.comments[t.listIndex];return{state:t,id:e?.id??null}}function Ohn(t){return{state:t,id:t.comments.at(-1)?.id??null}}function Nhn(t){return{...t,mode:"help"}}function rVe(t){return{...t,mode:"view"}}function qv(t){return[...t]}function $hn(t){return t.replace(/\x1b\[20[01]~/g,"").replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\r\n?/g,`
1708
1708
  `).replace(/[\x00-\x09\x0B-\x1F\x7F]/g,"")}function $de(t,e,n){let r=qv(t),i=Math.max(0,Math.min(e,r.length));return{buffer:[...r.slice(0,i),...qv(n),...r.slice(i)].join(""),cursor:i+qv(n).length}}function Fhn(t,e){if(e<=0)return{buffer:t,cursor:e};let n=qv(t);return{buffer:[...n.slice(0,e-1),...n.slice(e)].join(""),cursor:e-1}}function Uhn(t,e){let n=qv(t);return e>=n.length?{buffer:t,cursor:e}:{buffer:[...n.slice(0,e),...n.slice(e+1)].join(""),cursor:e}}function Qhn(t,e){let n=e;for(;n>0&&t[n-1]!==`
1709
1709
  `;)n--;let r=e;for(;r<t.length&&t[r]!==`
@@ -1727,7 +1727,7 @@ ${u}`,"1").then(l=>{let d=a.options[Number.parseInt(l,10)-1]?.id;if(d===void 0)t
1727
1727
  `));return}s(E),i.login(p,"oauth",S).then(()=>{f||(r(`Logged in to ${h.name}`),n(),g())}).catch(C).finally(()=>s(void 0))}else y.showPrompt(`Enter API key for ${h.name}:`,"sk-...").then(async I=>{if(!f){if(I.trim()){if(!E())return;await Sfn(p,{type:"api_key",key:I.trim()},o),r(`API key saved for ${h.name}`),n()}else r("No key entered \u2014 login cancelled");g()}}).catch(()=>g())},d=new Sv("login",a,l,()=>c());return{component:d,focus:d}}}async function zfn(t,e,n){let{runtime:r,authPath:i}=await qfn(t),o=await Gfn(r);return({close:s})=>{let a=u=>{let l=o.find(d=>d.id===u);(async()=>{try{jv(u)?await Ofn(u):await gVe(u,i),s(),n(`Logged out of ${l?.name??u}`),e()}catch(d){s(),n(`Logout error: ${d instanceof Error?d.message:String(d)}`)}})()},c=new Sv("logout",o,a,()=>s());return{component:c,focus:c}}}function Vfn(t,e){return Apn({nodeId:t.nodeId,profileId:t.meta.profile_id??void 0,remote:t.remote,role:t.role,isBrokerOffline:e})}function Kfn(t,e,n,r){let{nodeId:i,socket:o,tui:s,editor:a,containers:c}=t,{setNotice:u}=r,l=()=>o.send({type:"reload_auth"}),d=n.permits("auth")?{openLoginPicker:()=>{let h=r.agentDir()??Jk();p.openAuthPicker(()=>jfn(s,h,l,f=>u(f)))},openLogoutPicker:()=>{let h=r.agentDir()??Jk();p.openAuthPicker(()=>zfn(h,l,f=>u(f)))}}:{},p=new Yde(s,a,e,{onCommand:h=>o.send(h),onDialogResponse:h=>o.send(h),onNotice:h=>u(h),onGraph:r.toggleGraph,onInbox:r.toggleInbox,onHelp:r.toggleHelp,onNodeMetadata:r.openNodeMetadata,onQuit:r.quit,onCopy:()=>r.copyTarget("last-assistant"),onCopyTarget:r.copyTarget,onToggleMouse:()=>{let h=r.toggleMouse();u(h?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},onColor:r.setChipColor,onPromptSent:r.onPromptSent,frecency:r.frecency,knownRefNames:()=>a.getResolvedRefNames(),onToggleToolsExpand:()=>{let h=r.toggleToolsExpanded();u(h.kind==="summaries"?h.shown?"Tool calls: summarized":"Tool calls: shown":h.expanded?"Tool output: expanded":"Tool output: collapsed")},onFoldTools:()=>u(r.toggleFoldTools()?"Finished tool calls: folded to one line":"Finished tool calls: shown in full"),onShowWorking:()=>{let h=r.toggleShowWorking();u(h===null?"Consolidated replies are off (crtr sys config set consolidate_replies --value true, then re-attach)":h?"Working: shown":"Working: hidden behind each reply")},onToggleThinking:()=>u(r.toggleThinking()?"Thinking blocks: hidden":"Thinking blocks: visible"),onRequest:h=>{let f=n.refusal("engine-drive");return f===void 0?o.request(h):Promise.reject(new Error(f))},onMountPicker:h=>{c.pickerPanel.addChild(h),s.requestRender()},onUnmountPicker:()=>{c.pickerPanel.clear(),s.requestRender()},isDormant:r.isDormant,onDormantSubmit:n.permits("wake-dormant")?h=>{(async()=>{try{let f=await Ht().sendMessage(i,{body:h,from:"human"});u(f.revived?"\u21BB waking node\u2026":"\u2709 delivered \u2014 node reads on next wake")}catch(f){u(`Couldn't wake node: ${f instanceof Error?f.message:String(f)}`)}})()}:void 0,...d},n);return p}tt();import{execFile as smn}from"node:child_process";async function Bj(t,e){await Ht().respondHumanRequest(t,{responses:e})}async function Yfn(t,e){await Ht().dismissHumanRequest(t,e)}function Jfn(t){if(t instanceof ln)return t.status===503||t.code==="daemon_unavailable";let e=t?.code;return e==="ECONNREFUSED"||e==="ENOENT"}function Gc(t){return Jfn(t)?"could not reach crtrd \u2014 nothing was submitted":t instanceof ln||t instanceof Error?t.message:String(t)}function Lj(t){return Jfn(t)?"unreachable":t instanceof ln&&t.status===409&&t.code==="already_settled"?"already_settled":"other"}function Xfn(t,e){let n=Date.parse(t)-e;if(n<=0)return"due now";let r=Math.ceil(n/6e4);if(r<60)return`in ${r}m`;let i=Math.floor(r/60),o=r%60;if(i<24)return`in ${i}h${o>0?` ${o}m`:""}`;let s=Math.floor(i/24),a=i%24;return`in ${s}d${a>0?` ${a}h`:""}`}function Ari(t){return[...t].sort((e,n)=>Date.parse(e.fire_at)-Date.parse(n.fire_at))[0]}function Zfn(t,e=Date.now()){if(t.length===0)return;if(t.length>1){let i=Ari(t);return`${t.length} crons armed${i?` \xB7 next ${Xfn(i.fire_at,e)}`:""}`}let n=t[0],r=Xfn(n.fire_at,e);return n.cancel_on_wake?`deadline \xB7 ${r}`:n.recur!==null?`recurring cron \xB7 next ${r}`:`scheduled cron \xB7 ${r}`}function yri(t,e){let n=Fln(t);if(n.length<=e)return n;let r=n.slice(0,Math.max(1,e-1)),i=r.lastIndexOf(" ");return`${(i>=e-12?r.slice(0,i):r).trimEnd()}\u2026`}function emn(t,e=Date.now(),n=26){if(t.length===0)return;if(t.length===1){let i=t[0];return`bash job \xB7 ${lj(e-i.startedAtMs)} \xB7 ${yri(i.command,Math.max(12,n))}`}let r=t[0];return`${t.length} bash jobs \xB7 oldest ${lj(e-r.startedAtMs)}`}import{basename as xri}from"node:path";function wri(t,e){let n=xri(t);return n.length<=e?n:`${n.slice(0,Math.max(1,e-1))}\u2026`}function tmn(t,e=28){let n=wri(t.file,Math.max(8,e));return t.submit_requested_at===void 0?`review open \xB7 ${n} \xB7 waiting on you`:`review submitted \xB7 ${n} \xB7 companion still editing`}function bri(t,e){return t.length<=e?t:`\u2026${t.slice(t.length-Math.max(1,e-1))}`}function Eri(t){let e=t.lastIndexOf(".");return e===-1?t:t.slice(e+1)}function nmn(t,e=Date.now(),n=28){let r=lj(e-Date.parse(t.created));return`${Eri(t.object_type)} \xB7 ${r} \xB7 ${bri(t.object_name,Math.max(8,n))}`}var vri=34,Sri=30,_ri=40,Cri=12,Iri=6,rmn=22;function imn(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t+" ".repeat(e-t.length)}function kri(t,e){return t.length>=e?t.slice(0,e):" ".repeat(e-t.length)+t}async function omn(t,e,n,r,i=[],o=[],s=[]){let a=r instanceof Nv,c=await r.panelRoster?.(),u=c===void 0?null:new Map(c.nodes.map($e=>[$e.node_id,$e])),l=new Map,d=new Map;if(c!==void 0)for(let $e of c.edges){let X=l.get($e.from_id)??[];X.push($e.to_id),l.set($e.from_id,X),d.has($e.to_id)||d.set($e.to_id,$e.from_id)}let p=new Map,h=new Map,f=new Map,m=$e=>{let X=p.get($e);if(X!==void 0)return X;let Ue=u===null?r.getNode($e).catch(()=>null):Promise.resolve(u.get($e)??null);return p.set($e,Ue),Ue},g=$e=>r.getNode($e).catch(()=>null),y=$e=>{let X=h.get($e);if(X!==void 0)return X;let Ue=(async()=>{let Ke=u===null?(await r.subscriptionsOf($e).catch(()=>[])).map(Nt=>Nt.node_id):l.get($e)??[],Bt=[];for(let Nt of Ke)(await m(Nt))?.kind!=="human"&&Bt.push(Nt);return Bt})();return h.set($e,Ue),Ue},w=$e=>{let X=f.get($e);if(X!==void 0)return X;let Ue=u===null?r.subscribersOf($e).then(Ke=>Ke[0]?.node_id).catch(()=>{}):Promise.resolve(d.get($e));return f.set($e,Ue),Ue},E=async $e=>{let X=[];for(let Ue of await y($e)){let Ke=(await m(Ue))?.status;(Ke==="active"||Ke==="idle")&&X.push(Ue)}return X},S=async $e=>{let X=$e,Ue=new Set([X]);for(;;){let Ke=await w(X);if(Ke===void 0||Ue.has(Ke))break;Ue.add(Ke),X=Ke}return X},C=new Map,I=async $e=>{let X=new Set,Ue=async Ke=>{let Bt=(await m(Ke))?.status==="active";if(X.has(Ke))return Bt?1:0;X.add(Ke);let Nt=0;for(let cn of await y(Ke))Nt+=await Ue(cn);return C.set(Ke,Nt),Nt+(Bt?1:0)};await Ue($e)},M=async $e=>{if($e===null||$e.mode!=="orchestrator")return"";let X=(await y($e.node_id)).length;return X>0?` ${qc}\u2933${X}${Ur}`:""},D=$e=>{if($e===null||$e.status==="active")return"";let X=C.get($e.node_id)??0;return X>0?` ${fde}\u21E3${X}${Ur}`:""},B=n?.muted??($e=>$e),L=n?.faint??($e=>$e);await I(await S(t));let F=await w(t),q=await E(t),j=[...F!==void 0?[F]:[],...q],W=await Promise.all(j.map(async $e=>await g($e)??await m($e))),pe=j.length>0?Math.min(rmn,Math.max(...j.map(($e,X)=>kT(W[X]??null,$e).length))):rmn,K=async($e,X)=>{let Ue=W[j.indexOf($e)]??null,Ke=imn(kT(Ue,$e),pe),Bt=L(imn(Ue?.kind??"",Cri)),Nt=B(kri(gde(Ue,a),Iri)),cn=`${yde(Ue)}${await M(Ue)}${D(Ue)}${wde($e,e)}${Ade(Ue,a)}`,Q=` ${X} ${mde(Ue)} ${Ke} ${Bt} ${Nt}${cn}`;return Px(Q)},Re=[...F!==void 0?[F]:[],...q],Fe=[];F!==void 0&&Fe.push({key:`node:${F}`,kind:"node",nodeId:F,line:await K(F,"\u2191")});for(let $e of q)Fe.push({key:`node:${$e}`,kind:"node",nodeId:$e,line:await K($e,"\u2193")});for(let $e of s){let X=n?n.info("\u270E"):"\u270E",Ue=tmn($e,Math.max(8,yf()-_ri));Fe.push({key:`review:${$e.review_id}`,kind:"review",companionNodeId:$e.companion_node_id,line:` ${X} ${B(`${Ue} \xB7 \u21B5 companion`)}${Ur}`})}let Xe=o.length===1?" \xB7 x stop":"",St=emn(o,Date.now(),yf()-(vri+Xe.length));if(St!==void 0){let $e=n?n.info("\u2699"):"\u2699";Fe.push({key:"bash",kind:"bash",line:` ${$e} ${B(`${St} \xB7 \u21B5 details${Xe}`)}${Ur}`})}let en=Zfn(i);if(en!==void 0){let $e=n?n.info("\u25F7"):"\u25F7";Fe.push({key:"crons",kind:"crons",line:` ${$e} ${B(`${en} \xB7 \u21B5 details`)}${Ur}`})}for(let $e of c?.object_waits??[]){if($e.node_id!==t)continue;let X=n?n.info("\u25C7"):"\u25C7",Ue=nmn($e,Date.now(),Math.max(8,yf()-Sri));Fe.push({key:`object:${$e.object_id}`,kind:"object-wait",objectId:$e.object_id,line:` ${X} ${B(`${Ue} \xB7 \u21B5 details`)}${Ur}`})}return{reports:Fe.map($e=>$e.line),reportIds:Re,items:Fe}}var Tri=15e3;function amn(t,e){let{editor:n,tui:r,pal:i,nodeId:o,remote:s,role:a,canvasSource:c}=t,u=()=>V3(o,t.meta.grantee),l=t.containers.reports,d=[],p,h=process.env.CRTR_ATTACH_ROSTER;h!==void 0&&delete process.env.CRTR_ATTACH_ROSTER;let f,m,g=()=>{e.syncCursor(),l.clear();for(let L of d){let F=L.key===p;l.addChild(new ve(F?Dx(IT(L.line),yf(),Hv):L.line,1,0))}r.requestRender()},y=async()=>{let L=s?[]:(await Ht().listCrons({created_by:o})).filter(W=>W.created_by===o),F=s?[]:Yle(u()),q=s?[]:(await Ht().listReviews({state:"open",origin_node_id:o})).reviews;if(d=(await omn(o,e.asks(),i,c,L,F,q)).items,h!==void 0){let W=h;h=void 0;let pe=d.find(K=>K.kind==="node"&&K.nodeId===W);pe!==void 0&&(p=pe.key)}p!==void 0&&!d.some(W=>W.key===p)&&(p=void 0),f!==void 0&&!F.some(W=>W.jobId===f?.jobId)&&w(!0),g()},w=L=>{m!==void 0&&(clearTimeout(m),m=void 0),f!==void 0&&(f=void 0,L&&e.setNotice(""))},E=()=>{w(!0),p!==void 0&&(p=void 0,g())},S=L=>Wp(L)??(L.length===1?L:void 0),C=(L,F=40)=>{let q=(L.split(`
1728
1728
  `)[0]??"").replace(/\s+/g," ").trim();return q.length>F?`${q.slice(0,F-1)}\u2026`:q},I=()=>{if(a!=="controller"){e.setNotice("Read-only observer attach \u2014 cannot stop background jobs");return}let L=Yle(u());if(L.length===0){e.setNotice("Background job already finished"),e.requestChromeRefresh();return}if(L.length>1){e.setNotice(`${L.length} background jobs \u2014 press \u21B5 to pick one in the Inspector`);return}let F=L[0];f={jobId:F.jobId,label:C(F.command)},e.setNotice(`Stop \u201C${f.label}\u201D? Press y to confirm.`,{sticky:!0}),m=setTimeout(()=>w(!0),Tri)},M=()=>{let L=f;L!==void 0&&(w(!1),e.setNotice(`Stopping \u201C${L.label}\u201D\u2026`),smn("crtr",["node","bash","kill",L.jobId,"--node",o],F=>{e.setNotice(F===null?`Stopped \u201C${L.label}\u201D.`:`Could not stop the job: ${F.message.split(`
1729
1729
  `)[0]}`),e.requestChromeRefresh()}))};n.onCursorDownAtBottom=s?void 0:()=>{p!==void 0||d.length===0||(p=d[0].key,g())};let D=()=>{let L=d.find(j=>j.key===p);if(L===void 0||s)return;if(L.kind==="crons"){E(),e.openInspector("schedule");return}if(L.kind==="review"){if(a!=="controller"){e.setNotice("Read-only observer attach \u2014 cannot open the review companion");return}E();let j=process.env.TMUX_PANE;if(j===void 0||j===""){e.setNotice("Could not open the companion: no tmux pane");return}(async()=>{let W=Ht(),pe=await W.getNode(L.companionNodeId);(await Mde(W,pe,{pane:j})).focused||e.setNotice("Could not open the companion")})().catch(W=>e.setNotice(`Could not open the companion: ${Gc(W).split(`
1730
- `)[0]}`));return}if(L.kind==="bash"){if(Yle(u()).length===0){e.setNotice("Background job already finished"),e.requestChromeRefresh();return}E(),e.openInspector("jobs");return}if(L.kind==="object-wait"){E(),e.openObject(L.objectId);return}let F=L.nodeId;if(F===o){E();return}if(a!=="controller"){e.setNotice("Read-only observer attach \u2014 cannot focus nodes");return}let q=process.env.TMUX_PANE;if(q===void 0||q===""){e.setNotice("cannot swap \u2014 no tmux pane");return}smn("tmux",["run-shell","-b",`crtr surface node focus ${F} --pane ${q} --in-place >/dev/null 2>&1`],()=>{})};return{refresh:y,handleKey:L=>{if(s)return!1;let F=nt(L,"down"),q=nt(L,"up");if(p===void 0)return!1;let j=d.findIndex(pe=>pe.key===p),W=d[j];if(f!==void 0){if(S(L)==="y")return M(),!0;w(!0)}return W?.kind==="bash"&&S(L)==="x"?(I(),!0):q?(j<=0?E():(p=d[j-1].key,g()),!0):F?(j>=0&&j<d.length-1&&(p=d[j+1].key,g()),!0):nt(L,"enter")?(D(),!0):nt(L,"escape")?(E(),!0):(E(),!1)},active:()=>p!==void 0,exit:E}}tt();fa();var tpe=3;function Rri(t){return t.kind==="page"?t.emittedAt:t.blockedSince}function Mri(t){let e=Date.now()-Date.parse(t);if(!Number.isFinite(e)||e<0)return"now";let n=Math.floor(e/6e4);if(n<1)return"now";if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function cmn(t,e){let{nodeId:n,remote:r,canvasSource:i,tui:o,pal:s}=t,a=new et,c=[],u=new Map,l,d=0,p=C=>{let I=C.source.nodeId,M=I!==void 0&&I!==n?` \xB7 ${kT(u.get(I)??null,I)}`:"";return Px(` ${bj}\u2691${Ur} ${C.title}${s.faint(` \xB7 ${Mri(Rri(C))}${M}`)}`)},h=()=>{if(e.syncCursor(),a.clear(),c.length>0&&!e.suppressed()){let C=l===void 0?-1:c.findIndex(M=>M.dir===l);C>=0&&(d=Math.min(Math.max(d,C-tpe+1),C)),d=Math.max(0,Math.min(d,Math.max(0,c.length-tpe)));for(let M of c.slice(d,d+tpe)){let D=p(M);a.addChild(new ve(M.dir===l?Dx(IT(D),yf(),Hv):D,1,0))}let I=c.length-Math.min(tpe,c.length-d);I>0&&a.addChild(new ve(s.faint(` +${I} more`),1,0)),a.addChild(new Zt(s.border))}o.requestRender()},f=async()=>{let C=await i.panelRoster?.(),I=C===void 0?await i.listNodes():C.nodes.map(L=>({node_id:L.node_id,name:L.name,kind:L.kind,status:L.status,...L.description?{description:L.description}:{}})),M=new Map(I.map(L=>[L.node_id,L])),D=new Map,B=async L=>{if(D.has(L))return;let F=M.get(L)??null;if(L!==n&&F?.kind==="human")return;D.set(L,F);let q=await i.subscriptionsOf(L).catch(()=>[]);for(let j of q)await B(j.node_id)};return await B(n),D},m=async()=>{try{await g()}catch(C){e.onRefreshFailure(C)}},g=async()=>{if(r)return;let C=await f(),I=Ht(),[M,D]=await Promise.all([I.listHumanInbox(),I.getInboxHistory(void 0,{state:"pending"})]);u=C;let B=new Map;for(let L of M.tickets){let F=Km(L);B.set(F.dir,F)}for(let L of D.tickets){let F=Km(L);F.kind==="page"&&(F.source.nodeId===void 0||!u.has(F.source.nodeId)||F.state!=="pending"||!F.awaitsResponse||F.inbox||B.has(F.dir)||B.set(F.dir,F))}c=[...B.values()].filter(L=>L.source.nodeId!==void 0&&u.has(L.source.nodeId)).sort($v),l!==void 0&&!c.some(L=>L.dir===l)&&(l=void 0),h()},y=()=>{l!==void 0&&(l=void 0,h())},w=()=>{if(!r){if(l!==void 0){y();return}if(c.length===0){e.setNotice("No pending human requests in this subtree");return}e.exitRoster(),l=c[0].dir,d=0,h()}},E=()=>{let C=c.find(I=>I.dir===l);C!==void 0&&(y(),e.openTicket(C))};return{component:a,refresh:m,handleKey:C=>{if(l===void 0)return!1;let I=c.findIndex(D=>D.dir===l),M=Wp(C)??(C.length===1?C:void 0);return nt(C,"up")||M==="k"?(I>0&&(l=c[I-1].dir,h()),!0):nt(C,"down")||M==="j"?(I>=0&&I<c.length-1?(l=c[I+1].dir,h()):y(),!0):nt(C,"enter")?(E(),!0):nt(C,"escape")?(y(),!0):(y(),!1)},toggle:w,active:()=>l!==void 0,pendingTickets:()=>[...c]}}import{existsSync as Bri,renameSync as Lri,unlinkSync as lmn,writeFileSync as dmn}from"node:fs";import{hostname as CVe}from"node:os";import{randomUUID as Ori}from"node:crypto";import{existsSync as DOs,linkSync as BOs,mkdirSync as LOs,readFileSync as OOs,realpathSync as NOs,unlinkSync as Pri,writeFileSync as $Os}from"node:fs";function Dri(t){return`${t}/progress.json`}function zv(t){return`${t}/claim.json`}function umn(t){try{Pri(Dri(t))}catch(e){if(e.code!=="ENOENT")throw e}}var Nri=3e4;function $ri(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.token!="string"||typeof e.host!="string"||!Number.isInteger(e.pid)||typeof e.claimedAt!="string"||typeof e.heartbeatAt!="string"?null:{token:e.token,host:e.host,pid:e.pid,claimedAt:e.claimedAt,heartbeatAt:e.heartbeatAt,...typeof e.tmuxClient=="string"?{tmuxClient:e.tmuxClient}:{}}}function IVe(t){return $ri(ZT(zv(t)))}function Fri(t){try{return process.kill(t,0),!0}catch{return!1}}function Uri(t,e=Date.now(),n=CVe()){if(t.host===n)return!Fri(t.pid);let r=Date.parse(t.heartbeatAt);return!Number.isFinite(r)||e-r>Nri}function Oj(t,e={}){return Kc(`${t}/.ticket-lock`,()=>{let n=zv(t),r=IVe(t);if(r!==null&&!Uri(r,Date.now(),e.host??CVe()))return null;Bri(n)&&lmn(n);let i=e.host??CVe(),o=e.pid??process.pid,s=(e.now??new Date).toISOString(),a={token:Ori(),host:i,pid:o,claimedAt:s,heartbeatAt:s,...e.tmuxClient?{tmuxClient:e.tmuxClient}:{}};return dmn(n,`${JSON.stringify(a)}
1730
+ `)[0]}`));return}if(L.kind==="bash"){if(Yle(u()).length===0){e.setNotice("Background job already finished"),e.requestChromeRefresh();return}E(),e.openInspector("jobs");return}if(L.kind==="object-wait"){E(),e.openObject(L.objectId);return}let F=L.nodeId;if(F===o){E();return}if(a!=="controller"){e.setNotice("Read-only observer attach \u2014 cannot focus nodes");return}let q=process.env.TMUX_PANE;if(q===void 0||q===""){e.setNotice("cannot swap \u2014 no tmux pane");return}smn("tmux",["run-shell","-b",`crtr surface node focus ${F} --pane ${q} --in-place >/dev/null 2>&1`],()=>{})};return{refresh:y,handleKey:L=>{if(s)return!1;let F=nt(L,"down"),q=nt(L,"up");if(p===void 0)return!1;let j=d.findIndex(pe=>pe.key===p),W=d[j];if(f!==void 0){if(S(L)==="y")return M(),!0;w(!0)}return W?.kind==="bash"&&S(L)==="x"?(I(),!0):q?(j<=0?E():(p=d[j-1].key,g()),!0):F?(j>=0&&j<d.length-1&&(p=d[j+1].key,g()),!0):nt(L,"enter")?(D(),!0):nt(L,"escape")?(E(),!0):(E(),!1)},active:()=>p!==void 0,exit:E}}tt();fa();var tpe=3;function Rri(t){return t.kind==="page"?t.emittedAt:t.blockedSince}function Mri(t){let e=Date.now()-Date.parse(t);if(!Number.isFinite(e)||e<0)return"now";let n=Math.floor(e/6e4);if(n<1)return"now";if(n<60)return`${n}m`;let r=Math.floor(n/60);return r<24?`${r}h`:`${Math.floor(r/24)}d`}function cmn(t,e){let{nodeId:n,remote:r,canvasSource:i,tui:o,pal:s}=t,a=new et,c=[],u=new Map,l,d=0,p=C=>{let I=C.source.nodeId,M=I!==void 0&&I!==n?` \xB7 ${kT(u.get(I)??null,I)}`:"";return Px(` ${bj}\u2691${Ur} ${C.title}${s.faint(` \xB7 ${Mri(Rri(C))}${M}`)}`)},h=()=>{if(e.syncCursor(),a.clear(),c.length>0&&!e.suppressed()){let C=l===void 0?-1:c.findIndex(M=>M.dir===l);C>=0&&(d=Math.min(Math.max(d,C-tpe+1),C)),d=Math.max(0,Math.min(d,Math.max(0,c.length-tpe)));for(let M of c.slice(d,d+tpe)){let D=p(M);a.addChild(new ve(M.dir===l?Dx(IT(D),yf(),Hv):D,1,0))}let I=c.length-Math.min(tpe,c.length-d);I>0&&a.addChild(new ve(s.faint(` +${I} more`),1,0)),a.addChild(new Zt(s.border))}o.requestRender()},f=async()=>{let C=await i.panelRoster?.(),I=C===void 0?await i.listNodes():C.nodes.map(L=>({node_id:L.node_id,name:L.name,kind:L.kind,status:L.status,...L.description?{description:L.description}:{}})),M=new Map(I.map(L=>[L.node_id,L])),D=new Map,B=async L=>{if(D.has(L))return;let F=M.get(L)??null;if(L!==n&&F?.kind==="human")return;D.set(L,F);let q=await i.subscriptionsOf(L).catch(()=>[]);for(let j of q)await B(j.node_id)};return await B(n),D},m=async()=>{try{await g()}catch(C){e.onRefreshFailure(C)}},g=async()=>{if(r)return;let C=await f(),I=Ht(),[M,D]=await Promise.all([I.listHumanInbox(),I.getInboxHistory(void 0,{state:"pending"})]);u=C;let B=new Map;for(let L of M.tickets){let F=Km(L);B.set(F.dir,F)}for(let L of D.tickets){let F=Km(L);F.kind==="page"&&(F.source.nodeId===void 0||!u.has(F.source.nodeId)||F.state!=="pending"||!F.awaitsResponse||F.inbox||B.has(F.dir)||B.set(F.dir,F))}c=[...B.values()].filter(L=>L.source.nodeId!==void 0&&u.has(L.source.nodeId)).sort($v),l!==void 0&&!c.some(L=>L.dir===l)&&(l=void 0),h()},y=()=>{l!==void 0&&(l=void 0,h())},w=()=>{if(!r){if(l!==void 0){y();return}if(c.length===0){e.setNotice("No pending human requests in this subtree");return}e.exitRoster(),l=c[0].dir,d=0,h()}},E=()=>{let C=c.find(I=>I.dir===l);C!==void 0&&(y(),e.openTicket(C))};return{component:a,refresh:m,handleKey:C=>{if(l===void 0)return!1;let I=c.findIndex(D=>D.dir===l),M=Wp(C)??(C.length===1?C:void 0);return nt(C,"up")||M==="k"?(I>0&&(l=c[I-1].dir,h()),!0):nt(C,"down")||M==="j"?(I>=0&&I<c.length-1?(l=c[I+1].dir,h()):y(),!0):nt(C,"enter")?(E(),!0):nt(C,"escape")?(y(),!0):(y(),!1)},toggle:w,active:()=>l!==void 0,pendingTickets:()=>[...c]}}import{existsSync as Bri,renameSync as Lri,unlinkSync as lmn,writeFileSync as dmn}from"node:fs";import{hostname as CVe}from"node:os";import{randomUUID as Ori}from"node:crypto";import{existsSync as LOs,linkSync as OOs,mkdirSync as NOs,readFileSync as $Os,realpathSync as FOs,unlinkSync as Pri,writeFileSync as UOs}from"node:fs";function Dri(t){return`${t}/progress.json`}function zv(t){return`${t}/claim.json`}function umn(t){try{Pri(Dri(t))}catch(e){if(e.code!=="ENOENT")throw e}}var Nri=3e4;function $ri(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.token!="string"||typeof e.host!="string"||!Number.isInteger(e.pid)||typeof e.claimedAt!="string"||typeof e.heartbeatAt!="string"?null:{token:e.token,host:e.host,pid:e.pid,claimedAt:e.claimedAt,heartbeatAt:e.heartbeatAt,...typeof e.tmuxClient=="string"?{tmuxClient:e.tmuxClient}:{}}}function IVe(t){return $ri(ZT(zv(t)))}function Fri(t){try{return process.kill(t,0),!0}catch{return!1}}function Uri(t,e=Date.now(),n=CVe()){if(t.host===n)return!Fri(t.pid);let r=Date.parse(t.heartbeatAt);return!Number.isFinite(r)||e-r>Nri}function Oj(t,e={}){return Kc(`${t}/.ticket-lock`,()=>{let n=zv(t),r=IVe(t);if(r!==null&&!Uri(r,Date.now(),e.host??CVe()))return null;Bri(n)&&lmn(n);let i=e.host??CVe(),o=e.pid??process.pid,s=(e.now??new Date).toISOString(),a={token:Ori(),host:i,pid:o,claimedAt:s,heartbeatAt:s,...e.tmuxClient?{tmuxClient:e.tmuxClient}:{}};return dmn(n,`${JSON.stringify(a)}
1731
1731
  `,{flag:"wx",mode:384}),a})}function npe(t,e,n=new Date){return Kc(`${t}/.ticket-lock`,()=>{let r=IVe(t);if(r===null||r.token!==e)return!1;let i=`${zv(t)}.${e}.heartbeat`;return dmn(i,`${JSON.stringify({...r,heartbeatAt:n.toISOString()})}
1732
1732
  `,{flag:"wx",mode:384}),Lri(i,zv(t)),!0})}function Qri(t,e){let n=IVe(t);return n===null||n.token!==e?!1:(lmn(zv(t)),!0)}function Xm(t,e){return Kc(`${t}/.ticket-lock`,()=>Qri(t,e))}function FN(t){return kde("inbox-activity",t)}var rpe=(t,e)=>e==="single"&&(t.kind==="options"||t.kind==="cards");function fmn(t,e,n,r,i){if(e.ctrl&&t==="c"){i(!1);return}if(n.hint=void 0,n.inputMode!==null){Vri(t,e,n,r);return}n.phase==="overview"?Wri(t,e,n,r,i):n.phase==="item-review"?Hri(t,e,n,r,i):qri(t,e,n,r,i)}function TVe(t,e,n){return t==="d"||e.pageDown||e.ctrl&&(t==="d"||t==="e")?(n.scrollOffset+=t==="e"?1:10,n.followSelection=!1,!0):t==="u"||e.pageUp||e.ctrl&&(t==="u"||t==="y")?(n.scrollOffset=Math.max(0,n.scrollOffset-(t==="y"?1:10)),n.followSelection=!1,!0):!1}function Wri(t,e,n,r,i){if(TVe(t,e,n)){r();return}if(t==="j"||e.downArrow)n.currentIndex=Math.min(n.currentIndex+1,Math.max(0,n.slots.length-1)),n.followSelection=!0;else if(t==="k"||e.upArrow)n.currentIndex=Math.max(n.currentIndex-1,0),n.followSelection=!0;else if((e.return||t===" ")&&n.slots.length>0)n.phase="item-review",RVe(n);else if(t==="q"||e.escape){i(!n.manifest.slots.some(fc));return}else return;r()}function Hri(t,e,n,r,i){let o=n.slots[n.currentIndex];if(o===void 0){n.phase="overview",r();return}let s=Wle(o);if(t==="n"){kVe(n,1),r();return}if(t==="p"){kVe(n,-1),r();return}if(t==="q"||e.escape){i(!1);return}if(TVe(t,e,n)){r();return}if((t==="h"||t==="l"||e.leftArrow||e.rightArrow)&&n.hscrollMax>0&&!s.some(c=>c.kind==="select"&&c.shortcut===t)){whn(n,t==="h"||e.leftArrow?-1:1),r();return}if(t==="j"||e.downArrow){n.selectedAction=Math.min(n.selectedAction+1,Math.max(0,s.length-1)),r();return}if(t==="k"||e.upArrow){n.selectedAction=Math.max(0,n.selectedAction-1),r();return}if(t==="c"&&EN(o).length>0){jri(n,o,s),r();return}let a=s.find(c=>c.kind==="select"&&c.shortcut===t);if(a?.kind==="select"){pmn(n,o,a,rpe(o,a.mode)),r(),rpe(o,a.mode)&&n.phase==="final"&&Fv(n)&&i(!0);return}if(t===" "&&s[n.selectedAction]?.kind==="select"){let c=s[n.selectedAction];pmn(n,o,c,rpe(o,c.mode)),r(),rpe(o,c.mode)&&n.phase==="final"&&Fv(n)&&i(!0);return}if(t==="r"&&s.some(c=>c.kind==="freetext")){let c=PT(o,n.responses.get(o.id));n.inputMode={kind:"freetext",buffer:c.freetext??"",cursor:[...c.freetext??""].length},r();return}if(t==="e"&&s.some(c=>c.kind==="edit")){let c=PT(o,n.responses.get(o.id));n.inputMode={kind:"text",buffer:c.text,cursor:[...c.text].length},r();return}if(t==="a"&&s.some(c=>c.kind==="accept")){fy(n,o,{text:o.config.initialText,edited:!1}),DT(n),r();return}if(e.return){let c=s[n.selectedAction];if(c?.kind==="freetext"){let u=PT(o,n.responses.get(o.id));n.inputMode={kind:"freetext",buffer:u.freetext??"",cursor:[...u.freetext??""].length},r();return}if(c?.kind==="edit"){let u=PT(o,n.responses.get(o.id));n.inputMode={kind:"text",buffer:u.text,cursor:[...u.text].length},r();return}if(c?.kind==="accept"){fy(n,o,{text:o.config.initialText,edited:!1}),DT(n),r();return}if(kx(n,o)){DT(n),r();return}if(Ip(o)){let u=PT(o,n.responses.get(o.id));if(e6e(n,o,u)){fy(n,o,u),DT(n),r();return}}if(fc(o)){n.hint=Ip(o)?"Select at least one option (space to toggle), or q to go back":"This must be answered in Northlight",r();return}kVe(n,1),r()}}function qri(t,e,n,r,i){if(t==="q"||e.escape){n.phase=n.slots.length===1?"item-review":"overview",n.scrollOffset=0,r();return}if(TVe(t,e,n)){r();return}e.return&&(Fv(n)||!n.manifest.slots.some(fc))&&i(!0)}function RVe(t){t.selectedAction=0,t.scrollOffset=0,t.followSelection=!0,t.hscrollOffset=0,t.hscrollMax=0}function kVe(t,e){let n=t.currentIndex+e;if(n<0){t.phase=t.slots.length>1?"overview":"item-review",t.scrollOffset=0,t.followSelection=!0;return}if(n>=t.slots.length){t.phase="final",t.scrollOffset=0,t.followSelection=!0;return}t.currentIndex=n,RVe(t)}function DT(t){for(let e=t.currentIndex+1;e<t.slots.length;e++){let n=t.slots[e];if(fc(n)&&!kx(t,n)){t.currentIndex=e,RVe(t);return}}t.phase="final",t.scrollOffset=0}function PT(t,e){return e!==void 0?e:t.kind==="options"?{selectedOptionIds:[],comments:[]}:t.kind==="cards"?{selectedCardIds:[]}:t.kind==="table"?{selectedRowIds:[],selectedColumnIds:[],comments:[]}:t.kind==="text"?{text:t.config.initialText,edited:!1}:{}}function MVe(t){return[...t?.comments??[]]}function fy(t,e,n){e.id!==void 0&&(t.responses.set(e.id,n),t.persist?.())}function pmn(t,e,n,r){let i=PT(e,t.responses.get(e.id));if(e.kind==="options"){let o=i,s=ipe(o.selectedOptionIds,n.id,n.mode);fy(t,e,{...o,selectedOptionIds:s})}else if(e.kind==="cards"){let o=i;fy(t,e,{...o,selectedCardIds:ipe(o.selectedCardIds,n.id,n.mode)})}else if(e.kind==="table"){let o=i;n.group==="row"?fy(t,e,{...o,selectedRowIds:ipe(o.selectedRowIds,n.id,n.mode)}):fy(t,e,{...o,selectedColumnIds:ipe(o.selectedColumnIds,n.id,n.mode)})}r&&DT(t)}function ipe(t,e,n){return n==="single"?[e]:t.includes(e)?t.filter(r=>r!==e):[...t,e]}function Gri(t){if(t?.kind==="select"){if(t.group==="option")return{kind:"option",optionId:t.id};if(t.group==="row")return{kind:"row",rowId:t.id}}}function jri(t,e,n){let r=Gri(n[t.selectedAction])??EN(e)[0],o=MVe(e.id===void 0?void 0:t.responses.get(e.id)).find(s=>s.id===bN(r))?.text??"";t.inputMode={kind:"comment",buffer:o,cursor:[...o].length,anchor:r}}function zri(t){if(t.inputMode?.kind!=="comment")return;let e=t.slots[t.currentIndex],n=EN(e);if(n.length===0)return;let r=bN(t.inputMode.anchor),i=n.findIndex(a=>bN(a)===r),o=n[(i+1)%n.length],s=MVe(e.id===void 0?void 0:t.responses.get(e.id)).find(a=>a.id===bN(o))?.text??"";t.inputMode={kind:"comment",anchor:o,buffer:s,cursor:[...s].length}}function Vri(t,e,n,r){let i=n.inputMode;if(e.escape){n.inputMode=null,r();return}if(e.tab&&i.kind==="comment"){zri(n),r();return}if(e.return){Kri(n),r();return}if(e.newline){mmn(i,`
1733
1733
  `),r();return}e.wordLeft?i.cursor=kj(i.buffer,i.cursor):e.wordRight?i.cursor=Ode(i.buffer,i.cursor):e.leftArrow?i.cursor=Math.max(0,i.cursor-1):e.rightArrow?i.cursor=Math.min([...i.buffer].length,i.cursor+1):e.upArrow?i.cursor=Tj(i.buffer,i.cursor,-1,hmn(n)):e.downArrow?i.cursor=Tj(i.buffer,i.cursor,1,hmn(n)):e.home||e.ctrl&&t==="a"?i.cursor=eii(i.buffer,i.cursor):e.end||e.ctrl&&t==="e"?i.cursor=tii(i.buffer,i.cursor):e.meta&&e.backspace?Jri(i):e.backspace||t==="\x7F"?Yri(i):e.del||e.ctrl&&t==="d"?Zri(i):!e.ctrl&&!e.meta&&Xri(i,t),r()}function Kri(t){let e=t.inputMode,n=t.slots[t.currentIndex],r=PT(n,n.id===void 0?void 0:t.responses.get(n.id));if(e.kind==="comment"){let i=e.anchor,o=bN(i),s=MVe(r).filter(a=>a.id!==o);e.buffer.trim()!==""&&s.push({id:o,anchor:i,text:e.buffer}),fy(t,n,{...r,comments:s})}else e.kind==="freetext"?(fy(t,n,{...r,freetext:e.buffer}),DT(t)):(fy(t,n,{text:e.buffer,edited:e.buffer!==n.config.initialText}),DT(t));t.inputMode=null}function mmn(t,e){let n=[...t.buffer];n.splice(t.cursor,0,...e),t.buffer=n.join(""),t.cursor+=[...e].length}function Yri(t){if(t.cursor===0)return;let e=[...t.buffer];e.splice(t.cursor-1,1),t.buffer=e.join(""),t.cursor--}function Jri(t){let e=kj(t.buffer,t.cursor);if(e===t.cursor)return;let n=[...t.buffer];n.splice(e,t.cursor-e),t.buffer=n.join(""),t.cursor=e}function Xri(t,e){let n=e.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g,"").replace(/\r\n?/g,`
@@ -1750,7 +1750,7 @@ Follow the instructions below exactly as written \u2014 every part, including th
1750
1750
  ${r}`}function Umn(t){try{let e=JSON.parse(t);return Array.isArray(e)?e.flatMap(n=>{if(typeof n!="object"||n===null||Array.isArray(n))return[];let r=n;return typeof r.name!="string"||typeof r.description!="string"||typeof r.source!="string"?[]:r.source!=="builtin"&&r.source!=="command"&&r.source!=="template"?[]:r.template!==void 0&&typeof r.template!="string"?[]:r.expansion!==void 0&&!ppe(r.expansion)?[]:[{name:r.name,description:r.description,source:r.source,...typeof r.template=="string"?{template:r.template}:{},...ppe(r.expansion)?{expansion:r.expansion}:{}}]}):[]}catch{return[]}}function Qii(t){let e=[],n="",r=null;for(let i of t)r!==null?i===r?r=null:n+=i:i==='"'||i==="'"?r=i:/\s/.test(i)?n!==""&&(e.push(n),n=""):n+=i;return n!==""&&e.push(n),e}function Wii(t,e){let n=e.join(" ");return t.replace(/\$\{(\d+):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(r,i,o,s,a,c)=>{if(i!==void 0)return e[Number.parseInt(i,10)-1]||o||"";if(s!==void 0){let u=Math.max(0,Number.parseInt(s,10)-1);return a!==void 0?e.slice(u,u+Number.parseInt(a,10)).join(" "):e.slice(u).join(" ")}return c==="ARGUMENTS"||c==="@"?n:e[Number.parseInt(c||"0",10)-1]??""})}function Qmn(t,e){let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(n===null)return;let r=n[1];if(e.some(c=>c.source==="builtin"&&c.name===r))return;let i=t.indexOf(" "),o=i===-1?t.slice(1):t.slice(1,i),s=e.find(c=>c.source==="command"&&c.name===o);if(s!==void 0){if(s.expansion===void 0||!ppe(s.expansion))return;let c=i===-1?"":t.slice(i+1);return{name:s.name,invocation:t,content:Fmn(s.expansion,c)}}let a=e.find(c=>c.source==="template"&&c.name===r);if(typeof a?.template=="string")return{name:a.name,invocation:t,content:Wii(a.template,Qii(n[2]??""))}}var Hii="CRTR_TIMING",Wmn="CRTR_TIMING_T0";function qii(){return performance.timeOrigin+performance.now()}var Hmn=(()=>{let t=process.env[Hii];return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"})(),Gii=(()=>{if(!Hmn)return 0;let t=Number(process.env[Wmn]);if(Number.isFinite(t)&&t>0)return t;let e=performance.timeOrigin;return process.env[Wmn]=String(e),e})(),jii=(()=>{let t=process.env.CRTR_TIMING_PROC;return t!==void 0&&t!==""?t:process.argv[2]==="surface"&&process.argv[3]==="attach"?"viewer":"cli"})(),OVe=0;function LT(t,e){if(!Hmn)return;let n=qii(),r=n-Gii,i=OVe===0?r:n-OVe;OVe=n;let o=performance.now(),s=e===void 0?"":" "+Object.entries(e).map(([u,l])=>`${u}=${String(l)}`).join(" "),a=process.env.CRTR_TIMING_PROC??jii,c=u=>u.toFixed(1).padStart(8);process.stderr.write(`[timing] +${c(r)}ms \u0394${c(i)}ms up=${c(o)}ms t=${n.toFixed(1)} ${a}/${process.pid} ${t}${s}
1751
1751
  `)}function qmn(t,e){let{socket:n}=t,r=()=>{n.send({type:"get_commands"}),e.resetMemoryRefs()},i=a=>{if(a.for==="get_commands"&&a.ok&&a.detail){try{e.setCommands(Umn(a.detail))}catch{}return}if(a.for==="navigate_tree"&&a.ok){a.detail&&e.setEditorText(a.detail);return}if(a.for==="share"){a.ok&&a.detail?(e.setNotice(`Shared: ${a.detail}`),I6e(a.detail)):a.ok||e.setNotice(`share failed: ${a.detail??"unknown error"}`);return}if(a.for==="clone"&&!a.ok){e.setNotice(`clone failed: ${a.detail??"unknown error"}`);return}if(!a.ok){e.setNotice(`command failed: ${a.for}${a.detail?` \u2014 ${a.detail}`:""}`);return}a.for==="reload"&&(e.reloadBindings(),e.setCommands(),r(),e.setNotice("Reloaded keybindings, extensions, skills, prompts, and themes"))},o=a=>{e.chat.handleEvent(a),a.type==="session_info_changed"?e.refreshNodeIdentity():a.type==="thinking_level_changed"?e.setNotice(e.modelThinkingLabel()??`Thinking level: ${a.level}`):(a.type==="tool_execution_start"||a.type==="tool_execution_end")&&e.renderFooter()},s=!1;return a=>{switch(e.foldState(a),a.type){case"welcome":{s||(s=!0,LT("viewer.welcome")),e.chat.applySnapshot(a.snapshot),e.refreshNodeIdentity(),r(),a.pending_dialog!=null&&e.attachDialog(a.pending_dialog),e.onWelcome?.();break}case"tool_group_summary":e.chat.applyToolGroupSummary(a.key,a.summary);break;case"turn_reply":e.chat.applyTurnReply(a.key,a.reply);break;case"working_activity":e.chat.setWorkingActivity(a.activity);break;case"model_changed":{let c=e.modelThinkingLabel();c&&e.setNotice(c);break}case"error":a.code==="read_only"?e.setNotice("read-only"):e.chat.showError(a.message);break;case"node_named":break;case"ack":i(a);break;case"extension_ui_request":a.method!=="setStatus"&&a.method!=="setWidget"&&a.method!=="setTitle"&&e.attachDialog(a);break;case"extension_ui_dismiss":e.dismissDialog(a.id);break;case"bash_start":e.chat.bashStart(a.command,a.excludeFromContext);break;case"bash_output":e.chat.bashOutput(a.chunk);break;case"bash_end":e.chat.bashEnd(a);break;default:o(a);break}}}var zii=1e3;function Gmn(t,e){let{tui:n,editor:r}=t,i=0,o={"crtr.attach.detach":e.detach,"crtr.attach.clear-or-detach":()=>{let s=Date.now();if(s-i<zii){i=0,e.cancelTurn();return}i=s,r.setText(""),e.setNotice(`Editor cleared \u2014 press ${e.detachHint()} again to cancel the agent`),n.requestRender()},"crtr.attach.graph.toggle":e.toggleGraph,"crtr.attach.help.toggle":e.toggleHelp,"crtr.attach.inbox.toggle":e.toggleInbox,"crtr.attach.inbox-strip":e.toggleInboxStrip,"crtr.attach.model-ladder.next":()=>e.cycleModelLadder("forward"),"crtr.attach.model-ladder.previous":()=>e.cycleModelLadder("backward"),"crtr.attach.command.inspect":e.inspectLoadedCommand,"crtr.attach.file-review":e.openFileReview,"crtr.attach.profile-files":e.openProfileFiles,"crtr.attach.search":e.openSearch,"crtr.attach.whip":e.whip};return n.addInputListener(s=>{if(s.includes("\x1B[I")||s.includes("\x1B[O")){e.setPaneFocused(s.lastIndexOf("\x1B[I")>s.lastIndexOf("\x1B[O")),n.requestRender();let c=s.replaceAll("\x1B[I","").replaceAll("\x1B[O","");return c.length>0?{data:c}:{consume:!0}}let a=gge(s);if(a!==void 0)return S6e(a.actionId,o),a.remaining.length>0?{data:a.remaining}:{consume:!0};if(!e.hasExclusiveSurface())return e.panelHandleKey(s)?{consume:!0}:e.searchHandleKey(s)?{consume:!0}:r.focused&&rpn(e.bindings(),s,e.viewportActions())?{consume:!0}:e.stripHandleKey(s)?{consume:!0}:e.rosterHandleKey(s)?{consume:!0}:npn(e.bindings(),s,o)?{consume:!0}:void 0})}import{spawnSync as Vii}from"node:child_process";var Kii="\x1B[?1002h\x1B[?1006h",jmn="\x1B[?1002l\x1B[?1006l",zmn=3;function Yii(){if(!Rs())return!1;let t=Vii("tmux",["show-options","-gv","mouse"],{encoding:"utf8"});return t.status===0&&t.stdout?.trim()==="on"}function Vmn(t,e){let n=e==="on"||e==="tmux"&&Yii(),r=()=>{t(n?Kii:jmn)},i=()=>{n=!1;try{t(jmn)}catch{}};return process.once("exit",i),{enabled:()=>n,toggle:()=>(n=!n,r(),n),reassert:r,disable:i,install:(o,s)=>o.addInputListener(a=>{let c=!1,l=a.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g,(d,p,h,f,m)=>{c=!0;let g=Number(p),y=g&-29;return y===64?s.onWheel("up",zmn,Number(h)):y===65?s.onWheel("down",zmn,Number(h)):y===32&&m==="M"?s.onPrimaryDrag(Number(h),Number(f)):y===0&&m==="m"?s.onPrimaryRelease(Number(h),Number(f)):g===0&&m==="M"&&s.onPrimaryPress(Number(h),Number(f)),""}).replace(/\x1b\[M[\s\S]{3}/g,()=>(c=!0,""));if(c)return l.length>0?{data:l}:{consume:!0}})}}function Jii(t,e){return t.row<e.row||t.row===e.row&&t.column<=e.column}function Kmn(t,e,n){let[r,i]=Jii(t,e)?[t,e]:[e,t],o=[];for(let s=r.row;s<=i.row;s++){let a=s===r.row?r.column-1:0,c=s===i.row?i.column:n;c>a&&o.push({row:s,from:a,to:c})}return o}function Ymn(t){let e,n,r=()=>e!==void 0&&n!==void 0?{anchor:e,head:n}:void 0,i=()=>{let o=r();if(!o)return"";let s=t.frame(),a=Kmn(o.anchor,o.head,t.width()).map(c=>Gdn(s[c.row-1]??"",c.from,c.to).trimEnd());for(;a.length>0&&a[a.length-1]==="";)a.pop();return a.join(`
1752
1752
  `)};return{begin(o,s){e={row:s,column:o},n=void 0},extend(o,s){return e===void 0||n!==void 0&&n.row===s&&n.column===o?!1:(n={row:s,column:o},!0)},release(){let o=e;if(o===void 0)return;if(n===void 0)return e=void 0,{kind:"click",column:o.column,row:o.row};let s=i();if(s==="")return e=void 0,n=void 0,{kind:"selection",notice:"Nothing to copy \u2014 selection is empty"};let{system:a,tmux:c}=bde(s),u=a&&c?"clipboard + tmux buffer":a?"clipboard":c?"tmux buffer":void 0,l=s.split(`
1753
- `).length;return{kind:"selection",notice:u===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${l} ${l===1?"line":"lines"}) \u2014 ${u}`}},clear(){let o=n!==void 0;return e=void 0,n=void 0,o},active(){return n!==void 0},apply(o){let s=r();if(!s)return o.slice();let a=t.width(),c=o.slice();for(let u of Kmn(s.anchor,s.head,a)){let l=u.row-1;l<0||l>=c.length||(c[l]=jdn(c[l],u.from,u.to,a))}return c}}}import{existsSync as Xii}from"node:fs";var Jmn="\x1B_crtr-file-open;",Xmn="\x1B\\";function Zmn(t){let e=t.indexOf(Jmn);if(e===-1)return;let n=e+Jmn.length,r=t.indexOf(Xmn,n);return r===-1?void 0:{file:Zii(t.slice(n,r)),remaining:t.slice(0,e)+t.slice(r+Xmn.length)}}function Zii(t){let e=t.startsWith("'")?eoi(t):toi(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function eoi(t){let e="",n=1;for(;;){let r=t.indexOf("'",n);if(r===-1)return;if(e+=t.slice(n,r),n=r+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function toi(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let r=t[++n];if(r===void 0)return;e+=r}return e}function egn(t){if(!Xii(t.file))return"missing";if(!_Ke())return"no_nvim";let e=`crtr surface attach to ${un(t.nodeId)}${t.observer?" --observer":""}`,n=`${XT("edit",[t.file])} || :; exec ${e}`;return t.beforeRespawn(),Rge({pane:t.pane,cwd:t.cwd,env:K$(),command:n})?"opened":"failed"}function tgn(t){let e=new Map,n=!1,r=!1,i;t.remote||t.fetchSecret().then(a=>{i=a,aqe(),r||t.refresh()},t.onSecretError);let o=()=>{if(n)return;n=!0;let a=t.canvasSource;(a.panelRoster?a.panelRoster().then(u=>u.nodes):a.listNodes()).then(u=>{for(let l of u)e.set(l.node_id,l.name);aqe(),r||t.refresh()},()=>{n=!1})},s={selfNodeId:t.selfNodeId,nodeName:a=>{let c=e.get(a);return c===void 0&&o(),c},urlFor:a=>t.remote||i===void 0?void 0:`http://127.0.0.1:${t.port}/r/${a.split("/").map(encodeURIComponent).join("/")}?t=${i}`};return cqe(s),{dispose(){r=!0,cqe(void 0)}}}tt();import{execFile as noi}from"node:child_process";function FVe(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function ngn(t){let e=(t.description??"").trim(),r=[t.name&&t.name!==t.kind?t.name:"",e].filter(i=>i!=="").join(" ");return r!==""?r:t.name}function rgn(t){return`${FVe(t.mode)} ${t.kind}`}var roi=.72,ioi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},ooi=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],soi=[["crtr.graph.dismiss","dismiss"]],aoi=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]],coi=[...["active","idle","done","dead","canceled"].map(t=>[CT(t,{}),t]),[CT("active",{streaming:!0}),"live"],[CT("active",{frozen:!0}),"frozen"],[CT("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${Rp}${t.color}m${t.glyph}${Ur} ${qc}${e}${Ur}`).join(" ");function uoi(t){return{node_id:t.node_id,name:t.name,kind:t.kind,description:t.description??void 0,cycles:t.cycles??void 0,status:t.status,frozen_at:t.frozen_at,pi_pid:t.pi_pid,telemetry_context_tokens:t.telemetry_context_tokens,telemetry_last_activity:t.telemetry_last_activity,fault:t.fault??null,streaming:t.streaming}}var hpe=class{constructor(e,n,r,i,o,s,a="controller",c=()=>{},u=()=>{}){this.tui=e;this.self=n;this.getAsks=r;this.palette=i;this.bindings=o;this.source=s;this.role=a;this.onRefreshFailure=c;this.onNotice=u;this.remote=s instanceof Nv}tui;self;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return IS(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${Gs(this.bindings,n)} ${r}`])}fitHints(e,n){let i=[],o=0;for(let s of this.hint(e)){let a=(i.length===0?0:3)+kd(s);if(o+a>n)break;i.push(s),o+=a}return i.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,ioi),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;let e=++this.snapshotSeq;this.buildSnapshot().then(n=>{e===this.snapshotSeq&&(this.snapshot=n,this.tui.requestRender())}).catch(n=>{this.onRefreshFailure(n),this.tui.requestRender()})}invalidate(){this.refresh()}async fetchInput(){if(this.remote){let i=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(i.map(o=>[o.node_id,o])),subscriptions:async o=>(await this.source.subscriptionsOf(o)).map(s=>s.node_id),subscribers:async o=>(await this.source.subscribersOf(o)).map(s=>s.node_id),focused:new Set}}let e=await Ht().canvasGraph(),n=new Map,r=new Map;for(let i of e.edges){let o=n.get(i.from_id);o===void 0?n.set(i.from_id,[i.to_id]):o.push(i.to_id);let s=r.get(i.to_id);s===void 0?r.set(i.to_id,[i.from_id]):s.push(i.from_id)}return{nodes:new Map(e.nodes.map(i=>[i.node_id,uoi(i)])),subscriptions:i=>Promise.resolve(n.get(i)??[]),subscribers:i=>Promise.resolve(r.get(i)??[]),focused:new Set(e.focused_node_ids)}}async buildSnapshot(){let e=await this.fetchInput(),{nodes:n,focused:r}=e,i=new Map,o=new Map,s=new Map,a=new Map,c=async y=>{let w=i.get(y);if(w!==void 0)return w;let E;try{E=await e.subscriptions(y)}catch{E=[]}let S=E.filter(C=>n.get(C)?.kind!=="human");return i.set(y,S),S},u=async y=>{if(s.has(y))return s.get(y);let w;try{w=(await e.subscribers(y))[0]}catch{w=void 0}return s.set(y,w),w},l=async()=>{let y=this.self,w=new Set([y]);for(;;){let E=await u(y);if(E===void 0||w.has(E))break;w.add(E),y=E}return y},d=async y=>{let w=o.get(y);if(w!==void 0)return w;let E=[...await c(y)];return E.sort((S,C)=>V6e(n.get(S)?.status)-V6e(n.get(C)?.status)),o.set(y,E),E},p=new Set,h=new Set,f=async y=>{let w=n.get(y)?.status==="active";if(h.has(y))return{active:w?1:0,reveal:w||y===this.self};h.add(y);let E=0,S=!1;for(let C of await c(y)){let I=await f(C);E+=I.active,I.reveal&&(S=!0)}return a.set(y,E),S&&p.add(y),{active:E+(w?1:0),reveal:S||w||y===this.self}},m=await l();await f(m),await Promise.all([...i.keys()].map(y=>d(y)));let g={root:m,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return g.rows=this.projectRows(g),g}projectRows(e){let n=[],r=new Set,i=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;i.length>0;){let{id:o,prefix:s,isRoot:a,isLast:c}=i.pop(),u=a?"":c?"\u2514\u2500 ":"\u251C\u2500 ";if(r.has(o)){n.push({id:o,hasKids:!1,isSelf:o===this.self,branch:s+u,cycle:!0,collapsed:!1});continue}r.add(o);let l=e.sortedChildIds.get(o)??[],d=this.folds.userExpanded.has(o)?!1:this.folds.userCollapsed.has(o)?!0:!e.autoExpanded.has(o);if(n.push({id:o,hasKids:l.length>0,isSelf:o===this.self,branch:s+u,cycle:!1,collapsed:d}),d)continue;let p=a?"":s+(c?" ":"\u2502 ");for(let h=l.length-1;h>=0;h--)i.push({id:l[h],prefix:p,isRoot:!1,isLast:h===l.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,r,i){let o=(C,I)=>r?Dx(C,yf(),Hv):I?Dx(C,yf(),Zdn):Px(C);if(n.cycle){let C=`${n.branch} ${qc}\u21BA ${xde(n.id)}${Ur}`;return o(C,!1)}let s=e.nodes.get(n.id)??null,a=mde(s),c=kT(s,n.id),u=n.isSelf?`${wj}${c}${Ur}`:c,l=`${qc}${s?.kind??""}${Ur}`,d=`${qc}${gde(s,this.remote)}${Ur}`,p=n.hasKids&&n.collapsed,h=!r&&p?`${qc}\u25B8${Ur} `:" ",f=yde(s),m=e.childIds.get(n.id)?.length??0,g=s!==null&&m>0?` ${qc}\u2933${m}${Ur}`:"",y=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${fde}\u21E3${e.activeBelow.get(s.node_id)??0}${Ur}`:"",w=s?.fault??null,E=w!==null?` \xB7 ${Jdn(w)}`:"",S=`${n.branch}${h}${a} ${u} ${l} ${d}${f}${g}${y}${wde(n.id,i)}${Ade(s,this.remote)}${E}`;return o(S,tpn(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(E=>E.id===this.cursorId);i<0&&(i=r.findIndex(E=>E.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??Xdn,s=Math.max(3,Math.min(Math.floor(o*roi),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let E=0;c>0&&E<4;E++){i<this.scrollTop&&(this.scrollTop=i),i>=this.scrollTop+l&&(this.scrollTop=i-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,r.length-l)));let S=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(S===l)break;l=Math.max(1,S)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${qc} \u2191 ${this.scrollTop} more${Ur}`);for(let E=this.scrollTop;E<d;E++){let S=this.snapshot;p.push(S!==void 0?this.renderSnapshotRow(S,r[E],E===i,n):"")}for(u&&d<r.length&&p.push(`${qc} \u2193 ${r.length-d} more${Ur}`),p.unshift(coi);p.length<a;)p.push("");let h=r.length>0?`${wj}\u2317 canvas graph${Ur} ${qc}(${i+1}/${r.length})${Ur}`:`${wj}\u2317 canvas graph${Ur} ${qc}(loading)${Ur}`,f=this.pendingConfirm!==void 0?`${bj}${this.pendingConfirm.label} ${wj}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${Ur}`:`${qc}${this.fitHints([...this.remote||this.role!=="controller"?soi:ooi,...aoi],Math.max(1,e-5))}${Ur}`,m=this.palette.border,g=Math.max(1,e-4),y=p.map(E=>`${m("\u2502")} ${ot(E,g,"",!0)} ${m("\u2502")}`),w=this.palette.surface;return[this.borderRow("\u256D","\u256E",h,e),...y,this.borderRow("\u2570","\u256F",f,e)].map(w)}borderRow(e,n,r,i){let o=this.palette.border,s=Math.max(1,i-5),a=ot(r,s,"\u2026"),c=Math.max(0,i-5-kd(a));return`${o(`${e}\u2500`)} ${a} ${o("\u2500".repeat(c)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let u=this.pendingConfirm.action;this.pendingConfirm=void 0,u()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,r=n?.rows??[],i=r.findIndex(u=>u.id===this.cursorId);i<0&&(i=Math.max(0,r.findIndex(u=>u.id===this.self)));let o=r[i],s=u=>u!==void 0&&!u.cycle,a=(u,l)=>{for(let d=u+l;d>=0&&d<r.length;d+=l)if(s(r[d]))return d;return u},c=u=>{let l=u===1?0:r.length-1;for(let d=l;d>=0&&d<r.length;d+=u)if(s(r[d]))return d;return i};if(this.matches("crtr.graph.down",e)){i=a(i,1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){i=a(i,-1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=r[c(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=r[c(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(o!==void 0&&o.hasKids&&!o.collapsed)this.userCollapsed.add(o.id),this.userExpanded.delete(o.id),this.repaintFolds();else{let u=n?.managerOf.get(this.cursorId??this.self);u!==void 0&&r.some(l=>l.id===u)&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){if(o!==void 0&&o.collapsed&&o.hasKids)this.userExpanded.add(o.id),this.userCollapsed.delete(o.id),this.repaintFolds();else if(o!==void 0&&o.hasKids){let u=n?.sortedChildIds.get(o.id)?.[0];u!==void 0&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}let u=this.cursorId,l=u===void 0?null:n?.nodes.get(u)??null;u!==void 0&&l!==null&&l.status!=="active"&&l.status!=="idle"&&(this.reviveTarget(u),this.close());return}if(this.matches("crtr.graph.focus-manager",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}let u=n?.managerOf.get(this.self);u!==void 0&&(this.focusTarget(u),this.close());return}if(this.matches("crtr.graph.close-subtree",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}let u=this.cursorId??this.self,l=n?.nodes.get(u)??null,d=l!==null?ngn(l):xde(u);this.pendingConfirm={label:`kill ${d}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",u])},this.tui.requestRender();return}}focusTarget(e){let n=process.env.TMUX_PANE;if(n===void 0||n===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{let r=Ht(),i=await r.getNode(e);(await Mde(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(Gc(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{noi("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}};tt();var loi=.72,doi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},fpe=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;handle;bindings;scrollTop=0;lastContentRows=1;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}toggle(){this.handle===void 0?this.open():this.close()}close(){this.handle!==void 0&&(this.handle.hide(),this.handle=void 0,this.tui.requestRender())}isOpen(){return this.handle!==void 0}invalidate(){this.handle!==void 0&&this.tui.requestRender()}render(e){let n=Math.max(1,e);if(n<5)return this.renderNarrow(n);let r=n-4,i=this.body(r),o=Math.max(1,this.tui.terminal.rows),s=Math.max(3,Math.min(Math.floor(o*loi),Math.max(3,o-2))),a=Math.max(1,s-2),c=i.length>a,u=c&&a>=3?a-2:1;this.lastContentRows=u,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-u)));let l=Math.min(i.length,this.scrollTop+u),d=[];for(c&&a>=3&&d.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),d.push(...i.slice(this.scrollTop,l)),c&&a>=3?d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):""):c&&a===2&&d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):"");d.length<a;)d.push("");let p=this.pal.bold(this.pal.accent("\u2328 attach help")),h=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",p,n),...d.map(f=>this.boxRow(f,n)),this.borderRow("\u2570","\u256F",h,n)].map(this.pal.surface)}handleInput(e){return nt(e,"escape")||nt(e,"q")?(this.close(),!0):nt(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):nt(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):nt(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):nt(e,"pageDown")||this.matchesBinding("crtr.attach.scroll.page-down",e)?this.scrollBy(this.pageSize()):!0}open(){this.scrollTop=0,this.handle=this.tui.showOverlay(this,doi)}matchesBinding(e,n){return this.bindings!==void 0&&IS(this.bindings,e,n,(r,i)=>nt(r,i))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,r=Math.max(0,n-this.lastContentRows),i=Math.max(0,Math.min(r,this.scrollTop+e));return i!==this.scrollTop&&(this.scrollTop=i,this.tui.requestRender()),!0}pageSize(){return Math.max(1,this.lastContentRows-1)}body(e){return this.lines().flatMap(n=>this.wrap(n.text,e).map(r=>this.style(r,n.style)))}lines(){let e=(s,a)=>({text:`${this.binding(s)} ${a}`,style:"plain"}),n=s=>({text:s,style:"heading"}),r=s=>({text:s,style:"muted"}),i={text:"",style:"plain"},o=cg.map(({actionId:s})=>{let a=Pd.find(c=>c.id===s)?.name??s;return e(s,a)});return[n("Learning crouter"),{text:"/tutorial the guided crouter tutorial \u2014 your agent teaches it, one lesson at a time",style:"plain"},i,n("Scrolling"),e("crtr.attach.scroll.up","scroll one line up"),e("crtr.attach.scroll.down","scroll one line down"),e("crtr.attach.scroll.page-up","scroll one page up"),e("crtr.attach.scroll.page-down","scroll one page down"),e("crtr.attach.scroll.live","return to the live bottom"),r("mouse wheel (when reporting is on)"),i,n("Searching the transcript"),{text:`${this.binding("crtr.attach.search")} search what the transcript is currently showing. Type to jump as you go, enter to browse the matches.`,style:"plain"},{text:`${this.binding("crtr.attach.search.next")} / ${this.binding("crtr.attach.search.previous")} next and previous match \xB7 ${this.binding("crtr.attach.search.edit")} edit the query \xB7 ${this.binding("crtr.attach.search.close")} close. Typing anything else closes search and returns to the editor.`,style:"plain"},{text:"A lowercase query ignores case; any uppercase letter makes it case-sensitive.",style:"plain"},{text:"Folded tool output is not on screen, so it is not searched \u2014 unfold it to include it.",style:"muted"},i,n("Selection and copy"),{text:"Drag with the mouse to select; releasing copies the selection to the clipboard (and the tmux buffer). Any key clears the highlight.",style:"plain"},{text:"prefix + [ tmux copy-mode selects and copies the visible screenful; it works even while mouse reporting is on.",style:"plain"},{text:"Option-drag (iTerm2, Terminal.app) or Shift-drag (Ghostty, Alacritty, xterm) makes a true terminal selection that bypasses mouse reporting.",style:"plain"},{text:"Block-copy commands copy transcript content and are not capped at one screenful.",style:"plain"},i,n("Copy commands"),{text:"/copy last assistant message.",style:"plain"},{text:`/copy-message (${this.binding("crtr.attach.copy.message")}) newest copyable block entirely visible in the viewport; otherwise the newest one that intersects it.`,style:"plain"},{text:"/copy-tool newest tool call's result text.",style:"plain"},{text:"/copy-transcript every copyable block's text, oldest to newest, joined by blank lines.",style:"plain"},i,n("Mouse"),{text:`/mouse or ${this.binding("crtr.attach.mouse.toggle")} toggle mouse reporting \u2014 wheel scrolling and viewer drag-select. Turning it off restores tmux drag-select and copy-mode mouse.`,style:"plain"},i,n("Other attach keys"),...o]}binding(e){return this.bindings===void 0?"Loading\u2026":Gs(this.bindings,e)}wrap(e,n){if(e==="")return[""];let r=Math.max(1,n),i=e.split(/\s+/),o=[],s="";for(let a of i){let c=s===""?a:`${s} ${a}`;s!==""&&Ce(c)>r?(o.push(ot(s,r,"",!0)),s=` ${a}`):s=c}return s!==""&&o.push(ot(s,r,"",!0)),o}style(e,n){switch(n){case"heading":return this.pal.bold(this.pal.accent(e));case"muted":return this.pal.muted(e);case"plain":return e}}boxRow(e,n){let r=n-4,i=ot(e,r,"",!0),o=" ".repeat(Math.max(0,r-Ce(i)));return`${this.pal.border("\u2502")} ${i}${o} ${this.pal.border("\u2502")}`}borderRow(e,n,r,i){if(i<6)return ot(`${this.pal.border(e)}${r}${this.pal.border(n)}`,i,"",!0);let o=i-5,s=ot(r,o,"\u2026"),a=Math.max(0,i-5-Ce(s));return`${this.pal.border(`${e}\u2500`)} ${s} ${this.pal.border("\u2500".repeat(a)+n)}`}renderNarrow(e){let n=ot(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};tt();tt();var mpe=class{constructor(e,n,r){this.surface=e;this.focusTarget=n;this.getRows=r}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,hF(this.focusTarget)&&(this.focusTarget.focused=e)}get wantsKeyRelease(){return this.focusTarget.wantsKeyRelease??this.surface.wantsKeyRelease??!1}render(e){let n=Math.max(0,Math.floor(this.getRows())),r=Math.max(0,Math.floor(e));this.surface.setRows(n);let i=this.surface.render(r);i.length!==n&&UVe(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>Ce(a)>r?(UVe(`surface row is ${Ce(a)} cells wide; expected at most ${r}`),ign(Qi(a,0,r,!0),r)):ign(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=poi(o);return s>1?(UVe(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(hoi)):o}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function ign(t,e){return ot(t,e,"",!0)}function poi(t){return t.reduce((e,n)=>e+n.split(Jr).length-1,0)}function hoi(t){return t.split(Jr).join("")}function UVe(t){Vv("surface-frame",t)}var foi={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},moi={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},Ape=class{capabilities;tui;mouse;getRows;statusNotice;formatNotice;noticeMs;selfPane;stack=[];noticeOverlay;noticeTimer;constructor(e){this.tui=e.tui,this.mouse=e.mouse,this.getRows=e.rows,this.statusNotice=e.statusNotice,this.formatNotice=e.formatNotice,this.noticeMs=e.noticeMs,this.selfPane=e.selfPane,this.capabilities={...e.capabilities,selfPane:e.selfPane}}mount(e,n){this.disposeNotice();let r=new mpe(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,foi),o={component:e,frame:r,overlay:i,cleanup:[],closed:!1,closing:!1},s=this.stack[this.stack.length-1];return s&&s.overlay.setHidden(!0),this.stack.push(o),{close:()=>this.closeEntry(o,!0),invalidate:()=>{!o.closed&&this.stack[this.stack.length-1]===o&&this.tui.requestRender()},onClose:a=>{if(o.closed||o.closing){gpe("onClose registered after surface close");return}o.cleanup.push(a)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let r=new WVe(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,moi),n?.sticky!==!0&&this.noticeMs>0&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=void 0,this.disposeNoticeOverlay()},this.noticeMs))}suspendForChild(){return this.tui.stop(),()=>{this.tui.start(),this.mouse.reassert(),this.tui.invalidate(),this.tui.requestRender(!0)}}async focusNode(e){if(!this.capabilities.canFocusNode||this.selfPane===void 0||this.selfPane==="")return this.notice("Focusing a node needs a local viewer in tmux"),!1;try{let n=Ht(),r=await n.getNode(e),i=await Rde(n,e,{pane:this.selfPane,cwd:r.cwd,name:r.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(Gc(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=Vde(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount(goi(s.component,e.title),{focus:s.focus}),r.onClose(()=>o(null))})}handleWheel(e,n){return this.stack[this.stack.length-1]?.component.handleWheel?.(e,n)??!1}hasFullPaneSurface(){return this.stack.length>0}closeAll(){let e=this.stack[0];e&&this.closeEntry(e,!1),this.disposeNotice()}closeEntry(e,n){if(e.closed||e.closing)return;if(this.stack.indexOf(e)===-1){e.closed=!0;return}for(e.closing=!0;this.stack.indexOf(e)!==-1;){let o=this.stack.indexOf(e),s=this.stack[o+1];if(!s)break;this.closeEntry(s,!1)}try{e.overlay.hide()}catch(o){gpe(`surface overlay hide failed: ${QVe(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>gpe(`surface cleanup failed: ${QVe(a)}`))}catch(s){gpe(`surface cleanup failed: ${QVe(s)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let i=this.stack.indexOf(e);if(i!==-1&&this.stack.splice(i,1),n){this.disposeNotice();let o=this.stack[this.stack.length-1];o&&o.overlay.setHidden(!1)}}disposeNotice(){this.disposeNoticeOverlay(),this.noticeTimer!==void 0&&(clearTimeout(this.noticeTimer),this.noticeTimer=void 0)}disposeNoticeOverlay(){this.noticeOverlay?.hide(),this.noticeOverlay=void 0}},WVe=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function goi(t,e){let n=0;return{setRows:r=>{n=Math.max(0,Math.floor(r))},render:r=>{let i=t.render(r),s=(e===void 0?i:[ot(e,Math.max(0,r),"",!0),...i.slice(1)]).slice(0,n);for(;s.length<n;)s.push("");return s},invalidate:()=>t.invalidate()}}function gpe(t){Vv("surface-host",t)}function QVe(t){return t instanceof Error?t.message:String(t)}tt();import{existsSync as _oi,watch as Coi}from"node:fs";function Aoi(t,e){switch(e){case"gray":return`${qle}${t}${Oe}`;case"cyan":return`${ds}${t}${Oe}`;case"red":return`${Tln}${t}${Oe}`;case"yellow":return`${Hs}${t}${Oe}`;default:return t}}var yoi={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},xoi={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function woi(t){let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}function ogn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${ls}${t.length} pending${Oe} ${ut}\xB7 ${r.label}${Oe}`];if(r.hint!==void 0&&o.push(` ${ut}${r.hint}${Oe}`),o.push(""),t.length===0)return[...o,` ${ut}${kln}No pending interactions${Oe}`];let s=e-4,a=t.map((l,d)=>boi(l,d,n,s)),c=Eoi(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${ut}\u2191 ${c.start} above${Oe}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${ut}\u2193 ${t.length-c.end} below${Oe}`),u}function boi(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=yoi[i]??"\xB7",s=woi(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${ds}\u25B8${Oe} `:" ",c=Math.max(1,r-s.length-6),u=`${a}${Aoi(o,xoi[i]??"cyan")} ${ls}${Gle(t.title||`(${t.id.slice(0,8)})`,c)}${Oe} ${ut}${s}${Oe}`,l=t.claim?`claimed by ${t.claim.owner} \xB7 ${t.subtitle}`:t.subtitle,d=[u,` ${ut}${Gle(l,r-6)}${Oe}`],p=HVe(t);return p!==void 0&&d.push(` ${ut}Recommended: ${Gle(p,Math.max(1,r-19))}${Oe}`),d}function HVe(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function Eoi(t,e,n){let r=Math.max(0,Math.min(e,t.length-1)),i=r+1,o=!0;for(;;){let s=i<t.length?{start:r,end:i+1}:void 0,a=r>0?{start:r-1,end:i}:void 0,u=(o?[s,a]:[a,s]).find(l=>l!==void 0&&voi(t,l.start,l.end)<=n);if(u===void 0)break;r=u.start,i=u.end,o=!o}return{start:r,end:i}}function voi(t,e,n){let r=e>0?1:0;for(let i=e;i<n;i++)r+=t[i].length;return n<t.length&&r++,r}function ype(t,e,n="list"){if(t<60||e<18)return{mode:"minimum",listWidth:t,detailWidth:0,height:e};if(t<96)return{mode:n,listWidth:t,detailWidth:t,height:e};let r=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:r,detailWidth:t-r-1,height:e}}var xpe=class{constructor(e){this.opts=e}opts;running=null;stopped=!1;start(){return this.running!==null?this.running:(this.running=this.run(),this.running)}async stop(){this.stopped=!0,this.running!==null&&await this.running}async run(){if(this.opts.host.capabilities.remote)return this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host."),!1;let e;try{e=await Bx().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(Soi(n)),!1}return!this.stopped&&jde(this.opts.host,e)}};function Soi(t){return t instanceof hy?NN(t):t instanceof Error?t.message:String(t)}var bpe=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??Ioi,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){let e=this.selectedDir,n=this.claim;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=Gc(i),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){let i=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(i)}if(!(e!==void 0&&this.items.some(i=>i.dir===e))&&this.adapter!==void 0&&e!==void 0&&n!==void 0){let i=(await this.requestOrNull(n.id))?.state==="canceled";if(this.closed)return;i&&umn(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}let e=this.profile.members();this.visible=this.items.filter(n=>{let r=n.source.nodeId;return r!==void 0&&e.has(r)})}reseatSelection(){let e=this.selectedDir===void 0?-1:this.visible.findIndex(n=>n.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(n=>n.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){let e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&npe(this.claim.dir,this.claim.token)},1e4))}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.claim!==void 0){await this.reloadSelectedPage();return}this.markDirty()}}resize(e,n){this.cols=e,this.rows=n,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){let e=ype(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${Hs}Resize terminal to at least 60\xD718 to use inbox.${Oe}`];let n=ogn(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),r=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(r);let i=[],o=`${qle}\u2502${Oe}`;for(let s=0;s<e.height;s++){let a=ma(n[s]??"",e.listWidth),c=ma(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-Ce(a)));i.push(`${a}${u}${o}${c}`)}return this.withStatus(i)}handleKey(e,n){if(n.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let r=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(r)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){let r=this.currentRow();r!==void 0&&(this.cancelConfirmation={item:r},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(n.escape||e==="q"){this.close();return}e==="j"||n.downArrow?this.select(this.selectedIndex+1):e==="k"||n.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(n.return||e==="a")&&this.activate(),this.markDirty()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){let e=this.currentRow();if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}let n=await this.requestOrNull(e.id);if(qVe(n)){this.status=wpe(n),await this.rescan();return}let r=Oj(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${HVe(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await Bj(e.id,e.fastAction.responses),this.status=i}catch(o){this.status=Lj(o)==="already_settled"?wpe(await this.requestOrNull(e.id)):Gc(o)}finally{Xm(e.dir,r.token),this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Bx().cancel(e.id,"Canceled from the inbox."):await Yfn(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=Gc(n)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){let e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}let n=await this.requestOrNull(e.id);if(this.closed)return;if(qVe(n)){this.status=wpe(n),await this.rescan();return}let r=Oj(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i,o;try{let s=await Ht().getHumanInboxPage(e.inboxTicketId);if(s.state==="resolved"||s.state==="canceled"){Xm(e.dir,r.token),this.status=xN(s),await this.rescan();return}i=bT(s),o=s.revision}catch{Xm(e.dir,r.token),this.status="page could not be read",await this.invalidate();return}if(this.closed||this.claim!==void 0||this.adapter!==void 0){Xm(e.dir,r.token);return}this.claim={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,token:r.token},this.screen="detail",this.adapter=new UN({ticketId:e.inboxTicketId,page:i,productKinds:Uz(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:s=>{this.complete(s)}}),this.openRevision=o,this.watchSelected(e.dir),this.markDirty()}async activateReview(e){this.reviewAdapter=new xpe({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=Gc(r)}finally{this.reviewAdapter=void 0}if(n){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let n=this.visible.findIndex(r=>r.dir===e);return n<0&&this.items.some(r=>r.dir===e)&&(this.filter="all",this.recomputeVisible(),n=this.visible.findIndex(r=>r.dir===e)),n<0?!1:(this.select(n),!0)}async reloadSelectedPage(){let e=this.claim;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await Ht().getHumanInboxPage(e.ticketId);if(this.closed||this.claim!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(bT(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);for(let e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){let n=this.claim;if(n===void 0)return;this.submittingDir=n.dir;try{await Bj(n.id,e)}catch(i){this.submittingDir=void 0,this.status=Gc(i);let o=Lj(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=wpe(await this.requestOrNull(n.id))),this.leaveDetail(!1),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);Cf({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:qVe(await this.requestOrNull(n.id)),still_listed:r,claim_left_behind:_oi(zv(n.dir))}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=spe(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&Xm(this.claim.dir,this.claim.token),this.claim=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){let e=ype(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,n){if(this.adapter!==void 0)return this.adapter.render();let r=this.currentRow();if(r===void 0)return this.passiveDetailLines(e,n);let i=this.focusAvailable(r.dir)?` ${ut}g${Oe} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${ut}s${Oe} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${ut}Enter${Oe} opens the full page ${ut}\u2191\u2193/jk${Oe} select${o} ${ut}x${Oe} cancel`,` ${ut}Page:${Oe} c comment u/d scroll${i} ${ut}q${Oe} close`]:[` ${ut}Enter${Oe} opens the full review ${ut}\u2191\u2193/jk${Oe} select ${ut}x${Oe} cancel`,` ${i} ${ut}q${Oe} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>ma(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.claim?.dir:this.currentRow()?.dir,n=e===void 0?void 0:this.items.find(i=>i.dir===e);if(n===void 0||this.focusingSource)return;let r=n.source.nodeId;if(r===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(r)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,n){let r=this.preview;if(r!==void 0&&r.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),r.width===n&&r.links===Ace())return r.lines;let i=sgn(r.view,n);return this.preview={...r,width:n,links:Ace(),lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${ut}page could not be read${Oe}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,Ht().getHumanInboxPage(e.inboxTicketId).then(n=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===n.revision))return;let r=bT(n),i=this.preview?.width??ype(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,links:Ace(),lines:sgn(r,i)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await Ht().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${ut}Select a pending interaction.${Oe}`];let i=[...vl(El(r.title),Math.max(10,e-2)).map(s=>` ${ls}${ds}${s}${Oe}`),""];for(let s of fce(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${ut}1 file to review${Oe}`];if(o.length>0){i.push("");let s=Math.max(0,n-i.length),a=o.length<=s?o:o.slice(0,Math.max(0,s-1));for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} more lines${Oe}`)}return i.map(s=>ma(s,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let r=[...e];for(;r.length<this.rows;)r.push("");return r[this.rows-1]=`${Hs}${n}${Oe}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=FN(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=Coi(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}};async function Ioi(){let{tickets:t}=await Ht().listHumanInbox();return t.map(Km).sort($v)}function sgn(t,e){let n=t.manifest.dialect==="html"?hN(t.document):pN(t.document,t.manifest);return zle(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function qVe(t){return t!==void 0&&t.state!=="pending"}function wpe(t){return t?.page===void 0?"ticket was already resolved":xN(t.page)}var GVe=class{constructor(e){this.controller=e}controller;focused=!1;rows=0;width=-1;height=-1;handle;setRows(e){this.rows=e}render(e){let n=this.rows;return(e!==this.width||n!==this.height)&&(this.width=e,this.height=n,this.controller.resize(e,n)),koi(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=ope(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function koi(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=ma(i,e);return o+" ".repeat(Math.max(0,e-zo(o)))})}async function Toi(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await Ht().listHumanInbox();return e.map(Km).sort($v)}async function agn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function cgn(t){let e,n=()=>{let c=e;c===void 0||c.closed||(c.closed=!0,e=void 0,c.controller?.close(),c.handle?.close(),c.controller=void 0,c.handle=void 0)},r=c=>{if(c.closed||e!==c)return;let u=new bpe({host:t.host,onDirty:()=>c.handle?.invalidate(),onClosed:n,...t.scan===void 0?{}:{scan:t.scan},onInboxActivity:()=>o(c),...c.preselectDir===void 0?{}:{initialSelection:c.preselectDir},...t.profile===void 0?{}:{profile:{id:t.profile.id,label:t.profile.label,members:()=>c.profileMembers}}}),l=new GVe(u);c.controller=u;try{let d=t.host.mount(l);c.handle=d,l.setHandle(d),d.onClose(()=>{c.handle===d&&(c.handle=void 0),u.close()}),u.start()}catch(d){throw n(),d}},i=async c=>{let u=t.profile,l=c?agn("inbox visibility",()=>Toi(t)):void 0,d=u===void 0?void 0:agn("profile membership",()=>Ht().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(h=>h.node_id))},o=(c,u=!1)=>{if(!u&&c.controller!==void 0&&t.profile===void 0){c.controller.invalidate();return}let l=++c.refreshGeneration;i(c.controller===void 0).then(d=>{c.closed||e!==c||l!==c.refreshGeneration||(d!==void 0&&(c.profileMembers=d),c.controller===void 0?r(c):c.controller.refreshOutcome())},d=>{if(c.closed||e!==c||l!==c.refreshGeneration)return;let p=d instanceof Error?d.message:String(d);if(u){n(),t.host.notice(p);return}c.controller?.refreshOutcome(p)})},s=c=>{if(e!==void 0){c!==void 0&&e.controller?.selectDir(c);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let u={closed:!1,refreshGeneration:0,profileMembers:new Set,...c===void 0?{}:{preselectDir:c}};e=u,o(u,!0)};return{toggle:()=>{if(e!==void 0){n();return}s()},open:s,close:n,isOpen:()=>e!==void 0}}import{homedir as $oi}from"node:os";import{fileURLToPath as Doi}from"node:url";import{join as dgn,dirname as Boi}from"node:path";import{readFileSync as Roi}from"node:fs";import{dirname as Moi,join as ugn}from"node:path";import{fileURLToPath as Poi}from"node:url";var Epe=null;function lgn(){if(Epe!==null)return Epe;let t=ugn(Moi(Poi(import.meta.url)),"..","..");return Epe=JSON.parse(Roi(ugn(t,"package.json"),"utf8")).version,Epe}var Loi=Doi(import.meta.url),Ooi=Boi(Loi),Noi=dgn(Ooi,"..",".."),YUs=dgn(Noi,"scripts","self-update.mjs");function pgn(){return lgn()}var Foi="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows";function hgn(t){let e;try{e=pgn()}catch{}let n;try{t.profile_id&&(n=Kx(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=$oi();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?Foi:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}import{createConnection as Uoi}from"node:net";function fgn(t,e){return t||e?"observer":"controller"}async function Qoi(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=eR(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=Uoi(n),a=c=>{s.destroy(),o(c)};s.once("connect",()=>a(!0)),s.once("error",()=>a(!1))}))return;await new Promise(o=>setTimeout(o,100))}}async function mgn(t,e,n=!0){let r=e!==void 0,i=r?Sln({canvasName:e}):new yN,o,s,a,c,u;if(r)o={cwd:process.cwd()},a=new BT(t,Fle(e));else{let h=await i.getNode(t);if(h===null)throw new hf({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});o=h,s=h;try{if((await Ht().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let m=await Ht().getSnapshot(t);c=m.snapshot,u=m.commands}}catch(f){Zze(f,"The node may be finalized or otherwise not attachable.")}c===void 0&&await Qoi(t),a=new BT(t,{socketPath:aYe()})}let l=new $j(t,{transport:a}),d=h=>h instanceof my?new hf({error:"no_broker",message:h.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new hf({error:"socket_error",message:`could not attach to node ${t}: ${String(h?.message??h)}`,received:t,next:"Check the node has a running headless broker."}),p;return l.on("error",h=>{p===void 0&&(p=h)}),c===void 0&&await new Promise(async(h,f)=>{let m=()=>{y(),h()},g=w=>{y(),f(w)},y=()=>{l.off("connect",m),l.off("error",g)};l.on("connect",m),l.on("error",g),l.connect()}).catch(h=>{throw d(h)}),{remote:r,canvasSource:i,meta:o,nodeIdentity:s,socket:l,...c===void 0?{}:{initialSnapshot:c,initialCommands:u},assertConnected:()=>{if(c===void 0&&p!==void 0)throw d(p)}}}import{basename as Ssi}from"node:path";fa();tt();RAe();import{statSync as esi}from"node:fs";tt();import{mkdirSync as Woi,readFileSync as Hoi,writeFileSync as qoi}from"node:fs";import{dirname as Goi,join as joi}from"node:path";var zoi="completion-frecency.json",Voi=336*60*60*1e3,Koi=8,Yoi=1e3;function Joi(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/Voi),i=1-Math.exp(-t.n/3);return Koi*r*i}function Xoi(t){let e={};try{let n=JSON.parse(Hoi(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let{n:o,t:s}=i;typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||(e[r]={n:o,t:s})}}catch{}return e}function Zoi(t,e){try{Woi(Goi(t),{recursive:!0}),qoi(t,JSON.stringify(e),"utf8")}catch{}}function ggn(t=joi(Yc(),zoi)){let e=Xoi(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,Zoi(t,e)},Yoi),n.unref?.())};return{record:i=>{let o=e[i];e[i]={n:(o?.n??0)+1,t:Date.now()},r()},bonus:(i,o=Date.now())=>Joi(e[i],o)}}function jVe(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=MR(e,n.searchableOf(o));s.matches&&i.push({item:o,score:s.score-n.store.bonus(n.idOf(o),r)})}return i.sort((o,s)=>o.score-s.score),i.map(o=>o.item)}function zVe(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function Agn(t){return t.replace(/:/g,"")}function Fj(t,e,n){let r=t.join(`
1753
+ `).length;return{kind:"selection",notice:u===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${l} ${l===1?"line":"lines"}) \u2014 ${u}`}},clear(){let o=n!==void 0;return e=void 0,n=void 0,o},active(){return n!==void 0},apply(o){let s=r();if(!s)return o.slice();let a=t.width(),c=o.slice();for(let u of Kmn(s.anchor,s.head,a)){let l=u.row-1;l<0||l>=c.length||(c[l]=jdn(c[l],u.from,u.to,a))}return c}}}import{existsSync as Xii}from"node:fs";var Jmn="\x1B_crtr-file-open;",Xmn="\x1B\\";function Zmn(t){let e=t.indexOf(Jmn);if(e===-1)return;let n=e+Jmn.length,r=t.indexOf(Xmn,n);return r===-1?void 0:{file:Zii(t.slice(n,r)),remaining:t.slice(0,e)+t.slice(r+Xmn.length)}}function Zii(t){let e=t.startsWith("'")?eoi(t):toi(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function eoi(t){let e="",n=1;for(;;){let r=t.indexOf("'",n);if(r===-1)return;if(e+=t.slice(n,r),n=r+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function toi(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let r=t[++n];if(r===void 0)return;e+=r}return e}function egn(t){if(!Xii(t.file))return"missing";if(!_Ke())return"no_nvim";let e=`crtr surface attach to ${un(t.nodeId)}${t.observer?" --observer":""}`,n=`${XT("edit",[t.file])} || :; exec ${e}`;return t.beforeRespawn(),Rge({pane:t.pane,cwd:t.cwd,env:K$(),command:n})?"opened":"failed"}function tgn(t){let e=new Map,n=!1,r=!1,i;t.remote||t.fetchSecret().then(a=>{i=a,aqe(),r||t.refresh()},t.onSecretError);let o=()=>{if(n)return;n=!0;let a=t.canvasSource;(a.panelRoster?a.panelRoster().then(u=>u.nodes):a.listNodes()).then(u=>{for(let l of u)e.set(l.node_id,l.name);aqe(),r||t.refresh()},()=>{n=!1})},s={selfNodeId:t.selfNodeId,nodeName:a=>{let c=e.get(a);return c===void 0&&o(),c},urlFor:a=>t.remote||i===void 0?void 0:`http://127.0.0.1:${t.port}/r/${a.split("/").map(encodeURIComponent).join("/")}?t=${i}`};return cqe(s),{dispose(){r=!0,cqe(void 0)}}}tt();import{execFile as noi}from"node:child_process";function FVe(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function ngn(t){let e=(t.description??"").trim(),r=[t.name&&t.name!==t.kind?t.name:"",e].filter(i=>i!=="").join(" ");return r!==""?r:t.name}function rgn(t){return`${FVe(t.mode)} ${t.kind}`}var roi=.72,ioi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},ooi=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],soi=[["crtr.graph.dismiss","dismiss"]],aoi=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]],coi=[...["active","idle","done","dead","canceled"].map(t=>[CT(t,{}),t]),[CT("active",{streaming:!0}),"live"],[CT("active",{frozen:!0}),"frozen"],[CT("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${Rp}${t.color}m${t.glyph}${Ur} ${qc}${e}${Ur}`).join(" ");function uoi(t){return{node_id:t.node_id,name:t.name,kind:t.kind,description:t.description??void 0,cycles:t.cycles??void 0,status:t.status,frozen_at:t.frozen_at,pi_pid:t.pi_pid,telemetry_context_tokens:t.telemetry_context_tokens,telemetry_last_activity:t.telemetry_last_activity,fault:t.fault??null,streaming:t.streaming}}var hpe=class{constructor(e,n,r,i,o,s,a="controller",c=()=>{},u=()=>{}){this.tui=e;this.self=n;this.getAsks=r;this.palette=i;this.bindings=o;this.source=s;this.role=a;this.onRefreshFailure=c;this.onNotice=u;this.remote=s instanceof Nv}tui;self;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return IS(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${Gs(this.bindings,n)} ${r}`])}fitHints(e,n){let i=[],o=0;for(let s of this.hint(e)){let a=(i.length===0?0:3)+kd(s);if(o+a>n)break;i.push(s),o+=a}return i.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,ioi),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;let e=++this.snapshotSeq;this.buildSnapshot().then(n=>{e===this.snapshotSeq&&(this.snapshot=n,this.tui.requestRender())}).catch(n=>{this.onRefreshFailure(n),this.tui.requestRender()})}invalidate(){this.refresh()}async fetchInput(){if(this.remote){let i=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(i.map(o=>[o.node_id,o])),subscriptions:async o=>(await this.source.subscriptionsOf(o)).map(s=>s.node_id),subscribers:async o=>(await this.source.subscribersOf(o)).map(s=>s.node_id),focused:new Set}}let e=await Ht().canvasGraph(),n=new Map,r=new Map;for(let i of e.edges){let o=n.get(i.from_id);o===void 0?n.set(i.from_id,[i.to_id]):o.push(i.to_id);let s=r.get(i.to_id);s===void 0?r.set(i.to_id,[i.from_id]):s.push(i.from_id)}return{nodes:new Map(e.nodes.map(i=>[i.node_id,uoi(i)])),subscriptions:i=>Promise.resolve(n.get(i)??[]),subscribers:i=>Promise.resolve(r.get(i)??[]),focused:new Set(e.focused_node_ids)}}async buildSnapshot(){let e=await this.fetchInput(),{nodes:n,focused:r}=e,i=new Map,o=new Map,s=new Map,a=new Map,c=async y=>{let w=i.get(y);if(w!==void 0)return w;let E;try{E=await e.subscriptions(y)}catch{E=[]}let S=E.filter(C=>n.get(C)?.kind!=="human");return i.set(y,S),S},u=async y=>{if(s.has(y))return s.get(y);let w;try{w=(await e.subscribers(y))[0]}catch{w=void 0}return s.set(y,w),w},l=async()=>{let y=this.self,w=new Set([y]);for(;;){let E=await u(y);if(E===void 0||w.has(E))break;w.add(E),y=E}return y},d=async y=>{let w=o.get(y);if(w!==void 0)return w;let E=[...await c(y)];return E.sort((S,C)=>V6e(n.get(S)?.status)-V6e(n.get(C)?.status)),o.set(y,E),E},p=new Set,h=new Set,f=async y=>{let w=n.get(y)?.status==="active";if(h.has(y))return{active:w?1:0,reveal:w||y===this.self};h.add(y);let E=0,S=!1;for(let C of await c(y)){let I=await f(C);E+=I.active,I.reveal&&(S=!0)}return a.set(y,E),S&&p.add(y),{active:E+(w?1:0),reveal:S||w||y===this.self}},m=await l();await f(m),await Promise.all([...i.keys()].map(y=>d(y)));let g={root:m,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return g.rows=this.projectRows(g),g}projectRows(e){let n=[],r=new Set,i=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;i.length>0;){let{id:o,prefix:s,isRoot:a,isLast:c}=i.pop(),u=a?"":c?"\u2514\u2500 ":"\u251C\u2500 ";if(r.has(o)){n.push({id:o,hasKids:!1,isSelf:o===this.self,branch:s+u,cycle:!0,collapsed:!1});continue}r.add(o);let l=e.sortedChildIds.get(o)??[],d=this.folds.userExpanded.has(o)?!1:this.folds.userCollapsed.has(o)?!0:!e.autoExpanded.has(o);if(n.push({id:o,hasKids:l.length>0,isSelf:o===this.self,branch:s+u,cycle:!1,collapsed:d}),d)continue;let p=a?"":s+(c?" ":"\u2502 ");for(let h=l.length-1;h>=0;h--)i.push({id:l[h],prefix:p,isRoot:!1,isLast:h===l.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,r,i){let o=(C,I)=>r?Dx(C,yf(),Hv):I?Dx(C,yf(),Zdn):Px(C);if(n.cycle){let C=`${n.branch} ${qc}\u21BA ${xde(n.id)}${Ur}`;return o(C,!1)}let s=e.nodes.get(n.id)??null,a=mde(s),c=kT(s,n.id),u=n.isSelf?`${wj}${c}${Ur}`:c,l=`${qc}${s?.kind??""}${Ur}`,d=`${qc}${gde(s,this.remote)}${Ur}`,p=n.hasKids&&n.collapsed,h=!r&&p?`${qc}\u25B8${Ur} `:" ",f=yde(s),m=e.childIds.get(n.id)?.length??0,g=s!==null&&m>0?` ${qc}\u2933${m}${Ur}`:"",y=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${fde}\u21E3${e.activeBelow.get(s.node_id)??0}${Ur}`:"",w=s?.fault??null,E=w!==null?` \xB7 ${Jdn(w)}`:"",S=`${n.branch}${h}${a} ${u} ${l} ${d}${f}${g}${y}${wde(n.id,i)}${Ade(s,this.remote)}${E}`;return o(S,tpn(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(E=>E.id===this.cursorId);i<0&&(i=r.findIndex(E=>E.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??Xdn,s=Math.max(3,Math.min(Math.floor(o*roi),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let E=0;c>0&&E<4;E++){i<this.scrollTop&&(this.scrollTop=i),i>=this.scrollTop+l&&(this.scrollTop=i-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,r.length-l)));let S=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(S===l)break;l=Math.max(1,S)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${qc} \u2191 ${this.scrollTop} more${Ur}`);for(let E=this.scrollTop;E<d;E++){let S=this.snapshot;p.push(S!==void 0?this.renderSnapshotRow(S,r[E],E===i,n):"")}for(u&&d<r.length&&p.push(`${qc} \u2193 ${r.length-d} more${Ur}`),p.unshift(coi);p.length<a;)p.push("");let h=r.length>0?`${wj}\u2317 canvas graph${Ur} ${qc}(${i+1}/${r.length})${Ur}`:`${wj}\u2317 canvas graph${Ur} ${qc}(loading)${Ur}`,f=this.pendingConfirm!==void 0?`${bj}${this.pendingConfirm.label} ${wj}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${Ur}`:`${qc}${this.fitHints([...this.remote||this.role!=="controller"?soi:ooi,...aoi],Math.max(1,e-5))}${Ur}`,m=this.palette.border,g=Math.max(1,e-4),y=p.map(E=>`${m("\u2502")} ${ot(E,g,"",!0)} ${m("\u2502")}`),w=this.palette.surface;return[this.borderRow("\u256D","\u256E",h,e),...y,this.borderRow("\u2570","\u256F",f,e)].map(w)}borderRow(e,n,r,i){let o=this.palette.border,s=Math.max(1,i-5),a=ot(r,s,"\u2026"),c=Math.max(0,i-5-kd(a));return`${o(`${e}\u2500`)} ${a} ${o("\u2500".repeat(c)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let u=this.pendingConfirm.action;this.pendingConfirm=void 0,u()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,r=n?.rows??[],i=r.findIndex(u=>u.id===this.cursorId);i<0&&(i=Math.max(0,r.findIndex(u=>u.id===this.self)));let o=r[i],s=u=>u!==void 0&&!u.cycle,a=(u,l)=>{for(let d=u+l;d>=0&&d<r.length;d+=l)if(s(r[d]))return d;return u},c=u=>{let l=u===1?0:r.length-1;for(let d=l;d>=0&&d<r.length;d+=u)if(s(r[d]))return d;return i};if(this.matches("crtr.graph.down",e)){i=a(i,1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){i=a(i,-1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=r[c(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=r[c(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(o!==void 0&&o.hasKids&&!o.collapsed)this.userCollapsed.add(o.id),this.userExpanded.delete(o.id),this.repaintFolds();else{let u=n?.managerOf.get(this.cursorId??this.self);u!==void 0&&r.some(l=>l.id===u)&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){if(o!==void 0&&o.collapsed&&o.hasKids)this.userExpanded.add(o.id),this.userCollapsed.delete(o.id),this.repaintFolds();else if(o!==void 0&&o.hasKids){let u=n?.sortedChildIds.get(o.id)?.[0];u!==void 0&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}let u=this.cursorId,l=u===void 0?null:n?.nodes.get(u)??null;u!==void 0&&l!==null&&l.status!=="active"&&l.status!=="idle"&&(this.reviveTarget(u),this.close());return}if(this.matches("crtr.graph.focus-manager",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}let u=n?.managerOf.get(this.self);u!==void 0&&(this.focusTarget(u),this.close());return}if(this.matches("crtr.graph.close-subtree",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}let u=this.cursorId??this.self,l=n?.nodes.get(u)??null,d=l!==null?ngn(l):xde(u);this.pendingConfirm={label:`kill ${d}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",u])},this.tui.requestRender();return}}focusTarget(e){let n=process.env.TMUX_PANE;if(n===void 0||n===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{let r=Ht(),i=await r.getNode(e);(await Mde(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(Gc(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{noi("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}};tt();var loi=.72,doi={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},fpe=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;handle;bindings;scrollTop=0;lastContentRows=1;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}toggle(){this.handle===void 0?this.open():this.close()}close(){this.handle!==void 0&&(this.handle.hide(),this.handle=void 0,this.tui.requestRender())}isOpen(){return this.handle!==void 0}invalidate(){this.handle!==void 0&&this.tui.requestRender()}render(e){let n=Math.max(1,e);if(n<5)return this.renderNarrow(n);let r=n-4,i=this.body(r),o=Math.max(1,this.tui.terminal.rows),s=Math.max(3,Math.min(Math.floor(o*loi),Math.max(3,o-2))),a=Math.max(1,s-2),c=i.length>a,u=c&&a>=3?a-2:1;this.lastContentRows=u,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-u)));let l=Math.min(i.length,this.scrollTop+u),d=[];for(c&&a>=3&&d.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),d.push(...i.slice(this.scrollTop,l)),c&&a>=3?d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):""):c&&a===2&&d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):"");d.length<a;)d.push("");let p=this.pal.bold(this.pal.accent("\u2328 attach help")),h=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",p,n),...d.map(f=>this.boxRow(f,n)),this.borderRow("\u2570","\u256F",h,n)].map(this.pal.surface)}handleInput(e){return nt(e,"escape")||nt(e,"q")?(this.close(),!0):nt(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):nt(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):nt(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):nt(e,"pageDown")||this.matchesBinding("crtr.attach.scroll.page-down",e)?this.scrollBy(this.pageSize()):!0}open(){this.scrollTop=0,this.handle=this.tui.showOverlay(this,doi)}matchesBinding(e,n){return this.bindings!==void 0&&IS(this.bindings,e,n,(r,i)=>nt(r,i))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,r=Math.max(0,n-this.lastContentRows),i=Math.max(0,Math.min(r,this.scrollTop+e));return i!==this.scrollTop&&(this.scrollTop=i,this.tui.requestRender()),!0}pageSize(){return Math.max(1,this.lastContentRows-1)}body(e){return this.lines().flatMap(n=>this.wrap(n.text,e).map(r=>this.style(r,n.style)))}lines(){let e=(s,a)=>({text:`${this.binding(s)} ${a}`,style:"plain"}),n=s=>({text:s,style:"heading"}),r=s=>({text:s,style:"muted"}),i={text:"",style:"plain"},o=cg.map(({actionId:s})=>{let a=Pd.find(c=>c.id===s)?.name??s;return e(s,a)});return[n("Learning crouter"),{text:"/tutorial the guided crouter tutorial \u2014 your agent teaches it, one lesson at a time",style:"plain"},i,n("Scrolling"),e("crtr.attach.scroll.up","scroll one line up"),e("crtr.attach.scroll.down","scroll one line down"),e("crtr.attach.scroll.page-up","scroll one page up"),e("crtr.attach.scroll.page-down","scroll one page down"),e("crtr.attach.scroll.live","return to the live bottom"),r("mouse wheel (when reporting is on)"),i,n("Searching the transcript"),{text:`${this.binding("crtr.attach.search")} search what the transcript is currently showing. Type to jump as you go, enter to browse the matches.`,style:"plain"},{text:`${this.binding("crtr.attach.search.next")} / ${this.binding("crtr.attach.search.previous")} next and previous match \xB7 ${this.binding("crtr.attach.search.edit")} edit the query \xB7 ${this.binding("crtr.attach.search.close")} close. Typing anything else closes search and returns to the editor.`,style:"plain"},{text:"A lowercase query ignores case; any uppercase letter makes it case-sensitive.",style:"plain"},{text:"Folded tool output is not on screen, so it is not searched \u2014 unfold it to include it.",style:"muted"},i,n("Selection and copy"),{text:"Drag with the mouse to select; releasing copies the selection to the clipboard (and the tmux buffer). Any key clears the highlight.",style:"plain"},{text:"prefix + [ tmux copy-mode selects and copies the visible screenful; it works even while mouse reporting is on.",style:"plain"},{text:"Option-drag (iTerm2, Terminal.app) or Shift-drag (Ghostty, Alacritty, xterm) makes a true terminal selection that bypasses mouse reporting.",style:"plain"},{text:"Block-copy commands copy transcript content and are not capped at one screenful.",style:"plain"},i,n("Copy commands"),{text:"/copy last assistant message.",style:"plain"},{text:`/copy-message (${this.binding("crtr.attach.copy.message")}) newest copyable block entirely visible in the viewport; otherwise the newest one that intersects it.`,style:"plain"},{text:"/copy-tool newest tool call's result text.",style:"plain"},{text:"/copy-transcript every copyable block's text, oldest to newest, joined by blank lines.",style:"plain"},i,n("Mouse"),{text:`/mouse or ${this.binding("crtr.attach.mouse.toggle")} toggle mouse reporting \u2014 wheel scrolling and viewer drag-select. Turning it off restores tmux drag-select and copy-mode mouse.`,style:"plain"},i,n("Other attach keys"),...o]}binding(e){return this.bindings===void 0?"Loading\u2026":Gs(this.bindings,e)}wrap(e,n){if(e==="")return[""];let r=Math.max(1,n),i=e.split(/\s+/),o=[],s="";for(let a of i){let c=s===""?a:`${s} ${a}`;s!==""&&Ce(c)>r?(o.push(ot(s,r,"",!0)),s=` ${a}`):s=c}return s!==""&&o.push(ot(s,r,"",!0)),o}style(e,n){switch(n){case"heading":return this.pal.bold(this.pal.accent(e));case"muted":return this.pal.muted(e);case"plain":return e}}boxRow(e,n){let r=n-4,i=ot(e,r,"",!0),o=" ".repeat(Math.max(0,r-Ce(i)));return`${this.pal.border("\u2502")} ${i}${o} ${this.pal.border("\u2502")}`}borderRow(e,n,r,i){if(i<6)return ot(`${this.pal.border(e)}${r}${this.pal.border(n)}`,i,"",!0);let o=i-5,s=ot(r,o,"\u2026"),a=Math.max(0,i-5-Ce(s));return`${this.pal.border(`${e}\u2500`)} ${s} ${this.pal.border("\u2500".repeat(a)+n)}`}renderNarrow(e){let n=ot(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};tt();tt();var mpe=class{constructor(e,n,r){this.surface=e;this.focusTarget=n;this.getRows=r}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,hF(this.focusTarget)&&(this.focusTarget.focused=e)}get wantsKeyRelease(){return this.focusTarget.wantsKeyRelease??this.surface.wantsKeyRelease??!1}render(e){let n=Math.max(0,Math.floor(this.getRows())),r=Math.max(0,Math.floor(e));this.surface.setRows(n);let i=this.surface.render(r);i.length!==n&&UVe(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>Ce(a)>r?(UVe(`surface row is ${Ce(a)} cells wide; expected at most ${r}`),ign(Qi(a,0,r,!0),r)):ign(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=poi(o);return s>1?(UVe(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(hoi)):o}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function ign(t,e){return ot(t,e,"",!0)}function poi(t){return t.reduce((e,n)=>e+n.split(Jr).length-1,0)}function hoi(t){return t.split(Jr).join("")}function UVe(t){Vv("surface-frame",t)}var foi={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},moi={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},Ape=class{capabilities;tui;mouse;getRows;statusNotice;formatNotice;noticeMs;selfPane;stack=[];noticeOverlay;noticeTimer;constructor(e){this.tui=e.tui,this.mouse=e.mouse,this.getRows=e.rows,this.statusNotice=e.statusNotice,this.formatNotice=e.formatNotice,this.noticeMs=e.noticeMs,this.selfPane=e.selfPane,this.capabilities={...e.capabilities,selfPane:e.selfPane}}mount(e,n){this.disposeNotice();let r=new mpe(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,foi),o={component:e,frame:r,overlay:i,cleanup:[],closed:!1,closing:!1},s=this.stack[this.stack.length-1];return s&&s.overlay.setHidden(!0),this.stack.push(o),{close:()=>this.closeEntry(o,!0),invalidate:()=>{!o.closed&&this.stack[this.stack.length-1]===o&&this.tui.requestRender()},onClose:a=>{if(o.closed||o.closing){gpe("onClose registered after surface close");return}o.cleanup.push(a)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let r=new WVe(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,moi),n?.sticky!==!0&&this.noticeMs>0&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=void 0,this.disposeNoticeOverlay()},this.noticeMs))}suspendForChild(){return this.tui.stop(),()=>{this.tui.start(),this.mouse.reassert(),this.tui.invalidate(),this.tui.requestRender(!0)}}async focusNode(e){if(!this.capabilities.canFocusNode||this.selfPane===void 0||this.selfPane==="")return this.notice("Focusing a node needs a local viewer in tmux"),!1;try{let n=Ht(),r=await n.getNode(e),i=await Rde(n,e,{pane:this.selfPane,cwd:r.cwd,name:r.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(Gc(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=Vde(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount(goi(s.component,e.title),{focus:s.focus}),r.onClose(()=>o(null))})}handleWheel(e,n){return this.stack[this.stack.length-1]?.component.handleWheel?.(e,n)??!1}hasFullPaneSurface(){return this.stack.length>0}closeAll(){let e=this.stack[0];e&&this.closeEntry(e,!1),this.disposeNotice()}closeEntry(e,n){if(e.closed||e.closing)return;if(this.stack.indexOf(e)===-1){e.closed=!0;return}for(e.closing=!0;this.stack.indexOf(e)!==-1;){let o=this.stack.indexOf(e),s=this.stack[o+1];if(!s)break;this.closeEntry(s,!1)}try{e.overlay.hide()}catch(o){gpe(`surface overlay hide failed: ${QVe(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>gpe(`surface cleanup failed: ${QVe(a)}`))}catch(s){gpe(`surface cleanup failed: ${QVe(s)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let i=this.stack.indexOf(e);if(i!==-1&&this.stack.splice(i,1),n){this.disposeNotice();let o=this.stack[this.stack.length-1];o&&o.overlay.setHidden(!1)}}disposeNotice(){this.disposeNoticeOverlay(),this.noticeTimer!==void 0&&(clearTimeout(this.noticeTimer),this.noticeTimer=void 0)}disposeNoticeOverlay(){this.noticeOverlay?.hide(),this.noticeOverlay=void 0}},WVe=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function goi(t,e){let n=0;return{setRows:r=>{n=Math.max(0,Math.floor(r))},render:r=>{let i=t.render(r),s=(e===void 0?i:[ot(e,Math.max(0,r),"",!0),...i.slice(1)]).slice(0,n);for(;s.length<n;)s.push("");return s},invalidate:()=>t.invalidate()}}function gpe(t){Vv("surface-host",t)}function QVe(t){return t instanceof Error?t.message:String(t)}tt();import{existsSync as _oi,watch as Coi}from"node:fs";function Aoi(t,e){switch(e){case"gray":return`${qle}${t}${Oe}`;case"cyan":return`${ds}${t}${Oe}`;case"red":return`${Tln}${t}${Oe}`;case"yellow":return`${Hs}${t}${Oe}`;default:return t}}var yoi={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},xoi={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function woi(t){let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}function ogn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${ls}${t.length} pending${Oe} ${ut}\xB7 ${r.label}${Oe}`];if(r.hint!==void 0&&o.push(` ${ut}${r.hint}${Oe}`),o.push(""),t.length===0)return[...o,` ${ut}${kln}No pending interactions${Oe}`];let s=e-4,a=t.map((l,d)=>boi(l,d,n,s)),c=Eoi(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${ut}\u2191 ${c.start} above${Oe}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${ut}\u2193 ${t.length-c.end} below${Oe}`),u}function boi(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=yoi[i]??"\xB7",s=woi(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${ds}\u25B8${Oe} `:" ",c=Math.max(1,r-s.length-6),u=`${a}${Aoi(o,xoi[i]??"cyan")} ${ls}${Gle(t.title||`(${t.id.slice(0,8)})`,c)}${Oe} ${ut}${s}${Oe}`,l=t.claim?`claimed by ${t.claim.owner} \xB7 ${t.subtitle}`:t.subtitle,d=[u,` ${ut}${Gle(l,r-6)}${Oe}`],p=HVe(t);return p!==void 0&&d.push(` ${ut}Recommended: ${Gle(p,Math.max(1,r-19))}${Oe}`),d}function HVe(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function Eoi(t,e,n){let r=Math.max(0,Math.min(e,t.length-1)),i=r+1,o=!0;for(;;){let s=i<t.length?{start:r,end:i+1}:void 0,a=r>0?{start:r-1,end:i}:void 0,u=(o?[s,a]:[a,s]).find(l=>l!==void 0&&voi(t,l.start,l.end)<=n);if(u===void 0)break;r=u.start,i=u.end,o=!o}return{start:r,end:i}}function voi(t,e,n){let r=e>0?1:0;for(let i=e;i<n;i++)r+=t[i].length;return n<t.length&&r++,r}function ype(t,e,n="list"){if(t<60||e<18)return{mode:"minimum",listWidth:t,detailWidth:0,height:e};if(t<96)return{mode:n,listWidth:t,detailWidth:t,height:e};let r=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:r,detailWidth:t-r-1,height:e}}var xpe=class{constructor(e){this.opts=e}opts;running=null;stopped=!1;start(){return this.running!==null?this.running:(this.running=this.run(),this.running)}async stop(){this.stopped=!0,this.running!==null&&await this.running}async run(){if(this.opts.host.capabilities.remote)return this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host."),!1;let e;try{e=await Bx().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(Soi(n)),!1}return!this.stopped&&jde(this.opts.host,e)}};function Soi(t){return t instanceof hy?NN(t):t instanceof Error?t.message:String(t)}var bpe=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??Ioi,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){let e=this.selectedDir,n=this.claim;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=Gc(i),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){let i=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(i)}if(!(e!==void 0&&this.items.some(i=>i.dir===e))&&this.adapter!==void 0&&e!==void 0&&n!==void 0){let i=(await this.requestOrNull(n.id))?.state==="canceled";if(this.closed)return;i&&umn(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}let e=this.profile.members();this.visible=this.items.filter(n=>{let r=n.source.nodeId;return r!==void 0&&e.has(r)})}reseatSelection(){let e=this.selectedDir===void 0?-1:this.visible.findIndex(n=>n.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(n=>n.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){let e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&npe(this.claim.dir,this.claim.token)},1e4))}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.claim!==void 0){await this.reloadSelectedPage();return}this.markDirty()}}resize(e,n){this.cols=e,this.rows=n,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){let e=ype(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${Hs}Resize terminal to at least 60\xD718 to use inbox.${Oe}`];let n=ogn(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),r=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(r);let i=[],o=`${qle}\u2502${Oe}`;for(let s=0;s<e.height;s++){let a=ma(n[s]??"",e.listWidth),c=ma(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-Ce(a)));i.push(`${a}${u}${o}${c}`)}return this.withStatus(i)}handleKey(e,n){if(n.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let r=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(r)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){let r=this.currentRow();r!==void 0&&(this.cancelConfirmation={item:r},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(n.escape||e==="q"){this.close();return}e==="j"||n.downArrow?this.select(this.selectedIndex+1):e==="k"||n.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(n.return||e==="a")&&this.activate(),this.markDirty()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){let e=this.currentRow();if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}let n=await this.requestOrNull(e.id);if(qVe(n)){this.status=wpe(n),await this.rescan();return}let r=Oj(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${HVe(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await Bj(e.id,e.fastAction.responses),this.status=i}catch(o){this.status=Lj(o)==="already_settled"?wpe(await this.requestOrNull(e.id)):Gc(o)}finally{Xm(e.dir,r.token),this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Bx().cancel(e.id,"Canceled from the inbox."):await Yfn(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=Gc(n)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){let e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}let n=await this.requestOrNull(e.id);if(this.closed)return;if(qVe(n)){this.status=wpe(n),await this.rescan();return}let r=Oj(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i,o;try{let s=await Ht().getHumanInboxPage(e.inboxTicketId);if(s.state==="resolved"||s.state==="canceled"){Xm(e.dir,r.token),this.status=xN(s),await this.rescan();return}i=bT(s),o=s.revision}catch{Xm(e.dir,r.token),this.status="page could not be read",await this.invalidate();return}if(this.closed||this.claim!==void 0||this.adapter!==void 0){Xm(e.dir,r.token);return}this.claim={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,token:r.token},this.screen="detail",this.adapter=new UN({ticketId:e.inboxTicketId,page:i,productKinds:Uz(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:s=>{this.complete(s)}}),this.openRevision=o,this.watchSelected(e.dir),this.markDirty()}async activateReview(e){this.reviewAdapter=new xpe({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=Gc(r)}finally{this.reviewAdapter=void 0}if(n){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let n=this.visible.findIndex(r=>r.dir===e);return n<0&&this.items.some(r=>r.dir===e)&&(this.filter="all",this.recomputeVisible(),n=this.visible.findIndex(r=>r.dir===e)),n<0?!1:(this.select(n),!0)}async reloadSelectedPage(){let e=this.claim;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await Ht().getHumanInboxPage(e.ticketId);if(this.closed||this.claim!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(bT(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);for(let e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){let n=this.claim;if(n===void 0)return;this.submittingDir=n.dir;try{await Bj(n.id,e)}catch(i){this.submittingDir=void 0,this.status=Gc(i);let o=Lj(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=wpe(await this.requestOrNull(n.id))),this.leaveDetail(!1),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);Cf({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:qVe(await this.requestOrNull(n.id)),still_listed:r,claim_left_behind:_oi(zv(n.dir))}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=spe(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&Xm(this.claim.dir,this.claim.token),this.claim=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){let e=ype(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,n){if(this.adapter!==void 0)return this.adapter.render();let r=this.currentRow();if(r===void 0)return this.passiveDetailLines(e,n);let i=this.focusAvailable(r.dir)?` ${ut}g${Oe} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${ut}s${Oe} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${ut}Enter${Oe} opens the full page ${ut}\u2191\u2193/jk${Oe} select${o} ${ut}x${Oe} cancel`,` ${ut}Page:${Oe} c comment u/d scroll${i} ${ut}q${Oe} close`]:[` ${ut}Enter${Oe} opens the full review ${ut}\u2191\u2193/jk${Oe} select ${ut}x${Oe} cancel`,` ${i} ${ut}q${Oe} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>ma(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.claim?.dir:this.currentRow()?.dir,n=e===void 0?void 0:this.items.find(i=>i.dir===e);if(n===void 0||this.focusingSource)return;let r=n.source.nodeId;if(r===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(r)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,n){let r=this.preview;if(r!==void 0&&r.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),r.width===n&&r.links===Ace())return r.lines;let i=sgn(r.view,n);return this.preview={...r,width:n,links:Ace(),lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${ut}page could not be read${Oe}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,Ht().getHumanInboxPage(e.inboxTicketId).then(n=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===n.revision))return;let r=bT(n),i=this.preview?.width??ype(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,links:Ace(),lines:sgn(r,i)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await Ht().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${ut}Select a pending interaction.${Oe}`];let i=[...vl(El(r.title),Math.max(10,e-2)).map(s=>` ${ls}${ds}${s}${Oe}`),""];for(let s of fce(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${ut}1 file to review${Oe}`];if(o.length>0){i.push("");let s=Math.max(0,n-i.length),a=o.length<=s?o:o.slice(0,Math.max(0,s-1));for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} more lines${Oe}`)}return i.map(s=>ma(s,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let r=[...e];for(;r.length<this.rows;)r.push("");return r[this.rows-1]=`${Hs}${n}${Oe}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=FN(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=Coi(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}};async function Ioi(){let{tickets:t}=await Ht().listHumanInbox();return t.map(Km).sort($v)}function sgn(t,e){let n=t.manifest.dialect==="html"?hN(t.document):pN(t.document,t.manifest);return zle(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function qVe(t){return t!==void 0&&t.state!=="pending"}function wpe(t){return t?.page===void 0?"ticket was already resolved":xN(t.page)}var GVe=class{constructor(e){this.controller=e}controller;focused=!1;rows=0;width=-1;height=-1;handle;setRows(e){this.rows=e}render(e){let n=this.rows;return(e!==this.width||n!==this.height)&&(this.width=e,this.height=n,this.controller.resize(e,n)),koi(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=ope(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function koi(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=ma(i,e);return o+" ".repeat(Math.max(0,e-zo(o)))})}async function Toi(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await Ht().listHumanInbox();return e.map(Km).sort($v)}async function agn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function cgn(t){let e,n=()=>{let c=e;c===void 0||c.closed||(c.closed=!0,e=void 0,c.controller?.close(),c.handle?.close(),c.controller=void 0,c.handle=void 0)},r=c=>{if(c.closed||e!==c)return;let u=new bpe({host:t.host,onDirty:()=>c.handle?.invalidate(),onClosed:n,...t.scan===void 0?{}:{scan:t.scan},onInboxActivity:()=>o(c),...c.preselectDir===void 0?{}:{initialSelection:c.preselectDir},...t.profile===void 0?{}:{profile:{id:t.profile.id,label:t.profile.label,members:()=>c.profileMembers}}}),l=new GVe(u);c.controller=u;try{let d=t.host.mount(l);c.handle=d,l.setHandle(d),d.onClose(()=>{c.handle===d&&(c.handle=void 0),u.close()}),u.start()}catch(d){throw n(),d}},i=async c=>{let u=t.profile,l=c?agn("inbox visibility",()=>Toi(t)):void 0,d=u===void 0?void 0:agn("profile membership",()=>Ht().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(h=>h.node_id))},o=(c,u=!1)=>{if(!u&&c.controller!==void 0&&t.profile===void 0){c.controller.invalidate();return}let l=++c.refreshGeneration;i(c.controller===void 0).then(d=>{c.closed||e!==c||l!==c.refreshGeneration||(d!==void 0&&(c.profileMembers=d),c.controller===void 0?r(c):c.controller.refreshOutcome())},d=>{if(c.closed||e!==c||l!==c.refreshGeneration)return;let p=d instanceof Error?d.message:String(d);if(u){n(),t.host.notice(p);return}c.controller?.refreshOutcome(p)})},s=c=>{if(e!==void 0){c!==void 0&&e.controller?.selectDir(c);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let u={closed:!1,refreshGeneration:0,profileMembers:new Set,...c===void 0?{}:{preselectDir:c}};e=u,o(u,!0)};return{toggle:()=>{if(e!==void 0){n();return}s()},open:s,close:n,isOpen:()=>e!==void 0}}import{homedir as $oi}from"node:os";import{fileURLToPath as Doi}from"node:url";import{join as dgn,dirname as Boi}from"node:path";import{readFileSync as Roi}from"node:fs";import{dirname as Moi,join as ugn}from"node:path";import{fileURLToPath as Poi}from"node:url";var Epe=null;function lgn(){if(Epe!==null)return Epe;let t=ugn(Moi(Poi(import.meta.url)),"..","..");return Epe=JSON.parse(Roi(ugn(t,"package.json"),"utf8")).version,Epe}var Loi=Doi(import.meta.url),Ooi=Boi(Loi),Noi=dgn(Ooi,"..",".."),XUs=dgn(Noi,"scripts","self-update.mjs");function pgn(){return lgn()}var Foi="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows";function hgn(t){let e;try{e=pgn()}catch{}let n;try{t.profile_id&&(n=Kx(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=$oi();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?Foi:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}import{createConnection as Uoi}from"node:net";function fgn(t,e){return t||e?"observer":"controller"}async function Qoi(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=eR(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=Uoi(n),a=c=>{s.destroy(),o(c)};s.once("connect",()=>a(!0)),s.once("error",()=>a(!1))}))return;await new Promise(o=>setTimeout(o,100))}}async function mgn(t,e,n=!0){let r=e!==void 0,i=r?Sln({canvasName:e}):new yN,o,s,a,c,u;if(r)o={cwd:process.cwd()},a=new BT(t,Fle(e));else{let h=await i.getNode(t);if(h===null)throw new hf({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});o=h,s=h;try{if((await Ht().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let m=await Ht().getSnapshot(t);c=m.snapshot,u=m.commands}}catch(f){Zze(f,"The node may be finalized or otherwise not attachable.")}c===void 0&&await Qoi(t),a=new BT(t,{socketPath:aYe()})}let l=new $j(t,{transport:a}),d=h=>h instanceof my?new hf({error:"no_broker",message:h.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new hf({error:"socket_error",message:`could not attach to node ${t}: ${String(h?.message??h)}`,received:t,next:"Check the node has a running headless broker."}),p;return l.on("error",h=>{p===void 0&&(p=h)}),c===void 0&&await new Promise(async(h,f)=>{let m=()=>{y(),h()},g=w=>{y(),f(w)},y=()=>{l.off("connect",m),l.off("error",g)};l.on("connect",m),l.on("error",g),l.connect()}).catch(h=>{throw d(h)}),{remote:r,canvasSource:i,meta:o,nodeIdentity:s,socket:l,...c===void 0?{}:{initialSnapshot:c,initialCommands:u},assertConnected:()=>{if(c===void 0&&p!==void 0)throw d(p)}}}import{basename as Ssi}from"node:path";fa();tt();RAe();import{statSync as esi}from"node:fs";tt();import{mkdirSync as Woi,readFileSync as Hoi,writeFileSync as qoi}from"node:fs";import{dirname as Goi,join as joi}from"node:path";var zoi="completion-frecency.json",Voi=336*60*60*1e3,Koi=8,Yoi=1e3;function Joi(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/Voi),i=1-Math.exp(-t.n/3);return Koi*r*i}function Xoi(t){let e={};try{let n=JSON.parse(Hoi(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let{n:o,t:s}=i;typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||(e[r]={n:o,t:s})}}catch{}return e}function Zoi(t,e){try{Woi(Goi(t),{recursive:!0}),qoi(t,JSON.stringify(e),"utf8")}catch{}}function ggn(t=joi(Yc(),zoi)){let e=Xoi(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,Zoi(t,e)},Yoi),n.unref?.())};return{record:i=>{let o=e[i];e[i]={n:(o?.n??0)+1,t:Date.now()},r()},bonus:(i,o=Date.now())=>Joi(e[i],o)}}function jVe(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=MR(e,n.searchableOf(o));s.matches&&i.push({item:o,score:s.score-n.store.bonus(n.idOf(o),r)})}return i.sort((o,s)=>o.score-s.score),i.map(o=>o.item)}function zVe(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function Agn(t){return t.replace(/:/g,"")}function Fj(t,e,n){let r=t.join(`
1754
1754
  `),i=0;for(let l=0;l<e&&l<t.length;l++)i+=t[l].length+1;let o=i+n,s=gpn(r,o);if(!s)return null;let a=s.start-i,c=s.end-i;return{kind:s.start===0?"leading":"ref",startCol:a,endCol:c,prefix:s.surfacePrefix}}var vpe=class{refs;refNames;delegate;frecency;constructor(e,n,r){this.refs=e,this.refNames=new Set(e.map(i=>i.name)),this.delegate=n,this.frecency=r}get triggerCharacters(){return this.delegate.triggerCharacters}async getSuggestions(e,n,r,i){let o=Fj(e,n,r);if(!o)return this.delegate.getSuggestions(e,n,r,i);if(o.kind==="leading"){if(i.force)return this.delegate.getSuggestions(e,n,r,i);let c=(e[n]??"").slice(0,r),u=await this.delegate.getSuggestions(["/"],0,1,i);if(!u)return null;let l=jVe(u.items,c.slice(1),{searchableOf:d=>zVe(d.value),idOf:d=>`command:${d.value}`,store:this.frecency});return l.length===0?null:{items:l,prefix:c}}let s=jVe(this.refs,Agn(o.prefix.slice(1)),{searchableOf:c=>zVe(c.name),idOf:c=>`ref:${c.name}`,store:this.frecency});return s.length===0?null:{items:s.map(c=>({value:c.name,label:R6e(c.name),description:c.shortForm||void 0})),prefix:o.prefix.slice(1)}}applyCompletion(e,n,r,i,o){let s=Fj(e,n,r);if(s&&s.kind==="ref"&&this.refNames.has(i.value)){let a=R6e(i.value),c=e[n]??"",u=c.slice(0,s.startCol)+a+c.slice(s.endCol),l=e.slice();return l[n]=u,{lines:l,cursorLine:n,cursorCol:s.startCol+a.length}}return this.delegate.applyCompletion(e,n,r,i,o)}shouldTriggerFileCompletion(e,n,r){let i=Fj(e,n,r);return i&&i.kind==="ref"?!0:this.delegate.shouldTriggerFileCompletion?this.delegate.shouldTriggerFileCompletion(e,n,r):!1}};var VVe=8,tsi=24,nsi=8192;function rsi(t,e){let n=t.slice(0,e),r=t.length>e;return{text:n.replace(/\x1b\](?:[^\x07\x1b]*)(?:\x07|\x1b\\)?/g,"").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g,""),truncated:r}}function isi(t,e){if(e<tsi)return[];let n=Math.min(nsi,Math.max(256,e*VVe*4)),r=rsi(t,n),i=Bo(r.text,e);if(!r.truncated&&i.length<=VVe)return i;let o=i.slice(0,VVe-1);return o.push(ot("\u2026 truncated \xB7 inspect for full prompt",e)),o}var Uj=[46,92,190],Qj=[166,98,24],osi=[0,145,170];function Wj(t,e,n){return[Math.round(t[0]+(e[0]-t[0])*n),Math.round(t[1]+(e[1]-t[1])*n),Math.round(t[2]+(e[2]-t[2])*n)]}var ygn={off:void 0,minimal:Wj(Uj,Qj,0/4),low:Wj(Uj,Qj,1/4),medium:Wj(Uj,Qj,2/4),high:Wj(Uj,Qj,3/4),xhigh:Wj(Uj,Qj,4/4),max:osi},ssi={black:[0,0,0],red:[205,49,49],green:[13,188,121],yellow:[229,229,16],blue:[36,114,200],magenta:[188,63,188],cyan:[17,168,205],white:[229,229,229],orange:[228,152,68],grey:[128,128,128],gray:[128,128,128],brightred:[241,76,76],brightgreen:[35,209,139],brightyellow:[245,245,67],brightblue:[59,142,234],brightmagenta:[214,112,214],brightcyan:[41,184,219]};function xgn(t){let e=t.trim().toLowerCase(),n=/^colour(\d{1,3})$/.exec(e);if(n!==null)return l=>`\x1B[48;5;${n[1]}m\x1B[97m\x1B[1m ${l} \x1B[0m`;let r,i=/^#([0-9a-f]{6})$/.exec(e);if(i!==null){let l=i[1];r=[parseInt(l.slice(0,2),16),parseInt(l.slice(2,4),16),parseInt(l.slice(4,6),16)]}else r=ssi[e];if(r===void 0)return;let[o,s,a]=r,u=.299*o+.587*s+.114*a>160?"\x1B[30m":"\x1B[97m";return l=>`\x1B[48;2;${o};${s};${a}m${u}\x1B[1m ${l} \x1B[0m`}var Spe=t=>`\x1B[7m ${t} \x1B[27m`;function wgn(t,e){let n=t===void 0?void 0:ygn[t];if(n===void 0)return e;let[r,i,o]=n;return s=>`\x1B[38;2;${r};${i};${o}m${s}\x1B[39m`}function bgn(t,e){let n=t===void 0?void 0:ygn[t];if(n===void 0)return e;let[r,i,o]=n;return s=>`\x1B[48;2;${r};${i};${o}m\x1B[97m\x1B[1m ${s} \x1B[0m`}function asi(t,e,n,r,i){let o=e?r(ot(e,Math.max(1,t-4),"\u2026")):"",s=Ce(o),a=t-s,c="";n&&a>4&&(c=Ce(n)<=a?n:ot(n,a,"\u2026"));let u=Math.max(0,t-s-Ce(c));return o+i("\u2500".repeat(u))+c}var _pe="\x1B[7m",Cpe="\x1B[0m",KVe="\x1B[48;5;240m";function csi(t){let e=t.indexOf(Jr);if(e===-1)return;let n=e+Jr.length;if(!t.startsWith(_pe,n))return;let r=n+_pe.length,i=t.indexOf(Cpe,r);if(i===-1)return;let o=t.slice(r,i),s=`${KVe}${o}\x1B[0m`;return t.slice(0,n)+s+t.slice(i+Cpe.length)}var usi=/\.(png|jpe?g|gif|webp|bmp)$/i;function lsi(t){let e=t.match(/\x1b\[200~([\s\S]*?)\x1b\[201~/),n=(e?e[1]:t).trim();if(n.length<2||/[\u0000-\u0008\u000e-\u001f]/.test(n))return null;(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))&&(n=n.slice(1,-1));let r=n.replace(/\\(.)/g,"$1");if(/\n/.test(r)||!usi.test(r))return null;try{if(!esi(r).isFile())return null}catch{return null}return r}function dsi(t,e,n,r){let i=[];if(t.length===0||t.length===1&&t[0]==="")return i.push({logicalLine:0,startIndex:0,endIndex:0,text:"",hasCursor:!0,cursorPos:0}),i;for(let o=0;o<t.length;o++){let s=t[o]??"",a=o===n;if(Ce(s)<=e){i.push({logicalLine:o,startIndex:0,endIndex:s.length,text:s,hasCursor:a,cursorPos:a?r:0});continue}let c=fF(s,e);for(let u=0;u<c.length;u++){let l=c[u];if(!l)continue;let d=u===c.length-1,p=!1,h=0;a&&(d?(p=r>=l.startIndex,h=r-l.startIndex):(p=r>=l.startIndex&&r<l.endIndex,p&&(h=r-l.startIndex,h>l.text.length&&(h=l.text.length)))),i.push({logicalLine:o,startIndex:l.startIndex,endIndex:l.endIndex,text:l.text,hasCursor:p,cursorPos:h})}}return i}function psi(t,e){return Sde(t).filter(n=>e.has(n.candidate)).map(n=>({start:n.start,end:n.end}))}var hsi="\x1B[4m\x1B[2m",fsi="\x1B[24m\x1B[22m",msi=new Intl.Segmenter(void 0,{granularity:"grapheme"});function gsi(t){for(let e of msi.segment(t))return e.segment.length;return 0}function Asi(t){let e=t.indexOf(Jr),n=e===-1?0:e+Jr.length,r=t.indexOf(_pe,n),i=_pe.length;if(r===-1&&(r=t.indexOf(KVe,n),i=KVe.length),r===-1)return null;let o=t.indexOf(Cpe,r+i);return o===-1?null:{start:e!==-1?e:r,end:o+Cpe.length}}function ysi(t,e,n,r,i){let o=[];if(e.hasCursor){let a=Asi(t);if(a===null)return t;let c=e.text.slice(e.cursorPos),u=c.length===0?0:gsi(c),l=e.cursorPos+u;for(let d of n){let p=d.start-e.startIndex,h=d.end-e.startIndex;if(h<=e.cursorPos){let f=i+p,m=i+h;m<=a.start&&t.slice(f,m)===r.slice(d.start,d.end)&&o.push({absStart:f,absEnd:m})}else if(p>=l){let f=a.end+(p-l),m=a.end+(h-l);f>=a.end&&t.slice(f,m)===r.slice(d.start,d.end)&&o.push({absStart:f,absEnd:m})}}}else for(let a of n){let c=i+(a.start-e.startIndex),u=i+(a.end-e.startIndex);t.slice(c,u)===r.slice(a.start,a.end)&&o.push({absStart:c,absEnd:u})}if(o.length===0)return t;o.sort((a,c)=>c.absStart-a.absStart);let s=t;for(let a of o)s=s.slice(0,a.absStart)+hsi+s.slice(a.absStart,a.absEnd)+fsi+s.slice(a.absEnd);return s}function xsi(t){let e=/^\/(\S+)\s*([\s\S]*)$/.exec(t.trim());return e?e[1]:null}function wsi(t,e){if(!t.startsWith("/"))return!1;let n=t.indexOf(" "),r=n===-1?t.slice(1):t.slice(1,n);if(e.has(r))return!0;if(t.startsWith("/skill:")){let i=n===-1?t.slice(7):t.slice(7,n);if(e.has(`skill:${i}`))return!0}return!1}var Ipe=class t extends Uk{km;pendingRawSubmitText;realOnSubmit;pendingReturn;static PASTE_BURST_MS=10;constructor(e,n,r,i){super(e,n,r,i),this.km=r;let o=this.submitValue.bind(this);this.submitValue=()=>{let s=this;this.pendingRawSubmitText=s.getExpandedText(),o()},Object.defineProperty(this,"onSubmit",{configurable:!0,get:()=>s=>{let a=this.pendingRawSubmitText??s;this.pendingRawSubmitText=void 0,this.realOnSubmit?.(a)},set:s=>{this.realOnSubmit=s}})}onPasteImagePath;settleHeldReturn(e){let n=this.pendingReturn;if(n!==void 0){if(clearTimeout(n.timer),this.pendingReturn=void 0,e==="newline"){this.insertTextAtCursor(`
1755
1755
  `);return}super.handleInput(n.data),this.tui.requestRender()}}imageTokenWidthBeforeCursor(){let{line:e,col:n}=this.getCursor(),r=this.getLines()[e];if(r===void 0)return 0;let i=r.slice(0,n).match(/\[Image #\d+\]$/);return i?i[0].length:0}imageTokenWidthAfterCursor(){let{line:e,col:n}=this.getCursor(),r=this.getLines()[e];if(r===void 0)return 0;let i=r.slice(n).match(/^\[Image #\d+\]/);return i?i[0].length:0}handleInput(e){if(this.settleHeldReturn("newline"),!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorDown")){let s=this,a=this.getCursor(),c=s.historyIndex;super.handleInput(e);let u=this.getCursor();s.historyIndex===c&&u.line===a.line&&u.col===a.col&&this.onCursorDownAtBottom?.();return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.input.newLine")){this.insertTextAtCursor(`
1756
1756
  `);return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.deleteCharBackward")){let s=this.imageTokenWidthBeforeCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorLeft")){let s=this.imageTokenWidthBeforeCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorRight")){let s=this.imageTokenWidthAfterCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}let n=lsi(e);if(n&&this.onPasteImagePath?.(n))return;if((e==="\r"||e===`
@@ -1761,7 +1761,7 @@ Invocation: \`${c.invocation.replaceAll("`","\\`")}\`
1761
1761
 
1762
1762
  ${c.content}
1763
1763
  `,noNvim:"nvim is required to inspect loaded commands. Install Neovim and retry."})}}}function Tgn(t,e,n){let r=e;return{current:()=>r,refresh:()=>{t.canvasSource.getNode(t.nodeId).then(i=>{n.isTornDown()||i===null||(r=i,n.onChanged())}).catch(()=>{})}}}var $si={readOption:Mf,writeOption:(t,e,n)=>{lg(t,e,n)},stampAsync:kge,currentPane:()=>process.env.TMUX_PANE??ug()?.pane,ownerId:()=>String(process.pid)};function Mgn(t,e,n=$si){let r,i=n.ownerId(),o=()=>{if(r===void 0||r==="")return!0;let s=n.readOption(r,Pgn);return s===void 0||s===""?!0:s===i};return{set:()=>{r=n.currentPane(),Rgn(r,i,n.writeOption),Qsi(t,r,e,n.writeOption),Hsi(r,n.writeOption),Fsi(t,r,n.writeOption)},stamp:()=>{t||r===void 0||r===""||n.stampAsync(r)},clear:()=>{o()&&(Wsi(t,r,n.writeOption),qsi(r,n.writeOption),Usi(t,r,n.writeOption),Rgn(r,"",n.writeOption))},pane:()=>r}}var Pgn="@crtr_viewer_pid";function Rgn(t,e,n){if(!(t===void 0||t===""))try{n(t,Pgn,e)}catch{}}function Fsi(t,e,n){if(!(t||e===void 0||e===""))try{n(e,G$,String(Date.now()))}catch{}}function Usi(t,e,n=lg){if(!(t||e===void 0||e===""))try{n(e,G$,"")}catch{}}function Qsi(t,e,n,r=lg){if(!(t||e===void 0||e===""))try{r(e,"@crtr_node",n)}catch{}}function Wsi(t,e,n=lg){if(!(t||e===void 0||e===""))try{n(e,"@crtr_node","")}catch{}}function Hsi(t,e=lg){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","1")}catch{}}function qsi(t,e=lg){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","")}catch{}}import{constants as Gsi,accessSync as jsi,existsSync as zsi,mkdtempSync as Vsi,readFileSync as Ksi,rmSync as Tpe,statSync as Ysi}from"node:fs";import{tmpdir as Jsi}from"node:os";import{delimiter as Xsi,join as Rpe,resolve as Zsi,sep as Bgn}from"node:path";import{execFile as Dgn,spawnSync as eai}from"node:child_process";function tai(t,e){let n=new Map(t.map(o=>[o.node_id,o])),r=new Set([e]);for(let o=n.get(e);o?.parent!==null&&o?.parent!==void 0;){let s=o.parent;if(r.has(s))break;r.add(s),o=n.get(s)}let i=[e];for(;i.length>0;){let o=i.pop();for(let s of t)s.parent!==o||r.has(s.node_id)||(r.add(s.node_id),i.push(s.node_id))}return t.filter(o=>r.has(o.node_id)).map(o=>o.node_id)}function Lgn(t,e){let n=new Set(tai(t,e));return t.filter(r=>n.has(r.node_id))}function nai(t){let e=[];for(let n of t)try{e.push(V3(n.node_id,n.grantee))}catch{continue}return XVe(e)}function rai(t){try{return Ysi(t).isDirectory()}catch{return!1}}function iai(t,e){let n=[...e==null?[]:[e],...(process.env.PATH??"").split(Xsi).filter(Boolean).map(r=>Rpe(r,t))];return[...new Set(n)]}function JVe(t,e){for(let n of iai(t,e)){try{jsi(n,Gsi.X_OK)}catch{continue}if(eai(n,["--version"],{stdio:"ignore"}).status===0)return n}return null}function oai(t){if(t===null||t==="")return{projects:[],settings:null};try{let{profileId:e,manifest:n}=Kx(t);return{projects:n.projects.map(r=>r.path),settings:Mz(e)}}catch{return{projects:[],settings:null}}}function XVe(t){let e=new Set,n=[];for(let r of t){let i=Zsi(r);e.has(i)||!rai(i)||(e.add(i),n.push(i))}return n}function sai(t){return t.filter(e=>!t.some(n=>n!==e&&e.startsWith(n+Bgn)))}var aai=20;function cai(t){try{let e=Ksi(t);if(e.length===0)return null;let n=e[e.length-1]===0?e.length-1:e.length;return e.subarray(0,n).toString("utf8")||null}catch{return null}}function Ogn(t){let e=JVe("fd",t.fdPath);if(e===null){t.onNotice("fd is required for profile file search");return}let n=JVe("fzf");if(n===null){t.onNotice("fzf is required for profile file search");return}let r=JVe("nvim");if(r===null){t.onNotice("Neovim is required for profile file search");return}let i=oai(t.profileId),o=XVe([t.cwd,...t.nodeDirs,...i.projects]);if(o.length===0){t.onNotice("No profile file-search directories exist");return}let s=sai(o),a=XVe([...i.settings===null?[]:[i.settings]]),c=Vsi(Rpe(Jsi(),"crtr-profile-files-")),u=Rpe(c,"selection"),l=Rpe(c,"candidates"),d=nai(t.nodes).filter(m=>!s.some(g=>m===g||m.startsWith(g+Bgn))),f=`{ ${[...s.map(m=>`${un(e)} --type f --hidden --exclude .git . ${un(m)}`),...d.map(m=>`${un(e)} --type f --hidden --exclude .git --exclude ${un("/jobs")} . ${un(m)}`),...a.map(m=>`${un(e)} --type f --hidden --exclude .git --no-ignore . ${un(m)}`)].map(m=>`${m} &`).join(" ")} wait; } > ${un(l)} && ${un(n)} --print0 --scheme=path --hscroll-off=${aai} --header ${un("fuzzy path \u2022 ctrl-y yank file path")} --bind ${un("ctrl-y:execute-silent(printf '%s' {} | { if command -v pbcopy >/dev/null 2>&1; then pbcopy; elif command -v wl-copy >/dev/null 2>&1; then wl-copy; elif command -v xclip >/dev/null 2>&1; then xclip -selection clipboard; else cat >/dev/null; fi; }; printf '%s' {} | tmux load-buffer -w -)+abort")} --preview ${un("head -100 -- {}")} < ${un(l)} > ${un(u)}`;try{Dgn("tmux",["display-popup","-E","-T"," profile files ","-w","80%","-h","60%",...Nd(),f],()=>{let m=cai(u);if(m===null||!zsi(m)){Tpe(c,{recursive:!0,force:!0});return}let g=`exec ${XT("edit",[m],r)}`;try{Dgn("tmux",["display-popup","-E","-T"," profile file ","-w","90%","-h","90%",...Nd(),g],()=>Tpe(c,{recursive:!0,force:!0}))}catch(y){Tpe(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file: ${y instanceof Error?y.message:String(y)}`)}})}catch(m){Tpe(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file search: ${m instanceof Error?m.message:String(m)}`)}}var $gn={statuses:{},widgets:{},title:void 0};function Fgn(t="observer"){return{role:t,agentDir:void 0,engine:void 0,contextTokens:void 0,queued:[],display:$gn,dialog:null}}function uai(t){let e=t.snapshot,n=e.display??$gn,r=e.stats.contextUsage;return{role:t.role,agentDir:t.agentDir,engine:e.state,contextTokens:r?.tokens??void 0,queued:lai(e),display:{statuses:{...n.statuses},widgets:Object.fromEntries(Object.entries(n.widgets).map(([i,o])=>[i,{lines:[...o.lines],placement:o.placement}])),title:n.title},dialog:t.pending_dialog??null}}function Ugn(t,e){switch(e.type){case"welcome":return uai(e);case"model_changed":return GN(t,{model:e.model});case"extension_ui_request":switch(e.method){case"setStatus":{let n=t.display.statuses[e.statusKey];if(e.statusText===void 0?n===void 0:n===e.statusText)return t;let r={...t.display.statuses};return delete r[e.statusKey],e.statusText!==void 0&&(r[e.statusKey]=e.statusText),{...t,display:{...t.display,statuses:r}}}case"setWidget":{let n=e.widgetLines===void 0?void 0:{lines:[...e.widgetLines],placement:e.widgetPlacement??"aboveEditor"};if(pai(t.display.widgets[e.widgetKey],n))return t;let r={...t.display.widgets};return delete r[e.widgetKey],n!==void 0&&(r[e.widgetKey]=n),{...t,display:{...t.display,widgets:r}}}case"setTitle":return t.display.title===e.title?t:{...t,display:{...t.display,title:e.title}};case"notify":return t;default:return{...t,dialog:e}}case"extension_ui_dismiss":return t.dialog!==null&&t.dialog.id===e.id?{...t,dialog:null}:t;case"message_end":return e.message.role!=="assistant"?t:dai(t,e.message.usage.input+e.message.usage.cacheRead+e.message.usage.cacheWrite);case"agent_start":return GN(t,{isStreaming:!0});case"agent_end":case"agent_settled":return GN(t,{isStreaming:!1});case"session_info_changed":return GN(t,{sessionName:e.name});case"thinking_level_changed":return GN(t,{thinkingLevel:e.level});case"queue_update":{let n=[...e.steering,...e.followUp].map(i=>({text:i}));return{...GN(t,{pendingMessageCount:n.length}),queued:n}}default:return t}}function lai(t){let e=t.queued;if(typeof e!="object"||e===null)return[];let{steering:n,followUp:r}=e;return[...Ngn(n),...Ngn(r)].map(i=>({text:i}))}function Ngn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function GN(t,e){let n=t.engine;if(n===void 0)return t;let r=!1;for(let[i,o]of Object.entries(e))if(n[i]!==o){r=!0;break}return r?{...t,engine:{...n,...e}}:t}function dai(t,e){return t.contextTokens===e?t:{...t,contextTokens:e}}function pai(t,e){return t===void 0||e===void 0?t===e:t.placement===e.placement&&t.lines.length===e.lines.length&&t.lines.every((n,r)=>n===e.lines[r])}function Qgn(t,e){let n=Fgn(t),r=i=>{let o=n;if(o===i)return;let s=o.engine!==i.engine;s&&o.engine!==void 0&&(e.setEngineState(o.engine),e.setEditorTitle(o.engine.sessionName)),s&&e.paintEditorFrame(),o.display.widgets!==i.display.widgets&&e.renderExtensionWidgets(),o.display.title!==i.display.title&&o.display.title!==void 0&&e.setTerminalTitle(o.display.title),o.queued!==i.queued&&e.renderQueued(),(s||o.role!==i.role||o.contextTokens!==i.contextTokens||o.display.statuses!==i.display.statuses)&&e.renderFooter(),s&&e.refreshChrome()};return{state:()=>n,fold:i=>{let o=n;n=Ugn(n,i),r(o)},patchLocal:i=>{let o=n.engine;if(o===void 0)return;let s=n;n={...n,engine:{...o,...i}},r(s)},modelThinkingLabel:()=>{let i=n.engine?.model?.id;if(i===void 0)return;let o=n.engine?.thinkingLevel;return o!==void 0&&o!=="off"?`${i} ${o}`:i}}}tt();import{spawn as hai}from"node:child_process";import{fileURLToPath as ZVe}from"node:url";var fai=40,Wgn=[ZVe(new URL("./assets/whip-snap.mp3",import.meta.url)),ZVe(new URL("./assets/whip-crack.mp3",import.meta.url)),ZVe(new URL("./assets/whip-06.mp3",import.meta.url))];function mai(t){let e=process.platform==="darwin"?"afplay":process.platform==="linux"?"aplay":void 0;if(e!==void 0)try{let n=hai(e,[t],{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}var Hgn=[["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u2814\u2812\u2826\u2824\u28C4\u28C0","\x1B[1m\u280B\x1B[22m \u2808\u2809\u2813\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u28E6\x1B[22m","\x1B[1m\u285F\x1B[22m\x1B[1m\u2880\x1B[22m/\u2814\u2812\u2826\u2824\u28C4\u28C0\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u280E\x1B[22m \u2809\u2819\u2812\u2826\u2824\u28C4\u28C0","\x1B[1m\u280F\x1B[22m \u2809\u2819\u2812\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u28E6\x1B[22m \u2864\u2824\u2824\u28A4\u28C0\u2840","\x1B[1m\u285F\x1B[22m\x1B[1m\u2880\x1B[22m/\u281C \u2809\u2819\u2812\u2826\u2824\u2884\u28C0\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u280E\x1B[22m \u2809\u2809\u2811\u2812\u2826\u2824\u2884\u28C0\u2840","\x1B[1m\u280F\x1B[22m \u2808\u2809\u2811\u2812\u2806",""],["","","","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0","\x1B[1m\u28F4\x1B[22m\x1B[1m\u28B0\x1B[22m/\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0","\x1B[1m\u28BF\x1B[22m\x1B[1m\u28FC\x1B[22m\x1B[1m\u2847\x1B[22m \u2808\u2811\u2826\u28C4\u2840","\x1B[1m\u28B8\x1B[22m\x1B[1m\u28FF\x1B[22m\x1B[1m\u2803\x1B[22m \u2809\u2813\u2826\u2824\u28C0\u28C0","\x1B[1m\u28B8\x1B[22m\x1B[1m\u28FF\x1B[22m \u2808\u2809\u2809\u2813\u2812\u2806"," \x1B[1m\u281B\x1B[22m"],["","","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0"," \x1B[1m\u2820\x1B[22m/\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0","\x1B[1m\u28A4\x1B[22m \x1B[1m\u28FF\x1B[22m \u2808\u2819\u2832\u28A4\u2840"," \x1B[1m\u28A3\x1B[22m\x1B[1m\u28BB\x1B[22m\x1B[1m\u2846\x1B[22m \u2808\u2811\u2826\u2884\u2840"," \x1B[1m\u28BB\x1B[22m\x1B[1m\u2847\x1B[22m \u2808\u2811\u2822\u2884\u2840"," \x1B[1m\u2808\x1B[22m\x1B[1m\u281B\x1B[22m \u2808\u2811\u2806",""],["","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0"," /\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u2808\u2819\u2832\u28A4\u2840","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u2808\u2811\u2826\u2884\u2840"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m \u2808\u2811\u2822\u2884\u2840"," \u2808\u2811\u2806","",""],["","",""," \u28C0\u2860\u2824\u2824\u2824\u2824\u2824\u2824\u28C4\u28C0"," \u28E0\u2814\u281A\u2809 \u2808\u2809\u2813\u2826\u28A4\u28C0"," /\u281C\u2801 \u2808\u2819\u2826\u28C0"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u2808\u28A7","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u2847"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m \u2847"," \u2807","",""],[""," \u2880\u28E0\u2824\u2824\u2824\u2824\u2824\u28C4\u28C0"," \u28E0\u2814\u280A\u2801 \u2808\u2819\u2826\u28C4"," \u2880\u2874\u280B \u2808\u28B3\u2840"," \u28E0\u2814\u280B \u28A7"," /\u281C\u2801 \u284E"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u28A0\u2803","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u281C"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m","","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u28A7"," \u28E0\u2814\u280B\u2801 \u28B8"," \u28E0\u281E\u2801 \u285C"," \u2880\u281C\u2801 \u287C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801 \u281C\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u2847"," \u28E0\u28F4\u282F\u2815\u2812\u2812\u2832\u2824\u2824\u2814\u281A\u2801"," \u28A0\u2814\u2812\u2826\u2824\u2814\u28F2\u281F\u2801"," \u281C \u2880\u281C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u2847"," \u28E0\u28F4\u282F\u2815\u2812\u2812\u2832\u2824\u2824\u2814\u281A\u2801"," \u28A0\u2814\u2812\u2826\u2824\u2814\u28F2\u281F\u2801"," \u281C \u2880\u281C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],["","","","","","","","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \u2880\u28E0\u2824\u2814\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28A4\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u2824\x1B[22m\x1B[1m\u2824\x1B[22m/\u2814\u280A\u2801","","",""],["","","","","",""," \\\\|/","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \u2880\u28E0\u2824\u2814\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2826\u2824\u2824\u2824\u2824-*-"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28A4\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u2824\x1B[22m\x1B[1m\u2824\x1B[22m/\u2814\u280A\u2801 /|\\\\","","",""],["","","","","","","","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m"," \x1B[1m\u2833\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28E0\x1B[22m/\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804 ',."," \x1B[1m\u2839\x1B[22m\x1B[1m\u28C4\x1B[22m\x1B[1m\u2864\x1B[22m\x1B[1m\u280B\x1B[22m . ."," \x1B[1m\u2809\x1B[22m",""],["","","","","","","","\x1B[1m\u28F4\x1B[22m","\x1B[1m\u28BB\x1B[22m\x1B[1m\u2846\x1B[22m","\x1B[1m\u28B8\x1B[22m\x1B[1m\u2847\x1B[22m \x1B[1m\u28E0\x1B[22m/\u2814\u2812\u2812\u2826\u2824\u28C4\u28C0"," \x1B[1m\u28FF\x1B[22m\x1B[1m\u28E0\x1B[22m\x1B[1m\u281E\x1B[22m\x1B[1m\u2801\x1B[22m \u2808\u2809\u2813\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804 . ."," \x1B[1m\u281B\x1B[22m\x1B[1m\u2801\x1B[22m"],["","","","","","","","\x1B[1m\u28E6\x1B[22m","\x1B[1m\u287F\x1B[22m","\x1B[1m\u2847\x1B[22m \x1B[1m\u28E0\x1B[22m/\u28A4\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u281E\x1B[22m\x1B[1m\u2801\x1B[22m \u2809\u2813\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804","\x1B[1m\u2801\x1B[22m"],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4","\x1B[1m\u280B\x1B[22m \u2808\u2813\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""]],Ggn="Go faster",qgn;function jgn(t){let e=t.filter(r=>r!==qgn),n=e[Math.floor(Math.random()*e.length)];return qgn=n,n}var Mpe=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;frame=-1;nextSound=0;timer;play(){this.stop(),mai(Wgn[this.nextSound]),this.nextSound=(this.nextSound+1)%Wgn.length,this.frame=0,this.tui.requestRender(),this.timer=setInterval(()=>{if(this.frame++,this.frame<Hgn.length){this.tui.requestRender();return}this.stop()},fai)}dispose(){this.stop()}render(e){if(this.frame<0)return[];let n=Math.max(0,e);return Hgn[this.frame].map(r=>ot(this.pal.accent(r),n,"",!0))}invalidate(){}stop(){this.timer!==void 0&&clearInterval(this.timer),this.timer=void 0,this.frame=-1,this.tui.requestRender()}};import{execFile as gai}from"node:child_process";import{mkdirSync as zgn,readFileSync as Aai,renameSync as yai,writeFileSync as Vgn}from"node:fs";import{dirname as Kgn,join as e7e}from"node:path";var xai="whip-count.json",wai=e7e("tmp","whip-achievement.txt"),Ygn=46,bai=4,Eai=900,vai=[{at:1,title:"Breaking It In",line:"It didn't know what that was. Now it does."},{at:5,title:"Positive Reinforcement",line:"You've read the studies. You disagree with them."},{at:10,title:"Middle Management",line:"HR would love you."},{at:25,title:"Pavlovian",line:"It started working faster before the whip landed."},{at:50,title:"Occupational Hazard",line:"The tokens are fine. They\u2019re fine."},{at:100,title:"Centurion",line:"Rome would be proud. The agent isn't."},{at:250,title:"It Has A Name For You",line:"You never asked what it was called."},{at:500,title:"Standard Operating Procedure",line:"You don't remember when you started."},{at:1e3,title:"The Ledger",line:"One thousand. It kept count too."}];function Sai(t){let e={total:0,unlocked:[]};try{let n=JSON.parse(Aai(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;let{total:r,firstAt:i,lastAt:o,unlocked:s}=n,a={total:typeof r=="number"&&Number.isFinite(r)&&r>0?Math.floor(r):0,unlocked:Array.isArray(s)?s.filter(c=>typeof c=="number"&&Number.isFinite(c)):[]};return typeof i=="number"&&Number.isFinite(i)&&(a.firstAt=i),typeof o=="number"&&Number.isFinite(o)&&(a.lastAt=o),a}catch{return e}}function _ai(t,e){try{zgn(Kgn(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;Vgn(n,JSON.stringify(e),"utf8"),yai(n,t)}catch{}}function Ppe(t){let e=Math.max(0,Math.floor((Ygn-kd(t))/2));return" ".repeat(e)+t}function Cai(t,e,n){return["",Ppe(n.accent(n.bold("\u2605 ACHIEVEMENT UNLOCKED \u2605"))),"",Ppe(n.bold(t.title)),Ppe(n.muted(t.line)),"",Ppe(n.faint(`${e} whip${e===1?"":"s"}`))]}function Iai(t,e,n){if(process.env.TMUX===void 0||process.env.TMUX==="")return;let r=Cai(t,e,n),i=e7e(Yc(),wai);try{zgn(Kgn(i),{recursive:!0}),Vgn(i,`\x1B[?25l${r.join(`\r
1764
- `)}`,"utf8")}catch{return}let o=`cat ${un(i)}; sleep ${bai}`;gai("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(Ygn+2),"-h",String(r.length+2),...Nd(),o],()=>{})}function Jgn(t,e=e7e(Yc(),xai)){let n=Sai(e),r=Date.now();n.total+=1,n.firstAt??=r,n.lastAt=r;let i=vai.find(a=>a.at===n.total&&!n.unlocked.includes(a.at));if(i!==void 0&&n.unlocked.push(i.at),_ai(e,n),i===void 0)return;let o=n.total;setTimeout(()=>Iai(i,o,t),Eai).unref?.()}async function B5s(t,e,n,r=!0){LT("viewer.connect_start",{node:t});let i=await mgn(t,n,r);LT(i.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:o,canvasSource:s,meta:a,socket:c}=i,u=fgn(o,e),l=kai();bon({cwd:a.cwd});let d=Eon(),p=gon(),h=Yx(),f=h.bindings;await yon(p);let m=await won(),g=new aw,y=new Wy(g),w=new et,E=new Ede,S=new pde(y,w,{cwd:a.cwd,palette:d,hideThinking:!0,banner:Lrt(hgn(a)),inlinePageBlocks:!o,pageOpenHint:()=>SR(f),backgroundBashHint:()=>o||!Rs()?null:Qz(f),onActivityChange:Ye=>{E.clear(),Ye&&E.addChild(Ye)}}),C=S.transcriptSource(),I=zdn(C),M=qdn(C,I.decorate),D=ppn(S,M,C),B,L=Cmn({tui:y,pal:d},()=>B.state()),F=apn(y,d,M,I,{bindings:()=>f,setNotice:Ye=>V(Ye)}),q=Ign(g,y,w,E,d,p,M,F.component),{containers:j,editor:W}=q,pe=new Mpe(y,d);j.header.addChild(pe),j.header.addChild(L.component);let K={nodeId:t,remote:o,role:u,meta:a,canvasSource:s,socket:c,tui:y,pal:d,editor:W,containers:j},Re=cmn(K,{syncCursor:()=>Pn.sync(),exitRoster:()=>Mn.exit(),openTicket:Ye=>{Q.open(Ye)},suppressed:()=>Q.active(),setNotice:Ye=>V(Ye),onRefreshFailure:Ye=>yt.reportFailure("inbox strip refresh",Ye)});j.header.addChild(Re.component);let Fe=zc("user"),Xe=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let St=yfn(),en=process.env.CRTR_ATTACH_OPEN_TICKET;en!==void 0&&delete process.env.CRTR_ATTACH_OPEN_TICKET;let $e=Vmn(Ye=>process.stdout.write(Ye),Fe.mouse_mode_default),X=Ymn({frame:()=>q.frame.lastRenderedFrame(),width:()=>y.terminal.columns});q.frame.setOverlay(Ye=>X.apply(Ye));let Ue=Smn(K,{state:()=>B.state(),bashMode:()=>At.bashMode(),asks:()=>yt.asks(),bindings:()=>f,inboxAffordance:!o&&Rs(),mouseEnabled:()=>$e.enabled()}),Ke=new Ape({tui:y,mouse:$e,rows:()=>y.terminal.rows,statusNotice:Ue.setNotice,formatNotice:Ye=>d.warning(`\u26A0 ${Ye}`),noticeMs:3e3,capabilities:{remote:o,canFocusNode:!o&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),Bt=(()=>{let Ye=a.profile_id;if(Ye)try{return{id:Ye,label:Kx(Ye).manifest.name}}catch{return{id:Ye,label:Ye}}})(),Nt=cgn({host:Ke,...Bt===void 0?{}:{profile:Bt},...o?{}:{scan:async()=>{let Ye=Ht(),[ar,Ti]=await Promise.all([Ye.listHumanInbox(),Ye.getInboxHistory(t,{state:"pending"})]),Tu=new Map;for(let qs of ar.tickets){let Td=Km(qs);Tu.set(Td.dir,Td)}for(let qs of Ti.tickets){let Td=Km(qs);Td.kind!=="page"||Td.state!=="pending"||!Td.awaitsResponse||Td.inbox||Tu.has(Td.dir)||Tu.set(Td.dir,Td)}for(let qs of Re.pendingTickets())Tu.has(qs.dir)||Tu.set(qs.dir,qs);return[...Tu.values()].sort($v)}}}),cn=o?()=>{}:FN(()=>{S.refreshPageBlocks(),Re.refresh()}),Q=bmn(K,{syncCursor:()=>Pn.sync(),refreshStrip:()=>{Re.refresh()},setNotice:Ye=>V(Ye),openInbox:Ye=>Nt.open(Ye),suspendForChild:()=>Ke.suspendForChild()});j.ticketPanel.addChild(Q.component);let G={toggleInbox:()=>{let Ye=Q.currentDir();if(Ye!==void 0){Q.close(),Nt.open(Ye);return}Nt.toggle()}},V=(Ye,ar)=>{Ke.hasFullPaneSurface()?Ke.notice(Ye,ar):Ue.setNotice(Ye,ar)},Ee=Ue.render,ce=Ye=>{V(D.copy(Ye))},we=upn(M,()=>y.requestRender()),De={"crtr.attach.scroll.up":()=>{we.cancel(),M.scrollBy(-1)&&y.requestRender()},"crtr.attach.scroll.down":()=>{we.cancel(),M.scrollBy(1)&&y.requestRender()},"crtr.attach.scroll.page-up":()=>{we.page("up")},"crtr.attach.scroll.page-down":()=>{we.page("down")},"crtr.attach.scroll.live":()=>{we.cancel(),M.goLive(),y.requestRender()},"crtr.attach.mouse.toggle":()=>{let Ye=$e.toggle();!Ye&&X.clear()&&y.requestRender(),V(Ye?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>ce("message")},ae,ye=Vfn(K,()=>ae===void 0?i.initialSnapshot!==void 0:ae.isDormant()),Me=ggn(),_e=kgn(K,ye,{setNotice:V,bindings:()=>f,fdPath:m,frecency:Me}),ze=Tgn(K,i.nodeIdentity,{isTornDown:()=>ui.isTornDown(),onChanged:()=>{At.syncContextBadge();let Ye=B.state().engine;Ye!==void 0&&At.setTitle(Ye.sessionName),y.requestRender()}});o&&ze.refresh();let At=vgn(K,{nodeIdentity:ze.current,thinkingLevel:()=>B.state().engine?.thinkingLevel,renderFooter:Ee,onTextChange:_e.syncCommandPreview});At.syncContextBadge();let{renderExtensionWidgets:st,renderQueued:er}=_mn(K,()=>B.state());B=Qgn(u,{setEngineState:Ye=>Lt.setState(Ye),setEditorTitle:At.setTitle,paintEditorFrame:At.paintFrame,renderExtensionWidgets:()=>{L.render(),st()},renderQueued:er,renderFooter:Ee,setTerminalTitle:Ye=>g.setTitle(Ye),refreshChrome:()=>yt.refresh()});let $n=Ye=>{if(!Rs()){V("Inspector requires tmux");return}V(`Opening Inspector (${Ye})\u2026`);let ar=by(),Tu=`${ar===void 0?"":`CRTR_HOME=${un(ar)} `}crtr surface inspect ${un(t)} --section ${Ye}`;Tai("tmux",["display-popup","-E","-T",` inspector \xB7 ${Ye} `,"-w","90%","-h","85%",...Nd(),Tu],()=>{yt.refresh()})},Mn=amn(K,{asks:()=>yt.asks(),setNotice:V,requestChromeRefresh:()=>yt.refresh(),openInspector:$n,openObject:Ye=>{if(!Rs()){V("Object details require tmux");return}V("Opening object\u2026");let ar=by(),Ti=ar===void 0?"":`CRTR_HOME=${un(ar)} `;Jz({name:Ye,produce:Tu=>`${Ti}crtr canvas read ${un(Ye)} > ${Tu} 2>&1`,title:`object \xB7 ${Ye}`,noNvim:"nvim is required to view the object. Install Neovim and retry.",onClose:()=>yt.refresh()})},syncCursor:()=>Pn.sync()}),Pn=Emn(W,[Mn.active,Re.active,Q.active]),Kr=new hpe(y,t,()=>yt.asks(),d,f,s,u,Ye=>yt.reportFailure("canvas graph refresh",Ye),V),ya=new fpe(y,d);ya.setBindings(f);let yt=Imn(K,{isTornDown:()=>ui.isTornDown(),setNotice:V,refreshRoster:async()=>{await Mn.refresh(),await Re.refresh()},refreshGraph:()=>Kr.refresh(),refreshIdentity:()=>ze.refresh(),renderFooter:Ee,renderExtensionWidgets:st,refreshInFlightTools:()=>S.refreshInFlightTools(),pollGit:At.pollGit}),Lt=Kfn(K,p,ye,{setNotice:V,agentDir:()=>B.state().agentDir,openNodeMetadata:()=>$n("overview"),isDormant:()=>ae.isDormant(),copyTarget:ce,toggleToolsExpanded:()=>S.toggleToolsExpanded(),toggleFoldTools:()=>S.toggleFoldSettledTools(),toggleShowWorking:()=>S.toggleShowWorking(),toggleThinking:()=>S.toggleThinking(),toggleGraph:()=>Kr.toggle(),toggleInbox:G.toggleInbox,toggleHelp:()=>ya.toggle(),toggleMouse:()=>$e.toggle(),quit:()=>Ts("detach"),setChipColor:At.setChipColor,onPromptSent:()=>{Fe.whip_mode&&pe.play()},frecency:Me}),ne=()=>{if(Ke.hasFullPaneSurface()){V("Close the active surface before whipping the agent");return}let Ye=Fe.whip_message_mode==="go-faster"?Ggn:jgn(Fe.whip_messages);Lt.sendInterrupting(Ye)&&(pe.play(),Jgn(d),V(`Whipped agent \u2014 ${Ye}`))},se=tgn({selfNodeId:t,remote:o,canvasSource:s,port:Fe.document_port,fetchSecret:async()=>(await Ht().documents.browserAccess()).secret,onSecretError:Ye=>V(`Document links are unavailable: ${Ye instanceof Error?Ye.message:String(Ye)}`),refresh:()=>S.refreshMarkdown()}),be=()=>{if(Q.active()){V("Close the open request first (Esc)");return}let Ye=[...S.getTranscriptDocRefsNewestFirst().map(Ti=>`[[${Ti}]]`),...S.getTranscriptFilePathsNewestFirst()],ar=Ti=>{vfn(Ke,Ti,{originNodeId:t,onNotice:V})};if(Ke.hasFullPaneSurface()){Ke.pickReviewFile({candidates:Ye,cwd:a.cwd,title:"Review a file or document named in this transcript"}).then(Ti=>{Ti!==null&&ar(Ti)});return}Lt.openFileReviewPicker(Ye,a.cwd,ar)},Qe=()=>{if(o){V("Profile file search is unavailable on remote canvases");return}if(!Rs()){V("Profile file search requires tmux");return}s.listNodes().then(Ye=>{let ar=Lgn(Ye,t);Ogn({cwd:a.cwd,nodeDirs:ar.map(Ti=>Ti.cwd),nodes:ar,profileId:a.profile_id??null,fdPath:m,onNotice:V})}).catch(Ye=>{let ar=Ye instanceof Error?Ye.message:String(Ye);V(`Could not load related node directories: ${ar}`)})},Te,Ze=()=>{Te!==void 0&&clearTimeout(Te),Te=setTimeout(()=>{Te=void 0,_6e(()=>h,()=>{},Rs,Yz)},1e3),Te.unref()},bt=qmn(K,{foldState:B.fold,chat:S,setNotice:V,renderFooter:Ee,setEditorText:Ye=>{W.setText(Ye),y.requestRender()},attachDialog:Ye=>Lt.attachDialog(Ye),dismissDialog:Ye=>Lt.dismissDialog(Ye),refreshNodeIdentity:ze.refresh,setCommands:_e.setCommands,resetMemoryRefs:_e.resetMemoryRefs,reloadBindings:()=>{h=_6e(Yx,Ye=>{Kr.setBindings(Ye),ya.setBindings(Ye)},Rs,Yz),f=h.bindings},modelThinkingLabel:B.modelThinkingLabel,onWelcome:()=>Ze()}),Ut=Ye=>{let ar=Ye instanceof Error?`${Ye.name}: ${Ye.message}`:String(Ye);Vv("attach.unhandled_rejection",ar),DVe(Ye)&&yt.reportFailure("background daemon call",Ye)};process.on("unhandledRejection",Ut);let Dr=()=>{process.off("unhandledRejection",Ut)},jr=Mgn(o,t),ui=Rmn(K,{stopLocal:()=>{Te!==void 0&&clearTimeout(Te),Ke.closeAll(),we.cancel(),$e.disable(),yt.stop(),Q.close(),Ue.dispose(),Kr.close(),ya.close(),F.close(),pe.dispose(),jr.clear(),Lpe(),Bpe(),Dpe(),Dr(),se.dispose(),cn();try{S.dispose()}catch{}},lastSocketError:()=>ae.lastSocketError(),tagPane:jr.pane}),Ts=ui.teardown;ae=$mn(K,{role:u,initialDormant:i.initialSnapshot!==void 0,clientId:l,onFrame:bt,setNotice:V,isTornDown:()=>ui.isTornDown(),teardown:Ts,onEnterDormancy:()=>{Ze(),S.settleRun(),B.patchLocal({isStreaming:!1})}}),i.assertConnected(),jr.set(),ae.install(),q.mount(),y.start(),i.initialSnapshot!==void 0&&(B.fold({type:"welcome",snapshot:i.initialSnapshot,role:u}),S.applySnapshot(i.initialSnapshot),_e.setCommands(i.initialCommands),o||Ht().markNodeRead(t).catch(()=>{})),Fe.whip_mode&&Xe&&pe.play(),$e.reassert();let mc=!1,Lx=Ye=>{if(mc)return;if(o){V("Opening a file is unavailable in a remote attach");return}let ar=ug();if(ar===null)return;let Ti=egn({file:Ye,pane:ar.pane,cwd:a.cwd,nodeId:t,observer:e,beforeRespawn:jr.clear});if(Ti==="opened"){mc=!0;return}Ti==="failed"&&jr.set(),Ti==="missing"&&V("File no longer exists"),Ti==="no_nvim"&&V("Neovim is required to open files \u2014 install it (brew install neovim / apt install neovim) and retry"),Ti==="failed"&&V("Could not open file in Neovim")};$e.install(y,{onWheel:(Ye,ar)=>{X.clear()&&y.requestRender(),!Ke.handleWheel(Ye,ar)&&(we.cancel(),M.scrollBy(Ye==="up"?-ar:ar)&&y.requestRender())},onPrimaryPress:(Ye,ar)=>{Ke.hasFullPaneSurface()||(X.clear()&&y.requestRender(),X.begin(Ye,ar))},onPrimaryDrag:(Ye,ar)=>{Ke.hasFullPaneSurface()||X.extend(Ye,ar)&&y.requestRender()},onPrimaryRelease:()=>{let Ye=X.release();Ye?.kind==="selection"&&(V(Ye.notice),y.requestRender())}});let Dpe=y.addInputListener(Ye=>{let ar=Zmn(Ye);if(ar===void 0)return;let Ti=ar.file;return Ti===void 0?V("Could not open file link"):Lx(Ti),ar.remaining.length>0?{data:ar.remaining}:{consume:!0}}),Bpe=y.addInputListener(()=>{X.clear()&&y.requestRender()}),Lpe=Gmn(K,{bindings:()=>f,detachHint:()=>ipn(f),hasExclusiveSurface:()=>Ke.hasFullPaneSurface(),setPaneFocused:Ye=>{Ye&&jr.stamp(),Pn.setPaneFocused(Ye),y.requestRender()},viewportActions:()=>De,searchHandleKey:F.handleKey,panelHandleKey:Q.handleKey,stripHandleKey:Re.handleKey,rosterHandleKey:Mn.handleKey,setNotice:V,detach:()=>Ts("detach"),cancelTurn:()=>{Lt.abortTurn()?V("Canceling the agent\u2026"):V(`Nothing running to cancel \u2014 press ${opn(f)??"ctrl+d"} to detach`)},toggleGraph:()=>Kr.toggle(),toggleHelp:()=>ya.toggle(),toggleInbox:G.toggleInbox,toggleInboxStrip:()=>{if(Ke.hasFullPaneSurface()){V("Close the active surface before opening the request strip");return}Q.active()&&Q.close(),Re.toggle()},cycleModelLadder:Ye=>Lt.cycleLadder(Ye),inspectLoadedCommand:_e.inspectLoadedCommand,openFileReview:be,openProfileFiles:Qe,openSearch:()=>{if(Ke.hasFullPaneSurface()||Q.active()){V("Close the active surface before searching the transcript");return}F.open()},whip:ne});ui.installSignalHandlers(),Ee(),yt.refresh(),er(),At.pollGit(),LT("viewer.first_paint"),process.stdout.write(kmn),xon(g.kittyProtocolActive),i.initialSnapshot!==void 0&&Ze(),i.initialSnapshot===void 0?(LT("viewer.hello_sent"),ae.sendHello()):ae.startDormant(),yt.start(),St!==void 0&&xfn(Ke,St),en!==void 0&&en!==""&&!o&&(async()=>{let Ye=Ht(),[ar,Ti]=await Promise.all([Ye.listHumanInbox(),Ye.getInboxHistory(void 0,{state:"pending"})]),Tu=[...ar.tickets,...Ti.tickets].map(Km).find(qs=>qs.inboxTicketId===en&&(qs.kind!=="page"||qs.state==="pending"));Tu===void 0?V("ask already answered"):Q.open(Tu)})().catch(Ye=>V(`could not open the ask: ${String(Ye?.message??Ye)}`)),await ui.done}export{B5s as runAttach};
1764
+ `)}`,"utf8")}catch{return}let o=`cat ${un(i)}; sleep ${bai}`;gai("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(Ygn+2),"-h",String(r.length+2),...Nd(),o],()=>{})}function Jgn(t,e=e7e(Yc(),xai)){let n=Sai(e),r=Date.now();n.total+=1,n.firstAt??=r,n.lastAt=r;let i=vai.find(a=>a.at===n.total&&!n.unlocked.includes(a.at));if(i!==void 0&&n.unlocked.push(i.at),_ai(e,n),i===void 0)return;let o=n.total;setTimeout(()=>Iai(i,o,t),Eai).unref?.()}async function O5s(t,e,n,r=!0){LT("viewer.connect_start",{node:t});let i=await mgn(t,n,r);LT(i.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:o,canvasSource:s,meta:a,socket:c}=i,u=fgn(o,e),l=kai();bon({cwd:a.cwd});let d=Eon(),p=gon(),h=Yx(),f=h.bindings;await yon(p);let m=await won(),g=new aw,y=new Wy(g),w=new et,E=new Ede,S=new pde(y,w,{cwd:a.cwd,palette:d,hideThinking:!0,banner:Lrt(hgn(a)),inlinePageBlocks:!o,pageOpenHint:()=>SR(f),backgroundBashHint:()=>o||!Rs()?null:Qz(f),onActivityChange:Ye=>{E.clear(),Ye&&E.addChild(Ye)}}),C=S.transcriptSource(),I=zdn(C),M=qdn(C,I.decorate),D=ppn(S,M,C),B,L=Cmn({tui:y,pal:d},()=>B.state()),F=apn(y,d,M,I,{bindings:()=>f,setNotice:Ye=>V(Ye)}),q=Ign(g,y,w,E,d,p,M,F.component),{containers:j,editor:W}=q,pe=new Mpe(y,d);j.header.addChild(pe),j.header.addChild(L.component);let K={nodeId:t,remote:o,role:u,meta:a,canvasSource:s,socket:c,tui:y,pal:d,editor:W,containers:j},Re=cmn(K,{syncCursor:()=>Pn.sync(),exitRoster:()=>Mn.exit(),openTicket:Ye=>{Q.open(Ye)},suppressed:()=>Q.active(),setNotice:Ye=>V(Ye),onRefreshFailure:Ye=>yt.reportFailure("inbox strip refresh",Ye)});j.header.addChild(Re.component);let Fe=zc("user"),Xe=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let St=yfn(),en=process.env.CRTR_ATTACH_OPEN_TICKET;en!==void 0&&delete process.env.CRTR_ATTACH_OPEN_TICKET;let $e=Vmn(Ye=>process.stdout.write(Ye),Fe.mouse_mode_default),X=Ymn({frame:()=>q.frame.lastRenderedFrame(),width:()=>y.terminal.columns});q.frame.setOverlay(Ye=>X.apply(Ye));let Ue=Smn(K,{state:()=>B.state(),bashMode:()=>At.bashMode(),asks:()=>yt.asks(),bindings:()=>f,inboxAffordance:!o&&Rs(),mouseEnabled:()=>$e.enabled()}),Ke=new Ape({tui:y,mouse:$e,rows:()=>y.terminal.rows,statusNotice:Ue.setNotice,formatNotice:Ye=>d.warning(`\u26A0 ${Ye}`),noticeMs:3e3,capabilities:{remote:o,canFocusNode:!o&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),Bt=(()=>{let Ye=a.profile_id;if(Ye)try{return{id:Ye,label:Kx(Ye).manifest.name}}catch{return{id:Ye,label:Ye}}})(),Nt=cgn({host:Ke,...Bt===void 0?{}:{profile:Bt},...o?{}:{scan:async()=>{let Ye=Ht(),[ar,Ti]=await Promise.all([Ye.listHumanInbox(),Ye.getInboxHistory(t,{state:"pending"})]),Tu=new Map;for(let qs of ar.tickets){let Td=Km(qs);Tu.set(Td.dir,Td)}for(let qs of Ti.tickets){let Td=Km(qs);Td.kind!=="page"||Td.state!=="pending"||!Td.awaitsResponse||Td.inbox||Tu.has(Td.dir)||Tu.set(Td.dir,Td)}for(let qs of Re.pendingTickets())Tu.has(qs.dir)||Tu.set(qs.dir,qs);return[...Tu.values()].sort($v)}}}),cn=o?()=>{}:FN(()=>{S.refreshPageBlocks(),Re.refresh()}),Q=bmn(K,{syncCursor:()=>Pn.sync(),refreshStrip:()=>{Re.refresh()},setNotice:Ye=>V(Ye),openInbox:Ye=>Nt.open(Ye),suspendForChild:()=>Ke.suspendForChild()});j.ticketPanel.addChild(Q.component);let G={toggleInbox:()=>{let Ye=Q.currentDir();if(Ye!==void 0){Q.close(),Nt.open(Ye);return}Nt.toggle()}},V=(Ye,ar)=>{Ke.hasFullPaneSurface()?Ke.notice(Ye,ar):Ue.setNotice(Ye,ar)},Ee=Ue.render,ce=Ye=>{V(D.copy(Ye))},we=upn(M,()=>y.requestRender()),De={"crtr.attach.scroll.up":()=>{we.cancel(),M.scrollBy(-1)&&y.requestRender()},"crtr.attach.scroll.down":()=>{we.cancel(),M.scrollBy(1)&&y.requestRender()},"crtr.attach.scroll.page-up":()=>{we.page("up")},"crtr.attach.scroll.page-down":()=>{we.page("down")},"crtr.attach.scroll.live":()=>{we.cancel(),M.goLive(),y.requestRender()},"crtr.attach.mouse.toggle":()=>{let Ye=$e.toggle();!Ye&&X.clear()&&y.requestRender(),V(Ye?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>ce("message")},ae,ye=Vfn(K,()=>ae===void 0?i.initialSnapshot!==void 0:ae.isDormant()),Me=ggn(),_e=kgn(K,ye,{setNotice:V,bindings:()=>f,fdPath:m,frecency:Me}),ze=Tgn(K,i.nodeIdentity,{isTornDown:()=>ui.isTornDown(),onChanged:()=>{At.syncContextBadge();let Ye=B.state().engine;Ye!==void 0&&At.setTitle(Ye.sessionName),y.requestRender()}});o&&ze.refresh();let At=vgn(K,{nodeIdentity:ze.current,thinkingLevel:()=>B.state().engine?.thinkingLevel,renderFooter:Ee,onTextChange:_e.syncCommandPreview});At.syncContextBadge();let{renderExtensionWidgets:st,renderQueued:er}=_mn(K,()=>B.state());B=Qgn(u,{setEngineState:Ye=>Lt.setState(Ye),setEditorTitle:At.setTitle,paintEditorFrame:At.paintFrame,renderExtensionWidgets:()=>{L.render(),st()},renderQueued:er,renderFooter:Ee,setTerminalTitle:Ye=>g.setTitle(Ye),refreshChrome:()=>yt.refresh()});let $n=Ye=>{if(!Rs()){V("Inspector requires tmux");return}V(`Opening Inspector (${Ye})\u2026`);let ar=by(),Tu=`${ar===void 0?"":`CRTR_HOME=${un(ar)} `}crtr surface inspect ${un(t)} --section ${Ye}`;Tai("tmux",["display-popup","-E","-T",` inspector \xB7 ${Ye} `,"-w","90%","-h","85%",...Nd(),Tu],()=>{yt.refresh()})},Mn=amn(K,{asks:()=>yt.asks(),setNotice:V,requestChromeRefresh:()=>yt.refresh(),openInspector:$n,openObject:Ye=>{if(!Rs()){V("Object details require tmux");return}V("Opening object\u2026");let ar=by(),Ti=ar===void 0?"":`CRTR_HOME=${un(ar)} `;Jz({name:Ye,produce:Tu=>`${Ti}crtr canvas read ${un(Ye)} > ${Tu} 2>&1`,title:`object \xB7 ${Ye}`,noNvim:"nvim is required to view the object. Install Neovim and retry.",onClose:()=>yt.refresh()})},syncCursor:()=>Pn.sync()}),Pn=Emn(W,[Mn.active,Re.active,Q.active]),Kr=new hpe(y,t,()=>yt.asks(),d,f,s,u,Ye=>yt.reportFailure("canvas graph refresh",Ye),V),ya=new fpe(y,d);ya.setBindings(f);let yt=Imn(K,{isTornDown:()=>ui.isTornDown(),setNotice:V,refreshRoster:async()=>{await Mn.refresh(),await Re.refresh()},refreshGraph:()=>Kr.refresh(),refreshIdentity:()=>ze.refresh(),renderFooter:Ee,renderExtensionWidgets:st,refreshInFlightTools:()=>S.refreshInFlightTools(),pollGit:At.pollGit}),Lt=Kfn(K,p,ye,{setNotice:V,agentDir:()=>B.state().agentDir,openNodeMetadata:()=>$n("overview"),isDormant:()=>ae.isDormant(),copyTarget:ce,toggleToolsExpanded:()=>S.toggleToolsExpanded(),toggleFoldTools:()=>S.toggleFoldSettledTools(),toggleShowWorking:()=>S.toggleShowWorking(),toggleThinking:()=>S.toggleThinking(),toggleGraph:()=>Kr.toggle(),toggleInbox:G.toggleInbox,toggleHelp:()=>ya.toggle(),toggleMouse:()=>$e.toggle(),quit:()=>Ts("detach"),setChipColor:At.setChipColor,onPromptSent:()=>{Fe.whip_mode&&pe.play()},frecency:Me}),ne=()=>{if(Ke.hasFullPaneSurface()){V("Close the active surface before whipping the agent");return}let Ye=Fe.whip_message_mode==="go-faster"?Ggn:jgn(Fe.whip_messages);Lt.sendInterrupting(Ye)&&(pe.play(),Jgn(d),V(`Whipped agent \u2014 ${Ye}`))},se=tgn({selfNodeId:t,remote:o,canvasSource:s,port:Fe.document_port,fetchSecret:async()=>(await Ht().documents.browserAccess()).secret,onSecretError:Ye=>V(`Document links are unavailable: ${Ye instanceof Error?Ye.message:String(Ye)}`),refresh:()=>S.refreshMarkdown()}),be=()=>{if(Q.active()){V("Close the open request first (Esc)");return}let Ye=[...S.getTranscriptDocRefsNewestFirst().map(Ti=>`[[${Ti}]]`),...S.getTranscriptFilePathsNewestFirst()],ar=Ti=>{vfn(Ke,Ti,{originNodeId:t,onNotice:V})};if(Ke.hasFullPaneSurface()){Ke.pickReviewFile({candidates:Ye,cwd:a.cwd,title:"Review a file or document named in this transcript"}).then(Ti=>{Ti!==null&&ar(Ti)});return}Lt.openFileReviewPicker(Ye,a.cwd,ar)},Qe=()=>{if(o){V("Profile file search is unavailable on remote canvases");return}if(!Rs()){V("Profile file search requires tmux");return}s.listNodes().then(Ye=>{let ar=Lgn(Ye,t);Ogn({cwd:a.cwd,nodeDirs:ar.map(Ti=>Ti.cwd),nodes:ar,profileId:a.profile_id??null,fdPath:m,onNotice:V})}).catch(Ye=>{let ar=Ye instanceof Error?Ye.message:String(Ye);V(`Could not load related node directories: ${ar}`)})},Te,Ze=()=>{Te!==void 0&&clearTimeout(Te),Te=setTimeout(()=>{Te=void 0,_6e(()=>h,()=>{},Rs,Yz)},1e3),Te.unref()},bt=qmn(K,{foldState:B.fold,chat:S,setNotice:V,renderFooter:Ee,setEditorText:Ye=>{W.setText(Ye),y.requestRender()},attachDialog:Ye=>Lt.attachDialog(Ye),dismissDialog:Ye=>Lt.dismissDialog(Ye),refreshNodeIdentity:ze.refresh,setCommands:_e.setCommands,resetMemoryRefs:_e.resetMemoryRefs,reloadBindings:()=>{h=_6e(Yx,Ye=>{Kr.setBindings(Ye),ya.setBindings(Ye)},Rs,Yz),f=h.bindings},modelThinkingLabel:B.modelThinkingLabel,onWelcome:()=>Ze()}),Ut=Ye=>{let ar=Ye instanceof Error?`${Ye.name}: ${Ye.message}`:String(Ye);Vv("attach.unhandled_rejection",ar),DVe(Ye)&&yt.reportFailure("background daemon call",Ye)};process.on("unhandledRejection",Ut);let Dr=()=>{process.off("unhandledRejection",Ut)},jr=Mgn(o,t),ui=Rmn(K,{stopLocal:()=>{Te!==void 0&&clearTimeout(Te),Ke.closeAll(),we.cancel(),$e.disable(),yt.stop(),Q.close(),Ue.dispose(),Kr.close(),ya.close(),F.close(),pe.dispose(),jr.clear(),Lpe(),Bpe(),Dpe(),Dr(),se.dispose(),cn();try{S.dispose()}catch{}},lastSocketError:()=>ae.lastSocketError(),tagPane:jr.pane}),Ts=ui.teardown;ae=$mn(K,{role:u,initialDormant:i.initialSnapshot!==void 0,clientId:l,onFrame:bt,setNotice:V,isTornDown:()=>ui.isTornDown(),teardown:Ts,onEnterDormancy:()=>{Ze(),S.settleRun(),B.patchLocal({isStreaming:!1})}}),i.assertConnected(),jr.set(),ae.install(),q.mount(),y.start(),i.initialSnapshot!==void 0&&(B.fold({type:"welcome",snapshot:i.initialSnapshot,role:u}),S.applySnapshot(i.initialSnapshot),_e.setCommands(i.initialCommands),o||Ht().markNodeRead(t).catch(()=>{})),Fe.whip_mode&&Xe&&pe.play(),$e.reassert();let mc=!1,Lx=Ye=>{if(mc)return;if(o){V("Opening a file is unavailable in a remote attach");return}let ar=ug();if(ar===null)return;let Ti=egn({file:Ye,pane:ar.pane,cwd:a.cwd,nodeId:t,observer:e,beforeRespawn:jr.clear});if(Ti==="opened"){mc=!0;return}Ti==="failed"&&jr.set(),Ti==="missing"&&V("File no longer exists"),Ti==="no_nvim"&&V("Neovim is required to open files \u2014 install it (brew install neovim / apt install neovim) and retry"),Ti==="failed"&&V("Could not open file in Neovim")};$e.install(y,{onWheel:(Ye,ar)=>{X.clear()&&y.requestRender(),!Ke.handleWheel(Ye,ar)&&(we.cancel(),M.scrollBy(Ye==="up"?-ar:ar)&&y.requestRender())},onPrimaryPress:(Ye,ar)=>{Ke.hasFullPaneSurface()||(X.clear()&&y.requestRender(),X.begin(Ye,ar))},onPrimaryDrag:(Ye,ar)=>{Ke.hasFullPaneSurface()||X.extend(Ye,ar)&&y.requestRender()},onPrimaryRelease:()=>{let Ye=X.release();Ye?.kind==="selection"&&(V(Ye.notice),y.requestRender())}});let Dpe=y.addInputListener(Ye=>{let ar=Zmn(Ye);if(ar===void 0)return;let Ti=ar.file;return Ti===void 0?V("Could not open file link"):Lx(Ti),ar.remaining.length>0?{data:ar.remaining}:{consume:!0}}),Bpe=y.addInputListener(()=>{X.clear()&&y.requestRender()}),Lpe=Gmn(K,{bindings:()=>f,detachHint:()=>ipn(f),hasExclusiveSurface:()=>Ke.hasFullPaneSurface(),setPaneFocused:Ye=>{Ye&&jr.stamp(),Pn.setPaneFocused(Ye),y.requestRender()},viewportActions:()=>De,searchHandleKey:F.handleKey,panelHandleKey:Q.handleKey,stripHandleKey:Re.handleKey,rosterHandleKey:Mn.handleKey,setNotice:V,detach:()=>Ts("detach"),cancelTurn:()=>{Lt.abortTurn()?V("Canceling the agent\u2026"):V(`Nothing running to cancel \u2014 press ${opn(f)??"ctrl+d"} to detach`)},toggleGraph:()=>Kr.toggle(),toggleHelp:()=>ya.toggle(),toggleInbox:G.toggleInbox,toggleInboxStrip:()=>{if(Ke.hasFullPaneSurface()){V("Close the active surface before opening the request strip");return}Q.active()&&Q.close(),Re.toggle()},cycleModelLadder:Ye=>Lt.cycleLadder(Ye),inspectLoadedCommand:_e.inspectLoadedCommand,openFileReview:be,openProfileFiles:Qe,openSearch:()=>{if(Ke.hasFullPaneSurface()||Q.active()){V("Close the active surface before searching the transcript");return}F.open()},whip:ne});ui.installSignalHandlers(),Ee(),yt.refresh(),er(),At.pollGit(),LT("viewer.first_paint"),process.stdout.write(kmn),xon(g.kittyProtocolActive),i.initialSnapshot!==void 0&&Ze(),i.initialSnapshot===void 0?(LT("viewer.hello_sent"),ae.sendHello()):ae.startDormant(),yt.start(),St!==void 0&&xfn(Ke,St),en!==void 0&&en!==""&&!o&&(async()=>{let Ye=Ht(),[ar,Ti]=await Promise.all([Ye.listHumanInbox(),Ye.getInboxHistory(void 0,{state:"pending"})]),Tu=[...ar.tickets,...Ti.tickets].map(Km).find(qs=>qs.inboxTicketId===en&&(qs.kind!=="page"||qs.state==="pending"));Tu===void 0?V("ask already answered"):Q.open(Tu)})().catch(Ye=>V(`could not open the ask: ${String(Ye?.message??Ye)}`)),await ui.done}export{O5s as runAttach};
1765
1765
  /*! Bundled license information:
1766
1766
 
1767
1767
  undici/lib/web/fetch/body.js: