dispach 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +72 -13
  2. package/dist/{App-5a35bjkt.js → App-b1yrwrcq.js} +6 -6
  3. package/dist/{App-5a35bjkt.js.map → App-b1yrwrcq.js.map} +1 -1
  4. package/dist/{ConfigEditor-7nnc2ke6.js → ConfigEditor-n8hdw6r7.js} +2 -2
  5. package/dist/{KeyProbe-kbz0j6sm.js → KeyProbe-9jjeze5r.js} +2 -2
  6. package/dist/{Picker-2zjjt17a.js → Picker-hfeh1g6m.js} +3 -3
  7. package/dist/{Picker-2zjjt17a.js.map → Picker-hfeh1g6m.js.map} +1 -1
  8. package/dist/{SessionPicker-fyyvxy40.js → SessionPicker-zyqkg4dn.js} +3 -3
  9. package/dist/{SessionPicker-fyyvxy40.js.map → SessionPicker-zyqkg4dn.js.map} +1 -1
  10. package/dist/{SkillBrowser-x7r51zy0.js → SkillBrowser-3qdp8080.js} +3 -3
  11. package/dist/{SkillBrowser-x7r51zy0.js.map → SkillBrowser-3qdp8080.js.map} +1 -1
  12. package/dist/{WizardApp-v0dghsyw.js → WizardApp-vzpbydy3.js} +3 -3
  13. package/dist/{WizardApp-v0dghsyw.js.map → WizardApp-vzpbydy3.js.map} +1 -1
  14. package/dist/client.js +10 -10
  15. package/dist/client.js.map +4 -4
  16. package/dist/{config-9cv76yrk.js → config-g7za9x13.js} +5 -5
  17. package/dist/{config-9cv76yrk.js.map → config-g7za9x13.js.map} +1 -1
  18. package/dist/credential-npr6z8c8.js +19 -0
  19. package/dist/{credential-yxqj8x1f.js.map → credential-npr6z8c8.js.map} +2 -2
  20. package/dist/{index-zked16y4.js → index-02dn6m2j.js} +2 -2
  21. package/dist/{index-a4xqgdrm.js → index-0d93hyfc.js} +2 -2
  22. package/dist/{index-5t6wahx8.js → index-1c5113t4.js} +26 -26
  23. package/dist/index-1c5113t4.js.map +12 -0
  24. package/dist/{index-zxh0ntgf.js → index-258d8bzg.js} +2 -2
  25. package/dist/{index-nvm5hwe4.js → index-6p999cx4.js} +5 -5
  26. package/dist/{index-nvm5hwe4.js.map → index-6p999cx4.js.map} +1 -1
  27. package/dist/{index-73jfw4jp.js → index-6q4wf8e3.js} +2 -2
  28. package/dist/{index-r3wwvqzb.js → index-fecm8xe7.js} +16 -16
  29. package/dist/{index-r3wwvqzb.js.map → index-fecm8xe7.js.map} +2 -2
  30. package/dist/{index-83bqtze0.js → index-ff514z3y.js} +5 -5
  31. package/dist/{index-83bqtze0.js.map → index-ff514z3y.js.map} +1 -1
  32. package/dist/{index-17an0jqq.js → index-h9mw7b9d.js} +2 -2
  33. package/dist/{index-5x4dn0gg.js → index-hwpvhaza.js} +2 -2
  34. package/dist/{index-e0j1jafd.js → index-j55s3ehk.js} +5 -5
  35. package/dist/{index-e0j1jafd.js.map → index-j55s3ehk.js.map} +1 -1
  36. package/dist/{index-000rxxy3.js → index-mtn0g9vc.js} +4 -4
  37. package/dist/{index-000rxxy3.js.map → index-mtn0g9vc.js.map} +1 -1
  38. package/dist/{index-dwyr2kdm.js → index-qdbq8crg.js} +4 -4
  39. package/dist/{index-dwyr2kdm.js.map → index-qdbq8crg.js.map} +1 -1
  40. package/dist/{index-ez2mb28y.js → index-s9mbq7h6.js} +4 -4
  41. package/dist/{index-ez2mb28y.js.map → index-s9mbq7h6.js.map} +1 -1
  42. package/dist/{index-0b1hdwnm.js → index-tf71ap9v.js} +2 -2
  43. package/dist/index-ttwyrdjs.js +427 -0
  44. package/dist/index-ttwyrdjs.js.map +11 -0
  45. package/dist/{index-7z4sw2dm.js → index-tv4yv7d2.js} +162 -162
  46. package/dist/{index-7z4sw2dm.js.map → index-tv4yv7d2.js.map} +8 -8
  47. package/dist/{index-d69d6pkm.js → index-ty24n0jh.js} +35 -35
  48. package/dist/{index-d69d6pkm.js.map → index-ty24n0jh.js.map} +1 -1
  49. package/dist/{index-2wmsmcbr.js → index-vgc3y3rm.js} +4 -4
  50. package/dist/{index-2wmsmcbr.js.map → index-vgc3y3rm.js.map} +1 -1
  51. package/dist/index-whaw4b18.js +6 -0
  52. package/dist/index-whaw4b18.js.map +10 -0
  53. package/dist/index.js +50 -50
  54. package/dist/index.js.map +3 -3
  55. package/dist/lib/commands.d.ts.map +1 -1
  56. package/dist/lib/init-flow.d.ts +17 -4
  57. package/dist/lib/init-flow.d.ts.map +1 -1
  58. package/dist/lib/provision.d.ts.map +1 -1
  59. package/dist/{web-x77y8w3v.js → web-vkb16r62.js} +4 -4
  60. package/dist/{web-x77y8w3v.js.map → web-vkb16r62.js.map} +1 -1
  61. package/dist/wire.js +10 -10
  62. package/dist/wire.js.map +4 -4
  63. package/package.json +1 -1
  64. package/dist/credential-yxqj8x1f.js +0 -19
  65. package/dist/index-5t6wahx8.js.map +0 -12
  66. package/dist/index-9bkd0fdj.js +0 -427
  67. package/dist/index-9bkd0fdj.js.map +0 -11
  68. package/dist/index-xf178c4m.js +0 -6
  69. package/dist/index-xf178c4m.js.map +0 -10
  70. /package/dist/{ConfigEditor-7nnc2ke6.js.map → ConfigEditor-n8hdw6r7.js.map} +0 -0
  71. /package/dist/{KeyProbe-kbz0j6sm.js.map → KeyProbe-9jjeze5r.js.map} +0 -0
  72. /package/dist/{index-zked16y4.js.map → index-02dn6m2j.js.map} +0 -0
  73. /package/dist/{index-a4xqgdrm.js.map → index-0d93hyfc.js.map} +0 -0
  74. /package/dist/{index-zxh0ntgf.js.map → index-258d8bzg.js.map} +0 -0
  75. /package/dist/{index-73jfw4jp.js.map → index-6q4wf8e3.js.map} +0 -0
  76. /package/dist/{index-17an0jqq.js.map → index-h9mw7b9d.js.map} +0 -0
  77. /package/dist/{index-5x4dn0gg.js.map → index-hwpvhaza.js.map} +0 -0
  78. /package/dist/{index-0b1hdwnm.js.map → index-tf71ap9v.js.map} +0 -0
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{t,pt,Ft,he,Be,Ke}from"./index-7z4sw2dm.js";import{wr}from"./index-9bkd0fdj.js";import{At,To}from"./index-0b1hdwnm.js";import{l,p,d,c}from"./index-j7gyr5nx.js";import{chmodSync as E,existsSync as _,readFileSync as b,statSync as R,writeFileSync as N}from"node:fs";import{dirname as j,join as F}from"node:path";function x(e){if(!(e===""||/^["']/.test(e)||/\s/.test(e)||e.includes("#")||e!==e.trim()))return e;return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function w(e,n,o){let r=`${n}=${x(o)}`,i=e.split(`
2
+ import{t,pt,Ft,me,Be,Ke}from"./index-tv4yv7d2.js";import{wr}from"./index-ttwyrdjs.js";import{At,To}from"./index-tf71ap9v.js";import{l,p,d,c}from"./index-j7gyr5nx.js";import{chmodSync as E,existsSync as _,readFileSync as b,statSync as R,writeFileSync as N}from"node:fs";import{dirname as j,join as F}from"node:path";function x(e){if(!(e===""||/^["']/.test(e)||/\s/.test(e)||e.includes("#")||e!==e.trim()))return e;return`"${e.replace(/\\/g,"\\\\").replace(/"/g,"\\\"").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}function w(e,n,o){let r=`${n}=${x(o)}`,i=e.split(`
3
3
  `),s=new RegExp(`^\\s*(?:export\\s+)?${n}\\s*=`),a=i.findIndex((u)=>s.test(u));if(a!==-1){let u=i[a]??"",h=/^\s*export\s+/.exec(u)?.[0]??"";return{text:[...i.slice(0,a),`${h}${r}`,...i.slice(a+1)].join(`
4
4
  `),replaced:!0}}let f=e.replace(/\n+$/,"");return{text:f===""?`${r}
5
5
  `:`${f}
6
6
  ${r}
7
- `,replaced:!1}}function T(e){return F(j(e),".env")}async function Wn(e,n,o){let r=Ft(o),i=await pt({file:e,path:n.split("."),value:r});return{note:`${n} is now ${O(r)}`,reflowed:i.reflowed,before:i.before}}async function qn(e,n,o){let r=b(e,"utf8"),i=he(r,["channels"]);if(!Array.isArray(i))throw new t({code:"cli_config_no_channels",message:"This agent has no channels, so there is nobody to allow.",hint:"`config set <agent> channels '[{type: telegram, id: tg, tokenEnv: TELEGRAM_BOT_TOKEN, mode: longpoll}]'` declares one first."});let s=i.filter((g)=>typeof g==="object"&&g!==null&&!Array.isArray(g)),a=s.findIndex((g)=>String(g.id??"")===n);if(a===-1)throw new t({code:"cli_config_channel_unknown",message:`No channel with id "${n}".`,hint:`Declared: ${s.map((g)=>String(g.id??"")).join(", ")}.`,field:"channel"});let f=s[a],u=o.map((g)=>gr(g,String(f.type??""))),h=[...new Set(u)],m=Array.isArray(f.allowFrom)?f.allowFrom.map(String):[],A=await pt({file:e,path:["channels"],value:s.map((g,S)=>S===a?{...g,allowFrom:h}:g)});return{note:h.length===0?`${n} now allows nobody, which refuses every message`:`${n} now allows ${h.join(", ")}`,reflowed:A.reflowed,before:m}}function Gn(e,n,o){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw new t({code:"cli_config_env_name_invalid",message:`"${n}" is not an environment variable name.`,hint:"Letters, digits and underscores, not starting with a digit — MODEL_API_KEY, TELEGRAM_BOT_TOKEN.",field:"name"});if(o==="")throw new t({code:"cli_config_env_empty",message:`An empty value for ${n} would not start the agent.`,hint:"A variable set to nothing fails the load exactly as a missing one does. Nothing was written."});let r=T(e),i=_(r)?b(r,"utf8"):"",s=w(i,n,o);N(r,s.text,{encoding:"utf8",mode:384});let a=(R(r).mode&63)!==0;if(a)E(r,384);return{note:`${n} ${s.replaced?"replaced":"written"} in ${r}${a?" (tightened to 0600)":""}`,reflowed:!1,before:void 0}}function gr(e,n){let o=e.trim();if(o==="")throw new t({code:"cli_config_handle_missing",message:"No handle given.",hint:"On Telegram that is the username, not the display name.",field:"handle"});if(n!=="telegram")return o;let r=wr(o);if(!r.ok)throw new t({code:"cli_config_handle_invalid",message:`"${o}" ${r.reason}`,hint:"A handle that cannot exist matches nobody, and the only symptom is the bot silently refusing every message from the person it was set up for.",field:"handle"});return r.value}function O(e){if(e==="")return"empty";if(typeof e==="string")return e;return JSON.stringify(e)}function Tt(e){if(e===void 0||e===null)return"(not set)";if(typeof e==="string")return e===""?'""':e;if(typeof e==="boolean"||typeof e==="number")return String(e);return JSON.stringify(e)}function V(e){return e.split(/[.[]/)[0]??e}function fo(e,n){let o=[`${n}`,""],r=new Map;for(let s of e){let a=V(s.setting.path);r.set(a,[...r.get(a)??[],s])}let i=!0;for(let[s,a]of r){o.push(p(s,i)),i=!1;for(let f of a){let u=f.setting.agentListed?"":" · yours only",h=f.setting.via===void 0?"":` · set with \`${f.setting.via}\``,m=f.setting.confirm===void 0?"":" · asks first";o.push(l([{label:f.setting.path,value:Tt(f.value)}]),c(`${f.setting.means}${u}${h}${m}`,4))}}return o.push("","A change takes effect the next time the agent starts. `yours only` marks a field the agent is","refused: what it may do is its to ask for, where it writes and who may reach it are yours."),o.join(`
7
+ `,replaced:!1}}function T(e){return F(j(e),".env")}async function Wn(e,n,o){let r=Ft(o),i=await pt({file:e,path:n.split("."),value:r});return{note:`${n} is now ${O(r)}`,reflowed:i.reflowed,before:i.before}}async function qn(e,n,o){let r=b(e,"utf8"),i=me(r,["channels"]);if(!Array.isArray(i))throw new t({code:"cli_config_no_channels",message:"This agent has no channels, so there is nobody to allow.",hint:"`config set <agent> channels '[{type: telegram, id: tg, tokenEnv: TELEGRAM_BOT_TOKEN, mode: longpoll}]'` declares one first."});let s=i.filter((g)=>typeof g==="object"&&g!==null&&!Array.isArray(g)),a=s.findIndex((g)=>String(g.id??"")===n);if(a===-1)throw new t({code:"cli_config_channel_unknown",message:`No channel with id "${n}".`,hint:`Declared: ${s.map((g)=>String(g.id??"")).join(", ")}.`,field:"channel"});let f=s[a],u=o.map((g)=>gr(g,String(f.type??""))),h=[...new Set(u)],m=Array.isArray(f.allowFrom)?f.allowFrom.map(String):[],A=await pt({file:e,path:["channels"],value:s.map((g,S)=>S===a?{...g,allowFrom:h}:g)});return{note:h.length===0?`${n} now allows nobody, which refuses every message`:`${n} now allows ${h.join(", ")}`,reflowed:A.reflowed,before:m}}function Gn(e,n,o){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw new t({code:"cli_config_env_name_invalid",message:`"${n}" is not an environment variable name.`,hint:"Letters, digits and underscores, not starting with a digit — MODEL_API_KEY, TELEGRAM_BOT_TOKEN.",field:"name"});if(o==="")throw new t({code:"cli_config_env_empty",message:`An empty value for ${n} would not start the agent.`,hint:"A variable set to nothing fails the load exactly as a missing one does. Nothing was written."});let r=T(e),i=_(r)?b(r,"utf8"):"",s=w(i,n,o);N(r,s.text,{encoding:"utf8",mode:384});let a=(R(r).mode&63)!==0;if(a)E(r,384);return{note:`${n} ${s.replaced?"replaced":"written"} in ${r}${a?" (tightened to 0600)":""}`,reflowed:!1,before:void 0}}function gr(e,n){let o=e.trim();if(o==="")throw new t({code:"cli_config_handle_missing",message:"No handle given.",hint:"On Telegram that is the username, not the display name.",field:"handle"});if(n!=="telegram")return o;let r=wr(o);if(!r.ok)throw new t({code:"cli_config_handle_invalid",message:`"${o}" ${r.reason}`,hint:"A handle that cannot exist matches nobody, and the only symptom is the bot silently refusing every message from the person it was set up for.",field:"handle"});return r.value}function O(e){if(e==="")return"empty";if(typeof e==="string")return e;return JSON.stringify(e)}function Tt(e){if(e===void 0||e===null)return"(not set)";if(typeof e==="string")return e===""?'""':e;if(typeof e==="boolean"||typeof e==="number")return String(e);return JSON.stringify(e)}function V(e){return e.split(/[.[]/)[0]??e}function fo(e,n){let o=[`${n}`,""],r=new Map;for(let s of e){let a=V(s.setting.path);r.set(a,[...r.get(a)??[],s])}let i=!0;for(let[s,a]of r){o.push(p(s,i)),i=!1;for(let f of a){let u=f.setting.agentListed?"":" · yours only",h=f.setting.via===void 0?"":` · set with \`${f.setting.via}\``,m=f.setting.confirm===void 0?"":" · asks first";o.push(l([{label:f.setting.path,value:Tt(f.value)}]),c(`${f.setting.means}${u}${h}${m}`,4))}}return o.push("","A change takes effect the next time the agent starts. `yours only` marks a field the agent is","refused: what it may do is its to ask for, where it writes and who may reach it are yours."),o.join(`
8
8
  `)}function ho(e,n){return[l([{label:e.path,value:Tt(n)}]),c(e.means,4),...e.toAgent===void 0?[]:[c(`to the agent: ${e.toAgent}`,4)]].join(`
9
9
  `)}function mo(e,n){if(e.confirm===void 0)return;if(e.path==="tools.untrusted.onMutate"&&String(n).toLowerCase()!=="allow")return;return e.confirm}function po(e){let n=[l([{label:"set",value:`${e.path} = ${Tt(e.after)}`},{label:"was",value:e.before===void 0?"(not set)":Tt(e.before)},{label:"file",value:e.file}])];if(e.reflowed)n.push("",d("the block could not be edited in place, so the file was re-serialised — it is valid, and comments may have moved"));if(e.running!==void 0)n.push("",d(`this agent is running (pid ${e.running.pid}, ${e.running.mode}) and holds its settings for its lifetime — the change applies after ${e.restartHint}`));for(let o of e.pending)n.push(d(`${o.name} is not set — ${o.why}`)),n.push(d(`fill it in with \`config env <agent> ${o.name}\``));return n.join(`
10
- `)}function go(){return Ke.filter((e)=>e.via===void 0&&!/[[<]/.test(e.path)).map((e)=>e.path)}function _t(e){if(typeof e!=="object"||e===null)return[];let n=e,o=[],r=(f,u)=>{if(typeof f==="string"&&f!=="")o.push({name:f,why:u})},i=y(n.model);for(let f of["main","selector","compactor"]){let u=y(i?.[f]);r(u?.apiKeyEnv,"the manifest will not load until it is set")}if(Array.isArray(n.channels))for(let f of n.channels){let u=y(f);if(u===void 0||u.enabled===!1)continue;r(u.tokenEnv,`the ${String(u.id??u.type??"channel")} channel is read at boot, so the agent will not start until it is set`)}let s=y(n.server);if(s?.enabled===!0)r(s.tokenEnv,"the HTTP API would accept unauthenticated requests. This does not stop the agent starting");let a=y(y(n.tools)?.providers);for(let[f,u]of Object.entries(a??{}))r(y(u)?.apiKeyEnv,`the ${f} provider's tools will not work until it is set`);return o}function y(e){if(typeof e!=="object"||e===null||Array.isArray(e))return;return e}function Zn(e,n){return e.filter((o)=>n[o.name]===void 0||n[o.name]==="")}function k(e,n){let o=[],r=new Map;for(let i of e){if(i.setting.via!==void 0||/[[<]/.test(i.setting.path))continue;let s=i.setting.path.split(".")[0]??i.setting.path;r.set(s,[...r.get(s)??[],i])}for(let[i,s]of r){o.push({kind:"heading",label:i});for(let a of s)o.push({kind:"setting",setting:a.setting,value:a.value})}if(n.channels.length>0){o.push({kind:"heading",label:"who may reach it"});for(let i of n.channels)o.push({kind:"allow",channelId:i.id,channelType:i.type,handles:i.allowFrom})}if(n.secrets.length>0){o.push({kind:"heading",label:"secrets — written to the .env, never shown"});for(let i of n.secrets)o.push({kind:"secret",name:i.name,why:i.why,present:n.present(i.name)})}return o}import{readFileSync as v}from"node:fs";function Vn(e){let n=v(e,"utf8");return Ke.map((o)=>{if(o.path==="channels[].allowFrom"){let r=he(n,["channels"]);if(!Array.isArray(r))return{setting:o,value:void 0};let i={};for(let s of r){if(typeof s!=="object"||s===null)continue;let a=s;if(typeof a.id!=="string")continue;i[a.id]=a.allowFrom??[]}return{setting:o,value:Object.keys(i).length===0?void 0:i}}if(o.path==="tools.providers.<id>.writeRoots"){let r=he(n,["tools","providers"]);if(typeof r!=="object"||r===null||Array.isArray(r))return{setting:o,value:void 0};let i={};for(let[s,a]of Object.entries(r)){if(typeof a!=="object"||a===null)continue;let f=a.writeRoots;if(f!==void 0)i[s]=f}return{setting:o,value:Object.keys(i).length===0?void 0:i}}return{setting:o,value:he(n,o.path.split("."))}})}function at(e){let n=v(e,"utf8"),o=Be(n),r=At(e),i=he(n,["channels"]);return k(Vn(e),{channels:(Array.isArray(i)?i:[]).filter((s)=>typeof s==="object"&&s!==null&&!Array.isArray(s)).map((s)=>({id:String(s.id??""),type:String(s.type??""),allowFrom:Array.isArray(s.allowFrom)?s.allowFrom.map(String):[]})).filter((s)=>s.id!==""),secrets:_t(o),present:(s)=>To(r,s)})}async function rn(e,n,o){switch(n.kind){case"setting":{if(o.trim()==="")throw new t({code:"cli_config_value_missing",message:`No value given for ${n.setting.path}.`,hint:'A bare word, a number, a list as ["a", "b"], or a map as {k: v}.',field:"value"});return(await Wn(e,n.setting.path,o)).note}case"allow":{let r=o.trim()===""?[]:o.trim().split(/\s+/);return(await qn(e,n.channelId,r)).note}case"secret":return Gn(e,n.name,o).note;case"heading":return""}}
10
+ `)}function go(){return Ke.filter((e)=>e.via===void 0&&!/[[<]/.test(e.path)).map((e)=>e.path)}function _t(e){if(typeof e!=="object"||e===null)return[];let n=e,o=[],r=(f,u)=>{if(typeof f==="string"&&f!=="")o.push({name:f,why:u})},i=y(n.model);for(let f of["main","selector","compactor"]){let u=y(i?.[f]);r(u?.apiKeyEnv,"the manifest will not load until it is set")}if(Array.isArray(n.channels))for(let f of n.channels){let u=y(f);if(u===void 0||u.enabled===!1)continue;r(u.tokenEnv,`the ${String(u.id??u.type??"channel")} channel is read at boot, so the agent will not start until it is set`)}let s=y(n.server);if(s?.enabled===!0)r(s.tokenEnv,"the HTTP API would accept unauthenticated requests. This does not stop the agent starting");let a=y(y(n.tools)?.providers);for(let[f,u]of Object.entries(a??{}))r(y(u)?.apiKeyEnv,`the ${f} provider's tools will not work until it is set`);return o}function y(e){if(typeof e!=="object"||e===null||Array.isArray(e))return;return e}function Zn(e,n){return e.filter((o)=>n[o.name]===void 0||n[o.name]==="")}function k(e,n){let o=[],r=new Map;for(let i of e){if(i.setting.via!==void 0||/[[<]/.test(i.setting.path))continue;let s=i.setting.path.split(".")[0]??i.setting.path;r.set(s,[...r.get(s)??[],i])}for(let[i,s]of r){o.push({kind:"heading",label:i});for(let a of s)o.push({kind:"setting",setting:a.setting,value:a.value})}if(n.channels.length>0){o.push({kind:"heading",label:"who may reach it"});for(let i of n.channels)o.push({kind:"allow",channelId:i.id,channelType:i.type,handles:i.allowFrom})}if(n.secrets.length>0){o.push({kind:"heading",label:"secrets — written to the .env, never shown"});for(let i of n.secrets)o.push({kind:"secret",name:i.name,why:i.why,present:n.present(i.name)})}return o}import{readFileSync as v}from"node:fs";function Vn(e){let n=v(e,"utf8");return Ke.map((o)=>{if(o.path==="channels[].allowFrom"){let r=me(n,["channels"]);if(!Array.isArray(r))return{setting:o,value:void 0};let i={};for(let s of r){if(typeof s!=="object"||s===null)continue;let a=s;if(typeof a.id!=="string")continue;i[a.id]=a.allowFrom??[]}return{setting:o,value:Object.keys(i).length===0?void 0:i}}if(o.path==="tools.providers.<id>.writeRoots"){let r=me(n,["tools","providers"]);if(typeof r!=="object"||r===null||Array.isArray(r))return{setting:o,value:void 0};let i={};for(let[s,a]of Object.entries(r)){if(typeof a!=="object"||a===null)continue;let f=a.writeRoots;if(f!==void 0)i[s]=f}return{setting:o,value:Object.keys(i).length===0?void 0:i}}return{setting:o,value:me(n,o.path.split("."))}})}function at(e){let n=v(e,"utf8"),o=Be(n),r=At(e),i=me(n,["channels"]);return k(Vn(e),{channels:(Array.isArray(i)?i:[]).filter((s)=>typeof s==="object"&&s!==null&&!Array.isArray(s)).map((s)=>({id:String(s.id??""),type:String(s.type??""),allowFrom:Array.isArray(s.allowFrom)?s.allowFrom.map(String):[]})).filter((s)=>s.id!==""),secrets:_t(o),present:(s)=>To(r,s)})}async function rn(e,n,o){switch(n.kind){case"setting":{if(o.trim()==="")throw new t({code:"cli_config_value_missing",message:`No value given for ${n.setting.path}.`,hint:'A bare word, a number, a list as ["a", "b"], or a map as {k: v}.',field:"value"});return(await Wn(e,n.setting.path,o)).note}case"allow":{let r=o.trim()===""?[]:o.trim().split(/\s+/);return(await qn(e,n.channelId,r)).note}case"secret":return Gn(e,n.name,o).note;case"heading":return""}}
11
11
  export{Wn,qn,Gn,gr,Tt,fo,ho,mo,po,go,_t,Zn,Vn,at,rn};
12
12
 
13
- //# debugId=751BD955E8FE876E64756E2164756E21
14
- //# sourceMappingURL=index-83bqtze0.js.map
13
+ //# debugId=D81357B6476A51F364756E2164756E21
14
+ //# sourceMappingURL=index-ff514z3y.js.map
@@ -8,6 +8,6 @@
8
8
  "/**\n * What the config editor shows, and what one confirmed row does. Reads files; no Ink.\n *\n * Its own module because **both hosts import it statically** — `config.ts` for the standalone editor and\n * `App.tsx` for the pane — while `index.ts` imports `config.ts` *dynamically* to keep Ink off the\n * startup path. A module reached both ways makes `bun build --splitting` emit its exports twice and the\n * binary refuses to parse, and `bun test` sails straight through it because tests import source. So the\n * shared half lives where nothing has to be lazy about it.\n */\n\nimport { readFileSync } from \"node:fs\"\nimport { HarnessError, manifestDocument, manifestValueAt, SETTINGS } from \"@dispach/core\"\nimport { applyAllow, applySecret, applySet } from \"#lib/config-apply\"\nimport type { EditorRow } from \"#lib/config-editor\"\nimport { agentEnv, isSet } from \"#lib/config-env\"\nimport { editorRows, envNeeds, type SettingValue } from \"#lib/config-view\"\n\n/**\n * Every setting with whatever the file currently holds.\n *\n * Two rows do not have a readable dotted path — `allowFrom` lives inside a list entry and `writeRoots`\n * inside a provider — so they are gathered by walking the block instead. Shown rather than omitted: a\n * field missing from a listing reads as \"no such concept\", which is the same reasoning that puts a\n * `none` row in slot 2 instead of leaving the line out.\n */\nexport function currentValues(manifestPath: string): readonly SettingValue[] {\n const source = readFileSync(manifestPath, \"utf8\")\n return SETTINGS.map((setting) => {\n if (setting.path === \"channels[].allowFrom\") {\n const channels = manifestValueAt(source, [\"channels\"])\n if (!Array.isArray(channels)) return { setting, value: undefined }\n const byId: Record<string, unknown> = {}\n for (const entry of channels) {\n if (typeof entry !== \"object\" || entry === null) continue\n const row = entry as { id?: unknown; allowFrom?: unknown }\n if (typeof row.id !== \"string\") continue\n byId[row.id] = row.allowFrom ?? []\n }\n return { setting, value: Object.keys(byId).length === 0 ? undefined : byId }\n }\n if (setting.path === \"tools.providers.<id>.writeRoots\") {\n const providers = manifestValueAt(source, [\"tools\", \"providers\"])\n if (typeof providers !== \"object\" || providers === null || Array.isArray(providers)) {\n return { setting, value: undefined }\n }\n const roots: Record<string, unknown> = {}\n for (const [id, config] of Object.entries(providers as Record<string, unknown>)) {\n if (typeof config !== \"object\" || config === null) continue\n const found = (config as { writeRoots?: unknown }).writeRoots\n if (found !== undefined) roots[id] = found\n }\n return { setting, value: Object.keys(roots).length === 0 ? undefined : roots }\n }\n return { setting, value: manifestValueAt(source, setting.path.split(\".\")) }\n })\n}\n\n/**\n * The rows the editor shows, read fresh from the manifest and its `.env`.\n *\n * Exported because both hosts build them: this command mounts the editor standalone, and the chat opens\n * it as a pane. Two builders would drift on the first row either one grew.\n */\nexport function editorRowsFor(manifestPath: string): readonly EditorRow[] {\n const source = readFileSync(manifestPath, \"utf8\")\n const document = manifestDocument(source)\n const env = agentEnv(manifestPath)\n const channels = manifestValueAt(source, [\"channels\"])\n\n return editorRows(currentValues(manifestPath), {\n channels: (Array.isArray(channels) ? channels : [])\n .filter(\n (entry): entry is Record<string, unknown> =>\n typeof entry === \"object\" && entry !== null && !Array.isArray(entry),\n )\n .map((entry) => ({\n id: String(entry.id ?? \"\"),\n type: String(entry.type ?? \"\"),\n allowFrom: Array.isArray(entry.allowFrom) ? entry.allowFrom.map(String) : [],\n }))\n .filter((entry) => entry.id !== \"\"),\n secrets: envNeeds(document),\n // The agent's layered environment, not this process's — `ambientEnv` alone never adds the file\n // beside the manifest, which made a row read `(not set)` right after somebody set it.\n present: (name: string) => isSet(env, name),\n })\n}\n\n/**\n * Perform one row's edit. The editor's only asynchronous part, and the plain commands' path too.\n *\n * A blank buffer means different things per row and each is the useful reading: no handles is \"allow\n * nobody\", which is a real thing to want; an empty *setting* would be a value nobody typed on purpose;\n * and an empty secret is refused by `applySecret`, because a variable set to nothing fails the load\n * exactly as a missing one does.\n */\nexport async function applyEditorRow(\n manifestPath: string,\n row: EditorRow,\n raw: string,\n): Promise<string> {\n switch (row.kind) {\n case \"setting\": {\n if (raw.trim() === \"\") {\n throw new HarnessError({\n code: \"cli_config_value_missing\",\n message: `No value given for ${row.setting.path}.`,\n hint: 'A bare word, a number, a list as [\"a\", \"b\"], or a map as {k: v}.',\n field: \"value\",\n })\n }\n return (await applySet(manifestPath, row.setting.path, raw)).note\n }\n case \"allow\": {\n const handles = raw.trim() === \"\" ? [] : raw.trim().split(/\\s+/)\n return (await applyAllow(manifestPath, row.channelId,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C9C,CAAC,EAWL,eAAsB,EAAc,CAChC,EACA,EACA,EACe,CACf,OAAQ,EAAI,UACH,UAAW,CACZ,GAAI,EAAI,KAAK,IAAM,GACf,MAAM,IAAI,EAAa,CACnB,KAAM,2BACN,QAAS,sBAAsB,EAAI,QAAQ,QAC3C,KAAM,mEACN,MAAO,OACX,CAAC,EAEL,OAAQ,MAAM,GAAS,EAAc,EAAI,QAAQ,KAAM,CAAG,GAAG,IACjE,KACK,QAAS,CACV,IAAM,EAAU,EAAI,KAAK,IAAM,GAAK,CAAC,EAAI,EAAI,KAAK,EAAE,MAAM,KAAK,EAC/D,OAAQ,MAAM,GAAW,EAAc,EAAI,UAAW,CAAO,GAAG,IACpE,KACK,SACD,OAAO,GAAY,EAAc,EAAI,KAAM,CAAG,EAAE,SAC/C,UACD,MAAO",
11
- "debugId": "751BD955E8FE876E64756E2164756E21",
11
+ "debugId": "D81357B6476A51F364756E2164756E21",
12
12
  "names": []
13
13
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{S}from"./index-d4x6yvqh.js";import{Rn,In,Ge,Ze,Ve}from"./index-2wmsmcbr.js";var s=" · ",l=3;function Po(n,e){let t=[{kind:"title",text:S(n.title,e)}],r=n.agent===void 0?n.summary:[`${n.agent.name}${s}${n.agent.model}`,n.summary].filter((a)=>a!=="").join(s);if(r!=="")t.push({kind:"summary",text:S(r,e)});let i=n.state??[];if(i.length>0)t.push({kind:"state",text:S(i.map((a)=>a.label).join(s),e)});let o=n.warnings??[];for(let a of o.slice(0,l))t.push({kind:"warning",text:S(`⚠ ${a}`,e)});if(o.length>l)t.push({kind:"warning",text:S(`⚠ and ${o.length-l} more`,e)});return t}function Mo(n,e){let t=n.map((i)=>`${i.key} ${i.does}`),r="";for(let i of t){let o=r===""?i:`${r}${s}${i}`;if([...o].length>e)break;r=o}return r===""?S(t[0]??"",e):r}function rr(n,e){let t=[n.title];if(n.summary!=="")t.push(n.summary);if(n.agent!==void 0)t.push(n.agent.name,n.agent.model);let r=n.warnings??[];if(r.length>0)t.push(`⚠ ${r.length} note${r.length===1?"":"s"} at the top`);return S(t.join(s),e)}var Lo={key:"q",does:"back"};function u(n,e){return n===void 0||n<=0?e:n}function q(n,e){return Math.max(Rn,Math.min(In,u(n,e)))}function Do(n,e){return Math.max(Ge,Math.min(Ze,u(n,e)-Ve))}
2
+ import{S}from"./index-d4x6yvqh.js";import{Rn,In,Ge,Ze,Ve}from"./index-vgc3y3rm.js";var s=" · ",l=3;function Po(n,e){let t=[{kind:"title",text:S(n.title,e)}],r=n.agent===void 0?n.summary:[`${n.agent.name}${s}${n.agent.model}`,n.summary].filter((a)=>a!=="").join(s);if(r!=="")t.push({kind:"summary",text:S(r,e)});let i=n.state??[];if(i.length>0)t.push({kind:"state",text:S(i.map((a)=>a.label).join(s),e)});let o=n.warnings??[];for(let a of o.slice(0,l))t.push({kind:"warning",text:S(`⚠ ${a}`,e)});if(o.length>l)t.push({kind:"warning",text:S(`⚠ and ${o.length-l} more`,e)});return t}function Mo(n,e){let t=n.map((i)=>`${i.key} ${i.does}`),r="";for(let i of t){let o=r===""?i:`${r}${s}${i}`;if([...o].length>e)break;r=o}return r===""?S(t[0]??"",e):r}function rr(n,e){let t=[n.title];if(n.summary!=="")t.push(n.summary);if(n.agent!==void 0)t.push(n.agent.name,n.agent.model);let r=n.warnings??[];if(r.length>0)t.push(`⚠ ${r.length} note${r.length===1?"":"s"} at the top`);return S(t.join(s),e)}var Lo={key:"q",does:"back"};function u(n,e){return n===void 0||n<=0?e:n}function q(n,e){return Math.max(Rn,Math.min(In,u(n,e)))}function Do(n,e){return Math.max(Ge,Math.min(Ze,u(n,e)-Ve))}
3
3
  export{Po,Mo,rr,Lo,q,Do};
4
4
 
5
5
  //# debugId=CCA62814AD4503FC64756E2164756E21
6
- //# sourceMappingURL=index-17an0jqq.js.map
6
+ //# sourceMappingURL=index-h9mw7b9d.js.map
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{e,t}from"./index-7z4sw2dm.js";import{Rt,le,It,Ot,Ao}from"./index-xf178c4m.js";class se extends t{static ERROR_NAME="UsageError"}function D(n,s){let i=Array.from({length:s.length+1},(r,f)=>f);for(let r=1;r<=n.length;r+=1){let f=[r];for(let u=1;u<=s.length;u+=1){let h=(i[u-1]??0)+(n[r-1]===s[u-1]?0:1),c=(f[u-1]??0)+1,b=(i[u]??0)+1;f.push(Math.min(h,c,b))}i=f}return i[s.length]??Math.max(n.length,s.length)}function R(n,s){let i,r=Number.POSITIVE_INFINITY;for(let f of s){let u=D(n,f);if(u<r)r=u,i=f}return i!==void 0&&r<=Math.max(2,Math.floor(n.length/3))?i:void 0}class N{#e;#t;constructor(n,s){this.#e=n,this.#t=s}#n(n,s){let i=this.#t.get(n);if(i===void 0)throw new se({code:"cli_flag_not_declared",message:`No flag "${n}" is declared for this command.`,hint:"This is a bug in the CLI, not in the command line. Add the flag to lib/commands.ts or fix the reader."});if(i.kind!==s)throw new se({code:"cli_flag_kind_mismatch",message:`Flag "${n}" is declared as ${i.kind} but was read as ${s}.`,hint:"This is a bug in the CLI. The reader and lib/commands.ts disagree."});return this.#e.get(n)}str(n){let s=this.#n(n,"string");return typeof s==="string"?s:void 0}num(n){let s=this.#n(n,"number");return typeof s==="number"?s:void 0}bool(n){return this.#n(n,"boolean")===!0}has(n){return this.#e.has(n)}}function g(n,s,i,r){return r===void 0?{code:n,message:s,hint:i}:{code:n,message:s,hint:i,field:r}}function v(n){let s=n[0];return new se({code:"cli_usage",message:n.length===1&&s!==void 0?s.message:`${n.length} problems with the command line.`,hint:n.length===1&&s!==void 0?s.hint:"Each problem below names the flag and its fix.",...s?.field===void 0?{}:{field:s.field},details:n})}function E(n,s,i){let r=Number(s);if(s.trim()===""||!Number.isFinite(r))return g("cli_flag_not_a_number",`${i} expects a number, got ${JSON.stringify(s)}.`,`Pass a number, as in ${i} 50. The old parser silently used the default here, which made a typo look like it worked.`,i);if(n.integer===!0&&!Number.isInteger(r))return g("cli_flag_not_an_integer",`${i} expects a whole number, got ${s}.`,`Drop the fractional part: ${i} ${Math.trunc(r)}.`,i);if(n.min!==void 0&&r<n.min)return g("cli_flag_below_min",`${i} must be at least ${n.min}, got ${r}.`,`Pass ${n.min} or more.`,i);return r}function jr(n){let s=n[0];if(s===void 0)return{kind:"usage"};if(s.startsWith("-")){let a=new Set(Rt.flatMap((o)=>o.short===void 0?[`--${o.name}`]:[`--${o.name}`,`-${o.short}`])),l=n.filter((o)=>!a.has(o));if(l.length>0)throw v([g("cli_no_command","No command given.",`Run \`${e.slug} --help\` for the command list. Commands are ${le.map((o)=>o.name).join(", ")}.`,l[0])]);if(n.includes("--version")||n.includes("-v"))return{kind:"version"};if(n.includes("--help")||n.includes("-h"))return{kind:"help",command:void 0};return{kind:"usage"}}let i=It(s);if(i===void 0){let a=R(s,le.map((l)=>l.name));throw v([g("cli_unknown_command",`Unknown command "${s}".`,a===void 0?`Run \`${e.slug} --help\` for the command list.`:`Did you mean "${a}"? Run \`${e.slug} --help\` for the full list.`,s)])}let r=new Map(Ot(i).map((a)=>[a.name,a])),f=new Map(Ot(i).filter((a)=>a.short!==void 0).map((a)=>[a.short,a])),u=new Map,h=[],c=[],b=!1,F=(a,l,o)=>{if(l===""){c.push(g("cli_flag_empty_value",`${o} was given an empty value.`,"Pass a value, or drop the flag entirely to use the default.",o));return}if(a.kind==="number"){let d=E(a,l,o);if(typeof d==="number")u.set(a.name,d);else c.push(d);return}u.set(a.name,l)};for(let a=1;a<n.length;a+=1){let l=n[a];if(l===void 0)continue;if(b){h.push(l);continue}if(l==="--"){b=!0;continue}if(l.startsWith("--")){let o=l.slice(2),d=o.indexOf("="),p=d===-1?o:o.slice(0,d),m=r.get(p);if(m===void 0){let y=Ao(p,i.name),M=R(p,[...r.keys()]);c.push(g(y.length>0?"cli_flag_wrong_command":"cli_unknown_flag",y.length>0?`${i.name} does not accept --${p}.`:`Unknown flag --${p}.`,y.length>0?`--${p} is accepted by: ${y.join(", ")}.`:M===void 0?`Run \`${e.slug} ${i.name} --help\` for the flags this command accepts.`:`Did you mean --${M}?`,`--${p}`));continue}let _=`--${p}`;if(m.kind==="boolean"){if(d!==-1){c.push(g("cli_flag_takes_no_value",`${_} is a switch and takes no value.`,`Drop the "=${o.slice(d+1)}" — pass ${_} on its own.`,_));continue}u.set(m.name,!0);continue}if(d!==-1){F(m,o.slice(d+1),_);continue}let k=n[a+1];if(m.bare!==void 0&&(k===void 0||k.startsWith("-"))){u.set(m.name,m.bare);continue}if(k===void 0){c.push(g("cli_flag_needs_value",`${_} needs a value.`,`Pass one, as in ${_} <${m.placeholder??"value"}>.`,_));continue}F(m,k,_),a+=1;continue}if(l.startsWith("-")&&l.length>1){for(let o of[...l.slice(1)]){let d=f.get(o);if(d===void 0){c.push(g("cli_unknown_flag",`Unknown flag -${o}.`,`Run \`${e.slug} ${i.name} --help\` for the flags this command accepts.`,`-${o}`));continue}if(d.kind!=="boolean"){c.push(g("cli_short_flag_needs_value",`-${o} takes a value and cannot be bundled.`,`Write it on its own: --${d.name} <${d.placeholder??"value"}>.`,`-${o}`));continue}u.set(d.name,!0)}continue}h.push(l)}let w=new N(u,r);if(w.bool("help"))return{kind:"help",command:i};if(w.bool("version"))return{kind:"version"};let S=i.args.some((a)=>a.variadic===!0),x=i.args.filter((a)=>a.required);if(c.length>0)throw v(c);else if(h.length<x.length){let a=x[h.length];c.push(g("cli_missing_argument",`${i.name} needs ${a===void 0?"another argument":`a ${a.name}`}.`,`Usage: ${e.slug} ${i.name} ${i.args.map((l)=>`<${l.name}${l.variadic===!0?"...":""}>`).join(" ")}`))}else if(!S&&h.length>i.args.length){let a=h.slice(i.args.length);c.push(g("cli_unexpected_argument",`${i.name} takes ${i.args.length} argument(s), got ${h.length}.`,i.unexpectedArgHint??`Unexpected: ${a.join(" ")}. Quote a value containing spaces.`))}if(c.length>0)throw v(c);return{kind:"command",parsed:{command:i,positionals:h,flags:w}}}
2
+ import{e,t}from"./index-tv4yv7d2.js";import{Rt,le,It,Ot,Ao}from"./index-whaw4b18.js";class se extends t{static ERROR_NAME="UsageError"}function D(n,s){let i=Array.from({length:s.length+1},(r,f)=>f);for(let r=1;r<=n.length;r+=1){let f=[r];for(let u=1;u<=s.length;u+=1){let h=(i[u-1]??0)+(n[r-1]===s[u-1]?0:1),c=(f[u-1]??0)+1,b=(i[u]??0)+1;f.push(Math.min(h,c,b))}i=f}return i[s.length]??Math.max(n.length,s.length)}function R(n,s){let i,r=Number.POSITIVE_INFINITY;for(let f of s){let u=D(n,f);if(u<r)r=u,i=f}return i!==void 0&&r<=Math.max(2,Math.floor(n.length/3))?i:void 0}class N{#e;#t;constructor(n,s){this.#e=n,this.#t=s}#n(n,s){let i=this.#t.get(n);if(i===void 0)throw new se({code:"cli_flag_not_declared",message:`No flag "${n}" is declared for this command.`,hint:"This is a bug in the CLI, not in the command line. Add the flag to lib/commands.ts or fix the reader."});if(i.kind!==s)throw new se({code:"cli_flag_kind_mismatch",message:`Flag "${n}" is declared as ${i.kind} but was read as ${s}.`,hint:"This is a bug in the CLI. The reader and lib/commands.ts disagree."});return this.#e.get(n)}str(n){let s=this.#n(n,"string");return typeof s==="string"?s:void 0}num(n){let s=this.#n(n,"number");return typeof s==="number"?s:void 0}bool(n){return this.#n(n,"boolean")===!0}has(n){return this.#e.has(n)}}function g(n,s,i,r){return r===void 0?{code:n,message:s,hint:i}:{code:n,message:s,hint:i,field:r}}function v(n){let s=n[0];return new se({code:"cli_usage",message:n.length===1&&s!==void 0?s.message:`${n.length} problems with the command line.`,hint:n.length===1&&s!==void 0?s.hint:"Each problem below names the flag and its fix.",...s?.field===void 0?{}:{field:s.field},details:n})}function E(n,s,i){let r=Number(s);if(s.trim()===""||!Number.isFinite(r))return g("cli_flag_not_a_number",`${i} expects a number, got ${JSON.stringify(s)}.`,`Pass a number, as in ${i} 50. The old parser silently used the default here, which made a typo look like it worked.`,i);if(n.integer===!0&&!Number.isInteger(r))return g("cli_flag_not_an_integer",`${i} expects a whole number, got ${s}.`,`Drop the fractional part: ${i} ${Math.trunc(r)}.`,i);if(n.min!==void 0&&r<n.min)return g("cli_flag_below_min",`${i} must be at least ${n.min}, got ${r}.`,`Pass ${n.min} or more.`,i);return r}function jr(n){let s=n[0];if(s===void 0)return{kind:"usage"};if(s.startsWith("-")){let a=new Set(Rt.flatMap((o)=>o.short===void 0?[`--${o.name}`]:[`--${o.name}`,`-${o.short}`])),l=n.filter((o)=>!a.has(o));if(l.length>0)throw v([g("cli_no_command","No command given.",`Run \`${e.slug} --help\` for the command list. Commands are ${le.map((o)=>o.name).join(", ")}.`,l[0])]);if(n.includes("--version")||n.includes("-v"))return{kind:"version"};if(n.includes("--help")||n.includes("-h"))return{kind:"help",command:void 0};return{kind:"usage"}}let i=It(s);if(i===void 0){let a=R(s,le.map((l)=>l.name));throw v([g("cli_unknown_command",`Unknown command "${s}".`,a===void 0?`Run \`${e.slug} --help\` for the command list.`:`Did you mean "${a}"? Run \`${e.slug} --help\` for the full list.`,s)])}let r=new Map(Ot(i).map((a)=>[a.name,a])),f=new Map(Ot(i).filter((a)=>a.short!==void 0).map((a)=>[a.short,a])),u=new Map,h=[],c=[],b=!1,F=(a,l,o)=>{if(l===""){c.push(g("cli_flag_empty_value",`${o} was given an empty value.`,"Pass a value, or drop the flag entirely to use the default.",o));return}if(a.kind==="number"){let d=E(a,l,o);if(typeof d==="number")u.set(a.name,d);else c.push(d);return}u.set(a.name,l)};for(let a=1;a<n.length;a+=1){let l=n[a];if(l===void 0)continue;if(b){h.push(l);continue}if(l==="--"){b=!0;continue}if(l.startsWith("--")){let o=l.slice(2),d=o.indexOf("="),p=d===-1?o:o.slice(0,d),m=r.get(p);if(m===void 0){let y=Ao(p,i.name),M=R(p,[...r.keys()]);c.push(g(y.length>0?"cli_flag_wrong_command":"cli_unknown_flag",y.length>0?`${i.name} does not accept --${p}.`:`Unknown flag --${p}.`,y.length>0?`--${p} is accepted by: ${y.join(", ")}.`:M===void 0?`Run \`${e.slug} ${i.name} --help\` for the flags this command accepts.`:`Did you mean --${M}?`,`--${p}`));continue}let _=`--${p}`;if(m.kind==="boolean"){if(d!==-1){c.push(g("cli_flag_takes_no_value",`${_} is a switch and takes no value.`,`Drop the "=${o.slice(d+1)}" — pass ${_} on its own.`,_));continue}u.set(m.name,!0);continue}if(d!==-1){F(m,o.slice(d+1),_);continue}let k=n[a+1];if(m.bare!==void 0&&(k===void 0||k.startsWith("-"))){u.set(m.name,m.bare);continue}if(k===void 0){c.push(g("cli_flag_needs_value",`${_} needs a value.`,`Pass one, as in ${_} <${m.placeholder??"value"}>.`,_));continue}F(m,k,_),a+=1;continue}if(l.startsWith("-")&&l.length>1){for(let o of[...l.slice(1)]){let d=f.get(o);if(d===void 0){c.push(g("cli_unknown_flag",`Unknown flag -${o}.`,`Run \`${e.slug} ${i.name} --help\` for the flags this command accepts.`,`-${o}`));continue}if(d.kind!=="boolean"){c.push(g("cli_short_flag_needs_value",`-${o} takes a value and cannot be bundled.`,`Write it on its own: --${d.name} <${d.placeholder??"value"}>.`,`-${o}`));continue}u.set(d.name,!0)}continue}h.push(l)}let w=new N(u,r);if(w.bool("help"))return{kind:"help",command:i};if(w.bool("version"))return{kind:"version"};let S=i.args.some((a)=>a.variadic===!0),x=i.args.filter((a)=>a.required);if(c.length>0)throw v(c);else if(h.length<x.length){let a=x[h.length];c.push(g("cli_missing_argument",`${i.name} needs ${a===void 0?"another argument":`a ${a.name}`}.`,`Usage: ${e.slug} ${i.name} ${i.args.map((l)=>`<${l.name}${l.variadic===!0?"...":""}>`).join(" ")}`))}else if(!S&&h.length>i.args.length){let a=h.slice(i.args.length);c.push(g("cli_unexpected_argument",`${i.name} takes ${i.args.length} argument(s), got ${h.length}.`,i.unexpectedArgHint??`Unexpected: ${a.join(" ")}. Quote a value containing spaces.`))}if(c.length>0)throw v(c);return{kind:"command",parsed:{command:i,positionals:h,flags:w}}}
3
3
  export{se,jr};
4
4
 
5
5
  //# debugId=EAE3DB2145C6B8F464756E2164756E21
6
- //# sourceMappingURL=index-5x4dn0gg.js.map
6
+ //# sourceMappingURL=index-hwpvhaza.js.map
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import{zo}from"./index-3g3ny01d.js";import{Wo}from"./index-d4x6yvqh.js";import{ts,Cr}from"./index-2wmsmcbr.js";var D={value:"",cursor:0,history:[],historyOffset:0,draft:"",past:[],future:[],search:void 0,anchor:void 0};function c(r){return[...r]}function u(r,e){return Math.max(0,Math.min(r,e))}function h(r){return{value:r.value,cursor:r.cursor}}function d(r,e){let n=r.past.at(-1);if(e.coalesce&&n!==void 0&&r.future.length===0)return{...r,future:[]};if(n!==void 0&&n.value===r.value)return{...r,future:[]};return{...r,past:[...r.past,h(r)].slice(-Cr),future:[]}}function a(r,e){return{...r,value:e,cursor:c(e).length}}function k(r,e){let n=d(r,{coalesce:!e.includes(`
2
+ import{zo}from"./index-3g3ny01d.js";import{Wo}from"./index-d4x6yvqh.js";import{ts,Cr}from"./index-vgc3y3rm.js";var D={value:"",cursor:0,history:[],historyOffset:0,draft:"",past:[],future:[],search:void 0,anchor:void 0};function c(r){return[...r]}function u(r,e){return Math.max(0,Math.min(r,e))}function h(r){return{value:r.value,cursor:r.cursor}}function d(r,e){let n=r.past.at(-1);if(e.coalesce&&n!==void 0&&r.future.length===0)return{...r,future:[]};if(n!==void 0&&n.value===r.value)return{...r,future:[]};return{...r,past:[...r.past,h(r)].slice(-Cr),future:[]}}function a(r,e){return{...r,value:e,cursor:c(e).length}}function k(r,e){let n=d(r,{coalesce:!e.includes(`
3
3
  `)}),o=c(n.value),t=u(n.cursor,o.length),i=[...o.slice(0,t),...c(e),...o.slice(t)];return{...n,value:i.join(""),cursor:t+c(e).length}}function E(r){let e=c(r.value),n=u(r.cursor,e.length);if(n===0)return r;let o=d(r,{coalesce:!1}),t=[...e.slice(0,n-1),...e.slice(n)];return{...o,value:t.join(""),cursor:n-1}}function y(r){let e=c(r.value),n=u(r.cursor,e.length);if(n>=e.length)return r;return{...d(r,{coalesce:!1}),value:[...e.slice(0,n),...e.slice(n+1)].join("")}}function f(r){return r===void 0||/\s/.test(r)}function v(r,e){let n=e;while(n>0&&f(r[n-1]))n-=1;while(n>0&&!f(r[n-1]))n-=1;return n}function b(r,e){let n=e;while(n<r.length&&f(r[n]))n+=1;while(n<r.length&&!f(r[n]))n+=1;return n}function x(r){let e=c(r.value),n=v(e,u(r.cursor,e.length));if(n===r.cursor)return r;return{...d(r,{coalesce:!1}),value:[...e.slice(0,n),...e.slice(r.cursor)].join(""),cursor:n}}function A(r){let e=c(r.value),n=u(r.cursor,e.length),o=b(e,n);if(o===n)return r;return{...d(r,{coalesce:!1}),value:[...e.slice(0,n),...e.slice(o)].join("")}}function l(r,e){let n=c(r),o=u(e,n.length),t=o;while(t>0&&n[t-1]!==`
4
4
  `)t-=1;let i=o;while(i<n.length&&n[i]!==`
5
5
  `)i+=1;return{start:t,end:i}}function ar(r){let e=c(r.value),n=u(r.cursor,e.length),o=e.slice(0,n),{start:t}=l(r.value,n);return{line:o.filter((i)=>i===`
6
6
  `).length,lines:e.filter((i)=>i===`
7
7
  `).length+1,column:n-t}}function p(r,e){let n=c(r.value),o=u(r.cursor,n.length),t=l(r.value,o),i=o-t.start;if(e<0){if(t.start===0)return r;let m=l(r.value,t.start-1);return{...r,cursor:Math.min(m.start+i,m.end)}}if(t.end>=n.length)return r;let s=l(r.value,t.end+1);return{...r,cursor:Math.min(s.start+i,s.end)}}function L(r){if(r.history.length===0)return r;let e=Math.min(r.historyOffset+1,r.history.length),n=r.history[r.history.length-e];if(n===void 0)return r;return a({...d(r,{coalesce:!1}),historyOffset:e,draft:r.historyOffset===0?r.value:r.draft},n)}function I(r){if(r.historyOffset===0)return r;let e=r.historyOffset-1,n=d(r,{coalesce:!1});if(e===0)return a({...n,historyOffset:0},r.draft);let o=r.history[r.history.length-e];return o===void 0?r:a({...n,historyOffset:e},o)}function Ut(r){let e=(r.search?.query??"").toLowerCase(),n=new Set,o=[];for(let t=r.history.length-1;t>=0;t-=1){let i=r.history[t];if(i===void 0||n.has(i))continue;if(e===""||i.toLowerCase().includes(e))n.add(i),o.push(i)}return o}function C(r){let e=Ut(r);return e[u(r.search?.index??0,Math.max(0,e.length-1))]}function g(r,e){let n=r.search;if(n===void 0)return r;let o=Ut(r);if(o.length===0)return r;return{...r,search:{...n,index:u(n.index+e,o.length-1)}}}function T(r,e){let n=r.search;if(n===void 0)return r;return{...r,search:{query:n.query+e,index:0}}}function M(r){let e=r.search;if(e===void 0)return r;let n=c(e.query).slice(0,-1).join("");return{...r,search:{query:n,index:0}}}function O(r){let e=C(r);if(e===void 0)return{...r,search:void 0};return a({...d(r,{coalesce:!1}),search:void 0},e)}function K(r){let e=r.past.at(-1);if(e===void 0)return r;return{...r,value:e.value,cursor:u(e.cursor,c(e.value).length),past:r.past.slice(0,-1),future:[h(r),...r.future],historyOffset:0}}function j(r){let e=r.future[0];if(e===void 0)return r;return{...r,value:e.value,cursor:u(e.cursor,c(e.value).length),past:[...r.past,h(r)].slice(-Cr),future:r.future.slice(1)}}function kt(r){if(r.anchor===void 0||r.anchor===r.cursor)return;return r.anchor<r.cursor?{start:r.anchor,end:r.cursor}:{start:r.cursor,end:r.anchor}}function w(r){let e=kt(r);if(e===void 0)return{...r,anchor:void 0};let n=c(r.value);return{...d(r,{coalesce:!1}),value:[...n.slice(0,e.start),...n.slice(e.end)].join(""),cursor:e.start,anchor:void 0}}function R(r){return r.kind==="insert"||r.kind==="newline"||r.kind==="backspace"||r.kind==="delete"}function V(r,e){if(r.search===void 0&&R(e)&&kt(r)!==void 0){let o=w(r);if(e.kind==="backspace"||e.kind==="delete")return o;return V(o,e)}if(e.kind==="extend"){let o=r.anchor??r.cursor;return{...V({...r,anchor:void 0},{kind:e.to}),anchor:o}}if(e.kind==="cutSelection")return w(r);if(e.kind==="copySelection")return r;if(e.kind==="selectAll")return{...r,anchor:0,cursor:c(r.value).length};let n=W(r,e);return n.anchor===void 0?n:{...n,anchor:void 0}}function W(r,e){if(r.search!==void 0)switch(e.kind){case"insert":return T(r,e.text);case"backspace":return M(r);case"historyPrev":case"lineUp":return g(r,1);case"historyNext":case"lineDown":return g(r,-1);case"searchAccept":return O(r);case"searchCancel":return{...r,search:void 0};case"searchOpen":return r;default:return{...r,search:void 0}}switch(e.kind){case"insert":return k(r,e.text);case"newline":return k(r,`
8
- `);case"backspace":return E(r);case"delete":return y(r);case"cursorLeft":return{...r,cursor:u(r.cursor-1,c(r.value).length)};case"cursorRight":return{...r,cursor:u(r.cursor+1,c(r.value).length)};case"cursorHome":return{...r,cursor:l(r.value,r.cursor).start};case"cursorEnd":return{...r,cursor:l(r.value,r.cursor).end};case"bufferStart":return{...r,cursor:0};case"bufferEnd":return{...r,cursor:c(r.value).length};case"wordLeft":return{...r,cursor:v(c(r.value),r.cursor)};case"wordRight":return{...r,cursor:b(c(r.value),r.cursor)};case"lineUp":return p(r,-1);case"lineDown":return p(r,1);case"killToStart":{let{start:n}=l(r.value,r.cursor);if(n===r.cursor)return r;let o=c(r.value);return{...d(r,{coalesce:!1}),value:[...o.slice(0,n),...o.slice(r.cursor)].join(""),cursor:n}}case"killToEnd":{let{end:n}=l(r.value,r.cursor);if(n===r.cursor)return r;let o=c(r.value);return{...d(r,{coalesce:!1}),value:[...o.slice(0,r.cursor),...o.slice(n)].join("")}}case"killWord":return x(r);case"killWordForward":return A(r);case"historyPrev":return L(r);case"historyNext":return I(r);case"undo":return K(r);case"redo":return j(r);case"searchOpen":return{...r,search:{query:"",index:0}};case"searchAccept":case"searchCancel":case"submit":case"cancel":case"exit":case"arm":case"scroll":case"pointer":case"reasoning":case"paste":case"none":return r;case"extend":case"selectAll":case"copySelection":case"cutSelection":return r}}function Uo(r){let e=r.value.trim();if(e==="")return{text:"",state:{...D,history:r.history}};let o=r.history.at(-1)===e?r.history:[...r.history,e].slice(-ts);return{text:e,state:{...D,history:o}}}function kn(r,e,n={}){let{line:o,lines:t}=ar(r);return{busy:e,empty:r.value==="",firstLine:o===0,lastLine:o===t-1,searching:r.search!==void 0,armed:n.armed??!1,scrolled:n.scrolled??!1}}function H(r,e){switch(r){case"c":if(e.searching)return{kind:"searchCancel"};if(e.busy)return{kind:"cancel"};return e.armed?{kind:"exit"}:{kind:"arm"};case"d":return e.empty?{kind:"exit"}:{kind:"delete"};case"a":return{kind:"cursorHome"};case"e":return{kind:"cursorEnd"};case"b":return{kind:"cursorLeft"};case"f":return{kind:"cursorRight"};case"u":return{kind:"killToStart"};case"k":return{kind:"killToEnd"};case"w":return{kind:"killWord"};case"p":return{kind:"historyPrev"};case"n":return{kind:"historyNext"};case"r":return{kind:"searchOpen"};case"o":return{kind:"reasoning"};case"z":return{kind:"undo"};case"y":return{kind:"redo"};default:return{kind:"none"}}}function jt(r,e,n){let o=Wo(r);if(o!==void 0){if(o.rows!==0)return{kind:"scroll",move:o.rows<0?"up":"down",times:Math.abs(o.rows)};if(o.at!==void 0&&o.kind!==void 0&&o.kind!=="wheel")return{kind:"pointer",gesture:o.kind,column:o.at.column,row:o.at.row,shift:o.shift===!0};return{kind:"none"}}if(e.eventType==="release")return{kind:"none"};if(e.shift){let i=B(e);if(i!==void 0)return{kind:"extend",to:i}}if(e.super){if(e.leftArrow)return{kind:"cursorHome"};if(e.rightArrow)return{kind:"cursorEnd"};if(e.upArrow)return{kind:"bufferStart"};if(e.downArrow)return{kind:"bufferEnd"};if(e.backspace)return{kind:"killToStart"};if(e.delete)return{kind:"killToEnd"};if(r==="z")return e.shift?{kind:"redo"}:{kind:"undo"};if(r==="a")return{kind:"selectAll"};if(r==="c")return{kind:"copySelection"};if(r==="x")return{kind:"cutSelection"};return{kind:"none"}}if(zo(r))return{kind:"none"};if(e.ctrl&&e.leftArrow)return{kind:"wordLeft"};if(e.ctrl&&e.rightArrow)return{kind:"wordRight"};if(e.ctrl&&e.backspace)return{kind:"killWord"};if(e.ctrl)return H(r.toLowerCase(),n);if(e.meta){if(e.return)return{kind:"newline"};if(e.pageUp)return{kind:"scroll",move:"top"};if(e.pageDown)return{kind:"scroll",move:"bottom"};if(e.upArrow)return{kind:"scroll",move:"up"};if(e.downArrow)return{kind:"scroll",move:"down"};if(e.leftArrow||r==="b")return{kind:"wordLeft"};if(e.rightArrow||r==="f")return{kind:"wordRight"};if(e.backspace)return{kind:"killWord"};if(r==="d")return{kind:"killWordForward"};if(r==="r")return{kind:"reasoning"};return{kind:"none"}}if(e.return&&e.shift)return{kind:"newline"};if(e.pageUp)return{kind:"scroll",move:"pageUp"};if(e.pageDown)return{kind:"scroll",move:"pageDown"};if(e.home)return{kind:"cursorHome"};if(e.end)return{kind:"cursorEnd"};if(e.return)return n.searching?{kind:"searchAccept"}:{kind:"submit"};if(e.backspace)return{kind:"backspace"};if(e.delete)return{kind:"delete"};if(e.leftArrow)return{kind:"cursorLeft"};if(e.rightArrow)return{kind:"cursorRight"};if(e.upArrow)return n.searching||n.firstLine?{kind:"historyPrev"}:{kind:"lineUp"};if(e.downArrow)return n.searching||n.lastLine?{kind:"historyNext"}:{kind:"lineDown"};if(e.escape){if(n.searching)return{kind:"searchCancel"};return n.scrolled?{kind:"scroll",move:"bottom"}:{kind:"none"}}if(e.tab)return{kind:"none"};if(r==="")return{kind:"none"};if(r==="\x1B[H"||r==="\x1B[1~")return{kind:"cursorHome"};if(r==="\x1B[F"||r==="\x1B[4~")return{kind:"cursorEnd"};if(/[\r\n]/.test(r)){let i=r.split(/\r\n|[\r\n]/).map(S),s=i.at(-1)===""&&i.length>1;return{kind:"paste",lines:s?i.slice(0,-1):i,complete:s}}let t=S(r);return t===""?{kind:"none"}:{kind:"insert",text:t}}function B(r){if(r.super){if(r.leftArrow)return"cursorHome";if(r.rightArrow)return"cursorEnd";if(r.upArrow)return"bufferStart";if(r.downArrow)return"bufferEnd";return}if(r.meta||r.ctrl){if(r.leftArrow)return"wordLeft";if(r.rightArrow)return"wordRight";return}if(r.home)return"cursorHome";if(r.end)return"cursorEnd";if(r.leftArrow)return"cursorLeft";if(r.rightArrow)return"cursorRight";if(r.upArrow)return"lineUp";if(r.downArrow)return"lineDown";return}function S(r){return[...r].filter((e)=>{let n=e.codePointAt(0)??0;return n>=32&&n!==127}).join("")}function zt(r,e){if(e.ctrl)return r.toLowerCase()==="c"||r.toLowerCase()==="d"?{kind:"cancel"}:{kind:"none"};if(e.return)return{kind:"confirm"};if(e.escape)return{kind:"cancel"};if(r===" ")return{kind:"toggle"};if(r==="a")return{kind:"all"};if(r==="n")return{kind:"none-selected"};let n=we(r,e);return n.kind==="move"?n:{kind:"none"}}function we(r,e){if(e.ctrl)return r.toLowerCase()==="c"||r.toLowerCase()==="d"?{kind:"exit"}:{kind:"none"};if(e.return)return{kind:"choose"};if(e.escape)return{kind:"back"};if(e.upArrow)return{kind:"move",move:{kind:"up"}};if(e.downArrow)return{kind:"move",move:{kind:"down"}};switch(r){case"k":return{kind:"move",move:{kind:"up"}};case"j":return{kind:"move",move:{kind:"down"}};case"g":return{kind:"move",move:{kind:"first"}};case"G":return{kind:"move",move:{kind:"last"}};default:break}if(/^[1-9]$/.test(r))return{kind:"move",move:{kind:"jump",index:Number(r)-1}};return{kind:"none"}}function Sn(r,e,n){if(e.ctrl&&r.toLowerCase()==="c")return{kind:"abort"};if(e.escape)return{kind:"back"};if(e.return)return{kind:"commit"};if(n.select)return{kind:"list",intent:we(r,e)};let o=jt(r,e,{busy:!1,empty:n.empty,firstLine:!0,lastLine:!0,searching:!1,armed:!1,scrolled:!1});switch(o.kind){case"submit":return{kind:"commit"};case"exit":return{kind:"abort"};case"arm":case"scroll":return{kind:"edit",intent:{kind:"none"}};case"historyPrev":case"historyNext":return{kind:"edit",intent:{kind:"none"}};case"paste":return{kind:"edit",intent:{kind:"insert",text:o.lines[0]??""}};default:return{kind:"edit",intent:o}}}
9
- export{D,ar,Ut,kt,V,Uo,kn,jt,zt,we,Sn};
8
+ `);case"backspace":return E(r);case"delete":return y(r);case"cursorLeft":return{...r,cursor:u(r.cursor-1,c(r.value).length)};case"cursorRight":return{...r,cursor:u(r.cursor+1,c(r.value).length)};case"cursorHome":return{...r,cursor:l(r.value,r.cursor).start};case"cursorEnd":return{...r,cursor:l(r.value,r.cursor).end};case"bufferStart":return{...r,cursor:0};case"bufferEnd":return{...r,cursor:c(r.value).length};case"wordLeft":return{...r,cursor:v(c(r.value),r.cursor)};case"wordRight":return{...r,cursor:b(c(r.value),r.cursor)};case"lineUp":return p(r,-1);case"lineDown":return p(r,1);case"killToStart":{let{start:n}=l(r.value,r.cursor);if(n===r.cursor)return r;let o=c(r.value);return{...d(r,{coalesce:!1}),value:[...o.slice(0,n),...o.slice(r.cursor)].join(""),cursor:n}}case"killToEnd":{let{end:n}=l(r.value,r.cursor);if(n===r.cursor)return r;let o=c(r.value);return{...d(r,{coalesce:!1}),value:[...o.slice(0,r.cursor),...o.slice(n)].join("")}}case"killWord":return x(r);case"killWordForward":return A(r);case"historyPrev":return L(r);case"historyNext":return I(r);case"undo":return K(r);case"redo":return j(r);case"searchOpen":return{...r,search:{query:"",index:0}};case"searchAccept":case"searchCancel":case"submit":case"cancel":case"exit":case"arm":case"scroll":case"pointer":case"reasoning":case"paste":case"none":return r;case"extend":case"selectAll":case"copySelection":case"cutSelection":return r}}function Uo(r){let e=r.value.trim();if(e==="")return{text:"",state:{...D,history:r.history}};let o=r.history.at(-1)===e?r.history:[...r.history,e].slice(-ts);return{text:e,state:{...D,history:o}}}function kn(r,e,n={}){let{line:o,lines:t}=ar(r);return{busy:e,empty:r.value==="",firstLine:o===0,lastLine:o===t-1,searching:r.search!==void 0,armed:n.armed??!1,scrolled:n.scrolled??!1}}function H(r,e){switch(r){case"c":if(e.searching)return{kind:"searchCancel"};if(e.busy)return{kind:"cancel"};return e.armed?{kind:"exit"}:{kind:"arm"};case"d":return e.empty?{kind:"exit"}:{kind:"delete"};case"a":return{kind:"cursorHome"};case"e":return{kind:"cursorEnd"};case"b":return{kind:"cursorLeft"};case"f":return{kind:"cursorRight"};case"u":return{kind:"killToStart"};case"k":return{kind:"killToEnd"};case"w":return{kind:"killWord"};case"p":return{kind:"historyPrev"};case"n":return{kind:"historyNext"};case"r":return{kind:"searchOpen"};case"o":return{kind:"reasoning"};case"z":return{kind:"undo"};case"y":return{kind:"redo"};default:return{kind:"none"}}}function jt(r,e,n){let o=Wo(r);if(o!==void 0){if(o.rows!==0)return{kind:"scroll",move:o.rows<0?"up":"down",times:Math.abs(o.rows)};if(o.at!==void 0&&o.kind!==void 0&&o.kind!=="wheel")return{kind:"pointer",gesture:o.kind,column:o.at.column,row:o.at.row,shift:o.shift===!0};return{kind:"none"}}if(e.eventType==="release")return{kind:"none"};if(e.shift){let i=B(e);if(i!==void 0)return{kind:"extend",to:i}}if(e.super){if(e.leftArrow)return{kind:"cursorHome"};if(e.rightArrow)return{kind:"cursorEnd"};if(e.upArrow)return{kind:"bufferStart"};if(e.downArrow)return{kind:"bufferEnd"};if(e.backspace)return{kind:"killToStart"};if(e.delete)return{kind:"killToEnd"};if(r==="z")return e.shift?{kind:"redo"}:{kind:"undo"};if(r==="a")return{kind:"selectAll"};if(r==="c")return{kind:"copySelection"};if(r==="x")return{kind:"cutSelection"};return{kind:"none"}}if(zo(r))return{kind:"none"};if(e.ctrl&&e.leftArrow)return{kind:"wordLeft"};if(e.ctrl&&e.rightArrow)return{kind:"wordRight"};if(e.ctrl&&e.backspace)return{kind:"killWord"};if(e.ctrl)return H(r.toLowerCase(),n);if(e.meta){if(e.return)return{kind:"newline"};if(e.pageUp)return{kind:"scroll",move:"top"};if(e.pageDown)return{kind:"scroll",move:"bottom"};if(e.upArrow)return{kind:"scroll",move:"up"};if(e.downArrow)return{kind:"scroll",move:"down"};if(e.leftArrow||r==="b")return{kind:"wordLeft"};if(e.rightArrow||r==="f")return{kind:"wordRight"};if(e.backspace)return{kind:"killWord"};if(r==="d")return{kind:"killWordForward"};if(r==="r")return{kind:"reasoning"};return{kind:"none"}}if(e.return&&e.shift)return{kind:"newline"};if(e.pageUp)return{kind:"scroll",move:"pageUp"};if(e.pageDown)return{kind:"scroll",move:"pageDown"};if(e.home)return{kind:"cursorHome"};if(e.end)return{kind:"cursorEnd"};if(e.return)return n.searching?{kind:"searchAccept"}:{kind:"submit"};if(e.backspace)return{kind:"backspace"};if(e.delete)return{kind:"delete"};if(e.leftArrow)return{kind:"cursorLeft"};if(e.rightArrow)return{kind:"cursorRight"};if(e.upArrow)return n.searching||n.firstLine?{kind:"historyPrev"}:{kind:"lineUp"};if(e.downArrow)return n.searching||n.lastLine?{kind:"historyNext"}:{kind:"lineDown"};if(e.escape){if(n.searching)return{kind:"searchCancel"};return n.scrolled?{kind:"scroll",move:"bottom"}:{kind:"none"}}if(e.tab)return{kind:"none"};if(r==="")return{kind:"none"};if(r==="\x1B[H"||r==="\x1B[1~")return{kind:"cursorHome"};if(r==="\x1B[F"||r==="\x1B[4~")return{kind:"cursorEnd"};if(/[\r\n]/.test(r)){let i=r.split(/\r\n|[\r\n]/).map(S),s=i.at(-1)===""&&i.length>1;return{kind:"paste",lines:s?i.slice(0,-1):i,complete:s}}let t=S(r);return t===""?{kind:"none"}:{kind:"insert",text:t}}function B(r){if(r.super){if(r.leftArrow)return"cursorHome";if(r.rightArrow)return"cursorEnd";if(r.upArrow)return"bufferStart";if(r.downArrow)return"bufferEnd";return}if(r.meta||r.ctrl){if(r.leftArrow)return"wordLeft";if(r.rightArrow)return"wordRight";return}if(r.home)return"cursorHome";if(r.end)return"cursorEnd";if(r.leftArrow)return"cursorLeft";if(r.rightArrow)return"cursorRight";if(r.upArrow)return"lineUp";if(r.downArrow)return"lineDown";return}function S(r){return[...r].filter((e)=>{let n=e.codePointAt(0)??0;return n>=32&&n!==127}).join("")}function zt(r,e){if(e.ctrl)return r.toLowerCase()==="c"||r.toLowerCase()==="d"?{kind:"cancel"}:{kind:"none"};if(e.return)return{kind:"confirm"};if(e.escape)return{kind:"cancel"};if(r===" ")return{kind:"toggle"};if(r==="a")return{kind:"all"};if(r==="n")return{kind:"none-selected"};let n=be(r,e);return n.kind==="move"?n:{kind:"none"}}function be(r,e){if(e.ctrl)return r.toLowerCase()==="c"||r.toLowerCase()==="d"?{kind:"exit"}:{kind:"none"};if(e.return)return{kind:"choose"};if(e.escape)return{kind:"back"};if(e.upArrow)return{kind:"move",move:{kind:"up"}};if(e.downArrow)return{kind:"move",move:{kind:"down"}};switch(r){case"k":return{kind:"move",move:{kind:"up"}};case"j":return{kind:"move",move:{kind:"down"}};case"g":return{kind:"move",move:{kind:"first"}};case"G":return{kind:"move",move:{kind:"last"}};default:break}if(/^[1-9]$/.test(r))return{kind:"move",move:{kind:"jump",index:Number(r)-1}};return{kind:"none"}}function Sn(r,e,n){if(e.ctrl&&r.toLowerCase()==="c")return{kind:"abort"};if(e.escape)return{kind:"back"};if(e.return)return{kind:"commit"};if(n.select)return{kind:"list",intent:be(r,e)};let o=jt(r,e,{busy:!1,empty:n.empty,firstLine:!0,lastLine:!0,searching:!1,armed:!1,scrolled:!1});switch(o.kind){case"submit":return{kind:"commit"};case"exit":return{kind:"abort"};case"arm":case"scroll":return{kind:"edit",intent:{kind:"none"}};case"historyPrev":case"historyNext":return{kind:"edit",intent:{kind:"none"}};case"paste":return{kind:"edit",intent:{kind:"insert",text:o.lines[0]??""}};default:return{kind:"edit",intent:o}}}
9
+ export{D,ar,Ut,kt,V,Uo,kn,jt,zt,be,Sn};
10
10
 
11
- //# debugId=5643B4EA03895CAC64756E2164756E21
12
- //# sourceMappingURL=index-e0j1jafd.js.map
11
+ //# debugId=D74D8516B55F9B6964756E2164756E21
12
+ //# sourceMappingURL=index-j55s3ehk.js.map
@@ -6,6 +6,6 @@
6
6
  "/**\n * Keystrokes in, intents out. Pure, and free of any Ink import.\n *\n * The one contract worth stating explicitly, because Phase 1 established and measured it:\n * **Ctrl-C cancels the turn, not the process.** Whether a keystroke means \"cancel\" or \"exit\"\n * depends on whether a turn is in flight, so that decision belongs here — in a function that can be\n * tested against both states — rather than in a component where it can only be tested by hand.\n */\n\nimport { lineInfo } from \"#editor\"\nimport { isTerminalReply } from \"#lib/csi\"\nimport { mouseInput } from \"#lib/mouse\"\nimport type { EditorState, Intent, KeyState, MotionKind } from \"#lib/types\"\n\nexport interface KeyContext {\n /** A turn is in flight. */\n readonly busy: boolean\n /** The input buffer is empty. */\n readonly empty: boolean\n /**\n * The cursor is on the first line, so ↑ means history rather than a line up.\n *\n * Position decides, because a multi-line buffer wants both and every editor resolves it this way:\n * at the top of what you are composing there is nothing above to move to, so the arrow is free to\n * mean the other thing. `^P`/`^N` stay unconditional history for anyone who would rather not think\n * about where the cursor is.\n */\n readonly firstLine: boolean\n readonly lastLine: boolean\n /** `^R` is open, so enter accepts a match and escape closes it. */\n readonly searching: boolean\n /**\n * A first ^C has already been pressed at an idle prompt, so the next one leaves.\n *\n * Held by the caller rather than derived, because it is the one piece of keyboard state with a\n * *clock* attached — it expires — and a pure function cannot own that. What it must not do is\n * decide what an armed ^C means, which is why the flag comes in here and the decision stays below.\n */\n readonly armed: boolean\n /**\n * The transcript window is parked above the newest row, so escape means \"come back down\".\n *\n * Escape had nothing to do at an idle prompt and was claimed as `none` to keep control characters\n * out of the buffer. A scrolled-away view is the one state where a reader plainly wants a way out\n * of where they are, and escape is the key they will press.\n */\n readonly scrolled: boolean\n}\n\n/**\n * The context for a given editor state.\n *\n * Exported and derived in one place so no renderer computes it by hand. `empty` was already this shape\n * — editor state passed to the keymap as context — and the two line flags are the same idea; a caller\n * that got `firstLine` wrong would make the arrows misbehave in a way no test of this module would see.\n */\nexport function keyContext(\n editor: EditorState,\n busy: boolean,\n session: { readonly armed?: boolean; readonly scrolled?: boolean } = {},\n): KeyContext {\n const { line, lines } = lineInfo(editor)\n return {\n busy,\n empty: editor.value === \"\",\n firstLine: line === 0,\n lastLine: line === lines - 1,\n searching: editor.search !== undefined,\n armed: session.armed ?? false,\n scrolled: session.scrolled ?? false,\n }\n}\n\n/** Ctrl-key chords arrive as `key.ctrl` plus the letter in `input`. */\nfunction ctrlIntent(letter: string, context: KeyContext): Intent {\n switch (letter) {\n case \"c\":\n // While a search is open, ^C dismisses it rather than the session: the search is the\n // foreground thing, and quitting the whole session from it would lose a message somebody\n // is part-way through composing.\n if (context.searching) return { kind: \"searchCancel\" }\n // The whole point. Busy means a turn is generating; interrupting it must leave the\n // prompt behind, not the shell.\n if (context.busy) return { kind: \"cancel\" }\n // At an idle prompt it takes two, and the first one says so.\n //\n // One press used to exit, which was defensible while the session left its conversation in\n // the scrollback: ^C landed you back in a shell with the transcript still above it. On the\n // alternate screen the buffer is discarded on the way out, so the same keystroke now throws\n // the visible conversation away — and it is one press away from the chord that means\n // \"cancel this turn\", pressed reflexively when a reply runs long. ^D still leaves in one,\n // for anyone who wants that, and the status line names whichever is live.\n return context.armed ? { kind: \"exit\" } : { kind: \"arm\" }\n case \"d\":\n // Ctrl-D is end-of-input, so it only ends the session when there is nothing to submit.\n // On a line with text it is a forward delete, as in a shell.\n return context.empty ? { kind: \"exit\" } : { kind: \"delete\" }\n case \"a\":\n return { kind: \"cursorHome\" }\n case \"e\":\n return { kind: \"cursorEnd\" }\n case \"b\":\n return { kind: \"cursorLeft\" }\n case \"f\":\n return { kind: \"cursorRight\" }\n case \"u\":\n return { kind: \"killToStart\" }\n case \"k\":\n return { kind: \"killToEnd\" }\n case \"w\":\n return { kind: \"killWord\" }\n case \"p\":\n return { kind: \"historyPrev\" }\n case \"n\":\n return { kind: \"historyNext\" }\n case \"r\":\n return { kind: \"searchOpen\" }\n case \"o\":\n // The same thing ⌥r does, on a chord that cannot fail to arrive.\n //\n // ⌥r needs either the kitty protocol or the terminal's option-as-meta setting; a ctrl letter\n // needs neither, because it is a single control byte every terminal has always sent. Reported\n // as \"⌥r doesn't do anything\", and while the immediate cause was a fold with nothing in it,\n // the standing cause is that a view toggle should not depend on a terminal handshake at all.\n // ^O is what the reference CLI binds its own transcript toggle to, so the habit transfers.\n return { kind: \"reasoning\" }\n case \"z\":\n // Undo, not SIGTSTP. Ink puts stdin in raw mode, so the terminal never generates the\n // signal and the byte arrives here — which makes this a choice rather than an accident.\n // Suspending a chat you can leave with ^D is worth little; undo is worth a lot, and the\n // footer says so, which is what keeps the trade visible.\n return { kind: \"undo\" }\n case \"y\":\n return { kind: \"redo\" }\n default:\n return { kind: \"none\" }\n }\n}\n\nexport function keyToIntent(input: string, key: KeyState, context: KeyContext): Intent {\n // The mouse, before anything else, and unconditionally.\n //\n // Ink has no idea what a mouse report is and hands it over as text: with tracking on, one wheel notch\n // reached the insert branch and typed the report into the message. So every report is claimed here —\n // the wheel becomes a scroll and everything else becomes nothing at all, because a click that falls\n // through is the same bug with a different button.\n const mouse = mouseInput(input)\n if (mouse !== undefined) {\n if (mouse.rows !== 0) {\n return {\n kind: \"scroll\",\n move: mouse.rows < 0 ? \"up\" : \"down\",\n times: Math.abs(mouse.rows),\n }\n }\n // A press, drag or release. Reported rather than resolved: which row of the conversation a cell\n // sits on is a question about the frame, and this function has no frame. Still claimed either way —\n // a report that fell through would be typed into the message, which is the bug this branch exists\n // for and does not stop being one because the gesture is now useful.\n if (mouse.at !== undefined && mouse.kind !== undefined && mouse.kind !== \"wheel\") {\n return {\n kind: \"pointer\",\n gesture: mouse.kind,\n column: mouse.at.column,\n row: mouse.at.row,\n shift: mouse.shift === true,\n }\n }\n return { kind: \"none\" }\n }\n\n // A key *release* is not a keystroke. `reportEventTypes` is on so that `super` survives on an arrow\n // key (Ink's kitty branch requires the `:eventType` field), and the cost is that Ink hands the type\n // through without filtering — so every enhanced key arrives twice, down and up, and every chord would\n // fire twice. Repeats are kept: holding a key down is a real thing to do.\n if (key.eventType === \"release\") return { kind: \"none\" }\n\n // ─── shift extends a selection ───────────────────────────────────────────────────────\n //\n // Before the cmd, ctrl and option blocks, because every one of them would otherwise claim the chord\n // and drop the shift: `cmd+shift+←` arrives as `CSI 1;10D` — one plus shift plus super — and the\n // super block below matches on `key.super` without looking at shift at all.\n //\n // Only the motion keys are recognised, which is what keeps this from swallowing ordinary typing:\n // `key.shift` is true for every capital letter, and a letter matches none of the tests in\n // `shiftMotion`. Return is not a motion either, so `⇧⏎` still reaches the newline branch.\n if (key.shift) {\n const to = shiftMotion(key)\n if (to !== undefined) return { kind: \"extend\", to }\n }\n\n // ─── command chords ──────────────────────────────────────────────────────────────────\n //\n // `super` is Cmd, and it is only ever true once the kitty keyboard protocol has been negotiated —\n // no legacy sequence can express it, and Ink's legacy path folds it into `meta`, which is why\n // `cmd+←` used to word-move like `⌥←` instead of jumping to the start of the line.\n //\n // Horizontal is the line, vertical is the whole message: that is what macOS binds and what every\n // editor on the platform does. Before the ctrl and meta blocks because a chord can carry more than\n // one modifier, and cmd is the most specific claim.\n if (key.super) {\n if (key.leftArrow) return { kind: \"cursorHome\" }\n if (key.rightArrow) return { kind: \"cursorEnd\" }\n if (key.upArrow) return { kind: \"bufferStart\" }\n if (key.downArrow) return { kind: \"bufferEnd\" }\n if (key.backspace) return { kind: \"killToStart\" }\n if (key.delete) return { kind: \"killToEnd\" }\n if (input === \"z\") return key.shift ? { kind: \"redo\" } : { kind: \"undo\" }\n if (input === \"a\") return { kind: \"selectAll\" }\n // Reachable only where the protocol delivers `super`, and the terminal may claim them first for\n // its own copy — which is exactly why a *selection* in the composer does not auto-copy: the\n // fallback for a chord that may not arrive is retyping, not a surprise clipboard write.\n if (input === \"c\") return { kind: \"copySelection\" }\n if (input === \"x\") return { kind: \"cutSelection\" }\n // Unclaimed, and deliberately swallowed for the same reason an unclaimed option chord is: the\n // insert branch would type the bare letter, so cmd+s would put an \"s\" in the message.\n return { kind: \"none\" }\n }\n\n // Ctrl with an arrow or a backspace is the other spelling of a word operation — Linux and Windows\n // convention, and the reference honours `ctrl || meta || fn` for exactly one action because a\n // physical chord reaches a terminal in more than one encoding. Before `ctrlIntent`, which dispatches\n // on a *letter* and would see an empty string here.\n // A terminal's answer to a question this process asked is not a keystroke. Claimed next to the mouse\n // for the same reason: Ink hands it over as text, and text reaches the insert branch.\n if (isTerminalReply(input)) return { kind: \"none\" }\n\n if (key.ctrl && key.leftArrow) return { kind: \"wordLeft\" }\n if (key.ctrl && key.rightArrow) return { kind: \"wordRight\" }\n if (key.ctrl && key.backspace) return { kind: \"killWord\" }\n\n if (key.ctrl) return ctrlIntent(input.toLowerCase(), context)\n\n // ─── option chords ───────────────────────────────────────────────────────────────────\n //\n // Every one of these is measured against Ink's parser rather than assumed, because a terminal has\n // more than one way to send them and the parser reporting *a* key says nothing about which:\n //\n // ⌥← Apple Terminal `ESC b` → input \"b\" + meta iTerm2 `CSI 1;3D` → leftArrow + meta\n // ⌥→ Apple Terminal `ESC f` → input \"f\" + meta iTerm2 `CSI 1;3C` → rightArrow + meta\n // ⌥⌫ `ESC DEL` → backspace + meta\n // ⌥d `ESC d` → input \"d\" + meta\n // ⌥r `ESC r` → input \"r\" + meta\n // ⌥⏎ `ESC CR` → return + meta\n // ⇧⏎ kitty protocol `CSI 13;2u` → return + shift (only once the terminal is taught)\n //\n // Both spellings of each are honoured, so the same binding works in both families of terminal.\n //\n // Under the kitty protocol these arrive as `CSI <codepoint>;3u` instead — `⌥r` is `CSI 114;3u`, and\n // Ink reports it as `input \"r\"` with `meta` set, which is the same shape the table above describes.\n // That is why negotiating the protocol needed no change here: these bindings were always right and\n // simply never arrived, because Warp's Option-as-Meta setting is off by default and `⌥r` was\n // reaching us as the composed character `®`.\n if (key.meta) {\n if (key.return) return { kind: \"newline\" }\n // ⌥↑/⌥↓ walk the conversation a row at a time, and ⌥PgUp/⌥PgDn go to its ends. Bare ↑/↓ cannot\n // do this: they already mean line movement inside a message and history at its edges, and a\n // third meaning on one key is how a keyboard stops being predictable.\n if (key.pageUp) return { kind: \"scroll\", move: \"top\" }\n if (key.pageDown) return { kind: \"scroll\", move: \"bottom\" }\n if (key.upArrow) return { kind: \"scroll\", move: \"up\" }\n if (key.downArrow) return { kind: \"scroll\", move: \"down\" }\n if (key.leftArrow || input === \"b\") return { kind: \"wordLeft\" }\n if (key.rightArrow || input === \"f\") return { kind: \"wordRight\" }\n if (key.backspace) return { kind: \"killWord\" }\n if (input === \"d\") return { kind: \"killWordForward\" }\n // Reasoning is folded to a few rows by default, and this is how the rest of it is read. Same\n // shape as ⌥d — a letter with meta — so it works wherever the chords above already do.\n if (input === \"r\") return { kind: \"reasoning\" }\n // An unclaimed option chord does nothing. Falling through would reach the insert branch and\n // type the bare letter, so ⌥s would silently put an \"s\" in the message. Composed characters\n // (é, ∆) are unaffected: macOS sends those as the character itself, with no meta flag.\n return { kind: \"none\" }\n }\n\n // Shift+enter is a newline where the terminal can express it — `terminal-setup` is what teaches\n // iTerm2, VS Code, Ghostty and Kitty to send the sequence Ink already understands. Where it\n // cannot, this is never true and ⏎ submits, which is why ⌥⏎ is the documented chord.\n if (key.return && key.shift) return { kind: \"newline\" }\n\n // Paging the conversation, unmodified.\n //\n // Deliberately not ^U/^D, which the plan named: both are already taken by the editor — ^U deletes to\n // the start of the line and ^D leaves an empty one — and they are documented, shell-standard, and\n // reached by muscle memory. A scroll key that silently deleted half a message would be a worse bug\n // than no scroll key.\n if (key.pageUp) return { kind: \"scroll\", move: \"pageUp\" }\n if (key.pageDown) return { kind: \"scroll\", move: \"pageDown\" }\n\n // Home and End. Ink has always parsed them; `KeyState` never declared the fields, so both keys did\n // nothing whatsoever until now. The raw-sequence fallback further down catches the terminals that\n // send a spelling Ink does not flag.\n if (key.home) return { kind: \"cursorHome\" }\n if (key.end) return { kind: \"cursorEnd\" }\n\n if (key.return) return context.searching ? { kind: \"searchAccept\" } : { kind: \"submit\" }\n if (key.backspace) return { kind: \"backspace\" }\n if (key.delete) return { kind: \"delete\" }\n if (key.leftArrow) return { kind: \"cursorLeft\" }\n if (key.rightArrow) return { kind: \"cursorRight\" }\n // History at the edges of the buffer, line movement inside it. While searching both walk the match\n // list, which the reducer routes — the arrows mean \"previous\" and \"next\" either way.\n if (key.upArrow) {\n return context.searching || context.firstLine ? { kind: \"historyPrev\" } : { kind: \"lineUp\" }\n }\n if (key.downArrow) {\n return context.searching || context.lastLine\n ? { kind: \"historyNext\" }\n : { kind: \"lineDown\" }\n }\n\n // Escape closes a search; otherwise it is claimed deliberately and does nothing, rather than\n // falling through to the insert branch where it would put a control character into the buffer and\n // be sent to a model. Tab is claimed for the same reason.\n if (key.escape) {\n if (context.searching) return { kind: \"searchCancel\" }\n return context.scrolled ? { kind: \"scroll\", move: \"bottom\" } : { kind: \"none\" }\n }\n if (key.tab) return { kind: \"none\" }\n\n // A paste arrives as one large `input` with no key flags, so insert has to accept many\n // characters at once rather than assuming a single keypress.\n if (input === \"\") return { kind: \"none\" }\n\n // Home and End again, by raw sequence. There are four spellings in the wild and Ink flags only some\n // of them — the reference keeps the same fallback for the same reason (`useTextInput.ts:385-389`).\n // After the empty-input check and before the printable filter, which would otherwise strip the\n // escape and insert `[H` into the message.\n if (input === \"\\u001B[H\" || input === \"\\u001B[1~\") return { kind: \"cursorHome\" }\n if (input === \"\\u001B[F\" || input === \"\\u001B[4~\") return { kind: \"cursorEnd\" }\n\n // Newlines inside that chunk are line breaks, not control noise. Stripping them — which the\n // printable filter below would do — silently joins the last word of one line to the first word\n // of the next and submits nothing, so a pasted multi-line prompt arrives mangled with no error.\n if (/[\\r\\n]/.test(input)) {\n const lines = input.split(/\\r\\n|[\\r\\n]/).map(printableOnly)\n // A trailing newline means the final line is finished too; without one, the tail is still\n // being typed.\n const complete = lines.at(-1) === \"\" && lines.length > 1\n return { kind: \"paste\", lines: complete ? lines.slice(0, -1) : lines, complete }\n }\n\n const printable = printableOnly(input)\n return printable === \"\" ? { kind: \"none\" } : { kind: \"insert\", text: printable }\n}\n\n/**\n * Which motion a shift chord extends by, or `undefined` when the key is not a motion at all.\n *\n * Modifier first, then the bare keys, so `shift+cmd+←` is a line and `shift+⌥←` is a word rather than both\n * being a character. `shift+↑` extends a line up even on the first line, where the unshifted arrow means\n * history: selecting upward is unambiguous, and a history chord that also grew a selection would be one\n * key doing two unrelated things.\n *\n * `input` is deliberately not consulted. The `ESC b` spelling of `⌥←` would arrive shifted as `ESC B`, and\n * matching a capital letter here is how `shift+B` would start selecting words. Terminals send the CSI form\n * for a shifted arrow, which carries the flags this reads.\n */\nfunction shiftMotion(key: KeyState): MotionKind | undefined {\n if (key.super) {\n if (key.leftArrow) return \"cursorHome\"\n if (key.rightArrow) return \"cursorEnd\"\n if (key.upArrow) return \"bufferStart\"\n if (key.downArrow) return \"bufferEnd\"\n return undefined\n }\n if (key.meta || key.ctrl) {\n if (key.leftArrow) return \"wordLeft\"\n if (key.rightArrow) return \"wordRight\"\n return undefined\n }\n if (key.home) return \"cursorHome\"\n if (key.end) return \"cursorEnd\"\n if (key.leftArrow) return \"cursorLeft\"\n if (key.rightArrow) return \"cursorRight\"\n if (key.upArrow) return \"lineUp\"\n if (key.downArrow) return \"lineDown\"\n return undefined\n}\n\n/**\n * Drop C0 controls and DEL. A bracketed-paste marker or a stray escape sequence reaching the buffer\n * would be invisible on screen and sent to the model as if it had been typed.\n */\nfunction printableOnly(text: string): string {\n return [...text]\n .filter((char) => {\n const code = char.codePointAt(0) ?? 0\n return code >= 0x20 && code !== 0x7f\n })\n .join(\"\")\n}\n\n// ─── screen keymaps ──────────────────────────────────────────────────────────────────────\n//\n// The wizard and picker differ from the chat input in what Esc means — a *context*, not a new\n// module, which is why they live here beside `keyToIntent` rather than in per-screen files: one\n// keyboard home, closed by the same drift tests.\n\nimport type { SelectMove } from \"#lib/select\"\n\nexport type ListIntent =\n | { readonly kind: \"move\"; readonly move: SelectMove }\n | { readonly kind: \"choose\" }\n | { readonly kind: \"back\" }\n | { readonly kind: \"exit\" }\n | { readonly kind: \"none\" }\n\n/**\n * A checklist adds two verbs a single-select list does not have: tick a row, and finish.\n *\n * Space ticks and enter finishes, which is the convention every multi-select in a terminal uses — and\n * getting it the other way round is the mistake that makes a picker feel broken, because enter on a\n * highlighted row is such a strong habit that people submit with one thing ticked and never see the rest.\n * `a` and `n` are all/none, worth having when the list is fifty rows long.\n */\nexport type CheckIntent =\n | { readonly kind: \"move\"; readonly move: SelectMove }\n | { readonly kind: \"toggle\" }\n | { readonly kind: \"all\" }\n | { readonly kind: \"none-selected\" }\n | { readonly kind: \"confirm\" }\n | { readonly kind: \"cancel\" }\n | { readonly kind: \"none\" }\n\nexport function keyToCheckIntent(input: string, key: KeyState): CheckIntent {\n if (key.ctrl) {\n return input.toLowerCase() === \"c\" || input.toLowerCase() === \"d\"\n ? { kind: \"cancel\" }\n : { kind: \"none\" }\n }\n if (key.return) return { kind: \"confirm\" }\n if (key.escape) return { kind: \"cancel\" }\n // Ink reports the space bar as the input string \" \" with no flag of its own.\n if (input === \" \") return { kind: \"toggle\" }\n if (input === \"a\") return { kind: \"all\" }\n if (input === \"n\") return { kind: \"none-selected\" }\n\n const list = keyToListIntent(input, key)\n // Movement is shared so the two lists cannot drift apart; `choose` cannot arrive, because `key.return`\n // is handled above, and the remaining kinds are not this screen's.\n return list.kind === \"move\" ? list : { kind: \"none\" }\n}\n\n/**\n * List navigation: arrows or j/k, g/G for ends, enter chooses, esc backs out, ^C/^D leave.\n *\n * A digit jumps the cursor — visibly and reversibly — and deliberately does not choose: a stray\n * number must never launch an agent.\n */\nexport function keyToListIntent(input: string, key: KeyState): ListIntent {\n if (key.ctrl) {\n return input.toLowerCase() === \"c\" || input.toLowerCase() === \"d\"\n ? { kind: \"exit\" }\n : { kind: \"none\" }\n }\n if (key.return) return { kind: \"choose\" }\n if (key.escape) return { kind: \"back\" }\n if (key.upArrow) return { kind: \"move\", move: { kind: \"up\" } }\n if (key.downArrow) return { kind: \"move\", move: { kind: \"down\" } }\n\n switch (input) {\n case \"k\":\n return { kind: \"move\", move: { kind: \"up\" } }\n case \"j\":\n return { kind: \"move\", move: { kind: \"down\" } }\n case \"g\":\n return { kind: \"move\", move: { kind: \"first\" } }\n case \"G\":\n return { kind: \"move\", move: { kind: \"last\" } }\n default:\n break\n }\n if (/^[1-9]$/.test(input)) {\n return { kind: \"move\", move: { kind: \"jump\", index: Number(input) - 1 } }\n }\n return { kind: \"none\" }\n}\n\nexport type WizardKeyIntent =\n | { readonly kind: \"back\" }\n | { readonly kind: \"abort\" }\n | { readonly kind: \"commit\" }\n | { readonly kind: \"list\"; readonly intent: ListIntent }\n | { readonly kind: \"edit\"; readonly intent: Intent }\n\n/**\n * The wizard's chrome keys are checked before delegation — Esc means \"back a question\" here,\n * which is exactly why chat's `keyToIntent` (which claims Esc as none) is not reused raw.\n *\n * Text steps then get the full chat editor treatment (^A/^E, ^W, code-point cursor); select steps\n * get the list navigation. A pasted blob collapses to its first line — a wizard answer is one\n * line — and history chords mean nothing inside a question.\n */\nexport function keyToWizardIntent(\n input: string,\n key: KeyState,\n context: { readonly select: boolean; readonly empty: boolean },\n): WizardKeyIntent {\n if (key.ctrl && input.toLowerCase() === \"c\") return { kind: \"abort\" }\n if (key.escape) return { kind: \"back\" }\n if (key.return) return { kind: \"commit\" }\n\n if (context.select) {\n return { kind: \"list\", intent: keyToListIntent(input, key) }\n }\n\n // A wizard answer is one line — a pasted blob collapses to its first — so the cursor is always on\n // both the first and the last line, and ↑/↓ mean history rather than line movement. There is no\n // search here either.\n const intent = keyToIntent(input, key, {\n busy: false,\n empty: context.empty,\n firstLine: true,\n lastLine: true,\n searching: false,\n // A question is not a conversation: there is nothing to scroll and nothing to arm, and Esc is\n // claimed above as \"back a question\" before this is ever reached.\n armed: false,\n scrolled: false,\n })\n switch (intent.kind) {\n case \"submit\":\n return { kind: \"commit\" }\n case \"exit\":\n // ^D on an empty question line reads as \"get me out\", same as ^C.\n return { kind: \"abort\" }\n case \"arm\":\n case \"scroll\":\n // Unreachable in practice — ^C is claimed as `abort` above and there is nothing to scroll —\n // and listed rather than left to the default, so adding a session-only intent cannot\n // silently become an edit the wizard applies to a field.\n return { kind: \"edit\", intent: { kind: \"none\" } }\n case \"historyPrev\":\n case \"historyNext\":\n return { kind: \"edit\", intent: { kind: \"none\" } }\n case \"paste\":\n return {\n kind: \"edit\",\n intent: { kind: \"insert\", text: intent.lines[0] ?? \"\" },\n }\n default:\n return { kind: \"edit\", intent }\n }\n}\n"
7
7
  ],
8
8
  "mappings": ";+GA2BO,IAAM,EAA4B,CACrC,MAAO,GACP,OA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AG,CAC1D,UAEA,MAAO,CAAE,KAAM,OAAQ,QAAO",
9
- "debugId": "5643B4EA03895CAC64756E2164756E21",
9
+ "debugId": "D74D8516B55F9B6964756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{e,E,t,T}from"./index-7z4sw2dm.js";function f(n){return n!==void 0&&n!==""}function xe(n=process.env){return{noColor:f(n.NO_COLOR),dumbTerminal:n.TERM==="dumb",ci:f(n.CI)&&n.CI!=="false",debug:f(n.DEBUG),sandboxHome:f(n[`${e.envPrefix}HOME`])?n[`${e.envPrefix}HOME`]:void 0,noEnhancedKeys:f(n[`${e.envPrefix}NO_CSI_U`])}}import{existsSync as l,readdirSync as x,statSync as p}from"node:fs";import{homedir as R}from"node:os";import{isAbsolute as S,join as i,resolve as h,sep as b}from"node:path";function ee(n=process.env){return xe(n).sandboxHome??i(R(),e.stateDir)}function B(n){return i(ee(n),"agents")}function w(n){return i(ee(n),"store.db")}function Xt(n){let o=i(ee(n),"logs","server");return{out:i(o,"out.log"),err:i(o,"err.log")}}function Jt(n,o){let s=i(ee(o),"logs");return{out:i(s,`${n}.out.log`),err:i(s,`${n}.err.log`)}}function P(n,o){let s=h(B(o)),d=h(n);return d===s||d.startsWith(s+b)}function ao(n,o){if(P(n,o))return;return`note: ${h(n)} is outside the sandbox (${B(o)}) — this agent has no bare name, so every later command needs its path. Omit --dir to put it in the sandbox.`}function K(n){let o=B(n),s;try{s=x(o)}catch{return[]}let d=[];for(let r of s.sort()){let u=i(o,r),g=i(u,"agent.yaml");try{if(!p(u).isDirectory())continue}catch{continue}if(!l(g))continue;let y=0;try{y=p(g).mtimeMs}catch{}try{let c=T(g);d.push({ref:r,dir:u,manifestPath:g,mtimeMs:y,...c.id===void 0?{}:{id:c.id},...c.name===void 0?{}:{name:c.name},...c.modelId===void 0?{}:{modelId:c.modelId}})}catch(c){d.push({ref:r,dir:u,manifestPath:g,mtimeMs:y,problem:c instanceof Error?c.message:String(c)})}}let a=new Map;for(let r of d){if(r.id===void 0)continue;a.set(r.id,[...a.get(r.id)??[],r])}let m=d.map((r)=>{if(r.id===void 0||(a.get(r.id)?.length??0)<2)return r;return{...r,problem:`manifest id "${r.id}" is shared with another sandbox agent — their sessions share one history`}});return[...m.filter((r)=>r.problem===void 0),...m.filter((r)=>r.problem!==void 0)]}function te(n,o,s=process.cwd()){let d=n.includes(b)||n.includes("/")||n.endsWith(".yaml")||n.endsWith(".yml"),a=S(n)?n:h(s,n);if(!d&&l(a)&&l(i(B(o),n)))process.stderr.write(`note: using ./${n} from the current directory; a sandbox agent "${n}" also exists — run it from elsewhere, or as ${i(B(o),n)}
2
+ import{e,E,t,T}from"./index-tv4yv7d2.js";function f(n){return n!==void 0&&n!==""}function Ee(n=process.env){return{noColor:f(n.NO_COLOR),dumbTerminal:n.TERM==="dumb",ci:f(n.CI)&&n.CI!=="false",debug:f(n.DEBUG),sandboxHome:f(n[`${e.envPrefix}HOME`])?n[`${e.envPrefix}HOME`]:void 0,noEnhancedKeys:f(n[`${e.envPrefix}NO_CSI_U`])}}import{existsSync as l,readdirSync as x,statSync as p}from"node:fs";import{homedir as R}from"node:os";import{isAbsolute as S,join as i,resolve as h,sep as b}from"node:path";function ee(n=process.env){return Ee(n).sandboxHome??i(R(),e.stateDir)}function B(n){return i(ee(n),"agents")}function w(n){return i(ee(n),"store.db")}function Xt(n){let o=i(ee(n),"logs","server");return{out:i(o,"out.log"),err:i(o,"err.log")}}function Jt(n,o){let s=i(ee(o),"logs");return{out:i(s,`${n}.out.log`),err:i(s,`${n}.err.log`)}}function P(n,o){let s=h(B(o)),d=h(n);return d===s||d.startsWith(s+b)}function ao(n,o){if(P(n,o))return;return`note: ${h(n)} is outside the sandbox (${B(o)}) — this agent has no bare name, so every later command needs its path. Omit --dir to put it in the sandbox.`}function K(n){let o=B(n),s;try{s=x(o)}catch{return[]}let d=[];for(let r of s.sort()){let u=i(o,r),g=i(u,"agent.yaml");try{if(!p(u).isDirectory())continue}catch{continue}if(!l(g))continue;let y=0;try{y=p(g).mtimeMs}catch{}try{let c=T(g);d.push({ref:r,dir:u,manifestPath:g,mtimeMs:y,...c.id===void 0?{}:{id:c.id},...c.name===void 0?{}:{name:c.name},...c.modelId===void 0?{}:{modelId:c.modelId}})}catch(c){d.push({ref:r,dir:u,manifestPath:g,mtimeMs:y,problem:c instanceof Error?c.message:String(c)})}}let a=new Map;for(let r of d){if(r.id===void 0)continue;a.set(r.id,[...a.get(r.id)??[],r])}let m=d.map((r)=>{if(r.id===void 0||(a.get(r.id)?.length??0)<2)return r;return{...r,problem:`manifest id "${r.id}" is shared with another sandbox agent — their sessions share one history`}});return[...m.filter((r)=>r.problem===void 0),...m.filter((r)=>r.problem!==void 0)]}function te(n,o,s=process.cwd()){let d=n.includes(b)||n.includes("/")||n.endsWith(".yaml")||n.endsWith(".yml"),a=S(n)?n:h(s,n);if(!d&&l(a)&&l(i(B(o),n)))process.stderr.write(`note: using ./${n} from the current directory; a sandbox agent "${n}" also exists — run it from elsewhere, or as ${i(B(o),n)}
3
3
  `);if(d||l(a)){if(l(a)){if(p(a).isDirectory()){let g=i(a,"agent.yaml");if(l(g))return g;throw new t({code:"cli_agent_dir_without_manifest",message:`${n} is a directory with no agent.yaml inside.`,hint:"Point at the manifest itself, or at a directory that holds one. Sandbox agents are run by bare name, with no path separators."})}return a}throw new t({code:"cli_agent_path_missing",message:`${n} looks like a path, and nothing is there.`,hint:`Paths resolve against the current directory. For an agent in the sandbox, use its bare name — \`${e.slug} run <name>\` — which resolves under ${B(o)}.`})}let m=i(B(o),n,"agent.yaml");if(l(m))return m;let r=K(o).map((g)=>g.ref),u=E(n,r);throw new t({code:"cli_agent_unknown",message:`No agent named "${n}" in the sandbox${r.length===0?", which is empty":""}.`,hint:r.length===0?`Create one with \`${e.slug} init\`, or pass a path to an agent.yaml.`:`Known agents: ${r.join(", ")}.${u===void 0?"":` Did you mean ${u}?`} A path (./dir or file.yaml) is also accepted.`})}
4
- export{xe,ee,B,w,Xt,Jt,ao,K,te};
4
+ export{Ee,ee,B,w,Xt,Jt,ao,K,te};
5
5
 
6
- //# debugId=6CD099BA631E191464756E2164756E21
7
- //# sourceMappingURL=index-000rxxy3.js.map
6
+ //# debugId=6744C413011979E664756E2164756E21
7
+ //# sourceMappingURL=index-mtn0g9vc.js.map
@@ -6,6 +6,6 @@
6
6
  "/**\n * The home sandbox: where agents live when nobody says otherwise.\n *\n * `~/<stateDir>/` (brand-derived, so a rename moves it) holds `agents/<ref>/` for init-created\n * agents and `store.db` for their sessions. One root, one store: the store schema is already\n * keyed by agent id, and a cwd-relative default meant the same agent got a different session\n * history in every directory you happened to be in.\n *\n * Discovery reads manifest *headers*, never `loadManifest`: loading expands env references and\n * checks that key variables are set, so a picker built on it would fail exactly when it is\n * needed most — on a machine where the key is not exported yet. A broken manifest becomes a\n * listed entry with a `problem`, never a broken listing.\n *\n * Tests override the root with `<ENVPREFIX>HOME` pointed at a tmpdir; nothing here touches the\n * real home directory when that is set.\n */\n\nimport { existsSync, readdirSync, statSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { isAbsolute, join, resolve, sep } from \"node:path\"\nimport { BRAND, HarnessError, nearest, readManifestHeader } from \"@dispach/core\"\nimport { readEnv } from \"#lib/env\"\n\nexport function sandboxRoot(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n const override = readEnv(env).sandboxHome\n return override ?? join(homedir(), BRAND.stateDir)\n}\n\nexport function agentsDir(env?: Readonly<Record<string, string | undefined>>): string {\n return join(sandboxRoot(env), \"agents\")\n}\n\nexport function storePath(env?: Readonly<Record<string, string | undefined>>): string {\n return join(sandboxRoot(env), \"store.db\")\n}\n\n/**\n * Where a service writes its output, keyed by the agent's **manifest id**.\n *\n * Not by the directory name, which is what `run <ref>` takes — the same split as the store's\n * `agent_id` and the launchd label. Two directories with one manifest id therefore share these files,\n * which `listAgents` already warns about.\n *\n * Here rather than in `daemon.ts`, where it was private, because it is a fact about the sandbox layout\n * and `remove` needs it too. Moved rather than duplicated: a second copy of a path derivation is how\n * one command deletes a file another command is still writing to.\n */\n/**\n * Where the one server unit writes, in a **subdirectory** rather than beside the agent logs.\n *\n * `logs/<id>.err.log` is the per-agent shape, so a flat `logs/server.err.log` would collide with an\n * agent whose id happened to be `server` — and the collision would appear as a service and an agent\n * appending to one file, which is the kind of thing nobody diagnoses from a log.\n */\nexport function serverLogPaths(env?: Readonly<Record<string, string | undefined>>): {\n readonly out: string\n readonly err: string\n} {\n const dir = join(sandboxRoot(env), \"logs\", \"server\")\n return { out: join(dir, \"out.log\"), err: join(dir, \"err.log\") }\n}\n\nexport function logPaths(\n agentId: string,\n env?: Readonly<Record<string, string | undefined>>,\n): { readonly out: string; readonly err: string } {\n const dir = join(sandboxRoot(env), \"logs\")\n return { out: join(dir, `${agentId}.out.log`), err: join(dir, `${agentId}.err.log`) }\n}\n\n/**\n * Is this path inside the sandbox's agents directory?\n *\n * Both sides are resolved first, for the reason `root.ts` already records: an unresolved\n * `<base>/../../elsewhere` passes a prefix test while landing nowhere near the base. The `sep`\n * suffix is what stops `~/.brand/agents-backup` reading as inside `~/.brand/agents`.\n */\nexport function insideSandbox(\n targetDir: string,\n env?: Readonly<Record<string, string | undefined>>,\n): boolean {\n const base = resolve(agentsDir(env))\n const target = resolve(targetDir)\n return target === base || target.startsWith(base + sep)\n}\n\n/**\n * The one-line note an out-of-sandbox target earns, or `undefined` when it is inside.\n *\n * A note rather than a refusal: `init --dir ./examples/scout` is a legitimate thing to want, and a\n * command that refuses it would be one people work around with `mv`. What is *not* legitimate is\n * doing it silently — an agent outside the sandbox has no bare name, so every later `run`, `config`,\n * `daemon` and `schedules` call needs a path, and the reason for that is only obvious at the moment\n * the directory is chosen.\n *\n * Pure and separate from the write so the sentence can be asserted without a filesystem.\n */\nexport function outsideSandboxNote(\n targetDir: string,\n env?: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n if (insideSandbox(targetDir, env)) return undefined\n return `note: ${resolve(targetDir)} is outside the sandbox (${agentsDir(env)}) — this agent has no bare name, so every later command needs its path. Omit --dir to put it in the sandbox.`\n}\n\nexport interface SandboxAgent {\n /** The directory name — what `run <ref>` takes. Filesystem-unique by construction. */\n readonly ref: string\n /** Absolute agent directory. */\n readonly dir: string\n /** Absolute path to its agent.yaml. */\n readonly manifestPath: string\n /** From the manifest header; may differ from `ref` for hand-copied directories. */\n readonly id?: string\n readonly name?: string\n /** Raw — may literally be an unexpanded `${MODEL_ID}` reference. */\n readonly modelId?: string\n /** Modification time of the manifest, for \"recently used\" ordering hints. */\n readonly mtimeMs: number\n /** Present when the manifest could not be read; the entry lists anyway, honestly. */\n readonly problem?: string\n}\n\n/**\n * Every agent directory in the sandbox, alphabetical by ref with broken entries last.\n *\n * Broken means the header could not be read — the entry still appears, carrying the problem,\n * because a listing that silently hides a corrupted agent turns \"why is my agent gone\" into a\n * filesystem investigation. Duplicate manifest ids are marked the same way: both run, but their\n * sessions share a store keyed by that id, which is worth a warning rather than a pretence.\n */\nexport function listAgents(\n env?: Readonly<Record<string, string | undefined>>,\n): readonly SandboxAgent[] {\n const dir = agentsDir(env)\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n // No sandbox yet is the normal first-run state, not an error.\n return []\n }\n\n const agents: SandboxAgent[] = []\n for (const ref of entries.sort()) {\n const agentDir = join(dir, ref)\n const manifestPath = join(agentDir, \"agent.yaml\")\n try {\n if (!statSync(agentDir).isDirectory()) continue\n } catch {\n continue\n }\n if (!existsSync(manifestPath)) continue\n\n let mtimeMs = 0\n try {\n mtimeMs = statSync(manifestPath).mtimeMs\n } catch {\n // Raced away between existsSync and statSync; list it with what we have.\n }\n\n try {\n const header = readManifestHeader(manifestPath)\n agents.push({\n ref,\n dir: agentDir,\n manifestPath,\n mtimeMs,\n ...(header.id === undefined ? {} : { id: header.id }),\n ...(header.name === undefined ? {} : { name: header.name }),\n ...(header.modelId === undefined ? {} : { modelId: header.modelId }),\n })\n } catch (error) {\n agents.push({\n ref,\n dir: agentDir,\n manifestPath,\n mtimeMs,\n problem: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n // Duplicate manifest ids share session history — say so rather than pretend it is fine.\n const byId = new Map<string, SandboxAgent[]>()\n for (const agent of agents) {\n if (agent.id === undefined) continue\n byId.set(agent.id, [...(byId.get(agent.id) ?? []), agent])\n }\n const marked = agents.map((agent) => {\n if (agent.id === undefined || (byId.get(agent.id)?.length ?? 0) < 2) return agent\n return {\n ...agent,\n problem: `manifest id \"${agent.id}\" is shared with another sandbox agent — their sessions share one history`,\n }\n })\n\n return [\n ...marked.filter((a) => a.problem === undefined),\n ...marked.filter((a) => a.problem !== undefined),\n ]\n}\n\n/**\n * Turn what the user typed into a manifest path.\n *\n * The filesystem wins: anything that looks like a path (a separator, a .yaml suffix, or a thing\n * that exists here) is a path, so `./milo` always forces the file even when a sandbox agent\n * `milo` exists — the same rule git applies to pathspec-versus-branch, with the same free escape\n * hatch. Only then is the ref tried as a sandbox agent name.\n */\nexport function resolveAgentRef(\n ref: string,\n env?: Readonly<Record<string, string | undefined>>,\n cwd: string = process.cwd(),\n): string {\n const looksLikePath =\n ref.includes(sep) || ref.includes(\"/\") || ref.endsWith(\".yaml\") || ref.endsWith(\".yml\")\n const asPath = isAbsolute(ref) ? ref : resolve(cwd, ref)\n\n // A bare name that happens to exist in the cwd wins as a path — but silently running the\n // wrong agent is worse than one stderr line. Only fires on genuine ambiguity.\n if (!looksLikePath && existsSync(asPath) && existsSync(join(agentsDir(env), ref))) {\n process.stderr.write(\n `note: using ./${ref} from the current directory; a sandbox agent \"${ref}\" also exists — run it from elsewhere, or as ${join(agentsDir(env), ref)}\\n`,\n )\n }\n\n if (looksLikePath || existsSync(asPath)) {\n if (existsSync(asPath)) {\n if (statSync(asPath).isDirectory()) {\n const inside = join(asPath, \"agent.yaml\")\n if (existsSync(inside)) return inside\n throw new HarnessError({\n code: \"cli_agent_dir_without_manifest\",\n message: `${ref} is a directory with no agent.yaml inside.`,\n hint: \"Point at the manifest itself, or at a directory that holds one. Sandbox agents are run by bare name, with no path separators.\",\n })\n }\n return asPath\n }\n throw new HarnessError({\n code: \"cli_agent_path_missing\",\n message: `${ref} looks like a path, and nothing is there.`,\n hint: `Paths resolve against the current directory. For an agent in the sandbox, use its bare name — \\`${BRAND.slug} run <name>\\` — which resolves under ${agentsDir(env)}.`,\n })\n }\n\n const sandboxManifest = join(agentsDir(env), ref, \"agent.yaml\")\n if (existsSync(sandboxManifest)) return sandboxManifest\n\n const known = listAgents(env).map((agent) => agent.ref)\n const suggestion = nearest(ref, known)\n throw new HarnessError({\n code: \"cli_agent_unknown\",\n message: `No agent named \"${ref}\" in the sandbox${known.length === 0 ? \", which is empty\" : \"\"}.`,\n hint:\n known.length === 0\n ? `Create one with \\`${BRAND.slug} init\\`, or pass a path to an agent.yaml.`\n : `Known agents: ${known.join(\", \")}.${suggestion === undefined ? \"\" : ` Did you mean ${suggestion}?`} A path (./dir or file.yaml) is also accepted.`,\n })\n}\n"
7
7
  ],
8
8
  "mappings": ";yCAeA,SAAS,CAAK,CAAC,EAAoC,CAC/C,OAAO,IAAU,QAAa,IAAU,GAGrC,SAAS,EAAO,CAAC,EAAoD,QAAQ,IAAe,CAC/F,MAAO,CACH,QAAS,EAAM,EAAI,QAAQ,EAC3B,aAAc,EAAI,OAAS,OAG3B,GAAI,EAAM,EAAI,EAAE,GAAK,EAAI,KAAO,QAChC,MAAO,EAAM,EAAI,KAAK,EAEtB,YAAa,EAAM,EAAI,GAAG,EAAM,gBAAgB,EAC1C,EAAI,GAAG,EAAM,iBACb,OAEN,eAAgB,EAAM,EAAI,GAAG,EAAM,oBAAoB,CAC3D,EChBJ,qBAAS,iBAAY,cAAa,gBAClC,kBAAS,gBACT,qBAAS,UAAY,aAAM,SAAS,kBAI7B,SAAS,EAAW,CACvB,EAAoD,QAAQ,IACtD,CAEN,OADiB,GAAQ,CAAG,EAAE,aACX,EAAK,EAAQ,EAAG,EAAM,QAAQ,EAG9C,SAAS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,EAAK,EAAU,CAAG,EAAG,CAAG;AAAA,CACpJ,EAGJ,GAAI,GAAiB,EAAW,CAAM,EAAG,CACrC,GAAI,EAAW,CAAM,EAAG,CACpB,GAAI,EAAS,CAAM,EAAE,YAAY,EAAG,CAChC,IAAM,EAAS,EAAK,EAAQ,YAAY,EACxC,GAAI,EAAW,CAAM,EAAG,OAAO,EAC/B,MAAM,IAAI,EAAa,CACnB,KAAM,iCACN,QAAS,GAAG,8CACZ,KAAM,+HACV,CAAC,EAEL,OAAO,EAEX,MAAM,IAAI,EAAa,CACnB,KAAM,yBACN,QAAS,GAAG,6CACZ,KAAM,mGAAmG,EAAM,4CAA4C,EAAU,CAAG,IAC5K,CAAC,EAGL,IAAM,EAAkB,EAAK,EAAU,CAAG,EAAG,EAAK,YAAY,EAC9D,GAAI,EAAW,CAAe,EAAG,OAAO,EAExC,IAAM,EAAQ,EAAW,CAAG,EAAE,IAAI,CAAC,IAAU,EAAM,GAAG,EAChD,EAAa,EAAQ,EAAK,CAAK,EACrC,MAAM,IAAI,EAAa,CACnB,KAAM,oBACN,QAAS,mBAAmB,oBAAsB,EAAM,SAAW,EAAI,mBAAqB,MAC5F,KACI,EAAM,SAAW,EACX,qBAAqB,EAAM,gDAC3B,iBAAiB,EAAM,KAAK,IAAI,KAAK,IAAe,OAAY,GAAK,iBAAiB,oDACpG,CAAC",
9
- "debugId": "6CD099BA631E191464756E2164756E21",
9
+ "debugId": "6744C413011979E664756E2164756E21",
10
10
  "names": []
11
11
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{e,T,x,_,M,m}from"./index-7z4sw2dm.js";import{w,K}from"./index-000rxxy3.js";async function zr(t,i,n){let s=[];if(t.length===0)for(let a of K(i)){if(a.problem!==void 0||a.id===void 0)continue;s.push({agentId:a.id,manifestPath:a.manifestPath})}else for(let a of t){let r=T(a);s.push({agentId:r.id??"",manifestPath:a})}let o=await f(async(a)=>new Map((await a.agentState.list()).filter((r)=>!r.enabled).map((r)=>[r.agentId,r.reason])),n);return s.map((a)=>{let r=o?.get(a.agentId),d=o?.has(a.agentId)===!0;return{...a,enabled:!d,...r===void 0?{}:{reason:r}}})}async function f(t,i){let n;try{return n=await M.open({path:i??w()}),await t(n)}catch{return}finally{await n?.close()}}async function Pn(t,i,n,s){await f(async(o)=>{if(i)await o.agentState.enable(t);else await o.agentState.disable(t,new Date().toISOString(),n===void 0?void 0:n)},s)}async function Br(t,i){return await f(async(n)=>{let s=await n.agentState.get(t);if(s===void 0)return{enabled:!0};return{enabled:s.enabled,...s.reason===void 0?{}:{reason:s.reason}}},i)}async function Ne(t,i){return await f(async(n)=>{let s=await n.leases.get(t);if(s===void 0)return;if(s.pid===process.pid||!_(s.pid))return;return s},i)}async function Ce(t){return[...(await St(t)).filter((n)=>n.baseUrl!==void 0)].sort((n,s)=>n.agentId.localeCompare(s.agentId))[0]}async function St(t){return await f(async(i)=>(await i.leases.all()).filter((n)=>n.pid!==process.pid&&_(n.pid)),t)??[]}function xt(t){return t===void 0||t===""?"":T(t).id??""}function Je(t){let i=process.env[`${e.envPrefix}API_TOKEN`];try{let n=x(t,{env:m([t])}),s=n.env[n.manifest.server.tokenEnv];return s===void 0||s===""?i:s}catch{return i===""?void 0:i}}async function Qe(t,i,n,s){let o=t.baseUrl;if(o===void 0)return{ok:!1,status:0,detail:"this host serves no HTTP"};let a=s===void 0?void 0:Je(s);try{let r=await fetch(`${o}${i}`,{method:"POST",headers:{"content-type":"application/json",...a===void 0?{}:{authorization:`Bearer ${a}`}},body:JSON.stringify(n),signal:AbortSignal.timeout(c)});if(r.ok){let u=await r.json().catch(()=>{return});return{ok:!0,status:r.status,...u===void 0?{}:{body:u}}}let d=await r.json().catch(()=>{return});return{ok:!1,status:r.status,...d?.error?.message===void 0?{}:{detail:d.error.message},...d?.error?.hint===void 0?{}:{hint:d.error.hint}}}catch(r){return{ok:!1,status:0,detail:r instanceof Error?r.message:String(r)}}}async function ur(t,i,n,s){let o=t.baseUrl;if(o===void 0)return{ok:!1,status:0,detail:"this host serves no HTTP"};let a=s===void 0?void 0:Je(s);try{let r=await fetch(`${o}${n}`,{method:i,headers:a===void 0?{}:{authorization:`Bearer ${a}`},signal:AbortSignal.timeout(c)}),d=await r.json().catch(()=>{return});if(r.ok)return{ok:!0,status:r.status,...d===void 0?{}:{body:d}};let u=d;return{ok:!1,status:r.status,...u?.error?.message===void 0?{}:{detail:u.error.message},...u?.error?.hint===void 0?{}:{hint:u.error.hint}}}catch(r){return{ok:!1,status:0,detail:r instanceof Error?r.message:String(r)}}}var c=1e4;function Kt(t,i){for(let n of K(i))if(n.id===t)return n.manifestPath;return}
3
- export{zr,Pn,Br,Ne,Ce,St,xt,Je,Qe,ur,Kt};
2
+ import{e,T,x,_,M,m}from"./index-tv4yv7d2.js";import{w,K}from"./index-mtn0g9vc.js";async function zr(t,i,n){let s=[];if(t.length===0)for(let a of K(i)){if(a.problem!==void 0||a.id===void 0)continue;s.push({agentId:a.id,manifestPath:a.manifestPath})}else for(let a of t){let r=T(a);s.push({agentId:r.id??"",manifestPath:a})}let o=await f(async(a)=>new Map((await a.agentState.list()).filter((r)=>!r.enabled).map((r)=>[r.agentId,r.reason])),n);return s.map((a)=>{let r=o?.get(a.agentId),d=o?.has(a.agentId)===!0;return{...a,enabled:!d,...r===void 0?{}:{reason:r}}})}async function f(t,i){let n;try{return n=await M.open({path:i??w()}),await t(n)}catch{return}finally{await n?.close()}}async function Pn(t,i,n,s){await f(async(o)=>{if(i)await o.agentState.enable(t);else await o.agentState.disable(t,new Date().toISOString(),n===void 0?void 0:n)},s)}async function Br(t,i){return await f(async(n)=>{let s=await n.agentState.get(t);if(s===void 0)return{enabled:!0};return{enabled:s.enabled,...s.reason===void 0?{}:{reason:s.reason}}},i)}async function Ce(t,i){return await f(async(n)=>{let s=await n.leases.get(t);if(s===void 0)return;if(s.pid===process.pid||!_(s.pid))return;return s},i)}async function Pe(t){return[...(await St(t)).filter((n)=>n.baseUrl!==void 0)].sort((n,s)=>n.agentId.localeCompare(s.agentId))[0]}async function St(t){return await f(async(i)=>(await i.leases.all()).filter((n)=>n.pid!==process.pid&&_(n.pid)),t)??[]}function xt(t){return t===void 0||t===""?"":T(t).id??""}function Je(t){let i=process.env[`${e.envPrefix}API_TOKEN`];try{let n=x(t,{env:m([t])}),s=n.env[n.manifest.server.tokenEnv];return s===void 0||s===""?i:s}catch{return i===""?void 0:i}}async function Qe(t,i,n,s){let o=t.baseUrl;if(o===void 0)return{ok:!1,status:0,detail:"this host serves no HTTP"};let a=s===void 0?void 0:Je(s);try{let r=await fetch(`${o}${i}`,{method:"POST",headers:{"content-type":"application/json",...a===void 0?{}:{authorization:`Bearer ${a}`}},body:JSON.stringify(n),signal:AbortSignal.timeout(c)});if(r.ok){let u=await r.json().catch(()=>{return});return{ok:!0,status:r.status,...u===void 0?{}:{body:u}}}let d=await r.json().catch(()=>{return});return{ok:!1,status:r.status,...d?.error?.message===void 0?{}:{detail:d.error.message},...d?.error?.hint===void 0?{}:{hint:d.error.hint}}}catch(r){return{ok:!1,status:0,detail:r instanceof Error?r.message:String(r)}}}async function ur(t,i,n,s){let o=t.baseUrl;if(o===void 0)return{ok:!1,status:0,detail:"this host serves no HTTP"};let a=s===void 0?void 0:Je(s);try{let r=await fetch(`${o}${n}`,{method:i,headers:a===void 0?{}:{authorization:`Bearer ${a}`},signal:AbortSignal.timeout(c)}),d=await r.json().catch(()=>{return});if(r.ok)return{ok:!0,status:r.status,...d===void 0?{}:{body:d}};let u=d;return{ok:!1,status:r.status,...u?.error?.message===void 0?{}:{detail:u.error.message},...u?.error?.hint===void 0?{}:{hint:u.error.hint}}}catch(r){return{ok:!1,status:0,detail:r instanceof Error?r.message:String(r)}}}var c=1e4;function Kt(t,i){for(let n of K(i))if(n.id===t)return n.manifestPath;return}
3
+ export{zr,Pn,Br,Ce,Pe,St,xt,Je,Qe,ur,Kt};
4
4
 
5
- //# debugId=D1618D18D9D176A664756E2164756E21
6
- //# sourceMappingURL=index-dwyr2kdm.js.map
5
+ //# debugId=00E8CDAE2C5FDD7B64756E2164756E21
6
+ //# sourceMappingURL=index-qdbq8crg.js.map
@@ -5,6 +5,6 @@
5
5
  "/**\n * Reaching a running host, and reading the durable on/off switch.\n *\n * Shared by `serve`, `stop` and `start`, because all three ask the same two questions and a second\n * answer to either is a disagreement waiting to happen: *which agents is this sandbox supposed to\n * run*, and *where is the process already running them*.\n *\n * **Why an HTTP request rather than a signal.** Since one process hosts several agents, stopping\n * one by signalling the lease holder takes every other agent in that process down with it. A signal\n * also cannot name an agent. So `stop` posts to the host, which disposes exactly one — and the\n * address comes off the lease row rather than from a manifest, because `--port` overrides the file,\n * `--port 0` picks one at random and a container republishes it. Guessing 7420 is how a second host\n * on 7421 becomes invisible to the one command that must never miss it.\n *\n * **The fallback is the old behaviour, not an error.** A lease with no address is a `run` REPL or an\n * embedded runtime — real states, serving no HTTP — and those are still stopped by signalling the\n * process, which is what `stop` did for every lease before any of this existed.\n */\n\nimport { dirname } from \"node:path\"\nimport {\n BRAND,\n type LeaseRecord,\n loadManifest,\n processAlive,\n readManifestHeader,\n SqliteStore,\n} from \"@dispach/core\"\nimport { ambientEnv } from \"#lib/ambient\"\nimport { listAgents, storePath } from \"#lib/sandbox\"\n\n/** An agent the sandbox holds, with the durable switch resolved. */\nexport interface HostableAgent {\n readonly agentId: string\n readonly manifestPath: string\n readonly enabled: boolean\n /** Why it was switched off, when somebody said. */\n readonly reason?: string\n}\n\n/**\n * The manifests a bare `serve` should host, and the ones it should not.\n *\n * A listing rather than a filter, because the caller has to *report* what it is skipping: an agent\n * missing from a banner with no line explaining it is the \"I set this up and it is not running\"\n * failure the switch exists to make explicable.\n *\n * Broken entries are dropped here rather than surfaced, and that is the one thing this hides: a\n * directory whose header will not parse has no id, so there is nothing to look the state up by and\n * nothing to serve. the agents listing is what shows those, and it shows them already.\n */\nexport async function hostableAgents(\n paths: readonly string[],\n env: Readonly<Record<string, string | undefined>>,\n store?: string,\n): Promise<readonly HostableAgent[]> {\n const found: { agentId: string; manifestPath: string }[] = []\n\n if (paths.length === 0) {\n // The bare form: whatever the sandbox holds. This is what the service unit runs, and it is\n // why `agent_state` exists — \"every agent here\" needs an answer to \"except which\".\n for (const agent of listAgents(env)) {\n if (agent.problem !== undefined || agent.id === undefined) continue\n found.push({ agentId: agent.id, manifestPath: agent.manifestPath })\n }\n } else {\n for (const manifestPath of paths) {\n // The header, not a full load: reading a manifest to learn its id must not depend on\n // the agent's credentials being present, which is the whole reason\n // `readManifestHeader` exists and why the picker is built on it.\n const header = readManifestHeader(manifestPath)\n found.push({ agentId: header.id ?? \"\", manifestPath })\n }\n }\n\n const disabled = await withStore(\n async (db) =>\n new Map(\n (await db.agentState.list())\n .filter((row) => !row.enabled)\n .map((row) => [row.agentId, row.reason]),\n ),\n store,\n )\n\n return found.map((entry) => {\n const reason = disabled?.get(entry.agentId)\n const off = disabled?.has(entry.agentId) === true\n return {\n ...entry,\n enabled: !off,\n ...(reason === undefined ? {} : { reason }),\n }\n })\n}\n\n/**\n * Open the store, ask one question, close it.\n *\n * Deliberately a second, short-lived connection rather than the one `Runtime.create` opens: the\n * answer is needed *before* the runtime exists, because it decides which agents the runtime is\n * asked for. Handing the runtime a caller-owned store would work and would move shutdown ownership\n * into the command, which is a larger change than one sequential read deserves — the migrations are\n * already applied, so this costs a couple of milliseconds.\n *\n * `undefined` on any failure, and the callers treat that as \"nothing is disabled\". A missing store\n * is the ordinary first-run state, and a `serve` that refused to start because it could not read an\n * on/off table would be a worse failure than the one it was guarding against.\n *\n * **The path is threaded rather than defaulted at each call site**, because `serve` honours\n * `--store` and these helpers did not — so a host serving out of one database would have read its\n * on/off switch from another. Invisible in normal use, where both resolve to the sandbox, and\n * wrong in exactly the configuration the tests use.\n */\nasync function withStore<T>(\n work: (store: SqliteStore) => Promise<T>,\n path?: string,\n): Promise<T | undefined> {\n let store: SqliteStore | undefined\n try {\n store = await SqliteStore.open({ path: path ?? storePath() })\n return await work(store)\n } catch {\n return undefined\n } finally {\n await store?.close()\n }\n}\n\n/** The durable switch, written from a command rather than through a host. */\nexport async function writeAgentState(\n agentId: string,\n enabled: boolean,\n reason?: string,\n store?: string,\n): Promise<void> {\n await withStore(async (db) => {\n if (enabled) await db.agentState.enable(agentId)\n else\n await db.agentState.disable(\n agentId,\n new Date().toISOString(),\n reason === undefined ? undefined : reason,\n )\n }, store)\n}\n\n/** Whether this agent is switched off, and why. */\nexport async function agentStateOf(\n agentId: string,\n store?: string,\n): Promise<{ enabled: boolean; reason?: string } | undefined> {\n return await withStore(async (db) => {\n const row = await db.agentState.get(agentId)\n if (row === undefined) return { enabled: true }\n return { enabled: row.enabled, ...(row.reason === undefined ? {} : { reason: row.reason }) }\n }, store)\n}\n\n/**\n * The live process serving this agent, if there is one.\n *\n * Liveness is re-checked here rather than trusted from the row, for the recorded reason: a boot\n * that fails *after* claiming leaves a lease seconds old with no process under it, and anything\n * reading a lease to decide what to do has to probe rather than believe the heartbeat.\n */\nexport async function liveHostOf(\n agentId: string,\n store?: string,\n): Promise<LeaseRecord | undefined> {\n return await withStore(async (db) => {\n const lease = await db.leases.get(agentId)\n if (lease === undefined) return undefined\n if (lease.pid === process.pid || !processAlive(lease.pid)) return undefined\n return lease\n }, store)\n}\n\n/**\n * Any live host with an HTTP address, for `start`.\n *\n * **Not `liveHostOf(agentId)`, and that is the whole reason this exists.** A stopped agent has no\n * lease — `dispose` released it — so looking for \"the host holding this agent\" finds nothing and\n * `start` would report that nothing was running while a host sat there ready to adopt it. Found by\n * running the pair in order rather than by reading either one.\n *\n * With several hosts this asks the first by agent id. Nondeterministic and harmless: any host can\n * serve any agent in the sandbox, and one that cannot look the manifest up answers `501` rather\n * than failing quietly.\n */\nexport async function anyLiveHost(store?: string): Promise<LeaseRecord | undefined> {\n const hosts = (await liveHosts(store)).filter((lease) => lease.baseUrl !== undefined)\n return [...hosts].sort((a, b) => a.agentId.localeCompare(b.agentId))[0]\n}\n\n/** Every live lease, for the commands that report on the whole sandbox. */\nexport async function liveHosts(store?: string): Promise<readonly LeaseRecord[]> {\n return (\n (await withStore(\n async (db) =>\n (\n await db.leases.all()\n ).filter((lease) => lease.pid !== process.pid && processAlive(lease.pid)),\n store,\n )) ?? []\n )\n}\n\n/**\n * The credential a running host will want, best effort.\n *\n * The manifest's live env is the authority — that is where `serve` itself read the token from — so\n * this loads it. When the load fails it falls back to the process environment under the brand's\n * default variable, because the common reason for a failed load is a missing *model* key and\n * refusing to stop an agent over that would be absurd. A wrong or absent token is not silent: the\n * request comes back `401` and the caller says which variable to set.\n */\n/**\n * The agent id a manifest declares, without loading it.\n *\n * `readManifestHeader` rather than `loadManifest` for the reason `lib/sandbox.ts` already records:\n * loading checks that the key variables are set, so a *lookup* built on it fails exactly when the\n * agent is misconfigured — which is when you most need to name it. Here that would mean `run` and\n * `web` refusing to find a host for an agent whose `.env` is incomplete.\n */\nexport function agentIdFor(manifestPath: string | undefined): string {\n return manifestPath === undefined || manifestPath === \"\"\n ? \"\"\n : (readManifestHeader(manifestPath).id ?? \"\")\n}\n\nexport function hostToken(manifestPath: string): string | undefined {\n const fallback = process.env[`${BRAND.envPrefix}API_TOKEN`]\n try {\n const loaded = loadManifest(manifestPath, { env: ambientEnv([manifestPath]) })\n const configured = loaded.env[loaded.manifest.server.tokenEnv]\n return configured === undefined || configured === \"\" ? fallback : configured\n } catch {\n return fallback === \"\" ? undefined : fallback\n }\n}\n\nexport interface HostReply {\n readonly ok: boolean\n readonly status: number\n /** The server's own `error.message`, when it sent one. */\n readonly detail?: string\n /**\n * The parsed success body, for the callers that need one.\n *\n * `stop` and `start` only ever asked whether it worked, so this was discarded. Minting a\n * credential is the first caller that needs what came back — the secret is printed **once** and\n * exists nowhere else, so throwing the body away would make the command useless.\n */\n readonly body?: unknown\n /** The server's `error.hint`, which is the half a person acts on. */\n readonly hint?: string\n}\n\n/**\n * POST to a running host, with a bounded wait.\n *\n * Bounded because the alternative is a stop command that hangs on a wedged host, and the whole\n * brief for `stop` is that a person reaching for it is not in a position to go investigating. A\n * timeout falls through to the process-level stop, which is the thing that works on a host that has\n * stopped answering.\n */\nexport async function postToHost(\n lease: LeaseRecord,\n path: string,\n body: Readonly<Record<string, unknown>>,\n manifestPath?: string,\n): Promise<HostReply> {\n const base = lease.baseUrl\n if (base === undefined) return { ok: false, status: 0, detail: \"this host serves no HTTP\" }\n const token = manifestPath === undefined ? undefined : hostToken(manifestPath)\n\n try {\n const response = await fetch(`${base}${path}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(token === undefined ? {} : { authorization: `Bearer ${token}` }),\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(HOST_TIMEOUT_MS),\n })\n if (response.ok) {\n const body: unknown = await response.json().catch(() => undefined)\n return {\n ok: true,\n status: response.status,\n ...(body === undefined ? {} : { body }),\n }\n }\n const parsed = (await response.json().catch(() => undefined)) as\n | { error?: { message?: string; hint?: string } }\n | undefined\n return {\n ok: false,\n status: response.status,\n ...(parsed?.error?.message === undefined ? {} : { detail: parsed.error.message }),\n ...(parsed?.error?.hint === undefined ? {} : { hint: parsed.error.hint }),\n }\n } catch (error) {\n return {\n ok: false,\n status: 0,\n detail: error instanceof Error ? error.message : String(error),\n }\n }\n}\n\n/**\n * Any method against a running host, with the same bound and the same error shape.\n *\n * `postToHost` is this with `POST` and a body; both exist because a `GET` with a `content-type` and\n * an empty body is a request some proxies mangle, and because the one-method version read better at\n * the four call sites that had it. This is what `credential list` and `credential revoke` need.\n */\nexport async function callHost(\n lease: LeaseRecord,\n method: string,\n path: string,\n manifestPath?: string,\n): Promise<HostReply> {\n const base = lease.baseUrl\n if (base === undefined) return { ok: false, status: 0, detail: \"this host serves no HTTP\" }\n const token = manifestPath === undefined ? undefined : hostToken(manifestPath)\n try {\n const response = await fetch(`${base}${path}`, {\n method,\n headers: token === undefined ? {} : { authorization: `Bearer ${token}` },\n signal: AbortSignal.timeout(HOST_TIMEOUT_MS),\n })\n const body: unknown = await response.json().catch(() => undefined)\n if (response.ok) {\n return { ok: true, status: response.status, ...(body === undefined ? {} : { body }) }\n }\n const parsed = body as { error?: { message?: string; hint?: string } } | undefined\n return {\n ok: false,\n status: response.status,\n ...(parsed?.error?.message === undefined ? {} : { detail: parsed.error.message }),\n ...(parsed?.error?.hint === undefined ? {} : { hint: parsed.error.hint }),\n }\n } catch (error) {\n return {\n ok: false,\n status: 0,\n detail: error instanceof Error ? error.message : String(error),\n }\n }\n}\n\n/** Long enough for a dispose that waits on a channel to stop, short enough not to read as a hang. */\nconst HOST_TIMEOUT_MS = 10_000\n\n/** The sandbox manifest declaring this id, for the host's `resolveAgent` lookup. */\nexport function manifestForId(\n agentId: string,\n env?: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n for (const agent of listAgents(env)) {\n if (agent.id === agentId) return agent.manifestPath\n }\n return undefined\n}\n\n/** The directory an agent's manifest sits in, for messages that name a `.env`. */\nexport function agentDirOf(manifestPath: string): string {\n return dirname(manifestPath)\n}\n"
6
6
  ],
7
7
  "mappings": ";kFAmDA,eAAsB,EAAc,CAChC,EACA,EACA,EACiC,CACjC,IAAM,EAAqD,CAAC,EAE5D,GAAI,EAAM,SAAW,EAGjB,QAAW,KAAS,EAAW,CAAG,EAAG,CACjC,GAAI,EAAM,UAAY,QAAa,EAAM,KAAO,OAAW,SAC3D,EAAM,KAAK,CAAE,QAAS,EAAM,GAAI,aAAc,EAAM,YAAa,CAAC,EAGtE,aAAW,KAAgB,EAAO,CAI9B,IAAM,EAAS,EAAmB,CAAY,EAC9C,EAAM,KAAK,CAAE,QAAS,EAAO,IAAM,GAAI,cAAa,CAAC,EAI7D,IAAM,EAAW,MAAM,EACnB,MAAO,IACH,IAAI,KACC,MAAM,EAAG,WAAW,KAAK,GACrB,OAAO,CAAC,IAAQ,CAAC,EAAI,OAAO,EAC5B,IAAI,CAAC,IAAQ,CAAC,EAAI,QAAS,EAAI,MAAM,CAAC,CAC/C,EACJ,CACJ,EAEA,OAAO,EAAM,IAAI,CAAC,IAAU,CACxB,IAA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J,OAAQ,EACR,OAAQ,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CACjE,GAKR,IAAM,EAAkB,IAGjB,SAAS,EAAa,CACzB,EACA,EACkB,CAClB,QAAW,KAAS,EAAW,CAAG,EAC9B,GAAI,EAAM,KAAO,EAAS,OAAO,EAAM,aAE3C",
8
- "debugId": "D1618D18D9D176A664756E2164756E21",
8
+ "debugId": "00E8CDAE2C5FDD7B64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{spawn as s,spawnSync as f}from"node:child_process";function Ro(n){let e=f(n.command,[...n.args],{encoding:"utf8",...n.input===void 0?{}:{input:n.input},...n.cwd===void 0?{}:{cwd:n.cwd},...n.env===void 0?{}:{env:n.env},...n.timeoutMs===void 0?{}:{timeout:n.timeoutMs},...n.maxBuffer===void 0?{}:{maxBuffer:n.maxBuffer}}),d=e.error?.code;return{code:e.status??1,stdout:e.stdout??"",stderr:e.stderr??"",signalled:e.signal!==null,notFound:d==="ENOENT"}}function pe(n){return new Promise((e)=>{let d=s(n.command,[...n.args],{...n.cwd===void 0?{}:{cwd:n.cwd},...n.env===void 0?{}:{env:n.env},stdio:[n.input===void 0?"ignore":"pipe","pipe","pipe"]});if(n.input!==void 0)d.stdin?.end(n.input);let t="",a="",r=!1,u=n.maxBuffer??33554432;d.stdout?.on("data",(o)=>{if(t.length<u)t+=o.toString("utf8")}),d.stderr?.on("data",(o)=>{if(a.length<u)a+=o.toString("utf8")});let i=n.timeoutMs===void 0?void 0:setTimeout(()=>{r=!0,d.kill("SIGTERM")},n.timeoutMs);d.on("error",(o)=>{if(i!==void 0)clearTimeout(i);e({code:1,stdout:t,stderr:o.message,signalled:r,notFound:o.code==="ENOENT"})}),d.on("close",(o,l)=>{if(i!==void 0)clearTimeout(i);e({code:o??1,stdout:t,stderr:a,signalled:r||l!==null,notFound:!1})})})}
3
- export{Ro,pe};
2
+ import{spawn as s,spawnSync as f}from"node:child_process";function Ro(n){let e=f(n.command,[...n.args],{encoding:"utf8",...n.input===void 0?{}:{input:n.input},...n.cwd===void 0?{}:{cwd:n.cwd},...n.env===void 0?{}:{env:n.env},...n.timeoutMs===void 0?{}:{timeout:n.timeoutMs},...n.maxBuffer===void 0?{}:{maxBuffer:n.maxBuffer}}),d=e.error?.code;return{code:e.status??1,stdout:e.stdout??"",stderr:e.stderr??"",signalled:e.signal!==null,notFound:d==="ENOENT"}}function ge(n){return new Promise((e)=>{let d=s(n.command,[...n.args],{...n.cwd===void 0?{}:{cwd:n.cwd},...n.env===void 0?{}:{env:n.env},stdio:[n.input===void 0?"ignore":"pipe","pipe","pipe"]});if(n.input!==void 0)d.stdin?.end(n.input);let t="",a="",r=!1,u=n.maxBuffer??33554432;d.stdout?.on("data",(o)=>{if(t.length<u)t+=o.toString("utf8")}),d.stderr?.on("data",(o)=>{if(a.length<u)a+=o.toString("utf8")});let i=n.timeoutMs===void 0?void 0:setTimeout(()=>{r=!0,d.kill("SIGTERM")},n.timeoutMs);d.on("error",(o)=>{if(i!==void 0)clearTimeout(i);e({code:1,stdout:t,stderr:o.message,signalled:r,notFound:o.code==="ENOENT"})}),d.on("close",(o,l)=>{if(i!==void 0)clearTimeout(i);e({code:o??1,stdout:t,stderr:a,signalled:r||l!==null,notFound:!1})})})}
3
+ export{Ro,ge};
4
4
 
5
- //# debugId=6440A2AD82AFB7D764756E2164756E21
6
- //# sourceMappingURL=index-ez2mb28y.js.map
5
+ //# debugId=40F37B7163E8814864756E2164756E21
6
+ //# sourceMappingURL=index-s9mbq7h6.js.map
@@ -5,6 +5,6 @@
5
5
  "/**\n * The one place in this package that starts a process.\n *\n * There were two callers before this file existed and the second one is what created it: `lib/service.ts`\n * ran `launchctl`, and fetching a skill source needs `git`. The rule the boundaries test enforces is\n * \"exactly one module imports `node:child_process`\", and its stated reason is that a second call site is a\n * second place a test has to intercept — the first one that forgets reaches somebody's real machine. Two\n * callers of one seam keeps that property; an allowlist with two entries in it loses it, and would go on\n * losing it once per phase.\n *\n * Deliberately thin, and deliberately not clever. Everything specific to a tool — git's four ways of\n * being told not to prompt, launchd's exit-status decoding — belongs to the caller that knows about it.\n * What lives here is \"run this, capture what it said, and tell me honestly how it ended\".\n *\n * `notFound` is a field rather than an exception because the two callers want different sentences for it:\n * a missing `git` has a remedy the person can act on, and a missing `launchctl` means this is not the\n * operating system the caller thought it was. A shared error message would be wrong for both.\n */\n\nimport { spawn, spawnSync } from \"node:child_process\"\n\nexport interface SpawnRequest {\n readonly command: string\n readonly args: readonly string[]\n readonly cwd?: string\n /** Replaces the environment entirely when given. Callers spread `process.env` themselves. */\n readonly env?: Readonly<Record<string, string | undefined>>\n readonly timeoutMs?: number\n readonly maxBuffer?: number\n /**\n * Text to write to the child's stdin, which is then closed.\n *\n * Added for the clipboard: `pbcopy` reads what it copies from stdin and there is no argument form. The\n * alternative was a temporary file, which puts whatever was selected on disk — and a selection is\n * routinely the most sensitive thing on the screen. The seam grows rather than the caller working\n * around it, per the rule about first-party code not getting private escape hatches.\n */\n readonly input?: string\n}\n\nexport interface SpawnResult {\n readonly code: number\n readonly stdout: string\n readonly stderr: string\n /** True when a timeout or a signal ended it, rather than the process choosing to exit. */\n readonly signalled: boolean\n /** True when the command is not on PATH at all. */\n readonly notFound: boolean\n}\n\nexport function spawnCapture(request: SpawnRequest): SpawnResult {\n const result = spawnSync(request.command, [...request.args], {\n encoding: \"utf8\",\n ...(request.input === undefined ? {} : { input: request.input }),\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n ...(request.env === undefined ? {} : { env: request.env as NodeJS.ProcessEnv }),\n ...(request.timeoutMs === undefined ? {} : { timeout: request.timeoutMs }),\n ...(request.maxBuffer === undefined ? {} : { maxBuffer: request.maxBuffer }),\n })\n const code = (result.error as NodeJS.ErrnoException | undefined)?.code\n return {\n code: result.status ?? 1,\n stdout: result.stdout ?? \"\",\n stderr: result.stderr ?? \"\",\n signalled: result.signal !== null,\n notFound: code === \"ENOENT\",\n }\n}\n\n/**\n * The same thing, without blocking the event loop.\n *\n * Exists because `spawnSync` inside an Ink app freezes the whole terminal: no spinner frame advances, and\n * the keypresses that arrive during a twenty-second `git clone` are echoed by the tty instead of being\n * consumed by the app — which is how `^[[B^[[A` ended up printed in the middle of a fetch progress line.\n * Anything a rendered screen waits on has to be awaited, not blocked on.\n */\nexport function spawnCaptureAsync(request: SpawnRequest): Promise<SpawnResult> {\n return new Promise((resolve) => {\n const child = spawn(request.command, [...request.args], {\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n ...(request.env === undefined ? {} : { env: request.env as NodeJS.ProcessEnv }),\n // Never inherit: a child that writes to the terminal would paint over the rendered frame, and\n // one that reads from it would steal the keys the app is listening for.\n // A pipe only when there is something to write. `ignore` otherwise, for the reason below.\n stdio: [request.input === undefined ? \"ignore\" : \"pipe\", \"pipe\", \"pipe\"],\n })\n if (request.input !== undefined) {\n // Ended immediately: a child reading stdin waits for EOF, so a pipe left open is a process\n // that never exits and a promise that never settles.\n child.stdin?.end(request.input)\n }\n let stdout = \"\"\n let stderr = \"\"\n let signalled = false\n const cap = request.maxBuffer ?? 32 * 1024 * 1024\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n if (stdout.length < cap) stdout += chunk.toString(\"utf8\")\n })\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n if (stderr.length < cap) stderr += chunk.toString(\"utf8\")\n })\n const timer =\n request.timeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n signalled = true\n // The group, not the pid: `git clone` spawns helpers, and killing only the parent\n // leaves them running with nothing referencing them.\n child.kill(\"SIGTERM\")\n }, request.timeoutMs)\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (timer !== undefined) clearTimeout(timer)\n resolve({\n code: 1,\n stdout,\n stderr: error.message,\n signalled,\n notFound: error.code === \"ENOENT\",\n })\n })\n child.on(\"close\", (code, signal) => {\n if (timer !== undefined) clearTimeout(timer)\n resolve({\n code: code ?? 1,\n stdout,\n stderr,\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AO,OAAS,EAAK,GAAU,EAAM,SAAS,MAAM,EAC3D,EACD,EAAM,QAAQ,GAAG,OAAQ,CAAC,IAAkB,CACxC,GAAI,EAAO,OAAS,EAAK,GAAU,EAAM,SAAS,MAAM,EAC3D,EACD,IAAM,EACF,EAAQ,YAAc,OAChB,OACA,WAAW,IAAM,CACb,EAAY,GAGZ,EAAM,KAAK,SAAS,GACrB,EAAQ,SAAS,EAC9B,EAAM,GAAG,QAAS,CAAC,IAAiC,CAChD,GAAI,IAAU,OAAW,aAAa,CAAK,EAC3C,EAAQ,CACJ,KAAM,EACN,SACA,OAAQ,EAAM,QACd,YACA,SAAU,EAAM,OAAS,QAC7B,CAAC,EACJ,EACD,EAAM,GAAG,QAAS,CAAC,EAAM,IAAW,CAChC,GAAI,IAAU,OAAW,aAAa,CAAK,EAC3C,EAAQ,CACJ,KAAM,GAAQ,EACd,SACA,SACA,UAAW,GAAa,IAAW,KACnC,SAAU,EACd,CAAC,EACJ,EACJ",
8
- "debugId": "6440A2AD82AFB7D764756E2164756E21",
8
+ "debugId": "40F37B7163E8814864756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{gt,pn,Or,m}from"./index-7z4sw2dm.js";import{existsSync as E,readFileSync as h}from"node:fs";import{dirname as l,join as o,resolve as u}from"node:path";function At(n){let e=o(l(n),".env"),r={};if(E(e))try{r=gt(h(e,"utf8"))}catch{}return pn(r,m([n]))}function To(n,e){let r=n[e];return r!==void 0&&r!==""}function f(n,e,r={}){let i=l(n),t=u(r.cwd??process.cwd()),d=r.readDir??Or,v=r.env??process.env,g=m([n],r),p=d(i),y=d(t),a=g[e];if(a!==void 0&&a!==""){let b=u(i)===t,c=y[e];if(!b&&c!==void 0&&v[e]===c)return{kind:"ambiguous",path:o(t,".env")};return{kind:"export"}}let s=p[e];if(s!==void 0&&s!=="")return{kind:"agent",path:o(i,".env")};return{kind:"unset"}}function _o(n){switch(n.kind){case"export":return"from the environment, not a .env file";case"ambiguous":return"from the environment or ./.env — indistinguishable";case"agent":return;case"unset":return"not set"}}function $o(n){let e=[],r=x(n.rawModelId);if(r!==void 0)e.push({field:"model.main.id",variable:r,origin:f(n.manifestPath,r,n.options??{})});if(n.apiKeyEnv!==void 0)e.push({field:"model.main.apiKeyEnv",variable:n.apiKeyEnv,origin:f(n.manifestPath,n.apiKeyEnv,n.options??{})});return e}function x(n){if(n===void 0)return;return/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(n.trim())?.[1]}
2
+ import{gt,pn,Or,m}from"./index-tv4yv7d2.js";import{existsSync as E,readFileSync as h}from"node:fs";import{dirname as l,join as o,resolve as u}from"node:path";function At(n){let e=o(l(n),".env"),r={};if(E(e))try{r=gt(h(e,"utf8"))}catch{}return pn(r,m([n]))}function To(n,e){let r=n[e];return r!==void 0&&r!==""}function f(n,e,r={}){let i=l(n),t=u(r.cwd??process.cwd()),d=r.readDir??Or,v=r.env??process.env,g=m([n],r),p=d(i),y=d(t),a=g[e];if(a!==void 0&&a!==""){let b=u(i)===t,c=y[e];if(!b&&c!==void 0&&v[e]===c)return{kind:"ambiguous",path:o(t,".env")};return{kind:"export"}}let s=p[e];if(s!==void 0&&s!=="")return{kind:"agent",path:o(i,".env")};return{kind:"unset"}}function _o(n){switch(n.kind){case"export":return"from the environment, not a .env file";case"ambiguous":return"from the environment or ./.env — indistinguishable";case"agent":return;case"unset":return"not set"}}function $o(n){let e=[],r=x(n.rawModelId);if(r!==void 0)e.push({field:"model.main.id",variable:r,origin:f(n.manifestPath,r,n.options??{})});if(n.apiKeyEnv!==void 0)e.push({field:"model.main.apiKeyEnv",variable:n.apiKeyEnv,origin:f(n.manifestPath,n.apiKeyEnv,n.options??{})});return e}function x(n){if(n===void 0)return;return/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(n.trim())?.[1]}
3
3
  export{At,To,_o,$o};
4
4
 
5
5
  //# debugId=09DE6EA43B9B21E464756E2164756E21
6
- //# sourceMappingURL=index-0b1hdwnm.js.map
6
+ //# sourceMappingURL=index-tf71ap9v.js.map