@qitqode/qitqode-android-arm64 0.1.20 → 0.1.21

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 (79) hide show
  1. package/bundle/{chunk-xb031er5.js → chunk-0942095s.js} +1 -1
  2. package/bundle/{chunk-0x0a51w3.js → chunk-0czxqcg7.js} +1 -1
  3. package/bundle/{chunk-9a5nck3f.js → chunk-1b9ey3yh.js} +1 -1
  4. package/bundle/{chunk-gspdrdyq.js → chunk-21q96fet.js} +1 -1
  5. package/bundle/{chunk-wnjg8mmh.js → chunk-21t254fq.js} +1 -1
  6. package/bundle/{chunk-zfvk6zjj.js → chunk-2db8pn5k.js} +1 -1
  7. package/bundle/{chunk-r2waj5n2.js → chunk-3gxhdy0c.js} +1 -1
  8. package/bundle/{chunk-471yj527.js → chunk-3m0t96kb.js} +1 -1
  9. package/bundle/{chunk-dp3hqm2m.js → chunk-4tk4wppp.js} +1 -1
  10. package/bundle/{chunk-p77m937s.js → chunk-5k1eyz7y.js} +1 -1
  11. package/bundle/{chunk-c4mxtqyq.js → chunk-5rcnwm9j.js} +1 -1
  12. package/bundle/{chunk-k728fzrr.js → chunk-5yghd32r.js} +1 -1
  13. package/bundle/{chunk-q39h31te.js → chunk-651fyxmn.js} +3 -3
  14. package/bundle/{chunk-7myavy3p.js → chunk-6ba9fc92.js} +1 -1
  15. package/bundle/{chunk-w0fg8n1f.js → chunk-6dznrhs4.js} +1 -1
  16. package/bundle/{chunk-knwayz0m.js → chunk-6t70j1wg.js} +1 -1
  17. package/bundle/{chunk-3makpbng.js → chunk-767vf2ha.js} +1 -1
  18. package/bundle/{chunk-k6z419yx.js → chunk-76p9v2jf.js} +1 -1
  19. package/bundle/{chunk-1brsnwhv.js → chunk-7hxksr4h.js} +1 -1
  20. package/bundle/{chunk-2w154wad.js → chunk-7jefvta3.js} +1 -1
  21. package/bundle/{chunk-fegrrsfj.js → chunk-7skp0dmg.js} +1 -1
  22. package/bundle/{chunk-1qw3yh13.js → chunk-88ckmmdr.js} +3 -3
  23. package/bundle/{chunk-0pbpzty2.js → chunk-8fn883z8.js} +1 -1
  24. package/bundle/{chunk-c422awkv.js → chunk-9gfe4wtk.js} +1 -1
  25. package/bundle/{chunk-rdsae6k4.js → chunk-9hwsz356.js} +1 -1
  26. package/bundle/{chunk-3fzgbam3.js → chunk-9vvvyk10.js} +1 -1
  27. package/bundle/{chunk-n0y1ea17.js → chunk-atg7cn5r.js} +1 -1
  28. package/bundle/{chunk-qq48ffjc.js → chunk-b3721b7c.js} +1 -1
  29. package/bundle/{chunk-nt07vncv.js → chunk-b4r19v4g.js} +1 -1
  30. package/bundle/{chunk-b2ky15zx.js → chunk-bsg92mw7.js} +1 -1
  31. package/bundle/{chunk-skjge2wh.js → chunk-bzj7yxw6.js} +1 -1
  32. package/bundle/{chunk-1gj0m10e.js → chunk-c1dwcsax.js} +1 -1
  33. package/bundle/{chunk-ysxmk1z1.js → chunk-c4vfxy1e.js} +1 -1
  34. package/bundle/{chunk-v7yvnnmr.js → chunk-esjs9s9g.js} +1 -1
  35. package/bundle/chunk-f2q7cbah.js +2 -0
  36. package/bundle/{chunk-mpn5qm9j.js → chunk-fssswy6j.js} +1 -1
  37. package/bundle/{chunk-4pedvzse.js → chunk-ghtm9598.js} +1 -1
  38. package/bundle/{chunk-p41h8naw.js → chunk-gkz68a5s.js} +1 -1
  39. package/bundle/{chunk-gfm4vad7.js → chunk-gp6nvjb8.js} +153 -153
  40. package/bundle/{chunk-6tjghyx6.js → chunk-hkydp4m3.js} +1 -1
  41. package/bundle/{chunk-hjvje9xj.js → chunk-htdpkk8v.js} +1 -1
  42. package/bundle/{chunk-ghmctw8s.js → chunk-hvnhkrd3.js} +1 -1
  43. package/bundle/{chunk-fgqrcjsm.js → chunk-hvqgvsa5.js} +1 -1
  44. package/bundle/{chunk-dgbvsnqb.js → chunk-js7becx7.js} +1 -1
  45. package/bundle/{chunk-5549c7mb.js → chunk-jwgqpntf.js} +1 -1
  46. package/bundle/{chunk-7nas10jx.js → chunk-k44dj66f.js} +1 -1
  47. package/bundle/{chunk-9g4hz1st.js → chunk-kvs7qbga.js} +1 -1
  48. package/bundle/{chunk-1q2vhe78.js → chunk-m7q12naw.js} +1 -1
  49. package/bundle/{chunk-pskkmca2.js → chunk-mc1m6dxk.js} +1 -1
  50. package/bundle/{chunk-anse7bd0.js → chunk-myjbd0vk.js} +1 -1
  51. package/bundle/{chunk-b49rxw15.js → chunk-n499tbz0.js} +1 -1
  52. package/bundle/{chunk-y36ggefa.js → chunk-n5k2c708.js} +1 -1
  53. package/bundle/{chunk-zafrxr1q.js → chunk-n6fh34xx.js} +1 -1
  54. package/bundle/{chunk-6bq7rx7m.js → chunk-n7a4wpjj.js} +1 -1
  55. package/bundle/{chunk-vh8w0ea8.js → chunk-ns0hezdf.js} +1 -1
  56. package/bundle/{chunk-pn77fh9b.js → chunk-q2zk0z41.js} +1 -1
  57. package/bundle/{chunk-s2g5989e.js → chunk-qh76pgsk.js} +1 -1
  58. package/bundle/{chunk-tp7sfreh.js → chunk-qxtz0tfd.js} +1 -1
  59. package/bundle/{chunk-3gdqmave.js → chunk-qy1s81tv.js} +2 -2
  60. package/bundle/{chunk-28knamc9.js → chunk-r03jc8xm.js} +1 -1
  61. package/bundle/{chunk-wmqcz5rb.js → chunk-rkb592nb.js} +1 -1
  62. package/bundle/{chunk-w8rvjbgr.js → chunk-s811ht10.js} +1 -1
  63. package/bundle/{chunk-8k1q3g8s.js → chunk-sj8py6vk.js} +1 -1
  64. package/bundle/{chunk-dvn528qs.js → chunk-t6dymkmx.js} +1 -1
  65. package/bundle/{chunk-jc0wbpjq.js → chunk-th5z0zx7.js} +1 -1
  66. package/bundle/chunk-tnn7hm4v.js +2 -0
  67. package/bundle/{chunk-aej69zjj.js → chunk-v0jnnpsz.js} +1 -1
  68. package/bundle/{chunk-f57rqsby.js → chunk-vdt8dvqs.js} +1 -1
  69. package/bundle/{chunk-0fwz5r1k.js → chunk-w2f8sjc4.js} +1 -1
  70. package/bundle/{chunk-rmmrnx95.js → chunk-w5nwkb0s.js} +1 -1
  71. package/bundle/{chunk-ckhhm2m8.js → chunk-w9mdrb90.js} +1 -1
  72. package/bundle/{chunk-xbxgrwvy.js → chunk-y7hkykkj.js} +1 -1
  73. package/bundle/{chunk-ej3gmaba.js → chunk-yja3y138.js} +1 -1
  74. package/bundle/{chunk-k5vwx1nv.js → chunk-yt6cfsdh.js} +1 -1
  75. package/bundle/index.js +3 -3
  76. package/bundle/worker.js +1 -1
  77. package/package.json +1 -1
  78. package/bundle/chunk-7pqevqry.js +0 -2
  79. package/bundle/chunk-p4pc1zdd.js +0 -2
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Gs as X}from"./chunk-v7yvnnmr.js";function D(j){return j.parserConfiguration({"populate--":!0}).scriptName("qitqode").wrap(100).help("help","show help").alias("help","h").version("version","show version number",X).alias("version","v").option("print-logs",{describe:"print logs to stderr",type:"boolean"}).option("log-level",{describe:"log level",type:"string",choices:["DEBUG","INFO","WARN","ERROR"]}).option("pure",{describe:"run without external plugins",type:"boolean"})}var H={port:{type:"number",describe:"port to listen on",default:0},hostname:{type:"string",describe:"hostname to listen on",default:"127.0.0.1"},mdns:{type:"boolean",describe:"enable mDNS service discovery (defaults hostname to 0.0.0.0)",default:!1},"mdns-domain":{type:"string",describe:"custom domain name for mDNS service (default: qitqode.local)",default:"qitqode.local"},cors:{type:"string",array:!0,describe:"additional domains to allow for CORS",default:[]},"no-auth":{type:"boolean",describe:"allow starting without authentication on non-loopback addresses (DANGEROUS)",default:!1}};function u(j){return j.options(H)}function F(j,z=process.argv){return z.some((B)=>B===j||B.startsWith(`${j}=`))}function P(j,z=process.argv){return F("--port",z)||F("--hostname",z)||F("--mdns",z)||!!j.mdns||j.port!==0||j.hostname!=="127.0.0.1"}function _(j,z,B=process.argv){let J=F("--port",B),Z=F("--hostname",B),$=F("--mdns",B),q=F("--mdns-domain",B),K=$?j.mdns:z?.server?.mdns??j.mdns,M=q?j["mdns-domain"]:z?.server?.mdnsDomain??j["mdns-domain"],N=J?j.port:z?.server?.port??j.port,U=Z?j.hostname:K&&!z?.server?.hostname?"0.0.0.0":z?.server?.hostname??j.hostname,V=z?.server?.cors??[],Y=Array.isArray(j.cors)?j.cors:j.cors?[j.cors]:[],b=[...V,...Y],A=j["no-auth"];return{hostname:U,port:N,mdns:K,mdnsDomain:M,cors:b,noAuth:A}}var k={model:{type:"string",alias:["m"],describe:"model to use in the format of provider/model"},continue:{alias:["c"],describe:"continue the last session",type:"boolean"},session:{alias:["s"],type:"string",describe:"session id to continue"},fork:{type:"boolean",describe:"fork the session when continuing (use with --continue or --session)"},prompt:{type:"string",describe:"prompt to use"},agent:{type:"string",describe:"agent to use"},dark:{type:"boolean",describe:"start in dark theme (overrides saved theme preference for this launch)"},light:{type:"boolean",describe:"start in light theme (overrides saved theme preference for this launch)"},monochrome:{type:"boolean",describe:"start in monochrome accessible rendering \u2014 no color, plain terminal, screen-reader friendly"},headless:{type:"boolean",describe:"headless permissionless mode for AI subagent use \u2014 auto-approves all tool permissions, implies --never-ask"},"api-key":{type:"string",describe:"Qlex API key for non-interactive authentication in headless mode (can also be set via $QLEX_API_KEY)"},sso:{type:"boolean",describe:"sign in via SSO device-code flow before starting a headless session \u2014 prints a URL and code, waits for browser approval (requires --headless)"},free:{type:"boolean",describe:"start in Free tier (no cost) \u2014 shorthand for the Free model tier"},default:{type:"boolean",describe:"start in Default tier \u2014 shorthand for the Default model tier"},fast:{type:"boolean",describe:"start in Fast tier \u2014 shorthand for the Fast model tier"},economy:{type:"boolean",describe:"start in Economy tier \u2014 shorthand for the Economy model tier"},power:{type:"boolean",describe:"start in Power tier \u2014 shorthand for the Power model tier"}},L=36,W="\x1B[38;5;214m",I="\x1B[0;2m",Q="\x1B[0m";function G(j,z){let B=Math.round(j/100*L),J=`${"\u25A0".repeat(B)}${"\uFF65".repeat(L-B)}`;return`\r${W}${J} ${j.toString().padStart(3)}%${Q} ${I}${z}${Q}`}
2
+ import{Gs as X}from"./chunk-esjs9s9g.js";function D(j){return j.parserConfiguration({"populate--":!0}).scriptName("qitqode").wrap(100).help("help","show help").alias("help","h").version("version","show version number",X).alias("version","v").option("print-logs",{describe:"print logs to stderr",type:"boolean"}).option("log-level",{describe:"log level",type:"string",choices:["DEBUG","INFO","WARN","ERROR"]}).option("pure",{describe:"run without external plugins",type:"boolean"})}var H={port:{type:"number",describe:"port to listen on",default:0},hostname:{type:"string",describe:"hostname to listen on",default:"127.0.0.1"},mdns:{type:"boolean",describe:"enable mDNS service discovery (defaults hostname to 0.0.0.0)",default:!1},"mdns-domain":{type:"string",describe:"custom domain name for mDNS service (default: qitqode.local)",default:"qitqode.local"},cors:{type:"string",array:!0,describe:"additional domains to allow for CORS",default:[]},"no-auth":{type:"boolean",describe:"allow starting without authentication on non-loopback addresses (DANGEROUS)",default:!1}};function u(j){return j.options(H)}function F(j,z=process.argv){return z.some((B)=>B===j||B.startsWith(`${j}=`))}function P(j,z=process.argv){return F("--port",z)||F("--hostname",z)||F("--mdns",z)||!!j.mdns||j.port!==0||j.hostname!=="127.0.0.1"}function _(j,z,B=process.argv){let J=F("--port",B),Z=F("--hostname",B),$=F("--mdns",B),q=F("--mdns-domain",B),K=$?j.mdns:z?.server?.mdns??j.mdns,M=q?j["mdns-domain"]:z?.server?.mdnsDomain??j["mdns-domain"],N=J?j.port:z?.server?.port??j.port,U=Z?j.hostname:K&&!z?.server?.hostname?"0.0.0.0":z?.server?.hostname??j.hostname,V=z?.server?.cors??[],Y=Array.isArray(j.cors)?j.cors:j.cors?[j.cors]:[],b=[...V,...Y],A=j["no-auth"];return{hostname:U,port:N,mdns:K,mdnsDomain:M,cors:b,noAuth:A}}var k={model:{type:"string",alias:["m"],describe:"model to use in the format of provider/model"},continue:{alias:["c"],describe:"continue the last session",type:"boolean"},session:{alias:["s"],type:"string",describe:"session id to continue"},fork:{type:"boolean",describe:"fork the session when continuing (use with --continue or --session)"},prompt:{type:"string",describe:"prompt to use"},agent:{type:"string",describe:"agent to use"},dark:{type:"boolean",describe:"start in dark theme (overrides saved theme preference for this launch)"},light:{type:"boolean",describe:"start in light theme (overrides saved theme preference for this launch)"},monochrome:{type:"boolean",describe:"start in monochrome accessible rendering \u2014 no color, plain terminal, screen-reader friendly"},headless:{type:"boolean",describe:"headless permissionless mode for AI subagent use \u2014 auto-approves all tool permissions, implies --never-ask"},"api-key":{type:"string",describe:"Qlex API key for non-interactive authentication in headless mode (can also be set via $QLEX_API_KEY)"},sso:{type:"boolean",describe:"sign in via SSO device-code flow before starting a headless session \u2014 prints a URL and code, waits for browser approval (requires --headless)"},free:{type:"boolean",describe:"start in Free tier (no cost) \u2014 shorthand for the Free model tier"},default:{type:"boolean",describe:"start in Default tier \u2014 shorthand for the Default model tier"},fast:{type:"boolean",describe:"start in Fast tier \u2014 shorthand for the Fast model tier"},economy:{type:"boolean",describe:"start in Economy tier \u2014 shorthand for the Economy model tier"},power:{type:"boolean",describe:"start in Power tier \u2014 shorthand for the Power model tier"}},L=36,W="\x1B[38;5;214m",I="\x1B[0;2m",Q="\x1B[0m";function G(j,z){let B=Math.round(j/100*L),J=`${"\u25A0".repeat(B)}${"\uFF65".repeat(L-B)}`;return`\r${W}${J} ${j.toString().padStart(3)}%${Q} ${I}${z}${Q}`}
3
3
  export{D as Jf,H as Kf,u as Lf,P as Mf,_ as Nf,k as Of,G as Pf};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{a,b,c,d,e,f}from"./chunk-9a5nck3f.js";import"./chunk-knwayz0m.js";import"./chunk-f72j5yx8.js";import"./chunk-wnjg8mmh.js";import"./chunk-9g05wsae.js";import"./chunk-x1dfc7qd.js";import"./chunk-wmmck56g.js";import"./chunk-ntmn6epc.js";import"./chunk-pn77fh9b.js";import"./chunk-1qw3yh13.js";import"./chunk-ckhhm2m8.js";import"./chunk-tp7sfreh.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import"./chunk-q39h31te.js";import"./chunk-0x0a51w3.js";import"./chunk-7myavy3p.js";import"./chunk-fegrrsfj.js";import"./chunk-c4x99ayd.js";import"./chunk-w0fg8n1f.js";import"./chunk-0pbpzty2.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-jc0wbpjq.js";import"./chunk-jfy6bfvv.js";import"./chunk-aej69zjj.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-k5vwx1nv.js";import"./chunk-ej3gmaba.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import"./chunk-v7yvnnmr.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import"./chunk-fa03gsff.js";export{e as statusEffect,a as resolveApiKeyFlag,d as logoutEffect,c as loginEffect,b as apiKeyLoginEffect,f as AuthCommand};
