dispach 0.2.3 → 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.
- package/README.md +29 -25
- package/dist/APEv2Parser-x13n424p.js +5 -0
- package/dist/{FlacParser-drm5wq0p.js.map → APEv2Parser-x13n424p.js.map} +1 -1
- package/dist/{AiffParser-9hj6fpmy.js → AiffParser-ns1y9f0g.js} +3 -3
- package/dist/{AiffParser-9hj6fpmy.js.map → AiffParser-ns1y9f0g.js.map} +1 -1
- package/dist/App-wkpkwgjt.js +11 -0
- package/dist/{App-2f72vhjv.js.map → App-wkpkwgjt.js.map} +1 -1
- package/dist/AsfParser-bae2a1yf.js +5 -0
- package/dist/{AsfParser-7emspn04.js.map → AsfParser-bae2a1yf.js.map} +1 -1
- package/dist/ConfigEditor-hy9jtas3.js +6 -0
- package/dist/{ConfigEditor-vk7vxaa6.js.map → ConfigEditor-hy9jtas3.js.map} +1 -1
- package/dist/DsdiffParser-s0zvxnfa.js +5 -0
- package/dist/{DsdiffParser-dz88pnnr.js.map → DsdiffParser-s0zvxnfa.js.map} +1 -1
- package/dist/{DsfParser-qgh63tbs.js → DsfParser-90mvzt4v.js} +3 -3
- package/dist/{DsfParser-qgh63tbs.js.map → DsfParser-90mvzt4v.js.map} +1 -1
- package/dist/FlacParser-8xprykrh.js +5 -0
- package/dist/{APEv2Parser-ysjr6adv.js.map → FlacParser-8xprykrh.js.map} +1 -1
- package/dist/{KeyProbe-5anphmb7.js → KeyProbe-fk5krzks.js} +3 -3
- package/dist/{KeyProbe-5anphmb7.js.map → KeyProbe-fk5krzks.js.map} +1 -1
- package/dist/MP4Parser-nmvbkq21.js +5 -0
- package/dist/{MP4Parser-yr7p3z12.js.map → MP4Parser-nmvbkq21.js.map} +2 -2
- package/dist/{MatroskaParser-jkbsbsk3.js → MatroskaParser-tsmz2qfq.js} +3 -3
- package/dist/{MatroskaParser-jkbsbsk3.js.map → MatroskaParser-tsmz2qfq.js.map} +1 -1
- package/dist/{MpegParser-t93vwnew.js → MpegParser-y5fjpaz9.js} +3 -3
- package/dist/{MpegParser-t93vwnew.js.map → MpegParser-y5fjpaz9.js.map} +1 -1
- package/dist/MusepackParser-544q0byg.js +5 -0
- package/dist/{MusepackParser-6e8kbh2d.js.map → MusepackParser-544q0byg.js.map} +2 -2
- package/dist/OggParser-v77rbjnt.js +5 -0
- package/dist/{OggParser-ggcypmag.js.map → OggParser-v77rbjnt.js.map} +1 -1
- package/dist/Picker-32m79nmp.js +5 -0
- package/dist/{Picker-j7txnm7w.js.map → Picker-32m79nmp.js.map} +1 -1
- package/dist/SessionPicker-9p06npt5.js +5 -0
- package/dist/{SessionPicker-hpv2ncsb.js.map → SessionPicker-9p06npt5.js.map} +1 -1
- package/dist/SkillBrowser-ezdx3xsh.js +5 -0
- package/dist/{SkillBrowser-qc542n71.js.map → SkillBrowser-ezdx3xsh.js.map} +1 -1
- package/dist/WavPackParser-k623m0hk.js +5 -0
- package/dist/{WavPackParser-jw9stzqp.js.map → WavPackParser-k623m0hk.js.map} +1 -1
- package/dist/WaveParser-nj4p1vx8.js +5 -0
- package/dist/{WaveParser-epmncs9w.js.map → WaveParser-nj4p1vx8.js.map} +1 -1
- package/dist/WizardApp-p350qspw.js +5 -0
- package/dist/{WizardApp-pgzcz9zq.js.map → WizardApp-p350qspw.js.map} +1 -1
- package/dist/channels-a9zx9yba.js +31 -0
- package/dist/{channels-m8nambmm.js.map → channels-a9zx9yba.js.map} +1 -1
- package/dist/config-3mz4zwsf.js +24 -0
- package/dist/{config-hmgrqgf2.js.map → config-3mz4zwsf.js.map} +2 -2
- package/dist/credential-ja7zmd4c.js +19 -0
- package/dist/{credential-nkb2ya59.js.map → credential-ja7zmd4c.js.map} +1 -1
- package/dist/index-039ew35r.js +6 -0
- package/dist/index-039ew35r.js.map +10 -0
- package/dist/index-0dvs3a06.js +6 -0
- package/dist/{index-jc4kmfwa.js.map → index-0dvs3a06.js.map} +1 -1
- package/dist/{index-pszmnhgq.js → index-1cagdzqe.js} +9 -9
- package/dist/{index-pszmnhgq.js.map → index-1cagdzqe.js.map} +1 -1
- package/dist/index-2fw9e5gg.js +6 -0
- package/dist/{index-0444sh6x.js.map → index-2fw9e5gg.js.map} +1 -1
- package/dist/{index-hgm2gchq.js → index-2td5h856.js} +12 -12
- package/dist/{index-hgm2gchq.js.map → index-2td5h856.js.map} +1 -1
- package/dist/{index-m6fqx0ch.js → index-446exxcb.js} +7 -7
- package/dist/{index-m6fqx0ch.js.map → index-446exxcb.js.map} +1 -1
- package/dist/{index-snz49ndn.js → index-4fajxhdv.js} +4 -4
- package/dist/{index-snz49ndn.js.map → index-4fajxhdv.js.map} +1 -1
- package/dist/index-4j65jp20.js +9 -0
- package/dist/{index-38gs9anh.js.map → index-4j65jp20.js.map} +1 -1
- package/dist/index-5gn74n56.js +10 -0
- package/dist/{index-22fzzn7z.js.map → index-5gn74n56.js.map} +2 -2
- package/dist/index-5zpfz4kb.js +9 -0
- package/dist/{index-eztfverw.js.map → index-5zpfz4kb.js.map} +1 -1
- package/dist/index-60h4knj6.js +126 -0
- package/dist/{index-ry6a4bqh.js.map → index-60h4knj6.js.map} +2 -2
- package/dist/index-635wcsh1.js +5 -0
- package/dist/{index-2bsardvh.js.map → index-635wcsh1.js.map} +1 -1
- package/dist/{index-k8e9f466.js → index-67sfck4d.js} +19 -19
- package/dist/index-67sfck4d.js.map +13 -0
- package/dist/index-7p8d1gf0.js +63 -0
- package/dist/{index-ytxbw8py.js.map → index-7p8d1gf0.js.map} +1 -1
- package/dist/index-7zgjkbb0.js +5 -0
- package/dist/{index-qgsdgbk8.js.map → index-7zgjkbb0.js.map} +1 -1
- package/dist/{index-zw6wyas6.js → index-86rb86nr.js} +4 -4
- package/dist/{index-zw6wyas6.js.map → index-86rb86nr.js.map} +1 -1
- package/dist/{index-fbsrhcga.js → index-8jejze0z.js} +4 -4
- package/dist/{index-fbsrhcga.js.map → index-8jejze0z.js.map} +1 -1
- package/dist/index-8k8y7edx.js +7 -0
- package/dist/{index-3826kf9t.js.map → index-8k8y7edx.js.map} +1 -1
- package/dist/index-8mkatm20.js +6 -0
- package/dist/{index-42e29zs4.js.map → index-8mkatm20.js.map} +1 -1
- package/dist/{index-3vzf253k.js → index-9k6qa50r.js} +7 -7
- package/dist/{index-3vzf253k.js.map → index-9k6qa50r.js.map} +1 -1
- package/dist/{index-yw3fby4n.js → index-a1axc952.js} +4 -4
- package/dist/{index-yw3fby4n.js.map → index-a1axc952.js.map} +1 -1
- package/dist/index-ayhdn87b.js +6 -0
- package/dist/{index-dzy19wtf.js.map → index-ayhdn87b.js.map} +1 -1
- package/dist/index-b8bfzbfe.js +6 -0
- package/dist/{index-836hc2h1.js.map → index-b8bfzbfe.js.map} +2 -2
- package/dist/index-brh25jhq.js +6 -0
- package/dist/{index-hrwakb11.js.map → index-brh25jhq.js.map} +2 -2
- package/dist/index-c6qrcweh.js +6 -0
- package/dist/{index-nxhqf597.js.map → index-c6qrcweh.js.map} +1 -1
- package/dist/index-cb45233h.js +6 -0
- package/dist/{index-nvc24414.js.map → index-cb45233h.js.map} +1 -1
- package/dist/{index-51x0n5z0.js → index-dcy14zdn.js} +5 -5
- package/dist/{index-51x0n5z0.js.map → index-dcy14zdn.js.map} +1 -1
- package/dist/index-f6r3h2yh.js +8 -0
- package/dist/{index-9t4dz145.js.map → index-f6r3h2yh.js.map} +1 -1
- package/dist/index-gezqawvw.js +11 -0
- package/dist/{index-sh44ymqz.js.map → index-gezqawvw.js.map} +1 -1
- package/dist/{index-1mbdz3f7.js → index-h787rq0h.js} +10 -10
- package/dist/{index-1mbdz3f7.js.map → index-h787rq0h.js.map} +1 -1
- package/dist/index-hd5nkwd7.js +74 -0
- package/dist/{index-djeqvfms.js.map → index-hd5nkwd7.js.map} +5 -5
- package/dist/index-k6wq0j4q.js +6 -0
- package/dist/{index-mjfv7k5w.js.map → index-k6wq0j4q.js.map} +1 -1
- package/dist/index-kz01jz58.js +6 -0
- package/dist/{index-323jvr1g.js.map → index-kz01jz58.js.map} +1 -1
- package/dist/{index-dv9pdjy4.js → index-mgef1n4e.js} +10 -10
- package/dist/{index-dv9pdjy4.js.map → index-mgef1n4e.js.map} +1 -1
- package/dist/{index-fxpmx6cr.js → index-n197qdw1.js} +191 -191
- package/dist/{index-fxpmx6cr.js.map → index-n197qdw1.js.map} +3 -3
- package/dist/index-nndwx2wp.js +153 -0
- package/dist/{index-dpcm1j62.js.map → index-nndwx2wp.js.map} +2 -2
- package/dist/index-pz92ksp8.js +5 -0
- package/dist/{index-3c5jt6by.js.map → index-pz92ksp8.js.map} +1 -1
- package/dist/index-qj4adnfe.js +14 -0
- package/dist/{index-y7dxq4a4.js.map → index-qj4adnfe.js.map} +2 -2
- package/dist/index-r83jpct7.js +6 -0
- package/dist/{index-xg7s813b.js.map → index-r83jpct7.js.map} +2 -2
- package/dist/{index-2zjh5zd5.js → index-rqfwd7j5.js} +4 -4
- package/dist/{index-2zjh5zd5.js.map → index-rqfwd7j5.js.map} +1 -1
- package/dist/index-s0f0s6n5.js +6 -0
- package/dist/{index-pqw1n1pv.js.map → index-s0f0s6n5.js.map} +1 -1
- package/dist/index-s0t15ndj.js +6 -0
- package/dist/{index-8edck2pr.js.map → index-s0t15ndj.js.map} +1 -1
- package/dist/index-tc054tcb.js +6 -0
- package/dist/{index-8tmv33mr.js.map → index-tc054tcb.js.map} +1 -1
- package/dist/{index-095hrkyr.js → index-ts8a1sdn.js} +6 -6
- package/dist/{index-095hrkyr.js.map → index-ts8a1sdn.js.map} +1 -1
- package/dist/index-tv52jhac.js +1252 -0
- package/dist/{index-hpvfqq6r.js.map → index-tv52jhac.js.map} +3 -3
- package/dist/index-x9nn57kk.js +6 -0
- package/dist/{index-1x8mzvz7.js.map → index-x9nn57kk.js.map} +1 -1
- package/dist/{index-308y9xt0.js → index-xyh98x7p.js} +4 -4
- package/dist/{index-308y9xt0.js.map → index-xyh98x7p.js.map} +1 -1
- package/dist/{index-jff5q27j.js → index-yy4v9kca.js} +4 -4
- package/dist/{index-jff5q27j.js.map → index-yy4v9kca.js.map} +1 -1
- package/dist/{index-bqdkm3de.js → index-yz0fcxky.js} +4 -4
- package/dist/{index-bqdkm3de.js.map → index-yz0fcxky.js.map} +1 -1
- package/dist/{index-p6ya59m6.js → index-z4adxmzm.js} +5 -5
- package/dist/{index-p6ya59m6.js.map → index-z4adxmzm.js.map} +1 -1
- package/dist/{index-4fj1k64j.js → index-zzpgsbn3.js} +4 -4
- package/dist/{index-4fj1k64j.js.map → index-zzpgsbn3.js.map} +1 -1
- package/dist/index.js +345 -345
- package/dist/index.js.map +4 -4
- package/dist/web-7mdrcb8a.js +14 -0
- package/dist/{web-gfv0mzgs.js.map → web-7mdrcb8a.js.map} +1 -1
- package/dist/wrapper-4hdmdwft.js +5 -0
- package/dist/{wrapper-f662ny3r.js.map → wrapper-4hdmdwft.js.map} +1 -1
- package/package.json +1 -1
- package/dist/APEv2Parser-ysjr6adv.js +0 -5
- package/dist/App-2f72vhjv.js +0 -11
- package/dist/AsfParser-7emspn04.js +0 -5
- package/dist/ConfigEditor-vk7vxaa6.js +0 -6
- package/dist/DsdiffParser-dz88pnnr.js +0 -5
- package/dist/FlacParser-drm5wq0p.js +0 -5
- package/dist/MP4Parser-yr7p3z12.js +0 -5
- package/dist/MusepackParser-6e8kbh2d.js +0 -5
- package/dist/OggParser-ggcypmag.js +0 -5
- package/dist/Picker-j7txnm7w.js +0 -5
- package/dist/SessionPicker-hpv2ncsb.js +0 -5
- package/dist/SkillBrowser-qc542n71.js +0 -5
- package/dist/WavPackParser-jw9stzqp.js +0 -5
- package/dist/WaveParser-epmncs9w.js +0 -5
- package/dist/WizardApp-pgzcz9zq.js +0 -5
- package/dist/channels-m8nambmm.js +0 -31
- package/dist/config-hmgrqgf2.js +0 -24
- package/dist/credential-nkb2ya59.js +0 -19
- package/dist/index-0444sh6x.js +0 -6
- package/dist/index-1x8mzvz7.js +0 -6
- package/dist/index-22fzzn7z.js +0 -10
- package/dist/index-2bsardvh.js +0 -5
- package/dist/index-323jvr1g.js +0 -6
- package/dist/index-3826kf9t.js +0 -7
- package/dist/index-38gs9anh.js +0 -9
- package/dist/index-3c5jt6by.js +0 -5
- package/dist/index-42e29zs4.js +0 -6
- package/dist/index-836hc2h1.js +0 -6
- package/dist/index-8edck2pr.js +0 -6
- package/dist/index-8tmv33mr.js +0 -6
- package/dist/index-9t4dz145.js +0 -8
- package/dist/index-djeqvfms.js +0 -74
- package/dist/index-dpcm1j62.js +0 -153
- package/dist/index-dzy19wtf.js +0 -6
- package/dist/index-eztfverw.js +0 -9
- package/dist/index-hpvfqq6r.js +0 -1252
- package/dist/index-hrwakb11.js +0 -6
- package/dist/index-jc4kmfwa.js +0 -6
- package/dist/index-k8e9f466.js.map +0 -13
- package/dist/index-mjfv7k5w.js +0 -6
- package/dist/index-nvc24414.js +0 -6
- package/dist/index-nxhqf597.js +0 -6
- package/dist/index-pqw1n1pv.js +0 -6
- package/dist/index-qgsdgbk8.js +0 -5
- package/dist/index-qv6ktepc.js +0 -6
- package/dist/index-qv6ktepc.js.map +0 -10
- package/dist/index-ry6a4bqh.js +0 -126
- package/dist/index-sh44ymqz.js +0 -11
- package/dist/index-xg7s813b.js +0 -6
- package/dist/index-y7dxq4a4.js +0 -14
- package/dist/index-ytxbw8py.js +0 -63
- package/dist/web-gfv0mzgs.js +0 -14
- package/dist/wrapper-f662ny3r.js +0 -5
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
5
|
-
`)}function M(e,t){return t<=0?"—":`${(e/t*100).toFixed(1)}%`}function
|
|
6
|
-
hint: ${o}`)}case"context.dropped":{let{messages:n,budget:r}=t.data;return
|
|
7
|
-
`))}function
|
|
8
|
-
`);n.push(o({key:`${s.id}:title`,role:"banner",text:
|
|
9
|
-
export{
|
|
2
|
+
import{J,Tt,Ci}from"./index-tv52jhac.js";import{at}from"./index-039ew35r.js";import{ca}from"./index-ayhdn87b.js";import{dn}from"./index-z4adxmzm.js";import{C}from"./index-9k6qa50r.js";import{Qi}from"./index-2fw9e5gg.js";import{Ca,ha}from"./index-tc054tcb.js";var w=[{kind:"help",word:"/help",aliases:[],summary:"this list"},{kind:"status",word:"/status",aliases:[],summary:"model, channels, server, store — what this agent is and what is actually running"},{kind:"context",word:"/context",aliases:[],summary:"what is in the prompt right now, per slot, and what the percentage is a percentage of"},{kind:"restart",word:"/restart",aliases:[],summary:"restart the agent, for any configuration changes to take effect (memory files on disk are untouched)"},{kind:"tools",word:"/tools",aliases:[],summary:"what the model may call, and what the catalogue costs every turn"},{kind:"new",word:"/new",aliases:[],summary:"start a fresh conversation — this one stays in the store under its own key, and /sessions goes back to it"},{kind:"reset",word:"/reset",aliases:[],summary:"clear this conversation's history in place, keeping its key — memory files on disk are untouched"},{kind:"exit",word:"/exit",aliases:["/quit",":q"],summary:"leave — asks first, because the screen goes with it"}],Yi="⌥⏎ or a trailing \\ for a new line · ⏎ sends",ji="/ commands · ⏎ sends · ⇧⏎ new line · ^C twice leaves",T=[{chord:"^C",summary:"cancel the turn in flight — at an idle prompt, press it twice to leave (the screen goes with it)"},{chord:"^D",summary:"leave when the line is empty; delete forward when it is not"},{chord:"^A / ^E",summary:"start of line / end of line"},{chord:"^B / ^F",summary:"back one character / forward one"},{chord:"^U / ^K",summary:"delete to the start of the line / to the end"},{chord:"^W",summary:"delete the word before the cursor"},{chord:"^P / ^N",summary:"previous / next of what you have already sent"},{chord:"↑ / ↓",summary:"a line up or down inside the message — the same history at its first and last line"},{chord:"⌥⏎ / ⇧⏎",summary:"a new line in the message — ⌥⏎ everywhere, ⇧⏎ where the terminal can tell it apart (`keys` says); a trailing \\ does the same; ⏎ sends it"},{chord:"⌥← / ⌥→",summary:"back one word / forward one — ^← / ^→ do the same"},{chord:"⌥⌫ / ⌥d",summary:"delete the word before the cursor / after it"},{chord:"Home / End",summary:"start of line / end of line, the same as ^A / ^E"},{chord:"cmd← / cmd→",summary:"start of line / end of line, where the terminal reports cmd (else ^A / ^E)"},{chord:"cmd↑ / cmd↓",summary:"the start / end of the whole message, however many lines it has"},{chord:"cmd⌫ / cmd⌦",summary:"delete to the start of the line / to the end"},{chord:"cmdz / cmd⇧z",summary:"undo / redo, the same as ^Z / ^Y"},{chord:"⇧ + any motion",summary:"select as the cursor moves — ⇧← a character, ⇧⌥← a word, ⇧cmd← to the line start, ⇧cmd↑ to the top; typing or ⌫ replaces what is selected"},{chord:"cmda",summary:"select the whole message"},{chord:"^R",summary:"search what you have already sent — ↑↓ to pick, ⏎ to use it, esc to cancel"},{chord:"^Z / ^Y",summary:"undo / redo the last edit — suspend is not available inside a session"},{chord:"PgUp / PgDn",summary:"back and forward through the conversation a screen at a time"},{chord:"⌥↑ / ⌥↓",summary:"the same, one row at a time"},{chord:"⌥PgUp / ⌥PgDn",summary:"the start of the conversation / back to the newest reply"},{chord:"^O / ⌥r",summary:"show the model's reasoning whole — folded to a few rows so the reply stays findable; ^O works on every terminal, ⌥r needs one that reports it"},{chord:"drag",summary:"select text — in the conversation it goes to the clipboard when you let go, so ⌘V works; in the input box it does not, because you are usually about to type over it (⌘C copies, ⌘X cuts). Double-click a word, triple-click a line, esc clears"},{chord:"esc",summary:"return to the newest reply when you have scrolled away"}],j=T.flatMap((e)=>[...e.chord.matchAll(/\^([A-Za-z])/g)].map((t)=>(t[1]??"").toLowerCase())),U=T.flatMap((e)=>[...e.chord.matchAll(/⌥([a-z])(?![A-Za-z])/g)].map((t)=>t[1]??""));var I=/^\/[A-Za-z][\w-]*$/,L=/^(\/[A-Za-z][\w-]*)\s+(.*)$/,k=new Map(w.flatMap((e)=>[e.word,...e.aliases].map((t)=>[t.toLowerCase(),e.kind])));function Kn(e,t=[]){let n=e.trim(),r=k.get(n.toLowerCase());if(r!==void 0)return{kind:r};let o=new Set(t);if(o.has(n.slice(1).toLowerCase())&&I.test(n))return{kind:"command",name:n.slice(1).toLowerCase(),rest:""};let l=L.exec(n);if(l!==null){let i=(l[1]??"").toLowerCase(),a=l[2]??"",d=k.get(i);if(d!==void 0)return{kind:d,rest:a};if(o.has(i.slice(1)))return{kind:"command",name:i.slice(1),rest:a};return}if(!I.test(n))return;let s=J(n.toLowerCase(),[...k.keys(),...t.map((i)=>`/${i}`)]);return{kind:"unknown",word:n,...s===void 0?{}:{nearest:s}}}var R=20;function D(e){return` ${[e.word,...e.aliases].join(" / ").padEnd(R)}${e.summary}`}function K(e){return` ${e.chord.padEnd(R)}${e.summary}`}function Yn(){return["commands:",...w.map(D),"","keys:",...T.map(K)].join(`
|
|
3
|
+
`)}function on(e){let t=e.nearest===void 0?"":` Did you mean ${e.nearest}?`;return`${e.word} is not a command.${t} Type /help for the list — or add a space if you meant to say it to the model.`}function er(e){let t=e.describe();return{dialect:t.dialect,catalogueTokens:t.catalogueTokens,tools:e.tools.specs().map((n)=>({slug:n.slug,mutating:n.mutating,trust:n.trust??"trusted",...n.trustReason===void 0?{}:{trustReason:n.trustReason},summary:n.summary}))}}function bA(e){if(e.tools.length===0)return`no tools — this agent pinned none, so the model can only reply. Add them under tools.local or tools.pinned. (call format ${e.dialect})`;let t=e.tools.reduce((r,o)=>Math.max(r,o.slug.length),0),n=e.tools.flatMap((r)=>[` ${r.slug.padEnd(t)} ${r.mutating?"write":"read "} ${r.trust==="untrusted"?"untrusted":"trusted "} ${r.summary}`,...r.trustReason===void 0?[]:[`${" ".repeat(2+t+2+5+2+9+2)}trusted: ${r.trustReason}`]]);return[`${e.tools.length} tool${e.tools.length===1?"":"s"} · call format ${e.dialect} · catalogue ${e.catalogueTokens} tokens, on every turn`,...n].join(`
|
|
4
|
+
`)}function Ji(e){let t=Math.max(1,e.window-e.wireTokens-e.reserveOutput),n=(e.total/t*100).toFixed(1),r=e.calibration.samples===0?"estimated — the estimator runs low on tool-heavy prompts":`corrected ×${e.calibration.ratio.toFixed(2)} from ${e.calibration.samples} reported ${e.calibration.samples===1?"figure":"figures"}`,o=e.slots.reduce((a,d)=>Math.max(a,d.label.length),0),l=e.slots.map((a)=>` ${String(a.slot).padStart(2)} ${a.label.padEnd(o)} ${String(a.tokens).padStart(6)}${a.pinned?" pinned":""}`),s=e.history.reduce((a,d)=>Math.max(a,d.label.length),0),i=e.history.length===0?[]:e.history.map((a)=>` ${a.label.padEnd(s)} ${String(a.tokens).padStart(6)} ${M(a.tokens,e.total).padStart(6)} ${String(a.messages).padStart(3)} msg`);return[C([{label:"window",value:`${e.window} (${e.windowSource})`},{label:"budget",value:`${t} = window ${e.window} − wire ${e.wireTokens} − reserveOutput ${e.reserveOutput}`},{label:"prompt",value:`${e.total} tokens · ${n}% of budget`},{label:"counted",value:r},{label:"compaction",value:e.lastCompaction??"none this session"},{label:"cache",value:e.cache===void 0?"not reported by this endpoint":`${e.cache.cached} of ${e.cache.prompt} prompt tokens (${M(e.cache.cached,e.cache.prompt)}) over ${e.cache.turns} turn${e.cache.turns===1?"":"s"} · ${e.cache.source}`}]),""," slots",...l,...i.length===0?[]:[""," history, by kind — share of the whole prompt",...i]].join(`
|
|
5
|
+
`)}function M(e,t){return t<=0?"—":`${(e/t*100).toFixed(1)}%`}function tr(){let e=w.map((r)=>({word:r.word,summary:r.summary,kind:"session"})),t=new Set(e.map((r)=>r.word)),n=at.filter((r)=>r.inSession!=="hidden").filter((r)=>!t.has(`/${r.name}`)).map((r)=>({word:`/${r.name}`,summary:r.summary,kind:r.inSession==="view"?"view":"output",spec:r}));return[...e,...n]}function qi(e,t=tr()){if(!/^\/[A-Za-z-]*$/.test(e))return;let n=e.slice(1).toLowerCase(),r=t.filter((o)=>o.word.slice(1).toLowerCase().startsWith(n));return{query:n,matches:r}}function Ur(e,t){if(e.matches.length===0)return;return e.matches[Math.max(0,Math.min(t,e.matches.length-1))]}function jn(){return tr().filter((e)=>e.kind!=="session").map((e)=>e.word.slice(1))}var A={items:[],live:void 0,status:"idle",nextId:0,turnFrom:void 0};function m(e,t,n,r={}){let o={id:`t${e.nextId}`,role:t,text:n,...r.stats===void 0?{}:{stats:r.stats},...r.callId===void 0?{}:{callId:r.callId},...r.pending===void 0?{}:{pending:r.pending}};return{...e,items:[...e.items,o],nextId:e.nextId+1}}function S(e){let t=e.live;if(t===void 0)return e;let n=e;if(t.reasoning!=="")n=m(n,"reasoning",t.reasoning);if(t.text!=="")n=m(n,"assistant",t.text);return{...n,live:void 0}}function Vi(e,t){switch(t.kind){case"user":return m(e,"user",t.text);case"note":return m(e,"note",t.text);case"cancelling":return e.status==="idle"?e:{...e,status:"cancelling"};case"delta":return N(e,t.of,t.text);case"event":return H(e,t.event);case"trim":return F(e)}}function F(e){let t=e.items.length-ha;return t<=0?e:{...e,items:e.items.slice(t)}}function N(e,t,n){if(n==="")return e;let r=e.live??{text:"",reasoning:"",last:void 0};return{...e,live:{text:t==="text"?r.text+n:r.text,reasoning:t==="reasoning"?r.reasoning+n:r.reasoning,last:t},status:e.status==="cancelling"?"cancelling":"streaming"}}function f(e,t,n,r){let o=e.items.findIndex(t);if(o===-1)return e;let l=[...e.items],s=l[o],i=s.subagents??[],a=i.findIndex((c)=>c.sessionKey===n),d=r(a===-1?void 0:i[a]);if(d===void 0)return e;let u=a===-1?[...i,d].sort((c,p)=>(c.index??0)-(p.index??0)):i.map((c,p)=>p===a?d:c);return l[o]={...s,subagents:u},{...e,items:l}}var O=(e)=>(t)=>t.subagents?.some((n)=>n.sessionKey===e)===!0;function V(e,t){let n=t.sessionKey??"",r=O(n);if("slug"in t.data&&t.data.slug===Ci)return e;switch(t.type){case"tool.call":return f(e,r,n,(o)=>o===void 0?void 0:{...o,lines:[...o.lines,{callId:t.data.callId,text:`${t.data.slug} …`}]});case"tool.result":{let{slug:o,callId:l,ok:s,latencyMs:i}=t.data,a=`${o} — ${s?"ok":"failed"} · ${i} ms`;return f(e,r,n,(d)=>d===void 0?void 0:{...d,lines:d.lines.some((u)=>u.callId===l)?d.lines.map((u)=>u.callId===l?{callId:l,text:a}:u):[...d.lines,{callId:l,text:a}]})}case"tool.gated":return f(e,r,n,(o)=>o===void 0?void 0:{...o,lines:[...o.lines,{text:`${t.data.slug} — blocked: ${t.data.reason}`}]});default:return e}}function H(e,t){if(t.parentTurnId!==void 0)return V(e,t);switch(t.type){case"handoff.start":{let{kind:n,name:r,callId:o,sessionKey:l,label:s,index:i}=t.data;if(n!=="self"||o===void 0)return e;return f(e,(a)=>a.callId===o,l,(a)=>a??{name:r??"subagent",sessionKey:l,lines:[],...s===void 0?{}:{label:s},...i===void 0?{}:{index:i}})}case"handoff.result":{let{sessionKey:n,steps:r,tokens:o,outcome:l}=t.data,s=`${r} step${r===1?"":"s"} · ${Qi(o.prompt+o.output)} tokens · ${l==="ok"?"ok":l.replace("_"," ")}`;return f(e,O(n),n,(i)=>i===void 0?void 0:{...i,summary:s})}case"turn.start":return{...e,live:{text:"",reasoning:"",last:void 0},status:"thinking",turnFrom:e.items.length};case"model.result":return S(e);case"model.chunk":return N(e,t.data.kind,t.data.delta);case"tool.call":return{...m(S(e),"tool",`${t.data.slug}${t.data.mutating?" (changes state)":""}`,{callId:t.data.callId,pending:!0}),status:e.status==="cancelling"?"cancelling":"working"};case"tool.result":{let{slug:n,callId:r,ok:o,latencyMs:l,truncated:s}=t.data,i=`${n} — ${o?"ok":"failed"} · ${l} ms${s?" · observation trimmed":""}`,a=e.items.findIndex((c)=>c.callId===r&&c.pending===!0);if(a===-1)return m(e,o?"tool":"error",i);let d=[...e.items],u=d[a];return d[a]={id:u.id,role:o?"tool":"error",text:i,callId:r,...u.subagents===void 0?{}:{subagents:u.subagents}},{...e,items:d}}case"tool.gated":return m(e,"note",`${t.data.slug} — blocked: ${t.data.reason}`);case"tool.repair":return m(e,"note",t.data.slugs.length===0?`reply stopped short (${t.data.errors.join("; ")}), asking the model to finish`:`${t.data.slugs.join(", ")} — could not be used, asking the model again`);case"model.retry":{let{status:n,attempt:r,delayMs:o}=t.data;return m(e,"note",`retrying after HTTP ${n} — attempt ${r}, waiting ${o} ms`)}case"turn.end":{let{reason:n,steps:r,tokens:o,durationMs:l}=t.data,s={promptTokens:o.prompt,outputTokens:o.output,durationMs:l,steps:r,reason:n},i=S(e),a=e.turnFrom??0,d=-1;for(let h=i.items.length-1;h>=a;h-=1)if(i.items[h]?.role==="assistant"){d=h;break}let u=Tt(n,{steps:r,durationMs:l});if(d===-1)return{...m(i,"note",u??(n==="final"?"the model returned no text":""),{stats:s}),live:void 0,status:"idle",turnFrom:void 0};let c=[...i.items],p=c[d];c[d]={...p,stats:s};let y={...i,items:c,live:void 0,status:"idle",turnFrom:void 0};return u===void 0?y:m(y,"note",u)}case"error":{let{code:n,message:r,hint:o}=t.data;return m(e,"error",`${n}: ${r}
|
|
6
|
+
hint: ${o}`)}case"context.dropped":{let{messages:n,budget:r}=t.data;return m(e,"note",`context: ${n} older message(s) did not fit the ${r}-token budget and were left out`)}case"agent.warning":{let{code:n,message:r}=t.data;return m(e,"note",`${n}: ${r}`)}case"context.pressure":return{...e,pressure:t.data.fraction};case"compaction.stage":{let{stage:n,changed:r,before:o,after:l}=t.data;if(!r||n!=="collapse"&&n!=="reset")return e;return m(e,"note",`context: ${n==="reset"?"the conversation so far was replaced by a summary":"earlier turns were replaced by a summary"} (${o} → ${l} tokens)`)}case"phase.changed":{let{to:n,tools:r}=t.data;return{...m(e,"note",`phase: now in ${n} · ${r} tool${r===1?"":"s"} available`),phase:n}}case"context.reset":{let{warning:n}=t.data;return n===void 0?e:m(e,"note",`context: ${n}`)}default:return e}}function xr(e){return`${e.promptTokens} prompt · ${e.outputTokens} output · ${e.durationMs} ms`}function Wi(e){if(e.length===0)return A;return m(A,"banner",e.join(`
|
|
7
|
+
`))}function zi(e,t){let n=e;for(let r of t){if(r.text.trim()==="")continue;n=m(n,r.role,r.text)}return n}function Zi(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t]?.stats;if(n!==void 0)return n}return}function $i(e,t){let n=[],r=e.filter((l)=>l.role!=="reasoning"||t.showReasoning),o=(l)=>({...l,lead:0,continuation:!1});for(let[l,s]of r.entries()){if(l>0)n.push(o({key:`${s.id}:gap`,role:s.role,text:""}));if(s.role==="banner"){let[u="",...c]=s.text.split(`
|
|
8
|
+
`);n.push(o({key:`${s.id}:title`,role:"banner",text:u,bold:!0}));for(let[p,y]of c.entries())for(let[h,x]of dn(y,t.columns).entries())n.push({key:`${s.id}:note-${p}-${h}`,role:"banner",text:x,dim:!0,lead:0,continuation:h>0});continue}let i=ca[s.role],a=" ".repeat([...i].length),d=dn(s.text,Math.max(1,t.columns-[...i].length));if(s.role==="reasoning"){let u=t.expandReasoning===!0?d.length:Math.min(d.length,Ca),c=d.length-u;n.push(o({key:`${s.id}:label`,role:"reasoning",dim:!0,text:c>0?`· reasoning · ${d.length} rows · ⌥r expands`:`· reasoning · ${d.length} row${d.length===1?"":"s"}`}));for(let[p,y]of d.slice(0,u).entries())n.push({key:`${s.id}:${p}`,role:"reasoning",text:`${a}${y}`,lead:a.length,continuation:p>0});if(c>0)n.push(o({key:`${s.id}:folded`,role:"reasoning",dim:!0,text:`${a}… ${c} more row${c===1?"":"s"}`}));continue}for(let[u,c]of d.entries())n.push({key:`${s.id}:${u}`,role:s.role,text:`${u===0?i:a}${c}`,lead:[...i].length,continuation:u>0});for(let[u,c]of(s.subagents??[]).entries()){let p=t.expandReasoning===!0,y=c.summary??"running",h=!p&&c.lines.length>0?` · ⌥r shows ${c.lines.length} call${c.lines.length===1?"":"s"}`:"",x=c.label===void 0?"":` · ${c.label}`;for(let[g,b]of dn(`↳ subagent ${c.name}${x} · ${y}${h}`,Math.max(1,t.columns-a.length)).entries())n.push(o({key:`${s.id}:sub${u}-${g}`,role:s.role,text:`${a}${b}`,dim:!0}));if(p){let g=`${a} `;for(let[b,_]of c.lines.entries())for(let[E,P]of dn(_.text,Math.max(1,t.columns-g.length)).entries())n.push({key:`${s.id}:sub${u}-${b}-${E}`,role:s.role,text:`${g}${P}`,dim:!0,lead:g.length,continuation:E>0})}}if(s.stats!==void 0&&!t.quiet)n.push(o({key:`${s.id}:stats`,role:s.role,text:` ${xr(s.stats)}`,dim:!0}))}return n}
|
|
9
|
+
export{Yi,ji,Kn,Yn,on,er,bA,Ji,tr,qi,Ur,jn,Vi,xr,Wi,zi,Zi,$i};
|
|
10
10
|
|
|
11
|
-
//# debugId=
|
|
12
|
-
//# sourceMappingURL=index-
|
|
11
|
+
//# debugId=DE914263C13397E164756E2164756E21
|
|
12
|
+
//# sourceMappingURL=index-h787rq0h.js.map
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"/**\n * Events in, view state out. Pure, and the only place that decides what a turn looks like.\n *\n * The CLI has always been a `runtime.bus` subscriber; this makes it a *reducer* over that bus\n * instead of a set of callbacks writing to stdout. Three things follow from that:\n *\n * - \"What does the reader see when a turn errors mid-stream?\" is a unit test rather than something\n * reproduced by hand against a live endpoint.\n * - Finished items are append-only and immutable, which is exactly the contract Ink's `<Static>`\n * needs: a node written once and never re-rendered. The still-moving reply lives in `live`, so\n * the dynamic region stays one item regardless of how long the conversation gets.\n * - Phase 4's SSE client and Phase 12's TUI client can consume the same reduction instead of\n * re-deriving it.\n *\n * No clock and no randomness: ids come from a counter in the state, so the same events always\n * produce the same output and the tests need no fakes.\n */\n\nimport { type AnyEvent, endNote, SUBMIT_ARTIFACT } from \"@dispach/core\"\nimport { MAX_TRANSCRIPT_ITEMS, REASONING_FOLD_ROWS } from \"#lib/const\"\nimport { compactTokens } from \"#lib/rows\"\nimport { ROLE_PREFIX } from \"#lib/theme\"\nimport type {\n SubagentView,\n TranscriptItem,\n TranscriptRole,\n TranscriptRow,\n TranscriptState,\n TurnStats,\n} from \"#lib/types\"\nimport { wrapText } from \"#lib/wrap\"\n\n/**\n * The transcript is driven by more than the bus — a typed line and a cancellation request are not\n * events — so the reducer takes an action union rather than an event directly.\n */\nexport type TranscriptAction =\n | { readonly kind: \"user\"; readonly text: string }\n | { readonly kind: \"event\"; readonly event: AnyEvent }\n | { readonly kind: \"note\"; readonly text: string }\n | { readonly kind: \"cancelling\" }\n /**\n * A model delta that has already been through the dialect's stream filter.\n *\n * Filtering cannot happen in here: a filter is stateful and this reducer is pure. So the caller\n * owns one per step and dispatches what is left. A caller that dispatches the raw `model.chunk`\n * event instead still works — it just shows the invocation blocks, which is right for a dialect\n * with no in-band protocol and wrong for NLT.\n */\n | { readonly kind: \"delta\"; readonly of: \"text\" | \"reasoning\"; readonly text: string }\n /**\n * Drop the oldest items if the buffer is over `MAX_TRANSCRIPT_ITEMS`.\n *\n * An action rather than something `append` does on its own, because whether it is *safe* depends on\n * a fact this reducer cannot see: rows are addressed by position, so dropping any from the front\n * moves every offset below them. A reader parked twelve turns back would keep their offset and\n * silently start reading different text — the appearance of a live session that is not one, which is\n * the failure `ScrollState.pinned` exists to make impossible. Only the layer holding that flag knows\n * when eviction is allowed, so only it can ask.\n */\n | { readonly kind: \"trim\" }\n\nexport const EMPTY_TRANSCRIPT: TranscriptState = {\n items: [],\n live: undefined,\n status: \"idle\",\n nextId: 0,\n turnFrom: undefined,\n}\n\nfunction append(\n state: TranscriptState,\n role: TranscriptRole,\n text: string,\n extra: {\n readonly stats?: TurnStats\n readonly callId?: string\n readonly pending?: boolean\n } = {},\n): TranscriptState {\n const item: TranscriptItem = {\n id: `t${state.nextId}`,\n role,\n text,\n ...(extra.stats === undefined ? {} : { stats: extra.stats }),\n ...(extra.callId === undefined ? {} : { callId: extra.callId }),\n ...(extra.pending === undefined ? {} : { pending: extra.pending }),\n }\n return { ...state, items: [...state.items, item], nextId: state.nextId + 1 }\n}\n\n/**\n * Commit whatever the model has streamed so far, and clear it.\n *\n * Called at each step boundary rather than once at the end of the turn, which is what puts the\n * transcript back in the order things happened. Committing at `turn.end` alone produced a turn shaped\n * \"every tool row, then all the reasoning, then all the text\" — so the reasoning that *decided* to call\n * a tool was printed below the tool's result, and step one's reasoning was concatenated onto step two's\n * with no break between them. Live output on a real turn read `…look for it in my workspace.The user is\n * asking me to…`, two sentences from two steps with nothing marking the join.\n *\n * Reasoning goes in ahead of the text it produced. Whether it is *shown* is the view's business — the\n * item is written either way, so `--show-reasoning` can be honoured after the fact.\n */\nfunction flushLive(state: TranscriptState): TranscriptState {\n const live = state.live\n if (live === undefined) return state\n let next = state\n if (live.reasoning !== \"\") next = append(next, \"reasoning\", live.reasoning)\n if (live.text !== \"\") next = append(next, \"assistant\", live.text)\n return { ...next, live: undefined }\n}\n\n/** `data` is typed per event in core's map; narrowing by `type` first is what makes this safe. */\nexport function reduce(state: TranscriptState, action: TranscriptAction): TranscriptState {\n switch (action.kind) {\n case \"user\":\n return append(state, \"user\", action.text)\n\n case \"note\":\n return append(state, \"note\", action.text)\n\n case \"cancelling\":\n // A state, not an item. Cancellation that produced partial text still ends in a\n // `turn.end`, and that is what commits the text.\n return state.status === \"idle\" ? state : { ...state, status: \"cancelling\" }\n\n case \"delta\":\n return applyDelta(state, action.of, action.text)\n\n case \"event\":\n return reduceEvent(state, action.event)\n\n case \"trim\":\n return trim(state)\n }\n}\n\n/**\n * The oldest items above the cap, dropped. Identity when there is nothing to do.\n *\n * Returning the same object rather than a copy is what makes this cheap to ask about: `useReducer`\n * compares by reference and skips the render, so the caller can dispatch on every change without\n * checking first — and a caller that has to check first is a caller that eventually forgets.\n *\n * The banner is an ordinary item and goes with the rest. It is four hundred turns of scrollback above\n * the reader by then, and exempting it would leave the session's opening line pinned above a\n * conversation it no longer describes.\n */\nfunction trim(state: TranscriptState): TranscriptState {\n const over = state.items.length - MAX_TRANSCRIPT_ITEMS\n return over <= 0 ? state : { ...state, items: state.items.slice(over) }\n}\n\nfunction applyDelta(\n state: TranscriptState,\n kind: \"text\" | \"reasoning\",\n delta: string,\n): TranscriptState {\n if (delta === \"\") return state\n const live = state.live ?? { text: \"\", reasoning: \"\", last: undefined }\n return {\n ...state,\n live: {\n text: kind === \"text\" ? live.text + delta : live.text,\n reasoning: kind === \"reasoning\" ? live.reasoning + delta : live.reasoning,\n last: kind,\n },\n // A cancellation already asked for is not undone by another token arriving in flight; the\n // request stands until the turn actually ends.\n status: state.status === \"cancelling\" ? \"cancelling\" : \"streaming\",\n }\n}\n\n/**\n * The tool row `match` picks, with its subagent for `sessionKey` changed or added. Unchanged state\n * when no row matches or `change` declines.\n */\nfunction withSubagent(\n state: TranscriptState,\n match: (item: TranscriptItem) => boolean,\n sessionKey: string,\n change: (view: SubagentView | undefined) => SubagentView | undefined,\n): TranscriptState {\n const at = state.items.findIndex(match)\n if (at === -1) return state\n const items = [...state.items]\n const item = items[at] as TranscriptItem\n const views = item.subagents ?? []\n const index = views.findIndex((view) => view.sessionKey === sessionKey)\n const view = change(index === -1 ? undefined : views[index])\n if (view === undefined) return state\n const next =\n index === -1\n ? [...views, view].sort((a, b) => (a.index ?? 0) - (b.index ?? 0))\n : views.map((existing, i) => (i === index ? view : existing))\n items[at] = { ...item, subagents: next }\n return { ...state, items }\n}\n\n/** The row holding the subagent whose session is `sessionKey`. */\nconst holds = (sessionKey: string) => (item: TranscriptItem) =>\n item.subagents?.some((view) => view.sessionKey === sessionKey) === true\n\n/**\n * A subagent's own event: its tool calls become lines under the routed call's row. Its text and\n * turn events stay out of the conversation, which is the parent's; `handoff.result` reports the end.\n */\nfunction reduceChild(state: TranscriptState, event: AnyEvent): TranscriptState {\n const key = event.sessionKey ?? \"\"\n const mine = holds(key)\n // The child's return channel is how it hands back its answer, not work it did for the person.\n if (\"slug\" in event.data && event.data.slug === SUBMIT_ARTIFACT) return state\n switch (event.type) {\n case \"tool.call\":\n return withSubagent(state, mine, key, (view) =>\n view === undefined\n ? undefined\n : {\n ...view,\n lines: [\n ...view.lines,\n { callId: event.data.callId, text: `${event.data.slug} …` },\n ],\n },\n )\n case \"tool.result\": {\n const { slug, callId, ok, latencyMs } = event.data\n const text = `${slug} — ${ok ? \"ok\" : \"failed\"} · ${latencyMs} ms`\n return withSubagent(state, mine, key, (view) =>\n view === undefined\n ? undefined\n : {\n ...view,\n lines: view.lines.some((line) => line.callId === callId)\n ? view.lines.map((line) =>\n line.callId === callId ? { callId, text } : line,\n )\n : [...view.lines, { callId, text }],\n },\n )\n }\n case \"tool.gated\":\n return withSubagent(state, mine, key, (view) =>\n view === undefined\n ? undefined\n : {\n ...view,\n lines: [\n ...view.lines,\n { text: `${event.data.slug} — blocked: ${event.data.reason}` },\n ],\n },\n )\n default:\n return state\n }\n}\n\nfunction reduceEvent(state: TranscriptState, event: AnyEvent): TranscriptState {\n if (event.parentTurnId !== undefined) return reduceChild(state, event)\n switch (event.type) {\n case \"handoff.start\": {\n const { kind, name, callId, sessionKey, label, index } = event.data\n if (kind !== \"self\" || callId === undefined) return state\n return withSubagent(\n state,\n (item) => item.callId === callId,\n sessionKey,\n (view) =>\n view ?? {\n name: name ?? \"subagent\",\n sessionKey,\n lines: [],\n ...(label === undefined ? {} : { label }),\n ...(index === undefined ? {} : { index }),\n },\n )\n }\n\n case \"handoff.result\": {\n const { sessionKey, steps, tokens, outcome } = event.data\n const summary = `${steps} step${steps === 1 ? \"\" : \"s\"} · ${compactTokens(tokens.prompt + tokens.output)} tokens · ${outcome === \"ok\" ? \"ok\" : outcome.replace(\"_\", \" \")}`\n return withSubagent(state, holds(sessionKey), sessionKey, (view) =>\n view === undefined ? undefined : { ...view, summary },\n )\n }\n\n case \"turn.start\":\n return {\n ...state,\n live: { text: \"\", reasoning: \"\", last: undefined },\n status: \"thinking\",\n turnFrom: state.items.length,\n }\n\n case \"model.result\":\n // The step boundary. `model.result` is emitted once per model call, so this is where a step's\n // reasoning and text stop growing — no new event was needed to find it.\n return flushLive(state)\n\n case \"model.chunk\":\n return applyDelta(state, event.data.kind, event.data.delta)\n\n case \"tool.call\":\n // Committed the moment the call starts, not when it returns: a tool that takes eight\n // seconds must not leave the screen looking like a stalled model. Anything the model\n // streamed before deciding to call it is flushed first, so the reasoning sits above the\n // call it explains rather than below the call's result.\n return {\n ...append(\n flushLive(state),\n \"tool\",\n `${event.data.slug}${event.data.mutating ? \" (changes state)\" : \"\"}`,\n { callId: event.data.callId, pending: true },\n ),\n status: state.status === \"cancelling\" ? \"cancelling\" : \"working\",\n }\n\n case \"tool.result\": {\n const { slug, callId, ok, latencyMs, truncated } = event.data\n const text = `${slug} — ${ok ? \"ok\" : \"failed\"} · ${latencyMs} ms${truncated ? \" · observation trimmed\" : \"\"}`\n // The call's own row, completed. Matched on `callId` rather than on position, because calls\n // can overlap and \"the last tool row\" is then not the row this result belongs to.\n const at = state.items.findIndex(\n (item) => item.callId === callId && item.pending === true,\n )\n if (at === -1) {\n // No row to complete — a result for a call this transcript never saw. Appended rather\n // than dropped: an observation nobody can account for is exactly the thing worth seeing.\n return append(state, ok ? \"tool\" : \"error\", text)\n }\n const items = [...state.items]\n const item = items[at] as TranscriptItem\n items[at] = {\n id: item.id,\n role: ok ? \"tool\" : \"error\",\n text,\n callId,\n // The call's blocks outlive its own completion: the children's lines are the point.\n ...(item.subagents === undefined ? {} : { subagents: item.subagents }),\n }\n return { ...state, items }\n }\n\n case \"tool.gated\":\n // Deliberately visible. A blocked write is the one tool outcome a person must not have\n // to go looking for — and it is a `note` rather than an `error` because the wire spec is\n // explicit that this is not one: the turn continues and the model reports back.\n return append(state, \"note\", `${event.data.slug} — blocked: ${event.data.reason}`)\n\n case \"tool.repair\":\n // A silent repair is indistinguishable from a slow turn, and it costs a whole step. With no\n // slugs it is the runtime's nudge (14.123), not a tool that failed, and says so.\n return append(\n state,\n \"note\",\n event.data.slugs.length === 0\n ? `reply stopped short (${event.data.errors.join(\"; \")}), asking the model to finish`\n : `${event.data.slugs.join(\", \")} — could not be used, asking the model again`,\n )\n\n case \"model.retry\": {\n const { status, attempt, delayMs } = event.data\n return append(\n state,\n \"note\",\n `retrying after HTTP ${status} — attempt ${attempt}, waiting ${delayMs} ms`,\n )\n }\n\n case \"turn.end\": {\n const { reason, steps, tokens, durationMs } = event.data\n const stats: TurnStats = {\n promptTokens: tokens.prompt,\n outputTokens: tokens.output,\n durationMs,\n steps,\n reason,\n }\n\n // Whatever the last step streamed but never got a `model.result` for — a cancelled turn, or\n // one that ended on an error mid-stream. On a clean turn this is a no-op, because each step\n // committed itself as it finished.\n const next = flushLive(state)\n const from = state.turnFrom ?? 0\n // The reply this turn produced, which is where its cost belongs. Searched from the turn's own\n // first item: without that floor, a turn that produced no text would hang its statistics on\n // the *previous* turn's reply, which reads as that reply having cost twice.\n let reply = -1\n for (let at = next.items.length - 1; at >= from; at -= 1) {\n if (next.items[at]?.role === \"assistant\") {\n reply = at\n break\n }\n }\n // Why the turn stopped, from the formatter the plain path uses. Until this existed\n // `stats.reason` reached the reducer and was rendered nowhere, so a turn the step budget\n // cut off looked exactly like a completed one — which is how an agent came to stop\n // mid-task on \"Let me install it\" with nothing on screen explaining it.\n const why = endNote(reason, { steps, durationMs })\n\n if (reply === -1) {\n // A turn that produced nothing is not a normal outcome and must not look like one.\n const said = append(\n next,\n \"note\",\n why ?? (reason === \"final\" ? \"the model returned no text\" : \"\"),\n { stats },\n )\n return { ...said, live: undefined, status: \"idle\", turnFrom: undefined }\n }\n const items = [...next.items]\n const item = items[reply] as TranscriptItem\n items[reply] = { ...item, stats }\n const settled: TranscriptState = {\n ...next,\n items,\n live: undefined,\n status: \"idle\",\n turnFrom: undefined,\n }\n // Below the reply, not attached to it: the reply is what the model said, and this is what\n // the runtime did. Attaching it to the item would put a harness sentence in the model's\n // voice — the distinction `note` exists for.\n return why === undefined ? settled : append(settled, \"note\", why)\n }\n\n // `agent.error` used to fall through to here. It was declared in Phase 1, carried a\n // hint, and was emitted by **nothing, ever** — so this label was reachable only from a\n // test that constructed one by hand. Deleted rather than wired up: `error` already\n // carries every uncaught failure, and a second error event with no emitter is vocabulary\n // that makes the catalogue look richer than it is.\n case \"error\": {\n const { code, message, hint } = event.data\n return append(state, \"error\", `${code}: ${message}\\nhint: ${hint}`)\n }\n\n case \"context.dropped\": {\n const { messages, budget } = event.data\n // A note, not a stage line: the ladder decided what to compact and this is the budget\n // running out regardless. Worth saying because the agent is now answering without part of\n // the conversation, and nothing else on any surface would mention it.\n return append(\n state,\n \"note\",\n `context: ${messages} older message(s) did not fit the ${budget}-token budget and were left out`,\n )\n }\n\n case \"agent.warning\": {\n const { code, message } = event.data\n return append(state, \"note\", `${code}: ${message}`)\n }\n\n case \"context.pressure\":\n // A gauge, so it replaces rather than accumulates. `source` is deliberately not shown: it\n // is diagnostic and the status line has no room for a word that changes nothing a person\n // would do — it is on the event for whoever is reading events.\n return { ...state, pressure: event.data.fraction }\n\n case \"compaction.stage\": {\n const { stage, changed, before, after } = event.data\n // Only the stages that destroy detail get a line. trim, snip and micro are recoverable —\n // the conversation is still in the store and a snipped observation keeps a pointer — while\n // collapse and reset replace a span of the conversation with a summary, and a person who\n // was not watching the gauge still needs to know that happened.\n if (!changed || (stage !== \"collapse\" && stage !== \"reset\")) return state\n const what =\n stage === \"reset\"\n ? \"the conversation so far was replaced by a summary\"\n : \"earlier turns were replaced by a summary\"\n return append(state, \"note\", `context: ${what} (${before} → ${after} tokens)`)\n }\n\n case \"phase.changed\": {\n const { to, tools } = event.data\n // A line *and* the gauge. The line because a phase change is the reason the agent's\n // abilities changed mid-conversation, and a person scrolling back needs it where it\n // happened; the gauge because \"which phase am I in\" is a current-state question.\n const next = append(\n state,\n \"note\",\n `phase: now in ${to} · ${tools} tool${tools === 1 ? \"\" : \"s\"} available`,\n )\n return { ...next, phase: to }\n }\n\n case \"context.reset\": {\n const { warning } = event.data\n // The count itself is not shown — the note above already said what happened. A *second*\n // reset is a configuration problem rather than a busy session, and that is worth a line.\n return warning === undefined ? state : append(state, \"note\", `context: ${warning}`)\n }\n\n default:\n // Boot and bookkeeping events — `runtime.ready`, `store.ready`, `model.call`,\n // `context.assembled`. They belong to the banner and the status bar, not the transcript. Ignored explicitly so that a new event type added in a later\n // phase is inert here rather than a crash.\n return state\n }\n}\n\n/** What a renderer writes for a turn's cost. Kept here so the plain and rich paths agree. */\nexport function formatStats(stats: TurnStats): string {\n return `${stats.promptTokens} prompt · ${stats.outputTokens} output · ${stats.durationMs} ms`\n}\n\n/**\n * Opening banner — version, session, store, any turn a previous process left unfinished.\n *\n * One `banner` item rather than N notes, so the rich renderer can box it as a unit. The plain\n * path never calls this — it writes the lines directly — so plain output is unchanged by the\n * boxing.\n */\nexport function seed(notes: readonly string[]): TranscriptState {\n if (notes.length === 0) return EMPTY_TRANSCRIPT\n return append(EMPTY_TRANSCRIPT, \"banner\", notes.join(\"\\n\"))\n}\n\n/** One earlier message, as much of it as a transcript row needs. */\nexport interface PriorMessage {\n readonly role: \"user\" | \"assistant\"\n readonly text: string\n}\n\n/**\n * Put the conversation that already happened on the screen.\n *\n * Resuming used to paint an empty transcript over a full history: the messages reached the *model* and\n * never the person, so the banner said `17 message(s)` above a blank screen and the only honest reading\n * was that something had been lost. Rendering them is what makes that count verifiable.\n *\n * A separate function rather than a second argument to `seed`, because an optional parameter here would\n * have to distinguish \"no history\" from \"not asked for\" — and under `exactOptionalPropertyTypes` a\n * default parameter fires on an explicitly passed `undefined`, which has already cost this repo a\n * debugging round. `seedHistory(seed(banner), prior)` composes with nothing to remember.\n *\n * **Prose only.** Tool calls and observations are left out for the same reason they are left out of the\n * memory index: an observation is a wall of text a stranger wrote, and replaying forty of them above the\n * composer buries the conversation the person came back for. The turn statistics are left off too — they\n * were true of a process that has exited, and a cost line under a resumed reply reads as this session's.\n */\nexport function seedHistory(\n state: TranscriptState,\n messages: readonly PriorMessage[],\n): TranscriptState {\n let next = state\n for (const message of messages) {\n if (message.text.trim() === \"\") continue\n next = append(next, message.role, message.text)\n }\n return next\n}\n\n/** The most recent completed turn's cost, for the status bar. */\nexport function lastStats(items: readonly TranscriptItem[]): TurnStats | undefined {\n for (let i = items.length - 1; i >= 0; i -= 1) {\n const stats = items[i]?.stats\n if (stats !== undefined) return stats\n }\n return undefined\n}\n\n// ─── the finished conversation, as rows ──────────────────────────────────────────────────\n\n/**\n * Flatten items into the rows a windowed transcript scrolls through.\n *\n * ## Why rows rather than items\n *\n * Scrolling by item is the cheaper thing to build and the wrong unit. One assistant reply is a single\n * item and forty rows on screen, so an item-indexed window either shows the whole answer or none of it —\n * page-up from the bottom of a long reply would jump over the entire thing and land on the question\n * before it. Rows are what a reader moves through, so rows are what the offset counts.\n *\n * Wrapping happens here, not in Ink. A window has to know its content's height before it draws any of\n * it, and a count Ink might disagree with is a window off by however many lines wrapped — which shows up\n * as the last line of a reply hidden under the composer, intermittently, depending on the text.\n *\n * Pure, and one derivation for both halves of the frame: the component renders these rows and the layout\n * asks how many there are.\n */\nexport function transcriptRows(\n items: readonly TranscriptItem[],\n options: {\n readonly showReasoning: boolean\n readonly quiet: boolean\n readonly columns: number\n /** Reasoning blocks are shown whole rather than folded to `REASONING_FOLD_ROWS`. */\n readonly expandReasoning?: boolean\n },\n): readonly TranscriptRow[] {\n const rows: TranscriptRow[] = []\n const visible = items.filter((item) => item.role !== \"reasoning\" || options.showReasoning)\n\n /**\n * A row this renderer invented: a gap, a label, a fold notice, a stats line.\n *\n * `lead: 0` because there is no prefix to exclude, and `continuation: false` because it starts a line of\n * its own. Selectable, deliberately — a stats line or a banner note is text somebody may well want to\n * copy, and the cells worth excluding are the role prefixes, which are per-row and handled below.\n */\n const chrome = (row: Omit<TranscriptRow, \"lead\" | \"continuation\">): TranscriptRow => ({\n ...row,\n lead: 0,\n continuation: false,\n })\n\n for (const [at, item] of visible.entries()) {\n // A blank row between items, and never a trailing one. The rich transcript is read rather than\n // grepped, and two turns that touch each other read as one wall of text; a blank row at the end\n // would instead be a permanent gap above the composer.\n if (at > 0) rows.push(chrome({ key: `${item.id}:gap`, role: item.role, text: \"\" }))\n\n if (item.role === \"banner\") {\n // The banner keeps its content and loses its border. A bordered box inside a windowed list\n // costs two rows this module cannot count — Ink measures the frame, not us — and the frame\n // was decoration on a surface that is now itself a frame.\n const [title = \"\", ...lines] = item.text.split(\"\\n\")\n rows.push(chrome({ key: `${item.id}:title`, role: \"banner\", text: title, bold: true }))\n for (const [n, line] of lines.entries()) {\n for (const [w, wrapped] of wrapText(line, options.columns).entries()) {\n rows.push({\n key: `${item.id}:note-${n}-${w}`,\n role: \"banner\",\n text: wrapped,\n dim: true,\n lead: 0,\n // Only rows the *wrap* invented continue; a fresh source line does not.\n continuation: w > 0,\n })\n }\n }\n continue\n }\n\n const prefix = ROLE_PREFIX[item.role]\n const pad = \" \".repeat([...prefix].length)\n // The prefix is part of the first row's width and an indent on every row after it, so a reply\n // that wraps stays in one column instead of reading as a second message.\n const body = wrapText(item.text, Math.max(1, options.columns - [...prefix].length))\n\n if (item.role === \"reasoning\") {\n // A header row and an indented body, rather than a label wide enough to be the indent. Folded\n // unless asked for: the block is secondary, and at full length it routinely fills the screen\n // and pushes the reply it produced out of sight.\n const shown =\n options.expandReasoning === true\n ? body.length\n : Math.min(body.length, REASONING_FOLD_ROWS)\n const folded = body.length - shown\n rows.push(\n chrome({\n key: `${item.id}:label`,\n role: \"reasoning\",\n dim: true,\n text:\n folded > 0\n ? `· reasoning · ${body.length} rows · ⌥r expands`\n : `· reasoning · ${body.length} row${body.length === 1 ? \"\" : \"s\"}`,\n }),\n )\n for (const [n, line] of body.slice(0, shown).entries()) {\n rows.push({\n key: `${item.id}:${n}`,\n role: \"reasoning\",\n text: `${pad}${line}`,\n lead: pad.length,\n continuation: n > 0,\n })\n }\n if (folded > 0) {\n rows.push(\n chrome({\n key: `${item.id}:folded`,\n role: \"reasoning\",\n dim: true,\n text: `${pad}… ${folded} more row${folded === 1 ? \"\" : \"s\"}`,\n }),\n )\n }\n continue\n }\n\n for (const [n, line] of body.entries()) {\n rows.push({\n key: `${item.id}:${n}`,\n role: item.role,\n text: `${n === 0 ? prefix : pad}${line}`,\n // The prefix on the first row and its hanging indent on every row after it are the same\n // width, so one number covers both — and it is exactly the span a copy must drop.\n lead: [...prefix].length,\n continuation: n > 0,\n })\n }\n\n for (const [b, view] of (item.subagents ?? []).entries()) {\n // Folded with the reasoning blocks, by the same key: both are the detail behind a row, and\n // the reply is what a person reads first.\n const open = options.expandReasoning === true\n const status = view.summary ?? \"running\"\n const more =\n !open && view.lines.length > 0\n ? ` · ⌥r shows ${view.lines.length} call${view.lines.length === 1 ? \"\" : \"s\"}`\n : \"\"\n const label = view.label === undefined ? \"\" : ` · ${view.label}`\n for (const [n, line] of wrapText(\n `↳ subagent ${view.name}${label} · ${status}${more}`,\n Math.max(1, options.columns - pad.length),\n ).entries()) {\n rows.push(\n chrome({\n key: `${item.id}:sub${b}-${n}`,\n role: item.role,\n text: `${pad}${line}`,\n dim: true,\n }),\n )\n }\n if (open) {\n const inner = `${pad} `\n for (const [n, line] of view.lines.entries()) {\n for (const [w, wrapped] of wrapText(\n line.text,\n Math.max(1, options.columns - inner.length),\n ).entries()) {\n rows.push({\n key: `${item.id}:sub${b}-${n}-${w}`,\n role: item.role,\n text: `${inner}${wrapped}`,\n dim: true,\n lead: inner.length,\n continuation: w > 0,\n })\n }\n }\n }\n }\n\n if (item.stats !== undefined && !options.quiet) {\n rows.push(\n chrome({\n key: `${item.id}:stats`,\n role: item.role,\n text: ` ${formatStats(item.stats)}`,\n dim: true,\n }),\n )\n }\n }\n\n return rows\n}\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";mQAuCO,IAAM,EAAkD,CAC3D,CAAE,KAAM,OAAQ,KAAM,QAAS,QAAS,CAAC,EAAG,QAAS,WAAY,EACjE,CAKI,KAAM,SACN,KAAM,UACN,QAAS,CAAC,EACV,QAAS,kFACb,EACA,CAII,KAAM,UACN,KAAM,WACN,QAAS,CAAC,EACV,QACI,uFACR,EACA,CACI,KAAM,UACN,KAAM,WACN,QAAS,CAAC,EACV,QACI,sGACR,EACA,CACI,KAAM,QACN,KAAM,SACN,QAAS,CAAC,EACV,QAAS,kEACb,EACA,CAII,KAAM,MACN,KAAM,OACN,QAAS,CAAC,EACV,QACI,2GACR,EACA,CACI,KAAM,QACN,KAAM,SACN,QAAS,CAAC,EACV,QACI,kGACR,EACA,CACI,KAAM,OACN,KAAM,QACN,QAAS,CAAC,QAAS,IAAI,EAIvB,QAAS,qDACb,CACJ,EAoBa,GAAe,+CAUf,GAAmB,uDAEnB,EAA0C,CACnD,CACI,MAA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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
|