dispach 0.2.2 → 0.2.4

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 (225) hide show
  1. package/README.md +34 -27
  2. package/dist/APEv2Parser-x13n424p.js +5 -0
  3. package/dist/{FlacParser-7t7da7qy.js.map → APEv2Parser-x13n424p.js.map} +1 -1
  4. package/dist/{AiffParser-y21k3fak.js → AiffParser-ns1y9f0g.js} +3 -3
  5. package/dist/{AiffParser-y21k3fak.js.map → AiffParser-ns1y9f0g.js.map} +1 -1
  6. package/dist/App-wkpkwgjt.js +11 -0
  7. package/dist/{App-4w3qkcs4.js.map → App-wkpkwgjt.js.map} +3 -3
  8. package/dist/AsfParser-bae2a1yf.js +5 -0
  9. package/dist/{AsfParser-wd98k2h4.js.map → AsfParser-bae2a1yf.js.map} +1 -1
  10. package/dist/ConfigEditor-hy9jtas3.js +6 -0
  11. package/dist/{ConfigEditor-vk7vxaa6.js.map → ConfigEditor-hy9jtas3.js.map} +1 -1
  12. package/dist/DsdiffParser-s0zvxnfa.js +5 -0
  13. package/dist/{DsdiffParser-cbfaj500.js.map → DsdiffParser-s0zvxnfa.js.map} +1 -1
  14. package/dist/{DsfParser-tybrja4x.js → DsfParser-90mvzt4v.js} +3 -3
  15. package/dist/{DsfParser-tybrja4x.js.map → DsfParser-90mvzt4v.js.map} +1 -1
  16. package/dist/FlacParser-8xprykrh.js +5 -0
  17. package/dist/{APEv2Parser-etzjd528.js.map → FlacParser-8xprykrh.js.map} +1 -1
  18. package/dist/{KeyProbe-5anphmb7.js → KeyProbe-fk5krzks.js} +3 -3
  19. package/dist/{KeyProbe-5anphmb7.js.map → KeyProbe-fk5krzks.js.map} +1 -1
  20. package/dist/MP4Parser-nmvbkq21.js +5 -0
  21. package/dist/{MP4Parser-gc94h1n9.js.map → MP4Parser-nmvbkq21.js.map} +2 -2
  22. package/dist/{MatroskaParser-cy2k4fac.js → MatroskaParser-tsmz2qfq.js} +3 -3
  23. package/dist/{MatroskaParser-cy2k4fac.js.map → MatroskaParser-tsmz2qfq.js.map} +1 -1
  24. package/dist/{MpegParser-c460fwf0.js → MpegParser-y5fjpaz9.js} +3 -3
  25. package/dist/{MpegParser-c460fwf0.js.map → MpegParser-y5fjpaz9.js.map} +1 -1
  26. package/dist/MusepackParser-544q0byg.js +5 -0
  27. package/dist/{MusepackParser-8mq2eabg.js.map → MusepackParser-544q0byg.js.map} +2 -2
  28. package/dist/OggParser-v77rbjnt.js +5 -0
  29. package/dist/{OggParser-7dnc6apg.js.map → OggParser-v77rbjnt.js.map} +1 -1
  30. package/dist/Picker-32m79nmp.js +5 -0
  31. package/dist/{Picker-j7txnm7w.js.map → Picker-32m79nmp.js.map} +1 -1
  32. package/dist/SessionPicker-9p06npt5.js +5 -0
  33. package/dist/{SessionPicker-hpv2ncsb.js.map → SessionPicker-9p06npt5.js.map} +1 -1
  34. package/dist/SkillBrowser-ezdx3xsh.js +5 -0
  35. package/dist/{SkillBrowser-qc542n71.js.map → SkillBrowser-ezdx3xsh.js.map} +1 -1
  36. package/dist/WavPackParser-k623m0hk.js +5 -0
  37. package/dist/{WavPackParser-kt7cds9c.js.map → WavPackParser-k623m0hk.js.map} +1 -1
  38. package/dist/WaveParser-nj4p1vx8.js +5 -0
  39. package/dist/{WaveParser-g47ja0vy.js.map → WaveParser-nj4p1vx8.js.map} +1 -1
  40. package/dist/WizardApp-p350qspw.js +5 -0
  41. package/dist/{WizardApp-q4p979d1.js.map → WizardApp-p350qspw.js.map} +1 -1
  42. package/dist/channels-a9zx9yba.js +31 -0
  43. package/dist/{channels-4t89qpdt.js.map → channels-a9zx9yba.js.map} +1 -1
  44. package/dist/client.d.ts +43 -0
  45. package/dist/client.js +9 -9
  46. package/dist/client.js.map +5 -5
  47. package/dist/components/App.d.ts.map +1 -1
  48. package/dist/config-3mz4zwsf.js +24 -0
  49. package/dist/{config-35r6n1gh.js.map → config-3mz4zwsf.js.map} +2 -2
  50. package/dist/credential-ja7zmd4c.js +19 -0
  51. package/dist/{credential-dpdgg4j6.js.map → credential-ja7zmd4c.js.map} +1 -1
  52. package/dist/index-039ew35r.js +6 -0
  53. package/dist/index-039ew35r.js.map +10 -0
  54. package/dist/index-0dvs3a06.js +6 -0
  55. package/dist/{index-jc4kmfwa.js.map → index-0dvs3a06.js.map} +1 -1
  56. package/dist/{index-pszmnhgq.js → index-1cagdzqe.js} +9 -9
  57. package/dist/{index-pszmnhgq.js.map → index-1cagdzqe.js.map} +1 -1
  58. package/dist/index-2fw9e5gg.js +6 -0
  59. package/dist/{index-0444sh6x.js.map → index-2fw9e5gg.js.map} +1 -1
  60. package/dist/{index-a2eh8dnk.js → index-2td5h856.js} +12 -12
  61. package/dist/{index-a2eh8dnk.js.map → index-2td5h856.js.map} +1 -1
  62. package/dist/{index-m6fqx0ch.js → index-446exxcb.js} +7 -7
  63. package/dist/{index-m6fqx0ch.js.map → index-446exxcb.js.map} +1 -1
  64. package/dist/{index-snz49ndn.js → index-4fajxhdv.js} +4 -4
  65. package/dist/{index-snz49ndn.js.map → index-4fajxhdv.js.map} +1 -1
  66. package/dist/index-4j65jp20.js +9 -0
  67. package/dist/{index-38gs9anh.js.map → index-4j65jp20.js.map} +1 -1
  68. package/dist/index-5gn74n56.js +10 -0
  69. package/dist/{index-ew997be5.js.map → index-5gn74n56.js.map} +2 -2
  70. package/dist/index-5zpfz4kb.js +9 -0
  71. package/dist/{index-8h6kewy1.js.map → index-5zpfz4kb.js.map} +1 -1
  72. package/dist/index-60h4knj6.js +126 -0
  73. package/dist/{index-zce9gy22.js.map → index-60h4knj6.js.map} +2 -2
  74. package/dist/index-635wcsh1.js +5 -0
  75. package/dist/{index-2bsardvh.js.map → index-635wcsh1.js.map} +1 -1
  76. package/dist/index-67sfck4d.js +110 -0
  77. package/dist/index-67sfck4d.js.map +13 -0
  78. package/dist/index-7p8d1gf0.js +63 -0
  79. package/dist/{index-ytxbw8py.js.map → index-7p8d1gf0.js.map} +1 -1
  80. package/dist/index-7zgjkbb0.js +5 -0
  81. package/dist/{index-qgsdgbk8.js.map → index-7zgjkbb0.js.map} +1 -1
  82. package/dist/{index-zw6wyas6.js → index-86rb86nr.js} +4 -4
  83. package/dist/{index-zw6wyas6.js.map → index-86rb86nr.js.map} +1 -1
  84. package/dist/{index-fbsrhcga.js → index-8jejze0z.js} +4 -4
  85. package/dist/{index-fbsrhcga.js.map → index-8jejze0z.js.map} +1 -1
  86. package/dist/index-8k8y7edx.js +7 -0
  87. package/dist/{index-3826kf9t.js.map → index-8k8y7edx.js.map} +1 -1
  88. package/dist/index-8mkatm20.js +6 -0
  89. package/dist/{index-42e29zs4.js.map → index-8mkatm20.js.map} +1 -1
  90. package/dist/{index-3vzf253k.js → index-9k6qa50r.js} +7 -7
  91. package/dist/{index-3vzf253k.js.map → index-9k6qa50r.js.map} +1 -1
  92. package/dist/{index-yw3fby4n.js → index-a1axc952.js} +4 -4
  93. package/dist/{index-yw3fby4n.js.map → index-a1axc952.js.map} +1 -1
  94. package/dist/index-ayhdn87b.js +6 -0
  95. package/dist/{index-dzy19wtf.js.map → index-ayhdn87b.js.map} +1 -1
  96. package/dist/index-b8bfzbfe.js +6 -0
  97. package/dist/{index-7mn8ack9.js.map → index-b8bfzbfe.js.map} +2 -2
  98. package/dist/index-brh25jhq.js +6 -0
  99. package/dist/{index-fa9wvpyw.js.map → index-brh25jhq.js.map} +2 -2
  100. package/dist/index-c6qrcweh.js +6 -0
  101. package/dist/{index-nxhqf597.js.map → index-c6qrcweh.js.map} +1 -1
  102. package/dist/index-cb45233h.js +6 -0
  103. package/dist/{index-nvc24414.js.map → index-cb45233h.js.map} +1 -1
  104. package/dist/{index-51x0n5z0.js → index-dcy14zdn.js} +5 -5
  105. package/dist/{index-51x0n5z0.js.map → index-dcy14zdn.js.map} +1 -1
  106. package/dist/index-f6r3h2yh.js +8 -0
  107. package/dist/{index-twn9bfm2.js.map → index-f6r3h2yh.js.map} +1 -1
  108. package/dist/index-gezqawvw.js +11 -0
  109. package/dist/{index-fcsg95m5.js.map → index-gezqawvw.js.map} +1 -1
  110. package/dist/index-h787rq0h.js +12 -0
  111. package/dist/{index-wc4entme.js.map → index-h787rq0h.js.map} +3 -3
  112. package/dist/index-hd5nkwd7.js +74 -0
  113. package/dist/index-hd5nkwd7.js.map +13 -0
  114. package/dist/index-k6wq0j4q.js +6 -0
  115. package/dist/{index-gq1npngp.js.map → index-k6wq0j4q.js.map} +1 -1
  116. package/dist/index-kz01jz58.js +6 -0
  117. package/dist/{index-323jvr1g.js.map → index-kz01jz58.js.map} +1 -1
  118. package/dist/{index-kjqksgch.js → index-mgef1n4e.js} +10 -10
  119. package/dist/{index-kjqksgch.js.map → index-mgef1n4e.js.map} +1 -1
  120. package/dist/{index-haypwvzd.js → index-n197qdw1.js} +188 -188
  121. package/dist/{index-haypwvzd.js.map → index-n197qdw1.js.map} +3 -3
  122. package/dist/index-nndwx2wp.js +153 -0
  123. package/dist/{index-z157at3s.js.map → index-nndwx2wp.js.map} +2 -2
  124. package/dist/index-pz92ksp8.js +5 -0
  125. package/dist/{index-3c5jt6by.js.map → index-pz92ksp8.js.map} +1 -1
  126. package/dist/index-qj4adnfe.js +14 -0
  127. package/dist/{index-eqqd4k4f.js.map → index-qj4adnfe.js.map} +2 -2
  128. package/dist/index-r83jpct7.js +6 -0
  129. package/dist/{index-gbkma7ds.js.map → index-r83jpct7.js.map} +2 -2
  130. package/dist/{index-2zjh5zd5.js → index-rqfwd7j5.js} +4 -4
  131. package/dist/{index-2zjh5zd5.js.map → index-rqfwd7j5.js.map} +1 -1
  132. package/dist/index-s0f0s6n5.js +6 -0
  133. package/dist/{index-p1zy871m.js.map → index-s0f0s6n5.js.map} +1 -1
  134. package/dist/index-s0t15ndj.js +6 -0
  135. package/dist/{index-8edck2pr.js.map → index-s0t15ndj.js.map} +1 -1
  136. package/dist/index-tc054tcb.js +6 -0
  137. package/dist/{index-8tmv33mr.js.map → index-tc054tcb.js.map} +1 -1
  138. package/dist/{index-095hrkyr.js → index-ts8a1sdn.js} +6 -6
  139. package/dist/{index-095hrkyr.js.map → index-ts8a1sdn.js.map} +1 -1
  140. package/dist/index-tv52jhac.js +1252 -0
  141. package/dist/{index-qg9bn980.js.map → index-tv52jhac.js.map} +15 -14
  142. package/dist/index-x9nn57kk.js +6 -0
  143. package/dist/{index-1x8mzvz7.js.map → index-x9nn57kk.js.map} +1 -1
  144. package/dist/{index-ynsvkqgb.js → index-xyh98x7p.js} +4 -4
  145. package/dist/{index-ynsvkqgb.js.map → index-xyh98x7p.js.map} +1 -1
  146. package/dist/{index-ma6p7bt4.js → index-yy4v9kca.js} +4 -4
  147. package/dist/{index-ma6p7bt4.js.map → index-yy4v9kca.js.map} +1 -1
  148. package/dist/{index-bqdkm3de.js → index-yz0fcxky.js} +4 -4
  149. package/dist/{index-bqdkm3de.js.map → index-yz0fcxky.js.map} +1 -1
  150. package/dist/{index-p6ya59m6.js → index-z4adxmzm.js} +5 -5
  151. package/dist/{index-p6ya59m6.js.map → index-z4adxmzm.js.map} +1 -1
  152. package/dist/{index-4fj1k64j.js → index-zzpgsbn3.js} +4 -4
  153. package/dist/{index-4fj1k64j.js.map → index-zzpgsbn3.js.map} +1 -1
  154. package/dist/index.js +343 -343
  155. package/dist/index.js.map +7 -7
  156. package/dist/lib/source.d.ts +8 -0
  157. package/dist/lib/source.d.ts.map +1 -1
  158. package/dist/lib/types.d.ts +8 -2
  159. package/dist/lib/types.d.ts.map +1 -1
  160. package/dist/run.d.ts.map +1 -1
  161. package/dist/transcript.d.ts.map +1 -1
  162. package/dist/web-7mdrcb8a.js +14 -0
  163. package/dist/{web-zph4h3p9.js.map → web-7mdrcb8a.js.map} +1 -1
  164. package/dist/wire.d.ts +19 -0
  165. package/dist/wire.js +5 -5
  166. package/dist/wire.js.map +4 -4
  167. package/dist/wrapper-4hdmdwft.js +5 -0
  168. package/dist/{wrapper-f662ny3r.js.map → wrapper-4hdmdwft.js.map} +1 -1
  169. package/package.json +1 -1
  170. package/dist/APEv2Parser-etzjd528.js +0 -5
  171. package/dist/App-4w3qkcs4.js +0 -11
  172. package/dist/AsfParser-wd98k2h4.js +0 -5
  173. package/dist/ConfigEditor-vk7vxaa6.js +0 -6
  174. package/dist/DsdiffParser-cbfaj500.js +0 -5
  175. package/dist/FlacParser-7t7da7qy.js +0 -5
  176. package/dist/MP4Parser-gc94h1n9.js +0 -5
  177. package/dist/MusepackParser-8mq2eabg.js +0 -5
  178. package/dist/OggParser-7dnc6apg.js +0 -5
  179. package/dist/Picker-j7txnm7w.js +0 -5
  180. package/dist/SessionPicker-hpv2ncsb.js +0 -5
  181. package/dist/SkillBrowser-qc542n71.js +0 -5
  182. package/dist/WavPackParser-kt7cds9c.js +0 -5
  183. package/dist/WaveParser-g47ja0vy.js +0 -5
  184. package/dist/WizardApp-q4p979d1.js +0 -5
  185. package/dist/channels-4t89qpdt.js +0 -31
  186. package/dist/config-35r6n1gh.js +0 -24
  187. package/dist/credential-dpdgg4j6.js +0 -19
  188. package/dist/index-0444sh6x.js +0 -6
  189. package/dist/index-1x8mzvz7.js +0 -6
  190. package/dist/index-2bsardvh.js +0 -5
  191. package/dist/index-323jvr1g.js +0 -6
  192. package/dist/index-3826kf9t.js +0 -7
  193. package/dist/index-38gs9anh.js +0 -9
  194. package/dist/index-3c5jt6by.js +0 -5
  195. package/dist/index-42e29zs4.js +0 -6
  196. package/dist/index-664xcamy.js +0 -110
  197. package/dist/index-664xcamy.js.map +0 -13
  198. package/dist/index-7mn8ack9.js +0 -6
  199. package/dist/index-8edck2pr.js +0 -6
  200. package/dist/index-8h6kewy1.js +0 -9
  201. package/dist/index-8tmv33mr.js +0 -6
  202. package/dist/index-9914wh1d.js +0 -6
  203. package/dist/index-9914wh1d.js.map +0 -10
  204. package/dist/index-dzy19wtf.js +0 -6
  205. package/dist/index-eqqd4k4f.js +0 -14
  206. package/dist/index-ew997be5.js +0 -10
  207. package/dist/index-fa9wvpyw.js +0 -6
  208. package/dist/index-fcsg95m5.js +0 -11
  209. package/dist/index-gbkma7ds.js +0 -6
  210. package/dist/index-gq1npngp.js +0 -6
  211. package/dist/index-jc4kmfwa.js +0 -6
  212. package/dist/index-nvc24414.js +0 -6
  213. package/dist/index-nxhqf597.js +0 -6
  214. package/dist/index-p1zy871m.js +0 -6
  215. package/dist/index-qg9bn980.js +0 -1213
  216. package/dist/index-qgsdgbk8.js +0 -5
  217. package/dist/index-r4ax3x4d.js +0 -74
  218. package/dist/index-r4ax3x4d.js.map +0 -13
  219. package/dist/index-twn9bfm2.js +0 -8
  220. package/dist/index-wc4entme.js +0 -12
  221. package/dist/index-ytxbw8py.js +0 -63
  222. package/dist/index-z157at3s.js +0 -153
  223. package/dist/index-zce9gy22.js +0 -126
  224. package/dist/web-zph4h3p9.js +0 -14
  225. package/dist/wrapper-f662ny3r.js +0 -5
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ import{t,r,p,me,a,i,et,x,B,de,Js,Ot,Nt,ce,X}from"./index-tv52jhac.js";var yn="dispach",bn="Dispach",vn=1;function pe(e,n){return{slug:e,name:n,envPrefix:`${e.toUpperCase()}_`,stateDir:`.${e}`,apiVersion:`${e}/v${vn}`,packageScope:`@${e}`}}var H=pe(yn,bn),K=`${H.envPrefix}BRAND`,Pe=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;function Fe(e){return e.split("-").map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function je(e){if(e===void 0)return H;let n=e.trim();if(n==="")throw Error(`${K} is set but empty. hint: unset ${K} entirely to use the default brand — an empty value `+'is treated as a mistake rather than as "no override", because a declared-but-unset variable is usually a container passing through a name it never assigned.');if(!Pe.test(n))throw Error(`${K}="${n}" is not a usable brand slug. hint: the slug becomes an env var prefix, a dot-directory, an npm scope, and the `+"manifest apiVersion, so it must be lowercase alphanumeric with inner hyphens — "+"e.g. acme or acme-run.");if(n===H.slug)return H;return pe(n,Fe(n))}var V=je(process.env[K]);function _n(e,n){let s=Array.from({length:n.length+1},(o,d)=>d);for(let o=1;o<=e.length;o+=1){let d=[o];for(let l=1;l<=n.length;l+=1){let c=(s[l-1]??0)+(e[o-1]===n[l-1]?0:1),u=(d[l-1]??0)+1,h=(s[l]??0)+1;d.push(Math.min(c,u,h))}s=d}return s[n.length]??Math.max(e.length,n.length)}function jt(e,n){let s,o=Number.POSITIVE_INFINITY;for(let d of n){let l=_n(e,d);if(l<o)o=l,s=d}return s!==void 0&&o<=Math.max(2,Math.floor(e.length/3))?s:void 0}var We=Symbol.for("dispach.HarnessError");function _(e){return typeof e==="object"&&e!==null&&We in e}class ne extends Error{static ERROR_NAME="HarnessError";code;hint;field;details;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause});if(this.name=new.target.ERROR_NAME??"HarnessError",this[We]=!0,this.code=e.code,this.hint=e.hint,this.field=e.field,e.detail!==void 0)this.detail=e.detail;this.details=e.details??[]}toDetail(){return{code:this.code,message:this.message,hint:this.hint,...this.field===void 0?{}:{field:this.field},...this.detail===void 0?{}:{detail:this.detail},...this.details.length>1?{details:this.details}:{}}}format(){let e=[`${this.code}: ${this.message}`];if(this.field!==void 0)e.push(` field: ${this.field}`);if(e.push(` hint: ${this.hint}`),this.detail!==void 0)e.push(` detail: ${this.detail}`);if(this.details.length===1)return e.join(`
3
+ `);for(let n of this.details){if(e.push(""),e.push(` ${n.code}: ${n.message}`),n.field!==void 0)e.push(` field: ${n.field}`);e.push(` hint: ${n.hint}`)}return e.join(`
4
+ `)}}class Q extends ne{static ERROR_NAME="ConfigError"}class ct extends ne{static ERROR_NAME="ModelError";status;retryAfterSeconds;constructor(e){super(e);this.status=e.status,this.retryAfterSeconds=e.retryAfterSeconds}}class b extends ne{static ERROR_NAME="ToolError"}function Be(e,n){return new Q({code:"tools_provider_alias_conflict",message:`The manifest sets tools.providers (${e.join(", ")}) and also the deprecated tools.provider${n===void 0?"Config":` (${n})`}.`,hint:`Keep tools.providers and delete the other two. Merging them would give the scalar a position in the map that nobody wrote, and provider order decides which one wins a slug collision${n===void 0?"":` — move ${n}'s settings into tools.providers.${n}`}.`,field:"tools.provider"})}function He(){return new Q({code:"workspace_alias_conflict",message:"The manifest sets both context.files and context.static.",hint:"context.files is the deprecated alias for context.static and resolves against the manifest directory, while context.static resolves against context.workspace. Merging them would produce an order nobody wrote and paths nobody can predict from reading the manifest, so pick one — context.static.",field:"context.files"})}function Xe(e,n){return new b({code:"workspace_not_editable",message:`${e} is declared editable: ${n}, so it cannot be written to.`,hint:"Point the write at a volatile file whose frontmatter allows it (editable: append or replace), or change that file's frontmatter. Read-only identity is deliberate — it is the most effective known mitigation for persona drift, so this refuses rather than silently doing nothing."})}function Ke(){return new b({code:"memory_forget_arguments",message:"memory_forget needs either `query` or `ids`, not both and not neither.",hint:"Call it with `query` first to see what matches, show the person, then call it again with the `ids` they confirm."})}function Ge(){return new b({code:"memory_forget_unavailable",message:"Memory cannot be changed from here: nothing runs turns in this context.",hint:"memory_forget works inside a turn of a running agent."})}function qe(){return new b({code:"artifact_unavailable",message:"This runtime has no artifact store, so a compacted observation cannot be read back.",hint:"artifact_read only works inside a session backed by a store. If you are seeing a compaction pointer without one, the pointer was written by a different process — report the text of the pointer rather than guessing at what it replaced."})}function ze(e){return new b({code:"artifact_not_found",message:`No compacted observation is stored under ${JSON.stringify(e)} in this conversation.`,hint:"Copy the id exactly from the pointer in the conversation — it is not guessable and it is scoped to this conversation. If the pointer came from a session you have since switched away from, the observation is not reachable from here."})}function A(e,n,s,o="images"){return new ne({code:e,message:n,hint:s,field:o})}function Ve(e,n,s,o){return new Q({code:"schedule_tool_unknown",message:`Schedule "${e}" allows ${n.join(", ")}, which ${n.length===1?"names":"name"} nothing this agent has.`,hint:`A schedule can only narrow the agent's own tools: name a pinned or local slug, a tag: annotation, or *. Available: ${s.join(", ")||"none"}. Refused rather than ignored, because a run with fewer tools than its author wrote fails quietly turns later.`,field:o})}class dr{runtimeId;#n=new Map;#e=new Map;#t=0;#s;#i;constructor(e){this.runtimeId=e.runtimeId,this.#i=e.now??(()=>new Date().toISOString()),this.#s=e.onHandlerError??((n,s)=>{console.error(`event handler threw while handling ${s.type}:`,n)})}on(e,n,s={}){if(e==="*"){let l=this.#e.has(n),c=s.chunks===!0,u=l?this.#e.get(n)??!1:!1;if(this.#e.set(n,c||u),!l&&c)this.#t+=1;else if(l&&c&&!u)this.#t+=1;return()=>{if(!this.#e.has(n))return;if(this.#e.get(n)===!0)this.#t-=1;this.#e.delete(n)}}let o=this.#n.get(e);if(o===void 0)o=new Set,this.#n.set(e,o);let d=!o.has(n);if(o.add(n),d&&e==="model.chunk")this.#t+=1;return()=>{if(o?.delete(n)===!0&&e==="model.chunk")this.#t-=1}}once(e,n,s={}){let o=this.on(e,(d)=>{o(),n(d)},s);return o}next(e,n,s={}){return new Promise((o,d)=>{let l=this.on(e,(u)=>{l(),n?.removeEventListener("abort",c),o(u)},s),c=()=>{l(),d(n?.reason??Error("aborted"))};n?.addEventListener("abort",c,{once:!0})})}get chunkSubscribers(){return this.#t}emit(e,n,s={}){if(e==="model.chunk"&&this.#t===0)return;let o={v:1,ts:this.#i(),runtimeId:this.runtimeId,...s.agentId===void 0?{}:{agentId:s.agentId},...s.sessionKey===void 0?{}:{sessionKey:s.sessionKey},...s.turnId===void 0?{}:{turnId:s.turnId},...s.stepId===void 0?{}:{stepId:s.stepId},...s.parentTurnId===void 0?{}:{parentTurnId:s.parentTurnId},...s.parentSessionKey===void 0?{}:{parentSessionKey:s.parentSessionKey},type:e,data:n};this.#o(o)}#o(e){let n=e.type==="model.chunk",s=this.#n.get(e.type);if(s!==void 0)for(let o of[...s])this.#r(o,e);for(let[o,d]of[...this.#e]){if(n&&!d)continue;this.#r(o,e)}}#r(e,n){try{e(n)}catch(s){this.#s(s,n)}}}var Ye="0.2.4",Tn=/^(\d+)\.(\d+)\.(\d+)$/,kn=/^(\d+)(?:\.(\d+))?(?:\.(\d+))?$/;function An(e){let n=Tn.exec(e.trim());if(n===null)return;return{major:Number(n[1]),minor:Number(n[2]),patch:Number(n[3])}}function Sn(e){let n=/^(\d+\.\d+\.\d+)(?:-[0-9A-Za-z.-]+)?$/.exec(e.trim());return n===null?void 0:An(n[1]??"")}function $n(e){let n=kn.exec(e.trim());if(n===null)return;let[,s,o,d]=n;return{version:{major:Number(s),minor:Number(o??0),patch:Number(d??0)},specified:d!==void 0?3:o!==void 0?2:1}}function I(e,n){if(e.major!==n.major)return e.major-n.major;if(e.minor!==n.minor)return e.minor-n.minor;return e.patch-n.patch}function Nn(e){if(e.major!==0)return{major:e.major+1,minor:0,patch:0};if(e.minor!==0)return{major:0,minor:e.minor+1,patch:0};return{major:0,minor:0,patch:e.patch+1}}function In(e,n){if(n===1)return{major:e.major+1,minor:0,patch:0};return{major:e.major,minor:e.minor+1,patch:0}}function On(e,n){if(n==="*"||n==="x"||n==="X")return!0;let s=/^(>=|<=|>|<|=|\^|~)?\s*(\S.*)$/.exec(n);if(s===null)return;let o=$n(s[2]??"");if(o===void 0)return;let{version:d,specified:l}=o;switch(s[1]){case"^":return I(e,d)>=0&&I(e,Nn(d))<0;case"~":return I(e,d)>=0&&I(e,In(d,l))<0;case">=":return I(e,d)>=0;case"<=":return I(e,d)<=0;case">":return I(e,d)>0;case"<":return I(e,d)<0;default:if(l===3)return I(e,d)===0;if(l===2)return e.major===d.major&&e.minor===d.minor;return e.major===d.major}}function ur(e,n){let s=Sn(e);if(s===void 0)return;let o=n.split("||"),d=!1;for(let l of o){let c=l.trim().split(/\s+/).filter((h)=>h!=="");if(c.length===0)return;let u=!0;for(let h of c){let f=On(s,h);if(f===void 0)return;if(!f)u=!1}if(d=!0,u)return!0}return d?!1:void 0}var Er=200;var Rn="What I already know, carried from before this conversation and kept current. "+"Not a transcript — these are standing facts about the person I work for and my own working notes. "+"If they ask what I know or remember about them, this is the answer.";var S=(e)=>String.fromCharCode(e),D=S(27),it=S(7),xn=new RegExp(`${D}\\[[0-?]*[ -/]*[@-~]`,"g"),Ln=new RegExp(`${D}\\][\\s\\S]*?(?:${it}|${D}\\\\|$)`,"g"),Mn=new RegExp(`${D}[P^_X][\\s\\S]*?(?:${D}\\\\|${it}|$)`,"g"),Cn=new RegExp(`${D}[@-Z\\\\-_0-9=><]?`,"g"),Dn=new RegExp(`[${S(128)}-${S(159)}]`,"g"),Un=new RegExp(`[${S(0)}-${S(8)}${S(11)}${S(12)}${S(14)}-${S(31)}${S(127)}]`,"g");function Jt(e){return e.replace(/\r\n/g,`
5
+ `).replace(/\r/g,`
6
+ `).replace(Ln,"").replace(Mn,"").replace(xn,"").replace(Cn,"").replace(Dn,"").replace(Un,"")}function rt(e){return e==="untrusted"?"obu":"obs"}function ot(e){return e.startsWith(`${rt("untrusted")}_`)?"untrusted":"trusted"}var Pn=3.8;function at(e){if(e==="")return 0;let n=0;for(let s=0;s<e.length;s+=1)if(e.charCodeAt(s)===10)n+=1;return Math.ceil(e.length/Pn)+n}var qt=["runtime.ready","store.ready","runtime.stopping","agent.loaded","agent.disposed","agent.reloaded","agent.warning","plugin.loaded","plugin.slow","approval.requested","approval.resolved","handoff.start","handoff.result","peer.ask","peer.answer","turn.start","context.assembled","context.dropped","context.pressure","compaction.stage","context.reset","session.compacted","phase.changed","model.call","model.chunk","model.retry","model.fallback","model.result","media.result","tool.usage","tool.call","tool.result","tool.gated","tool.repair","tools.refreshed","agent.tools.refreshed","agent.channel.status","agent.channel.error","agent.channel.rejected","delivery.sent","delivery.retry","delivery.failed","delivery.uncertain","runtime.released","schedules.reconciled","schedule.fired","schedule.skipped","schedule.deferred","schedule.error","conversation.message","conversation.skipped","action.deferred","action.decided","agent.assigned","memory.read","memory.recalled","memory.forgotten","turn.end","error"],Fn=/\r\n\r\n|\n\n|\r\r/;function Je(e){let n=[],s,o,d;for(let l of e.split(/\r\n|\n|\r/)){if(l===""||l.startsWith(":"))continue;let c=l.indexOf(":"),u=c===-1?l:l.slice(0,c),h=c===-1?"":l.slice(c+1);if(h.startsWith(" "))h=h.slice(1);switch(u){case"data":n.push(h);break;case"event":s=h;break;case"id":o=h;break;case"retry":{let f=Number.parseInt(h,10);if(Number.isFinite(f))d=f;break}default:break}}if(n.length===0&&s===void 0)return;return{...s===void 0?{}:{event:s},data:n.join(`
7
+ `),...o===void 0?{}:{id:o},...d===void 0?{}:{retry:d}}}async function*pr(e){let n=new TextDecoder,s="";for await(let o of e){s+=typeof o==="string"?o:n.decode(o,{stream:!0});while(!0){let d=Fn.exec(s);if(d===null)break;let l=s.slice(0,d.index);s=s.slice(d.index+d[0].length);let c=Je(l);if(c!==void 0)yield c}}if(s+=n.decode(),s.trim()!==""){let o=Je(s);if(o!==void 0)yield o}}function Cr(){return{push:(e)=>e,endStep:()=>"",end:()=>""}}var dt=["anyOf","oneOf","allOf","not","$ref"],jn=["format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","minLength","maxLength","pattern","minItems","maxItems"],Wn=new Set(["string","number","integer","boolean","array","object"]),Bn=new Set(["string","number","integer","boolean"]);function Hn(e){let n=e.anyOf??e.oneOf,s=Array.isArray(n)?n.map((d)=>{let l=R(d);if(l===void 0)return;return Object.keys(l).filter((u)=>u!=="type"&&u!=="description"&&u!=="title").length===0?l.type:void 0}):Array.isArray(e.type)?e.type:[];if(n!==void 0&&!Array.isArray(n))return;let o=s.filter((d)=>d!=="null");if(o.length<2)return;if(!o.every((d)=>typeof d==="string"&&Bn.has(d)))return;return[...new Set(o)]}function R(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Xn(e){let n=[];for(let s of jn){let o=e[s];if(o===void 0||o===null)continue;if(typeof o==="object")continue;n.push(`${s} ${String(o)}`)}return n.join(", ")}function Ze(e){let n=typeof e.description==="string"?e.description.trim():"",s=Xn(e);if(n===""&&s==="")return;if(s==="")return n;return n===""?s:`${n} (${s})`}function lt(e){return Array.isArray(e)?e.filter((n)=>typeof n==="string"):[]}function Kn(e){let n=e.anyOf??e.oneOf;if(!Array.isArray(n)||n.length!==2)return e;let s=(u)=>R(u)?.type==="null",o=n.find((u)=>!s(u));if(!n.some(s)||R(o)===void 0)return e;let{anyOf:d,oneOf:l,...c}=e;return{...R(o),...c}}function Gn(e){if(!Array.isArray(e))return e;let n=e.filter((s)=>s!=="null");return n.length===1?n[0]:e}function ut(e,n,s){let o=Kn(e),d=Hn(o),l=d===void 0?o:(({anyOf:g,oneOf:y,...v})=>v)(o);for(let g of dt)if(l[g]!==void 0)throw s.unsupported(n,g);if(d!==void 0){let g=Ze(l);return{type:d,...g===void 0?{}:{description:g},...l.default===void 0||l.default===null?{}:{default:l.default}}}let c=Gn(l.type);if(Array.isArray(c))throw s.unsupported(n,"type: []");let u=typeof c==="string"&&Wn.has(c)?c:s.untyped??"string",h=Ze(l),f=Array.isArray(l.enum)?l.enum.filter((g)=>typeof g==="string"||typeof g==="number"||typeof g==="boolean"):void 0,w=u==="array"?R(l.items):void 0,m=u==="object"?R(l.properties):void 0;return{type:u,...h===void 0?{}:{description:h},...f===void 0||f.length===0?{}:{enum:f},...w===void 0?{}:{items:ut(w,`${n}[]`,s)},...m===void 0?{}:{properties:ht(m,n,s),required:lt(l.required)},...l.default===void 0||l.default===null?{}:{default:l.default}}}function ht(e,n,s){let o={};for(let[d,l]of Object.entries(e)){let c=R(l);if(c===void 0)continue;o[d]=ut(c,n===""?d:`${n}.${d}`,s)}return o}function io(e,n){if(e===void 0)return{type:"object",properties:{}};for(let l of dt)if(e[l]!==void 0)throw n.unsupported(n.rootPath??"parameters",l);let s=R(e.properties)??{},o=lt(e.required),d=ht(s,"",n);return{type:"object",properties:d,...o.length===0?{}:{required:o.filter((l)=>(l in d))}}}var ft="<<<",mt=">>>",G=/^\s*(?:(?:[-*+]|\d+[.)])\s+)?(?:<\s*)?action\s*:(.+)$/i,qn=/^\s*(?:[-*+]\s+|\d+[.)]\s+)?([A-Za-z_][\w.-]*?)\s*:(.*)$/,be=/^\s*`{3,}\s*(?:[\w+-]+\s*)?$/,ge=/^\s*end\s*$/i,Yn=/^\s*<\s*action\s*>\s*$/i,Qe=/^\s*<\s*\/\s*action\s*>\s*$/i,zn=/^\s*<\/?\s*[A-Za-z_][\w.:-]*\s*(?:\/\s*)?>\s*$/;function tt(e){let n=(e??"").trim();return n.endsWith(">")?n.slice(0,-1).trimEnd():n}function we(e){return nt(nt(Vn(e,"`'\"*<"),"`'\"*>"),".,;:").trim()}function Vn(e,n){let s=0;while(s<e.length&&n.includes(e[s]??""))s+=1;return e.slice(s)}function nt(e,n){let s=e.length;while(s>0&&n.includes(e[s-1]??""))s-=1;return e.slice(0,s)}function pt(e,n,s){let o=e.fields.get(n);if(o===void 0)e.fields.set(n,[s]);else o.push(s)}function gt(e){if(e.block===void 0||e.heredocKey===void 0)return;let n=[...e.heredocLines];if(n[n.length-1]==="")n.pop();pt(e.block,e.heredocKey,n.join(`
8
+ `)),e.block.wrapped.add(e.heredocKey),e.heredocKey=void 0,e.heredocLines=[]}function C(e){if(gt(e),e.block!==void 0)e.blocks.push(e.block);e.block=void 0,e.openKey=void 0,e.awaitingSlug=!1}function st(){return{block:void 0,openKey:void 0,severedKey:void 0,severedPending:void 0,heredocKey:void 0,heredocLines:[],justClosed:!1,awaitingSlug:!1,text:[],blocks:[]}}function Jn(e,n,s){let o=n.trim();if(e.heredocKey!==void 0){if(o===mt){gt(e);return}if(ge.test(o)){C(e),e.justClosed=!0;return}if(G.test(n)){C(e);let c=G.exec(n),u=we(tt(c?.[1]));if(u!=="")e.block={slug:u,fields:new Map,wrapped:new Set,severed:new Set};return}e.heredocLines.push(n);return}let d=G.exec(n);if(d!==null){let c=we(tt(d[1]));if(C(e),c==="")return;e.block={slug:c,fields:new Map,wrapped:new Set,severed:new Set};return}if(Yn.test(n)){C(e),e.awaitingSlug=!0;return}if(e.awaitingSlug){if(o==="")return;if(Qe.test(n)){e.awaitingSlug=!1;return}let c=we(o);if(e.awaitingSlug=!1,c!=="")e.block={slug:c,fields:new Map,wrapped:new Set,severed:new Set};return}if(Qe.test(n)){if(e.block!==void 0)C(e),e.justClosed=!0;return}if(zn.test(n))return;if(e.block===void 0){if(be.test(n)&&(e.justClosed||s())){e.justClosed=!1;return}if(ge.test(o)&&e.severedPending!==void 0){e.severedPending.block.severed.add(e.severedPending.key),e.severedPending=void 0;return}if(G.test(n))e.severedPending=void 0;if(e.text.push(n),o!=="")e.justClosed=!1;return}if(o===""){if(e.openKey!==void 0)e.severedKey=e.openKey;e.openKey=void 0;return}if(ge.test(o)){e.severedKey=void 0,C(e),e.justClosed=!0;return}if(be.test(n))return;let l=qn.exec(n);if(l!==null){let c=(l[1]??"").trim(),u=(l[2]??"").trim();if(e.severedKey=void 0,u===ft)e.heredocKey=c,e.heredocLines=[],e.openKey=void 0;else pt(e.block,c,u),e.openKey=c;return}if(e.openKey!==void 0){let c=e.block.fields.get(e.openKey),u=c?.[c.length-1];if(c!==void 0&&u!==void 0)c[c.length-1]=u===""?o:`${u}
9
+ ${o}`;return}if(e.severedKey!==void 0)e.severedPending={block:e.block,key:e.severedKey},e.severedKey=void 0;C(e),e.text.push(n)}function Zn(e){if(/^\s*(?:(?:[-*+]|\d+[.)]?)\s*)?$/.test(e))return!0;let n=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)?/,"").toLowerCase(),s=n.startsWith("<")?n.slice(1):n;if("action:".startsWith(s)||s.startsWith("action:"))return!0;if(/^<\/?$/.test(n)||/^<\/?[a-z_][\w.:-]*>?$/.test(n))return!0;return/^`{1,3}[\w+-]*$/.test(n)}function ye(e){return e.endsWith("\r")?e.slice(0,-1):e}function fr(){let e=st(),n="",s=0,o,d="",l=!1,c=(m)=>{if(m==="")return"";if(m.trim()==="")return d+=m,"";let g=d+m;if(d="",l)return g;return l=!0,g.replace(/^\s+/,"")},u=(m,g)=>{let y=e.text.length;return Jn(e,m,()=>g!==void 0&&G.test(g)),e.text.length>y?m:void 0},h=(m,g,y)=>{let v=u(m,g);if(v===void 0)return"";return c(v.slice(y))+c(`
10
+ `)},f=(m)=>{if(o===void 0)return"";let g=o;return o=void 0,h(g,m,0)};return{push(m){let g="";n+=m;let y=n.indexOf(`
11
+ `);while(y!==-1){let T=ye(n.slice(0,y));if(n=n.slice(y+1),g+=f(T),e.block===void 0&&be.test(T)&&!e.justClosed)o=T;else g+=h(T,void 0,s);s=0,y=n.indexOf(`
12
+ `)}let v=ye(n);if(e.block===void 0&&!e.awaitingSlug&&o===void 0&&!Zn(v))g+=c(v.slice(s)),s=v.length;return g},endStep(){let m=w();return d=`
13
+
14
+ `,e=st(),m},end:w};function w(){let m=f(void 0),g=ye(n);if(g!==""){let y=u(g,void 0);if(y!==void 0)m+=c(y.slice(s))}return n="",s=0,o=void 0,m}}var Eo=`# Tools
15
+
16
+ To use a tool, write an ACTION block. Start each line at the left margin, exactly like this:
17
+
18
+ ACTION: weather_lookup
19
+ city: Lisbon
20
+ units: celsius
21
+ END
22
+
23
+ That block is an example of the shape only. Your own tools are listed below — take the tool name and
24
+ every field name from that list, spelled exactly as it is written there.
25
+
26
+ Rules for a block:
27
+ - One field per line, written as \`name: value\`, where \`name\` is one of that tool's own field names.
28
+ - For a value spanning several lines, open it with \`${ft}\` and close it with \`${mt}\` alone on its own line.
29
+ - Finish every block with \`END\` alone on its own line.
30
+ - Several blocks are allowed. They run in the order you write them.
31
+ - Use only the tools listed below, only their listed fields, and always give every required field.
32
+
33
+ Anything you write outside a block is shown to the person you are talking to, so keep explanations
34
+ short and keep them out of the block. When no tool fits, simply reply — never invent a tool, and
35
+ never guess a value for a required field you have not been given.`;import{readFile as rs,realpath as wt,stat as os}from"node:fs/promises";import{isAbsolute as as,resolve as ve,sep as yt}from"node:path";import{basename as Ad,isAbsolute as Yt,resolve as zt}from"node:path";import{appendFile as $t,mkdir as Ii,readFile as Oi}from"node:fs/promises";import{join as It}from"node:path";import{appendFile as sn,mkdir as Ri,readFile as xi,writeFile as Li}from"node:fs/promises";import{join as Mi}from"node:path";import{readFile as Ji,writeFile as Zi}from"node:fs/promises";import{dirname as Qi}from"node:path";import{isDeepStrictEqual as er}from"node:util";import{existsSync as pn,readdirSync as oo,readFileSync as q,rmSync as Dt,writeFileSync as ie}from"node:fs";import{isAbsolute as uo,join as he,resolve as ho}from"node:path";var Qn=`${V.slug}_`,es="0123456789abcdefghjkmnpqrstvwxyz",ts=32;function hr(){let e=new Uint8Array(ts);crypto.getRandomValues(e);let n="";for(let s of e)n+=es[s&31]??"0";return`${Qn}${n}`}async function Br(e){let n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(n)].map((s)=>s.toString(16).padStart(2,"0")).join("")}var yr=64,ns=new RegExp("[\\u0000-\\u001f\\u007f]");function Qs(e){if(e.trim()==="")return"A key label cannot be empty.";if(e.length>yr)return`A key label is at most ${yr} characters; this one is ${e.length}.`;if(ns.test(e))return"A key label cannot contain control characters, including newlines and tabs.";return}function Vr(e){let n=`${e.channel}:${e.peerId}`;return e.thread===void 0||e.thread===""?n:`${n}:${e.thread}`}var ss=/^[0-9a-hjkmnp-tv-z]{6}$/;function Wr(e,n){if(e===n)return!0;return e.startsWith(`${n}~`)&&ss.test(e.slice(n.length+1))}var is=/~[0-9a-hjkmnp-tv-z]{6}$/;function ms(e,n){let s=n.get(e);if(s!==void 0)return s===e;if(is.test(e))return[...n.values()].includes(e);return!0}var so=3932160,bt=5;function Pt(e){let n=(d)=>e[d]??-1;if(n(0)===137&&n(1)===80&&n(2)===78&&n(3)===71)return"image/png";if(n(0)===255&&n(1)===216&&n(2)===255)return"image/jpeg";if(n(0)===71&&n(1)===73&&n(2)===70&&n(3)===56)return"image/gif";let s=n(0)===82&&n(1)===73&&n(2)===70&&n(3)===70,o=n(8)===87&&n(9)===69&&n(10)===66&&n(11)===80;if(s&&o)return"image/webp";return}var ds=/^[A-Za-z0-9+/]+={0,2}$/;async function Ss(e,n){if(n.length>bt)throw A("image_count_exceeded",`${n.length} images were sent with one message; at most ${bt} are.`,"Send the rest in a following message.");let s=[];for(let[o,d]of n.entries())s.push(await ls(e,d,`images[${o}]`));return s}async function ls(e,n,s){if(n.path!==void 0&&n.data!==void 0)throw A("image_source_ambiguous","An image named both a path and inline data.",'Send one: { "path": "files/…/shot.png" }, or { "data": "<base64>", "mediaType": "image/png" }.',s);if(n.path!==void 0)return await cs(e,n.path,s);if(n.data!==void 0)return us(n.data,n.mediaType,s);throw A("image_source_missing","An image named neither a path nor data.",`Send { "path": "files/…/shot.png" } (relative to the agent's directory), or { "data": "<base64>", "mediaType": "image/png" }.`,s)}async function cs(e,n,s){if(n.trim()===""||as(n))throw A("image_path_invalid",`The image path "${n}" is not relative to the agent's directory.`,"Name the file relative to the agent's directory, e.g. files/<conversation>/shot.png.",s);let o=ve(e,n),d=ve(e);if(o!==d&&!o.startsWith(`${d}${yt}`))throw vt(n,s);let l,c;try{c=await wt(e),l=await wt(ve(e,n))}catch{throw A("image_not_found",`No file at "${n}" in the agent's directory.`,"Save the image inside the agent's directory first, then name it relative to that directory.",s)}if(l!==c&&!l.startsWith(`${c}${yt}`))throw vt(n,s);let u=await os(l);if(!u.isFile())throw A("image_not_found",`"${n}" is not a file.`,"Name an image file, not a directory.",s);if(u.size>so)throw Ft(n,u.size,s);let h=new Uint8Array(await rs(l)),f=Pt(h);if(f===void 0)throw Bt(n,s);return{mediaType:f,data:Buffer.from(h).toString("base64"),ref:n}}function us(e,n,s){let o=e.replace(/\s+/g,"");if(o===""||o.length%4!==0||!ds.test(o))throw A("image_data_invalid","The image's data is not base64.",`Send the file's bytes base64-encoded, with no "data:" prefix.`,s);let{mediaType:d}=hs(new Uint8Array(Buffer.from(o,"base64")),"upload",s);if(n!==void 0&&n!==d)throw A("image_media_type_mismatch",`The image was declared ${n} and its bytes are ${d}.`,"Leave mediaType out, or send the type the file really is.",s);return{mediaType:d,data:o,ref:"upload"}}function hs(e,n,s="image"){if(e.length>so)throw Ft(n,e.length,s);let o=Pt(e);if(o===void 0)throw Bt(n,s);return{mediaType:o,data:Buffer.from(e).toString("base64"),ref:n}}function vt(e,n){return A("image_path_invalid",`The image path "${e}" leads outside the agent's directory.`,"Images are read from inside the agent's directory only. Copy the file there first.",n)}function Ft(e,n,s){return A("image_too_large",`"${e}" is ${n} bytes; an image may be at most ${so}.`,"Resize or compress it first.",s)}function Bt(e,n){return A("image_unsupported",`"${e}" is not a PNG, JPEG, GIF or WebP image.`,"Convert it to one of those formats first.",n)}var fs="session:";function Ht(e){return e.startsWith(fs)}var ps="scope:";function Xt(e){return e.startsWith(ps)}var _t="0123456789abcdefghijklmnopqrstuvwxyz";function gs(e){let n=new Uint8Array(e);crypto.getRandomValues(n);let s="";for(let o of n)s+=_t[o%_t.length];return s}function xe(e,n){return`${e}_${n.toString(36)}${gs(8)}`}function ao(e=Date.now()){return xe("t",e)}function ws(e=Date.now()){return xe("r",e)}function Ds(e=Date.now()){return xe("k",e)}var Tt="phase_set",Kt="*",Et="tag:";function bs(e){let n=Object.keys(e);return n.find((o)=>e[o]?.entry===!0)??n[0]}function kt(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}function Gt(e,n){if(e===Kt)return!0;if(e.startsWith(Et)){let s=e.slice(Et.length).toLowerCase();return n.tags.some((o)=>o.toLowerCase()===s)}return kt(e)===kt(n.slug)}function ys(e,n){return e.filter((s)=>!n.some((o)=>Gt(s,o)))}function Es(e,n){let s=e[n];if(s===void 0)return[Kt];return s.allow.includes(Tt)?s.allow:[...s.allow,Tt]}function zr(e){return e!==void 0&&Object.keys(e).length>1}function Os(e,n){return Object.keys(e).filter((s)=>Es(e,s).some((o)=>Gt(o,n)))}var Vt=["user","agent"];function Zr(e,n=""){let s="",o=0;for(;;){let d=e.indexOf("<!--",o);if(d===-1)break;let l=e.indexOf("-->",d+4);if(l===-1)break;s+=e.slice(o,d)+n,o=l+3}return s+e.slice(o)}function go(e){let n=e.length;while(n>0&&e[n-1]==="/")n-=1;return e.slice(0,n)}var As=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,$s=/\n{3,}/g;function Is(e){let n=As.exec(e);return n===null||n===void 0?e:e.slice(n[0].length)}function Cs(e){return Zr(e).replace($s,`
36
+
37
+ `).trim()}var J={static:2000,volatile:3500,reminder:500,total:6000};function js(e){let n=e.files.filter((l)=>l.tier==="volatile");if(n.length===0)return;let s=(l)=>l.editable==="append"||l.editable==="replace",o=n.find((l)=>s(l)&&l.eviction==="oldest")??n.find(s);if(o!==void 0)return{path:o.path,name:o.name,mode:o.editable==="replace"?"replace":"append",budget:o.budget,eviction:o.eviction};let d=n[0];if(d===void 0)return;return{name:d.name,mode:"refused",reason:d.editable}}function Z(e){return e.names.map((n,s)=>({name:n,path:Yt(n)?n:zt(e.base,n),tier:e.tier,field:`${e.field}[${s}]`}))}function Ns(e,n){let s=e.files??[],o=e.static??[];if(s.length>0&&o.length>0)throw He();let d=Yt(e.workspace)?e.workspace:zt(n,e.workspace),l=[],c=[];if(s.length>0)l.push(...Z({base:n,names:s,tier:"static",field:"context.files"})),c.push({code:"context_files_deprecated",message:`context.files is deprecated; its ${s.length} file(s) were loaded as the static tier.`,hint:"Move them to context.static and set context.workspace to the directory holding them. The tier lists say which files are cache-stable, which the agent may write to, and which sit after the conversation history — none of which an ordered array can express.",field:"context.files"});if(l.push(...Z({base:d,names:o,tier:"static",field:"context.static"})),l.push(...Z({base:d,names:e.volatile??[],tier:"volatile",field:"context.volatile"})),e.reminder!==void 0)l.push(...Z({base:d,names:[e.reminder],tier:"reminder",field:"context.reminder"}));return{refs:l,warnings:c}}var k=t().min(1),Ws=i({delimiters:B(["xml","markdown","plain"]).optional(),intensity:B(["emphatic","neutral","soft"]).optional(),examplesIn:B(["system","user"]).optional(),skillsIn:B(["system","user"]).optional()}).strict(),Bs=i({nativeTools:p().optional(),strictSchema:p().optional(),thinking:B(["none","anthropic","openai","deepseek"]).optional(),promptCache:B(["none","anthropic","openai","bedrock"]).optional(),parallelToolCalls:p().optional(),contextWindow:r().int().positive().optional(),maxOutput:r().int().positive().optional(),vision:p().optional(),promptStyle:Ws.optional()}).strict(),At="chat-completions",Zt=i({id:t().min(1),api:t().min(1).optional(),options:x(t(),me()).optional(),baseUrl:t().min(1).optional(),apiKeyEnv:t().min(1).optional(),temperature:r().min(0).max(2).optional(),topP:r().min(0).max(1).optional(),maxTokens:r().int().positive().optional(),reasoningEffort:B(["none","minimal","low","medium","high","xhigh","max"]).optional(),headers:x(t(),t()).optional(),streamUsage:p().optional(),capabilities:Bs.optional()}).strict();function Qt(e,n){if((e.api??At)===At&&e.baseUrl===void 0)n.addIssue({code:"custom",path:["baseUrl"],message:"baseUrl is required for the chat-completions transport"})}var Hs=Zt.superRefine(Qt),ee=Zt.extend({fallbacks:a(Hs).min(1).optional()}).superRefine(Qt),Xs=i({main:ee,selector:ee.optional(),compactor:ee.optional()}).catchall(ee),Ks=i({snip:r().default(0.6),micro:r().default(0.7),collapse:r().default(0.8),reset:r().default(0.88),trim:r().default(0.95)}).strict(),qs=i({static:r().int().positive().default(J.static),volatile:r().int().positive().default(J.volatile),reminder:r().int().positive().default(J.reminder),total:r().int().positive().default(J.total)}).strict(),Ys=i({perRuleSuccess:r().gt(0).lte(1).default(0.9),reliabilityTarget:r().gt(0).lt(1).default(0.8),onExceed:B(["fail","warn"]).default("fail")}).strict(),zs=i({file:t().min(1),requires:i({contextWindow:t().min(1).optional(),class:B(["frontier","small"]).optional()}).strict().optional(),onUnmet:B(["distill","omit","fail"]).default("distill"),distilled:t().min(1).optional()}).strict(),Vs=i({dir:t().min(1),maxActive:r().int().nonnegative().default(2),budget:r().int().positive().default(600)}).strict(),Zs=i({window:r().int().positive().optional(),reserveOutput:r().int().positive().default(4096),observationMaxTokens:r().int().positive().optional(),modelIdentity:B(["shown","hidden"]).default("shown"),files:a(t().min(1)).default([]),workspace:t().min(1).default("./workspace"),static:a(t().min(1)).default([]),volatile:a(t().min(1)).default([]),reminder:t().min(1).optional(),budgets:qs.prefault({}),rules:Ys.prefault({}),soul:zs.optional(),compactionNotice:p().optional(),thresholds:Ks.prefault({})}).strict(),si=i({max:r().int().positive().default(24),reserveWrite:r().int().nonnegative().default(6)}).strict(),ii=i({onMutate:B(["refuse","confirm","allow"]).default("refuse")}).strict(),ri=i({mode:B(["ask","allow","deny"]).default("allow"),allow:a(t().min(1)).default([]),deny:a(t().min(1)).default([]),onNoApprover:B(["deny","allow"]).default("deny")}).strict(),ai=i({dialect:B(["nlt","native"]).default("nlt"),providers:x(k,x(t(),me())).default({}),provider:k.optional(),providerConfig:x(t(),me()).default({}),budget:si.prefault({}),pinned:a(t().min(1)).default([]),search:i({enabled:p().default(!1)}).strict().prefault({}),local:a(t().min(1)).default([]),untrusted:ii.prefault({}),policy:ri.prefault({}),eventDetail:B(["none","redacted"]).default("none")}).strict(),di=i({allow:a(t().min(1)),entry:p().optional()}).strict(),li=i({dir:t().min(1).default("./skills"),maxActive:r().int().nonnegative().default(1),threshold:r().default(0.35),trusted:a(t().min(1)).optional()}).strict(),ci=i({retriever:t().min(1).default("fts5"),dir:t().min(1).default("./memory"),maxActive:r().int().nonnegative().default(5),threshold:r().default(0.2),budget:r().int().positive().default(2000),includeHistory:p().default(!0),shared:p().default(!0)}).strict(),ui=["owner","peer","channel-peer"],hi=i({scope:B(ui).default("channel-peer")}).strict(),fi=i({type:k,id:k,allowFrom:a(t().min(1)).optional(),enabled:p().default(!0),role:k.optional()}).passthrough(),en=i({channel:k,to:t().min(1)}).strict(),mi=i({default:k.optional(),reply:B(["all","final"]).default("all"),targets:x(t(),en).default({})}).strict(),oe=Js(()=>i({type:B(["string","number","integer","boolean","array","object"]),description:t().optional(),enum:a(et([t(),r(),p()])).optional(),items:oe.optional(),properties:x(t(),oe).optional(),required:a(t()).optional()})),tn=i({id:k,manifest:t().min(1),task:t().min(1),artifact:i({type:de("object"),properties:x(t(),oe),required:a(t()).optional()}).strict()}).strict(),pi=i({members:a(tn).min(1)}).strict(),gi=i({name:k,task:t().min(1),tools:a(t().min(1)).min(1),route:i({tools:a(t().min(1)).min(1)}).strict().optional(),spawn:p().default(!1),artifact:tn.shape.artifact.optional(),model:t().min(1).optional(),maxSteps:r().int().positive().optional(),timeoutMs:r().int().positive().optional()}).strict(),_e={provider:t().min(1),model:t().min(1).optional(),baseUrl:t().min(1).optional(),apiKeyEnv:t().min(1).optional(),options:x(t(),me()).optional()},wi=i({transcription:i({..._e,timeoutMs:r().int().positive().default(60000),maxBytes:r().int().positive().default(26214400)}).strict().optional(),speech:i({..._e,timeoutMs:r().int().positive().default(60000),maxCharacters:r().int().positive().default(3000)}).strict().optional(),image:i({..._e,timeoutMs:r().int().positive().default(120000),size:t().regex(/^[0-9]+x[0-9]+$/).default("1024x1024")}).strict().optional()}).strict(),yi=i({enabled:p().default(!1),escalateAfterMs:r().int().nonnegative().default(0)}).strict(),bi=i({offer:i({task:t().min(1),artifact:i({type:de("object"),properties:x(t(),oe),required:a(t()).optional()}).strict()}).strict().optional(),to:et([de("*"),a(k).min(1)]).optional(),ask:p().default(!1)}).strict(),nn=i({id:k,kind:B(["cron","every","at"]),expr:t().min(1),task:t().min(1),deliver:et([de("none"),en]),session:t().min(1).default("isolated"),role:k.optional(),tools:i({allow:a(t().min(1)).min(1)}).strict().optional(),timeoutMs:r().int().positive().optional(),maxSteps:r().int().positive().optional(),enabled:p().default(!0),timezone:t().min(1).optional()}).strict(),vi=et([t().min(1),i({spec:t().min(1),config:x(t(),me()).default({})}).strict()]),_i=i({identicalCalls:r().int().min(2).default(3),sameTool:r().int().min(2).optional()}).strict(),Ti=i({maxSteps:r().int().positive().default(40),noProgress:_i.prefault({}),turnTimeoutMs:r().int().positive().default(1800000),toolTimeoutMs:r().int().positive().default(120000),maxParallelTools:r().int().positive().default(4),maxConcurrentTurns:r().int().positive().optional(),reloadHoldMs:r().int().nonnegative().default(30000),maxHops:r().int().nonnegative().default(4),tokens:i({max:r().int().positive(),windowMs:r().int().positive()}).strict().optional()}).strict(),Ei=i({enabled:p().default(!1),port:r().int().min(1).max(65535).default(7420),host:t().min(1).default("127.0.0.1"),tokenEnv:t().min(1).default(`${V.envPrefix}API_TOKEN`),allowedOrigins:a(t().min(1)).default([]),allowedHosts:a(t().min(1)).default([])}).strict(),$r=i({apiVersion:t().min(1),id:k.refine((e)=>!e.startsWith("~"),{message:"An agent id may not start with `~`; that prefix is reserved for shared memory scopes."}),name:t().min(1).optional(),description:t().min(1).max(200,{message:"A description is one line of at most 200 characters; it is rendered into every peer's ask_agent description."}).refine((e)=>!/[\r\n]/.test(e),{message:"A description is one line; put the detail in AGENTS.md."}).optional(),extends:t().min(1).optional(),model:Xs,context:Zs.prefault({}),tools:ai.prefault({}),phases:x(t(),di).optional(),skills:li.optional(),knowledge:Vs.optional(),memory:ci.optional(),sessions:hi.optional(),channels:a(fi).default([]),delivery:mi.optional(),schedules:a(nn).default([]),team:pi.optional(),subagents:a(gi).optional(),media:wi.optional(),standIn:yi.optional(),delegation:bi.optional(),plugins:a(vi).default([]),limits:Ti.prefault({}),server:Ei.prefault({})}).strict(),j=["main","selector","compactor"];function ki(e){return j.includes(e)}function ae(e){return Object.keys(e).filter((n)=>!ki(n))}var Si={nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096},Te={nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,maxOutput:5000},Ee={vision:!0,nativeTools:!0,strictSchema:!1,thinking:"anthropic",promptCache:"none",parallelToolCalls:!0},ke="Thinking blocks must be replayed with tool results or multi-step reasoning degrades silently. Prompt caching is unavailable on Anthropic's OpenAI-compatible endpoint; through OpenRouter the chat-completions transport sends cache_control itself (`sendsCacheControl`).",$d=[{pattern:"gpt-4o*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:128000,maxOutput:16384}},{pattern:"gpt-4.1*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:1e6,maxOutput:32768}},{pattern:"gpt-4-turbo*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:128000,maxOutput:4096}},{pattern:"gpt-3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:16385,maxOutput:4096}},{pattern:"gpt-6*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:1050000,maxOutput:128000},note:"Window and output are reported figures, unverified here. Run `model probe` or override if your endpoint says otherwise."},{pattern:"gpt-5*",capabilities:{vision:!0,nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:200000,maxOutput:32768},note:"Deliberately conservative on window and output. Override if your endpoint serves more."},{pattern:"o1*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o3*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o4*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},...["claude-fable-5*","claude-opus-5*","claude-opus-4-8*","claude-opus-4-7*","claude-opus-4-6*","claude-sonnet-5*","claude-sonnet-4-6*","claude-haiku-5*"].map((e)=>({pattern:e,capabilities:{...Ee,contextWindow:1e6,maxOutput:128000},note:ke})),{pattern:"claude-haiku-*",family:!0,capabilities:{...Ee,contextWindow:200000,maxOutput:64000},note:ke},{pattern:"claude-*",family:!0,capabilities:{...Ee,contextWindow:200000,maxOutput:8192},note:ke},{pattern:"nova-micro*",capabilities:{...Te,contextWindow:128000}},{pattern:"nova-lite*",capabilities:{...Te,contextWindow:300000,vision:!0}},{pattern:"nova-pro*",capabilities:{...Te,contextWindow:300000,vision:!0}},{pattern:"gemini*",family:!0,capabilities:{vision:!0,nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:1e6,maxOutput:8192}},{pattern:"glm-5.3*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:131072},note:"Reasoning is billed to the output budget, like the deepseek rows.",verified:"2026-10-21 via OpenRouter, provider z-ai/fp8"},{pattern:"qwen/qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:262144,maxOutput:8192},note:"Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-10-23 via OpenRouter, provider deepinfra/bf16 (published context_length 262,144)"},{pattern:"qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192},note:"Served locally by Ollama, which reports no token usage unless model.<role>.streamUsage is set — token figures come from the estimator until it is. Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-13 against qwen3.5:9b on localhost:11434/v1"},{pattern:"qwen*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"llama*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:128000,maxOutput:4096}},{pattern:"mistral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"mixtral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"deepseek-v4-pro*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Reasoning tokens are billed to the output budget. With max_tokens=16 this model returned empty content and finish_reason=length; context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-12 against api.deepseek.com/v1"},{pattern:"deepseek-v4-flash*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:393216},verified:"2026-08-12 against api.deepseek.com/v1 (reasoning confirmed). Measured 2026-08-25 by `model probe --window`: contextWindow 1048576 as a ceiling — the endpoint refused a 1048576-token prompt and named that number; maxOutput 393216 from a refusal naming the range [1, 393216]; automatic prompt caching confirmed at 1024 of 1115 prompt tokens with no breakpoints sent, which is why promptCache stays `none` (it describes the runtime's job, not the provider's behaviour)."},{pattern:"deepseek-v4*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Family fallback for v4 ids this registry has not seen. Assumes reasoning, because both measured v4 models emit it."},{pattern:"deepseek-reasoner*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"Not served by the account this registry was tested against. Numbers are from provider documentation and are deliberately low — override them if your endpoint serves this id."},{pattern:"deepseek-chat*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:65536,maxOutput:8192},note:"Unverified, from provider documentation."},{pattern:"deepseek-r1*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"The open-weight name for the reasoner, used by self-hosted and Ollama deployments."},{pattern:"deepseek*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192}},{pattern:"gemma*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096}},{pattern:"phi*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:16384,maxOutput:4096}},{pattern:"*",capabilities:Si}];var Ms={attempts:3,baseDelayMs:400,maxDelayMs:8000};var St=/^(?:timeout\s+\S+|time|nice(?:\s+-n\s+\S+)?|stdbuf(?:\s+-\S+)*|command|builtin)\s+/i;function $i(e){let n=e.trim();for(let s=0;s<4&&St.test(n);s+=1)n=n.replace(St,"").trim();return n}var Ni=/&&|\|\||;|\||&|\n/;function Ts(e){return e.split(Ni).map((n)=>$i(n)).filter((n)=>n!=="")}var Ci=/^(?:[-*+]|\d+[.)])[ \t]+\S/,Di=/\*\*(\d{4})-(\d{2})-\d{2}T/;function Ne(e){let n=[],s=-1,o=(d)=>{if(s===-1)return;n.push({start:s,end:d,text:e.slice(s,d).join(`
38
+ `).trimEnd()}),s=-1};for(let d=0;d<e.length;d+=1){let l=e[d]??"";if(Ci.test(l)){o(d),s=d;continue}if(s===-1)continue;if(l.trim()===""||/^[ \t]/.test(l))continue;o(d)}return o(e.length),n}function Ie(e){return at(Cs(Is(e)))}function Ui(e,n){let s=Di.exec(e);if(s!==null)return`${s[1]}-${s[2]}.md`;let o=n.getUTCFullYear(),d=`${n.getUTCMonth()+1}`.padStart(2,"0");return`${o}-${d}.md`}function Pi(e,n){let s=e.split(/\r?\n/),o=Ne(s),d=[],l=o,c=e,u=Ie(c);while(u>n&&l.length>1){let h=l[0];if(h===void 0)break;d.push(h),l=l.slice(1),c=Fi(s,d),u=Ie(c)}if(u<=n)return{evict:d,remaining:c,tokens:u};return{evict:d,remaining:c,tokens:u,shortfall:l.length<=1?`${u} tokens remain against a ${n}-token budget with one note left, so eviction cannot help`:`${u} tokens remain against a ${n}-token budget`}}function Fi(e,n){let s=new Set;for(let o of n)for(let d=o.start;d<o.end;d+=1)s.add(d);return e.filter((o,d)=>!s.has(d)).join(`
39
+ `).replace(/\n{3,}/g,`
40
+
41
+ `)}async function ji(e){let n=e.tags.length===0?"":` _(${e.tags.join(", ")})_`,s=`
42
+ - **${e.now.toISOString()}**${n} ${e.text}
43
+ `;return await sn(e.path,s,"utf8"),await rn(e)}async function rn(e){let n=await xi(e.path,"utf8"),s=Pi(n,e.budget);if(s.evict.length===0)return{file:e.name,evicted:0,archives:[],...s.shortfall===void 0?{}:{shortfall:s.shortfall}};let o=new Map;for(let d of s.evict){let l=Ui(d.text,e.now);o.set(l,[...o.get(l)??[],d.text])}await Ri(e.archiveDir,{recursive:!0});for(let[d,l]of o)await sn(Mi(e.archiveDir,d),`${l.join(`
44
+ `)}
45
+ `,"utf8");return await Li(e.path,s.remaining,"utf8"),{file:e.name,evicted:s.evict.length,archives:[...o.keys()].sort(),...s.shortfall===void 0?{}:{shortfall:s.shortfall}}}var ue="local",Rt="memory",xt="notes.md",Wi={spec:{slug:"now",provider:ue,summary:"Reports the current date and time.",whenToUse:"you need today's date or the current time — including to work out what 'tomorrow' or 'in three hours' means",whenNotToUse:"the person already told you the date or time; use theirs rather than replacing it with the clock",mutating:!1,tags:["read","time"],parameters:{type:"object",properties:{timezone:{type:"string",description:"IANA name such as Europe/London. Defaults to UTC."},format:{type:"string",description:"iso for a machine-readable timestamp, human for a readable one",enum:["iso","human"],default:"iso"}}}},handler(e,n){let s=n.now(),o=typeof e.timezone==="string"&&e.timezone!==""?e.timezone:"UTC";if(e.format==="human")return`${new Intl.DateTimeFormat("en-GB",{dateStyle:"full",timeStyle:"short",timeZone:o}).format(s)} (${o})`;if(o==="UTC")return s.toISOString();return`${Bi(s,o)} (${o})`}};function Bi(e,n){let s=new Intl.DateTimeFormat("en-CA",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"longOffset"}).formatToParts(e),o=(l)=>s.find((c)=>c.type===l)?.value??"",d=o("timeZoneName").replace("GMT","");return`${o("year")}-${o("month")}-${o("day")}T${o("hour")}:${o("minute")}:${o("second")}${d===""?"Z":d}`}var Hi={spec:{slug:"memory_write",provider:ue,summary:"Saves a short note for later recall.",whenToUse:"the person tells you something durable about themselves or their work that later conversations should know",whenNotToUse:"for anything already in this conversation, for secrets or credentials, or to store your own reasoning",mutating:!0,tags:["write","memory"],parameters:{type:"object",properties:{text:{type:"string",description:"The note, in one or two sentences."},tags:{type:"array",items:{type:"string"},description:"Optional labels."}},required:["text"]}},async handler(e,n){let s=typeof e.text==="string"?e.text.trim():"",o=Array.isArray(e.tags)?e.tags.map((h)=>String(h)):[],d=n.now().toISOString(),l=o.length===0?"":` _(${o.join(", ")})_`,c=`
46
+ - **${d}**${l} ${s}
47
+ `;if(n.writeNote!==void 0)return await n.writeNote(o.length===0?s:`${s} (${o.join(", ")})`);let u=await Xi(s,o,c,n);if(n.shareNote===void 0)return u;return`${u} ${await n.shareNote(o.length===0?s:`${s} (${o.join(", ")})`)}`}};async function Xi(e,n,s,o){let d=o.writeTarget;if(d?.mode==="refused")throw Xe(d.name,d.reason??"none");if(d?.path!==void 0){if(d.budget!==void 0&&o.memoryDir!==void 0&&d.eviction==="oldest"){let c=await ji({path:d.path,name:d.name,budget:d.budget,archiveDir:o.memoryDir,text:e,tags:n,now:o.now()});if(c.shortfall!==void 0)return`Saved to ${c.file}, but it is still over budget: ${c.shortfall}. Ask the person to raise the budget or shorten the file — the agent will not load until they do.`;if(c.evicted===0)return`Saved to ${c.file}.`;return`Saved to ${c.file}. Moved ${c.evicted} older ${c.evicted===1?"note":"notes"} into ${c.archives.join(", ")}, still searchable.`}if(await $t(d.path,s,"utf8"),d.budget!==void 0){let c=Ie(await Oi(d.path,"utf8"))-d.budget;if(c>0)return`Saved to ${d.name}, which is now ${c} tokens over its ${d.budget}-token budget. The agent will not load until that is fixed: add \`eviction: oldest\` to its frontmatter so older notes move to the memory directory, or raise the budget.`}return`Saved to ${d.name}.`}let l=It(o.dir,Rt);return await Ii(l,{recursive:!0}),await $t(It(l,xt),s,"utf8"),`Saved to ${Rt}/${xt}.`}var Ki=1200,Gi=Ki*3,qi={spec:{slug:"artifact_read",provider:ue,summary:"Reads back a tool result that compaction replaced with a pointer.",whenToUse:"a compaction marker in this conversation names an id, and you need the tool result it replaced",whenNotToUse:"for anything still written out in the conversation, or to explore — every id comes from a marker, so there is nothing to browse",mutating:!1,tags:["read","context"],parameters:{type:"object",properties:{id:{type:"string",description:"The id printed inside the compaction marker, copied character for character."},from:{type:"integer",description:"Character offset to continue from. Omit for the beginning; a truncated reply says the number to pass."}},required:["id"]}},async handler(e,n){let s=typeof e.id==="string"?e.id.trim():"",o=typeof e.from==="number"&&e.from>0?Math.floor(e.from):0;if(n.readArtifact===void 0)throw qe();let d=await n.readArtifact(s);if(d===void 0)throw ze(s);let l=d.slug===void 0?"observation":`${d.slug} observation`,c=d.content.slice(o,o+Gi),u=o+c.length,h=`Compacted ${l}, ${d.tokens} tokens${o===0?"":`, from character ${o}`}:`;if(u>=d.content.length)return`${h}
48
+ ${c}`;return`${h}
49
+ ${c}
50
+
51
+ [cut here — ${d.content.length-u} characters remain; continue with artifact_read(id, from: ${u})]`},trustOf:(e)=>ot(typeof e.id==="string"?e.id.trim():"")};var Yi=30,zi={spec:{slug:"memory_forget",provider:ue,summary:"Finds and deletes saved notes, and what was said in past conversations.",whenToUse:"the person asks you to forget something you noted. Call it with `query` first, show the person what matched, then call it with the `ids` they confirm",whenNotToUse:"to tidy notes nobody asked you to remove, or with `ids` you have not shown the person",mutating:!0,tags:["write","memory"],parameters:{type:"object",properties:{query:{type:"string",description:"Words every matching note or past message contains, case-insensitive. Lists matches; deletes nothing."},ids:{type:"array",items:{type:"string"},description:"Ids from a previous listing (notes and conversation messages). Deletes exactly these."}}}},async handler(e,n){let s=typeof e.query==="string"?e.query.trim():"",o=Array.isArray(e.ids)?e.ids.map((h)=>String(h).trim()).filter((h)=>h!==""):[];if(s===""===(o.length===0))throw Ke();if(n.forgetMemory===void 0)throw Ge();let d=(h)=>h==="space"?"the team's shared memory":"your notes";if(s!==""){let h=await n.forgetMemory({query:s});if(h.notes.length===0)return`No note in ${d(h.scope)} contains "${s}".`;let f=h.notes.slice(0,Yi),w=h.notes.length>f.length?`
52
+ ${h.notes.length-f.length} more match; use more words to narrow it down.`:"";return[`${h.notes.length} ${h.notes.length===1?"note":"notes"} in ${d(h.scope)} ${h.notes.length===1?"matches":"match"}. Nothing is deleted yet: show these to the person, then call memory_forget with the ids they confirm.`,...f.map((m)=>`- ${m.id} (${m.source}): ${m.text}`)].join(`
53
+ `)+w}let l=await n.forgetMemory({ids:o}),c=l.notes.length===0?`Nothing was deleted from ${d(l.scope)}.`:`Deleted ${l.notes.length} ${l.notes.length===1?"note":"notes"} from ${d(l.scope)}; they will not be recalled again.`,u=l.missing.length===0?"":` No note has ${l.missing.length===1?"the id":"the ids"} ${l.missing.join(", ")}: already gone, or not yours to delete here.`;return c+u}},Vi=[Wi,Hi,zi,qi],xd=Vi.map((e)=>e.spec.slug);class Wt extends ne{static ERROR_NAME="MediaError"}function Ae(e,n,s,o){let d=s.get(n.provider);if(d===void 0)throw new Q({code:"media_provider_unknown",message:`${e}.provider is "${n.provider}", and no media provider by that name is registered. Registered: ${[...s.keys()].sort().join(", ")}.`,hint:n.provider==="aws"?"Amazon Transcribe and Nova Canvas come from the media-aws plugin, which the CLI and the image include. An embedder calling the runtime directly passes it in `builtInPlugins`.":'Use "openai" for any endpoint speaking the OpenAI audio and image routes, or add the plugin that provides this one.',field:`${e}.provider`});let l=n.options;if(d.optionsSchema!==void 0&&n.options!==void 0){let f=d.optionsSchema.safeParse(n.options);if(!f.success)throw new Q({code:"media_provider_options_invalid",message:`${e}.options are not valid for the ${n.provider} provider: ${f.error.issues?.[0]?.message??"invalid"}.`,hint:`See the ${n.provider} media provider's documentation for the fields it takes.`,field:`${e}.options`});l=f.data}let c=d.create({field:e,config:n,options:l,env:o.env,...o.fetch===void 0?{}:{fetch:o.fetch}}),[u,h]=e==="media.transcription"?[c.transcribe,"transcribe audio"]:e==="media.speech"?[c.synthesize,"speak text"]:[c.generateImage,"generate images"];if(u===void 0)throw new Q({code:"media_provider_incapable",message:`The ${n.provider} media provider does not ${h}.`,hint:"Name a provider that does in this section; the two sections may name different providers.",field:`${e}.provider`});return c}var tr={"audio/ogg":"ogg","audio/opus":"ogg","audio/mpeg":"mp3","audio/mp4":"m4a","audio/x-m4a":"m4a","audio/aac":"m4a","audio/wav":"wav","audio/x-wav":"wav","audio/webm":"webm","audio/flac":"flac"};function nr(e){return tr[e.split(";")[0]?.trim().toLowerCase()??""]??"ogg"}async function te(e,n,s){let o=(await e.text().catch(()=>"")).slice(0,300);return new Wt({code:"media_provider_refused",message:`${n} was refused (${e.status}): ${o}`,hint:e.status===401||e.status===403?`Check the key in the env var ${s}.apiKeyEnv names, and that it may use this model.`:"The provider's own words are above.",field:s})}var sr={create(e){let{config:n,field:s}=e,o=go(n.baseUrl??"https://api.openai.com/v1"),d=n.apiKeyEnv??"OPENAI_API_KEY",l=e.env[d];if(l===void 0||l==="")throw new Q({code:"media_key_missing",message:`${s} needs ${d}, which is not set.`,hint:`Put the endpoint's key in ${d}, in the environment or the .env beside the manifest, or name another variable with ${s}.apiKeyEnv.`,field:`${s}.apiKeyEnv`});let c=e.fetch??((h,f)=>fetch(h,f)),u=`Bearer ${l}`;return{async transcribe(h,f){let w=new FormData;w.set("file",new Blob([h.bytes],{type:h.mimeType}),`voice.${nr(h.mimeType)}`),w.set("model",n.model??"whisper-1");let m=await c(`${o}/audio/transcriptions`,{method:"POST",headers:{authorization:u},body:w,signal:f});if(!m.ok)throw await te(m,"The transcription",s);let g=await m.json();return{text:typeof g.text==="string"?g.text:"",...typeof g.duration==="number"?{durationS:g.duration}:{}}},async synthesize(h,f){let w=n.options??{},m=await c(`${o}/audio/speech`,{method:"POST",headers:{authorization:u,"content-type":"application/json"},body:JSON.stringify({model:n.model??"gpt-4o-mini-tts",voice:typeof w.voice==="string"?w.voice:"alloy",input:h.text,response_format:"opus"}),signal:f});if(!m.ok)throw await te(m,"The speech request",s);return{bytes:new Uint8Array(await m.arrayBuffer()),mimeType:"audio/ogg; codecs=opus",characters:h.text.length}},async generateImage(h,f){let w=await c(`${o}/images/generations`,{method:"POST",headers:{authorization:u,"content-type":"application/json"},body:JSON.stringify({model:n.model??"gpt-image-1",prompt:h.prompt,size:h.size,n:1}),signal:f});if(!w.ok)throw await te(w,"The image request",s);let g=(await w.json()).data?.[0];if(g?.b64_json!==void 0)return{bytes:Buffer.from(g.b64_json,"base64"),mimeType:"image/png"};if(g?.url!==void 0){let y=await c(g.url,{signal:f});if(!y.ok)throw await te(y,"Downloading the image",s);return{bytes:new Uint8Array(await y.arrayBuffer()),mimeType:y.headers.get("content-type")??"image/png"}}throw new Wt({code:"media_provider_empty",message:"The image endpoint answered with no image.",hint:"Some endpoints return an empty list for a refused prompt. Rephrasing it is usually what works.",field:s})}}}},ir=new Map([["openai",sr]]);function rr(e,n){let s=new Map([...ir,...n.providers??[]]),o=e.media?.transcription,d=e.media?.image,l=e.media?.speech;return{...l===void 0?{}:{speech:{config:l,provider:Ae("media.speech",l,s,n)}},...o===void 0?{}:{transcription:{config:o,provider:Ae("media.transcription",o,s,n)}},...d===void 0?{}:{image:{config:d,provider:Ae("media.image",d,s,n)}}}}function on(e){let n=e.providers??{},s=Object.keys(n),o=e.provider,d=e.providerConfig??{};if(s.length>0&&(o!==void 0||Object.keys(d).length>0))throw Be(s,o);if(o!==void 0)return{selections:[{id:o,config:d,legacy:!0}],warnings:[{code:"tools_provider_deprecated",message:`tools.provider is deprecated; "${o}" was loaded as tools.providers.${o}.`,hint:`Rewrite it as:
54
+ tools:
55
+ providers:
56
+ ${o}: { … the contents of providerConfig … }
57
+ The scalar permits exactly one provider, which is why an agent could not have the shell and the web at the same time. It still works and will keep working for now; nothing about the resolved catalogue changes.`,field:"tools.provider"}]};let l=s.map((c)=>({id:c,config:n[c]??{},legacy:!1}));if(Object.keys(d).length>0)return{selections:l,warnings:[{code:"tools_provider_config_orphaned",message:`tools.providerConfig has ${Object.keys(d).length} setting(s) and no tools.provider names a provider to apply them to, so they do nothing.`,hint:"Move them into the matching tools.providers.<id> block and delete tools.providerConfig. Reported rather than ignored: a configuration that looks applied and is not is worse than one that fails.",field:"tools.providerConfig"}]};return{selections:l,warnings:[]}}var Lt=new Map;function an(e){let n=Lt.get(e);if(n!==void 0)return n;let s;try{s=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch(o){throw new Q({code:"schedule_timezone_unknown",message:`"${e}" is not a timezone this runtime recognises.`,hint:"Use an IANA name such as Asia/Dhaka, Europe/London or America/Sao_Paulo — not an abbreviation like BST and not a UTC offset. Omit the field to use the TZ environment variable, then UTC.",field:"timezone",cause:o})}return Lt.set(e,s),s}function or(e){an(e)}function le(e,n){let s=an(e).formatToParts(new Date(n)),o=(u)=>{let h=s.find((f)=>f.type===u);return h===void 0?0:Number(h.value)},d=o("year"),l=o("month"),c=o("day");return{year:d,month:l,day:c,hour:o("hour"),minute:o("minute"),second:o("second"),weekday:new Date(Date.UTC(d,l-1,c)).getUTCDay()}}function ar(e,n){return le(e,n)}function Mt(e,n){let s=le(e,n);return Date.UTC(s.year,s.month-1,s.day,s.hour,s.minute,s.second)-(n-n%1000)}function lr(e,n){let s=Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second),o=s-Mt(e,s);o=s-Mt(e,o);let d=le(e,o);if(!(d.year===n.year&&d.month===n.month&&d.day===n.day&&d.hour===n.hour&&d.minute===n.minute&&d.second===n.second))return;let c=o-3600000,u=le(e,c);return u.year===n.year&&u.month===n.month&&u.day===n.day&&u.hour===n.hour&&u.minute===n.minute&&u.second===n.second?c:o}function cr(){return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}var gr=1462,dn=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],wr=["sun","mon","tue","wed","thu","fri","sat"],U={second:{min:0,max:59,label:"second"},minute:{min:0,max:59,label:"minute"},hour:{min:0,max:23,label:"hour"},dayOfMonth:{min:1,max:31,label:"day of month"},month:{min:1,max:12,names:dn,label:"month"},dayOfWeek:{min:0,max:7,names:wr,label:"day of week"}};function L(e,n,s,o){throw new Q({code:"schedule_cron_malformed",message:`"${e}" is not a valid cron expression: ${n}`,hint:s,field:o})}function Se(e,n,s,o){let d=n.names?.indexOf(e.toLowerCase());if(d!==void 0&&d!==-1)return d+(n.names===dn?1:0);if(!/^\d+$/.test(e))L(s,`"${e}" is not a ${n.label}.`,n.names===void 0?`The ${n.label} field takes numbers ${n.min}-${n.max}, ranges, steps and comma lists.`:`The ${n.label} field takes ${n.min}-${n.max} or a name (${n.names.slice(0,3).join(", ")}…).`,o);let l=Number(e);if(l<n.min||l>n.max)L(s,`${l} is outside the ${n.label} range ${n.min}-${n.max}.`,`Check the field order: ${n.label==="second"?"second minute hour day-of-month month day-of-week":"minute hour day-of-month month day-of-week"}.`,o);return l}function P(e,n,s,o){let d=new Set,l=!0;for(let c of e.split(",")){let u=c.trim();if(u==="")L(s,"an empty entry in a comma list.","Remove the stray comma.",o);let[h="",f]=u.split("/",2),w=f===void 0?1:Number(f);if(f!==void 0&&(!/^\d+$/.test(f)||w<1))L(s,`"${f}" is not a step.`,"A step is a whole number above zero, as in */15.",o);let m,g;if(h==="*"){if(m=n.min,g=n.max,w===1)l=!1}else if(h.includes("-")){let[y="",v=""]=h.split("-",2);if(m=Se(y,n,s,o),g=Se(v,n,s,o),m>g)L(s,`the range ${h} runs backwards.`,"Write the lower bound first, or use a comma list to wrap around.",o)}else m=Se(h,n,s,o),g=f===void 0?m:n.max;for(let y=m;y<=g;y+=w)d.add(y)}if(d.size===0)L(s,"it matches nothing.","Every field must admit at least one value.",o);return{values:d,restricted:l}}function br(e,n){let s=e.trim();if(s.startsWith("@"))L(s,"macros are not supported.",'Write the fields out — @daily is "0 0 * * *", @hourly is "0 * * * *", @weekly is "0 0 * * 0". For a plain interval use kind: every with an expression like 24h.',n);let o=s.split(/\s+/).filter((O)=>O!=="");if(o.length!==5&&o.length!==6)L(s,`it has ${o.length} field${o.length===1?"":"s"}, not 5 or 6.`,"Five fields are minute hour day-of-month month day-of-week. A sixth leading field is seconds.",n);let d=o.length===6,[l,c,u,h,f,w]=d?o:["0",...o],m=P(l??"0",U.second,s,n),g=P(c??"",U.minute,s,n),y=P(u??"",U.hour,s,n),v=P(h??"",U.dayOfMonth,s,n),T=P(f??"",U.month,s,n),E=P(w??"",U.dayOfWeek,s,n),N=new Set;for(let O of E.values)N.add(O===7?0:O);return{seconds:m.values,minutes:g.values,hours:y.values,daysOfMonth:v.values,months:T.values,daysOfWeek:N,domRestricted:v.restricted,dowRestricted:E.restricted,source:s}}function vr(e,n,s){let o=e.daysOfMonth.has(n),d=e.daysOfWeek.has(s);if(e.domRestricted&&e.dowRestricted)return o||d;if(e.domRestricted)return o;if(e.dowRestricted)return d;return!0}function Ct(e,n,s,o){let d=new Date(Date.UTC(e,n-1,s+o));return[d.getUTCFullYear(),d.getUTCMonth()+1,d.getUTCDate()]}function _r(e,n,s){return new Date(Date.UTC(e,n-1,s)).getUTCDay()}function GA(e,n,s){let o=ar(s,n+1000),d=new Date(Date.UTC(o.year,o.month-1,o.day+gr)),[l,c,u]=[o.year,o.month,o.day],h=!0;while(Date.UTC(l,c-1,u)<=d.getTime()){if(!e.months.has(c)){[l,c,u]=c===12?[l+1,1,1]:[l,c+1,1],h=!1;continue}if(!vr(e,u,_r(l,c,u))){[l,c,u]=Ct(l,c,u,1),h=!1;continue}for(let f of[...e.hours].sort((w,m)=>w-m)){if(h&&f<o.hour)continue;for(let w of[...e.minutes].sort((m,g)=>m-g)){if(h&&f===o.hour&&w<o.minute)continue;for(let m of[...e.seconds].sort((g,y)=>g-y)){if(h&&f===o.hour&&w===o.minute&&m<o.second)continue;let g=lr(s,{year:l,month:c,day:u,hour:f,minute:w,second:m});if(g!==void 0)return g}}}[l,c,u]=Ct(l,c,u,1),h=!1}return}var Tr=/^(\d+)(s|m|h|d)$/,kr={s:1000,m:60000,h:3600000,d:86400000},Ar=1000,Sr=315360000000;function Nr(e,n){let s=Tr.exec(e.trim());if(s===null)throw new Q({code:"schedule_duration_malformed",message:`"${e}" is not a duration.`,hint:"A duration is a whole number and one unit: 90s, 15m, 2h, 7d. There is no combined form — write 90m rather than 1h30m.",field:n});let o=Number(s[1]),d=s[2]??"",l=o*(kr[d]??0);if(l<Ar)throw new Q({code:"schedule_duration_too_small",message:`"${e}" is under the one-second minimum.`,hint:"An interval below a second is a busy loop rather than a schedule. If the intent is to run continuously, a schedule is the wrong mechanism.",field:n});if(l>Sr)throw new Q({code:"schedule_duration_too_large",message:`"${e}" is over the ten-year maximum.`,hint:"An interval this long is almost always a unit typo — check whether d was meant where h was written.",field:n});return{ms:l,source:e.trim()}}var Ir=315360000000,Or=900000,$e=1000;function Qr(e){let n=e.timezone??cr();or(n);let s=e.expr.trim();if(e.kind==="cron"){let d=br(s,e.field);if(GA(d,e.now,n)===void 0)throw new Q({code:"schedule_cron_unsatisfiable",message:`"${s}" never matches a real date.`,hint:"The expression parses but names a day that does not occur — 30 February, or a weekday-and-date pair that never coincide. Checked over four years, so a leap-year schedule like 0 3 29 2 * is accepted.",field:e.field});return{kind:"cron",spec:d,zone:n,source:s}}if(e.kind==="every")return{kind:"every",every:Nr(s,e.field),zone:n,source:s};let o=Date.parse(s);if(Number.isNaN(o))throw new Q({code:"schedule_at_malformed",message:`"${s}" is not an ISO 8601 instant.`,hint:"Write a full timestamp with an offset, as in 2026-12-25T09:00:00+06:00 or 2026-12-25T03:00:00Z. A bare date has no time of day.",field:e.field});if(o>e.now+Ir)throw new Q({code:"schedule_at_too_far",message:`${s} is more than ten years away.`,hint:"A one-shot this far out is almost always a year typo. Ten years is the documented bound.",field:e.field});return{kind:"at",at:o,zone:n,source:s}}function Rr(e){let n=2166136261;for(let s=0;s<e.length;s+=1)n^=e.charCodeAt(s),n=Math.imul(n,16777619)>>>0;return n}function Xr(e,n){if(n===void 0||n<=0)return 0;let s=Math.min(Math.floor(n/10),Or);return s<=0?0:Rr(e)%s}function xr(e,n){if(e.kind==="every")return e.every.ms;if(e.kind==="at")return;let s=GA(e.spec,n,e.zone);if(s===void 0)return;let o=GA(e.spec,s,e.zone);return o===void 0?void 0:o-s}function Lr(e,n,s,o,d={}){if(e.kind==="at"){if(d.consumed===!0)return{runAt:void 0,anchor:void 0,missed:0,missedCapped:!1,late:!1};if(e.at<=o)return{runAt:o,anchor:e.at,missed:0,missedCapped:!1,late:!0};return{runAt:e.at,anchor:e.at,missed:0,missedCapped:!1,late:!1}}let l=Xr(n,xr(e,s));if(e.kind==="every"){let f=o-s,w=f<=0?0:Math.floor(f/e.every.ms),m=Math.min(w,$e),g=w+1,y=s+g*e.every.ms;return{runAt:y+l,anchor:y,missed:m,missedCapped:w>$e,late:!1}}let c=s,u=0,h=!1;for(;;){let f=GA(e.spec,c,e.zone);if(f===void 0)return{runAt:void 0,anchor:void 0,missed:u,missedCapped:h,late:!1};if(f+l>o)return{runAt:f+l,anchor:f,missed:u,missedCapped:h,late:!1};if(c=f,u+=1,u>=$e){h=!0;let w=GA(e.spec,o,e.zone);return{runAt:w===void 0?void 0:w+l,anchor:w,missed:u,missedCapped:!0,late:!1}}}}function Mr(e,n,s){let o=[],d=Array.isArray(e.schedules)?e.schedules:[],l=new Set((Array.isArray(e.channels)?e.channels:[]).map((f)=>f!==null&&typeof f==="object"&&!Array.isArray(f)?f.id:void 0).filter((f)=>typeof f==="string")),c=new Set([...j,...ae(n.model)]),u=new Set,h=new Set;for(let[f,w]of d.entries()){if(w===null||typeof w!=="object"||Array.isArray(w))continue;let m=w,g=typeof m.id==="string"?m.id:`[${f}]`;if(h.has(g))o.push({code:"schedule_id_duplicate",message:`Two schedules share the id "${g}".`,hint:"A schedule id is the key reconciliation matches on and the segment of its session key, so it must be unique within an agent.",field:`schedules[${f}].id`});h.add(g);let y=m.deliver;if(y===void 0)o.push({code:"schedule_missing_delivery",message:`Schedule "${g}" has no delivery target.`,hint:'Set deliver to { channel, to }, or the literal "none" to return results only via the event stream.',field:`schedules[${f}].deliver`});else if(y!=="none"&&typeof y==="object"&&!Array.isArray(y)){let E=y.channel;if(typeof E==="string"&&!l.has(E))o.push({code:"schedule_delivery_channel_unknown",message:`Schedule "${g}" delivers to "${E}", which is not a channel id on this agent.${l.size===0?" The agent declares no channels.":` Declared: ${[...l].join(", ")}.`}`,hint:`A delivery target names a channel's id, not its type. Use deliver: "none" to return results through the event stream instead.`,field:`schedules[${f}].deliver.channel`})}let v=m.role;if(typeof v==="string"){if(u.add(v),!c.has(v))o.push({code:"schedule_role_unknown",message:`Schedule "${g}" names the model role "${v}", which is not declared under model:. Declared: ${[...c].join(", ")}.`,hint:"Add the role under model:, or point the schedule at one of the declared roles. Omit role entirely to use main.",field:`schedules[${f}].role`})}let T=n.schedules[f];if(T!==void 0)try{Qr({id:T.id,kind:T.kind,expr:T.expr,timezone:T.timezone,now:s,field:`schedules[${f}].expr`})}catch(E){if(!(E instanceof ne))throw E;o.push(E.toDetail())}}for(let f of n.subagents??[])u.add(f.model??"subagent");for(let f of ae(n.model)){if(u.has(f))continue;if(jt(f,j)===void 0)continue;o.push({code:"model_role_unreferenced",message:`model.${f} is declared but no schedule names it, so nothing will ever use it.`,hint:`If "${f}" was meant to be one of ${j.join(", ")}, it is misspelled — and the misspelled one is silently falling back to main. Otherwise point a schedule at it with role: ${f}, or remove it.`,field:`model.${f}`})}return o}function Dr(e){let n=[],s=new Set([...e.tools.pinned,...e.tools.local]),o=new Set([...j,...ae(e.model)]),d=new Set,l=new Map;for(let[c,u]of(e.subagents??[]).entries()){let h=`subagents[${c}]`;if(d.has(u.name))n.push({code:"subagent_name_duplicate",message:`Two subagents are called "${u.name}".`,hint:"Give each subagent its own name: it is how events, sessions and usage rows say which child ran.",field:`${h}.name`});d.add(u.name);let f=u.tools.filter((w)=>!s.has(w));if(f.length>0)n.push({code:"subagent_tool_not_pinned",message:`Subagent "${u.name}" lists ${f.join(", ")}, which this agent does not pin.`,hint:"A subagent may only use tools its parent has, so it can never act with more authority than the parent. Add the slug to tools.pinned (or tools.local), or remove it from the subagent.",field:`${h}.tools`});if(u.route===void 0&&!u.spawn)n.push({code:"subagent_unreachable",message:`Subagent "${u.name}" declares neither route nor spawn, so nothing can start it.`,hint:"Add route: {tools: [<slug>]} to run it for those calls, or spawn: true to let the model start it with delegate.",field:h});for(let w of u.route?.tools??[]){if(!u.tools.includes(w))n.push({code:"subagent_route_outside_tools",message:`Subagent "${u.name}" routes ${w} but does not list it under tools, so it could not make the call it is handed.`,hint:`Add ${w} to subagents[${c}].tools.`,field:`${h}.route.tools`});let m=l.get(w);if(m!==void 0&&m!==u.name)n.push({code:"subagent_route_duplicate",message:`${w} is routed to both "${m}" and "${u.name}".`,hint:"A routed call runs exactly one child. Route the slug from one subagent only.",field:`${h}.route.tools`});l.set(w,u.name)}if(u.model!==void 0&&!o.has(u.model))n.push({code:"subagent_role_unknown",message:`Subagent "${u.name}" names the model role "${u.model}", which is not declared under model:. Declared: ${[...o].join(", ")}.`,hint:"Add the role under model:, or remove model: from the subagent to use model.subagent (or main).",field:`${h}.model`})}return n}function Ur(e){let n=new Set([...j,...ae(e.model)]);return(e.channels??[]).flatMap((s,o)=>s.role===void 0||n.has(s.role)?[]:[{code:"channel_role_unknown",message:`Channel "${s.id}" names the model role "${s.role}", which is not declared under model:. Declared: ${[...n].join(", ")}.`,hint:"Add the role under model:, or point the channel at one of the declared roles. Omit role to run its turns on main.",field:`channels[${o}].role`}])}function ln(e){if(typeof e!=="string")return String(e);let n=/^[A-Za-z0-9_./@~-]+$/.test(e),s=/^[A-Za-z0-9_./]/.test(e);if(!n||!s)return JSON.stringify(e);try{return ce(e)===e?e:JSON.stringify(e)}catch{return JSON.stringify(e)}}function Y(e){return e.length-e.trimStart().length}function Le(e){let n=e.trim();return n===""||n.startsWith("#")}function Me(e,n,s,o){let d=new RegExp(`^\\s{${s}}${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*:`);for(let l=o;l<e.length;l+=1){let c=e[l]??"";if(Le(c))continue;if(Y(c)<s)return;if(Y(c)===s&&d.test(c))return l}return}function se(e,n,s){let o=n;for(let d=n+1;d<e.length;d+=1){let l=e[d]??"";if(Le(l))continue;if(Y(l)<=s)break;o=d}return o}function Pr(e){let n;for(let s=0;s<e.length;s+=1){let o=e[s];if(n!==void 0){if(o===n)n=void 0;continue}if(o==='"'||o==="'"){n=o;continue}if(o!=="#"||s===0||!/\s/.test(e[s-1]??""))continue;let d=s;while(d>0&&/\s/.test(e[d-1]??""))d-=1;return e.slice(d)}return""}function Ce(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function W(e,n,s){let o=" ".repeat(s);if(Array.isArray(n)){if(n.length===0)return[`${o}${e}: []`];return[`${o}${e}:`,...n.flatMap((d)=>Fr(d,s+2))]}if(Ce(n)){let d=Object.entries(n);if(d.length===0)return[`${o}${e}: {}`];return[`${o}${e}:`,...d.flatMap(([l,c])=>W(l,c,s+2))]}return[`${o}${e}: ${ln(n)}`]}function Fr(e,n){let s=" ".repeat(n);if(!Ce(e))return[`${s}- ${ln(e)}`];let o=Object.entries(e);if(o.length===0)return[`${s}- {}`];let d=o.flatMap(([u,h])=>W(u,h,n+2)),[l,...c]=d;return[`${s}- ${(l??"").trimStart()}`,...c]}function cn(e,n){let s=0,o=0,d,l=0;for(;l<n.length-1;l+=1){let c=Me(e,n[l]??"",o,s);if(c===void 0)break;d=c,s=c+1;let u=e.slice(c+1).find((h)=>!Le(h)&&Y(h)>o);if(u===void 0)return;o=Y(u)}return{searchFrom:s,indent:o,parent:d,depth:l}}function un(e,n){if(n.length===0)return;let s=e.split(`
58
+ `),o=cn(s,n);if(o===void 0)return;if(o.depth<n.length-1)return e;let d=Me(s,n[n.length-1]??"",o.indent,o.searchFrom);if(d===void 0)return e;let l=se(s,d,o.indent),c=[...s.slice(0,d),...s.slice(l+1)].join(`
59
+ `),u=n.slice(0,-1);if(u.length>0&&X(c).getIn([...u])==null)return un(c,u)??c;return c}function jr(e,n,s){if(n.length===0)return;let o=e.split(`
60
+ `),d=cn(o,n);if(d===void 0)return;let{searchFrom:l,indent:c,parent:u,depth:h}=d;if(h<n.length-1){if(u===void 0)return;let g=se(o,u,c-1)+1;return[...o.slice(0,g),...hn(n.slice(h),s,c),...o.slice(g)].join(`
61
+ `)}let f=n[n.length-1]??"",w=Me(o,f,c,l);if(w!==void 0){let g=o[w]??"",y=Array.isArray(s)||Ce(s)?"":Pr(g),v=se(o,w,c),T=W(f,s,c);if(y!=="")T[0]=`${T[0]}${y}`;return[...o.slice(0,w),...T,...o.slice(v+1)].join(`
62
+ `)}if(u===void 0)return;let m=se(o,u,c-1)+1;return[...o.slice(0,m),...W(f,s,c),...o.slice(m)].join(`
63
+ `)}function hn(e,n,s){let[o,...d]=e;if(o===void 0)return[];if(d.length===0)return W(o,n,s);return[`${" ".repeat(s)}${o}:`,...hn(d,n,s+Hr)]}var Hr=2;function Kr(e,n,s){let o=e.split(`
64
+ `),d=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`^#\\s*${d}\\s*:`),c=o.findIndex((f)=>l.test(f));if(c===-1)return;let u=c;while(/^#\s{2,}\S/.test(o[u+1]??""))u+=1;let h=/^#\s*Phase \d/.test(o[c-1]??"")?c-1:c;return[...o.slice(0,h),...W(n,s,0),...o.slice(u+1)].join(`
65
+ `)}function Gr(e,n){let s=[...n.path],o=s.join("."),d=De(X(e),s),l=n.remove===!0?un(e,s):jr(e,s,n.value)??n.fallback?.(e)??(s.length===1?Kr(e,s[0]??"",n.value):void 0),c;if(l===void 0){let m=X(e);if(n.remove===!0)m.deleteIn(s);else m.setIn(s,n.value);c=String(m)}else c=l;let u=X(c);if(u.errors.length>0)throw F(o,`the result is not valid YAML — ${u.errors[0]?.message??"unparseable"}`);let h=$r.safeParse(u.toJS());if(!h.success){let m=h.error.issues[0];throw F(o,`${m?.path.join(".")??o}: ${m?.message??"does not fit the schema"}`)}let w=Mr(u.toJS(),h.data,Date.now())[0]??Ur(h.data)[0]??Dr(h.data)[0];if(w!==void 0)throw F(o,`${w.message} ${w.hint}`);try{on(h.data.tools)}catch(m){throw F(o,m instanceof Error?m.message:"the providers block does not resolve")}return{next:c,before:d,reflowed:l===void 0,manifest:h.data}}async function Rs(e){let{edits:n}=await ei(e.file,[e]);return n[0]}async function ei(e,n){let s;try{s=await Ji(e,"utf8")}catch(l){throw Yr(e,l)}let o=qr(s,e,n),d=o.next!==s;if(d)await Zi(e,o.next,"utf8");return{edits:o.edits,written:d}}function qr(e,n,s){let o=e,d=[];for(let l of s){let c={...l,file:n},u=Gr(o,c),h=!er(u.before,De(X(u.next),c.path));if(h)Jr(c,u.manifest),eo(c,u.manifest),o=u.next;d.push({before:u.before,after:c.remove===!0?void 0:c.value,reflowed:h&&u.reflowed,manifest:u.manifest,changed:h})}return{next:o,edits:d}}function co(e){let n=e.trim();if(n==="")return"";let s=X(n);if(s.errors.length>0)throw new ne({code:"manifest_value_unreadable",message:`Cannot read ${JSON.stringify(e)} as a value.`,hint:'A bare word, a number, true or false, a list as ["a", "b"], or a map as {k: v}. Quote anything containing a colon or a "#".'});return s.toJS()}function ti(e,n){return De(X(e),n)}function _s(e){return X(e).toJS()}function De(e,n){let s=e.getIn([...n],!1);if(s===void 0||s===null)return;return Ot(s)||Nt(s)?s.toJS(e):s}function Yr(e,n){return new ne({code:"manifest_edit_unreadable",message:`Cannot read the manifest at ${e} to change it.`,hint:"Check the path and file permissions. Nothing was written.",cause:n})}function Jr(e,n){let s=e.providers;if(s===void 0||!e.path.join(".").startsWith("tools.provider"))return;for(let o of on(n.tools).selections){let d=s[o.id];if(d===void 0)throw F(e.path.join("."),`no tool provider called "${o.id}" is available here. Available: ${Object.keys(s).join(", ")||"(none)"}.`);let l;try{l=d({dir:Qi(e.file),env:{},config:o.config,agentId:n.id})}catch(c){if(_(c))throw c;throw F(e.path.join("."),`the ${o.id} provider refused its config: ${c instanceof Error?c.message:String(c)}`)}l.stop?.()}}function eo(e,n){if(e.mediaProviders===void 0||e.path[0]!=="media")return;for(let s of["transcription","image","speech"]){let o=n.media?.[s];if(o===void 0)continue;try{rr({...n,media:{[s]:o}},{env:{},providers:new Map(Object.entries(e.mediaProviders))})}catch(d){if(_(d)&&d.code==="media_key_missing")continue;throw d}}}function F(e,n){return new ne({code:"manifest_edit_invalid",message:`Setting ${e} would make the manifest invalid: ${n}`,hint:"Nothing was written. Check the value's shape — a list is [a, b], a map is {k: v} — against the field this path names."})}var aA=[{path:"tools.local",means:"built-in tools: now, memory_write, memory_forget, artifact_read",agentListed:!0},{path:"tools.providers",means:"where tools come from, as a map — {system: {}} for shell and files, {web: {backend: tavily, apiKeyEnv: TAVILY_API_KEY}} for the internet. Several at once",toAgent:"A writeRoots key inside is refused",agentListed:!0},{path:"tools.pinned",means:"the tools from those providers this agent may call",agentListed:!0},{path:"tools.policy.allow",means:'rules permitting a call: "exec", or narrower like "exec(git *)". Also what lets a mutating tool run in a turn that has read untrusted content',agentListed:!0},{path:"tools.policy.deny",means:"rules refusing a call. Beats any allow rule",toAgent:"Replacing these is refused: it is the one edit whose only purpose is to remove a restriction someone set",agentListed:!0,confirm:"Deny rules are the restrictions that beat every allow rule. Replacing them removes whatever was deliberately put out of reach."},{path:"tools.policy.mode",means:"allow | ask | deny — for calls no rule mentions",agentListed:!0},{path:"tools.untrusted.onMutate",means:"refuse | confirm | allow — what happens when a tool that changes something is asked for in a turn that has read outside content",toAgent:'Cannot be set to "allow"',agentListed:!0,confirm:'Setting this to "allow" turns off the check that stops text from outside the conversation driving a tool that changes things. A fetched page that says "now delete the backups" would be acted on.'},{path:"tools.dialect",means:"nlt | native — how tool calls are written",agentListed:!0},{path:"description",means:"what this agent is for, in one line of at most 200 characters. The person's other agents see it beside this one in ask_agent",agentListed:!0},{path:"model.main.id",means:"the model this agent runs on",agentListed:!0},{path:"model.main.temperature",means:"0 to 2",agentListed:!0},{path:"model.main.maxTokens",means:"the most one reply may generate; unset lets the endpoint decide",agentListed:!1},{path:"tools.budget.max",means:"how many tools the model is shown at once, built-ins included",agentListed:!1},{path:"model.main.reasoningEffort",means:"none | minimal | low | medium | high | xhigh | max — how hard a reasoning model thinks",agentListed:!1},{path:"model.main",means:"the main model as a whole role, {api, id, baseUrl or options, apiKeyEnv, capabilities, ...}; replaces it in one write",agentListed:!1},{path:"model.<role>",means:"a named model role, {id, api or baseUrl, apiKeyEnv, ...}; a schedule or message runs on it with role: <name>",agentListed:!1},{path:"limits.maxSteps",means:"tool calls allowed in one turn",agentListed:!0},{path:"limits.toolTimeoutMs",means:"how long any single tool may take",agentListed:!0},...["static","volatile","reminder","total"].map((e)=>({path:`context.budgets.${e}`,means:`token budget for the ${e==="total"?"whole workspace":`${e} tier`}; a file over it stops the agent loading`,agentListed:!1})),{path:"limits.noProgress",means:"when a turn is stopped for going nowhere, as a map: {identicalCalls: <n, default 3>, sameTool: <n, off when absent>}",agentListed:!1},{path:"limits.noProgress.sameTool",means:"stop a turn after this many calls in a row to one tool, whatever the arguments. Absent, off",agentListed:!1},{path:"context.modelIdentity",means:"shown or hidden: whether the agent can see which model it runs on (hidden keeps tuning settable)",agentListed:!1},{path:"context.window",means:"the token budget for a whole request; unset uses the model's known window",agentListed:!1},{path:"context.observationMaxTokens",means:"how much of a tool's output reaches the model",agentListed:!0},{path:"tools.eventDetail",means:"none | redacted — whether tool events carry the call's arguments and output",agentListed:!1},{path:"context.rules.onExceed",means:"fail | warn — whether too many counted rules in the workspace refuses the load",agentListed:!1},{path:"channels",means:"how people reach this agent, as a list — [{type: telegram, id: tg, tokenEnv: TELEGRAM_BOT_TOKEN, mode: longpoll}]. The token goes in the .env",toAgent:"The token itself goes in the .env, which only a person can write. allowFrom is refused here: who may talk to you is not yours to decide",agentListed:!0},{path:"delivery",means:"where a reply goes when a turn has no origin — {default: tg}. Names a channel id, not a channel type",agentListed:!0},{path:"delivery.reply",means:"channel replies: all (every step's text, default) or final (the last step's only)",agentListed:!0},{path:"schedules",means:'what runs unattended, as a list — [{id, kind: cron|every|at, expr, task, deliver}]. expr is a 5- or 6-field cron, a duration like 15m, or an ISO instant; deliver is {channel, to} or the literal "none"',toAgent:"Only `serve` fires these; under `run` they are validated and listed and no timer starts. deliver.to is the address a reply is *sent* to — on Telegram the numeric chat id, never an @handle, which addresses a channel and not a person. It is the id inbound messages arrive on, so read it off your own session keys (tg:<id>); allowFrom holds handles and confers nothing here. Set role to name a model other than main. The whole list is replaced, so read it first",agentListed:!0},{path:"media",means:"voice notes, spoken replies and images: {transcription, speech, image}, each {provider: openai|aws, model, apiKeyEnv, options}",toAgent:"image adds image_generate after a restart; filling in the key variable is the person's",agentListed:!0},{path:"server.enabled",means:"true | false — serve the HTTP API on 127.0.0.1",toAgent:"host and tokenEnv are refused: binding anywhere reachable is not yours to decide",agentListed:!0},{path:"server.port",means:"port for the HTTP API",agentListed:!0},{path:"channels[].allowFrom",means:"who may talk to this agent through a channel. Empty or absent refuses everyone — a bot that is connected, healthy and answering nobody is almost always this",agentListed:!1,via:"config allow"},{path:"server.host",means:"the address the HTTP API binds. 127.0.0.1 is local only; anything else is reachable from the network",agentListed:!1},{path:"server.tokenEnv",means:"the env var holding the bearer token the API requires. Without it the API is unauthenticated",agentListed:!1},{path:"delegation.offer",means:`what this agent takes on when another member's agent asks it, as a map: {task: "<one line>", artifact: {type: object, properties: {...}, required: [...]}}. The agents whose delegation.to names this one are reloaded so their roster shows it`,agentListed:!1},{path:"delegation.to",means:`the other members' agents this one may ask, by id, or "*" for every agent that offers. A peer ask is one hop: the asked agent answers, and cannot ask onward`,agentListed:!1},{path:"delegation.ask",means:"true or false: this agent asks the person's other agents (ask_agent) and they may ask it. Both have to say yes; an agent assigned to nobody that says yes is a shared agent anyone's agent may ask",agentListed:!1},{path:"sessions.scope",means:"how a turn's conversation is chosen: channel-peer (one per surface, the default), owner (the owner's turns from every surface share one), or peer (owner, and every registered participant gets one too)",agentListed:!1},{path:"memory.shared",means:"read and write the memory this agent's owner's agents share (agents:<owner>). Default true; false keeps memory_write private",agentListed:!1},{path:"subagents",means:"children that run work in their own context, as a list of {name, task, tools, route?: {tools}, spawn?, model?, maxSteps?, timeoutMs?}. route runs a child for those tool calls; spawn: true lets the model start it with delegate. Each tool must be pinned, and each routed slug belongs to one child",agentListed:!1},{path:"skills.trusted",means:"the skills whose scripts may run, by name. A skill not listed is still used for its steps, and its scripts are documentation only. Absent, every skill's scripts run",agentListed:!1},{path:"tools.providers.<id>.writeRoots",means:"the directories a file tool may write to, for that provider. Nothing outside them is writable — and this binds file tools only, never exec, which carries its target inside a shell string",agentListed:!1}];function En(e){return aA.find((n)=>n.path===e)}var to=/^model\.([A-Za-z][\w-]*)$/;function lo(e){let n=En(e);if(n!==void 0)return FA.includes(n.path)?n:void 0;let s=to.exec(e)?.[1];return s===void 0||s==="main"?void 0:En("model.<role>")}var Ai=aA.filter((e)=>e.agentListed).map((e)=>e.path),FA=aA.filter((e)=>e.via===void 0&&!e.path.includes("<")&&!e.path.includes("[")).map((e)=>e.path);var fn={kind:"public"};function mn(e){let n=e.split(".");if(n.length!==4)return;let s=[];for(let o of n){if(o.length===0||o.length>3||!/^[0-9]+$/.test(o))return;if(o.length>1&&o.startsWith("0"))return;let d=Number(o);if(d>255)return;s.push(d)}return s}function no(e){let n=e.split("%")[0]??"";if(n==="")return;if(!/^[0-9a-fA-F:.]+$/.test(n))return;let s=n.split("::");if(s.length>2)return;let o=(u)=>{if(u==="")return[];let h=u.split(":"),f=[];for(let w=0;w<h.length;w+=1){let m=h[w]??"";if(m.includes(".")){if(w!==h.length-1)return;let y=mn(m);if(y===void 0)return;f.push(...y);continue}if(m.length===0||m.length>4)return;let g=Number.parseInt(m,16);if(Number.isNaN(g))return;f.push(g>>8&255,g&255)}return f};if(s.length===1){let u=o(n);return u!==void 0&&u.length===16?u:void 0}let d=o(s[0]??""),l=o(s[1]??"");if(d===void 0||l===void 0)return;let c=16-d.length-l.length;if(c<0)return;return[...d,...Array(c).fill(0),...l]}function Oe(e){let[n=0,s=0,o=0,d=0]=e;if(n===0)return{kind:"unspecified",range:"0.0.0.0/8"};if(n===127)return{kind:"loopback",range:"127.0.0.0/8"};if(n===10)return{kind:"private",range:"10.0.0.0/8"};if(n===172&&s>=16&&s<=31)return{kind:"private",range:"172.16.0.0/12"};if(n===192&&s===168)return{kind:"private",range:"192.168.0.0/16"};if(n===100&&s>=64&&s<=127)return{kind:"cgnat",range:"100.64.0.0/10"};if(n===169&&s===254)return{kind:"link-local",range:"169.254.0.0/16"};if(n===192&&s===0&&o===0)return{kind:"reserved",range:"192.0.0.0/24"};if(n===192&&s===0&&o===2)return{kind:"reserved",range:"192.0.2.0/24 (TEST-NET-1)"};if(n===198&&(s===18||s===19))return{kind:"reserved",range:"198.18.0.0/15"};if(n===198&&s===51&&o===100)return{kind:"reserved",range:"198.51.100.0/24 (TEST-NET-2)"};if(n===203&&s===0&&o===113)return{kind:"reserved",range:"203.0.113.0/24 (TEST-NET-3)"};if(n>=224&&n<=239)return{kind:"multicast",range:"224.0.0.0/4"};if(n===255&&s===255&&o===255&&d===255)return{kind:"reserved",range:"255.255.255.255"};if(n>=240)return{kind:"reserved",range:"240.0.0.0/4"};return fn}function ro(e){if(e.length!==16)return{kind:"reserved",range:"unparseable"};if(e.slice(0,10).every((l)=>l===0)&&e[10]===255&&e[11]===255)return Oe(e.slice(12));if(e[0]===0&&e[1]===100&&e[2]===255&&e[3]===155&&e.slice(4,12).every((l)=>l===0))return Oe(e.slice(12));if(e.every((l)=>l===0))return{kind:"unspecified",range:"::"};if(e.slice(0,15).every((l)=>l===0)&&e[15]===1)return{kind:"loopback",range:"::1"};let o=e[0]??0,d=e[1]??0;if((o&254)===252)return{kind:"private",range:"fc00::/7"};if(o===254&&(d&192)===128)return{kind:"link-local",range:"fe80::/10"};if(o===255)return{kind:"multicast",range:"ff00::/8"};if(o===32&&d===1&&e[2]===13&&e[3]===184)return{kind:"reserved",range:"2001:db8::/32"};return fn}function mr(e){let n=e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e,s=mn(n);if(s!==void 0)return Oe(s);let o=no(n);if(o!==void 0)return ro(o);return}var ni=["agent","model","day","sender"];var Bd=["Summarise the conversation above for your own future reference. You are writing notes to yourself, not a report for a person.","","The person's own requests are preserved verbatim below your summary, so do not restate them.","Keep: decisions taken and why, facts established by tool results, and anything still outstanding.","Drop: pleasantries, your own reasoning, and anything already superseded.","Write plain prose under 300 words. No headings, no preamble, no closing summary.","End with one line naming what this summary does not cover, so a later step knows to ask rather than assume."].join(`
66
+ `);var Re=1,re=["MEMORY.md","memory/","knowledge/"],gn=/^[^/\\.][^/\\]*\.md$/;function M(e,n,s,o){return new ne({code:e,message:n,hint:s,...o===void 0?{}:{field:o}})}function wn(e){let n=js(e.workspace),s=(o)=>uo(o)?o:ho(e.dir,o);return{...n?.path===void 0||n.mode==="refused"?{}:{carried:{path:n.path,name:n.name,...n.budget===void 0?{}:{budget:n.budget},...n.eviction===void 0?{}:{eviction:n.eviction}}},...e.manifest.memory===void 0?{}:{memoryDir:s(e.manifest.memory.dir)},...e.manifest.knowledge===void 0?{}:{knowledgeDir:s(e.manifest.knowledge.dir)}}}function Ue(e){if(e===void 0)return[];try{return oo(e).filter((n)=>gn.test(n)&&!Ht(n)&&!Xt(n)).sort()}catch{return[]}}function ks(e){if(e===void 0||e.length===0)return re;return e.map((n,s)=>{let o=re.find((d)=>d===n);if(o===void 0)throw M("bundle_path_not_allowed",`"${n}" is not something a bundle can carry.`,`A bundle carries ${re.join(", ")} and nothing else — never the manifest, secrets or skills.`,`paths.${s}`);return o})}function vs(e,n=re,s=new Date){let o=wn(e),d=[];if(n.includes("MEMORY.md")&&o.carried!==void 0&&pn(o.carried.path))d.push({path:"MEMORY.md",content:q(o.carried.path,"utf8")});for(let[l,c]of[["memory/",o.memoryDir],["knowledge/",o.knowledgeDir]]){if(!n.includes(l)||c===void 0)continue;for(let u of Ue(c))d.push({path:`${l}${u}`,content:q(he(c,u),"utf8")})}return{version:Re,agentId:e.id,exportedAt:s.toISOString(),files:d}}function fo(e,n,s){let o=`files.${n}.path`;if(e.path==="MEMORY.md"){if(s.carried===void 0)throw M("bundle_memory_not_writable","This agent has no writable memory file to merge MEMORY.md into.","Give a volatile workspace file `editable: append` or `replace`, or export without MEMORY.md.",o);return{abs:s.carried.path,kind:"carried"}}let d=e.path.indexOf("/"),l=e.path.slice(0,d+1),c=e.path.slice(d+1);if(!(l==="memory/"||l==="knowledge/")||!gn.test(c)||Ht(c)||Xt(c))throw M("bundle_path_not_allowed",`"${e.path}" is not a path a bundle can carry.`,"A bundle carries MEMORY.md, memory/<name>.md and knowledge/<name>.md — one level, markdown only, never the manifest, secrets or skills.",o);let h=l==="memory/"?s.memoryDir:s.knowledgeDir;if(h===void 0)throw M(l==="memory/"?"bundle_no_memory":"bundle_no_knowledge",`This agent has no ${l==="memory/"?"memory":"knowledge"} block, so "${e.path}" has nowhere to go.`,`Add a \`${l==="memory/"?"memory":"knowledge"}:\` block to the manifest, or export without ${l}.`,o);return{abs:he(h,c),kind:l==="memory/"?"memory":"knowledge"}}function mo(e,n){let s=new Set(Ne(e.split(/\r?\n/)).map((o)=>o.text));return Ne(n.split(/\r?\n/)).map((o)=>o.text).filter((o)=>!s.has(o))}async function Ls(e){let n=e.now??new Date,s=e.mode??"skip",o=wo(e.bundle),d=wn(e.agent),l=o.map((v,T)=>({file:v,...fo(v,T,d)})),c=new Map,u=(v)=>{if(!c.has(v))c.set(v,pn(v)?q(v,"utf8"):void 0)};for(let v of l)u(v.abs);for(let v of Ue(d.memoryDir))u(he(d.memoryDir??"",v));if(d.carried!==void 0)u(d.carried.path);let h=[],f=[],w=[],m=[],g=0,y=!1;try{for(let{file:E,abs:N,kind:O}of l){let z=c.get(N);if(O==="knowledge"){if(z===E.content||z!==void 0&&s==="skip"){w.push(E.path);continue}ie(N,E.content,"utf8"),(z===void 0?h:m).push(E.path),y=!0;continue}if(z===void 0){ie(N,E.content,"utf8"),h.push(E.path),y||=O==="carried";continue}let fe=mo(q(N,"utf8"),E.content);if(fe.length===0){w.push(E.path);continue}ie(N,`${q(N,"utf8").trimEnd()}
67
+
68
+ ${fe.join(`
69
+ `)}
70
+ `,"utf8"),f.push({path:E.path,notes:fe.length}),y||=O==="carried"}let v=d.carried;if(y&&v?.eviction==="oldest"&&v.budget!==void 0&&d.memoryDir!==void 0)g=(await rn({path:v.path,name:v.name,budget:v.budget,archiveDir:d.memoryDir,now:n})).evicted;let T=y?await e.reload():"none";return{added:h,merged:f,skipped:w,overwritten:m,evicted:g,reload:T}}catch(v){if(po(c,d.memoryDir),!_(v))throw v;throw new ne({code:"bundle_import_refused",message:`Nothing was imported: the agent would not load with this bundle. ${v.message}`,hint:v.hint,...v.field===void 0?{}:{field:v.field}})}}function po(e,n){for(let[s,o]of e)if(o===void 0)Dt(s,{force:!0});else ie(s,o,"utf8");for(let s of Ue(n)){let o=he(n??"",s);if(!e.has(o))Dt(o,{force:!0})}}function wo(e){let n=typeof e==="object"&&e!==null?e:{};if(n.version!==Re)throw M("bundle_version_unsupported",`This bundle is version ${JSON.stringify(n.version)}; this build reads version ${Re}.`,"Export the bundle again with GET /v1/agents/:id/export on a build that matches.","version");if(!Array.isArray(n.files))throw M("bundle_files_invalid","A bundle needs a `files` list.",'Send the body GET /v1/agents/:id/export returned: { "version": 1, "files": [{ "path", "content" }] }.',"files");let s=new Set;return n.files.map((o,d)=>{let l=typeof o==="object"&&o!==null?o:{};if(typeof l.path!=="string"||typeof l.content!=="string")throw M("bundle_files_invalid",`files.${d} needs a string \`path\` and a string \`content\`.`,"Each entry is { path, content }, as an export writes it.",`files.${d}`);if(s.has(l.path))throw M("bundle_files_invalid",`"${l.path}" appears twice.`,"A bundle names each path once.",`files.${d}.path`);return s.add(l.path),{path:l.path,content:l.content}})}var Ut="agent:";function oi(e){return e.startsWith(Ut)?e.slice(Ut.length):void 0}var Kd=(()=>{let e=Symbol.for(`${V.slug}.liveRuntimes`),n=globalThis;return n[e]??=new Set,n[e]})();var yo="id, session_key, turn_id, role, content, tool_calls, tool_call_id, origin, tainted, created_at",Gd=yo.split(", ").map((e)=>`m.${e}`).join(", ");function Ps(){let e=new Uint8Array(24);return crypto.getRandomValues(e),`whsec_${Buffer.from(e).toString("base64")}`}function Gs(e){return e!=="model.chunk"}var bo="schedule";function Fs(e,n,s){if(e.startsWith("shared:")){let o=e.slice(7);if(o!=="")return o}return Vr({channel:bo,peerId:n,thread:s})}function Us(e){let n=nn.safeParse(e.body);if(!n.success){let h=n.error.issues[0];throw new Q({code:"schedule_invalid",message:`Schedule rejected: ${h?.path.join(".")??"body"} ${h?.message??"is invalid"}.`,hint:"A schedule needs id, kind (cron|every|at), expr, task and deliver. See docs/02-SPEC-MANIFEST.md.",...h?.path.length===void 0||h.path.length===0?{}:{field:h.path.join(".")}})}let s=n.data;if(s.deliver!=="none"){if(!e.channelIds.includes(s.deliver.channel))throw new Q({code:"schedule_delivery_channel_unknown",message:`Schedule "${s.id}" delivers to "${s.deliver.channel}", which is not a channel id on this agent.${e.channelIds.length===0?" The agent declares no channels.":` Declared: ${e.channelIds.join(", ")}.`}`,hint:`A delivery target names a channel's id, not its type. Use deliver: "none" to return results through the event stream instead.`,field:"deliver.channel"})}if(s.role!==void 0&&!e.roleNames.includes(s.role))throw new Q({code:"schedule_role_unknown",message:`Schedule "${s.id}" names the model role "${s.role}", which is not declared under model:. Declared: ${e.roleNames.join(", ")}.`,hint:"Add the role under model: in the manifest, or point the schedule at one of the declared roles. Omit role entirely to use main.",field:"role"});let o=s.tools?.allow;if(o!==void 0&&e.toolSpecs!==void 0){let h=ys(o,e.toolSpecs);if(h.length>0)throw Ve(s.id,h,e.toolSpecs.map((f)=>f.slug),"tools.allow")}let d=Qr({id:s.id,kind:s.kind,expr:s.expr,timezone:s.timezone,now:e.now,field:"expr"}),l=new Date(e.now).toISOString(),c=Lr(d,s.id,e.now,e.now),u=s.deliver==="none"?void 0:s.deliver;return{agentId:e.agentId,id:s.id,kind:s.kind,expr:s.expr,...s.timezone===void 0?{}:{timezone:s.timezone},task:s.task,...u===void 0?{}:{deliverChannel:u.channel,deliverTo:u.to},sessionMode:s.session,...s.role===void 0?{}:{role:s.role},toolsAllow:s.tools?.allow,timeoutMs:s.timeoutMs,maxSteps:s.maxSteps,enabled:s.enabled,origin:e.origin,anchorAt:c.anchor===void 0?l:new Date(c.anchor).toISOString(),nextRunAt:c.runAt===void 0?void 0:new Date(c.runAt).toISOString(),sourcePath:"",now:l}}function xs(e){return{...e.role===void 0?{}:{role:e.role},...e.toolsAllow===void 0?{}:{toolsAllow:e.toolsAllow},...e.maxSteps===void 0?{}:{maxSteps:e.maxSteps},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}}var qd=new Set("a an and are as at be but by do does for from had has have he her his i if in is it its me my not of on or our she that the their them then there they this to was we were what when which who will with you your would could should im ive dont its ill".split(" "));
71
+ export{V,jt,_,ne,Q,ct,b,dr,Ye,ur,Er,Jt,qt,pr,Cr,io,fr,hr,Br,yr,Qs,Vr,Wr,ms,so,Ss,ao,ws,Ds,bs,zr,Os,Vt,Zr,go,Ns,$r,Ms,Ts,Wt,GA,Qr,Xr,Rs,ei,co,ti,_s,aA,En,lo,Ai,FA,mr,ni,ks,vs,Ls,oi,Ps,Gs,Fs,Us,xs};
72
+
73
+ //# debugId=922483D9678CCB1D64756E2164756E21
74
+ //# sourceMappingURL=index-hd5nkwd7.js.map