2
+ import{a,b,c,d,e,f}from"./chunk-1b9ey3yh.js";import"./chunk-6t70j1wg.js";import"./chunk-f72j5yx8.js";import"./chunk-21t254fq.js";import"./chunk-9g05wsae.js";import"./chunk-x1dfc7qd.js";import"./chunk-wmmck56g.js";import"./chunk-ntmn6epc.js";import"./chunk-q2zk0z41.js";import"./chunk-88ckmmdr.js";import"./chunk-w9mdrb90.js";import"./chunk-qxtz0tfd.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import"./chunk-651fyxmn.js";import"./chunk-0czxqcg7.js";import"./chunk-6ba9fc92.js";import"./chunk-7skp0dmg.js";import"./chunk-c4x99ayd.js";import"./chunk-6dznrhs4.js";import"./chunk-8fn883z8.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-th5z0zx7.js";import"./chunk-jfy6bfvv.js";import"./chunk-v0jnnpsz.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-yt6cfsdh.js";import"./chunk-yja3y138.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import"./chunk-esjs9s9g.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import"./chunk-fa03gsff.js";export{e as statusEffect,a as resolveApiKeyFlag,d as logoutEffect,c as loginEffect,b as apiKeyLoginEffect,f as AuthCommand};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{dt as n}from"./chunk-v7yvnnmr.js";function s(e){let r=e?.password??n.QITQODE_SERVER_PASSWORD;if(!r)return;let t=e?.username??n.QITQODE_SERVER_USERNAME??"qitqode";return`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`}function o(e){let r=s(e);if(!r)return;return{Authorization:r}}
2
+ import{dt as n}from"./chunk-esjs9s9g.js";function s(e){let r=e?.password??n.QITQODE_SERVER_PASSWORD;if(!r)return;let t=e?.username??n.QITQODE_SERVER_USERNAME??"qitqode";return`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`}function o(e){let r=s(e);if(!r)return;return{Authorization:r}}
3
3
  export{o as M};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{rp as J}from"./chunk-jfy6bfvv.js";import{Et as Q,st as H,tt as I,ut as N}from"./chunk-b5x3zghc.js";import{pP as L}from"./chunk-fa03gsff.js";import{platform as R,release as U}from"os";import{tmpdir as V}from"os";import X from"path";import Y from"fs/promises";var Z=J(async()=>{let{which:D}=await import("./chunk-pskkmca2.js");return D}),T=J(async()=>{let{default:D}=await import("./chunk-0vw5a7m9.js");return D});function _(D){if(!process.stdout.isTTY)return;let A=`\x1B]52;c;${Buffer.from(D).toString("base64")}\x07`,E=process.env.TMUX||process.env.STY?`\x1BPtmux;\x1B${A}\x1B\\`:A;process.stdout.write(E)}async function $(){let D=R();if(D==="darwin"){let k=X.join(V(),"qitqode-clipboard.png");try{return await I(["osascript","-e",'set imageData to the clipboard as "PNGf"',"-e",`set fileRef to open for access POSIX file "${k}" with write permission`,"-e","set eof fileRef to 0","-e","write imageData to fileRef","-e","close access fileRef"],{nothrow:!0}),{data:(await Q(k)).toString("base64"),mime:"image/png"}}catch{}finally{await Y.rm(k,{force:!0}).catch(()=>{})}}if(D==="win32"||U().includes("WSL")){let E=await N(["powershell.exe","-NonInteractive","-NoProfile","-command","Add-Type -AssemblyName System.Windows.Forms; $img = [System.Windows.Forms.Clipboard]::GetImage(); if ($img) { $ms = New-Object System.IO.MemoryStream; $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); [System.Convert]::ToBase64String($ms.ToArray()) }"],{nothrow:!0});if(E.text){let K=Buffer.from(E.text.trim(),"base64");if(K.length>0)return{data:K.toString("base64"),mime:"image/png"}}}if(D==="linux"){let k=await I(["wl-paste","-t","image/png"],{nothrow:!0});if(k.stdout.byteLength>0)return{data:Buffer.from(k.stdout).toString("base64"),mime:"image/png"};let E=await I(["xclip","-selection","clipboard","-t","image/png","-o"],{nothrow:!0});if(E.stdout.byteLength>0)return{data:Buffer.from(E.stdout).toString("base64"),mime:"image/png"}}let A=await(await T()).read().catch(()=>{});if(A)return{data:A,mime:"text/plain"}}var j=J(async()=>{let D=R(),G=await Z();if(D==="darwin"&&G("osascript"))return console.log("clipboard: using osascript"),async(A)=>{let k=A.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");await I(["osascript","-e",`set the clipboard to "${k}"`],{nothrow:!0})};if(D==="linux"){if(process.env.WAYLAND_DISPLAY&&G("wl-copy"))return console.log("clipboard: using wl-copy"),async(A)=>{let k=H(["wl-copy"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};if(G("xclip"))return console.log("clipboard: using xclip"),async(A)=>{let k=H(["xclip","-selection","clipboard"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};if(G("xsel"))return console.log("clipboard: using xsel"),async(A)=>{let k=H(["xsel","--clipboard","--input"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})}}if(D==="win32")return console.log("clipboard: using powershell"),async(A)=>{let k=H(["powershell.exe","-NonInteractive","-NoProfile","-Command","[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};return console.log("clipboard: no native support"),async(A)=>{await(await T()).write(A).catch(()=>{})}});async function v(D){_(D),await(await j())(D)}
2
+ import{rp as J}from"./chunk-jfy6bfvv.js";import{Et as Q,st as H,tt as I,ut as N}from"./chunk-b5x3zghc.js";import{pP as L}from"./chunk-fa03gsff.js";import{platform as R,release as U}from"os";import{tmpdir as V}from"os";import X from"path";import Y from"fs/promises";var Z=J(async()=>{let{which:D}=await import("./chunk-mc1m6dxk.js");return D}),T=J(async()=>{let{default:D}=await import("./chunk-0vw5a7m9.js");return D});function _(D){if(!process.stdout.isTTY)return;let A=`\x1B]52;c;${Buffer.from(D).toString("base64")}\x07`,E=process.env.TMUX||process.env.STY?`\x1BPtmux;\x1B${A}\x1B\\`:A;process.stdout.write(E)}async function $(){let D=R();if(D==="darwin"){let k=X.join(V(),"qitqode-clipboard.png");try{return await I(["osascript","-e",'set imageData to the clipboard as "PNGf"',"-e",`set fileRef to open for access POSIX file "${k}" with write permission`,"-e","set eof fileRef to 0","-e","write imageData to fileRef","-e","close access fileRef"],{nothrow:!0}),{data:(await Q(k)).toString("base64"),mime:"image/png"}}catch{}finally{await Y.rm(k,{force:!0}).catch(()=>{})}}if(D==="win32"||U().includes("WSL")){let E=await N(["powershell.exe","-NonInteractive","-NoProfile","-command","Add-Type -AssemblyName System.Windows.Forms; $img = [System.Windows.Forms.Clipboard]::GetImage(); if ($img) { $ms = New-Object System.IO.MemoryStream; $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); [System.Convert]::ToBase64String($ms.ToArray()) }"],{nothrow:!0});if(E.text){let K=Buffer.from(E.text.trim(),"base64");if(K.length>0)return{data:K.toString("base64"),mime:"image/png"}}}if(D==="linux"){let k=await I(["wl-paste","-t","image/png"],{nothrow:!0});if(k.stdout.byteLength>0)return{data:Buffer.from(k.stdout).toString("base64"),mime:"image/png"};let E=await I(["xclip","-selection","clipboard","-t","image/png","-o"],{nothrow:!0});if(E.stdout.byteLength>0)return{data:Buffer.from(E.stdout).toString("base64"),mime:"image/png"}}let A=await(await T()).read().catch(()=>{});if(A)return{data:A,mime:"text/plain"}}var j=J(async()=>{let D=R(),G=await Z();if(D==="darwin"&&G("osascript"))return console.log("clipboard: using osascript"),async(A)=>{let k=A.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");await I(["osascript","-e",`set the clipboard to "${k}"`],{nothrow:!0})};if(D==="linux"){if(process.env.WAYLAND_DISPLAY&&G("wl-copy"))return console.log("clipboard: using wl-copy"),async(A)=>{let k=H(["wl-copy"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};if(G("xclip"))return console.log("clipboard: using xclip"),async(A)=>{let k=H(["xclip","-selection","clipboard"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};if(G("xsel"))return console.log("clipboard: using xsel"),async(A)=>{let k=H(["xsel","--clipboard","--input"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})}}if(D==="win32")return console.log("clipboard: using powershell"),async(A)=>{let k=H(["powershell.exe","-NonInteractive","-NoProfile","-Command","[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};return console.log("clipboard: no native support"),async(A)=>{await(await T()).write(A).catch(()=>{})}});async function v(D){_(D),await(await j())(D)}
3
3
  export{$ as rd,v as sd};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{zd as Xf}from"./chunk-b2ky15zx.js";import{Bd as Jf}from"./chunk-wmqcz5rb.js";import{Od as Gf}from"./chunk-wmmck56g.js";import{Lf as Af}from"./chunk-6tjghyx6.js";import{Zf as jf}from"./chunk-qq48ffjc.js";import"./chunk-rmmrnx95.js";import"./chunk-5549c7mb.js";import"./chunk-pn77fh9b.js";import"./chunk-hkqcpdmt.js";import"./chunk-nfg7nt13.js";import"./chunk-awdpkgxf.js";import"./chunk-xb031er5.js";import{gh as Uw,qh as Cw}from"./chunk-1qw3yh13.js";import"./chunk-ckhhm2m8.js";import{Bh as yf}from"./chunk-tp7sfreh.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import{Uk as Qf,Vk as h,Xk as _f,_j as zw,ek as H,fk as P}from"./chunk-q39h31te.js";import"./chunk-0x0a51w3.js";import"./chunk-7myavy3p.js";import"./chunk-fegrrsfj.js";import"./chunk-c4x99ayd.js";import"./chunk-w0fg8n1f.js";import"./chunk-0pbpzty2.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-jc0wbpjq.js";import"./chunk-jfy6bfvv.js";import"./chunk-aej69zjj.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import{Lq as $f}from"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-k5vwx1nv.js";import"./chunk-ej3gmaba.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import{Gs as Df,_s as ff,mt as V}from"./chunk-v7yvnnmr.js";import{Gt as Hw}from"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import{Cu as w}from"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import{nP as mD}from"./chunk-fa03gsff.js";var B={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_close:"session/close",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},L={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"};var Zf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),terminal:w.boolean().optional().default(!1)}),Of=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),label:w.string().nullish(),name:w.string(),optional:w.boolean().optional().default(!1),secret:w.boolean().optional().default(!0)}),Nf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),id:w.string(),name:w.string()}),Wf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),id:w.string(),link:w.string().nullish(),name:w.string(),vars:w.array(Of)}),Bf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),args:w.array(w.string()).optional(),description:w.string().nullish(),env:w.record(w.string(),w.string()).optional(),id:w.string(),name:w.string()}),Kf=w.union([Wf.and(w.object({type:w.literal("env_var")})),Bf.and(w.object({type:w.literal("terminal")})),Nf]),p=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),methodId:w.string()}),Lf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),Ff=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),blob:w.string(),mimeType:w.string().nullish(),uri:w.string()}),kf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),xf=w.object({amount:w.number(),currency:w.string()}),Vf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),terminalId:w.string()}),Pf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),newText:w.string(),oldText:w.string().nullish(),path:w.string()}),Mw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),name:w.string(),value:w.string()}),Hf=w.union([w.literal(-32700),w.literal(-32600),w.literal(-32601),w.literal(-32602),w.literal(-32603),w.literal(-32800),w.literal(-32000),w.literal(-32002),w.number().int().min(-2147483648,{message:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{message:"Invalid value: Expected int32 to be <= 2147483647"})]),Ew=w.object({code:Hf,data:w.unknown().optional(),message:w.string()}),Iw=w.unknown(),qw=w.unknown(),Sw=w.unknown(),Tf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),readTextFile:w.boolean().optional().default(!1),writeTextFile:w.boolean().optional().default(!1)}),hf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),auth:Zf.optional().default({terminal:!1}),fs:Tf.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:w.boolean().optional().default(!1)}),cw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),name:w.string(),value:w.string()}),Rw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),name:w.string(),title:w.string().nullish(),version:w.string()}),bf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),m=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cursor:w.string().nullish(),cwd:w.string().nullish()}),Uf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),http:w.boolean().optional().default(!1),sse:w.boolean().optional().default(!1)}),Cf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),headers:w.array(cw),name:w.string(),url:w.string()}),vf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),headers:w.array(cw),name:w.string(),url:w.string()}),Mf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),args:w.array(w.string()),command:w.string(),env:w.array(Mw),name:w.string()}),I=w.union([Cf.and(w.object({type:w.literal("http")})),vf.and(w.object({type:w.literal("sse")})),Mf]),o=w.string(),Ef=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),modelId:o,name:w.string()}),r=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),mcpServers:w.array(I)}),uw=w.string(),If=w.union([w.literal("allow_once"),w.literal("allow_always"),w.literal("reject_once"),w.literal("reject_always")]),qf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),kind:If,name:w.string(),optionId:uw}),Sf=w.union([w.literal("high"),w.literal("medium"),w.literal("low")]),cf=w.union([w.literal("pending"),w.literal("in_progress"),w.literal("completed")]),Rf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.string(),priority:Sf,status:cf}),uf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),entries:w.array(Rf)}),gf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),audio:w.boolean().optional().default(!1),embeddedContext:w.boolean().optional().default(!1),image:w.boolean().optional().default(!1)}),gw=w.number().int().gte(0).lte(65535),a=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),clientCapabilities:hf.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:Rw.nullish(),protocolVersion:gw}),lf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.string()}),tf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),T=w.union([w.number(),w.string()]).nullable(),sD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),requestId:T}),df=w.enum(["assistant","user"]),M=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),audience:w.array(df).nullish(),lastModified:w.string().nullish(),priority:w.number().nullish()}),nf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),data:w.string(),mimeType:w.string()}),pf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),data:w.string(),mimeType:w.string(),uri:w.string().nullish()}),mf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),description:w.string().nullish(),mimeType:w.string().nullish(),name:w.string(),size:w.number().nullish(),title:w.string().nullish(),uri:w.string()}),of=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),optionId:uw}),rf=w.union([w.object({outcome:w.literal("cancelled")}),of.and(w.object({outcome:w.literal("selected")}))]),af=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),outcome:rf}),zf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),sf=w.object({currentValue:w.boolean()}),ef=w.string(),lw=w.string(),wD=w.union([w.literal("mode"),w.literal("model"),w.literal("thought_level"),w.string()]),z=w.string(),iw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),name:w.string(),value:z}),fD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),group:ef,name:w.string(),options:w.array(iw)}),DD=w.union([w.array(iw),w.array(fD)]),$D=w.object({currentValue:z,options:DD}),C=w.intersection(w.union([$D.and(w.object({type:w.literal("select")})),sf.and(w.object({type:w.literal("boolean")}))]),w.object({_meta:w.record(w.string(),w.unknown()).nullish(),category:wD.nullish(),description:w.string().nullish(),id:lw,name:w.string()})),QD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C)}),_D=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),K=w.string(),s=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K}),eD=w.object({method:w.string(),params:w.union([s,Iw]).nullish()}),e=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K}),ww=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),args:w.array(w.string()).optional(),command:w.string(),cwd:w.string().nullish(),env:w.array(Mw).optional(),outputByteLimit:w.number().nullish(),sessionId:K}),fw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),mcpServers:w.array(I).optional(),sessionId:K}),Dw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,terminalId:w.string()}),$w=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),mcpServers:w.array(I),sessionId:K}),Qw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),limit:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),line:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:w.string(),sessionId:K}),_w=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,terminalId:w.string()}),Aw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),mcpServers:w.array(I).optional(),sessionId:K}),AD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),sessionId:K,title:w.string().nullish(),updatedAt:w.string().nullish()}),yD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),nextCursor:w.string().nullish(),sessions:w.array(AD)}),jD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),title:w.string().nullish(),updatedAt:w.string().nullish()}),JD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),q=w.string(),GD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),currentModeId:q}),XD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),id:q,name:w.string()}),S=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),availableModes:w.array(XD),currentModeId:q}),c=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),availableModels:w.array(Ef),currentModelId:o}),YD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C).nullish(),models:c.nullish(),modes:S.nullish(),sessionId:K}),ZD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C).nullish(),models:c.nullish(),modes:S.nullish()}),OD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C).nullish(),models:c.nullish(),modes:S.nullish(),sessionId:K}),ND=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C).nullish(),models:c.nullish(),modes:S.nullish()}),WD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),BD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),close:zf.nullish(),fork:_D.nullish(),list:JD.nullish(),resume:WD.nullish()}),KD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),loadSession:w.boolean().optional().default(!1),mcpCapabilities:Uf.optional().default({http:!1,sse:!1}),promptCapabilities:gf.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:BD.optional().default({})}),LD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),agentCapabilities:KD.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:Rw.nullish(),authMethods:w.array(Kf).optional().default([]),protocolVersion:gw}),yw=w.intersection(w.union([w.object({type:w.literal("boolean"),value:w.boolean()}),w.object({value:z})]),w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configId:lw,sessionId:K})),FD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C)}),jw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),modeId:q,sessionId:K}),kD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),Jw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),modelId:o,sessionId:K}),xD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),VD=w.union([w.literal("end_turn"),w.literal("max_tokens"),w.literal("max_turn_requests"),w.literal("refusal"),w.literal("cancelled")]),PD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),terminalId:w.string()}),HD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),exitCode:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:w.string().nullish()}),Gw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,terminalId:w.string()}),TD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),exitStatus:HD.nullish(),output:w.string(),truncated:w.boolean()}),hD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),text:w.string()}),bD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),mimeType:w.string().nullish(),text:w.string(),uri:w.string()}),UD=w.union([bD,Ff]),CD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),resource:UD}),Xw=w.union([hD.and(w.object({type:w.literal("text")})),pf.and(w.object({type:w.literal("image")})),nf.and(w.object({type:w.literal("audio")})),mf.and(w.object({type:w.literal("resource_link")})),CD.and(w.object({type:w.literal("resource")}))]),vD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:Xw}),n=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:Xw,messageId:w.string().nullish()}),Yw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),messageId:w.string().nullish(),prompt:w.array(Xw),sessionId:K}),w$=w.object({id:T,method:w.string(),params:w.union([a,p,r,$w,m,fw,Aw,e,jw,yw,Yw,Jw,qw]).nullish()}),tw=w.union([vD.and(w.object({type:w.literal("content")})),Pf.and(w.object({type:w.literal("diff")})),PD.and(w.object({type:w.literal("terminal")}))]),dw=w.string(),nw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),line:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:w.string()}),pw=w.union([w.literal("pending"),w.literal("in_progress"),w.literal("completed"),w.literal("failed")]),mw=w.union([w.literal("read"),w.literal("edit"),w.literal("delete"),w.literal("move"),w.literal("search"),w.literal("execute"),w.literal("think"),w.literal("fetch"),w.literal("switch_mode"),w.literal("other")]),MD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.array(tw).optional(),kind:mw.optional(),locations:w.array(nw).optional(),rawInput:w.unknown().optional(),rawOutput:w.unknown().optional(),status:pw.optional(),title:w.string(),toolCallId:dw}),ow=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.array(tw).nullish(),kind:mw.nullish(),locations:w.array(nw).nullish(),rawInput:w.unknown().optional(),rawOutput:w.unknown().optional(),status:pw.nullish(),title:w.string().nullish(),toolCallId:dw}),Zw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),options:w.array(qf),sessionId:K,toolCall:ow}),ED=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),hint:w.string()}),ID=ED,qD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string(),input:ID.nullish(),name:w.string()}),SD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),availableCommands:w.array(qD)}),cD=w.object({cachedReadTokens:w.number().nullish(),cachedWriteTokens:w.number().nullish(),inputTokens:w.number(),outputTokens:w.number(),thoughtTokens:w.number().nullish(),totalTokens:w.number()}),RD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),stopReason:VD,usage:cD.nullish(),userMessageId:w.string().nullish()}),f$=w.union([w.object({id:T,result:w.union([LD,Lf,OD,ZD,yD,YD,ND,kf,kD,FD,RD,xD,Sw])}),w.object({error:Ew,id:T})]),uD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cost:xf.nullish(),size:w.number(),used:w.number()}),gD=w.union([n.and(w.object({sessionUpdate:w.literal("user_message_chunk")})),n.and(w.object({sessionUpdate:w.literal("agent_message_chunk")})),n.and(w.object({sessionUpdate:w.literal("agent_thought_chunk")})),MD.and(w.object({sessionUpdate:w.literal("tool_call")})),ow.and(w.object({sessionUpdate:w.literal("tool_call_update")})),uf.and(w.object({sessionUpdate:w.literal("plan")})),SD.and(w.object({sessionUpdate:w.literal("available_commands_update")})),GD.and(w.object({sessionUpdate:w.literal("current_mode_update")})),QD.and(w.object({sessionUpdate:w.literal("config_option_update")})),jD.and(w.object({sessionUpdate:w.literal("session_info_update")})),uD.and(w.object({sessionUpdate:w.literal("usage_update")}))]),Ow=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,update:gD}),D$=w.object({method:w.string(),params:w.union([Ow,Iw]).nullish()}),Nw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,terminalId:w.string()}),lD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),exitCode:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:w.string().nullish()}),Ww=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.string(),path:w.string(),sessionId:K}),$$=w.object({id:T,method:w.string(),params:w.union([Ww,Qw,Zw,ww,Gw,_w,Nw,Dw,qw]).nullish()}),iD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),Q$=w.union([w.object({id:T,result:w.union([iD,lf,af,Vf,TD,tf,lD,bf,Sw])}),w.object({error:Ew,id:T})]);function rw(f,$){let D=new TextEncoder,Q=new TextDecoder,j=new ReadableStream({async start(_){let y="",X=$.getReader();try{while(!0){let{value:W,done:J}=await X.read();if(J)break;if(!W)continue;y+=Q.decode(W,{stream:!0});let G=y.split(`
2
+ import{zd as Xf}from"./chunk-bsg92mw7.js";import{Bd as Jf}from"./chunk-rkb592nb.js";import{Od as Gf}from"./chunk-wmmck56g.js";import{Lf as Af}from"./chunk-hkydp4m3.js";import{Zf as jf}from"./chunk-b3721b7c.js";import"./chunk-w5nwkb0s.js";import"./chunk-jwgqpntf.js";import"./chunk-q2zk0z41.js";import"./chunk-hkqcpdmt.js";import"./chunk-nfg7nt13.js";import"./chunk-awdpkgxf.js";import"./chunk-0942095s.js";import{gh as Uw,qh as Cw}from"./chunk-88ckmmdr.js";import"./chunk-w9mdrb90.js";import{Bh as yf}from"./chunk-qxtz0tfd.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import{Uk as Qf,Vk as h,Xk as _f,_j as zw,ek as H,fk as P}from"./chunk-651fyxmn.js";import"./chunk-0czxqcg7.js";import"./chunk-6ba9fc92.js";import"./chunk-7skp0dmg.js";import"./chunk-c4x99ayd.js";import"./chunk-6dznrhs4.js";import"./chunk-8fn883z8.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-th5z0zx7.js";import"./chunk-jfy6bfvv.js";import"./chunk-v0jnnpsz.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import{Lq as $f}from"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-yt6cfsdh.js";import"./chunk-yja3y138.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import{Gs as Df,_s as ff,mt as V}from"./chunk-esjs9s9g.js";import{Gt as Hw}from"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import{Cu as w}from"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import{nP as mD}from"./chunk-fa03gsff.js";var B={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_close:"session/close",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},L={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"};var Zf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),terminal:w.boolean().optional().default(!1)}),Of=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),label:w.string().nullish(),name:w.string(),optional:w.boolean().optional().default(!1),secret:w.boolean().optional().default(!0)}),Nf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),id:w.string(),name:w.string()}),Wf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),id:w.string(),link:w.string().nullish(),name:w.string(),vars:w.array(Of)}),Bf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),args:w.array(w.string()).optional(),description:w.string().nullish(),env:w.record(w.string(),w.string()).optional(),id:w.string(),name:w.string()}),Kf=w.union([Wf.and(w.object({type:w.literal("env_var")})),Bf.and(w.object({type:w.literal("terminal")})),Nf]),p=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),methodId:w.string()}),Lf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),Ff=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),blob:w.string(),mimeType:w.string().nullish(),uri:w.string()}),kf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),xf=w.object({amount:w.number(),currency:w.string()}),Vf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),terminalId:w.string()}),Pf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),newText:w.string(),oldText:w.string().nullish(),path:w.string()}),Mw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),name:w.string(),value:w.string()}),Hf=w.union([w.literal(-32700),w.literal(-32600),w.literal(-32601),w.literal(-32602),w.literal(-32603),w.literal(-32800),w.literal(-32000),w.literal(-32002),w.number().int().min(-2147483648,{message:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{message:"Invalid value: Expected int32 to be <= 2147483647"})]),Ew=w.object({code:Hf,data:w.unknown().optional(),message:w.string()}),Iw=w.unknown(),qw=w.unknown(),Sw=w.unknown(),Tf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),readTextFile:w.boolean().optional().default(!1),writeTextFile:w.boolean().optional().default(!1)}),hf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),auth:Zf.optional().default({terminal:!1}),fs:Tf.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:w.boolean().optional().default(!1)}),cw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),name:w.string(),value:w.string()}),Rw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),name:w.string(),title:w.string().nullish(),version:w.string()}),bf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),m=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cursor:w.string().nullish(),cwd:w.string().nullish()}),Uf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),http:w.boolean().optional().default(!1),sse:w.boolean().optional().default(!1)}),Cf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),headers:w.array(cw),name:w.string(),url:w.string()}),vf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),headers:w.array(cw),name:w.string(),url:w.string()}),Mf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),args:w.array(w.string()),command:w.string(),env:w.array(Mw),name:w.string()}),I=w.union([Cf.and(w.object({type:w.literal("http")})),vf.and(w.object({type:w.literal("sse")})),Mf]),o=w.string(),Ef=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),modelId:o,name:w.string()}),r=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),mcpServers:w.array(I)}),uw=w.string(),If=w.union([w.literal("allow_once"),w.literal("allow_always"),w.literal("reject_once"),w.literal("reject_always")]),qf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),kind:If,name:w.string(),optionId:uw}),Sf=w.union([w.literal("high"),w.literal("medium"),w.literal("low")]),cf=w.union([w.literal("pending"),w.literal("in_progress"),w.literal("completed")]),Rf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.string(),priority:Sf,status:cf}),uf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),entries:w.array(Rf)}),gf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),audio:w.boolean().optional().default(!1),embeddedContext:w.boolean().optional().default(!1),image:w.boolean().optional().default(!1)}),gw=w.number().int().gte(0).lte(65535),a=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),clientCapabilities:hf.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:Rw.nullish(),protocolVersion:gw}),lf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.string()}),tf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),T=w.union([w.number(),w.string()]).nullable(),sD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),requestId:T}),df=w.enum(["assistant","user"]),M=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),audience:w.array(df).nullish(),lastModified:w.string().nullish(),priority:w.number().nullish()}),nf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),data:w.string(),mimeType:w.string()}),pf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),data:w.string(),mimeType:w.string(),uri:w.string().nullish()}),mf=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),description:w.string().nullish(),mimeType:w.string().nullish(),name:w.string(),size:w.number().nullish(),title:w.string().nullish(),uri:w.string()}),of=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),optionId:uw}),rf=w.union([w.object({outcome:w.literal("cancelled")}),of.and(w.object({outcome:w.literal("selected")}))]),af=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),outcome:rf}),zf=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),sf=w.object({currentValue:w.boolean()}),ef=w.string(),lw=w.string(),wD=w.union([w.literal("mode"),w.literal("model"),w.literal("thought_level"),w.string()]),z=w.string(),iw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),name:w.string(),value:z}),fD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),group:ef,name:w.string(),options:w.array(iw)}),DD=w.union([w.array(iw),w.array(fD)]),$D=w.object({currentValue:z,options:DD}),C=w.intersection(w.union([$D.and(w.object({type:w.literal("select")})),sf.and(w.object({type:w.literal("boolean")}))]),w.object({_meta:w.record(w.string(),w.unknown()).nullish(),category:wD.nullish(),description:w.string().nullish(),id:lw,name:w.string()})),QD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C)}),_D=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),K=w.string(),s=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K}),eD=w.object({method:w.string(),params:w.union([s,Iw]).nullish()}),e=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K}),ww=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),args:w.array(w.string()).optional(),command:w.string(),cwd:w.string().nullish(),env:w.array(Mw).optional(),outputByteLimit:w.number().nullish(),sessionId:K}),fw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),mcpServers:w.array(I).optional(),sessionId:K}),Dw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,terminalId:w.string()}),$w=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),mcpServers:w.array(I),sessionId:K}),Qw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),limit:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),line:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:w.string(),sessionId:K}),_w=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,terminalId:w.string()}),Aw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),mcpServers:w.array(I).optional(),sessionId:K}),AD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cwd:w.string(),sessionId:K,title:w.string().nullish(),updatedAt:w.string().nullish()}),yD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),nextCursor:w.string().nullish(),sessions:w.array(AD)}),jD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),title:w.string().nullish(),updatedAt:w.string().nullish()}),JD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),q=w.string(),GD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),currentModeId:q}),XD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string().nullish(),id:q,name:w.string()}),S=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),availableModes:w.array(XD),currentModeId:q}),c=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),availableModels:w.array(Ef),currentModelId:o}),YD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C).nullish(),models:c.nullish(),modes:S.nullish(),sessionId:K}),ZD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C).nullish(),models:c.nullish(),modes:S.nullish()}),OD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C).nullish(),models:c.nullish(),modes:S.nullish(),sessionId:K}),ND=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C).nullish(),models:c.nullish(),modes:S.nullish()}),WD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),BD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),close:zf.nullish(),fork:_D.nullish(),list:JD.nullish(),resume:WD.nullish()}),KD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),loadSession:w.boolean().optional().default(!1),mcpCapabilities:Uf.optional().default({http:!1,sse:!1}),promptCapabilities:gf.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:BD.optional().default({})}),LD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),agentCapabilities:KD.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:Rw.nullish(),authMethods:w.array(Kf).optional().default([]),protocolVersion:gw}),yw=w.intersection(w.union([w.object({type:w.literal("boolean"),value:w.boolean()}),w.object({value:z})]),w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configId:lw,sessionId:K})),FD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),configOptions:w.array(C)}),jw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),modeId:q,sessionId:K}),kD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),Jw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),modelId:o,sessionId:K}),xD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),VD=w.union([w.literal("end_turn"),w.literal("max_tokens"),w.literal("max_turn_requests"),w.literal("refusal"),w.literal("cancelled")]),PD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),terminalId:w.string()}),HD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),exitCode:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:w.string().nullish()}),Gw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,terminalId:w.string()}),TD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),exitStatus:HD.nullish(),output:w.string(),truncated:w.boolean()}),hD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),text:w.string()}),bD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),mimeType:w.string().nullish(),text:w.string(),uri:w.string()}),UD=w.union([bD,Ff]),CD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),annotations:M.nullish(),resource:UD}),Xw=w.union([hD.and(w.object({type:w.literal("text")})),pf.and(w.object({type:w.literal("image")})),nf.and(w.object({type:w.literal("audio")})),mf.and(w.object({type:w.literal("resource_link")})),CD.and(w.object({type:w.literal("resource")}))]),vD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:Xw}),n=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:Xw,messageId:w.string().nullish()}),Yw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),messageId:w.string().nullish(),prompt:w.array(Xw),sessionId:K}),w$=w.object({id:T,method:w.string(),params:w.union([a,p,r,$w,m,fw,Aw,e,jw,yw,Yw,Jw,qw]).nullish()}),tw=w.union([vD.and(w.object({type:w.literal("content")})),Pf.and(w.object({type:w.literal("diff")})),PD.and(w.object({type:w.literal("terminal")}))]),dw=w.string(),nw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),line:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:w.string()}),pw=w.union([w.literal("pending"),w.literal("in_progress"),w.literal("completed"),w.literal("failed")]),mw=w.union([w.literal("read"),w.literal("edit"),w.literal("delete"),w.literal("move"),w.literal("search"),w.literal("execute"),w.literal("think"),w.literal("fetch"),w.literal("switch_mode"),w.literal("other")]),MD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.array(tw).optional(),kind:mw.optional(),locations:w.array(nw).optional(),rawInput:w.unknown().optional(),rawOutput:w.unknown().optional(),status:pw.optional(),title:w.string(),toolCallId:dw}),ow=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.array(tw).nullish(),kind:mw.nullish(),locations:w.array(nw).nullish(),rawInput:w.unknown().optional(),rawOutput:w.unknown().optional(),status:pw.nullish(),title:w.string().nullish(),toolCallId:dw}),Zw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),options:w.array(qf),sessionId:K,toolCall:ow}),ED=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),hint:w.string()}),ID=ED,qD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),description:w.string(),input:ID.nullish(),name:w.string()}),SD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),availableCommands:w.array(qD)}),cD=w.object({cachedReadTokens:w.number().nullish(),cachedWriteTokens:w.number().nullish(),inputTokens:w.number(),outputTokens:w.number(),thoughtTokens:w.number().nullish(),totalTokens:w.number()}),RD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),stopReason:VD,usage:cD.nullish(),userMessageId:w.string().nullish()}),f$=w.union([w.object({id:T,result:w.union([LD,Lf,OD,ZD,yD,YD,ND,kf,kD,FD,RD,xD,Sw])}),w.object({error:Ew,id:T})]),uD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),cost:xf.nullish(),size:w.number(),used:w.number()}),gD=w.union([n.and(w.object({sessionUpdate:w.literal("user_message_chunk")})),n.and(w.object({sessionUpdate:w.literal("agent_message_chunk")})),n.and(w.object({sessionUpdate:w.literal("agent_thought_chunk")})),MD.and(w.object({sessionUpdate:w.literal("tool_call")})),ow.and(w.object({sessionUpdate:w.literal("tool_call_update")})),uf.and(w.object({sessionUpdate:w.literal("plan")})),SD.and(w.object({sessionUpdate:w.literal("available_commands_update")})),GD.and(w.object({sessionUpdate:w.literal("current_mode_update")})),QD.and(w.object({sessionUpdate:w.literal("config_option_update")})),jD.and(w.object({sessionUpdate:w.literal("session_info_update")})),uD.and(w.object({sessionUpdate:w.literal("usage_update")}))]),Ow=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,update:gD}),D$=w.object({method:w.string(),params:w.union([Ow,Iw]).nullish()}),Nw=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),sessionId:K,terminalId:w.string()}),lD=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),exitCode:w.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:w.string().nullish()}),Ww=w.object({_meta:w.record(w.string(),w.unknown()).nullish(),content:w.string(),path:w.string(),sessionId:K}),$$=w.object({id:T,method:w.string(),params:w.union([Ww,Qw,Zw,ww,Gw,_w,Nw,Dw,qw]).nullish()}),iD=w.object({_meta:w.record(w.string(),w.unknown()).nullish()}),Q$=w.union([w.object({id:T,result:w.union([iD,lf,af,Vf,TD,tf,lD,bf,Sw])}),w.object({error:Ew,id:T})]);function rw(f,$){let D=new TextEncoder,Q=new TextDecoder,j=new ReadableStream({async start(_){let y="",X=$.getReader();try{while(!0){let{value:W,done:J}=await X.read();if(J)break;if(!W)continue;y+=Q.decode(W,{stream:!0});let G=y.split(`
3
3
  `);y=G.pop()||"";for(let Y of G){let O=Y.trim();if(O)try{let Z=JSON.parse(O);_.enqueue(Z)}catch(Z){console.error("Failed to parse JSON message:",O,Z)}}}}finally{X.releaseLock(),_.close()}}}),A=new WritableStream({async write(_){let y=JSON.stringify(_)+`
4
4
  `,X=f.getWriter();try{await X.write(D.encode(y))}finally{X.releaseLock()}}});return{readable:j,writable:A}}class Bw{#w;constructor(f,$){let D=f(this),Q=async(A,_)=>{switch(A){case B.initialize:{let y=a.parse(_);return D.initialize(y)}case B.session_new:{let y=r.parse(_);return D.newSession(y)}case B.session_load:{if(!D.loadSession)throw N.methodNotFound(A);let y=$w.parse(_);return D.loadSession(y)}case B.session_list:{if(!D.listSessions)throw N.methodNotFound(A);let y=m.parse(_);return D.listSessions(y)}case B.session_fork:{if(!D.unstable_forkSession)throw N.methodNotFound(A);let y=fw.parse(_);return D.unstable_forkSession(y)}case B.session_resume:{if(!D.unstable_resumeSession)throw N.methodNotFound(A);let y=Aw.parse(_);return D.unstable_resumeSession(y)}case B.session_close:{if(!D.unstable_closeSession)throw N.methodNotFound(A);let y=e.parse(_);return D.unstable_closeSession(y)}case B.session_set_mode:{if(!D.setSessionMode)throw N.methodNotFound(A);let y=jw.parse(_);return await D.setSessionMode(y)??{}}case B.authenticate:{let y=p.parse(_);return await D.authenticate(y)??{}}case B.session_prompt:{let y=Yw.parse(_);return D.prompt(y)}case B.session_set_model:{if(!D.unstable_setSessionModel)throw N.methodNotFound(A);let y=Jw.parse(_);return await D.unstable_setSessionModel(y)??{}}case B.session_set_config_option:{if(!D.setSessionConfigOption)throw N.methodNotFound(A);let y=yw.parse(_);return D.setSessionConfigOption(y)}default:if(D.extMethod)return D.extMethod(A,_);throw N.methodNotFound(A)}},j=async(A,_)=>{switch(A){case B.session_cancel:{let y=s.parse(_);return D.cancel(y)}default:if(D.extNotification)return D.extNotification(A,_);throw N.methodNotFound(A)}};this.#w=new Kw(Q,j,$)}async sessionUpdate(f){return await this.#w.sendNotification(L.session_update,f)}async requestPermission(f){return await this.#w.sendRequest(L.session_request_permission,f)}async readTextFile(f){return await this.#w.sendRequest(L.fs_read_text_file,f)}async writeTextFile(f){return await this.#w.sendRequest(L.fs_write_text_file,f)??{}}async createTerminal(f){let $=await this.#w.sendRequest(L.terminal_create,f);return new aw($.terminalId,f.sessionId,this.#w)}async extMethod(f,$){return await this.#w.sendRequest(f,$)}async extNotification(f,$){return await this.#w.sendNotification(f,$)}get signal(){return this.#w.signal}get closed(){return this.#w.closed}}class aw{id;#w;#f;constructor(f,$,D){this.id=f,this.#w=$,this.#f=D}async currentOutput(){return await this.#f.sendRequest(L.terminal_output,{sessionId:this.#w,terminalId:this.id})}async waitForExit(){return await this.#f.sendRequest(L.terminal_wait_for_exit,{sessionId:this.#w,terminalId:this.id})}async kill(){return await this.#f.sendRequest(L.terminal_kill,{sessionId:this.#w,terminalId:this.id})??{}}async release(){return await this.#f.sendRequest(L.terminal_release,{sessionId:this.#w,terminalId:this.id})??{}}async[Symbol.asyncDispose](){await this.release()}}class dD{#w;constructor(f,$){let D=f(this),Q=async(A,_)=>{switch(A){case L.fs_write_text_file:{let y=Ww.parse(_);return D.writeTextFile?.(y)}case L.fs_read_text_file:{let y=Qw.parse(_);return D.readTextFile?.(y)}case L.session_request_permission:{let y=Zw.parse(_);return D.requestPermission(y)}case L.terminal_create:{let y=ww.parse(_);return D.createTerminal?.(y)}case L.terminal_output:{let y=Gw.parse(_);return D.terminalOutput?.(y)}case L.terminal_release:{let y=_w.parse(_);return await D.releaseTerminal?.(y)??{}}case L.terminal_wait_for_exit:{let y=Nw.parse(_);return D.waitForTerminalExit?.(y)}case L.terminal_kill:{let y=Dw.parse(_);return await D.killTerminal?.(y)??{}}default:if(D.extMethod)return D.extMethod(A,_);throw N.methodNotFound(A)}},j=async(A,_)=>{switch(A){case L.session_update:{let y=Ow.parse(_);return D.sessionUpdate(y)}default:if(D.extNotification)return D.extNotification(A,_);throw N.methodNotFound(A)}};this.#w=new Kw(Q,j,$)}async initialize(f){return await this.#w.sendRequest(B.initialize,f)}async newSession(f){return await this.#w.sendRequest(B.session_new,f)}async loadSession(f){return await this.#w.sendRequest(B.session_load,f)??{}}async unstable_forkSession(f){return await this.#w.sendRequest(B.session_fork,f)}async listSessions(f){return await this.#w.sendRequest(B.session_list,f)}async unstable_resumeSession(f){return await this.#w.sendRequest(B.session_resume,f)}async unstable_closeSession(f){return await this.#w.sendRequest(B.session_close,f)}async setSessionMode(f){return await this.#w.sendRequest(B.session_set_mode,f)??{}}async unstable_setSessionModel(f){return await this.#w.sendRequest(B.session_set_model,f)??{}}async setSessionConfigOption(f){return await this.#w.sendRequest(B.session_set_config_option,f)}async authenticate(f){return await this.#w.sendRequest(B.authenticate,f)??{}}async prompt(f){return await this.#w.sendRequest(B.session_prompt,f)}async cancel(f){return await this.#w.sendNotification(B.session_cancel,f)}async extMethod(f,$){return await this.#w.sendRequest(f,$)}async extNotification(f,$){return await this.#w.sendNotification(f,$)}get signal(){return this.#w.signal}get closed(){return this.#w.closed}}class Kw{#w=new Map;#f=0;#A;#y;#$;#Q=Promise.resolve();#_=new AbortController;#j;constructor(f,$,D){this.#A=f,this.#y=$,this.#$=D,this.#j=new Promise((Q)=>{this.#_.signal.addEventListener("abort",()=>Q())}),this.#J()}get signal(){return this.#_.signal}get closed(){return this.#j}async#J(){let f=this.#$.readable.getReader();try{while(!0){let{value:$,done:D}=await f.read();if(D)break;if(!$)continue;try{this.#G($)}catch(Q){if(console.error("Unexpected error during message processing:",$,Q),"id"in $&&$.id!==void 0)this.#D({jsonrpc:"2.0",id:$.id,error:{code:-32700,message:"Parse error"}})}}}finally{f.releaseLock(),this.#_.abort()}}async#G(f){if("method"in f&&"id"in f){let $=await this.#X(f.method,f.params);if("error"in $)console.error("Error handling request",f,$.error);await this.#D({jsonrpc:"2.0",id:f.id,...$})}else if("method"in f){let $=await this.#Y(f.method,f.params);if("error"in $)console.error("Error handling notification",f,$.error)}else if("id"in f)this.#Z(f);else console.error("Invalid message",{message:f})}async#X(f,$){try{return{result:await this.#A(f,$)??null}}catch(D){if(D instanceof N)return D.toResult();if(D instanceof w.ZodError)return N.invalidParams(D.format()).toResult();let Q;if(D instanceof Error)Q=D.message;else if(typeof D==="object"&&D!=null&&"message"in D&&typeof D.message==="string")Q=D.message;try{return N.internalError(Q?JSON.parse(Q):{}).toResult()}catch{return N.internalError({details:Q}).toResult()}}}async#Y(f,$){try{return await this.#y(f,$),{result:null}}catch(D){if(D instanceof N)return D.toResult();if(D instanceof w.ZodError)return N.invalidParams(D.format()).toResult();let Q;if(D instanceof Error)Q=D.message;else if(typeof D==="object"&&D!=null&&"message"in D&&typeof D.message==="string")Q=D.message;try{return N.internalError(Q?JSON.parse(Q):{}).toResult()}catch{return N.internalError({details:Q}).toResult()}}}#Z(f){let $=this.#w.get(f.id);if($){if("result"in f)$.resolve(f.result);else if("error"in f)$.reject(f.error);this.#w.delete(f.id)}else console.error("Got response to unknown request",f.id)}async sendRequest(f,$){let D=this.#f++,Q=new Promise((j,A)=>{this.#w.set(D,{resolve:j,reject:A})});return await this.#D({jsonrpc:"2.0",id:D,method:f,params:$}),Q}async sendNotification(f,$){await this.#D({jsonrpc:"2.0",method:f,params:$})}async#D(f){return this.#Q=this.#Q.then(async()=>{let $=this.#$.writable.getWriter();try{await $.write(f)}finally{$.releaseLock()}}).catch(($)=>{console.error("ACP write error:",$)}),this.#Q}}class N extends Error{code;data;constructor(f,$,D){super($);this.code=f,this.name="RequestError",this.data=D}static parseError(f,$){return new N(-32700,`Parse error${$?`: ${$}`:""}`,f)}static invalidRequest(f,$){return new N(-32600,`Invalid request${$?`: ${$}`:""}`,f)}static methodNotFound(f){return new N(-32601,`"Method not found": ${f}`,{method:f})}static invalidParams(f,$){return new N(-32602,`Invalid params${$?`: ${$}`:""}`,f)}static internalError(f,$){return new N(-32603,`Internal error${$?`: ${$}`:""}`,f)}static authRequired(f,$){return new N(-32000,`Authentication required${$?`: ${$}`:""}`,f)}static resourceNotFound(f){return new N(-32002,`Resource not found${f?`: ${f}`:""}`,f&&{uri:f})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}}var E={};mD(E,{init:()=>rD,Agent:()=>vw,ACP:()=>E});var Lw=V.create({service:"acp-session-manager"});class Fw{sessions=new Map;sdk;constructor(f){this.sdk=f}tryGet(f){return this.sessions.get(f)}async create(f,$,D){let j=(await this.sdk.session.create({directory:f},{throwOnError:!0}).then((y)=>y.data)).id,_={id:j,cwd:f,mcpServers:$,createdAt:new Date,model:D};return Lw.info("creating_session",{state:_}),this.sessions.set(j,_),_}async load(f,$,D,Q){let j=await this.sdk.session.get({sessionID:f,directory:$},{throwOnError:!0}).then((y)=>y.data),A=Q,_={id:f,cwd:$,mcpServers:D,createdAt:new Date(j.time.created),model:A};return Lw.info("loading_session",{state:_}),this.sessions.set(f,_),_}get(f){let $=this.sessions.get(f);if(!$)throw Lw.error("session not found",{sessionId:f}),N.invalidParams(JSON.stringify({error:`Session not found: ${f}`}));return $}getModel(f){return this.get(f).model}setModel(f,$){let D=this.get(f);return D.model=$,this.sessions.set(f,D),D}getVariant(f){return this.get(f).variant}setVariant(f,$){let D=this.get(f);return D.variant=$,this.sessions.set(f,D),D}setMode(f,$){let D=this.get(f);return D.modeId=$,this.sessions.set(f,D),D}}import{pathToFileURL as R}from"url";var nD=V.create({service:"acp-message-translator"}),pD="default";function b(f){switch(f.toLocaleLowerCase()){case"bash":return"execute";case"webfetch":return"fetch";case"edit":case"patch":case"write":return"edit";case"grep":case"glob":case"context7_resolve_library_id":case"context7_get_library_docs":return"search";case"read":return"read";default:return"other"}}function u(f,$){switch(f.toLocaleLowerCase()){case"read":case"edit":case"write":return $.filePath?[{path:$.filePath}]:[];case"glob":case"grep":return $.path?[{path:$.path}]:[];case"bash":return[];default:return[]}}function g(f){try{if(f.startsWith("file://")){let $=f.slice(7),D=$.split("/").pop()||$;return{type:"file",url:f,filename:D,mime:"text/plain"}}if(f.startsWith("zed://")){let D=new URL(f).searchParams.get("path");if(D){let Q=D.split("/").pop()||D;return{type:"file",url:R(D).href,filename:Q,mime:"text/plain"}}}return{type:"text",text:f}}catch{return{type:"text",text:f}}}function sw(f,$){let D=zw(f,$);if(D===!1){nD.error("Failed to apply unified diff (context mismatch)");return}return D}function kw(f){if(f.tool!=="bash")return;if(!("metadata"in f.state)||!f.state.metadata||typeof f.state.metadata!=="object")return;let $=f.state.metadata.output;if(typeof $!=="string")return;return $}function l(f){return[...f].sort(($,D)=>{let Q=$.name.toLowerCase(),j=D.name.toLowerCase();if(Q<j)return-1;if(Q>j)return 1;return 0})}function xw(f,$){let D=f.find((j)=>j.id===$.providerID);if(!D)return[];let Q=D.models[$.modelID];if(!Q?.variants)return[];return Object.keys(Q.variants)}function ew(f,$={}){let D=$.includeVariants??!1;return f.flatMap((Q)=>{let j=Object.values(Q.models);return h.sort(j).flatMap((_)=>{let y={modelId:`${Q.id}/${_.id}`,name:`${Q.name}/${_.name}`};if(!D||!_.variants)return[y];let W=Object.keys(_.variants).filter((J)=>J!==pD).map((J)=>({modelId:`${Q.id}/${_.id}/${J}`,name:`${Q.name}/${_.name} (${J})`}));return[y,...W]})})}function i(f,$,D,Q){let j=`${f.providerID}/${f.modelID}`;if(!Q||!$||!D.includes($))return j;return`${j}/${$}`}function Vw(f){return{opencode:{modelId:`${f.model.providerID}/${f.model.modelID}`,variant:f.variant??null,availableVariants:f.availableVariants}}}function Pw(f,$){let D=h.parseModel(f),Q=$.find((A)=>A.id===D.providerID);if(!Q)return{model:D,variant:void 0};if(Q.models[D.modelID])return{model:D,variant:void 0};let j=D.modelID.split("/");if(j.length>1){let A=j[j.length-1],_=j.slice(0,-1).join("/"),y=Q.models[_];if(y?.variants&&A in y.variants)return{model:{providerID:D.providerID,modelID:P.make(_)},variant:A}}return{model:D,variant:void 0}}function t(f){let $=[{id:"model",name:"Model",category:"model",type:"select",currentValue:f.currentModelId,options:f.availableModels.map((D)=>({value:D.modelId,name:D.name}))}];if(f.modes)$.push({id:"mode",name:"Session Mode",category:"mode",type:"select",currentValue:f.modes.currentModeId,options:f.modes.availableModes.map((D)=>({value:D.id,name:D.name,...D.description?{description:D.description}:{}}))});return $}var wf=V.create({service:"acp-permissions"});class Tw{connection;sdk;sessionManager;permissionQueues=new Map;permissionOptions=[{optionId:"once",kind:"allow_once",name:"Allow once"},{optionId:"always",kind:"allow_always",name:"Always allow"},{optionId:"reject",kind:"reject_once",name:"Reject"}];constructor(f,$,D){this.connection=f;this.sdk=$;this.sessionManager=D}handle(f){let $=this.sessionManager.tryGet(f.sessionID);if(!$)return;let Q=(this.permissionQueues.get(f.sessionID)??Promise.resolve()).then(async()=>{let j=$.cwd,A=await this.connection.requestPermission({sessionId:f.sessionID,toolCall:{toolCallId:f.tool?.callID??f.id,status:"pending",title:f.permission,rawInput:f.metadata,kind:b(f.permission),locations:u(f.permission,f.metadata??{})},options:this.permissionOptions}).catch(async(_)=>{wf.error("failed to request permission from ACP",{error:_,permissionID:f.id,sessionID:f.sessionID}),await this.sdk.permission.reply({requestID:f.id,reply:"reject",directory:j});return});if(!A)return;if(A.outcome.outcome!=="selected"){await this.sdk.permission.reply({requestID:f.id,reply:"reject",directory:j});return}if(A.outcome.optionId!=="reject"&&f.permission=="edit"){let _=f.metadata||{},y=typeof _.filepath==="string"?_.filepath:"",X=typeof _.diff==="string"?_.diff:"",W=await Hw.exists(y)?await Hw.readText(y):"",J=sw(W,X);if(J)this.connection.writeTextFile({sessionId:$.id,path:y,content:J})}await this.sdk.permission.reply({requestID:f.id,reply:A.outcome.optionId,directory:j})}).catch((j)=>{wf.error("failed to handle permission",{error:j,permissionID:f.id})}).finally(()=>{if(this.permissionQueues.get(f.sessionID)===Q)this.permissionQueues.delete(f.sessionID)});this.permissionQueues.set(f.sessionID,Q)}}var F=V.create({service:"acp-event-bridge"});class hw{connection;sdk;sessionManager;eventAbort=new AbortController;eventStarted=!1;bashSnapshots=new Map;toolStarts=new Set;permissionHandler;constructor(f,$,D){this.connection=f;this.sdk=$;this.sessionManager=D;this.permissionHandler=new Tw(f,$,D)}start(){if(this.eventStarted)return;this.eventStarted=!0,this.runEventSubscription().catch((f)=>{if(this.eventAbort.signal.aborted)return;F.error("event subscription failed",{error:f})})}stop(){this.eventAbort.abort()}async runEventSubscription(){while(!0){if(this.eventAbort.signal.aborted)return;let f=await this.sdk.global.event({signal:this.eventAbort.signal,sseMaxRetryAttempts:0});for await(let $ of f.stream){if(this.eventAbort.signal.aborted)return;let D=$?.payload;if(!D)continue;await this.handleEvent(D).catch((Q)=>{F.error("failed to handle event",{error:Q,type:D.type})})}if(this.eventAbort.signal.aborted)return;await new Promise(($)=>{let D=()=>{clearTimeout(Q),this.eventAbort.signal.removeEventListener("abort",D),$()},Q=setTimeout(D,1000);if(this.eventAbort.signal.addEventListener("abort",D,{once:!0}),this.eventAbort.signal.aborted)D()})}}async handleEvent(f){switch(f.type){case"permission.asked":{this.permissionHandler.handle(f.properties);return}case"message.part.updated":{F.info("message part updated",{event:f.properties});let D=f.properties.part,Q=this.sessionManager.tryGet(D.sessionID);if(!Q)return;let j=Q.id;if(D.type==="tool")switch(await this.toolStart(j,D),D.state.status){case"pending":this.bashSnapshots.delete(D.callID);return;case"running":{let A=kw(D),_=[];if(A){let y=ff.fast(A);if(D.tool==="bash"){if(this.bashSnapshots.get(D.callID)===y){await this.sendToolInProgress(j,D,D.state,[]);return}this.bashSnapshots.set(D.callID,y)}_.push({type:"content",content:{type:"text",text:A}})}await this.sendToolInProgress(j,D,D.state,_);return}case"completed":await this.sendToolCompleted(j,D,D.state);return;case"error":await this.sendToolError(j,D,D.state);return}if(D.type!=="text"&&D.type!=="file")return;return}case"message.part.delta":{let $=f.properties,D=this.sessionManager.tryGet($.sessionID);if(!D)return;let Q=D.id,j=await this.sdk.session.message({sessionID:$.sessionID,messageID:$.messageID,directory:D.cwd},{throwOnError:!0}).then((_)=>_.data).catch((_)=>{F.error("unexpected error when fetching message",{error:_});return});if(!j||j.info.role!=="assistant")return;let A=j.parts.find((_)=>_.id===$.partID);if(!A)return;if(A.type==="text"&&$.field==="text"&&A.ignored!==!0){await this.connection.sessionUpdate({sessionId:Q,update:{sessionUpdate:"agent_message_chunk",messageId:$.messageID,content:{type:"text",text:$.delta}}}).catch((_)=>{F.error("failed to send text delta to ACP",{error:_})});return}if(A.type==="reasoning"&&$.field==="text")await this.connection.sessionUpdate({sessionId:Q,update:{sessionUpdate:"agent_thought_chunk",messageId:$.messageID,content:{type:"text",text:$.delta}}}).catch((_)=>{F.error("failed to send reasoning delta to ACP",{error:_})});return}}}async sendToolInProgress(f,$,D,Q){await this.connection.sessionUpdate({sessionId:f,update:{sessionUpdate:"tool_call_update",toolCallId:$.callID,status:"in_progress",kind:b($.tool),title:$.tool,locations:u($.tool,D.input),rawInput:D.input,...Q.length>0&&{content:Q}}}).catch((j)=>{F.error("failed to send tool in_progress to ACP",{error:j})})}async sendToolCompleted(f,$,D){this.toolStarts.delete($.callID),this.bashSnapshots.delete($.callID);let Q=b($.tool),j=[{type:"content",content:{type:"text",text:D.output}}];if(Q==="edit"){let A=D.input,_=typeof A.filePath==="string"?A.filePath:"",y=typeof A.oldString==="string"?A.oldString:"",X=typeof A.newString==="string"?A.newString:typeof A.content==="string"?A.content:"";j.push({type:"diff",path:_,oldText:y,newText:X})}await this.connection.sessionUpdate({sessionId:f,update:{sessionUpdate:"tool_call_update",toolCallId:$.callID,status:"completed",kind:Q,content:j,title:D.title,rawInput:D.input,rawOutput:{output:D.output,metadata:D.metadata}}}).catch((A)=>{F.error("failed to send tool completed to ACP",{error:A})})}async sendToolError(f,$,D){this.toolStarts.delete($.callID),this.bashSnapshots.delete($.callID),await this.connection.sessionUpdate({sessionId:f,update:{sessionUpdate:"tool_call_update",toolCallId:$.callID,status:"failed",kind:b($.tool),title:$.tool,rawInput:D.input,content:[{type:"content",content:{type:"text",text:D.error}}],rawOutput:{error:D.error,metadata:D.metadata}}}).catch((Q)=>{F.error("failed to send tool error to ACP",{error:Q})})}async toolStart(f,$){if(this.toolStarts.has($.callID))return;this.toolStarts.add($.callID),await this.connection.sessionUpdate({sessionId:f,update:{sessionUpdate:"tool_call",toolCallId:$.callID,title:$.tool,kind:b($.tool),status:"pending",locations:[],rawInput:{}}}).catch((D)=>{F.error("failed to send tool pending to ACP",{error:D})})}async processMessage(f){if(F.debug("process message",f),f.info.role!=="assistant"&&f.info.role!=="user")return;let $=f.info.sessionID;for(let D of f.parts)if(D.type==="tool")switch(await this.toolStart($,D),D.state.status){case"pending":this.bashSnapshots.delete(D.callID);break;case"running":{let Q=kw(D),j=[];if(Q)j.push({type:"content",content:{type:"text",text:Q}});await this.sendToolInProgress($,D,D.state,j);break}case"completed":await this.sendToolCompleted($,D,D.state);break;case"error":await this.sendToolError($,D,D.state);break}else if(D.type==="text"){if(D.text){let Q=D.synthetic?["assistant"]:D.ignored?["user"]:void 0;await this.connection.sessionUpdate({sessionId:$,update:{sessionUpdate:f.info.role==="user"?"user_message_chunk":"agent_message_chunk",messageId:f.info.id,content:{type:"text",text:D.text,...Q&&{annotations:{audience:Q}}}}}).catch((j)=>{F.error("failed to send text to ACP",{error:j})})}}else if(D.type==="file"){let Q=D.url,j=D.filename??"file",A=D.mime||"application/octet-stream",_=f.info.role==="user"?"user_message_chunk":"agent_message_chunk";if(Q.startsWith("file://"))await this.connection.sessionUpdate({sessionId:$,update:{sessionUpdate:_,messageId:f.info.id,content:{type:"resource_link",uri:Q,name:j,mimeType:A}}}).catch((y)=>{F.error("failed to send resource_link to ACP",{error:y})});else if(Q.startsWith("data:")){let y=Q.match(/^data:([^;]+);base64,(.*)$/),X=y?.[1],W=y?.[2]??"",J=X||A;if(J.startsWith("image/"))await this.connection.sessionUpdate({sessionId:$,update:{sessionUpdate:_,messageId:f.info.id,content:{type:"image",mimeType:J,data:W,uri:R(j).href}}}).catch((G)=>{F.error("failed to send image to ACP",{error:G})});else{let G=J.startsWith("text/")||J==="application/json",Y=R(j).href,O=G?{uri:Y,mimeType:J,text:Buffer.from(W,"base64").toString("utf-8")}:{uri:Y,mimeType:J,blob:W};await this.connection.sessionUpdate({sessionId:$,update:{sessionUpdate:_,messageId:f.info.id,content:{type:"resource",resource:O}}}).catch((Z)=>{F.error("failed to send resource to ACP",{error:Z})})}}}else if(D.type==="reasoning"){if(D.text)await this.connection.sessionUpdate({sessionId:$,update:{sessionUpdate:"agent_thought_chunk",messageId:f.info.id,content:{type:"text",text:D.text}}}).catch((Q)=>{F.error("failed to send reasoning to ACP",{error:Q})})}}}var x=V.create({service:"acp-agent"});async function oD(f,$,D,Q){return(await f.config.providers({directory:Q}).then((y)=>y.data?.providers??[]).catch((y)=>{return x.error("failed to get providers for context limit",{error:y}),[]})).find((y)=>y.id===$)?.models[D]?.limit.context??null}async function bw(f,$,D,Q){let j=await $.session.messages({sessionID:D,directory:Q,agent_id:"main"},{throwOnError:!0}).then((G)=>G.data).catch((G)=>{x.error("failed to fetch messages for usage update",{error:G});return});if(!j)return;let A=j.filter((G)=>G.info.role==="assistant"),_=A[A.length-1];if(!_)return;let y=_.info;if(!y.providerID||!y.modelID)return;let X=await oD($,H.make(y.providerID),P.make(y.modelID),Q);if(!X)return;let W=y.tokens.input+(y.tokens.cache?.read??0),J=A.reduce((G,Y)=>G+Y.info.cost,0);await f.sessionUpdate({sessionId:D,update:{sessionUpdate:"usage_update",used:W,size:X,cost:{amount:J,currency:"USD"}}}).catch((G)=>{x.error("failed to send usage update",{error:G})})}async function rD({sdk:f}){return{create:($,D)=>{return new vw($,D)}}}class vw{connection;config;sdk;sessionManager;eventBridge;constructor(f,$){this.connection=f,this.config=$,this.sdk=$.sdk,this.sessionManager=new Fw(this.sdk),this.eventBridge=new hw(f,this.sdk,this.sessionManager),this.eventBridge.start()}async initialize(f){x.info("initialize",{protocolVersion:f.protocolVersion});let $={description:"Run `qitqode auth login` in the terminal",name:"Login with qitqode",id:"qitqode-login"};if(f.clientCapabilities?._meta?.["terminal-auth"]===!0)$._meta={"terminal-auth":{command:"qitqode",args:["auth","login"],label:"QitQode Login"}};return{protocolVersion:1,agentCapabilities:{loadSession:!0,mcpCapabilities:{http:!0,sse:!0},promptCapabilities:{embeddedContext:!0,image:!0},sessionCapabilities:{fork:{},list:{},resume:{}}},authMethods:[$],agentInfo:{name:"QitQode",version:Df}}}async authenticate(f){throw Error("Authentication not implemented")}rethrowSessionError(f){let $=_f.fromError(f,{providerID:H.make(this.config.defaultModel?.providerID??"unknown")});if($f.isInstance($))throw N.authRequired();throw f}fetchSessionMessages(f,$){return this.sdk.session.messages({sessionID:f,directory:$,agent_id:"main"},{throwOnError:!0}).then((D)=>D.data).catch((D)=>{x.error("unexpected error when fetching message",{error:D});return})}loadSessionProviders(f){return this.sdk.config.providers({directory:f},{throwOnError:!0}).then(($)=>$.data.providers)}async newSession(f){let $=f.cwd;try{let D=await U(this.config,$),j=(await this.sessionManager.create(f.cwd,f.mcpServers,D)).id;x.info("creating_session",{sessionId:j,mcpServers:f.mcpServers.length});let A=await this.loadSessionMode({cwd:$,mcpServers:f.mcpServers,sessionId:j});return{sessionId:j,configOptions:A.configOptions,models:A.models,modes:A.modes,_meta:A._meta}}catch(D){this.rethrowSessionError(D)}}async loadSession(f){let{cwd:$,sessionId:D}=f;try{let Q=await U(this.config,$);await this.sessionManager.load(D,f.cwd,f.mcpServers,Q),x.info("load_session",{sessionId:D,mcpServers:f.mcpServers.length});let j=await this.loadSessionMode({cwd:$,mcpServers:f.mcpServers,sessionId:D}),A=await this.fetchSessionMessages(D,$),_=A?.findLast((y)=>y.info.role==="user")?.info;if(_?.role==="user"){if(j.models.currentModelId=`${_.model.providerID}/${_.model.modelID}`,this.sessionManager.setModel(D,{providerID:H.make(_.model.providerID),modelID:P.make(_.model.modelID)}),j.modes?.availableModes.some((y)=>y.id===_.agent))j.modes.currentModeId=_.agent,this.sessionManager.setMode(D,_.agent);j.configOptions=t({currentModelId:j.models.currentModelId,availableModels:j.models.availableModels,modes:j.modes})}return await this.replayMessagesAndSendUsage(A,D,$),j}catch(Q){this.rethrowSessionError(Q)}}async listSessions(f){try{let D=await this.sdk.session.list({directory:f.cwd??void 0,roots:!0},{throwOnError:!0}).then((G)=>G.data??[]),Q=f.cursor?Number(f.cursor):void 0,j=D.toSorted((G,Y)=>Y.time.updated-G.time.updated),A=Q?j.filter((G)=>G.time.updated<Q):j,_=A.slice(0,100),y=_.map((G)=>({sessionId:G.id,cwd:G.directory,title:G.title,updatedAt:new Date(G.time.updated).toISOString()})),X=_[_.length-1],W=A.length>100&&X?String(X.time.updated):void 0,J={sessions:y};if(W)J.nextCursor=W;return J}catch($){this.rethrowSessionError($)}}async unstable_forkSession(f){let $=f.cwd,D=f.mcpServers??[];try{let Q=await U(this.config,$),j=await this.sdk.session.fork({sessionID:f.sessionId,directory:$},{throwOnError:!0}).then((X)=>X.data);if(!j)throw Error("Fork session returned no data");let A=j.id;await this.sessionManager.load(A,$,D,Q),x.info("fork_session",{sessionId:A,mcpServers:D.length});let _=await this.loadSessionMode({cwd:$,mcpServers:D,sessionId:A}),y=await this.fetchSessionMessages(A,$);return await this.replayMessagesAndSendUsage(y,A,$),_}catch(Q){this.rethrowSessionError(Q)}}async unstable_resumeSession(f){let{cwd:$,sessionId:D}=f,Q=f.mcpServers??[];try{let j=await U(this.config,$);await this.sessionManager.load(D,$,Q,j),x.info("resume_session",{sessionId:D,mcpServers:Q.length});let A=await this.loadSessionMode({cwd:$,mcpServers:Q,sessionId:D});return await bw(this.connection,this.sdk,D,$),A}catch(j){this.rethrowSessionError(j)}}async loadAvailableModes(f){return(await this.config.sdk.app.agents({directory:f},{throwOnError:!0}).then((D)=>D.data)).filter((D)=>D.mode!=="subagent"&&!D.hidden).map((D)=>({id:D.name,name:D.name,description:D.description}))}async resolveModeState(f,$){let D=await this.loadAvailableModes(f),Q=this.sessionManager.get($).modeId||await(async()=>{if(!D.length)return;let j=await Cw.runPromise(Uw.Service.use((_)=>_.defaultAgent())),A=D.find((_)=>_.name===j)?.id??D[0].id;return this.sessionManager.setMode($,A),A})();return{availableModes:D,currentModeId:Q}}async replayMessagesAndSendUsage(f,$,D){for(let Q of f??[])x.debug("replay message",Q),await this.eventBridge.processMessage(Q);await bw(this.connection,this.sdk,$,D)}async resolveModelsAndModes(f){let $=xw(f.entries,f.model);f.onVariants?.($);let D=ew(f.entries,{includeVariants:!0}),Q=await this.resolveModeState(f.directory,f.sessionId),j=Q.currentModeId?{availableModes:Q.availableModes,currentModeId:Q.currentModeId}:void 0;return{availableVariants:$,availableModels:D,modes:j}}async loadSessionMode(f){let $=f.cwd,D=await U(this.config,$),Q=f.sessionId,j=await this.sdk.config.providers({directory:$}).then((Z)=>Z.data.providers),A=l(j),_=this.sessionManager.getVariant(Q),{availableVariants:y,availableModels:X,modes:W}=await this.resolveModelsAndModes({entries:A,model:D,directory:$,sessionId:Q,onVariants:(Z)=>{if(_&&!Z.includes(_))this.sessionManager.setVariant(Q,void 0)}}),G=(await this.config.sdk.command.list({directory:$},{throwOnError:!0}).then((Z)=>Z.data)).map((Z)=>({name:Z.name,description:Z.description??""}));if(!new Set(G.map((Z)=>Z.name)).has("compact"))G.push({name:"compact",description:"summarize the session to reduce context"});let O={};for(let Z of f.mcpServers)if("type"in Z)O[Z.name]={url:Z.url,headers:Z.headers.reduce((k,{name:v,value:d})=>{return k[v]=d,k},{}),type:"remote"};else O[Z.name]={type:"local",command:[Z.command,...Z.args],environment:Z.env.reduce((k,{name:v,value:d})=>{return k[v]=d,k},{})};return await Promise.all(Object.entries(O).map(async([Z,k])=>{await this.sdk.mcp.add({directory:$,name:Z,config:k},{throwOnError:!0}).catch((v)=>{x.error("failed to add mcp server",{name:Z,error:v})})})),setTimeout(()=>{this.connection.sessionUpdate({sessionId:Q,update:{sessionUpdate:"available_commands_update",availableCommands:G}})},0),{sessionId:Q,models:{currentModelId:i(D,_,y,!0),availableModels:X},modes:W,configOptions:t({currentModelId:i(D,_,y,!0),availableModels:X,modes:W}),_meta:Vw({model:D,variant:this.sessionManager.getVariant(Q),availableVariants:y})}}async unstable_setSessionModel(f){let $=this.sessionManager.get(f.sessionId),D=await this.loadSessionProviders($.cwd),Q=Pw(f.modelId,D);this.sessionManager.setModel($.id,Q.model),this.sessionManager.setVariant($.id,Q.variant);let j=l(D),A=xw(j,Q.model);return{_meta:Vw({model:Q.model,variant:Q.variant,availableVariants:A})}}async setSessionMode(f){let $=this.sessionManager.get(f.sessionId);if(!(await this.loadAvailableModes($.cwd)).some((Q)=>Q.id===f.modeId))throw Error(`Agent not found: ${f.modeId}`);this.sessionManager.setMode(f.sessionId,f.modeId)}async setSessionConfigOption(f){let $=this.sessionManager.get(f.sessionId),D=await this.loadSessionProviders($.cwd),Q=l(D);if(f.configId==="model"){if(typeof f.value!=="string")throw N.invalidParams("model value must be a string");let J=Pw(f.value,D);this.sessionManager.setModel($.id,J.model),this.sessionManager.setVariant($.id,J.variant)}else if(f.configId==="mode"){if(typeof f.value!=="string")throw N.invalidParams("mode value must be a string");if(!(await this.loadAvailableModes($.cwd)).some((G)=>G.id===f.value))throw N.invalidParams(JSON.stringify({error:`Mode not found: ${f.value}`}));this.sessionManager.setMode($.id,f.value)}else throw N.invalidParams(JSON.stringify({error:`Unknown config option: ${f.configId}`}));let j=this.sessionManager.get($.id),A=j.model??await U(this.config,$.cwd),{availableVariants:_,availableModels:y,modes:X}=await this.resolveModelsAndModes({entries:Q,model:A,directory:$.cwd,sessionId:$.id}),W=i(A,j.variant,_,!0);return{configOptions:t({currentModelId:W,availableModels:y,modes:X})}}async prompt(f){let $=f.sessionId,D=this.sessionManager.get($),Q=D.cwd,j=D.model,A=j??await U(this.config,Q);if(!j)this.sessionManager.setModel(D.id,A);let _=D.modeId??await Cw.runPromise(Uw.Service.use((Y)=>Y.defaultAgent())),y=[];for(let Y of f.prompt)switch(Y.type){case"text":{let O=Y.annotations?.audience,Z=O?.length===1&&O[0]==="assistant",k=O?.length===1&&O[0]==="user";y.push({type:"text",text:Y.text,...Z&&{synthetic:!0},...k&&{ignored:!0}});break}case"image":{let O=g(Y.uri??""),Z=O.type==="file"?O.filename:"image";if(Y.data)y.push({type:"file",url:`data:${Y.mimeType};base64,${Y.data}`,filename:Z,mime:Y.mimeType});else if(Y.uri&&Y.uri.startsWith("http:"))y.push({type:"file",url:Y.uri,filename:Z,mime:Y.mimeType});break}case"resource_link":{let O=g(Y.uri);if(Y.name&&O.type==="file")O.filename=Y.name;y.push(O);break}case"resource":{let O=Y.resource;if("text"in O&&O.text)y.push({type:"text",text:O.text});else if("blob"in O&&O.blob&&O.mimeType){let Z=g(O.uri??""),k=Z.type==="file"?Z.filename:"file";y.push({type:"file",url:`data:${O.mimeType};base64,${O.blob}`,filename:k,mime:O.mimeType})}break}default:break}x.info("parts",{parts:y});let X=(()=>{let Y=y.filter((k)=>k.type==="text").map((k)=>k.text).join("").trim();if(!Y.startsWith("/"))return;let[O,...Z]=Y.slice(1).split(/\s+/);return{name:O,args:Z.join(" ").trim()}})(),W=(Y)=>({totalTokens:Y.tokens.input+Y.tokens.output+Y.tokens.reasoning+(Y.tokens.cache?.read??0)+(Y.tokens.cache?.write??0),inputTokens:Y.tokens.input,outputTokens:Y.tokens.output,thoughtTokens:Y.tokens.reasoning||void 0,cachedReadTokens:Y.tokens.cache?.read||void 0,cachedWriteTokens:Y.tokens.cache?.write||void 0}),J,G=!1;if(!X)G=!0,J=(await this.sdk.session.prompt({sessionID:$,model:{providerID:A.providerID,modelID:A.modelID},variant:this.sessionManager.getVariant($),parts:y,agent:_,directory:Q})).data?.info;else{let Y=await this.config.sdk.command.list({directory:Q},{throwOnError:!0}).then((O)=>O.data.find((Z)=>Z.name===X.name));if(Y)G=!0,J=(await this.sdk.session.command({sessionID:$,command:Y.name,arguments:X.args,model:A.providerID+"/"+A.modelID,agent:_,directory:Q})).data?.info;else switch(X.name){case"compact":await this.config.sdk.session.summarize({sessionID:$,directory:Q,providerID:A.providerID,modelID:A.modelID},{throwOnError:!0});break}}return await bw(this.connection,this.sdk,$,Q),{stopReason:"end_turn",...G?{usage:J?W(J):void 0}:{},_meta:{}}}async cancel(f){let $=this.sessionManager.get(f.sessionId);await this.config.sdk.session.abort({sessionID:f.sessionId,directory:$.cwd},{throwOnError:!0})}}async function U(f,$){let{sdk:D,defaultModel:Q}=f;if(Q)return Q;let j=$??process.cwd(),A=await D.config.get({directory:j},{throwOnError:!0}).then((J)=>{let G=J.data;if(!G||!G.model)return;return h.parseModel(G.model)}).catch((J)=>{x.error("failed to load user config for default model",{error:J});return}),_=await D.config.providers({directory:j},{throwOnError:!0}).then((J)=>J.data?.providers??[]).catch((J)=>{return x.error("failed to list providers for default model",{error:J}),[]});if(A&&_.length){let J=_.find((G)=>G.id===A.providerID);if(J&&J.models[A.modelID])return A}if(A&&!_.length)return A;let y=_.find((J)=>J.id==="opencode");if(y){if(y.models["big-pickle"])return{providerID:H.opencode,modelID:P.make("big-pickle")};let[J]=h.sort(Object.values(y.models));if(J)return{providerID:H.make(J.providerID),modelID:P.make(J.id)}}for(let J of["default","fast","economical","power"]){let G=Qf[J];if(!G)continue;if(_.find((O)=>O.id===G.providerID)?.models[G.modelID])return{providerID:H.make(G.providerID),modelID:P.make(G.modelID)}}let X=_.flatMap((J)=>Object.values(J.models)),[W]=h.sort(X);if(W)return{providerID:H.make(W.providerID),modelID:P.make(W.id)};if(A)return A;return{providerID:H.opencode,modelID:P.make("big-pickle")}}var aD=V.create({service:"acp-command"}),z$=Gf({command:"acp",describe:"start ACP (Agent Client Protocol) server",builder:(f)=>{return Af(f).option("cwd",{describe:"working directory",type:"string",default:process.cwd()})},handler:async(f)=>{process.env.QITQODE_CLIENT="acp",await Jf(process.cwd(),async()=>{let $=await Xf(f),D=await jf.listen($),Q=yf({baseUrl:`http://${D.hostname}:${D.port}`}),j=new WritableStream({write(X){return new Promise((W,J)=>{process.stdout.write(X,(G)=>{if(G)J(G);else W()})})}}),A=new ReadableStream({start(X){process.stdin.on("data",(W)=>{X.enqueue(new Uint8Array(W))}),process.stdin.on("end",()=>X.close()),process.stdin.on("error",(W)=>X.error(W))}}),_=rw(j,A),y=await E.init({sdk:Q});new Bw((X)=>{return y.create(X,{sdk:Q})},_),aD.info("setup connection"),process.stdin.resume(),await new Promise((X,W)=>{process.stdin.on("end",X),process.stdin.on("error",W)})})}});export{z$ as AcpCommand};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{rh as r}from"./chunk-ckhhm2m8.js";import{Sj as e}from"./chunk-q39h31te.js";import{$l as t}from"./chunk-fegrrsfj.js";import{mp as l}from"./chunk-tq258v8s.js";import{It as a}from"./chunk-tk6gjy9d.js";import{BN as o}from"./chunk-meaa7wrs.js";var S={PromptAppend:t.define("tui.prompt.append",a.object({text:a.string()})),CommandExecute:t.define("tui.command.execute",a.object({command:a.union([a.enum(["session.list","session.new","session.share","session.interrupt","session.compact","session.page.up","session.page.down","session.line.up","session.line.down","session.half.page.up","session.half.page.down","session.first","session.last","prompt.clear","prompt.submit","agent.cycle"]),a.string()])})),ToastShow:t.define("tui.toast.show",a.object({title:a.string().optional(),message:a.string(),variant:a.enum(["info","success","warning","error"]),duration:a.number().default(5000).optional().describe("Duration in milliseconds")})),SessionSelect:t.define("tui.session.select",a.object({sessionID:e.zod.describe("Session ID to navigate to")})),InstructionsLoaded:r};class m extends o.Class("ConsoleState")({consoleManagedProviders:o.mutable(o.Array(o.String)),activeOrgName:o.optional(o.String),switchableOrgCount:o.Number}){static zod=l(this)}var f=m.make({consoleManagedProviders:[],activeOrgName:void 0,switchableOrgCount:0});
2
+ import{rh as r}from"./chunk-w9mdrb90.js";import{Sj as e}from"./chunk-651fyxmn.js";import{$l as t}from"./chunk-7skp0dmg.js";import{mp as l}from"./chunk-tq258v8s.js";import{It as a}from"./chunk-tk6gjy9d.js";import{BN as o}from"./chunk-meaa7wrs.js";var S={PromptAppend:t.define("tui.prompt.append",a.object({text:a.string()})),CommandExecute:t.define("tui.command.execute",a.object({command:a.union([a.enum(["session.list","session.new","session.share","session.interrupt","session.compact","session.page.up","session.page.down","session.line.up","session.line.down","session.half.page.up","session.half.page.down","session.first","session.last","prompt.clear","prompt.submit","agent.cycle"]),a.string()])})),ToastShow:t.define("tui.toast.show",a.object({title:a.string().optional(),message:a.string(),variant:a.enum(["info","success","warning","error"]),duration:a.number().default(5000).optional().describe("Duration in milliseconds")})),SessionSelect:t.define("tui.session.select",a.object({sessionID:e.zod.describe("Session ID to navigate to")})),InstructionsLoaded:r};class m extends o.Class("ConsoleState")({consoleManagedProviders:o.mutable(o.Array(o.String)),activeOrgName:o.optional(o.String),switchableOrgCount:o.Number}){static zod=l(this)}var f=m.make({consoleManagedProviders:[],activeOrgName:void 0,switchableOrgCount:0});
3
3
  export{S as mg,m as ng,f as og};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Os as c,Ps as d,Qs as e,Ss as f,Ts as h,Us as i,Vs as j,Ws as k,Ys as l,Zs as m,mt as n}from"./chunk-v7yvnnmr.js";import{Gt as g,vt as b}from"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import{_t as a}from"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{f as getEnvInfo,a as Wildcard,m as Token,l as Rpc,b as Process,n as Log,k as Lock,j as Locale,i as LocalContext,h as Keybind,g as Filesystem,e as EffectUtil,d as Color,c as Archive};
2
+ import{Os as c,Ps as d,Qs as e,Ss as f,Ts as h,Us as i,Vs as j,Ws as k,Ys as l,Zs as m,mt as n}from"./chunk-esjs9s9g.js";import{Gt as g,vt as b}from"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import{_t as a}from"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{f as getEnvInfo,a as Wildcard,m as Token,l as Rpc,b as Process,n as Log,k as Lock,j as Locale,i as LocalContext,h as Keybind,g as Filesystem,e as EffectUtil,d as Color,c as Archive};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{rd as a,sd as b}from"./chunk-fgqrcjsm.js";import"./chunk-jfy6bfvv.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{a as read,b as copy};
2
+ import{rd as a,sd as b}from"./chunk-hvqgvsa5.js";import"./chunk-jfy6bfvv.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{a as read,b as copy};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{H as I}from"./chunk-jj7wrfty.js";import{I as i,K as r}from"./chunk-43xq4p51.js";import{td as c}from"./chunk-haw1jzwb.js";import{ud as g}from"./chunk-hyr049cr.js";import{vd as y}from"./chunk-y2r3zker.js";import{wd as k}from"./chunk-b54t7ycj.js";import{xd as A}from"./chunk-fd1vbz1f.js";import{Cd as w,Dd as u,Fd as W,Gd as L,Hd as T,Jd as p,Kd as o,Ld as b,Md as P}from"./chunk-9g05wsae.js";import"./chunk-x1dfc7qd.js";import{Od as z}from"./chunk-wmmck56g.js";import{Sf as Y}from"./chunk-ntmn6epc.js";import{qh as M}from"./chunk-1qw3yh13.js";import"./chunk-ckhhm2m8.js";import"./chunk-tp7sfreh.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import{Dj as R,Sk as a,fl as s}from"./chunk-q39h31te.js";import{rl as V}from"./chunk-0x0a51w3.js";import{Pl as n}from"./chunk-7myavy3p.js";import"./chunk-fegrrsfj.js";import"./chunk-c4x99ayd.js";import"./chunk-w0fg8n1f.js";import"./chunk-0pbpzty2.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-jc0wbpjq.js";import"./chunk-jfy6bfvv.js";import"./chunk-aej69zjj.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-k5vwx1nv.js";import"./chunk-ej3gmaba.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import{ct as l}from"./chunk-v7yvnnmr.js";import{vt as d}from"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import{Mt as v}from"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import{$H as O}from"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import{pP as H1}from"./chunk-fa03gsff.js";import f from"path";import{pathToFileURL as J1}from"url";import Q1 from"os";import{access as S1,readdir as X1}from"fs/promises";var q1={en:A,zh:k,ja:c,fr:y,ru:g},B1=q1[I()]??A;function U($,B){let J=B1[$]??A[$]??$;if(!B)return J;return J.replace(/\{(\w+)\}/g,(X,H)=>(H in B)?String(B[H]):`{${H}}`)}import{text as Z1}from"stream/consumers";var D=($,B)=>M.runPromise(O.gen(function*(){yield*(yield*R.Service).set($,B)}));async function t(){let $=await p({message:"Enter your API key",validate:(B)=>B&&B.length>0?void 0:"Required"});if(w($))throw new Y.CancelledError;return $}async function h($,B){let J=$.provider??B;if("refresh"in $){let{type:X,provider:H,refresh:Z,access:j,expires:q,metadata:S,...G}=$;await D(J,{type:"oauth",refresh:Z,access:j,expires:q,...G})}if("key"in $)await D(J,{type:"api",key:$.key,...$.metadata?{metadata:$.metadata}:{}})}async function x($,B,J){let X=0;if(J){let j=$.auth.methods.findIndex((q)=>q.label.toLowerCase()===J.toLowerCase());if(j===-1)W.error(`Unknown method "${J}" for ${B}. Available: ${$.auth.methods.map((q)=>q.label).join(", ")}`),process.exit(1);X=j}else if($.auth.methods.length>1){let j=await b({message:"Login method",options:$.auth.methods.map((q,S)=>({label:q.label,value:S.toString()}))});if(w(j))throw new Y.CancelledError;X=parseInt(j)}let H=$.auth.methods[X];await new Promise((j)=>setTimeout(j,10));let Z={};if(H.prompts)for(let j of H.prompts){if(j.when){let q=Z[j.when.key];if(q===void 0)continue;if(!(j.when.op==="eq"?q===j.when.value:q!==j.when.value))continue}if(j.condition&&!j.condition(Z))continue;if(j.type==="select"){let q=await b({message:j.message,options:j.options});if(w(q))throw new Y.CancelledError;Z[j.key]=q}else{let q=await P({message:j.message,placeholder:j.placeholder,validate:j.validate?(S)=>j.validate(S??""):void 0});if(w(q))throw new Y.CancelledError;Z[j.key]=q}}if(H.type==="oauth"){let j=await H.authorize(Z);if(j.url)W.info("Go to: "+j.url);if(j.method==="auto"){if(j.instructions)W.info(j.instructions);let q=o();q.start("Waiting for authorization...");let S=await j.callback();if(S.type==="failed")q.stop("Failed to authorize",1);if(S.type==="success")await h(S,B),q.stop("Login successful")}if(j.method==="code"){let q=await P({message:"Paste the authorization code here: ",validate:(G)=>G&&G.length>0?void 0:"Required"});if(w(q))throw new Y.CancelledError;let S=await j.callback(q);if(S.type==="failed")W.error("Failed to authorize");if(S.type==="success")await h(S,B),W.success("Login successful")}return T("Done"),!0}if(H.type==="api"){if(H.authorize){let j=await t(),q=await H.authorize(Z);if(q.type==="failed")W.error("Failed to authorize");if(q.type==="success"){let S=q.provider??B;await D(S,{type:"api",key:q.key??j}),W.success("Login successful")}return T("Done"),!0}}return!1}function G1($){let B=new Set,J=[];for(let X of $.hooks){if(!X.auth)continue;let H=X.auth.provider;if(B.has(H))continue;if(B.add(H),Object.hasOwn($.existingProviders,H))continue;if($.disabled.has(H))continue;if($.enabled&&!$.enabled.has(H))continue;J.push({id:H,name:$.providerNames[H]??H})}return J}function m($){let B=$?.loginExtension;if(!B||typeof B!=="object")return;let J=B;if(typeof J.id!=="string"||typeof J.run!=="function")return;return J}async function W1(){try{let J=await import("./chunk-6rak9ez9.js");for(let X of Object.values(J.modules??{})){let H=m(X);if(H)return H}}catch{}let $=f.join(import.meta.dir,"..","..","ext");await S1($).catch(()=>{return});let B=await X1($).catch(()=>[]);for(let J of B.filter((X)=>X.endsWith(".ts")&&!X.endsWith(".d.ts")))try{let X=m(await import(J1(f.join($,J)).href));if(X)return X}catch{}return}var l1=z({command:"providers",aliases:["auth"],describe:"manage AI providers and credentials",builder:($)=>$.command(Y1).command(_1).command(F1).command(K1).demandCommand(),async handler(){}}),Y1=z({command:"list",aliases:["ls"],describe:"list providers and credentials",async handler($){Y.empty();let B=f.join(l.Path.data,"auth.json"),J=Q1.homedir(),X=B===J||B.startsWith(J+f.sep)?"~"+B.slice(J.length):B;L(`Credentials ${Y.Style.TEXT_DIM}${X}`);let H=await M.runPromise(O.gen(function*(){let q=yield*R.Service;return Object.entries(yield*q.all())})),Z=await V.get();for(let[q,S]of H){let G=Z[q]?.name||q;W.info(`${G} ${Y.Style.TEXT_DIM}${S.type}`)}T(`${H.length} credentials`);let j=[];for(let[q,S]of Object.entries(Z))for(let G of S.env)if(process.env[G])j.push({provider:S.name||q,envVar:G});if(j.length>0){Y.empty(),L("Environment");for(let{provider:q,envVar:S}of j)W.info(`${q} ${Y.Style.TEXT_DIM}${S}`);T(`${j.length} environment variable`+(j.length===1?"":"s"))}}}),_1=z({command:"login [url]",describe:"log in to a provider",builder:($)=>$.positional("url",{describe:"qitqode auth provider",type:"string"}).option("provider",{alias:["p"],describe:"provider id or name to log in to (skips provider selection)",type:"string"}).option("method",{alias:["m"],describe:"login method label (skips method selection)",type:"string"}),async handler($){await n.provide({directory:process.cwd(),async fn(){if(Y.empty(),L("Add credential"),$.url){let Q=$.url.replace(/\/+$/,""),_=await fetch(`${Q}/.well-known/opencode`).then((j1)=>j1.json());W.info(`Running \`${_.auth.command.join(" ")}\``);let F=d.spawn(_.auth.command,{stdout:"pipe"});if(!F.stdout){W.error("Failed"),T("Done");return}let[C,N]=await Promise.all([F.exited,Z1(F.stdout)]);if(C!==0){W.error("Failed"),T("Done");return}await D(Q,{type:"wellknown",key:_.auth.env,token:N.trim()}),W.success("Logged into "+Q),T("Done");return}await V.refresh(!0).catch(()=>{});let B=await M.runPromise(s.Service.use((Q)=>Q.get())),J=new Set(B.disabled_providers??[]),X=B.enabled_providers?new Set(B.enabled_providers):void 0,H=await V.get().then((Q)=>{let _={};for(let[F,C]of Object.entries(Q))if((X?X.has(F):!0)&&!J.has(F))_[F]=C;return _}),Z=await M.runPromise(O.gen(function*(){return yield*(yield*a.Service).list()})),j=i,q=G1({hooks:Z,existingProviders:H,disabled:J,enabled:X,providerNames:Object.fromEntries(Object.entries(B.provider??{}).map(([Q,_])=>[Q,_.name]))}),S=[...r(v(H),j,(Q)=>({openai:"ChatGPT Plus/Pro or API key"})[Q.id]),...q.map((Q)=>({label:Q.name,value:Q.id,hint:"plugin"}))],G=await W1(),e=G?[G.id,...G.aliases??[]]:[],K;if(G&&$.provider&&e.includes($.provider)){await G.run();return}else if($.provider){let Q=$.provider,_=S.find((N)=>N.value===Q),F=S.find((N)=>N.label.toLowerCase()===Q.toLowerCase()),C=_??F;if(!C)W.error(`Unknown provider "${Q}"`),process.exit(1);K=C.value}else{let Q=await b({message:U("cli.providers.select"),options:[...G?.menu?[{label:G.menu.label,value:G.id,hint:G.menu.hint}]:[],{label:U("cli.providers.other"),value:"__other__"}]});if(w(Q))throw new Y.CancelledError;if(G&&Q===G.id){await G.run();return}let _=await u({message:U("cli.providers.select"),maxItems:8,options:[...S,{value:"other",label:"Other"}]});if(w(_))throw new Y.CancelledError;K=_}let E=Z.findLast((Q)=>Q.auth?.provider===K);if(E&&E.auth){if(await x({auth:E.auth},K,$.method))return}if(K==="other"){let Q=await P({message:"Enter provider id",validate:(F)=>F&&F.match(/^[0-9a-z-]+$/)?void 0:"a-z, 0-9 and hyphens only"});if(w(Q))throw new Y.CancelledError;K=Q.replace(/^@ai-sdk\//,"");let _=Z.findLast((F)=>F.auth?.provider===K);if(_&&_.auth){if(await x({auth:_.auth},K,$.method))return}W.warn(`This only stores a credential for ${K} - you will need configure it in qitqode.json, check the docs for examples.`)}if(K==="amazon-bedrock")W.info(`Amazon Bedrock authentication priority:
2
+ import{H as I}from"./chunk-jj7wrfty.js";import{I as i,K as r}from"./chunk-43xq4p51.js";import{td as c}from"./chunk-haw1jzwb.js";import{ud as g}from"./chunk-hyr049cr.js";import{vd as y}from"./chunk-y2r3zker.js";import{wd as k}from"./chunk-b54t7ycj.js";import{xd as A}from"./chunk-fd1vbz1f.js";import{Cd as w,Dd as u,Fd as W,Gd as L,Hd as T,Jd as p,Kd as o,Ld as b,Md as P}from"./chunk-9g05wsae.js";import"./chunk-x1dfc7qd.js";import{Od as z}from"./chunk-wmmck56g.js";import{Sf as Y}from"./chunk-ntmn6epc.js";import{qh as M}from"./chunk-88ckmmdr.js";import"./chunk-w9mdrb90.js";import"./chunk-qxtz0tfd.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import{Dj as R,Sk as a,fl as s}from"./chunk-651fyxmn.js";import{rl as V}from"./chunk-0czxqcg7.js";import{Pl as n}from"./chunk-6ba9fc92.js";import"./chunk-7skp0dmg.js";import"./chunk-c4x99ayd.js";import"./chunk-6dznrhs4.js";import"./chunk-8fn883z8.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-th5z0zx7.js";import"./chunk-jfy6bfvv.js";import"./chunk-v0jnnpsz.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-yt6cfsdh.js";import"./chunk-yja3y138.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import{ct as l}from"./chunk-esjs9s9g.js";import{vt as d}from"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import{Mt as v}from"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import{$H as O}from"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import{pP as H1}from"./chunk-fa03gsff.js";import f from"path";import{pathToFileURL as J1}from"url";import Q1 from"os";import{access as S1,readdir as X1}from"fs/promises";var q1={en:A,zh:k,ja:c,fr:y,ru:g},B1=q1[I()]??A;function U($,B){let J=B1[$]??A[$]??$;if(!B)return J;return J.replace(/\{(\w+)\}/g,(X,H)=>(H in B)?String(B[H]):`{${H}}`)}import{text as Z1}from"stream/consumers";var D=($,B)=>M.runPromise(O.gen(function*(){yield*(yield*R.Service).set($,B)}));async function t(){let $=await p({message:"Enter your API key",validate:(B)=>B&&B.length>0?void 0:"Required"});if(w($))throw new Y.CancelledError;return $}async function h($,B){let J=$.provider??B;if("refresh"in $){let{type:X,provider:H,refresh:Z,access:j,expires:q,metadata:S,...G}=$;await D(J,{type:"oauth",refresh:Z,access:j,expires:q,...G})}if("key"in $)await D(J,{type:"api",key:$.key,...$.metadata?{metadata:$.metadata}:{}})}async function x($,B,J){let X=0;if(J){let j=$.auth.methods.findIndex((q)=>q.label.toLowerCase()===J.toLowerCase());if(j===-1)W.error(`Unknown method "${J}" for ${B}. Available: ${$.auth.methods.map((q)=>q.label).join(", ")}`),process.exit(1);X=j}else if($.auth.methods.length>1){let j=await b({message:"Login method",options:$.auth.methods.map((q,S)=>({label:q.label,value:S.toString()}))});if(w(j))throw new Y.CancelledError;X=parseInt(j)}let H=$.auth.methods[X];await new Promise((j)=>setTimeout(j,10));let Z={};if(H.prompts)for(let j of H.prompts){if(j.when){let q=Z[j.when.key];if(q===void 0)continue;if(!(j.when.op==="eq"?q===j.when.value:q!==j.when.value))continue}if(j.condition&&!j.condition(Z))continue;if(j.type==="select"){let q=await b({message:j.message,options:j.options});if(w(q))throw new Y.CancelledError;Z[j.key]=q}else{let q=await P({message:j.message,placeholder:j.placeholder,validate:j.validate?(S)=>j.validate(S??""):void 0});if(w(q))throw new Y.CancelledError;Z[j.key]=q}}if(H.type==="oauth"){let j=await H.authorize(Z);if(j.url)W.info("Go to: "+j.url);if(j.method==="auto"){if(j.instructions)W.info(j.instructions);let q=o();q.start("Waiting for authorization...");let S=await j.callback();if(S.type==="failed")q.stop("Failed to authorize",1);if(S.type==="success")await h(S,B),q.stop("Login successful")}if(j.method==="code"){let q=await P({message:"Paste the authorization code here: ",validate:(G)=>G&&G.length>0?void 0:"Required"});if(w(q))throw new Y.CancelledError;let S=await j.callback(q);if(S.type==="failed")W.error("Failed to authorize");if(S.type==="success")await h(S,B),W.success("Login successful")}return T("Done"),!0}if(H.type==="api"){if(H.authorize){let j=await t(),q=await H.authorize(Z);if(q.type==="failed")W.error("Failed to authorize");if(q.type==="success"){let S=q.provider??B;await D(S,{type:"api",key:q.key??j}),W.success("Login successful")}return T("Done"),!0}}return!1}function G1($){let B=new Set,J=[];for(let X of $.hooks){if(!X.auth)continue;let H=X.auth.provider;if(B.has(H))continue;if(B.add(H),Object.hasOwn($.existingProviders,H))continue;if($.disabled.has(H))continue;if($.enabled&&!$.enabled.has(H))continue;J.push({id:H,name:$.providerNames[H]??H})}return J}function m($){let B=$?.loginExtension;if(!B||typeof B!=="object")return;let J=B;if(typeof J.id!=="string"||typeof J.run!=="function")return;return J}async function W1(){try{let J=await import("./chunk-6rak9ez9.js");for(let X of Object.values(J.modules??{})){let H=m(X);if(H)return H}}catch{}let $=f.join(import.meta.dir,"..","..","ext");await S1($).catch(()=>{return});let B=await X1($).catch(()=>[]);for(let J of B.filter((X)=>X.endsWith(".ts")&&!X.endsWith(".d.ts")))try{let X=m(await import(J1(f.join($,J)).href));if(X)return X}catch{}return}var l1=z({command:"providers",aliases:["auth"],describe:"manage AI providers and credentials",builder:($)=>$.command(Y1).command(_1).command(F1).command(K1).demandCommand(),async handler(){}}),Y1=z({command:"list",aliases:["ls"],describe:"list providers and credentials",async handler($){Y.empty();let B=f.join(l.Path.data,"auth.json"),J=Q1.homedir(),X=B===J||B.startsWith(J+f.sep)?"~"+B.slice(J.length):B;L(`Credentials ${Y.Style.TEXT_DIM}${X}`);let H=await M.runPromise(O.gen(function*(){let q=yield*R.Service;return Object.entries(yield*q.all())})),Z=await V.get();for(let[q,S]of H){let G=Z[q]?.name||q;W.info(`${G} ${Y.Style.TEXT_DIM}${S.type}`)}T(`${H.length} credentials`);let j=[];for(let[q,S]of Object.entries(Z))for(let G of S.env)if(process.env[G])j.push({provider:S.name||q,envVar:G});if(j.length>0){Y.empty(),L("Environment");for(let{provider:q,envVar:S}of j)W.info(`${q} ${Y.Style.TEXT_DIM}${S}`);T(`${j.length} environment variable`+(j.length===1?"":"s"))}}}),_1=z({command:"login [url]",describe:"log in to a provider",builder:($)=>$.positional("url",{describe:"qitqode auth provider",type:"string"}).option("provider",{alias:["p"],describe:"provider id or name to log in to (skips provider selection)",type:"string"}).option("method",{alias:["m"],describe:"login method label (skips method selection)",type:"string"}),async handler($){await n.provide({directory:process.cwd(),async fn(){if(Y.empty(),L("Add credential"),$.url){let Q=$.url.replace(/\/+$/,""),_=await fetch(`${Q}/.well-known/opencode`).then((j1)=>j1.json());W.info(`Running \`${_.auth.command.join(" ")}\``);let F=d.spawn(_.auth.command,{stdout:"pipe"});if(!F.stdout){W.error("Failed"),T("Done");return}let[C,N]=await Promise.all([F.exited,Z1(F.stdout)]);if(C!==0){W.error("Failed"),T("Done");return}await D(Q,{type:"wellknown",key:_.auth.env,token:N.trim()}),W.success("Logged into "+Q),T("Done");return}await V.refresh(!0).catch(()=>{});let B=await M.runPromise(s.Service.use((Q)=>Q.get())),J=new Set(B.disabled_providers??[]),X=B.enabled_providers?new Set(B.enabled_providers):void 0,H=await V.get().then((Q)=>{let _={};for(let[F,C]of Object.entries(Q))if((X?X.has(F):!0)&&!J.has(F))_[F]=C;return _}),Z=await M.runPromise(O.gen(function*(){return yield*(yield*a.Service).list()})),j=i,q=G1({hooks:Z,existingProviders:H,disabled:J,enabled:X,providerNames:Object.fromEntries(Object.entries(B.provider??{}).map(([Q,_])=>[Q,_.name]))}),S=[...r(v(H),j,(Q)=>({openai:"ChatGPT Plus/Pro or API key"})[Q.id]),...q.map((Q)=>({label:Q.name,value:Q.id,hint:"plugin"}))],G=await W1(),e=G?[G.id,...G.aliases??[]]:[],K;if(G&&$.provider&&e.includes($.provider)){await G.run();return}else if($.provider){let Q=$.provider,_=S.find((N)=>N.value===Q),F=S.find((N)=>N.label.toLowerCase()===Q.toLowerCase()),C=_??F;if(!C)W.error(`Unknown provider "${Q}"`),process.exit(1);K=C.value}else{let Q=await b({message:U("cli.providers.select"),options:[...G?.menu?[{label:G.menu.label,value:G.id,hint:G.menu.hint}]:[],{label:U("cli.providers.other"),value:"__other__"}]});if(w(Q))throw new Y.CancelledError;if(G&&Q===G.id){await G.run();return}let _=await u({message:U("cli.providers.select"),maxItems:8,options:[...S,{value:"other",label:"Other"}]});if(w(_))throw new Y.CancelledError;K=_}let E=Z.findLast((Q)=>Q.auth?.provider===K);if(E&&E.auth){if(await x({auth:E.auth},K,$.method))return}if(K==="other"){let Q=await P({message:"Enter provider id",validate:(F)=>F&&F.match(/^[0-9a-z-]+$/)?void 0:"a-z, 0-9 and hyphens only"});if(w(Q))throw new Y.CancelledError;K=Q.replace(/^@ai-sdk\//,"");let _=Z.findLast((F)=>F.auth?.provider===K);if(_&&_.auth){if(await x({auth:_.auth},K,$.method))return}W.warn(`This only stores a credential for ${K} - you will need configure it in qitqode.json, check the docs for examples.`)}if(K==="amazon-bedrock")W.info(`Amazon Bedrock authentication priority:
3
3
  1. Bearer token (AWS_BEARER_TOKEN_BEDROCK or /connect)
4
4
  2. AWS credential chain (profile, access keys, IAM roles, EKS IRSA)
5
5
 
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{sp as a}from"./chunk-aej69zjj.js";import"./chunk-dhvwrrqx.js";import"./chunk-v7yvnnmr.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{a as which};
2
+ import{sp as a}from"./chunk-v0jnnpsz.js";import"./chunk-dhvwrrqx.js";import"./chunk-esjs9s9g.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{a as which};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{h as P,i as g,j as b,k as h,l as O}from"./chunk-f72j5yx8.js";import"./chunk-9g05wsae.js";import"./chunk-x1dfc7qd.js";import{Od as u}from"./chunk-wmmck56g.js";import{Sf as s}from"./chunk-ntmn6epc.js";import{qh as f}from"./chunk-1qw3yh13.js";import"./chunk-ckhhm2m8.js";import{Ah as E}from"./chunk-tp7sfreh.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import{Gj as S,Hj as p}from"./chunk-q39h31te.js";import"./chunk-0x0a51w3.js";import"./chunk-7myavy3p.js";import"./chunk-fegrrsfj.js";import"./chunk-c4x99ayd.js";import"./chunk-w0fg8n1f.js";import"./chunk-0pbpzty2.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-jc0wbpjq.js";import"./chunk-jfy6bfvv.js";import"./chunk-aej69zjj.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-k5vwx1nv.js";import"./chunk-ej3gmaba.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import"./chunk-v7yvnnmr.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import{Jz as I}from"./chunk-01gtn79f.js";import{$H as l,eC as d,vD as D}from"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import"./chunk-fa03gsff.js";var A=(o)=>l.promise(()=>E(o)),m=(o)=>l.sync(()=>s.println(o)),v=(o)=>s.Style.TEXT_DIM+o+s.Style.TEXT_NORMAL,L=(o)=>o?v(" (active)"):"",w=(o,e)=>`${o.email} ${v(o.url)}${L(e)}`,x=(o,e,t)=>`${e.name} (${o.email})${L(t)}`,C=(o,e,t)=>{let n=t?s.Style.TEXT_SUCCESS+"\u25CF"+s.Style.TEXT_NORMAL:" ",c=t?s.Style.TEXT_HIGHLIGHT_BOLD+e.name+s.Style.TEXT_NORMAL:e.name;return` ${n} ${c} ${v(o.email)} ${v(o.url)} ${v(e.id)}`},T=(o,e)=>d.isSome(o)&&o.value.id===e.accountID&&o.value.active_org_id===e.orgID,_=l.fn("login")(function*(o){let e=yield*p.Service;yield*P("Log in");let t=yield*e.login(o);yield*b.info("Go to: "+t.url),yield*b.info("Enter code: "+t.user),yield*A(t.url);let n=O();yield*n.start("Waiting for authorization...");let c=(r)=>l.gen(function*(){yield*l.sleep(r);let i=yield*e.poll(t);if(i._tag==="PollPending")return yield*c(r);if(i._tag==="PollSlow")return yield*c(D.sum(r,D.seconds(5)));return i}),a=yield*c(t.interval).pipe(l.timeout(t.expiry),l.catchTag("TimeoutError",()=>l.succeed(new S)));yield*I.valueTags(a,{PollSuccess:(r)=>l.gen(function*(){yield*n.stop("Logged in as "+r.email),yield*g("Done")}),PollExpired:()=>n.stop("Device code expired",1),PollDenied:()=>n.stop("Authorization denied",1),PollError:(r)=>n.stop("Error: "+String(r.cause),1),PollPending:()=>n.stop("Unexpected state",1),PollSlow:()=>n.stop("Unexpected state",1)})}),N=l.fn("logout")(function*(o){let e=yield*p.Service,t=yield*e.list();if(t.length===0)return yield*m("Not logged in");if(o){let i=t.find((y)=>y.email===o);if(!i)return yield*m("Account not found: "+o);yield*e.remove(i.id),yield*g("Logged out from "+o);return}let n=yield*e.active(),c=d.map(n,(i)=>i.id);yield*P("Log out");let a=t.map((i)=>{let y=d.isSome(c)&&c.value===i.id;return{value:i,label:w(i,y)}}),r=yield*h({message:"Select account to log out",options:a});if(d.isNone(r))return;yield*e.remove(r.value.id),yield*g("Logged out from "+r.value.email)}),$=l.fn("switch")(function*(){let o=yield*p.Service,e=yield*o.orgsByAccount();if(e.length===0)return yield*m("Not logged in");let t=yield*o.active(),n=e.flatMap((r)=>r.orgs.map((i)=>{let y=T(t,{accountID:r.account.id,orgID:i.id});return{value:{orgID:i.id,accountID:r.account.id,label:i.name},label:x(r.account,i,y)}}));if(n.length===0)return yield*m("No orgs found");yield*P("Switch org");let c=yield*h({message:"Select org",options:n});if(d.isNone(c))return;let a=c.value;yield*o.use(a.accountID,d.some(a.orgID)),yield*g("Switched to "+a.label)}),R=l.fn("orgs")(function*(){let o=yield*p.Service,e=yield*o.orgsByAccount();if(e.length===0)return yield*m("No accounts found");if(!e.some((n)=>n.orgs.length>0))return yield*m("No orgs found");let t=yield*o.active();for(let n of e)for(let c of n.orgs){let a=T(t,{accountID:n.account.id,orgID:c.id});yield*m(C(n.account,c,a))}}),M=l.fn("open")(function*(){let e=yield*(yield*p.Service).active();if(d.isNone(e))return yield*m("No active account");let t=e.value.url;yield*A(t),yield*g("Opened "+t)}),X=u({command:"login <url>",describe:!1,builder:(o)=>o.positional("url",{describe:"server URL",type:"string",demandOption:!0}),async handler(o){s.empty(),await f.runPromise(_(o.url))}}),B=u({command:"logout [email]",describe:!1,builder:(o)=>o.positional("email",{describe:"account email to log out from",type:"string"}),async handler(o){s.empty(),await f.runPromise(N(o.email))}}),U=u({command:"switch",describe:!1,async handler(){s.empty(),await f.runPromise($())}}),G=u({command:"orgs",describe:!1,async handler(){s.empty(),await f.runPromise(R())}}),H=u({command:"open",describe:!1,async handler(){s.empty(),await f.runPromise(M())}}),Y=u({command:"console",describe:!1,builder:(o)=>o.command({...X,describe:"log in to console"}).command({...B,describe:"log out from console"}).command({...U,describe:"switch active org"}).command({...G,describe:"list orgs"}).command({...H,describe:"open active console account"}).demandCommand(),async handler(){}});export{C as formatOrgLine,w as formatAccountLabel,U as SwitchCommand,G as OrgsCommand,H as OpenCommand,B as LogoutCommand,X as LoginCommand,Y as ConsoleCommand};
2
+ import{h as P,i as g,j as b,k as h,l as O}from"./chunk-f72j5yx8.js";import"./chunk-9g05wsae.js";import"./chunk-x1dfc7qd.js";import{Od as u}from"./chunk-wmmck56g.js";import{Sf as s}from"./chunk-ntmn6epc.js";import{qh as f}from"./chunk-88ckmmdr.js";import"./chunk-w9mdrb90.js";import{Ah as E}from"./chunk-qxtz0tfd.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import{Gj as S,Hj as p}from"./chunk-651fyxmn.js";import"./chunk-0czxqcg7.js";import"./chunk-6ba9fc92.js";import"./chunk-7skp0dmg.js";import"./chunk-c4x99ayd.js";import"./chunk-6dznrhs4.js";import"./chunk-8fn883z8.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-th5z0zx7.js";import"./chunk-jfy6bfvv.js";import"./chunk-v0jnnpsz.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-yt6cfsdh.js";import"./chunk-yja3y138.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import"./chunk-esjs9s9g.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import{Jz as I}from"./chunk-01gtn79f.js";import{$H as l,eC as d,vD as D}from"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import"./chunk-fa03gsff.js";var A=(o)=>l.promise(()=>E(o)),m=(o)=>l.sync(()=>s.println(o)),v=(o)=>s.Style.TEXT_DIM+o+s.Style.TEXT_NORMAL,L=(o)=>o?v(" (active)"):"",w=(o,e)=>`${o.email} ${v(o.url)}${L(e)}`,x=(o,e,t)=>`${e.name} (${o.email})${L(t)}`,C=(o,e,t)=>{let n=t?s.Style.TEXT_SUCCESS+"\u25CF"+s.Style.TEXT_NORMAL:" ",c=t?s.Style.TEXT_HIGHLIGHT_BOLD+e.name+s.Style.TEXT_NORMAL:e.name;return` ${n} ${c} ${v(o.email)} ${v(o.url)} ${v(e.id)}`},T=(o,e)=>d.isSome(o)&&o.value.id===e.accountID&&o.value.active_org_id===e.orgID,_=l.fn("login")(function*(o){let e=yield*p.Service;yield*P("Log in");let t=yield*e.login(o);yield*b.info("Go to: "+t.url),yield*b.info("Enter code: "+t.user),yield*A(t.url);let n=O();yield*n.start("Waiting for authorization...");let c=(r)=>l.gen(function*(){yield*l.sleep(r);let i=yield*e.poll(t);if(i._tag==="PollPending")return yield*c(r);if(i._tag==="PollSlow")return yield*c(D.sum(r,D.seconds(5)));return i}),a=yield*c(t.interval).pipe(l.timeout(t.expiry),l.catchTag("TimeoutError",()=>l.succeed(new S)));yield*I.valueTags(a,{PollSuccess:(r)=>l.gen(function*(){yield*n.stop("Logged in as "+r.email),yield*g("Done")}),PollExpired:()=>n.stop("Device code expired",1),PollDenied:()=>n.stop("Authorization denied",1),PollError:(r)=>n.stop("Error: "+String(r.cause),1),PollPending:()=>n.stop("Unexpected state",1),PollSlow:()=>n.stop("Unexpected state",1)})}),N=l.fn("logout")(function*(o){let e=yield*p.Service,t=yield*e.list();if(t.length===0)return yield*m("Not logged in");if(o){let i=t.find((y)=>y.email===o);if(!i)return yield*m("Account not found: "+o);yield*e.remove(i.id),yield*g("Logged out from "+o);return}let n=yield*e.active(),c=d.map(n,(i)=>i.id);yield*P("Log out");let a=t.map((i)=>{let y=d.isSome(c)&&c.value===i.id;return{value:i,label:w(i,y)}}),r=yield*h({message:"Select account to log out",options:a});if(d.isNone(r))return;yield*e.remove(r.value.id),yield*g("Logged out from "+r.value.email)}),$=l.fn("switch")(function*(){let o=yield*p.Service,e=yield*o.orgsByAccount();if(e.length===0)return yield*m("Not logged in");let t=yield*o.active(),n=e.flatMap((r)=>r.orgs.map((i)=>{let y=T(t,{accountID:r.account.id,orgID:i.id});return{value:{orgID:i.id,accountID:r.account.id,label:i.name},label:x(r.account,i,y)}}));if(n.length===0)return yield*m("No orgs found");yield*P("Switch org");let c=yield*h({message:"Select org",options:n});if(d.isNone(c))return;let a=c.value;yield*o.use(a.accountID,d.some(a.orgID)),yield*g("Switched to "+a.label)}),R=l.fn("orgs")(function*(){let o=yield*p.Service,e=yield*o.orgsByAccount();if(e.length===0)return yield*m("No accounts found");if(!e.some((n)=>n.orgs.length>0))return yield*m("No orgs found");let t=yield*o.active();for(let n of e)for(let c of n.orgs){let a=T(t,{accountID:n.account.id,orgID:c.id});yield*m(C(n.account,c,a))}}),M=l.fn("open")(function*(){let e=yield*(yield*p.Service).active();if(d.isNone(e))return yield*m("No active account");let t=e.value.url;yield*A(t),yield*g("Opened "+t)}),X=u({command:"login <url>",describe:!1,builder:(o)=>o.positional("url",{describe:"server URL",type:"string",demandOption:!0}),async handler(o){s.empty(),await f.runPromise(_(o.url))}}),B=u({command:"logout [email]",describe:!1,builder:(o)=>o.positional("email",{describe:"account email to log out from",type:"string"}),async handler(o){s.empty(),await f.runPromise(N(o.email))}}),U=u({command:"switch",describe:!1,async handler(){s.empty(),await f.runPromise($())}}),G=u({command:"orgs",describe:!1,async handler(){s.empty(),await f.runPromise(R())}}),H=u({command:"open",describe:!1,async handler(){s.empty(),await f.runPromise(M())}}),Y=u({command:"console",describe:!1,builder:(o)=>o.command({...X,describe:"log in to console"}).command({...B,describe:"log out from console"}).command({...U,describe:"switch active org"}).command({...G,describe:"list orgs"}).command({...H,describe:"open active console account"}).demandCommand(),async handler(){}});export{C as formatOrgLine,w as formatAccountLabel,U as SwitchCommand,G as OrgsCommand,H as OpenCommand,B as LogoutCommand,X as LoginCommand,Y as ConsoleCommand};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{bt as a,ct as b}from"./chunk-v7yvnnmr.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{a as Path,b as Global};
2
+ import{bt as a,ct as b}from"./chunk-esjs9s9g.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{a as Path,b as Global};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Od as q}from"./chunk-wmmck56g.js";import{Sf as v}from"./chunk-ntmn6epc.js";import{qh as S}from"./chunk-1qw3yh13.js";import"./chunk-ckhhm2m8.js";import"./chunk-tp7sfreh.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import"./chunk-q39h31te.js";import"./chunk-0x0a51w3.js";import{Gl as Q,Pl as H}from"./chunk-7myavy3p.js";import"./chunk-fegrrsfj.js";import"./chunk-c4x99ayd.js";import"./chunk-w0fg8n1f.js";import"./chunk-0pbpzty2.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-jc0wbpjq.js";import"./chunk-jfy6bfvv.js";import"./chunk-aej69zjj.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-k5vwx1nv.js";import"./chunk-ej3gmaba.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import"./chunk-v7yvnnmr.js";import{vt as K}from"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import"./chunk-fa03gsff.js";var P=q({command:"pr <number>",describe:"fetch and checkout a GitHub PR branch, then run qitqode",builder:(Y)=>Y.positional("number",{type:"number",describe:"PR number to checkout",demandOption:!0}),async handler(Y){await H.provide({directory:process.cwd(),async fn(){if(H.project.vcs!=="git")v.error("Could not find git repository. Please run this command from a git repository."),process.exit(1);let J=Y.number,Z=`pr/${J}`;if(v.println(`Fetching and checking out PR #${J}...`),(await K.run(["gh","pr","checkout",`${J}`,"--branch",Z,"--force"],{nothrow:!0})).code!==0)v.error(`Failed to checkout PR #${J}. Make sure you have gh CLI installed and authenticated.`),process.exit(1);let _=await K.text(["gh","pr","view",`${J}`,"--json","headRepository,headRepositoryOwner,isCrossRepository,headRefName,body"],{nothrow:!0}),V;if(_.code===0){let j=_.text;if(j.trim()){let z=JSON.parse(j);if(z&&z.isCrossRepository&&z.headRepository&&z.headRepositoryOwner){let L=z.headRepositoryOwner.login,W=z.headRepository.name,C=L;if(!(await S.runPromise(Q.Service.use((F)=>F.run(["remote"],{cwd:H.worktree}))).then((F)=>F.text().trim())).split(`
2
+ import{Od as q}from"./chunk-wmmck56g.js";import{Sf as v}from"./chunk-ntmn6epc.js";import{qh as S}from"./chunk-88ckmmdr.js";import"./chunk-w9mdrb90.js";import"./chunk-qxtz0tfd.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import"./chunk-651fyxmn.js";import"./chunk-0czxqcg7.js";import{Gl as Q,Pl as H}from"./chunk-6ba9fc92.js";import"./chunk-7skp0dmg.js";import"./chunk-c4x99ayd.js";import"./chunk-6dznrhs4.js";import"./chunk-8fn883z8.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-th5z0zx7.js";import"./chunk-jfy6bfvv.js";import"./chunk-v0jnnpsz.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-yt6cfsdh.js";import"./chunk-yja3y138.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import"./chunk-esjs9s9g.js";import{vt as K}from"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import"./chunk-fa03gsff.js";var P=q({command:"pr <number>",describe:"fetch and checkout a GitHub PR branch, then run qitqode",builder:(Y)=>Y.positional("number",{type:"number",describe:"PR number to checkout",demandOption:!0}),async handler(Y){await H.provide({directory:process.cwd(),async fn(){if(H.project.vcs!=="git")v.error("Could not find git repository. Please run this command from a git repository."),process.exit(1);let J=Y.number,Z=`pr/${J}`;if(v.println(`Fetching and checking out PR #${J}...`),(await K.run(["gh","pr","checkout",`${J}`,"--branch",Z,"--force"],{nothrow:!0})).code!==0)v.error(`Failed to checkout PR #${J}. Make sure you have gh CLI installed and authenticated.`),process.exit(1);let _=await K.text(["gh","pr","view",`${J}`,"--json","headRepository,headRepositoryOwner,isCrossRepository,headRefName,body"],{nothrow:!0}),V;if(_.code===0){let j=_.text;if(j.trim()){let z=JSON.parse(j);if(z&&z.isCrossRepository&&z.headRepository&&z.headRepositoryOwner){let L=z.headRepositoryOwner.login,W=z.headRepository.name,C=L;if(!(await S.runPromise(Q.Service.use((F)=>F.run(["remote"],{cwd:H.worktree}))).then((F)=>F.text().trim())).split(`
3
3
  `).includes(C))await S.runPromise(Q.Service.use((F)=>F.run(["remote","add",C,`https://github.com/${L}/${W}.git`],{cwd:H.worktree}))),v.println(`Added fork remote: ${C}`);let X=z.headRefName;await S.runPromise(Q.Service.use((F)=>F.run(["branch",`--set-upstream-to=${C}/${X}`,Z],{cwd:H.worktree})))}if(z&&z.body){let L=z.body.match(/https:\/\/opncd\.ai\/s\/([a-zA-Z0-9_-]+)/);if(L){let W=L[0];v.println(`Found qitqode session: ${W}`),v.println("Importing session...");let C=await K.text(["qitqode","import",W],{nothrow:!0});if(C.code===0){let X=C.text.trim().match(/Imported session: ([a-zA-Z0-9_-]+)/);if(X)V=X[1],v.println(`Session imported: ${V}`)}}}}}v.println(`Successfully checked out PR #${J} as branch '${Z}'`),v.println(),v.println("Starting qitqode..."),v.println();let D=V?["-s",V]:[],$=await K.spawn(["qitqode",...D],{stdin:"inherit",stdout:"inherit",stderr:"inherit",cwd:process.cwd()}).exited;if($!==0)throw Error(`qitqode exited with code ${$}`)}})}});export{P as PrCommand};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ph as a,qh as b}from"./chunk-1qw3yh13.js";import"./chunk-ckhhm2m8.js";import"./chunk-tp7sfreh.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import"./chunk-q39h31te.js";import"./chunk-0x0a51w3.js";import"./chunk-7myavy3p.js";import"./chunk-fegrrsfj.js";import"./chunk-c4x99ayd.js";import"./chunk-w0fg8n1f.js";import"./chunk-0pbpzty2.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-jc0wbpjq.js";import"./chunk-jfy6bfvv.js";import"./chunk-aej69zjj.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-k5vwx1nv.js";import"./chunk-ej3gmaba.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import"./chunk-v7yvnnmr.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import"./chunk-fa03gsff.js";export{b as AppRuntime,a as AppLayer};
2
+ import{ph as a,qh as b}from"./chunk-88ckmmdr.js";import"./chunk-w9mdrb90.js";import"./chunk-qxtz0tfd.js";import"./chunk-q6x5bmc3.js";import"./chunk-n1m5qdf5.js";import"./chunk-zeh3mjgp.js";import"./chunk-prrrw8t8.js";import"./chunk-tz8qhbk9.js";import"./chunk-k19zvbzh.js";import"./chunk-651fyxmn.js";import"./chunk-0czxqcg7.js";import"./chunk-6ba9fc92.js";import"./chunk-7skp0dmg.js";import"./chunk-c4x99ayd.js";import"./chunk-6dznrhs4.js";import"./chunk-8fn883z8.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-th5z0zx7.js";import"./chunk-jfy6bfvv.js";import"./chunk-v0jnnpsz.js";import"./chunk-98nh88th.js";import"./chunk-t7v8wzr9.js";import"./chunk-er5q8nhp.js";import"./chunk-cqtkxwd8.js";import"./chunk-h6htvj2y.js";import"./chunk-2qy62cv4.js";import"./chunk-t2n6fmpy.js";import"./chunk-x1naayst.js";import"./chunk-ng85b73s.js";import"./chunk-351wfvhp.js";import"./chunk-hmm1m733.js";import"./chunk-yt6cfsdh.js";import"./chunk-yja3y138.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import"./chunk-esjs9s9g.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import"./chunk-fa03gsff.js";export{b as AppRuntime,a as AppLayer};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Dl as s,El as t,Fl as u,Hl as v,Il as w}from"./chunk-7myavy3p.js";import"./chunk-fegrrsfj.js";import{Gn as q,Hn as r,Im as a,in as b,jn as c,kn as d,ln as e,mn as f,nn as g,on as h,pn as i,qn as j,rn as k,tn as l,un as m,vn as n,xn as o,zn as p}from"./chunk-c4x99ayd.js";import"./chunk-tq258v8s.js";import"./chunk-jfy6bfvv.js";import"./chunk-aej69zjj.js";import"./chunk-k5vwx1nv.js";import"./chunk-ej3gmaba.js";import"./chunk-3nc9wy1m.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-v7yvnnmr.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{a as sql,e as or,f as not,c as ne,j as lte,i as lt,p as like,l as isNull,m as isNotNull,k as inArray,h as gte,g as gt,n as exists,b as eq,r as desc,t as count,o as between,q as asc,d as and,w as Storage,v as NotFoundError,s as JsonMigration,u as Database};
2
+ import{Dl as s,El as t,Fl as u,Hl as v,Il as w}from"./chunk-6ba9fc92.js";import"./chunk-7skp0dmg.js";import{Gn as q,Hn as r,Im as a,in as b,jn as c,kn as d,ln as e,mn as f,nn as g,on as h,pn as i,qn as j,rn as k,tn as l,un as m,vn as n,xn as o,zn as p}from"./chunk-c4x99ayd.js";import"./chunk-tq258v8s.js";import"./chunk-jfy6bfvv.js";import"./chunk-v0jnnpsz.js";import"./chunk-yt6cfsdh.js";import"./chunk-yja3y138.js";import"./chunk-3nc9wy1m.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-esjs9s9g.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{a as sql,e as or,f as not,c as ne,j as lte,i as lt,p as like,l as isNull,m as isNotNull,k as inArray,h as gte,g as gt,n as exists,b as eq,r as desc,t as count,o as between,q as asc,d as and,w as Storage,v as NotFoundError,s as JsonMigration,u as Database};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ur as a,vr as b,wr as c}from"./chunk-k5vwx1nv.js";import"./chunk-ej3gmaba.js";import"./chunk-3nc9wy1m.js";import"./chunk-v7yvnnmr.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{c as makeRuntime,a as attachWith,b as attach};
2
+ import{ur as a,vr as b,wr as c}from"./chunk-yt6cfsdh.js";import"./chunk-yja3y138.js";import"./chunk-3nc9wy1m.js";import"./chunk-esjs9s9g.js";import"./chunk-b5x3zghc.js";import"./chunk-t1f7jeat.js";import"./chunk-tk6gjy9d.js";import"./chunk-pkdk0ppc.js";import"./chunk-hrnx60em.js";import"./chunk-bbznk59q.js";import"./chunk-01gtn79f.js";import"./chunk-meaa7wrs.js";import"./chunk-fa03gsff.js";export{c as makeRuntime,a as attachWith,b as attach};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ah as _,Ch as y,Eh as h}from"./chunk-tp7sfreh.js";class $ extends Error{cause;constructor(x,J){super(x);this.name="ForgewiseError",this.cause=J}}class K extends ${constructor(x="Device flow is not supported by this issuer."){super(x);this.name="DeviceFlowUnsupportedError"}}var p="https://app.forgewise.tech",a="forgewise-cli";function R(...x){return x.find((J)=>J!==void 0&&J.trim().length>0)}function i(){return!!process.env.REPLIT_DEV_DOMAIN}async function z(){let x=process.env.ACCOUNTS_ISSUER,J=process.env.FORGEWISE_CLIENT_ID;if(x&&J)return{issuer:x.replace(/\/+$/,""),clientId:J};let V;try{V=await y()}catch{V=void 0}let Y=R(x,V?.issuer,p).replace(/\/+$/,""),G=R(J,V?.clientId,a);return{issuer:Y,clientId:G}}function O(x,J,V){if(x>=200&&x<300)return{kind:"success"};let Y=J?.error??"";if(Y==="authorization_pending")return{kind:"wait",intervalMs:V};if(Y==="slow_down")return{kind:"wait",intervalMs:V+5000};if(Y==="access_denied")return{kind:"fatal",message:"Sign-in was denied in the browser."};if(Y==="expired_token")return{kind:"fatal",message:"The sign-in code expired before it was approved. Try again."};return{kind:"fatal",message:`Device sign-in failed: ${J?.error_description||Y||`HTTP ${x}`}`}}import I from"http";var w="/callback",C=[51737,51738],f=new Set;function A(x){return x.replace(/[&<>\"']/g,(J)=>{switch(J){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#39;"}})}function j(x){return`http://127.0.0.1:${x}${w}`}async function l(x){return new Promise((J,V)=>{let Y=I.createServer();Y.listen(x,"127.0.0.1",()=>{Y.close(()=>J(x))}),Y.on("error",V)})}async function F(){for(let x of C){if(f.has(x))continue;f.add(x);try{return await l(x)}catch{f.delete(x)}}throw new $(`Could not bind to any loopback port (tried ${C.join(", ")}). Free one of those ports and retry.`)}function U(x,J,V,Y){return new Promise((G,Z)=>{let W=()=>f.delete(x),Q=I.createServer((q,X)=>{try{let N=new URL(q.url??"/",`http://localhost:${x}`);if(N.pathname!==w){X.writeHead(404),X.end();return}let B=N.searchParams.get("code"),H=N.searchParams.get("state"),m=N.searchParams.get("error"),M=N.searchParams.get("error_description");if(m){let c=`${A(m)}${M?": "+A(M):""}`;X.writeHead(200,{"Content-Type":"text/html"}),X.end(`<html><body style="font-family:sans-serif;padding:2rem"><h2>Authorization failed</h2><p>${c}</p><p>You can close this tab.</p></body></html>`),Q.close(),Z(new $(`Authorization error: ${m}${M?" \u2014 "+M:""}`));return}if(!B||H!==J){X.writeHead(400),X.end("Invalid request");return}X.writeHead(200,{"Content-Type":"text/html"}),X.end('<html><body style="font-family:sans-serif;padding:2rem"><h2>Signed in! You can close this tab.</h2><p>Return to your terminal to continue.</p></body></html>'),Q.close(),G({code:B})}catch(N){Q.close(),Z(N)}});if(V?.aborted){W(),Z(new $("Login cancelled"));return}let D=()=>{W(),Q.close(()=>Z(new $("Login cancelled")))};if(V?.addEventListener("abort",D,{once:!0}),V?.aborted){D();return}Q.listen(x,"127.0.0.1",()=>{W(),Y?.()}),Q.on("error",(q)=>{W(),Z(q)})})}function k(x,J){return new Promise((V,Y)=>{if(J?.aborted){Y(new $("Login cancelled"));return}let G,Z=()=>{clearTimeout(G),J?.removeEventListener("abort",Z),Y(new $("Login cancelled"))};if(G=setTimeout(()=>{J?.removeEventListener("abort",Z),V()},x),J?.addEventListener("abort",Z,{once:!0}),J?.aborted)Z()})}function n(x,J=300000){if(!x)return!1;return Date.now()>=x-J}async function t(x){let{issuer:J}=await z();return h({issuer:J,accessToken:x})}import L from"crypto";var E="openid profile email",P=(x)=>x.toString("base64url");function b(){let x=P(L.randomBytes(32)),J=P(L.createHash("sha256").update(x).digest()),V=P(L.randomBytes(16));return{verifier:x,challenge:J,state:V}}function g(x){let J=new URL(`${x.issuer}/api/oauth/authorize`);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",x.clientId),J.searchParams.set("redirect_uri",x.redirectUri),J.searchParams.set("scope",E),J.searchParams.set("state",x.state),J.searchParams.set("code_challenge",x.challenge),J.searchParams.set("code_challenge_method","S256"),J.toString()}async function S(x,J){let V=await fetch(`${x}/api/oauth/userinfo`,{headers:{Authorization:`Bearer ${J.access_token}`}});if(!V.ok)throw new $(`Failed to fetch user profile (${V.status})`);let Y=await V.json();if(!Y.sub)throw new $("Userinfo response is missing required 'sub' field \u2014 the server returned an invalid user profile.");return{sub:Y.sub,name:Y.name??"",email:Y.email??"",access_token:J.access_token,expires_at:Date.now()+(J.expires_in??3600)*1000,...J.refresh_token?{refresh_token:J.refresh_token}:{}}}async function T(x){let J=await fetch(`${x.issuer}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:x.code,redirect_uri:x.redirectUri,client_id:x.clientId,code_verifier:x.verifier}).toString(),signal:x.signal??null});if(!J.ok){let Y=await J.text().catch(()=>"");throw new $(`Token exchange failed (${J.status}): ${Y}`)}let V=await J.json();return S(x.issuer,V)}async function o(x,J,V=5000){let Y=new AbortController,G=setTimeout(()=>Y.abort(),V);try{let Z=await fetch(`${x}/api/oauth/userinfo`,{headers:{Authorization:`Bearer ${J}`},signal:Y.signal});if(Z.status===401||Z.status===403)return!1;if(!Z.ok)return null;return!0}catch{return null}finally{clearTimeout(G)}}async function s(x){let{issuer:J,clientId:V}=await z(),Y;try{Y=await fetch(`${J}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:V,refresh_token:x}).toString()})}catch(Z){throw new $(`Could not reach the sign-in server to refresh the session: ${Z instanceof Error?Z.message:String(Z)}`,Z)}if(!Y.ok){let Z=await Y.json().catch(()=>{return});if(Z?.error==="invalid_grant")return"invalid_grant";throw new $(`Token refresh failed (${Y.status}): ${Z?.error??""}`)}let G=await Y.json();return S(J,G)}async function v(x){let J;try{J=await fetch(`${x.issuer}/api/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:x.clientId,scope:E}).toString(),signal:x.signal??null})}catch{if(x.signal?.aborted)throw new $("Login cancelled");throw new K}if(J.status===404||J.status===405||J.status===501)throw new K;if(!J.ok){let Y=await J.text().catch(()=>"");throw new $(`Device authorization failed (${J.status}): ${Y}`)}let V;try{V=await J.json()}catch{throw new K}if(!V.device_code||!V.user_code||!V.verification_uri)throw new K;return{deviceCode:V.device_code,info:{userCode:V.user_code,verificationUri:V.verification_uri,verificationUriComplete:V.verification_uri_complete,expiresAt:Date.now()+(V.expires_in??900)*1000},intervalMs:Math.max(1,V.interval??5)*1000}}async function d(x){let J;try{J=await fetch(`${x.issuer}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:x.deviceCode,client_id:x.clientId}).toString(),signal:x.signal??null})}catch{if(x.signal?.aborted)throw new $("Login cancelled");return{kind:"wait",intervalMs:x.currentIntervalMs}}let V;try{V=await J.json()}catch{V=void 0}let Y=O(J.status,V,x.currentIntervalMs);if(Y.kind==="success"){if(!V?.access_token)throw new $("Token endpoint returned success without an access_token.");return{kind:"success",profile:await S(x.issuer,{access_token:V.access_token,expires_in:V.expires_in})}}if(Y.kind==="fatal")throw new $(Y.message);return{kind:"wait",intervalMs:Y.intervalMs}}var r=300000;async function u(){let{issuer:x,clientId:J}=await z(),{verifier:V,challenge:Y,state:G}=b(),Z=await F(),W=j(Z),Q=g({issuer:x,clientId:J,redirectUri:W,challenge:Y,state:G});return{issuer:x,clientId:J,verifier:V,port:Z,redirectUri:W,authorizeStr:Q,state:G}}async function e(x){let{issuer:J,clientId:V}=await z(),{deviceCode:Y,info:G,intervalMs:Z}=await v({issuer:J,clientId:V,signal:x.signal});if(x.onCode(G),x.tryOpen){let Q=G.verificationUriComplete??G.verificationUri;_(Q)}let W=Z;while(Date.now()<G.expiresAt){await k(W,x.signal);let Q=await d({issuer:J,clientId:V,deviceCode:Y,currentIntervalMs:W,signal:x.signal});if(Q.kind==="success")return Q.profile;W=Q.intervalMs}throw new $("The sign-in code expired before it was approved. Try again.")}async function x0(){let{issuer:x,clientId:J,verifier:V,port:Y,redirectUri:G,authorizeStr:Z,state:W}=await u();process.stdout.write(`
2
+ import{Ah as _,Ch as y,Eh as h}from"./chunk-qxtz0tfd.js";class $ extends Error{cause;constructor(x,J){super(x);this.name="ForgewiseError",this.cause=J}}class K extends ${constructor(x="Device flow is not supported by this issuer."){super(x);this.name="DeviceFlowUnsupportedError"}}var p="https://app.forgewise.tech",a="forgewise-cli";function R(...x){return x.find((J)=>J!==void 0&&J.trim().length>0)}function i(){return!!process.env.REPLIT_DEV_DOMAIN}async function z(){let x=process.env.ACCOUNTS_ISSUER,J=process.env.FORGEWISE_CLIENT_ID;if(x&&J)return{issuer:x.replace(/\/+$/,""),clientId:J};let V;try{V=await y()}catch{V=void 0}let Y=R(x,V?.issuer,p).replace(/\/+$/,""),G=R(J,V?.clientId,a);return{issuer:Y,clientId:G}}function O(x,J,V){if(x>=200&&x<300)return{kind:"success"};let Y=J?.error??"";if(Y==="authorization_pending")return{kind:"wait",intervalMs:V};if(Y==="slow_down")return{kind:"wait",intervalMs:V+5000};if(Y==="access_denied")return{kind:"fatal",message:"Sign-in was denied in the browser."};if(Y==="expired_token")return{kind:"fatal",message:"The sign-in code expired before it was approved. Try again."};return{kind:"fatal",message:`Device sign-in failed: ${J?.error_description||Y||`HTTP ${x}`}`}}import I from"http";var w="/callback",C=[51737,51738],f=new Set;function A(x){return x.replace(/[&<>\"']/g,(J)=>{switch(J){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#39;"}})}function j(x){return`http://127.0.0.1:${x}${w}`}async function l(x){return new Promise((J,V)=>{let Y=I.createServer();Y.listen(x,"127.0.0.1",()=>{Y.close(()=>J(x))}),Y.on("error",V)})}async function F(){for(let x of C){if(f.has(x))continue;f.add(x);try{return await l(x)}catch{f.delete(x)}}throw new $(`Could not bind to any loopback port (tried ${C.join(", ")}). Free one of those ports and retry.`)}function U(x,J,V,Y){return new Promise((G,Z)=>{let W=()=>f.delete(x),Q=I.createServer((q,X)=>{try{let N=new URL(q.url??"/",`http://localhost:${x}`);if(N.pathname!==w){X.writeHead(404),X.end();return}let B=N.searchParams.get("code"),H=N.searchParams.get("state"),m=N.searchParams.get("error"),M=N.searchParams.get("error_description");if(m){let c=`${A(m)}${M?": "+A(M):""}`;X.writeHead(200,{"Content-Type":"text/html"}),X.end(`<html><body style="font-family:sans-serif;padding:2rem"><h2>Authorization failed</h2><p>${c}</p><p>You can close this tab.</p></body></html>`),Q.close(),Z(new $(`Authorization error: ${m}${M?" \u2014 "+M:""}`));return}if(!B||H!==J){X.writeHead(400),X.end("Invalid request");return}X.writeHead(200,{"Content-Type":"text/html"}),X.end('<html><body style="font-family:sans-serif;padding:2rem"><h2>Signed in! You can close this tab.</h2><p>Return to your terminal to continue.</p></body></html>'),Q.close(),G({code:B})}catch(N){Q.close(),Z(N)}});if(V?.aborted){W(),Z(new $("Login cancelled"));return}let D=()=>{W(),Q.close(()=>Z(new $("Login cancelled")))};if(V?.addEventListener("abort",D,{once:!0}),V?.aborted){D();return}Q.listen(x,"127.0.0.1",()=>{W(),Y?.()}),Q.on("error",(q)=>{W(),Z(q)})})}function k(x,J){return new Promise((V,Y)=>{if(J?.aborted){Y(new $("Login cancelled"));return}let G,Z=()=>{clearTimeout(G),J?.removeEventListener("abort",Z),Y(new $("Login cancelled"))};if(G=setTimeout(()=>{J?.removeEventListener("abort",Z),V()},x),J?.addEventListener("abort",Z,{once:!0}),J?.aborted)Z()})}function n(x,J=300000){if(!x)return!1;return Date.now()>=x-J}async function t(x){let{issuer:J}=await z();return h({issuer:J,accessToken:x})}import L from"crypto";var E="openid profile email",P=(x)=>x.toString("base64url");function b(){let x=P(L.randomBytes(32)),J=P(L.createHash("sha256").update(x).digest()),V=P(L.randomBytes(16));return{verifier:x,challenge:J,state:V}}function g(x){let J=new URL(`${x.issuer}/api/oauth/authorize`);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",x.clientId),J.searchParams.set("redirect_uri",x.redirectUri),J.searchParams.set("scope",E),J.searchParams.set("state",x.state),J.searchParams.set("code_challenge",x.challenge),J.searchParams.set("code_challenge_method","S256"),J.toString()}async function S(x,J){let V=await fetch(`${x}/api/oauth/userinfo`,{headers:{Authorization:`Bearer ${J.access_token}`}});if(!V.ok)throw new $(`Failed to fetch user profile (${V.status})`);let Y=await V.json();if(!Y.sub)throw new $("Userinfo response is missing required 'sub' field \u2014 the server returned an invalid user profile.");return{sub:Y.sub,name:Y.name??"",email:Y.email??"",access_token:J.access_token,expires_at:Date.now()+(J.expires_in??3600)*1000,...J.refresh_token?{refresh_token:J.refresh_token}:{}}}async function T(x){let J=await fetch(`${x.issuer}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:x.code,redirect_uri:x.redirectUri,client_id:x.clientId,code_verifier:x.verifier}).toString(),signal:x.signal??null});if(!J.ok){let Y=await J.text().catch(()=>"");throw new $(`Token exchange failed (${J.status}): ${Y}`)}let V=await J.json();return S(x.issuer,V)}async function o(x,J,V=5000){let Y=new AbortController,G=setTimeout(()=>Y.abort(),V);try{let Z=await fetch(`${x}/api/oauth/userinfo`,{headers:{Authorization:`Bearer ${J}`},signal:Y.signal});if(Z.status===401||Z.status===403)return!1;if(!Z.ok)return null;return!0}catch{return null}finally{clearTimeout(G)}}async function s(x){let{issuer:J,clientId:V}=await z(),Y;try{Y=await fetch(`${J}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:V,refresh_token:x}).toString()})}catch(Z){throw new $(`Could not reach the sign-in server to refresh the session: ${Z instanceof Error?Z.message:String(Z)}`,Z)}if(!Y.ok){let Z=await Y.json().catch(()=>{return});if(Z?.error==="invalid_grant")return"invalid_grant";throw new $(`Token refresh failed (${Y.status}): ${Z?.error??""}`)}let G=await Y.json();return S(J,G)}async function v(x){let J;try{J=await fetch(`${x.issuer}/api/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:x.clientId,scope:E}).toString(),signal:x.signal??null})}catch{if(x.signal?.aborted)throw new $("Login cancelled");throw new K}if(J.status===404||J.status===405||J.status===501)throw new K;if(!J.ok){let Y=await J.text().catch(()=>"");throw new $(`Device authorization failed (${J.status}): ${Y}`)}let V;try{V=await J.json()}catch{throw new K}if(!V.device_code||!V.user_code||!V.verification_uri)throw new K;return{deviceCode:V.device_code,info:{userCode:V.user_code,verificationUri:V.verification_uri,verificationUriComplete:V.verification_uri_complete,expiresAt:Date.now()+(V.expires_in??900)*1000},intervalMs:Math.max(1,V.interval??5)*1000}}async function d(x){let J;try{J=await fetch(`${x.issuer}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:x.deviceCode,client_id:x.clientId}).toString(),signal:x.signal??null})}catch{if(x.signal?.aborted)throw new $("Login cancelled");return{kind:"wait",intervalMs:x.currentIntervalMs}}let V;try{V=await J.json()}catch{V=void 0}let Y=O(J.status,V,x.currentIntervalMs);if(Y.kind==="success"){if(!V?.access_token)throw new $("Token endpoint returned success without an access_token.");return{kind:"success",profile:await S(x.issuer,{access_token:V.access_token,expires_in:V.expires_in})}}if(Y.kind==="fatal")throw new $(Y.message);return{kind:"wait",intervalMs:Y.intervalMs}}var r=300000;async function u(){let{issuer:x,clientId:J}=await z(),{verifier:V,challenge:Y,state:G}=b(),Z=await F(),W=j(Z),Q=g({issuer:x,clientId:J,redirectUri:W,challenge:Y,state:G});return{issuer:x,clientId:J,verifier:V,port:Z,redirectUri:W,authorizeStr:Q,state:G}}async function e(x){let{issuer:J,clientId:V}=await z(),{deviceCode:Y,info:G,intervalMs:Z}=await v({issuer:J,clientId:V,signal:x.signal});if(x.onCode(G),x.tryOpen){let Q=G.verificationUriComplete??G.verificationUri;_(Q)}let W=Z;while(Date.now()<G.expiresAt){await k(W,x.signal);let Q=await d({issuer:J,clientId:V,deviceCode:Y,currentIntervalMs:W,signal:x.signal});if(Q.kind==="success")return Q.profile;W=Q.intervalMs}throw new $("The sign-in code expired before it was approved. Try again.")}async function x0(){let{issuer:x,clientId:J,verifier:V,port:Y,redirectUri:G,authorizeStr:Z,state:W}=await u();process.stdout.write(`
3
3
  `),process.stdout.write(` Opening Forgewise sign-in in your browser...
4
4
  `),process.stdout.write(" Sign-in URL: "+Z+`
5
5
  `),process.stdout.write(`
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{gt as c,jt as i}from"./chunk-v7yvnnmr.js";import{pt as s}from"./chunk-b5x3zghc.js";function f(u){let n=!1,o=(e,a)=>{if(n)return;n=!0,process.exitCode=1,c.error(e,{error:s(a),process_role:u});let l=setTimeout(()=>process.exit(1),1000);i().finally(()=>{clearTimeout(l),process.exit(1)})},t=(e)=>o("unhandled rejection",e),r=(e)=>o("uncaught exception",e);return process.on("unhandledRejection",t),process.on("uncaughtException",r),()=>{process.off("unhandledRejection",t),process.off("uncaughtException",r)}}
2
+ import{gt as c,jt as i}from"./chunk-esjs9s9g.js";import{pt as s}from"./chunk-b5x3zghc.js";function f(u){let n=!1,o=(e,a)=>{if(n)return;n=!0,process.exitCode=1,c.error(e,{error:s(a),process_role:u});let l=setTimeout(()=>process.exit(1),1000);i().finally(()=>{clearTimeout(l),process.exit(1)})},t=(e)=>o("unhandled rejection",e),r=(e)=>o("uncaught exception",e);return process.on("unhandledRejection",t),process.on("uncaughtException",r),()=>{process.off("unhandledRejection",t),process.off("uncaughtException",r)}}
3
3
  export{f as Cs};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ji as LO,Li as UO}from"./chunk-tz8qhbk9.js";import{np as WO,op as l,pp as e,qp as n}from"./chunk-jc0wbpjq.js";import{$q as D$}from"./chunk-t2n6fmpy.js";import{Fs as VO}from"./chunk-thbjhgw0.js";import{dt as k,mt as DO}from"./chunk-v7yvnnmr.js";import{Ht as fO}from"./chunk-t1f7jeat.js";import{$H as f}from"./chunk-meaa7wrs.js";import{lP as gO,nP as yO}from"./chunk-fa03gsff.js";import{spawn as SO}from"child_process";async function oO(O){if(process.platform==="linux"){if(await new Promise((X)=>{let W=!1,J=(D)=>{if(W)return;W=!0,X(D)};try{let D=SO("xdg-open",[O],{stdio:"ignore",detached:!0});D.once("error",()=>J(!1)),D.once("spawn",()=>{D.unref(),J(!0)})}catch{J(!1)}}))return!0}try{let $=await D$(O);if(!$)return!1;return $.once("error",()=>{}),!0}catch{return!1}}function L$({onRequest:O,onSseError:$,onSseEvent:X,responseTransformer:W,responseValidator:J,sseDefaultRetryDelay:D,sseMaxRetryAttempts:G,sseMaxRetryDelay:Y,sseSleepFn:V,url:z,...I}){let U,S=V??((K)=>new Promise((N)=>setTimeout(N,K)));return{stream:async function*(){let K=D??3000,N=0,_=I.signal??new AbortController().signal;while(!0){if(_.aborted)break;N++;let v=I.headers instanceof Headers?I.headers:new Headers(I.headers);if(U!==void 0)v.set("Last-Event-ID",U);try{let R={redirect:"follow",...I,body:I.serializedBody,headers:v,signal:_},x=new Request(z,R);if(O)x=await O(z,R);let M=await(I.fetch??globalThis.fetch)(x);if(!M.ok)throw Error(`SSE failed: ${M.status} ${M.statusText}`);if(!M.body)throw Error("No body in SSE response");let F=M.body.pipeThrough(new TextDecoderStream).getReader(),w="",G$=()=>{try{F.cancel()}catch{}};_.addEventListener("abort",G$);try{while(!0){let{done:KO,value:BO}=await F.read();if(KO)break;w+=BO,w=w.replace(/\r\n?/g,`
2
+ import{Ji as LO,Li as UO}from"./chunk-tz8qhbk9.js";import{np as WO,op as l,pp as e,qp as n}from"./chunk-th5z0zx7.js";import{$q as D$}from"./chunk-t2n6fmpy.js";import{Fs as VO}from"./chunk-thbjhgw0.js";import{dt as k,mt as DO}from"./chunk-esjs9s9g.js";import{Ht as fO}from"./chunk-t1f7jeat.js";import{$H as f}from"./chunk-meaa7wrs.js";import{lP as gO,nP as yO}from"./chunk-fa03gsff.js";import{spawn as SO}from"child_process";async function oO(O){if(process.platform==="linux"){if(await new Promise((X)=>{let W=!1,J=(D)=>{if(W)return;W=!0,X(D)};try{let D=SO("xdg-open",[O],{stdio:"ignore",detached:!0});D.once("error",()=>J(!1)),D.once("spawn",()=>{D.unref(),J(!0)})}catch{J(!1)}}))return!0}try{let $=await D$(O);if(!$)return!1;return $.once("error",()=>{}),!0}catch{return!1}}function L$({onRequest:O,onSseError:$,onSseEvent:X,responseTransformer:W,responseValidator:J,sseDefaultRetryDelay:D,sseMaxRetryAttempts:G,sseMaxRetryDelay:Y,sseSleepFn:V,url:z,...I}){let U,S=V??((K)=>new Promise((N)=>setTimeout(N,K)));return{stream:async function*(){let K=D??3000,N=0,_=I.signal??new AbortController().signal;while(!0){if(_.aborted)break;N++;let v=I.headers instanceof Headers?I.headers:new Headers(I.headers);if(U!==void 0)v.set("Last-Event-ID",U);try{let R={redirect:"follow",...I,body:I.serializedBody,headers:v,signal:_},x=new Request(z,R);if(O)x=await O(z,R);let M=await(I.fetch??globalThis.fetch)(x);if(!M.ok)throw Error(`SSE failed: ${M.status} ${M.statusText}`);if(!M.body)throw Error("No body in SSE response");let F=M.body.pipeThrough(new TextDecoderStream).getReader(),w="",G$=()=>{try{F.cancel()}catch{}};_.addEventListener("abort",G$);try{while(!0){let{done:KO,value:BO}=await F.read();if(KO)break;w+=BO,w=w.replace(/\r\n?/g,`
3
3
  `);let Y$=w.split(`
4
4
 
5
5
  `);w=Y$.pop()??"";for(let NO of Y$){let MO=NO.split(`