@qitqode/qitqode-android-arm64 0.1.20 → 0.1.22

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-rdsae6k4.js → chunk-04ezvjjf.js} +1 -1
  2. package/bundle/{chunk-wmqcz5rb.js → chunk-07b36w5g.js} +1 -1
  3. package/bundle/{chunk-1qw3yh13.js → chunk-0jv8r99k.js} +3 -3
  4. package/bundle/chunk-0qrpg3n8.js +2 -0
  5. package/bundle/{chunk-6tjghyx6.js → chunk-18xhxdsh.js} +1 -1
  6. package/bundle/{chunk-5549c7mb.js → chunk-1zb95qfx.js} +1 -1
  7. package/bundle/{chunk-knwayz0m.js → chunk-2bbvvh0d.js} +1 -1
  8. package/bundle/{chunk-k5vwx1nv.js → chunk-2bxy8zm1.js} +1 -1
  9. package/bundle/{chunk-b2ky15zx.js → chunk-2epf5806.js} +1 -1
  10. package/bundle/{chunk-aej69zjj.js → chunk-2p6w3w8f.js} +1 -1
  11. package/bundle/{chunk-q39h31te.js → chunk-3f6t3wde.js} +3 -3
  12. package/bundle/{chunk-8k1q3g8s.js → chunk-40vz0fhv.js} +1 -1
  13. package/bundle/{chunk-fegrrsfj.js → chunk-50aznc8e.js} +1 -1
  14. package/bundle/{chunk-dvn528qs.js → chunk-5a80qybt.js} +1 -1
  15. package/bundle/{chunk-r2waj5n2.js → chunk-6hkv9411.js} +1 -1
  16. package/bundle/{chunk-9a5nck3f.js → chunk-6pe3xzkk.js} +1 -1
  17. package/bundle/{chunk-w0fg8n1f.js → chunk-73d0dy03.js} +1 -1
  18. package/bundle/{chunk-b49rxw15.js → chunk-7az1bpy8.js} +1 -1
  19. package/bundle/{chunk-c4mxtqyq.js → chunk-8r4xs1q9.js} +1 -1
  20. package/bundle/{chunk-xb031er5.js → chunk-8x6x3g16.js} +1 -1
  21. package/bundle/{chunk-w8rvjbgr.js → chunk-9ac4h2d9.js} +1 -1
  22. package/bundle/{chunk-3makpbng.js → chunk-a3a9bbk7.js} +1 -1
  23. package/bundle/{chunk-1q2vhe78.js → chunk-anqjy235.js} +1 -1
  24. package/bundle/{chunk-0x0a51w3.js → chunk-b5h8vd5n.js} +1 -1
  25. package/bundle/{chunk-3gdqmave.js → chunk-bn6mg34g.js} +2 -2
  26. package/bundle/{chunk-k728fzrr.js → chunk-btjcs9ee.js} +1 -1
  27. package/bundle/{chunk-p77m937s.js → chunk-c6wrjyep.js} +1 -1
  28. package/bundle/{chunk-pn77fh9b.js → chunk-cckshvkb.js} +1 -1
  29. package/bundle/{chunk-gspdrdyq.js → chunk-dcyzpkww.js} +1 -1
  30. package/bundle/{chunk-k6z419yx.js → chunk-dgsg31vm.js} +1 -1
  31. package/bundle/{chunk-jc0wbpjq.js → chunk-ds162xgb.js} +1 -1
  32. package/bundle/{chunk-hjvje9xj.js → chunk-eb0ksh4x.js} +1 -1
  33. package/bundle/{chunk-4pedvzse.js → chunk-f03yje8k.js} +1 -1
  34. package/bundle/{chunk-anse7bd0.js → chunk-fssgbz70.js} +1 -1
  35. package/bundle/{chunk-mpn5qm9j.js → chunk-fyd31m33.js} +1 -1
  36. package/bundle/{chunk-0fwz5r1k.js → chunk-fydd2nmw.js} +1 -1
  37. package/bundle/{chunk-9g4hz1st.js → chunk-g2bw2qf5.js} +1 -1
  38. package/bundle/{chunk-qq48ffjc.js → chunk-h5wh2d49.js} +1 -1
  39. package/bundle/{chunk-0pbpzty2.js → chunk-ha5qct06.js} +1 -1
  40. package/bundle/{chunk-fgqrcjsm.js → chunk-hf0gny5t.js} +1 -1
  41. package/bundle/{chunk-n0y1ea17.js → chunk-ht1hqsaa.js} +1 -1
  42. package/bundle/{chunk-7myavy3p.js → chunk-jee9y4t0.js} +1 -1
  43. package/bundle/{chunk-tp7sfreh.js → chunk-k6eyc1wv.js} +1 -1
  44. package/bundle/{chunk-p41h8naw.js → chunk-k9m536te.js} +1 -1
  45. package/bundle/{chunk-7nas10jx.js → chunk-kv58j3yk.js} +1 -1
  46. package/bundle/{chunk-dp3hqm2m.js → chunk-mbkw9s6e.js} +1 -1
  47. package/bundle/{chunk-1gj0m10e.js → chunk-msqx5bb0.js} +1 -1
  48. package/bundle/{chunk-s2g5989e.js → chunk-n39gqxkz.js} +1 -1
  49. package/bundle/{chunk-vh8w0ea8.js → chunk-nk42gy65.js} +1 -1
  50. package/bundle/{chunk-v7yvnnmr.js → chunk-p20ft5mj.js} +1 -1
  51. package/bundle/{chunk-ej3gmaba.js → chunk-qq9pvscd.js} +1 -1
  52. package/bundle/{chunk-2w154wad.js → chunk-qwf258sw.js} +1 -1
  53. package/bundle/{chunk-zafrxr1q.js → chunk-qy9s3nmy.js} +1 -1
  54. package/bundle/{chunk-dgbvsnqb.js → chunk-r0zsgad8.js} +1 -1
  55. package/bundle/{chunk-1brsnwhv.js → chunk-r4hkkcj4.js} +1 -1
  56. package/bundle/{chunk-28knamc9.js → chunk-rbrkvj3x.js} +1 -1
  57. package/bundle/{chunk-zfvk6zjj.js → chunk-rhgfyvth.js} +1 -1
  58. package/bundle/{chunk-ysxmk1z1.js → chunk-rpy4rgmm.js} +1 -1
  59. package/bundle/{chunk-skjge2wh.js → chunk-rry321tn.js} +1 -1
  60. package/bundle/{chunk-y36ggefa.js → chunk-t8365msg.js} +1 -1
  61. package/bundle/{chunk-ghmctw8s.js → chunk-tcp31yv0.js} +1 -1
  62. package/bundle/{chunk-ckhhm2m8.js → chunk-th189x63.js} +1 -1
  63. package/bundle/{chunk-3fzgbam3.js → chunk-v07wtbmt.js} +1 -1
  64. package/bundle/{chunk-xbxgrwvy.js → chunk-v6kenrks.js} +1 -1
  65. package/bundle/{chunk-471yj527.js → chunk-vmhq6cyz.js} +1 -1
  66. package/bundle/{chunk-gfm4vad7.js → chunk-vpp88hhd.js} +173 -173
  67. package/bundle/{chunk-6bq7rx7m.js → chunk-vvs87e61.js} +1 -1
  68. package/bundle/chunk-wg0849tq.js +2 -0
  69. package/bundle/{chunk-nt07vncv.js → chunk-x4b0ywbs.js} +1 -1
  70. package/bundle/{chunk-c422awkv.js → chunk-x8w2xgx6.js} +1 -1
  71. package/bundle/{chunk-pskkmca2.js → chunk-xj0ba60b.js} +1 -1
  72. package/bundle/{chunk-rmmrnx95.js → chunk-xjdxyeja.js} +1 -1
  73. package/bundle/{chunk-f57rqsby.js → chunk-xtfcdgwe.js} +1 -1
  74. package/bundle/{chunk-wnjg8mmh.js → chunk-zbvf09bm.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{Fo as E,Go as e,Ho as I}from"./chunk-w0fg8n1f.js";import{Jo as b,Lo as g,Mo as n,Po as i,Qo as x,cp as _0,dp as O0,ep as N,fp as Z0}from"./chunk-0pbpzty2.js";import{mp as p}from"./chunk-tq258v8s.js";import{Gs as y,Is as t,ct as T,dt as X,mt as q}from"./chunk-v7yvnnmr.js";import{Ct as d,Gt as Q,nt as s}from"./chunk-b5x3zghc.js";import{It as w}from"./chunk-tk6gjy9d.js";import{Kt as G,Pt as c}from"./chunk-pkdk0ppc.js";import{$H as B,BN as M,jD as v,oJ as a,yF as L}from"./chunk-meaa7wrs.js";import{nP as F}from"./chunk-fa03gsff.js";var h={};F(h,{waitForDependencies:()=>R0,layer:()=>$0,get:()=>C0,defaultLayer:()=>j0,TuiConfig:()=>h,Service:()=>C,Info:()=>W0});import r from"path";var D={};F(D,{Keybinds:()=>Q0,ConfigKeybinds:()=>D});var _=(O,Z)=>M.String.pipe(M.optional,M.withDecodingDefault(B.succeed(O))).annotate({description:Z}),B0=process.platform==="win32"?"ctrl+z,ctrl+-,super+z":"ctrl+-,super+z",K0=M.Struct({leader:_("ctrl+x","Leader key for keybind combinations"),app_exit:_("ctrl+c,ctrl+d,<leader>q","Exit the application"),editor_open:_("<leader>e","Open external editor"),theme_list:_("<leader>t","List available themes"),sidebar_toggle:_("<leader>b","Toggle sidebar"),scrollbar_toggle:_("none","Toggle session scrollbar"),status_view:_("<leader>s","View status"),session_export:_("<leader>x","Export session to editor"),session_new:_("<leader>n","Create a new session"),session_list:_("<leader>l","List all sessions"),session_timeline:_("<leader>g","Show session timeline"),session_fork:_("none","Fork session from message"),session_rename:_("ctrl+r","Rename session"),session_delete:_("ctrl+d","Delete session"),stash_delete:_("ctrl+d","Delete stash entry"),model_provider_list:_("ctrl+a","Open provider list from model dialog"),model_favorite_toggle:_("ctrl+f","Toggle model favorite status"),session_share:_("none","Share current session"),session_unshare:_("none","Unshare current session"),session_interrupt:_("escape","Interrupt current session"),session_compact:_("<leader>c","Compact the session"),messages_page_up:_("pageup,ctrl+alt+b","Scroll messages up by one page"),messages_page_down:_("pagedown,ctrl+alt+f","Scroll messages down by one page"),messages_line_up:_("ctrl+alt+y","Scroll messages up by one line"),messages_line_down:_("ctrl+alt+e","Scroll messages down by one line"),messages_half_page_up:_("ctrl+alt+u","Scroll messages up by half page"),messages_half_page_down:_("ctrl+alt+d","Scroll messages down by half page"),messages_first:_("ctrl+g,home","Navigate to first message"),messages_last:_("ctrl+alt+g,end","Navigate to last message"),messages_next:_("none","Navigate to next message"),messages_previous:_("none","Navigate to previous message"),messages_last_user:_("none","Navigate to last user message"),messages_copy:_("<leader>y","Copy message"),messages_undo:_("<leader>u","Undo message"),messages_redo:_("<leader>r","Redo message"),messages_toggle_conceal:_("<leader>h","Toggle code block concealment in messages"),tool_details:_("none","Toggle tool details visibility"),model_list:_("<leader>m","List available models"),model_cycle_recent:_("f2","Next recently used model"),model_cycle_recent_reverse:_("shift+f2","Previous recently used model"),model_cycle_favorite:_("none","Next favorite model"),model_cycle_favorite_reverse:_("none","Previous favorite model"),command_list:_("ctrl+p","List available commands"),agent_list:_("<leader>a","List agents"),agent_cycle:_("alt+m","Next agent"),agent_cycle_reverse:_("alt+shift+m","Previous agent"),variant_cycle:_("ctrl+t","Cycle model variants"),variant_list:_("none","List model variants"),input_clear:_("ctrl+c","Clear input field"),input_paste:_("super+v,ctrl+v","Paste from clipboard"),input_submit:_("return","Submit input"),input_newline:_("shift+return,ctrl+return,alt+return,ctrl+j","Insert newline in input"),input_move_left:_("left,ctrl+b","Move cursor left in input"),input_move_right:_("right,ctrl+f","Move cursor right in input"),input_move_up:_("up","Move cursor up in input"),input_move_down:_("down","Move cursor down in input"),input_select_left:_("shift+left","Select left in input"),input_select_right:_("shift+right","Select right in input"),input_select_up:_("shift+up","Select up in input"),input_select_down:_("shift+down","Select down in input"),input_line_home:_("ctrl+a","Move to start of line in input"),input_line_end:_("ctrl+e","Move to end of line in input"),input_select_line_home:_("ctrl+shift+a","Select to start of line in input"),input_select_line_end:_("ctrl+shift+e","Select to end of line in input"),input_visual_line_home:_("alt+a","Move to start of visual line in input"),input_visual_line_end:_("alt+e","Move to end of visual line in input"),input_select_visual_line_home:_("alt+shift+a","Select to start of visual line in input"),input_select_visual_line_end:_("alt+shift+e","Select to end of visual line in input"),input_buffer_home:_("home","Move to start of buffer in input"),input_buffer_end:_("end","Move to end of buffer in input"),input_select_buffer_home:_("shift+home","Select to start of buffer in input"),input_select_buffer_end:_("shift+end","Select to end of buffer in input"),input_delete_line:_("ctrl+shift+d","Delete line in input"),input_delete_to_line_end:_("ctrl+k","Delete to end of line in input"),input_delete_to_line_start:_("ctrl+u","Delete to start of line in input"),input_backspace:_("backspace,shift+backspace","Backspace in input"),input_delete:_("ctrl+d,delete,shift+delete","Delete character in input"),input_undo:_(B0,"Undo in input"),input_redo:_("ctrl+.,super+shift+z","Redo in input"),input_word_forward:_("alt+f,alt+right,ctrl+right","Move word forward in input"),input_word_backward:_("alt+b,alt+left,ctrl+left","Move word backward in input"),input_select_word_forward:_("alt+shift+f,alt+shift+right","Select word forward in input"),input_select_word_backward:_("alt+shift+b,alt+shift+left","Select word backward in input"),input_delete_word_forward:_("alt+d,alt+delete,ctrl+delete","Delete word forward in input"),input_delete_word_backward:_("ctrl+w,ctrl+backspace,alt+backspace","Delete word backward in input"),history_previous:_("up","Previous history item"),history_next:_("down","Next history item"),session_child_first:_("<leader>down","Go to first child session"),session_child_cycle:_("right","Go to next child session"),session_child_cycle_reverse:_("left","Go to previous child session"),session_parent:_("up","Go to parent session"),terminal_suspend:_("ctrl+z","Suspend terminal"),terminal_title_toggle:_("none","Toggle terminal title"),tips_toggle:_("<leader>h","Toggle tips on home screen"),plugin_manager:_("none","Open plugin manager dialog"),display_thinking:_("none","Toggle thinking blocks visibility")}).annotate({identifier:"KeybindsConfig"}),Q0=p(K0);var V0=w.object(Object.fromEntries(Object.keys(D.Keybinds.shape).map((O)=>[O,w.string().optional()]))).strict(),R=w.object({scroll_speed:w.number().min(0.001).optional().describe("TUI scroll speed"),scroll_acceleration:w.object({enabled:w.boolean().describe("Enable scroll acceleration")}).optional().describe("Scroll acceleration settings"),diff_style:w.enum(["auto","stacked"]).optional().describe("Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column"),mouse:w.boolean().optional().describe("Enable or disable mouse capture (default: true)"),accessible:w.boolean().optional().describe("Screen-reader friendly mode: linear main-screen rendering, no mouse capture, reduced motion, no sound (default: false)"),reduce_motion:w.boolean().optional().describe("Disable spinners and other animations, showing static text instead (default: false)"),sound:w.boolean().optional().describe("Enable or disable sound cues (default: true)"),announcements:w.enum(["quiet","normal","verbose"]).optional().describe("Verbosity of accessible-mode screen-reader announcements: 'quiet' announces only turn boundaries, errors, and stops; 'normal' adds tool-start lines; 'verbose' adds tool-completion lines (default: normal). Errors are always announced.")}),P=w.object({$schema:w.string().optional(),theme:w.string().optional(),keybinds:V0.optional(),plugin:I.Spec.zod.array().optional(),plugin_enabled:w.record(w.string(),w.boolean()).optional()}).extend(R.shape).strict();var H=q.create({service:"tui.migrate"}),Y0="https://qitqode.com/tui.json",D0=P.shape.theme.optional(),l=w.record(w.string(),w.unknown()).optional(),H0=w.object({scroll_speed:R.shape.scroll_speed.catch(void 0),scroll_acceleration:R.shape.scroll_acceleration.catch(void 0),diff_style:R.shape.diff_style.catch(void 0)}).strip();async function k(O){let Z=await N0(O);for(let W of Z){let j=await Q.readText(W).catch((o)=>{H.warn("failed to read config for tui migration",{path:W,error:o});return});if(!j)continue;let V=[],K=b(j,V,{allowTrailingComma:!0});if(V.length||!K||typeof K!=="object"||Array.isArray(K))continue;let $=D0.safeParse("theme"in K?K.theme:void 0),J=l.safeParse("keybinds"in K?K.keybinds:void 0),U=l.safeParse("tui"in K?K.tui:void 0),Y={theme:$.success?$.data:void 0,keybinds:J.success?J.data:void 0,tui:U.success?U.data:void 0},m=Y.tui?J0(Y.tui):void 0;if(Y.theme===void 0&&Y.keybinds===void 0&&!m)continue;let A=r.join(r.dirname(W),"tui.json");if(await Q.exists(A))continue;let z={$schema:Y0};if(Y.theme!==void 0)z.theme=Y.theme;if(Y.keybinds!==void 0)z.keybinds=Y.keybinds;if(m)Object.assign(z,m);if(!await Q.write(A,JSON.stringify(z,null,2)).then(()=>!0).catch((o)=>{return H.warn("failed to write tui migration target",{from:W,to:A,error:o}),!1}))continue;if(!await G0(W,j)){H.warn("tui config migrated but source file was not stripped",{from:W,to:A});continue}H.info("migrated tui config",{from:W,to:A})}}function J0(O){let Z=H0.parse(O);if(Z.scroll_speed===void 0&&Z.diff_style===void 0&&Z.scroll_acceleration===void 0)return;return Z}async function G0(O,Z){let W=O+".tui-migration.bak";if(!(await Q.exists(W)?!0:await Q.write(W,Z).then(()=>!0).catch(($)=>{return H.warn("failed to backup source config during tui migration",{path:O,backup:W,error:$}),!1})))return!1;let K=["theme","keybinds","tui"].reduce(($,J)=>{let U=g($,[J],void 0,{formattingOptions:{insertSpaces:!0,tabSize:2}});if(!U.length)return $;return n($,U)},Z);return Q.write(O,K).then(()=>{return H.info("stripped tui keys from server config",{path:O,backup:W}),!0}).catch(($)=>{return H.warn("failed to strip legacy tui keys from server config",{path:O,backup:W,error:$}),!1})}async function N0(O){let Z=[...N(T.Path.config,"qitqode"),...await Q.findUp(["qitqode.json","qitqode.jsonc"],O.cwd,void 0,{rootFirst:!0})];for(let j of G(O.directories))Z.push(...N(j,"qitqode"));if(X.QITQODE_CONFIG)Z.push(X.QITQODE_CONFIG);return(await Promise.all(G(Z).map(async(j)=>{return await Q.exists(j)?j:void 0}))).filter((j)=>!!j)}var f=v.Reference("CurrentWorkingDirectory",{defaultValue:()=>process.cwd()});var u=q.create({service:"tui.config"}),W0=P;class C extends v.Service()("@qitqode/TuiConfig"){}function U0(O,Z){if(Q.contains(Z.directory,O))return"local";return"global"}function A0(O){let Z={...O};if(!("tui"in Z))return Z;if(!s(Z.tui))return delete Z.tui,Z;let W=Z.tui;return delete Z.tui,{...W,...Z}}async function M0(O,Z){if(!O.plugin)return O;for(let W=0;W<O.plugin.length;W++)O.plugin[W]=await I.resolvePluginSpec(O.plugin[W],Z);return O}async function S(O,Z,W){let j=await z0(Z);if(O.result=c(O.result,j),!j.plugin?.length)return;let V=U0(Z,W),K=I.deduplicatePluginOrigins([...O.result.plugin_origins??[],...j.plugin.map(($)=>({spec:$,scope:V,source:Z}))]);O.result.plugin=K.map(($)=>$.spec),O.result.plugin_origins=K}var I0=B.fn("TuiConfig.loadState")(function*(O){let Z=yield*O0(O.directory);yield*B.promise(()=>k({directories:Z,cwd:O.directory}));let W=X.QITQODE_DISABLE_PROJECT_CONFIG?[]:yield*_0("tui",O.directory),j={result:{}};for(let $ of N(T.Path.config,"tui"))yield*B.promise(()=>S(j,$,O)).pipe(B.orDie);if(X.QITQODE_TUI_CONFIG){let $=X.QITQODE_TUI_CONFIG;yield*B.promise(()=>S(j,$,O)).pipe(B.orDie),u.debug("loaded custom tui config",{path:$})}for(let $ of W)yield*B.promise(()=>S(j,$,O)).pipe(B.orDie);let V=G(Z).filter(($)=>$.endsWith(".qitqode")||$===X.QITQODE_CONFIG_DIR);for(let $ of V){if(!$.endsWith(".qitqode")&&$!==X.QITQODE_CONFIG_DIR)continue;for(let J of N($,"tui"))yield*B.promise(()=>S(j,J,O)).pipe(B.orDie)}let K={...j.result.keybinds??{}};if(process.platform==="win32")K.terminal_suspend="none",K.input_undo??=G(["ctrl+z",...D.Keybinds.shape.input_undo.parse(void 0).split(",")]).join(",");return j.result.keybinds=D.Keybinds.parse(K),{config:j.result,dirs:j.result.plugin?.length?V:[]}}),$0=L.effect(C,B.gen(function*(){let O=yield*f,Z=yield*x.Service,W=yield*I0({directory:O}),j=yield*B.forEach(W.dirs,($)=>Z.install($,{add:[{name:"@qitqode/plugin",version:t?void 0:y}]}).pipe(B.forkScoped),{concurrency:"unbounded"}),V=B.fn("TuiConfig.get")(()=>B.succeed(W.config)),K=B.fn("TuiConfig.waitForDependencies")(()=>B.forEach(j,a.join,{concurrency:"unbounded"}).pipe(B.ignore(),B.asVoid));return C.of({get:V,waitForDependencies:K})}).pipe(B.withSpan("TuiConfig.layer"))),j0=$0.pipe(L.provide(x.defaultLayer),L.provide(d.defaultLayer)),{runPromise:w0}=i(C,j0);async function R0(){await w0((O)=>O.waitForDependencies())}async function C0(){return w0((O)=>O.get())}async function z0(O){let Z=await Z0(O);if(!Z)return{};return P0(Z,O).catch((W)=>{return u.warn("failed to load tui config",{path:O,error:W}),{}})}async function P0(O,Z){return e.substitute({text:O,type:"path",path:Z,missing:"empty"}).then((W)=>E.jsonc(W,Z)).then((W)=>{if(!s(W))return{};return E.schema(W0,A0(W),Z)}).then((W)=>M0(W,Z)).catch((W)=>{return u.warn("invalid tui config",{path:Z,error:W}),{}})}
2
+ import{Fo as E,Go as e,Ho as I}from"./chunk-73d0dy03.js";import{Jo as b,Lo as g,Mo as n,Po as i,Qo as x,cp as _0,dp as O0,ep as G,fp as Z0}from"./chunk-ha5qct06.js";import{mp as p}from"./chunk-tq258v8s.js";import{Gs as t,Is as y,ct as T,dt as X,mt as q}from"./chunk-p20ft5mj.js";import{Ct as d,Gt as Q,nt as s}from"./chunk-b5x3zghc.js";import{It as w}from"./chunk-tk6gjy9d.js";import{Kt as A,Pt as c}from"./chunk-pkdk0ppc.js";import{$H as B,BN as M,jD as v,oJ as a,yF as o}from"./chunk-meaa7wrs.js";import{nP as F}from"./chunk-fa03gsff.js";var h={};F(h,{waitForDependencies:()=>R0,layer:()=>$0,get:()=>C0,defaultLayer:()=>j0,TuiConfig:()=>h,Service:()=>C,Info:()=>W0});import r from"path";var D={};F(D,{Keybinds:()=>Q0,ConfigKeybinds:()=>D});var _=(O,Z)=>M.String.pipe(M.optional,M.withDecodingDefault(B.succeed(O))).annotate({description:Z}),B0=process.platform==="win32"?"ctrl+z,ctrl+-,super+z":"ctrl+-,super+z",K0=M.Struct({leader:_("ctrl+x","Leader key for keybind combinations"),app_exit:_("ctrl+c,ctrl+d,<leader>q","Exit the application"),editor_open:_("<leader>e","Open external editor"),theme_list:_("<leader>t","List available themes"),sidebar_toggle:_("<leader>b","Toggle sidebar"),scrollbar_toggle:_("none","Toggle session scrollbar"),status_view:_("<leader>s","View status"),session_export:_("<leader>x","Export session to editor"),session_new:_("<leader>n","Create a new session"),session_list:_("<leader>l","List all sessions"),session_timeline:_("<leader>g","Show session timeline"),session_fork:_("none","Fork session from message"),session_rename:_("ctrl+r","Rename session"),session_delete:_("ctrl+d","Delete session"),stash_delete:_("ctrl+d","Delete stash entry"),model_provider_list:_("ctrl+a","Open provider list from model dialog"),model_favorite_toggle:_("ctrl+f","Toggle model favorite status"),session_share:_("none","Share current session"),session_unshare:_("none","Unshare current session"),session_interrupt:_("escape","Interrupt current session"),session_compact:_("<leader>c","Compact the session"),messages_page_up:_("pageup,ctrl+alt+b","Scroll messages up by one page"),messages_page_down:_("pagedown,ctrl+alt+f","Scroll messages down by one page"),messages_line_up:_("ctrl+alt+y","Scroll messages up by one line"),messages_line_down:_("ctrl+alt+e","Scroll messages down by one line"),messages_half_page_up:_("ctrl+alt+u","Scroll messages up by half page"),messages_half_page_down:_("ctrl+alt+d","Scroll messages down by half page"),messages_first:_("ctrl+g,home","Navigate to first message"),messages_last:_("ctrl+alt+g,end","Navigate to last message"),messages_next:_("none","Navigate to next message"),messages_previous:_("none","Navigate to previous message"),messages_last_user:_("none","Navigate to last user message"),messages_copy:_("<leader>y","Copy message"),messages_undo:_("<leader>u","Undo message"),messages_redo:_("<leader>r","Redo message"),messages_toggle_conceal:_("<leader>h","Toggle code block concealment in messages"),tool_details:_("none","Toggle tool details visibility"),model_list:_("<leader>m","List available models"),model_cycle_recent:_("f2","Next recently used model"),model_cycle_recent_reverse:_("shift+f2","Previous recently used model"),model_cycle_favorite:_("none","Next favorite model"),model_cycle_favorite_reverse:_("none","Previous favorite model"),command_list:_("ctrl+p","List available commands"),agent_list:_("<leader>a","List agents"),agent_cycle:_("alt+m","Next agent"),agent_cycle_reverse:_("alt+shift+m","Previous agent"),variant_cycle:_("ctrl+t","Cycle model variants"),variant_list:_("none","List model variants"),input_clear:_("ctrl+c","Clear input field"),input_paste:_("super+v,ctrl+v","Paste from clipboard"),input_submit:_("return","Submit input"),input_newline:_("shift+return,ctrl+return,alt+return,ctrl+j","Insert newline in input"),input_move_left:_("left,ctrl+b","Move cursor left in input"),input_move_right:_("right,ctrl+f","Move cursor right in input"),input_move_up:_("up","Move cursor up in input"),input_move_down:_("down","Move cursor down in input"),input_select_left:_("shift+left","Select left in input"),input_select_right:_("shift+right","Select right in input"),input_select_up:_("shift+up","Select up in input"),input_select_down:_("shift+down","Select down in input"),input_line_home:_("ctrl+a","Move to start of line in input"),input_line_end:_("ctrl+e","Move to end of line in input"),input_select_line_home:_("ctrl+shift+a","Select to start of line in input"),input_select_line_end:_("ctrl+shift+e","Select to end of line in input"),input_visual_line_home:_("alt+a","Move to start of visual line in input"),input_visual_line_end:_("alt+e","Move to end of visual line in input"),input_select_visual_line_home:_("alt+shift+a","Select to start of visual line in input"),input_select_visual_line_end:_("alt+shift+e","Select to end of visual line in input"),input_buffer_home:_("home","Move to start of buffer in input"),input_buffer_end:_("end","Move to end of buffer in input"),input_select_buffer_home:_("shift+home","Select to start of buffer in input"),input_select_buffer_end:_("shift+end","Select to end of buffer in input"),input_delete_line:_("ctrl+shift+d","Delete line in input"),input_delete_to_line_end:_("ctrl+k","Delete to end of line in input"),input_delete_to_line_start:_("ctrl+u","Delete to start of line in input"),input_backspace:_("backspace,shift+backspace","Backspace in input"),input_delete:_("ctrl+d,delete,shift+delete","Delete character in input"),input_undo:_(B0,"Undo in input"),input_redo:_("ctrl+.,super+shift+z","Redo in input"),input_word_forward:_("alt+f,alt+right,ctrl+right","Move word forward in input"),input_word_backward:_("alt+b,alt+left,ctrl+left","Move word backward in input"),input_select_word_forward:_("alt+shift+f,alt+shift+right","Select word forward in input"),input_select_word_backward:_("alt+shift+b,alt+shift+left","Select word backward in input"),input_delete_word_forward:_("alt+d,alt+delete,ctrl+delete","Delete word forward in input"),input_delete_word_backward:_("ctrl+w,ctrl+backspace,alt+backspace","Delete word backward in input"),history_previous:_("up","Previous history item"),history_next:_("down","Next history item"),session_child_first:_("<leader>down","Go to first child session"),session_child_cycle:_("right","Go to next child session"),session_child_cycle_reverse:_("left","Go to previous child session"),session_parent:_("up","Go to parent session"),terminal_suspend:_("ctrl+z","Suspend terminal"),terminal_title_toggle:_("none","Toggle terminal title"),tips_toggle:_("<leader>h","Toggle tips on home screen"),plugin_manager:_("none","Open plugin manager dialog"),display_thinking:_("none","Toggle thinking blocks visibility")}).annotate({identifier:"KeybindsConfig"}),Q0=p(K0);var V0=w.object(Object.fromEntries(Object.keys(D.Keybinds.shape).map((O)=>[O,w.string().optional()]))).strict(),R=w.object({scroll_speed:w.number().min(0.001).optional().describe("TUI scroll speed"),scroll_acceleration:w.object({enabled:w.boolean().describe("Enable scroll acceleration")}).optional().describe("Scroll acceleration settings"),diff_style:w.enum(["auto","stacked"]).optional().describe("Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column"),mouse:w.boolean().optional().describe("Enable or disable mouse capture (default: true on desktop, false on Android/Termux)"),accessible:w.boolean().optional().describe("Screen-reader friendly mode: linear main-screen rendering, no mouse capture, reduced motion, no sound (default: false)"),reduce_motion:w.boolean().optional().describe("Disable spinners and other animations, showing static text instead (default: false)"),sound:w.boolean().optional().describe("Enable or disable sound cues (default: true)"),announcements:w.enum(["quiet","normal","verbose"]).optional().describe("Verbosity of accessible-mode screen-reader announcements: 'quiet' announces only turn boundaries, errors, and stops; 'normal' adds tool-start lines; 'verbose' adds tool-completion lines (default: normal). Errors are always announced.")}),P=w.object({$schema:w.string().optional(),theme:w.string().optional(),keybinds:V0.optional(),plugin:I.Spec.zod.array().optional(),plugin_enabled:w.record(w.string(),w.boolean()).optional()}).extend(R.shape).strict();var H=q.create({service:"tui.migrate"}),Y0="https://qitqode.com/tui.json",D0=P.shape.theme.optional(),l=w.record(w.string(),w.unknown()).optional(),H0=w.object({scroll_speed:R.shape.scroll_speed.catch(void 0),scroll_acceleration:R.shape.scroll_acceleration.catch(void 0),diff_style:R.shape.diff_style.catch(void 0)}).strip();async function k(O){let Z=await G0(O);for(let W of Z){let j=await Q.readText(W).catch((m)=>{H.warn("failed to read config for tui migration",{path:W,error:m});return});if(!j)continue;let V=[],K=b(j,V,{allowTrailingComma:!0});if(V.length||!K||typeof K!=="object"||Array.isArray(K))continue;let $=D0.safeParse("theme"in K?K.theme:void 0),J=l.safeParse("keybinds"in K?K.keybinds:void 0),N=l.safeParse("tui"in K?K.tui:void 0),Y={theme:$.success?$.data:void 0,keybinds:J.success?J.data:void 0,tui:N.success?N.data:void 0},L=Y.tui?J0(Y.tui):void 0;if(Y.theme===void 0&&Y.keybinds===void 0&&!L)continue;let U=r.join(r.dirname(W),"tui.json");if(await Q.exists(U))continue;let z={$schema:Y0};if(Y.theme!==void 0)z.theme=Y.theme;if(Y.keybinds!==void 0)z.keybinds=Y.keybinds;if(L)Object.assign(z,L);if(!await Q.write(U,JSON.stringify(z,null,2)).then(()=>!0).catch((m)=>{return H.warn("failed to write tui migration target",{from:W,to:U,error:m}),!1}))continue;if(!await A0(W,j)){H.warn("tui config migrated but source file was not stripped",{from:W,to:U});continue}H.info("migrated tui config",{from:W,to:U})}}function J0(O){let Z=H0.parse(O);if(Z.scroll_speed===void 0&&Z.diff_style===void 0&&Z.scroll_acceleration===void 0)return;return Z}async function A0(O,Z){let W=O+".tui-migration.bak";if(!(await Q.exists(W)?!0:await Q.write(W,Z).then(()=>!0).catch(($)=>{return H.warn("failed to backup source config during tui migration",{path:O,backup:W,error:$}),!1})))return!1;let K=["theme","keybinds","tui"].reduce(($,J)=>{let N=g($,[J],void 0,{formattingOptions:{insertSpaces:!0,tabSize:2}});if(!N.length)return $;return n($,N)},Z);return Q.write(O,K).then(()=>{return H.info("stripped tui keys from server config",{path:O,backup:W}),!0}).catch(($)=>{return H.warn("failed to strip legacy tui keys from server config",{path:O,backup:W,error:$}),!1})}async function G0(O){let Z=[...G(T.Path.config,"qitqode"),...await Q.findUp(["qitqode.json","qitqode.jsonc"],O.cwd,void 0,{rootFirst:!0})];for(let j of A(O.directories))Z.push(...G(j,"qitqode"));if(X.QITQODE_CONFIG)Z.push(X.QITQODE_CONFIG);return(await Promise.all(A(Z).map(async(j)=>{return await Q.exists(j)?j:void 0}))).filter((j)=>!!j)}var f=v.Reference("CurrentWorkingDirectory",{defaultValue:()=>process.cwd()});var u=q.create({service:"tui.config"}),W0=P;class C extends v.Service()("@qitqode/TuiConfig"){}function N0(O,Z){if(Q.contains(Z.directory,O))return"local";return"global"}function U0(O){let Z={...O};if(!("tui"in Z))return Z;if(!s(Z.tui))return delete Z.tui,Z;let W=Z.tui;return delete Z.tui,{...W,...Z}}async function M0(O,Z){if(!O.plugin)return O;for(let W=0;W<O.plugin.length;W++)O.plugin[W]=await I.resolvePluginSpec(O.plugin[W],Z);return O}async function S(O,Z,W){let j=await z0(Z);if(O.result=c(O.result,j),!j.plugin?.length)return;let V=N0(Z,W),K=I.deduplicatePluginOrigins([...O.result.plugin_origins??[],...j.plugin.map(($)=>({spec:$,scope:V,source:Z}))]);O.result.plugin=K.map(($)=>$.spec),O.result.plugin_origins=K}var I0=B.fn("TuiConfig.loadState")(function*(O){let Z=yield*O0(O.directory);yield*B.promise(()=>k({directories:Z,cwd:O.directory}));let W=X.QITQODE_DISABLE_PROJECT_CONFIG?[]:yield*_0("tui",O.directory),j={result:{}};for(let $ of G(T.Path.config,"tui"))yield*B.promise(()=>S(j,$,O)).pipe(B.orDie);if(X.QITQODE_TUI_CONFIG){let $=X.QITQODE_TUI_CONFIG;yield*B.promise(()=>S(j,$,O)).pipe(B.orDie),u.debug("loaded custom tui config",{path:$})}for(let $ of W)yield*B.promise(()=>S(j,$,O)).pipe(B.orDie);let V=A(Z).filter(($)=>$.endsWith(".qitqode")||$===X.QITQODE_CONFIG_DIR);for(let $ of V){if(!$.endsWith(".qitqode")&&$!==X.QITQODE_CONFIG_DIR)continue;for(let J of G($,"tui"))yield*B.promise(()=>S(j,J,O)).pipe(B.orDie)}let K={...j.result.keybinds??{}};if(process.platform==="win32")K.terminal_suspend="none",K.input_undo??=A(["ctrl+z",...D.Keybinds.shape.input_undo.parse(void 0).split(",")]).join(",");return j.result.keybinds=D.Keybinds.parse(K),{config:j.result,dirs:j.result.plugin?.length?V:[]}}),$0=o.effect(C,B.gen(function*(){let O=yield*f,Z=yield*x.Service,W=yield*I0({directory:O}),j=yield*B.forEach(W.dirs,($)=>Z.install($,{add:[{name:"@qitqode/plugin",version:y?void 0:t}]}).pipe(B.forkScoped),{concurrency:"unbounded"}),V=B.fn("TuiConfig.get")(()=>B.succeed(W.config)),K=B.fn("TuiConfig.waitForDependencies")(()=>B.forEach(j,a.join,{concurrency:"unbounded"}).pipe(B.ignore(),B.asVoid));return C.of({get:V,waitForDependencies:K})}).pipe(B.withSpan("TuiConfig.layer"))),j0=$0.pipe(o.provide(x.defaultLayer),o.provide(d.defaultLayer)),{runPromise:w0}=i(C,j0);async function R0(){await w0((O)=>O.waitForDependencies())}async function C0(){return w0((O)=>O.get())}async function z0(O){let Z=await Z0(O);if(!Z)return{};return P0(Z,O).catch((W)=>{return u.warn("failed to load tui config",{path:O,error:W}),{}})}async function P0(O,Z){return e.substitute({text:O,type:"path",path:Z,missing:"empty"}).then((W)=>E.jsonc(W,Z)).then((W)=>{if(!s(W))return{};return E.schema(W0,U0(W),Z)}).then((W)=>M0(W,Z)).catch((W)=>{return u.warn("invalid tui config",{path:Z,error:W}),{}})}
3
3
  export{W0 as s,C as t,$0 as u,j0 as v,R0 as w,C0 as x,h as y};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
2
  import{rp as G$}from"./chunk-jfy6bfvv.js";import{At as KZ,rt as eZ,wt as U$,xt as A$,zt as CZ}from"./chunk-b5x3zghc.js";import{Ht as k$}from"./chunk-t1f7jeat.js";import{It as SZ}from"./chunk-tk6gjy9d.js";import{$H as P,$N as r,AG as vZ,AO as v,CO as Y$,DB as rZ,DN as X$,EB as sZ,FI as YZ,GN as d,HE as $$,IN as m,KG as IZ,KO as F$,NG as zZ,NH as p,OE as q$,PA as L,PE as E,PN as DZ,QA as Z$,RE as WZ,SA as ZZ,SE as z$,TN as C,UA as oZ,YC as gZ,cG as $Z,dG as LZ,eG as qZ,eH as xZ,eO as B$,fG as f,fH as V$,hG as jZ,jG as J$,jO as JZ,kG as i,mO as fZ,nG as K$,nO as iZ,qG as o,rF as D$,rO as PZ,sG as l,sO as lZ,wA as a,wF as RZ,wG as h,wO as cZ,xG as Q$,zB as kZ,zG as c,zH as EZ}from"./chunk-meaa7wrs.js";import{lP as u$,nP as BZ,pP as h$}from"./chunk-fa03gsff.js";var pZ={};BZ(pZ,{makeHandle:()=>AZ,make:()=>GZ,ProcessId:()=>UZ,ExitCode:()=>FZ,ChildProcessSpawner:()=>W});var FZ=YZ(),UZ=YZ(),hZ="~effect/ChildProcessSpawner/ChildProcessHandle",j$={[hZ]:hZ,...kZ,toJSON(){return{_id:"ChildProcessHandle",pid:this.pid}}},AZ=(Z)=>Object.assign(Object.create(j$),Z),GZ=(Z)=>{let q=(B,Q)=>Z(B).pipe(h((U)=>fZ(Q?.includeStderr===!0?U.all:U.stdout)),r),z=(B,Q)=>iZ(q(B,Q));return W.of({spawn:Z,exitCode:(B)=>xZ(o(Z(B),(Q)=>Q.exitCode)),streamString:q,streamLines:z,lines:(B,Q)=>lZ(z(B,Q)),string:(B,Q)=>cZ(q(B,Q))})};class W extends gZ()("effect/process/ChildProcessSpawner"){}var x={};BZ(x,{setEnv:()=>HZ,setCwd:()=>yZ,prefix:()=>C$,pipeTo:()=>P$,parseFdName:()=>g,make:()=>k,isStandardCommand:()=>I$,isPipedCommand:()=>E$,isCommand:()=>s,fdName:()=>NZ});var MZ="~effect/unstable/process/ChildProcess",aZ={...rZ,...sZ,[MZ]:MZ,asEffect(){return W.use((Z)=>Z.spawn(this))}},s=(Z)=>oZ(Z,MZ),I$=(Z)=>Z._tag==="StandardCommand",E$=(Z)=>Z._tag==="PipedCommand",I=(Z,q,z)=>Object.assign(Object.create(aZ),{_tag:"StandardCommand",command:Z,args:q,options:z}),e=(Z,q,z={})=>Object.assign(Object.create(aZ),{_tag:"PipedCommand",left:Z,right:q,options:z}),k=function(...q){if(OZ(q[0])){let[U,...A]=q,G=bZ(U,A);return I(G[0]??"",G.slice(1),{})}if(typeof q[0]==="object"&&!Array.isArray(q[0])&&!OZ(q[0])){let U=q[0];return function(A,...G){let b=bZ(A,G);return I(b[0]??"",b.slice(1),U)}}if(typeof q[0]==="string"&&!Array.isArray(q[1])){let[U,A={}]=q;return I(U,[],A)}let[z,B=[],Q={}]=q;return I(z,B,Q)},P$=a((Z)=>s(Z[0])&&s(Z[1]),(Z,q,z)=>e(Z,q,z??{})),C$=function(...q){if(s(q[0])&&q.length>1){let[B,...Q]=q,U=dZ(Q);return _Z(B,U)}let z=dZ(q);return(B)=>_Z(B,z)},dZ=(Z)=>{if(OZ(Z[0])){let[B,...Q]=Z,U=bZ(B,Q);return{command:U[0]??"",args:U.slice(1)}}let[q,z=[]]=Z;return{command:q,args:z}},_Z=(Z,q)=>{switch(Z._tag){case"StandardCommand":return I(q.command,[...q.args,Z.command,...Z.args],Z.options);case"PipedCommand":return e(_Z(Z.left,q),Z.right,Z.options)}},yZ=a(2,(Z,q)=>{switch(Z._tag){case"StandardCommand":return I(Z.command,Z.args,{...Z.options,cwd:q});case"PipedCommand":return e(yZ(Z.left,q),yZ(Z.right,q),Z.options)}}),HZ=a(2,(Z,q)=>{switch(Z._tag){case"StandardCommand":{let z=Z.options.env===void 0?q:{...Z.options.env,...q};return I(Z.command,Z.args,{...Z.options,env:z})}case"PipedCommand":return e(HZ(Z.left,q),HZ(Z.right,q),Z.options)}}),OZ=(Z)=>Array.isArray(Z)&&("raw"in Z)&&Array.isArray(Z.raw),g=(Z)=>{let q=/^fd(\d+)$/.exec(Z);if(q===null)return;let z=parseInt(q[1],10);return z>=3?z:void 0},NZ=(Z)=>`fd${Z}`,bZ=(Z,q)=>{let z=[];for(let[B,Q]of Z.entries())z=S$(Z,q,z,Q,B);return z},S$=(Z,q,z,B,Q)=>{let U=Z.raw[Q];if(U===void 0)throw Error(`Invalid backslash sequence: ${Z.raw[Q]}`);let{hasLeadingWhitespace:A,hasTrailingWhitespace:G,tokens:b}=w$(B,U),N=nZ(z,b,A);if(Q===q.length)return N;let S=q[Q],QZ=Array.isArray(S)?S.map((VZ)=>mZ(VZ)):[mZ(S)];return nZ(N,QZ,G)},mZ=(Z)=>{if(typeof Z==="string")return Z;return String(Z)},tZ=new Set([" ","\t","\r",`
3
3
  `]),T$={x:3,u:5},w$=(Z,q)=>{if(q.length===0)return{tokens:[],hasLeadingWhitespace:!1,hasTrailingWhitespace:!1};let z=tZ.has(q[0]),B=[],Q=0;for(let A=0,G=0;A<Z.length;A+=1,G+=1){let b=q[G];if(tZ.has(b)){if(Q!==A)B.push(Z.slice(Q,A));Q=A+1}else if(b==="\\"){let N=q[G+1];if(N===`
4
- `)A-=1,G+=1;else if(N==="u"&&q[G+2]==="{")G=q.indexOf("}",G+3);else G+=T$[N]??1}}let U=Q===Z.length;if(!U)B.push(Z.slice(Q));return{tokens:B,hasLeadingWhitespace:z,hasTrailingWhitespace:U}},nZ=(Z,q,z)=>z||Z.length===0||q.length===0?[...Z,...q]:[...Z.slice(0,-1),`${Z.at(-1)}${q.at(0)}`,...q.slice(1)];var _$=u$(k$(),1);import*as M$ from"child_process";import{PassThrough as g$}from"stream";var R=(Z)=>Z instanceof globalThis.Error?Z:new globalThis.Error(String(Z)),x$=(Z)=>{switch(Z.code){case"ENOENT":return"NotFound";case"EACCES":return"PermissionDenied";case"EEXIST":return"AlreadyExists";case"EISDIR":return"BadResource";case"ENOTDIR":return"BadResource";case"EBUSY":return"Busy";case"ELOOP":return"BadResource";default:return"Unknown"}},y$=(Z)=>{let q=[],z=[],B=(A)=>{switch(A._tag){case"StandardCommand":q.push(A);return;case"PipedCommand":B(A.left),z.push(A.options),B(A.right);return}};if(B(Z),q.length===0)throw Error("flatten produced empty commands array");let[Q,...U]=q;return{commands:[Q,...U],opts:z}},O=(Z,q,z)=>{let B=y$(z).commands.map((Q)=>`${Q.command} ${Q.args.join(" ")}`).join(" | ");return X$({_tag:x$(q),module:"ChildProcess",method:Z,pathOrDescriptor:B,syscall:q.syscall,cause:q})},f$=J$(function*(){let Z=yield*Y$,q=yield*F$,z=p(function*($){if(L($.cwd))return;return yield*Z.access($.cwd),q.resolve($.cwd)}),B=($)=>$.extendEnv?{...eZ(),...$.env}:$.env,Q=($)=>DZ($)?"pipe":$,U=($)=>d($)?"pipe":$,A=($)=>{let D={stream:"pipe",encoding:"utf-8",endOnDone:!0};if(L($.stdin))return D;if(typeof $.stdin==="string")return{...D,stream:$.stdin};if(DZ($.stdin))return{...D,stream:$.stdin};return{stream:$.stdin.stream,encoding:$.stdin.encoding??D.encoding,endOnDone:$.stdin.endOnDone??D.endOnDone}},G=($,D)=>{let J=$[D];if(L(J))return{stream:"pipe"};if(typeof J==="string")return{stream:J};if(d(J))return{stream:J};return{stream:J.stream}},b=($)=>{if(L($.additionalFds))return[];return Object.entries($.additionalFds).flatMap(([D,J])=>{let K=g(D);return L(K)?[]:[{fd:K,config:J}]}).toSorted((D,J)=>D.fd-J.fd)},N=($,D,J,K)=>{let X=(F)=>process.platform==="win32"&&F==="pipe"?"overlapped":F,Y=[X(Q($.stream)),X(U(D.stream)),X(U(J.stream))];if(K.length===0)return Y;let V=K.reduce((F,_)=>Math.max(F,_.fd),2);for(let F=3;F<=V;F++)Y[F]="ignore";for(let F of K)Y[F.fd]=X("pipe");return Y},S=p(function*($,D,J){if(J.length===0)return{getInputFd:()=>m,getOutputFd:()=>C};let K=new Map,X=new Map;for(let Y of J){let V=D.stdio[Y.fd];switch(Y.config.type){case"input":{let F=m;if(V&&"write"in V)F=CZ.fromWritable({evaluate:()=>V,onError:(_)=>O(`fromWritable(fd${Y.fd})`,R(_),$),endOnDone:!0});if(Y.config.stream)yield*EZ(PZ(Y.config.stream,F));K.set(Y.fd,F);break}case"output":{let F=C;if(V&&"read"in V){let _=new g$;V.on("error",(y)=>_.destroy(R(y))),V.pipe(_),F=KZ.fromReadable({evaluate:()=>_,onError:(y)=>O(`fromReadable(fd${Y.fd})`,R(y),$)})}if(Y.config.sink)F=JZ(F,Y.config.sink);X.set(Y.fd,F);break}}}return{getInputFd:(Y)=>K.get(Y)??m,getOutputFd:(Y)=>X.get(Y)??C}}),QZ=($,D,J)=>LZ(()=>{let K=m;if(ZZ(D.stdin))K=CZ.fromWritable({evaluate:()=>D.stdin,onError:(X)=>O("fromWritable(stdin)",R(X),$),endOnDone:J.endOnDone,encoding:J.encoding});if(DZ(J.stream))return Q$(EZ(PZ(J.stream,K)),K);return $Z(K)}),VZ=($,D,J,K)=>{let X=D.stdout?KZ.fromReadable({evaluate:()=>D.stdout,onError:(V)=>O("fromReadable(stdout)",R(V),$)}):C,Y=D.stderr?KZ.fromReadable({evaluate:()=>D.stderr,onError:(V)=>O("fromReadable(stderr)",R(V),$)}):C;if(d(J.stream))X=JZ(X,J.stream);if(d(K.stream))Y=JZ(Y,K.stream);return{stdout:X,stderr:Y,all:B$(X,Y)}},b$=($,D)=>jZ((J)=>{let K=q$(),X=_$.default($.command,$.args,D),Y=!1,V;return X.on("error",(F)=>{J(i(O("spawn",F,$)))}),X.on("exit",(...F)=>{V=F}),X.on("close",(...F)=>{if(Y)return;Y=!0,z$(K,$$(V??F))}),X.on("spawn",()=>{J($Z([X,K]))}),qZ(()=>{X.kill("SIGTERM")})}),XZ=($,D,J)=>{if(globalThis.process.platform==="win32")return jZ((K)=>{M$.exec(`taskkill /pid ${D.pid} /T /F`,{windowsHide:!0},(X)=>{if(X)return K(i(O("kill",R(X),$)));K(f)})});return K$({try:()=>{globalThis.process.kill(-D.pid,J)},catch:(K)=>O("kill",R(K),$)})},wZ=($,D,J)=>LZ(()=>{if(D.kill(J))return f;return i(O("kill",Error("Failed to kill child process"),$))}),N$=($,D,J)=>(K)=>{let X=J?.killSignal??"SIGTERM";if(L(J?.forceKillAfter))return K(D,$,X);return zZ(K(D,$,X),{duration:J.forceKillAfter,orElse:()=>K(D,$,"SIGKILL")})},W$=($,D)=>{let J=D??"stdout";switch(J){case"stdout":return $.stdout;case"stderr":return $.stderr;case"all":return $.all;default:{let K=g(J);return Z$(K)?$.getOutputFd(K):$.stdout}}},T=p(function*($){switch($._tag){case"StandardCommand":{let D=A($.options),J=G($.options,"stdout"),K=G($.options,"stderr"),X=b($.options),Y=yield*z($.options),[V,F]=yield*V$(b$($,{cwd:Y,env:B($.options),stdio:N(D,J,K,X),detached:$.options.detached??process.platform!=="win32",shell:$.options.shell,windowsHide:process.platform==="win32"}),p(function*([M,H]){let t=yield*WZ(H),n=N$(M,$,$.options);if(t){let[u]=yield*E(H);if(process.platform==="win32")return yield*f;if(u!==0&&ZZ(u))return yield*IZ(n(XZ));return yield*f}let w=(u)=>vZ(XZ($,M,u),()=>wZ($,M,u)),R$=$.options.killSignal??"SIGTERM",uZ=w(R$).pipe(l(E(H)),c),L$=$.options.forceKillAfter?zZ(uZ,{duration:$.options.forceKillAfter,orElse:()=>w("SIGKILL").pipe(l(E(H)),c)}):uZ;return yield*IZ(L$)})),_=yield*S($,V,X),y=VZ($,V,J,K),j=!0;return AZ({pid:UZ(V.pid),stdin:yield*QZ($,V,D),stdout:y.stdout,stderr:y.stderr,all:y.all,getInputFd:_.getInputFd,getOutputFd:_.getOutputFd,isRunning:h(WZ(F),(M)=>!M),exitCode:o(E(F),([M,H])=>{if(ZZ(M))return $Z(FZ(M));return i(O("exitCode",Error(`Process interrupted due to receipt of signal: '${H}'`),$))}),kill:(M)=>{let H=M?.killSignal??"SIGTERM",t=(w)=>vZ(XZ($,V,w),()=>wZ($,V,w)),n=t(H).pipe(l(E(F)),c);if(!M?.forceKillAfter)return n;return zZ(n,{duration:M.forceKillAfter,orElse:()=>t("SIGKILL").pipe(l(E(F)),c)})},unref:qZ(()=>{if(j)V.unref(),j=!1;return qZ(()=>{if(!j)V.ref(),j=!0})})})}case"PipedCommand":{let D=y$($),[J,...K]=D.commands,X=T(J);for(let Y=0;Y<K.length;Y++){let V=K[Y],F=D.opts[Y]??{},_=A(V.options),y=r(h(X,(H)=>W$(H,F.from))),j=F.to??"stdin";if(j==="stdin"){X=T(k(V.command,V.args,{...V.options,stdin:{..._,stream:y}}));continue}let M=g(j);if(L(M)){X=T(k(V.command,V.args,{...V.options,stdin:{..._,stream:y}}));continue}X=T(k(V.command,V.args,{...V.options,additionalFds:{...V.options.additionalFds,[NZ(M)]:{type:"input",stream:y}}}))}return yield*X}}});return GZ(T)}),i$=D$(W,f$),l$=i$.pipe(RZ(U$.layer),RZ(A$)),Bq=G$(async()=>{let{makeRuntime:Z}=await import("./chunk-vh8w0ea8.js");return Z(W,l$)});var H$=(Z,q)=>P.gen(function*(){let z=yield*Z.spawn(q),[B,Q]=yield*P.all([v.mkString(v.decodeText(z.stdout)),v.mkString(v.decodeText(z.stderr))],{concurrency:2});return{code:yield*z.exitCode,text:B,stderr:Q}}).pipe(P.scoped),Mq=H$,_q=(Z,q,z)=>H$(Z,x.make("git",q,{cwd:z?.cwd,extendEnv:!0,stdin:"ignore"}));var TZ={};BZ(TZ,{payloads:()=>p$,define:()=>c$,BusEvent:()=>TZ});var O$=new Map;function c$(Z,q){let z={type:Z,properties:q};return O$.set(Z,z),z}function p$(){return O$.entries().map(([Z,q])=>{return SZ.object({type:SZ.literal(Z),properties:q.properties}).meta({ref:`Event.${q.type}`})}).toArray()}
4
+ `)A-=1,G+=1;else if(N==="u"&&q[G+2]==="{")G=q.indexOf("}",G+3);else G+=T$[N]??1}}let U=Q===Z.length;if(!U)B.push(Z.slice(Q));return{tokens:B,hasLeadingWhitespace:z,hasTrailingWhitespace:U}},nZ=(Z,q,z)=>z||Z.length===0||q.length===0?[...Z,...q]:[...Z.slice(0,-1),`${Z.at(-1)}${q.at(0)}`,...q.slice(1)];var _$=u$(k$(),1);import*as M$ from"child_process";import{PassThrough as g$}from"stream";var R=(Z)=>Z instanceof globalThis.Error?Z:new globalThis.Error(String(Z)),x$=(Z)=>{switch(Z.code){case"ENOENT":return"NotFound";case"EACCES":return"PermissionDenied";case"EEXIST":return"AlreadyExists";case"EISDIR":return"BadResource";case"ENOTDIR":return"BadResource";case"EBUSY":return"Busy";case"ELOOP":return"BadResource";default:return"Unknown"}},y$=(Z)=>{let q=[],z=[],B=(A)=>{switch(A._tag){case"StandardCommand":q.push(A);return;case"PipedCommand":B(A.left),z.push(A.options),B(A.right);return}};if(B(Z),q.length===0)throw Error("flatten produced empty commands array");let[Q,...U]=q;return{commands:[Q,...U],opts:z}},O=(Z,q,z)=>{let B=y$(z).commands.map((Q)=>`${Q.command} ${Q.args.join(" ")}`).join(" | ");return X$({_tag:x$(q),module:"ChildProcess",method:Z,pathOrDescriptor:B,syscall:q.syscall,cause:q})},f$=J$(function*(){let Z=yield*Y$,q=yield*F$,z=p(function*($){if(L($.cwd))return;return yield*Z.access($.cwd),q.resolve($.cwd)}),B=($)=>$.extendEnv?{...eZ(),...$.env}:$.env,Q=($)=>DZ($)?"pipe":$,U=($)=>d($)?"pipe":$,A=($)=>{let D={stream:"pipe",encoding:"utf-8",endOnDone:!0};if(L($.stdin))return D;if(typeof $.stdin==="string")return{...D,stream:$.stdin};if(DZ($.stdin))return{...D,stream:$.stdin};return{stream:$.stdin.stream,encoding:$.stdin.encoding??D.encoding,endOnDone:$.stdin.endOnDone??D.endOnDone}},G=($,D)=>{let J=$[D];if(L(J))return{stream:"pipe"};if(typeof J==="string")return{stream:J};if(d(J))return{stream:J};return{stream:J.stream}},b=($)=>{if(L($.additionalFds))return[];return Object.entries($.additionalFds).flatMap(([D,J])=>{let K=g(D);return L(K)?[]:[{fd:K,config:J}]}).toSorted((D,J)=>D.fd-J.fd)},N=($,D,J,K)=>{let X=(F)=>process.platform==="win32"&&F==="pipe"?"overlapped":F,Y=[X(Q($.stream)),X(U(D.stream)),X(U(J.stream))];if(K.length===0)return Y;let V=K.reduce((F,_)=>Math.max(F,_.fd),2);for(let F=3;F<=V;F++)Y[F]="ignore";for(let F of K)Y[F.fd]=X("pipe");return Y},S=p(function*($,D,J){if(J.length===0)return{getInputFd:()=>m,getOutputFd:()=>C};let K=new Map,X=new Map;for(let Y of J){let V=D.stdio[Y.fd];switch(Y.config.type){case"input":{let F=m;if(V&&"write"in V)F=CZ.fromWritable({evaluate:()=>V,onError:(_)=>O(`fromWritable(fd${Y.fd})`,R(_),$),endOnDone:!0});if(Y.config.stream)yield*EZ(PZ(Y.config.stream,F));K.set(Y.fd,F);break}case"output":{let F=C;if(V&&"read"in V){let _=new g$;V.on("error",(y)=>_.destroy(R(y))),V.pipe(_),F=KZ.fromReadable({evaluate:()=>_,onError:(y)=>O(`fromReadable(fd${Y.fd})`,R(y),$)})}if(Y.config.sink)F=JZ(F,Y.config.sink);X.set(Y.fd,F);break}}}return{getInputFd:(Y)=>K.get(Y)??m,getOutputFd:(Y)=>X.get(Y)??C}}),QZ=($,D,J)=>LZ(()=>{let K=m;if(ZZ(D.stdin))K=CZ.fromWritable({evaluate:()=>D.stdin,onError:(X)=>O("fromWritable(stdin)",R(X),$),endOnDone:J.endOnDone,encoding:J.encoding});if(DZ(J.stream))return Q$(EZ(PZ(J.stream,K)),K);return $Z(K)}),VZ=($,D,J,K)=>{let X=D.stdout?KZ.fromReadable({evaluate:()=>D.stdout,onError:(V)=>O("fromReadable(stdout)",R(V),$)}):C,Y=D.stderr?KZ.fromReadable({evaluate:()=>D.stderr,onError:(V)=>O("fromReadable(stderr)",R(V),$)}):C;if(d(J.stream))X=JZ(X,J.stream);if(d(K.stream))Y=JZ(Y,K.stream);return{stdout:X,stderr:Y,all:B$(X,Y)}},b$=($,D)=>jZ((J)=>{let K=q$(),X=_$.default($.command,$.args,D),Y=!1,V;return X.on("error",(F)=>{J(i(O("spawn",F,$)))}),X.on("exit",(...F)=>{V=F}),X.on("close",(...F)=>{if(Y)return;Y=!0,z$(K,$$(V??F))}),X.on("spawn",()=>{J($Z([X,K]))}),qZ(()=>{X.kill("SIGTERM")})}),XZ=($,D,J)=>{if(globalThis.process.platform==="win32")return jZ((K)=>{M$.exec(`taskkill /pid ${D.pid} /T /F`,{windowsHide:!0},(X)=>{if(X)return K(i(O("kill",R(X),$)));K(f)})});return K$({try:()=>{globalThis.process.kill(-D.pid,J)},catch:(K)=>O("kill",R(K),$)})},wZ=($,D,J)=>LZ(()=>{if(D.kill(J))return f;return i(O("kill",Error("Failed to kill child process"),$))}),N$=($,D,J)=>(K)=>{let X=J?.killSignal??"SIGTERM";if(L(J?.forceKillAfter))return K(D,$,X);return zZ(K(D,$,X),{duration:J.forceKillAfter,orElse:()=>K(D,$,"SIGKILL")})},W$=($,D)=>{let J=D??"stdout";switch(J){case"stdout":return $.stdout;case"stderr":return $.stderr;case"all":return $.all;default:{let K=g(J);return Z$(K)?$.getOutputFd(K):$.stdout}}},T=p(function*($){switch($._tag){case"StandardCommand":{let D=A($.options),J=G($.options,"stdout"),K=G($.options,"stderr"),X=b($.options),Y=yield*z($.options),[V,F]=yield*V$(b$($,{cwd:Y,env:B($.options),stdio:N(D,J,K,X),detached:$.options.detached??process.platform!=="win32",shell:$.options.shell,windowsHide:process.platform==="win32"}),p(function*([M,H]){let t=yield*WZ(H),n=N$(M,$,$.options);if(t){let[u]=yield*E(H);if(process.platform==="win32")return yield*f;if(u!==0&&ZZ(u))return yield*IZ(n(XZ));return yield*f}let w=(u)=>vZ(XZ($,M,u),()=>wZ($,M,u)),R$=$.options.killSignal??"SIGTERM",uZ=w(R$).pipe(l(E(H)),c),L$=$.options.forceKillAfter?zZ(uZ,{duration:$.options.forceKillAfter,orElse:()=>w("SIGKILL").pipe(l(E(H)),c)}):uZ;return yield*IZ(L$)})),_=yield*S($,V,X),y=VZ($,V,J,K),j=!0;return AZ({pid:UZ(V.pid),stdin:yield*QZ($,V,D),stdout:y.stdout,stderr:y.stderr,all:y.all,getInputFd:_.getInputFd,getOutputFd:_.getOutputFd,isRunning:h(WZ(F),(M)=>!M),exitCode:o(E(F),([M,H])=>{if(ZZ(M))return $Z(FZ(M));return i(O("exitCode",Error(`Process interrupted due to receipt of signal: '${H}'`),$))}),kill:(M)=>{let H=M?.killSignal??"SIGTERM",t=(w)=>vZ(XZ($,V,w),()=>wZ($,V,w)),n=t(H).pipe(l(E(F)),c);if(!M?.forceKillAfter)return n;return zZ(n,{duration:M.forceKillAfter,orElse:()=>t("SIGKILL").pipe(l(E(F)),c)})},unref:qZ(()=>{if(j)V.unref(),j=!1;return qZ(()=>{if(!j)V.ref(),j=!0})})})}case"PipedCommand":{let D=y$($),[J,...K]=D.commands,X=T(J);for(let Y=0;Y<K.length;Y++){let V=K[Y],F=D.opts[Y]??{},_=A(V.options),y=r(h(X,(H)=>W$(H,F.from))),j=F.to??"stdin";if(j==="stdin"){X=T(k(V.command,V.args,{...V.options,stdin:{..._,stream:y}}));continue}let M=g(j);if(L(M)){X=T(k(V.command,V.args,{...V.options,stdin:{..._,stream:y}}));continue}X=T(k(V.command,V.args,{...V.options,additionalFds:{...V.options.additionalFds,[NZ(M)]:{type:"input",stream:y}}}))}return yield*X}}});return GZ(T)}),i$=D$(W,f$),l$=i$.pipe(RZ(U$.layer),RZ(A$)),Bq=G$(async()=>{let{makeRuntime:Z}=await import("./chunk-nk42gy65.js");return Z(W,l$)});var H$=(Z,q)=>P.gen(function*(){let z=yield*Z.spawn(q),[B,Q]=yield*P.all([v.mkString(v.decodeText(z.stdout)),v.mkString(v.decodeText(z.stderr))],{concurrency:2});return{code:yield*z.exitCode,text:B,stderr:Q}}).pipe(P.scoped),Mq=H$,_q=(Z,q,z)=>H$(Z,x.make("git",q,{cwd:z?.cwd,extendEnv:!0,stdin:"ignore"}));var TZ={};BZ(TZ,{payloads:()=>p$,define:()=>c$,BusEvent:()=>TZ});var O$=new Map;function c$(Z,q){let z={type:Z,properties:q};return O$.set(Z,z),z}function p$(){return O$.entries().map(([Z,q])=>{return SZ.object({type:SZ.literal(Z),properties:q.properties}).meta({ref:`Event.${q.type}`})}).toArray()}
5
5
  export{W as Ul,pZ as Vl,x as Wl,l$ as Xl,H$ as Yl,Mq as Zl,_q as _l,TZ as $l};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Bd as s}from"./chunk-wmqcz5rb.js";import{Od as r}from"./chunk-wmmck56g.js";import{Ig as u,Jg as g,Sg as q,fh as z,gh as B,qh as i}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{Ik as f,Tj as G,Uj as V,Vk as x,Xj as S,dk as $,el as K,fl as J}from"./chunk-q39h31te.js";import"./chunk-0x0a51w3.js";import{Nl as R,Pl as p}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 U,mt as w}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{$H as c,AO as A}from"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import{qP as v,rP as P}from"./chunk-fa03gsff.js";import{EOL as X}from"os";var k=r({command:"config",describe:"show resolved configuration",builder:(e)=>e,async handler(){await s(process.cwd(),async()=>{let e=await i.runPromise(J.Service.use((o)=>o.get()));process.stdout.write(JSON.stringify(e,null,2)+X)})}});import{EOL as y}from"os";var Y=r({command:"search <query>",describe:"search files by query",builder:(e)=>e.positional("query",{type:"string",demandOption:!0,description:"Search query"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(g.Service.use((t)=>t.search({query:e.query})));process.stdout.write(o.join(y)+y)})}}),Z=r({command:"read <path>",describe:"read file contents as JSON",builder:(e)=>e.positional("path",{type:"string",demandOption:!0,description:"File path to read"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(g.Service.use((t)=>t.read(e.path)));process.stdout.write(JSON.stringify(o,null,2)+y)})}}),H=r({command:"status",describe:"show file status information",builder:(e)=>e,async handler(){await s(process.cwd(),async()=>{let e=await i.runPromise(g.Service.use((o)=>o.status()));process.stdout.write(JSON.stringify(e,null,2)+y)})}}),ee=r({command:"list <path>",describe:"list files in a directory",builder:(e)=>e.positional("path",{type:"string",demandOption:!0,description:"File path to list"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(g.Service.use((t)=>t.list(e.path)));process.stdout.write(JSON.stringify(o,null,2)+y)})}}),oe=r({command:"tree [dir]",describe:"show directory tree",builder:(e)=>e.positional("dir",{type:"string",description:"Directory to tree",default:process.cwd()}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(u.Service.use((t)=>t.tree({cwd:e.dir,limit:200})));console.log(JSON.stringify(o,null,2))})}}),L=r({command:"file",describe:"file system debugging utilities",builder:(e)=>e.command(Z).command(H).command(ee).command(Y).command(oe).demandCommand(),async handler(){}});import{EOL as D}from"os";var E=r({command:"lsp",describe:"LSP debugging utilities",builder:(e)=>e.command(te).command(re).command(ie).demandCommand(),async handler(){}}),te=r({command:"diagnostics <file>",describe:"get diagnostics for a file",builder:(e)=>e.positional("file",{type:"string",demandOption:!0}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(S.Service.use((t)=>c.gen(function*(){return yield*t.touchFile(e.file,!0),yield*c.sleep(1000),yield*t.diagnostics()})));process.stdout.write(JSON.stringify(o,null,2)+D)})}}),re=r({command:"symbols <query>",describe:"search workspace symbols",builder:(e)=>e.positional("query",{type:"string",demandOption:!0}),async handler(e){await s(process.cwd(),async()=>{let n=[];try{const o=v(n,w.Default.time("symbols"),0);let t=await i.runPromise(S.Service.use((d)=>d.workspaceSymbol(e.query)));process.stdout.write(JSON.stringify(t,null,2)+D)}catch(a){var m=a,l=1}finally{P(n,m,l)}})}}),ie=r({command:"document-symbols <uri>",describe:"get symbols from a document",builder:(e)=>e.positional("uri",{type:"string",demandOption:!0}),async handler(e){await s(process.cwd(),async()=>{let n=[];try{const o=v(n,w.Default.time("document-symbols"),0);let t=await i.runPromise(S.Service.use((d)=>d.documentSymbol(e.uri)));process.stdout.write(JSON.stringify(t,null,2)+D)}catch(a){var m=a,l=1}finally{P(n,m,l)}})}});import{EOL as C}from"os";var F=r({command:"rg",describe:"ripgrep debugging utilities",builder:(e)=>e.command(se).command(ne).command(ae).demandCommand(),async handler(){}}),se=r({command:"tree",describe:"show file tree using ripgrep",builder:(e)=>e.option("limit",{type:"number"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(u.Service.use((t)=>t.tree({cwd:p.directory,limit:e.limit})));process.stdout.write(o+C)})}}),ne=r({command:"files",describe:"list files using ripgrep",builder:(e)=>e.option("query",{type:"string",description:"Filter files by query"}).option("glob",{type:"string",description:"Glob pattern to match files"}).option("limit",{type:"number",description:"Limit number of results"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(c.gen(function*(){return yield*(yield*u.Service).files({cwd:p.directory,glob:e.glob?[e.glob]:void 0}).pipe(A.take(e.limit??1/0),A.runCollect,c.map((n)=>[...n]))}));process.stdout.write(o.join(C)+C)})}}),ae=r({command:"search <pattern>",describe:"search file contents using ripgrep",builder:(e)=>e.positional("pattern",{type:"string",demandOption:!0,description:"Search pattern"}).option("glob",{type:"array",description:"File glob patterns"}).option("limit",{type:"number",description:"Limit number of results"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(u.Service.use((t)=>t.search({cwd:p.directory,pattern:e.pattern,glob:e.glob,limit:e.limit})));process.stdout.write(JSON.stringify(o.items,null,2)+C)})}});import{EOL as me}from"os";var T=r({command:"scrap",describe:"list all known projects",builder:(e)=>e,async handler(){let e=w.Default.time("scrap"),o=await R.list();process.stdout.write(JSON.stringify(o,null,2)+me),e.stop()}});import{EOL as ce}from"os";var j=r({command:"skill",describe:"list all available skills",builder:(e)=>e,async handler(){await s(process.cwd(),async()=>{let e=await i.runPromise(c.gen(function*(){return yield*(yield*q.Service).all()}));process.stdout.write(JSON.stringify(e,null,2)+ce)})}});var M=r({command:"snapshot",describe:"snapshot debugging utilities",builder:(e)=>e.command(de).command(le).command(pe).demandCommand(),async handler(){}}),I=(e)=>s(process.cwd(),async()=>{console.log(await i.runPromise($.Service.use(e)))}),_=(e)=>e.positional("hash",{type:"string",description:"hash",demandOption:!0}),de=r({command:"track",describe:"track current snapshot state",async handler(){await I((e)=>e.track())}}),le=r({command:"patch <hash>",describe:"show patch for a snapshot hash",builder:_,async handler(e){await I((o)=>o.patch(e.hash))}}),pe=r({command:"diff <hash>",describe:"show diff for a snapshot hash",builder:_,async handler(e){await I((o)=>o.diff(e.hash))}});import{EOL as b}from"os";import{basename as ue}from"path";var Q=r({command:"agent <name>",describe:"show agent configuration details",builder:(e)=>e.positional("name",{type:"string",demandOption:!0,description:"Agent name"}).option("tool",{type:"string",description:"Tool id to execute"}).option("params",{type:"string",description:"Tool params as a JSON object"}),async handler(e){await s(process.cwd(),async()=>{let o=e.name,t=await i.runPromise(B.Service.use((d)=>d.get(o)));if(!t)process.stderr.write(`Agent ${o} not found, run '${ue(process.execPath)} agent list' to get an agent list`+b),process.exit(1);let n=await fe(t),a=await ye(t,n),m=e.tool;if(m){let d=n.find((W)=>W.id===m);if(!d)process.stderr.write(`Tool ${m} not found for agent ${o}`+b),process.exit(1);if(a[m]===!1)process.stderr.write(`Tool ${m} is disabled for agent ${o}`+b),process.exit(1);let h=ge(e.params),O=await we(t),N=await d.execute(h,O);process.stdout.write(JSON.stringify({tool:m,input:h,result:N},null,2)+b);return}let l={...t,tools:a};process.stdout.write(JSON.stringify(l,null,2)+b)})}});async function fe(e){return i.runPromise(c.gen(function*(){let o=yield*x.Service,t=yield*z.Service,n=e.model??(yield*o.defaultModel());return yield*t.tools({...n,agent:e})}))}async function ye(e,o){let t=f.disabled(o.map((a)=>a.id),e.permission),n={};for(let a of o)n[a.id]=!t.has(a.id);return n}function ge(e){if(!e)return{};let o=e.trim();if(o.length===0)return{};let t=(()=>{try{return JSON.parse(o)}catch{throw Error("Failed to parse --params. Provide a valid JSON object.")}})();if(!t||typeof t!=="object"||Array.isArray(t))throw Error("Tool params must be an object.");return t}async function we(e){let{session:o,messageID:t}=await i.runPromise(c.gen(function*(){let a=yield*K.Service,m=yield*a.create({title:`Debug tool run (${e.name})`}),l=G.ascending(),d=e.model?e.model:yield*c.gen(function*(){return yield*(yield*x.Service).defaultModel()}),h=Date.now(),O={id:l,sessionID:m.id,role:"assistant",time:{created:h},parentID:l,modelID:d.modelID,providerID:d.providerID,mode:"debug",agent:e.name,path:{cwd:p.directory,root:p.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};return yield*a.updateMessage(O),{session:m,messageID:l}})),n=f.merge(e.permission,o.permission??[]);return{sessionID:o.id,messageID:t,callID:V.ascending(),agent:e.name,abort:new AbortController().signal,messages:[],metadata:()=>c.void,ask(a){return c.sync(()=>{for(let m of a.patterns)if(f.evaluate(a.permission,m,n).action==="deny")throw new f.DeniedError({ruleset:n})})}}}var jo=r({command:"debug",describe:"debugging and troubleshooting tools",builder:(e)=>e.command(k).command(E).command(F).command(L).command(T).command(j).command(M).command(Q).command(be).command({command:"wait",describe:"wait indefinitely (for debugging)",async handler(){await s(process.cwd(),async()=>{await new Promise((o)=>setTimeout(o,86400000))})}}).demandCommand(),async handler(){}}),be=r({command:"paths",describe:"show global paths (data, config, cache, state)",handler(){for(let[e,o]of Object.entries(U.Path))console.log(e.padEnd(10),o)}});export{jo as DebugCommand};
2
+ import{Bd as s}from"./chunk-07b36w5g.js";import{Od as r}from"./chunk-wmmck56g.js";import{Ig as u,Jg as g,Sg as q,fh as z,gh as B,qh as i}from"./chunk-0jv8r99k.js";import"./chunk-th189x63.js";import"./chunk-k6eyc1wv.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{Ik as f,Tj as G,Uj as V,Vk as x,Xj as S,dk as $,el as K,fl as J}from"./chunk-3f6t3wde.js";import"./chunk-b5h8vd5n.js";import{Nl as R,Pl as p}from"./chunk-jee9y4t0.js";import"./chunk-50aznc8e.js";import"./chunk-c4x99ayd.js";import"./chunk-73d0dy03.js";import"./chunk-ha5qct06.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-ds162xgb.js";import"./chunk-jfy6bfvv.js";import"./chunk-2p6w3w8f.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-2bxy8zm1.js";import"./chunk-qq9pvscd.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import{ct as U,mt as w}from"./chunk-p20ft5mj.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{$H as c,AO as A}from"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import{qP as v,rP as P}from"./chunk-fa03gsff.js";import{EOL as X}from"os";var k=r({command:"config",describe:"show resolved configuration",builder:(e)=>e,async handler(){await s(process.cwd(),async()=>{let e=await i.runPromise(J.Service.use((o)=>o.get()));process.stdout.write(JSON.stringify(e,null,2)+X)})}});import{EOL as y}from"os";var Y=r({command:"search <query>",describe:"search files by query",builder:(e)=>e.positional("query",{type:"string",demandOption:!0,description:"Search query"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(g.Service.use((t)=>t.search({query:e.query})));process.stdout.write(o.join(y)+y)})}}),Z=r({command:"read <path>",describe:"read file contents as JSON",builder:(e)=>e.positional("path",{type:"string",demandOption:!0,description:"File path to read"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(g.Service.use((t)=>t.read(e.path)));process.stdout.write(JSON.stringify(o,null,2)+y)})}}),H=r({command:"status",describe:"show file status information",builder:(e)=>e,async handler(){await s(process.cwd(),async()=>{let e=await i.runPromise(g.Service.use((o)=>o.status()));process.stdout.write(JSON.stringify(e,null,2)+y)})}}),ee=r({command:"list <path>",describe:"list files in a directory",builder:(e)=>e.positional("path",{type:"string",demandOption:!0,description:"File path to list"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(g.Service.use((t)=>t.list(e.path)));process.stdout.write(JSON.stringify(o,null,2)+y)})}}),oe=r({command:"tree [dir]",describe:"show directory tree",builder:(e)=>e.positional("dir",{type:"string",description:"Directory to tree",default:process.cwd()}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(u.Service.use((t)=>t.tree({cwd:e.dir,limit:200})));console.log(JSON.stringify(o,null,2))})}}),L=r({command:"file",describe:"file system debugging utilities",builder:(e)=>e.command(Z).command(H).command(ee).command(Y).command(oe).demandCommand(),async handler(){}});import{EOL as D}from"os";var E=r({command:"lsp",describe:"LSP debugging utilities",builder:(e)=>e.command(te).command(re).command(ie).demandCommand(),async handler(){}}),te=r({command:"diagnostics <file>",describe:"get diagnostics for a file",builder:(e)=>e.positional("file",{type:"string",demandOption:!0}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(S.Service.use((t)=>c.gen(function*(){return yield*t.touchFile(e.file,!0),yield*c.sleep(1000),yield*t.diagnostics()})));process.stdout.write(JSON.stringify(o,null,2)+D)})}}),re=r({command:"symbols <query>",describe:"search workspace symbols",builder:(e)=>e.positional("query",{type:"string",demandOption:!0}),async handler(e){await s(process.cwd(),async()=>{let n=[];try{const o=v(n,w.Default.time("symbols"),0);let t=await i.runPromise(S.Service.use((d)=>d.workspaceSymbol(e.query)));process.stdout.write(JSON.stringify(t,null,2)+D)}catch(a){var m=a,l=1}finally{P(n,m,l)}})}}),ie=r({command:"document-symbols <uri>",describe:"get symbols from a document",builder:(e)=>e.positional("uri",{type:"string",demandOption:!0}),async handler(e){await s(process.cwd(),async()=>{let n=[];try{const o=v(n,w.Default.time("document-symbols"),0);let t=await i.runPromise(S.Service.use((d)=>d.documentSymbol(e.uri)));process.stdout.write(JSON.stringify(t,null,2)+D)}catch(a){var m=a,l=1}finally{P(n,m,l)}})}});import{EOL as C}from"os";var F=r({command:"rg",describe:"ripgrep debugging utilities",builder:(e)=>e.command(se).command(ne).command(ae).demandCommand(),async handler(){}}),se=r({command:"tree",describe:"show file tree using ripgrep",builder:(e)=>e.option("limit",{type:"number"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(u.Service.use((t)=>t.tree({cwd:p.directory,limit:e.limit})));process.stdout.write(o+C)})}}),ne=r({command:"files",describe:"list files using ripgrep",builder:(e)=>e.option("query",{type:"string",description:"Filter files by query"}).option("glob",{type:"string",description:"Glob pattern to match files"}).option("limit",{type:"number",description:"Limit number of results"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(c.gen(function*(){return yield*(yield*u.Service).files({cwd:p.directory,glob:e.glob?[e.glob]:void 0}).pipe(A.take(e.limit??1/0),A.runCollect,c.map((n)=>[...n]))}));process.stdout.write(o.join(C)+C)})}}),ae=r({command:"search <pattern>",describe:"search file contents using ripgrep",builder:(e)=>e.positional("pattern",{type:"string",demandOption:!0,description:"Search pattern"}).option("glob",{type:"array",description:"File glob patterns"}).option("limit",{type:"number",description:"Limit number of results"}),async handler(e){await s(process.cwd(),async()=>{let o=await i.runPromise(u.Service.use((t)=>t.search({cwd:p.directory,pattern:e.pattern,glob:e.glob,limit:e.limit})));process.stdout.write(JSON.stringify(o.items,null,2)+C)})}});import{EOL as me}from"os";var T=r({command:"scrap",describe:"list all known projects",builder:(e)=>e,async handler(){let e=w.Default.time("scrap"),o=await R.list();process.stdout.write(JSON.stringify(o,null,2)+me),e.stop()}});import{EOL as ce}from"os";var j=r({command:"skill",describe:"list all available skills",builder:(e)=>e,async handler(){await s(process.cwd(),async()=>{let e=await i.runPromise(c.gen(function*(){return yield*(yield*q.Service).all()}));process.stdout.write(JSON.stringify(e,null,2)+ce)})}});var M=r({command:"snapshot",describe:"snapshot debugging utilities",builder:(e)=>e.command(de).command(le).command(pe).demandCommand(),async handler(){}}),I=(e)=>s(process.cwd(),async()=>{console.log(await i.runPromise($.Service.use(e)))}),_=(e)=>e.positional("hash",{type:"string",description:"hash",demandOption:!0}),de=r({command:"track",describe:"track current snapshot state",async handler(){await I((e)=>e.track())}}),le=r({command:"patch <hash>",describe:"show patch for a snapshot hash",builder:_,async handler(e){await I((o)=>o.patch(e.hash))}}),pe=r({command:"diff <hash>",describe:"show diff for a snapshot hash",builder:_,async handler(e){await I((o)=>o.diff(e.hash))}});import{EOL as b}from"os";import{basename as ue}from"path";var Q=r({command:"agent <name>",describe:"show agent configuration details",builder:(e)=>e.positional("name",{type:"string",demandOption:!0,description:"Agent name"}).option("tool",{type:"string",description:"Tool id to execute"}).option("params",{type:"string",description:"Tool params as a JSON object"}),async handler(e){await s(process.cwd(),async()=>{let o=e.name,t=await i.runPromise(B.Service.use((d)=>d.get(o)));if(!t)process.stderr.write(`Agent ${o} not found, run '${ue(process.execPath)} agent list' to get an agent list`+b),process.exit(1);let n=await fe(t),a=await ye(t,n),m=e.tool;if(m){let d=n.find((W)=>W.id===m);if(!d)process.stderr.write(`Tool ${m} not found for agent ${o}`+b),process.exit(1);if(a[m]===!1)process.stderr.write(`Tool ${m} is disabled for agent ${o}`+b),process.exit(1);let h=ge(e.params),O=await we(t),N=await d.execute(h,O);process.stdout.write(JSON.stringify({tool:m,input:h,result:N},null,2)+b);return}let l={...t,tools:a};process.stdout.write(JSON.stringify(l,null,2)+b)})}});async function fe(e){return i.runPromise(c.gen(function*(){let o=yield*x.Service,t=yield*z.Service,n=e.model??(yield*o.defaultModel());return yield*t.tools({...n,agent:e})}))}async function ye(e,o){let t=f.disabled(o.map((a)=>a.id),e.permission),n={};for(let a of o)n[a.id]=!t.has(a.id);return n}function ge(e){if(!e)return{};let o=e.trim();if(o.length===0)return{};let t=(()=>{try{return JSON.parse(o)}catch{throw Error("Failed to parse --params. Provide a valid JSON object.")}})();if(!t||typeof t!=="object"||Array.isArray(t))throw Error("Tool params must be an object.");return t}async function we(e){let{session:o,messageID:t}=await i.runPromise(c.gen(function*(){let a=yield*K.Service,m=yield*a.create({title:`Debug tool run (${e.name})`}),l=G.ascending(),d=e.model?e.model:yield*c.gen(function*(){return yield*(yield*x.Service).defaultModel()}),h=Date.now(),O={id:l,sessionID:m.id,role:"assistant",time:{created:h},parentID:l,modelID:d.modelID,providerID:d.providerID,mode:"debug",agent:e.name,path:{cwd:p.directory,root:p.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};return yield*a.updateMessage(O),{session:m,messageID:l}})),n=f.merge(e.permission,o.permission??[]);return{sessionID:o.id,messageID:t,callID:V.ascending(),agent:e.name,abort:new AbortController().signal,messages:[],metadata:()=>c.void,ask(a){return c.sync(()=>{for(let m of a.patterns)if(f.evaluate(a.permission,m,n).action==="deny")throw new f.DeniedError({ruleset:n})})}}}var jo=r({command:"debug",describe:"debugging and troubleshooting tools",builder:(e)=>e.command(k).command(E).command(F).command(L).command(T).command(j).command(M).command(Q).command(be).command({command:"wait",describe:"wait indefinitely (for debugging)",async handler(){await s(process.cwd(),async()=>{await new Promise((o)=>setTimeout(o,86400000))})}}).demandCommand(),async handler(){}}),be=r({command:"paths",describe:"show global paths (data, config, cache, state)",handler(){for(let[e,o]of Object.entries(U.Path))console.log(e.padEnd(10),o)}});export{jo as DebugCommand};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Od as a}from"./chunk-wmmck56g.js";import{Pf as d}from"./chunk-6tjghyx6.js";import{Sf as i}from"./chunk-ntmn6epc.js";import{Dl as p,Fl as n}from"./chunk-7myavy3p.js";import"./chunk-fegrrsfj.js";import{Eo as f}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{pt as m}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-fa03gsff.js";import{spawn as y}from"child_process";import{Database as g}from"bun:sqlite";import{EOL as l}from"os";var b=a({command:"$0 [query]",describe:"open an interactive sqlite3 shell or run a query",builder:(t)=>{return t.positional("query",{type:"string",describe:"SQL query to execute"}).option("format",{type:"string",choices:["json","tsv"],default:"tsv",describe:"Output format"})},handler:async(t)=>{let o=t.query;if(o){let r=new g(n.Path,{readonly:!0});try{let e=r.query(o).all();if(t.format==="json")console.log(JSON.stringify(e,null,2));else if(e.length>0){let s=Object.keys(e[0]);console.log(s.join("\t"));for(let u of e)console.log(s.map((h)=>u[h]).join("\t"))}}catch(e){i.error(m(e)),process.exit(1)}r.close();return}let c=y("sqlite3",[n.Path],{stdio:"inherit"});await new Promise((r)=>c.on("close",r))}}),w=a({command:"path",describe:"print the database path",handler:()=>{console.log(n.Path)}}),q=a({command:"migrate",describe:"migrate JSON data to SQLite (merges with existing data)",handler:async()=>{let t=new g(n.Path),o=process.stderr.isTTY,c=-1;if(o)process.stderr.write("\x1B[?25l");try{let r=await p.run(f({client:t}),{progress:(e)=>{let s=Math.floor(e.current/e.total*100);if(s===c)return;if(c=s,o)process.stderr.write(d(s,`${e.current}/${e.total}`)+" ");else process.stderr.write(`sqlite-migration:${s}${l}`)}});if(o)process.stderr.write(`
2
+ import{Od as a}from"./chunk-wmmck56g.js";import{Pf as d}from"./chunk-18xhxdsh.js";import{Sf as i}from"./chunk-ntmn6epc.js";import{Dl as p,Fl as n}from"./chunk-jee9y4t0.js";import"./chunk-50aznc8e.js";import{Eo as f}from"./chunk-c4x99ayd.js";import"./chunk-tq258v8s.js";import"./chunk-jfy6bfvv.js";import"./chunk-2p6w3w8f.js";import"./chunk-2bxy8zm1.js";import"./chunk-qq9pvscd.js";import"./chunk-3nc9wy1m.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-p20ft5mj.js";import{pt as m}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-fa03gsff.js";import{spawn as y}from"child_process";import{Database as g}from"bun:sqlite";import{EOL as l}from"os";var b=a({command:"$0 [query]",describe:"open an interactive sqlite3 shell or run a query",builder:(t)=>{return t.positional("query",{type:"string",describe:"SQL query to execute"}).option("format",{type:"string",choices:["json","tsv"],default:"tsv",describe:"Output format"})},handler:async(t)=>{let o=t.query;if(o){let r=new g(n.Path,{readonly:!0});try{let e=r.query(o).all();if(t.format==="json")console.log(JSON.stringify(e,null,2));else if(e.length>0){let s=Object.keys(e[0]);console.log(s.join("\t"));for(let u of e)console.log(s.map((h)=>u[h]).join("\t"))}}catch(e){i.error(m(e)),process.exit(1)}r.close();return}let c=y("sqlite3",[n.Path],{stdio:"inherit"});await new Promise((r)=>c.on("close",r))}}),w=a({command:"path",describe:"print the database path",handler:()=>{console.log(n.Path)}}),q=a({command:"migrate",describe:"migrate JSON data to SQLite (merges with existing data)",handler:async()=>{let t=new g(n.Path),o=process.stderr.isTTY,c=-1;if(o)process.stderr.write("\x1B[?25l");try{let r=await p.run(f({client:t}),{progress:(e)=>{let s=Math.floor(e.current/e.total*100);if(s===c)return;if(c=s,o)process.stderr.write(d(s,`${e.current}/${e.total}`)+" ");else process.stderr.write(`sqlite-migration:${s}${l}`)}});if(o)process.stderr.write(`
3
3
  `);if(o)process.stderr.write("\x1B[?25h");else process.stderr.write(`sqlite-migration:done${l}`);if(i.println(`Migration complete: ${r.projects} projects, ${r.sessions} sessions, ${r.messages} messages`),r.errors.length>0)i.println(`${r.errors.length} errors occurred during migration`)}catch(r){if(o)process.stderr.write("\x1B[?25h");i.error(`Migration failed: ${m(r)}`),process.exit(1)}finally{t.close()}}}),v=a({command:"db",describe:"database tools",builder:(t)=>{return t.command(b).command(w).command(q).demandCommand()},handler:()=>{}});export{v as DbCommand};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{g as K}from"./chunk-knwayz0m.js";import{i as $}from"./chunk-f72j5yx8.js";import{F as O,G as v}from"./chunk-wnjg8mmh.js";import{Od as V}from"./chunk-wmmck56g.js";import{Sf as j}from"./chunk-ntmn6epc.js";import{Ag as w,pg as D,qg as L,rg as G,sg as W,wg as Y,zg as _}from"./chunk-pn77fh9b.js";import{qh as T}from"./chunk-1qw3yh13.js";import{Dj as Z}from"./chunk-q39h31te.js";import{$H as H}from"./chunk-meaa7wrs.js";var X="forgewise",S=(J,z=process.env)=>J.trim()||z.QLEX_API_KEY?.trim()||"",A=(J)=>H.gen(function*(){let z=J.trim();if(!z)yield*H.sync(()=>{j.println(j.Style.TEXT_DANGER+"Error: API key cannot be empty."+j.Style.TEXT_NORMAL)}),process.exit(1);yield*(yield*Z.Service).set(X,{type:"api",key:z,metadata:{method:"api-key"}}),yield*$(j.Style.TEXT_SUCCESS+"Signed in with API key."+j.Style.TEXT_NORMAL)}).pipe(H.withSpan("forgewise.login.apikey"));async function R(){let J=!G();try{return await _({tryOpen:J,onCode:(z)=>{if(process.stdout.write(`
2
+ import{g as K}from"./chunk-2bbvvh0d.js";import{i as $}from"./chunk-f72j5yx8.js";import{F as O,G as v}from"./chunk-zbvf09bm.js";import{Od as V}from"./chunk-wmmck56g.js";import{Sf as j}from"./chunk-ntmn6epc.js";import{Ag as w,pg as D,qg as L,rg as G,sg as W,wg as Y,zg as _}from"./chunk-cckshvkb.js";import{qh as T}from"./chunk-0jv8r99k.js";import{Dj as Z}from"./chunk-3f6t3wde.js";import{$H as H}from"./chunk-meaa7wrs.js";var X="forgewise",S=(J,z=process.env)=>J.trim()||z.QLEX_API_KEY?.trim()||"",A=(J)=>H.gen(function*(){let z=J.trim();if(!z)yield*H.sync(()=>{j.println(j.Style.TEXT_DANGER+"Error: API key cannot be empty."+j.Style.TEXT_NORMAL)}),process.exit(1);yield*(yield*Z.Service).set(X,{type:"api",key:z,metadata:{method:"api-key"}}),yield*$(j.Style.TEXT_SUCCESS+"Signed in with API key."+j.Style.TEXT_NORMAL)}).pipe(H.withSpan("forgewise.login.apikey"));async function R(){let J=!G();try{return await _({tryOpen:J,onCode:(z)=>{if(process.stdout.write(`
3
3
  `),process.stdout.write(" To sign in, open: "+z.verificationUri+`
4
4
  `),process.stdout.write(" and enter code: "+z.userCode+`
5
5
  `),z.verificationUriComplete)process.stdout.write(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Jo as w,Ko as A,No as U,Oo as O,So as R,Uo as s,Vo as F}from"./chunk-0pbpzty2.js";import{ip as G,mp as L}from"./chunk-tq258v8s.js";import{Bt as M,Gt as k}from"./chunk-b5x3zghc.js";import{BN as y}from"./chunk-meaa7wrs.js";import{nP as Y}from"./chunk-fa03gsff.js";var _={};Y(_,{schema:()=>x,jsonc:()=>v,ConfigParse:()=>_});function v($,r){let E=[],J=w($,E,{allowTrailingComma:!0});if(E.length){let C=$.split(`
2
+ import{Jo as w,Ko as A,No as U,Oo as O,So as R,Uo as s,Vo as F}from"./chunk-ha5qct06.js";import{ip as G,mp as L}from"./chunk-tq258v8s.js";import{Bt as M,Gt as k}from"./chunk-b5x3zghc.js";import{BN as y}from"./chunk-meaa7wrs.js";import{nP as Y}from"./chunk-fa03gsff.js";var _={};Y(_,{schema:()=>x,jsonc:()=>v,ConfigParse:()=>_});function v($,r){let E=[],J=w($,E,{allowTrailingComma:!0});if(E.length){let C=$.split(`
3
3
  `),T=E.map((I)=>{let Z=$.substring(0,I.offset).split(`
4
4
  `),H=Z.length,j=Z[Z.length-1].length+1,B=C[H-1],Q=`${A(I.error)} at line ${H}, column ${j}`;if(!B)return Q;return`${Q}
5
5
  Line ${H}: ${B}
@@ -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-p20ft5mj.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{ct as p,dt as f,mt as m}from"./chunk-v7yvnnmr.js";import{nP as l}from"./chunk-fa03gsff.js";var n={};l(n,{start:()=>I,Heap:()=>n});import h from"path";import{writeHeapSnapshot as u}from"v8";var i=m.create({service:"heap"}),g=60000,d=2147483648,o,s=!1,a=!0;function I(){if(!f.QITQODE_AUTO_HEAP_SNAPSHOT)return;if(o)return;let c=async()=>{if(s)return;let e=process.memoryUsage();if(e.rss<=d){a=!0;return}if(!a)return;s=!0,a=!1;let r=h.join(p.Path.log,`heap-${process.pid}-${new Date().toISOString().replace(/[:.]/g,"")}.heapsnapshot`);i.warn("heap usage exceeded limit",{rss:e.rss,heap:e.heapUsed,file:r}),await Promise.resolve().then(()=>u(r)).catch((t)=>{i.error("failed to write heap snapshot",{error:t instanceof Error?t.message:String(t),file:r})}),s=!1};o=setInterval(()=>{c()},g),o.unref?.()}
2
+ import{ct as p,dt as f,mt as m}from"./chunk-p20ft5mj.js";import{nP as l}from"./chunk-fa03gsff.js";var n={};l(n,{start:()=>I,Heap:()=>n});import h from"path";import{writeHeapSnapshot as u}from"v8";var i=m.create({service:"heap"}),g=60000,d=2147483648,o,s=!1,a=!0;function I(){if(!f.QITQODE_AUTO_HEAP_SNAPSHOT)return;if(o)return;let c=async()=>{if(s)return;let e=process.memoryUsage();if(e.rss<=d){a=!0;return}if(!a)return;s=!0,a=!1;let r=h.join(p.Path.log,`heap-${process.pid}-${new Date().toISOString().replace(/[:.]/g,"")}.heapsnapshot`);i.warn("heap usage exceeded limit",{rss:e.rss,heap:e.heapUsed,file:r}),await Promise.resolve().then(()=>u(r)).catch((t)=>{i.error("failed to write heap snapshot",{error:t instanceof Error?t.message:String(t),file:r})}),s=!1};o=setInterval(()=>{c()},g),o.unref?.()}
3
3
  export{I as Tf,n as Uf};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Jk as e}from"./chunk-q39h31te.js";import{Jl as r}from"./chunk-7myavy3p.js";import{It as o}from"./chunk-tk6gjy9d.js";var s=o.object({id:e.zod,type:o.string(),name:o.string(),branch:o.string().nullable(),directory:o.string().nullable(),extra:o.unknown().nullable(),projectID:r.zod});
2
+ import{Jk as e}from"./chunk-3f6t3wde.js";import{Jl as r}from"./chunk-jee9y4t0.js";import{It as o}from"./chunk-tk6gjy9d.js";var s=o.object({id:e.zod,type:o.string(),name:o.string(),branch:o.string().nullable(),directory:o.string().nullable(),extra:o.unknown().nullable(),projectID:r.zod});
3
3
  export{s as Gg};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{et as a,ft as b,gt as c,ht as d,it as e,jt as f,kt as g,lt as h}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{g as redactValue,e as init,f as flush,d as file,b as enabled,h as create,a as Level,c as Default};
2
+ import{et as a,ft as b,gt as c,ht as d,it as e,jt as f,kt as g,lt as h}from"./chunk-p20ft5mj.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{g as redactValue,e as init,f as flush,d as file,b as enabled,h as create,a as Level,c as Default};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Jo as j,Ko as R,Lo as O,Mo as A,So as y,Xo as q,Yo as M,_o as C,ep as K}from"./chunk-0pbpzty2.js";import{$s as v,ct as D}from"./chunk-v7yvnnmr.js";import{Gt as d,nt as m,pt as b,vt as I}from"./chunk-b5x3zghc.js";import{qP as T,rP as _}from"./chunk-fa03gsff.js";import P from"path";function pt(t){let e=t&&typeof t==="object"&&"cause"in t?t.cause??t:t;if(!(e instanceof I.RunFailedError))return{error:e,detail:b(e),missing:!1};let r=e.stderr.toString().split(/\r?\n/).map((o)=>o.trim()).filter(Boolean),n=r.filter((o)=>o.startsWith("error:")).map((o)=>o.replace(/^error:\s*/,""));return{error:e,detail:n[0]??r.at(-1),missing:r.some((o)=>o.includes("No version matching"))}}var $={resolve:(t)=>q(t)},z={readText:(t)=>d.readText(t),write:async(t,e)=>{await d.write(t,e)},exists:(t)=>d.exists(t),files:(t,e)=>K(t,e)},G=z;function V(t){if(typeof t==="string")return t;if(!Array.isArray(t))return;if(typeof t[0]!=="string")return;return t[0]}function H(t){if(!t||typeof t!=="object"||Array.isArray(t))return;let e=t;if(!Array.isArray(e.plugin))return;return e.plugin}function Q(t){if(typeof t==="string"){let e=t.trim();if(e)return e;return}if(!m(t))return;for(let e of["import","default"]){let r=t[e];if(typeof r!=="string")continue;let n=r.trim();if(!n)continue;return n}}function U(t){if(!m(t))return;let e=t.config;if(!m(e))return;return e}function E(t,e){let r=t.exports;if(!m(r))return;let n=r[`./${e}`];if(!Q(n))return;return{opts:U(n)}}function X(t){let e=t.main;if(typeof e!=="string")return!1;return Boolean(e.trim())}function Y(t){let e=typeof t.json.name==="string"&&t.json.name.trim().length>0?t.json.name.trim():P.basename(t.dir),r=[],n=E(t.json,"server");if(n)r.push({kind:"server",opts:n.opts});else if(X(t.json))r.push({kind:"server"});let o=E(t.json,"tui");if(o)r.push({kind:"tui",opts:o.opts});if(!r.some((c)=>c.kind==="tui")&&C(e,t).length)r.push({kind:"tui"});return r}function g(t,e,r,n=!1){return A(t,O(t,e,r,{formattingOptions:{tabSize:2,insertSpaces:!0},isArrayInsertion:n}))}function Z(t,e,r,n,o=!1){let c=y(r).pkg,u=(e??[]).map((i,p)=>({item:i,i:p,spec:V(i)})).filter((i)=>{if(!i.spec)return!1;if(i.spec===r)return!0;if(i.spec.startsWith("file://"))return!1;return y(i.spec).pkg===c});if(!u.length){if(!e)return{mode:"add",text:g(t,["plugin"],[n])};return{mode:"add",text:g(t,["plugin",e.length],n,!0)}}if(!o)return{mode:"noop",text:t};let s=u[0];if(!s)return{mode:"noop",text:t};if(u.length===1&&s.spec===r)return{mode:"noop",text:t};let a=t;if(typeof s.item==="string")a=g(a,["plugin",s.i],n);if(Array.isArray(s.item)&&typeof s.item[0]==="string")a=g(a,["plugin",s.i,0],r);let l=u.map((i)=>i.i).filter((i)=>i!==s.i).sort((i,p)=>p-i);for(let i of l)a=g(a,["plugin",i],void 0);return{mode:"replace",text:a}}async function gt(t,e=$){let r=await e.resolve(t).then((n)=>({ok:!0,item:n}),(n)=>({ok:!1,error:n}));if(!r.ok)return{ok:!1,code:"install_failed",error:r.error};return{ok:!0,target:r.item}}async function dt(t){let e=await M(t).then((n)=>({ok:!0,item:n}),(n)=>({ok:!1,error:n}));if(!e.ok)return{ok:!1,code:"manifest_read_failed",file:t,error:e.error};let r=await Promise.resolve().then(()=>Y(e.item)).then((n)=>({ok:!0,item:n}),(n)=>({ok:!1,error:n}));if(!r.ok)return{ok:!1,code:"manifest_read_failed",file:e.item.pkg,error:r.error};if(!r.item.length)return{ok:!1,code:"manifest_no_targets",file:e.item.pkg};return{ok:!0,targets:r.item}}function tt(t){if(t.global)return t.config??D.Path.config;let r=t.vcs==="git"&&t.worktree!=="/"?t.worktree:t.directory;return P.join(r,".qitqode")}function et(t){if(t==="server")return"qitqode";return"tui"}async function rt(t,e,r,n,o){let x=[];try{let c=et(e.kind);const S=T(x,await v.acquire(`plug-config:${d.resolve(P.join(t,c))}`),1);let u=o.files(t,c);let s=u[0];for(let f of u){if(!await o.exists(f))continue;s=f;break}let a=await o.readText(s).catch((f)=>{if(f.code==="ENOENT")return"{}";return f});if(a instanceof Error)return{ok:!1,code:"patch_failed",kind:e.kind,error:a};let l=a.trim()?a:"{}";let i=[];let p=j(l,i,{allowTrailingComma:!0});if(i.length){let f=i[0],h=l.substring(0,f.offset).split(`
2
+ import{Jo as j,Ko as R,Lo as O,Mo as A,So as y,Xo as q,Yo as M,_o as C,ep as K}from"./chunk-ha5qct06.js";import{$s as v,ct as D}from"./chunk-p20ft5mj.js";import{Gt as d,nt as m,pt as b,vt as I}from"./chunk-b5x3zghc.js";import{qP as T,rP as _}from"./chunk-fa03gsff.js";import P from"path";function pt(t){let e=t&&typeof t==="object"&&"cause"in t?t.cause??t:t;if(!(e instanceof I.RunFailedError))return{error:e,detail:b(e),missing:!1};let r=e.stderr.toString().split(/\r?\n/).map((o)=>o.trim()).filter(Boolean),n=r.filter((o)=>o.startsWith("error:")).map((o)=>o.replace(/^error:\s*/,""));return{error:e,detail:n[0]??r.at(-1),missing:r.some((o)=>o.includes("No version matching"))}}var $={resolve:(t)=>q(t)},z={readText:(t)=>d.readText(t),write:async(t,e)=>{await d.write(t,e)},exists:(t)=>d.exists(t),files:(t,e)=>K(t,e)},G=z;function V(t){if(typeof t==="string")return t;if(!Array.isArray(t))return;if(typeof t[0]!=="string")return;return t[0]}function H(t){if(!t||typeof t!=="object"||Array.isArray(t))return;let e=t;if(!Array.isArray(e.plugin))return;return e.plugin}function Q(t){if(typeof t==="string"){let e=t.trim();if(e)return e;return}if(!m(t))return;for(let e of["import","default"]){let r=t[e];if(typeof r!=="string")continue;let n=r.trim();if(!n)continue;return n}}function U(t){if(!m(t))return;let e=t.config;if(!m(e))return;return e}function E(t,e){let r=t.exports;if(!m(r))return;let n=r[`./${e}`];if(!Q(n))return;return{opts:U(n)}}function X(t){let e=t.main;if(typeof e!=="string")return!1;return Boolean(e.trim())}function Y(t){let e=typeof t.json.name==="string"&&t.json.name.trim().length>0?t.json.name.trim():P.basename(t.dir),r=[],n=E(t.json,"server");if(n)r.push({kind:"server",opts:n.opts});else if(X(t.json))r.push({kind:"server"});let o=E(t.json,"tui");if(o)r.push({kind:"tui",opts:o.opts});if(!r.some((c)=>c.kind==="tui")&&C(e,t).length)r.push({kind:"tui"});return r}function g(t,e,r,n=!1){return A(t,O(t,e,r,{formattingOptions:{tabSize:2,insertSpaces:!0},isArrayInsertion:n}))}function Z(t,e,r,n,o=!1){let c=y(r).pkg,u=(e??[]).map((i,p)=>({item:i,i:p,spec:V(i)})).filter((i)=>{if(!i.spec)return!1;if(i.spec===r)return!0;if(i.spec.startsWith("file://"))return!1;return y(i.spec).pkg===c});if(!u.length){if(!e)return{mode:"add",text:g(t,["plugin"],[n])};return{mode:"add",text:g(t,["plugin",e.length],n,!0)}}if(!o)return{mode:"noop",text:t};let s=u[0];if(!s)return{mode:"noop",text:t};if(u.length===1&&s.spec===r)return{mode:"noop",text:t};let a=t;if(typeof s.item==="string")a=g(a,["plugin",s.i],n);if(Array.isArray(s.item)&&typeof s.item[0]==="string")a=g(a,["plugin",s.i,0],r);let l=u.map((i)=>i.i).filter((i)=>i!==s.i).sort((i,p)=>p-i);for(let i of l)a=g(a,["plugin",i],void 0);return{mode:"replace",text:a}}async function gt(t,e=$){let r=await e.resolve(t).then((n)=>({ok:!0,item:n}),(n)=>({ok:!1,error:n}));if(!r.ok)return{ok:!1,code:"install_failed",error:r.error};return{ok:!0,target:r.item}}async function dt(t){let e=await M(t).then((n)=>({ok:!0,item:n}),(n)=>({ok:!1,error:n}));if(!e.ok)return{ok:!1,code:"manifest_read_failed",file:t,error:e.error};let r=await Promise.resolve().then(()=>Y(e.item)).then((n)=>({ok:!0,item:n}),(n)=>({ok:!1,error:n}));if(!r.ok)return{ok:!1,code:"manifest_read_failed",file:e.item.pkg,error:r.error};if(!r.item.length)return{ok:!1,code:"manifest_no_targets",file:e.item.pkg};return{ok:!0,targets:r.item}}function tt(t){if(t.global)return t.config??D.Path.config;let r=t.vcs==="git"&&t.worktree!=="/"?t.worktree:t.directory;return P.join(r,".qitqode")}function et(t){if(t==="server")return"qitqode";return"tui"}async function rt(t,e,r,n,o){let x=[];try{let c=et(e.kind);const S=T(x,await v.acquire(`plug-config:${d.resolve(P.join(t,c))}`),1);let u=o.files(t,c);let s=u[0];for(let f of u){if(!await o.exists(f))continue;s=f;break}let a=await o.readText(s).catch((f)=>{if(f.code==="ENOENT")return"{}";return f});if(a instanceof Error)return{ok:!1,code:"patch_failed",kind:e.kind,error:a};let l=a.trim()?a:"{}";let i=[];let p=j(l,i,{allowTrailingComma:!0});if(i.length){let f=i[0],h=l.substring(0,f.offset).split(`
3
3
  `);return{ok:!1,code:"invalid_json",kind:e.kind,file:s,line:h.length,col:h[h.length-1].length+1,parse:R(f.error)}}let N=H(p);let F=e.opts?[r,e.opts]:r;let k=Z(l,N,r,F,n);if(k.mode==="noop")return{ok:!0,item:{kind:e.kind,mode:k.mode,file:s}};let w=await o.write(s,k.text).catch((f)=>f);if(w instanceof Error)return{ok:!1,code:"patch_failed",kind:e.kind,error:w};return{ok:!0,item:{kind:e.kind,mode:k.mode,file:s}}}catch(J){var B=J,L=1}finally{var W=_(x,B,L);W&&await W}}async function mt(t,e=G){let r=tt(t),n=[];for(let o of t.targets){let c=await rt(r,o,t.spec,Boolean(t.force),e);if(!c.ok)return{...c,dir:r};n.push(c.item)}return{ok:!0,dir:r,items:n}}
4
4
  export{pt as n,z as o,gt as p,dt as q,mt as r};
@@ -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-0jv8r99k.js";import"./chunk-th189x63.js";import"./chunk-k6eyc1wv.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-3f6t3wde.js";import{rl as V}from"./chunk-b5h8vd5n.js";import{Pl as n}from"./chunk-jee9y4t0.js";import"./chunk-50aznc8e.js";import"./chunk-c4x99ayd.js";import"./chunk-73d0dy03.js";import"./chunk-ha5qct06.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-ds162xgb.js";import"./chunk-jfy6bfvv.js";import"./chunk-2p6w3w8f.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-2bxy8zm1.js";import"./chunk-qq9pvscd.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-p20ft5mj.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,3 +1,3 @@
1
1
  // @bun
2
- import{$l as M,Vl as A,Wl as e,Xl as oo,Yl as io}from"./chunk-fegrrsfj.js";import{hp as Oo}from"./chunk-w8xaw2dv.js";import{rp as Qo}from"./chunk-jfy6bfvv.js";import{Or as F,Pr as s,Vr as q,Wr as t}from"./chunk-3nc9wy1m.js";import{$s as E,Gs as m,Hs as k,_s as Zo,ct as _o,dt as y,mt as T}from"./chunk-v7yvnnmr.js";import{Gt as P}from"./chunk-b5x3zghc.js";import{It as o}from"./chunk-tk6gjy9d.js";import{$H as V,AO as v,BN as U,TF as I,jD as r,yF as B}from"./chunk-meaa7wrs.js";import{lP as Yo,nP as a,pP as zo}from"./chunk-fa03gsff.js";var Fo={};a(Fo,{stopRefresh:()=>vo,startRefresh:()=>Io,refresh:()=>u,readModelCatalogResponse:()=>yo,get:()=>So,Provider:()=>Lo,Model:()=>Bo,MODEL_CATALOG_MAX_BYTES:()=>$o,Data:()=>D});import Do from"path";var z={};a(z,{layer:()=>bo,isPreview:()=>qo,isNewerVersion:()=>no,isLocal:()=>Go,getReleaseType:()=>wo,defaultLayer:()=>Uo,UpgradeFailedError:()=>N,USER_AGENT:()=>Ko,Service:()=>L,Installation:()=>z,Info:()=>Ho,Event:()=>Ro});var f=(i)=>i.pipe(q.retryTransient({retryOn:"errors-and-responses",times:2,schedule:I.exponential(200).pipe(I.jittered)}));import c from"path";var x=Yo(Oo(),1);var l=T.create({service:"installation"}),G="@qitqode/cli";function no(i,n){if(!x.default.valid(i)||!x.default.valid(n))return!1;return x.default.gt(n,i)}var Ro={Updated:M.define("installation.updated",o.object({version:o.string()})),UpdateAvailable:M.define("installation.update-available",o.object({version:o.string()}))};function wo(i,n){if(!no(i,n))throw Error(`Version ${n} is not newer than ${i}`);let j=x.default.major(i),Z=x.default.minor(i),$=x.default.major(n),_=x.default.minor(n);if($>j)return"major";if(_>Z)return"minor";return"patch"}var Ho=o.object({version:o.string(),latest:o.string()}).meta({ref:"InstallationInfo"}),Ko=`qitqode/${k}/${m}/${y.QITQODE_CLIENT}`;function qo(){return k!=="latest"}function Go(){return k==="local"}class N extends U.TaggedErrorClass()("UpgradeFailedError",{stderr:U.String}){}var No=U.Struct({version:U.String});class L extends r.Service()("@qitqode/Installation"){}var bo=B.effect(L,V.gen(function*(){let i=yield*q.HttpClient,n=q.filterStatusOk(f(i)),j=yield*A.ChildProcessSpawner,Z=(J,b)=>e.make(J[0],J.slice(1),{cwd:b?.cwd,env:b?.env,extendEnv:!0}),$=V.fnUntraced(function*(J){let b=yield*io(j,J);return{code:b.code,stdout:b.text,stderr:b.stderr}},V.scoped),_=V.fnUntraced(function*(J,b){let Q=yield*j.spawn(Z(J,b)),W=yield*v.mkString(v.decodeText(Q.stdout));return yield*Q.exitCode,W},V.scoped,V.catch(()=>V.succeed(""))),O=V.fnUntraced(function*(J,b){return yield*$(Z(J,b))},V.catch(()=>V.succeed({code:A.ExitCode(1),stdout:"",stderr:""}))),K=V.fn("Installation.method")(function*(){if(process.execPath.includes(c.join(".qitqode","bin")))return"curl";if(process.execPath.includes(c.join(".local","bin")))return"curl";let J=process.execPath.toLowerCase(),b=[{name:"npm",command:()=>_(["npm","list","-g","--depth=0"])},{name:"pnpm",command:()=>_(["pnpm","list","-g","--depth=0"])},{name:"bun",command:()=>_(["bun","pm","ls","-g"])}];b.sort((Q,W)=>{let w=J.includes(Q.name),p=J.includes(W.name);if(w&&!p)return-1;if(!w&&p)return 1;return 0});for(let Q of b)if((yield*Q.command()).includes(G))return Q.name;return"unknown"}),X=V.fn("Installation.latest")(function*(J){let b=J||(yield*K());if(b==="curl"){let W=(yield*_(["curl","-sI","https://github.com/qitqode/qitqode/releases/latest"])).match(/^location:.*\/tag\/v([0-9][^\s/]*)/im);if(W)return W[1];return yield*V.die(Error("failed to resolve latest version from GitHub releases redirect"))}if(b==="npm"||b==="bun"||b==="pnpm"){let W=(yield*_(["npm","config","get","registry"])).trim()||"https://registry.npmjs.org",w=W.endsWith("/")?W.slice(0,-1):W,p=yield*n.execute(F.get(`${w}/${encodeURIComponent(G)}/${k}`).pipe(F.acceptJson));return(yield*s.schemaBodyJson(No)(p)).version}return l.warn("unsupported update channel, skipping",{method:b}),yield*V.die(Error(`unsupported update channel: ${b}`))},V.orDie),R=V.fn("Installation.upgrade")(function*(J,b){let W=yield*(()=>{if(J==="npm")return O(["npm","install","-g",`${G}@${b}`]);if(J==="pnpm")return O(["pnpm","install","-g",`${G}@${b}`]);if(J==="bun")return O(["bun","install","-g",`${G}@${b}`]);if(J==="curl")return new N({stderr:"Self-update is unavailable for script installations; reinstall QitQode from a trusted package."});return new N({stderr:`Unknown method: ${J}`})})();if(W.code!==0){let w=W.stderr||"";yield*new N({stderr:w})}l.info("upgraded",{method:J,target:b,stdout:W.stdout,stderr:W.stderr}),yield*_([process.execPath,"--version"])});return L.of({info:V.fn("Installation.info")(function*(){return{version:m,latest:yield*X()}}),method:K,latest:X,upgrade:R})})),Uo=bo.pipe(B.provide(t.layer),B.provide(oo));var C=o.lazy(()=>o.union([o.string(),o.number(),o.boolean(),o.null(),o.array(C),o.record(o.string(),C)])),jo=o.object({input:o.number(),output:o.number(),cache_read:o.number().optional(),cache_write:o.number().optional(),context_over_200k:o.object({input:o.number(),output:o.number(),cache_read:o.number().optional(),cache_write:o.number().optional()}).optional()}),d=o.object({id:o.string(),name:o.string(),family:o.string().optional(),release_date:o.string(),attachment:o.boolean(),reasoning:o.boolean(),temperature:o.boolean().optional(),tool_call:o.boolean(),interleaved:o.union([o.literal(!0),o.object({field:o.enum(["reasoning_content","reasoning_details"])}).strict()]).optional(),cost:jo.optional(),limit:o.object({context:o.number(),input:o.number().optional(),output:o.number()}),modalities:o.object({input:o.array(o.enum(["text","audio","image","video","pdf"])),output:o.array(o.enum(["text","audio","image","video","pdf"]))}).optional(),experimental:o.object({modes:o.record(o.string(),o.object({cost:jo.optional(),provider:o.object({body:o.record(o.string(),C).optional(),headers:o.record(o.string(),o.string()).optional()}).optional()})).optional()}).optional(),status:o.enum(["alpha","beta","deprecated"]).optional(),provider:o.object({npm:o.string().optional(),api:o.string().optional()}).optional()}),g=o.object({api:o.string().optional(),name:o.string(),env:o.array(o.string()),id:o.string(),npm:o.string().optional(),models:o.record(o.string(),d)});var h=T.create({service:"models.dev"}),Jo=xo(),Y=Do.join(_o.Path.cache,Jo==="https://models.dev"?"models.json":`models-${Zo.fast(Jo)}.json`),Po=300000,$o=8388608,H,po=o.record(o.string(),g),Bo=d,Lo=g;function xo(){return y.QITQODE_MODELS_URL||"https://models.dev"}function To(){return Date.now()-Number(P.stat(Y)?.mtimeMs??0)<Po}function Vo(i){return!i&&To()}function S(i){let n=po.parse(typeof i==="string"?JSON.parse(i):i);for(let[j,Z]of Object.entries(n))if(Z.id!==j)throw Error(`Invalid model provider: ${j}`);return n}async function Wo(i){let n=await P.readJson(i).catch(()=>{return});if(!n)return;try{return S(n)}catch(j){h.warn("Ignoring invalid model catalog cache",{file:i,error:j});return}}async function yo(i,n,j=$o){let Z=i.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if(Z!=="application/json"&&!Z?.endsWith("+json"))throw Error(`Invalid model catalog content type: ${Z||"missing"}`);let $=Number(i.headers.get("content-length"));if(Number.isFinite($)&&$>j)throw Error("Model catalog response is too large");if(!i.body)return"";let _=i.body.getReader(),O=()=>void _.cancel(n.reason);n.addEventListener("abort",O,{once:!0});let K=new Uint8Array(j),X=0;try{for(;;){let R=await _.read();if(R.done)break;if(X+=R.value.byteLength,X>j)throw await _.cancel(),Error("Model catalog response is too large");K.set(R.value,X-R.value.byteLength)}}finally{n.removeEventListener("abort",O)}return new TextDecoder().decode(K.subarray(0,X))}var Xo=async()=>{let i=AbortSignal.timeout(1e4),n=await fetch(`${xo()}/api.json`,{headers:{"User-Agent":z.USER_AGENT},signal:i});if(!n.ok)return;let j=S(await yo(n,i));return JSON.stringify(j)},D=Qo(async()=>{let i=await Wo(y.QITQODE_MODELS_PATH??Y);if(i)return i;let n=await import("./chunk-zt8kghd2.js").then((j)=>S(j.snapshot)).catch(()=>{return});if(n)return n;if(y.QITQODE_DISABLE_MODELS_FETCH)return{};return E.withLock(`models-dev:${Y}`,async()=>{let j=await Wo(y.QITQODE_MODELS_PATH??Y);if(j)return j;let Z=await Xo();if(Z)return await P.write(Y,Z).catch(($)=>{h.error("Failed to write models cache",{error:$})}),S(Z);return{}})});async function So(){return D()}async function u(i=!1){if(Vo(i))return D.reset();await E.withLock(`models-dev:${Y}`,async()=>{if(Vo(i))return D.reset();let n=await Xo();if(!n)return;await P.write(Y,n),D.reset()}).catch((n)=>{h.error("Failed to fetch models.dev",{error:n})})}function Io(){if(H||y.QITQODE_DISABLE_MODELS_FETCH||process.argv.includes("--get-yargs-completions"))return;u(),H=setInterval(async()=>{await u()},3600000),H.unref()}function vo(){if(!H)return;clearInterval(H),H=void 0}
2
+ import{$l as M,Vl as A,Wl as e,Xl as oo,Yl as io}from"./chunk-50aznc8e.js";import{hp as Oo}from"./chunk-w8xaw2dv.js";import{rp as Qo}from"./chunk-jfy6bfvv.js";import{Or as F,Pr as s,Vr as q,Wr as t}from"./chunk-3nc9wy1m.js";import{$s as E,Gs as m,Hs as k,_s as Zo,ct as _o,dt as y,mt as T}from"./chunk-p20ft5mj.js";import{Gt as P}from"./chunk-b5x3zghc.js";import{It as o}from"./chunk-tk6gjy9d.js";import{$H as V,AO as v,BN as U,TF as I,jD as r,yF as B}from"./chunk-meaa7wrs.js";import{lP as Yo,nP as a,pP as zo}from"./chunk-fa03gsff.js";var Fo={};a(Fo,{stopRefresh:()=>vo,startRefresh:()=>Io,refresh:()=>u,readModelCatalogResponse:()=>yo,get:()=>So,Provider:()=>Lo,Model:()=>Bo,MODEL_CATALOG_MAX_BYTES:()=>$o,Data:()=>D});import Do from"path";var z={};a(z,{layer:()=>bo,isPreview:()=>qo,isNewerVersion:()=>no,isLocal:()=>Go,getReleaseType:()=>wo,defaultLayer:()=>Uo,UpgradeFailedError:()=>N,USER_AGENT:()=>Ko,Service:()=>L,Installation:()=>z,Info:()=>Ho,Event:()=>Ro});var f=(i)=>i.pipe(q.retryTransient({retryOn:"errors-and-responses",times:2,schedule:I.exponential(200).pipe(I.jittered)}));import c from"path";var x=Yo(Oo(),1);var l=T.create({service:"installation"}),G="@qitqode/cli";function no(i,n){if(!x.default.valid(i)||!x.default.valid(n))return!1;return x.default.gt(n,i)}var Ro={Updated:M.define("installation.updated",o.object({version:o.string()})),UpdateAvailable:M.define("installation.update-available",o.object({version:o.string()}))};function wo(i,n){if(!no(i,n))throw Error(`Version ${n} is not newer than ${i}`);let j=x.default.major(i),Z=x.default.minor(i),$=x.default.major(n),_=x.default.minor(n);if($>j)return"major";if(_>Z)return"minor";return"patch"}var Ho=o.object({version:o.string(),latest:o.string()}).meta({ref:"InstallationInfo"}),Ko=`qitqode/${k}/${m}/${y.QITQODE_CLIENT}`;function qo(){return k!=="latest"}function Go(){return k==="local"}class N extends U.TaggedErrorClass()("UpgradeFailedError",{stderr:U.String}){}var No=U.Struct({version:U.String});class L extends r.Service()("@qitqode/Installation"){}var bo=B.effect(L,V.gen(function*(){let i=yield*q.HttpClient,n=q.filterStatusOk(f(i)),j=yield*A.ChildProcessSpawner,Z=(J,b)=>e.make(J[0],J.slice(1),{cwd:b?.cwd,env:b?.env,extendEnv:!0}),$=V.fnUntraced(function*(J){let b=yield*io(j,J);return{code:b.code,stdout:b.text,stderr:b.stderr}},V.scoped),_=V.fnUntraced(function*(J,b){let Q=yield*j.spawn(Z(J,b)),W=yield*v.mkString(v.decodeText(Q.stdout));return yield*Q.exitCode,W},V.scoped,V.catch(()=>V.succeed(""))),O=V.fnUntraced(function*(J,b){return yield*$(Z(J,b))},V.catch(()=>V.succeed({code:A.ExitCode(1),stdout:"",stderr:""}))),K=V.fn("Installation.method")(function*(){if(process.execPath.includes(c.join(".qitqode","bin")))return"curl";if(process.execPath.includes(c.join(".local","bin")))return"curl";let J=process.execPath.toLowerCase(),b=[{name:"npm",command:()=>_(["npm","list","-g","--depth=0"])},{name:"pnpm",command:()=>_(["pnpm","list","-g","--depth=0"])},{name:"bun",command:()=>_(["bun","pm","ls","-g"])}];b.sort((Q,W)=>{let w=J.includes(Q.name),p=J.includes(W.name);if(w&&!p)return-1;if(!w&&p)return 1;return 0});for(let Q of b)if((yield*Q.command()).includes(G))return Q.name;return"unknown"}),X=V.fn("Installation.latest")(function*(J){let b=J||(yield*K());if(b==="curl"){let W=(yield*_(["curl","-sI","https://github.com/qitqode/qitqode/releases/latest"])).match(/^location:.*\/tag\/v([0-9][^\s/]*)/im);if(W)return W[1];return yield*V.die(Error("failed to resolve latest version from GitHub releases redirect"))}if(b==="npm"||b==="bun"||b==="pnpm"){let W=(yield*_(["npm","config","get","registry"])).trim()||"https://registry.npmjs.org",w=W.endsWith("/")?W.slice(0,-1):W,p=yield*n.execute(F.get(`${w}/${encodeURIComponent(G)}/${k}`).pipe(F.acceptJson));return(yield*s.schemaBodyJson(No)(p)).version}return l.warn("unsupported update channel, skipping",{method:b}),yield*V.die(Error(`unsupported update channel: ${b}`))},V.orDie),R=V.fn("Installation.upgrade")(function*(J,b){let W=yield*(()=>{if(J==="npm")return O(["npm","install","-g",`${G}@${b}`]);if(J==="pnpm")return O(["pnpm","install","-g",`${G}@${b}`]);if(J==="bun")return O(["bun","install","-g",`${G}@${b}`]);if(J==="curl")return new N({stderr:"Self-update is unavailable for script installations; reinstall QitQode from a trusted package."});return new N({stderr:`Unknown method: ${J}`})})();if(W.code!==0){let w=W.stderr||"";yield*new N({stderr:w})}l.info("upgraded",{method:J,target:b,stdout:W.stdout,stderr:W.stderr}),yield*_([process.execPath,"--version"])});return L.of({info:V.fn("Installation.info")(function*(){return{version:m,latest:yield*X()}}),method:K,latest:X,upgrade:R})})),Uo=bo.pipe(B.provide(t.layer),B.provide(oo));var C=o.lazy(()=>o.union([o.string(),o.number(),o.boolean(),o.null(),o.array(C),o.record(o.string(),C)])),jo=o.object({input:o.number(),output:o.number(),cache_read:o.number().optional(),cache_write:o.number().optional(),context_over_200k:o.object({input:o.number(),output:o.number(),cache_read:o.number().optional(),cache_write:o.number().optional()}).optional()}),d=o.object({id:o.string(),name:o.string(),family:o.string().optional(),release_date:o.string(),attachment:o.boolean(),reasoning:o.boolean(),temperature:o.boolean().optional(),tool_call:o.boolean(),interleaved:o.union([o.literal(!0),o.object({field:o.enum(["reasoning_content","reasoning_details"])}).strict()]).optional(),cost:jo.optional(),limit:o.object({context:o.number(),input:o.number().optional(),output:o.number()}),modalities:o.object({input:o.array(o.enum(["text","audio","image","video","pdf"])),output:o.array(o.enum(["text","audio","image","video","pdf"]))}).optional(),experimental:o.object({modes:o.record(o.string(),o.object({cost:jo.optional(),provider:o.object({body:o.record(o.string(),C).optional(),headers:o.record(o.string(),o.string()).optional()}).optional()})).optional()}).optional(),status:o.enum(["alpha","beta","deprecated"]).optional(),provider:o.object({npm:o.string().optional(),api:o.string().optional()}).optional()}),g=o.object({api:o.string().optional(),name:o.string(),env:o.array(o.string()),id:o.string(),npm:o.string().optional(),models:o.record(o.string(),d)});var h=T.create({service:"models.dev"}),Jo=xo(),Y=Do.join(_o.Path.cache,Jo==="https://models.dev"?"models.json":`models-${Zo.fast(Jo)}.json`),Po=300000,$o=8388608,H,po=o.record(o.string(),g),Bo=d,Lo=g;function xo(){return y.QITQODE_MODELS_URL||"https://models.dev"}function To(){return Date.now()-Number(P.stat(Y)?.mtimeMs??0)<Po}function Vo(i){return!i&&To()}function S(i){let n=po.parse(typeof i==="string"?JSON.parse(i):i);for(let[j,Z]of Object.entries(n))if(Z.id!==j)throw Error(`Invalid model provider: ${j}`);return n}async function Wo(i){let n=await P.readJson(i).catch(()=>{return});if(!n)return;try{return S(n)}catch(j){h.warn("Ignoring invalid model catalog cache",{file:i,error:j});return}}async function yo(i,n,j=$o){let Z=i.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if(Z!=="application/json"&&!Z?.endsWith("+json"))throw Error(`Invalid model catalog content type: ${Z||"missing"}`);let $=Number(i.headers.get("content-length"));if(Number.isFinite($)&&$>j)throw Error("Model catalog response is too large");if(!i.body)return"";let _=i.body.getReader(),O=()=>void _.cancel(n.reason);n.addEventListener("abort",O,{once:!0});let K=new Uint8Array(j),X=0;try{for(;;){let R=await _.read();if(R.done)break;if(X+=R.value.byteLength,X>j)throw await _.cancel(),Error("Model catalog response is too large");K.set(R.value,X-R.value.byteLength)}}finally{n.removeEventListener("abort",O)}return new TextDecoder().decode(K.subarray(0,X))}var Xo=async()=>{let i=AbortSignal.timeout(1e4),n=await fetch(`${xo()}/api.json`,{headers:{"User-Agent":z.USER_AGENT},signal:i});if(!n.ok)return;let j=S(await yo(n,i));return JSON.stringify(j)},D=Qo(async()=>{let i=await Wo(y.QITQODE_MODELS_PATH??Y);if(i)return i;let n=await import("./chunk-zt8kghd2.js").then((j)=>S(j.snapshot)).catch(()=>{return});if(n)return n;if(y.QITQODE_DISABLE_MODELS_FETCH)return{};return E.withLock(`models-dev:${Y}`,async()=>{let j=await Wo(y.QITQODE_MODELS_PATH??Y);if(j)return j;let Z=await Xo();if(Z)return await P.write(Y,Z).catch(($)=>{h.error("Failed to write models cache",{error:$})}),S(Z);return{}})});async function So(){return D()}async function u(i=!1){if(Vo(i))return D.reset();await E.withLock(`models-dev:${Y}`,async()=>{if(Vo(i))return D.reset();let n=await Xo();if(!n)return;await P.write(Y,n),D.reset()}).catch((n)=>{h.error("Failed to fetch models.dev",{error:n})})}function Io(){if(H||y.QITQODE_DISABLE_MODELS_FETCH||process.argv.includes("--get-yargs-completions"))return;u(),H=setInterval(async()=>{await u()},3600000),H.unref()}function vo(){if(!H)return;clearInterval(H),H=void 0}
3
3
  export{f as gl,z as hl,$o as il,Bo as jl,Lo as kl,yo as ll,D as ml,So as nl,u as ol,Io as pl,vo as ql,Fo as rl};
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{a as VB,b as XB}from"./chunk-9a5nck3f.js";import"./chunk-knwayz0m.js";import"./chunk-f72j5yx8.js";import{z as BB}from"./chunk-39h565hz.js";import{A as t,C as r}from"./chunk-3w60y2x5.js";import{G as e}from"./chunk-wnjg8mmh.js";import{L as JB}from"./chunk-hnzs3ywg.js";import"./chunk-9g05wsae.js";import"./chunk-x1dfc7qd.js";import{Od as s}from"./chunk-wmmck56g.js";import{Lf as p,Mf as T,Nf as R,Of as g}from"./chunk-6tjghyx6.js";import{Sf as H}from"./chunk-ntmn6epc.js";import{zg as o}from"./chunk-pn77fh9b.js";import{qh as x}from"./chunk-1qw3yh13.js";import"./chunk-ckhhm2m8.js";import{Bh as i}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{Dj as L,Vk as a,Wj as n}from"./chunk-q39h31te.js";import"./chunk-0x0a51w3.js";import{Ol 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{Es as I}from"./chunk-thbjhgw0.js";import{Js as d,Ks as v,Ls as f,Ns as c,Xs as l,gt as F}from"./chunk-v7yvnnmr.js";import{Dt as u,Ft as N,pt as y}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{$H as D}from"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import{pP as E}from"./chunk-fa03gsff.js";import k from"path";import{fileURLToPath as $B}from"url";import{writeHeapSnapshot as zB}from"v8";import WB,{EOL as K}from"os";var YB={free:"free",default:"default",fast:"fast",economy:"economical",power:"power"};function HB(B){for(let[V,X]of Object.entries(YB))if(B[V]){let Z=I[X];if(Z)return`${Z.providerID}/${Z.modelID}`}return}function GB(B){return async(X,Z)=>{let Y=new Request(X,Z),W=Y.body?await Y.text():void 0,$=await B.call("fetch",{url:Y.url,method:Y.method,headers:Object.fromEntries(Y.headers.entries()),body:W});return new Response($.body,{status:$.status,headers:$.headers})}}function KB(B){return{subscribe:async(V)=>{return B.on("global.event",(X)=>{V(X)})}}}async function MB(){if(typeof globalThis.QITQODE_WORKER_PATH<"u")return globalThis.QITQODE_WORKER_PATH;let B=new URL("./cli/cmd/tui/worker.js",import.meta.url);if(await u($B(B)))return B;return new URL("./worker.ts",import.meta.url)}async function QB(B){let V=process.stdin.isTTY?void 0:await Bun.stdin.text();if(!B)return V;if(!V)return B;return V+`
3
- `+B}async function O(B){let V=i({baseUrl:B.url,fetch:B.fetch,directory:B.directory}),X=[{permission:"question",action:"deny",pattern:"*"},{permission:"plan_enter",action:"deny",pattern:"*"},{permission:"plan_exit",action:"deny",pattern:"*"}],Y=(await V.session.create({permission:X})).data?.id;if(!Y){H.error("headless: failed to create session");return}let W=await V.event.subscribe(),$=JB({sessionID:Y,query:async()=>{return(await V.session.status()).data?.[Y]}}),A=W.stream[Symbol.asyncIterator](),b=$.completion.then(()=>"DONE");(async()=>{try{while(!0){let z=await Promise.race([A.next(),b]);if(z==="DONE")break;let S=z;if(S.done)break;let M=S.value;$.onEvent(M);let G=M.properties;if(M.type==="message.part.updated"){let J=G?.part;if(!J||J.sessionID!==Y)continue;if(J.type==="text"&&J.time?.end){let q=String(J.text??"").trim();if(q)process.stdout.write(q+K)}}if(M.type==="permission.asked"){if(!G||G.sessionID!==Y)continue;await V.permission.reply({requestID:String(G.id),reply:"once"})}if(M.type==="session.error"){if(!G||G.sessionID!==Y||!G.error)continue;let J=G.error,q=J?.data!==null&&typeof J?.data==="object"&&"message"in J.data?String(J.data.message):String(J?.name??J);H.error(q)}}}finally{$.stop(),await A.return?.(void 0).catch(()=>{})}})().catch((z)=>{console.error(z),process.exit(1)});let P=B.model?a.parseModel(B.model):void 0;await V.session.prompt({sessionID:Y,agent:B.agent,model:P,parts:[{type:"text",text:B.prompt}]}),$.markStarted(),await $.completion}var uB=s({command:"$0 [project]",describe:"start qitqode tui",builder:(B)=>p(B).positional("project",{type:"string",describe:"path to start qitqode in"}).options(g).option("never-ask",{type:"boolean",describe:"start in never-ask mode \u2014 auto-decide without asking (permissions excluded), toggle at runtime with /never-ask",default:!1}).check((V)=>{if(V.dark&&V.light)throw Error("--dark and --light are mutually exclusive");if(V.sso&&!V.headless)throw Error("--sso requires --headless");if(V.sso&&V["api-key"]!==void 0)throw Error("--sso and --api-key are mutually exclusive");let X=Object.keys(YB).filter((Z)=>V[Z]);if(X.length>1)throw Error(`${X.map((Z)=>`--${Z}`).join(" and ")} are mutually exclusive \u2014 choose one tier flag`);if(X.length===1&&V.model)throw Error(`--${X[0]} and --model are mutually exclusive \u2014 use one or the other`);return!0}),handler:async(B)=>{if(B.monochrome)process.env.QITQODE_TUI_ACCESSIBLE="1",process.env.NO_COLOR="1";let V=r();try{t();let X=BB(B);if(X){H.error(X),process.exitCode=1;return}let Z=HB(B)??B.model,Y=N(process.env.PWD??process.cwd()),W=B.project?N(k.isAbsolute(B.project)?B.project:k.join(Y,B.project)):N(process.cwd()),$=h(W);if($){if(B.project){H.error("Cannot start in "+W+": "+$),process.exitCode=1;return}let J=N(WB.homedir());if(h(J)){H.error("Cannot start in "+W+": "+$),process.exitCode=1;return}F.warn("unsafe start directory, falling back to home",{requested:W,home:J}),W=J}let A=await MB();try{process.chdir(W)}catch{H.error("Failed to change directory to "+W);return}let b=N(process.cwd()),m=c({[v]:"worker",[d]:f()}),P=new Worker(A,{env:m});P.onerror=(J)=>{F.error("thread error",{message:J.message,filename:J.filename,lineno:J.lineno,colno:J.colno,error:J.error})};let z=l(P),S=()=>{z.call("reload",void 0).catch((J)=>{F.warn("worker reload failed",{error:y(J)})})};process.on("SIGUSR2",S);let M=!1,G=async()=>{if(M)return;M=!0,process.off("SIGUSR2",S),await n(z.call("shutdown",void 0),5000).catch((J)=>{F.warn("worker shutdown failed",{error:y(J)})}),P.terminate()};try{let J=import("./chunk-p4pc1zdd.js"),q=import("./chunk-xbxgrwvy.js").then(({TuiConfig:C})=>C.get()),U=await QB(B.prompt),ZB=await q;if(B.headless&&T(R(B))){H.error("--headless cannot be combined with network-listener flags (--port, --hostname, --mdns)"),process.exitCode=1;return}let w=R(B),_=T(w)?{url:(await z.call("server",w)).url,fetch:void 0,events:void 0}:{url:"http://qitqode.internal",fetch:GB(z),events:KB(z)};if(setTimeout(()=>{z.call("checkUpgrade",{directory:b}).catch(()=>{})},1000).unref?.(),B.headless){if(!U){H.error("--headless requires a prompt: pass --prompt or pipe input via stdin"),process.exitCode=1;return}if(B.sso){try{let Q=await o({tryOpen:!1,onCode:(j)=>{if(process.stdout.write(K),process.stdout.write(" To sign in, open: "+j.verificationUri+K),process.stdout.write(" and enter code: "+j.userCode+K),j.verificationUriComplete)process.stdout.write(K+" Or open this link directly:"+K+" "+j.verificationUriComplete+K);process.stdout.write(K+" Waiting for approval... (ctrl+c to cancel)"+K)}});await x.runPromise(D.gen(function*(){yield*(yield*L.Service).set("forgewise",e(Q,{rotateRefreshToken:!0}))})),process.stdout.write(" Signed in as "+(Q.name||Q.email)+K)}catch(Q){H.error("SSO sign-in failed: "+y(Q)),process.exitCode=1;return}await O({url:_.url,fetch:_.fetch,prompt:U,model:Z,agent:B.agent,directory:b});return}let C=VB(typeof B["api-key"]==="string"?String(B["api-key"]):"");if(C)await x.runPromise(XB(C));else if(!await x.runPromise(D.gen(function*(){return!!(yield*(yield*L.Service).get("forgewise"))}))){H.error(`Not signed in. Use one of:
2
+ import{a as VB,b as XB}from"./chunk-6pe3xzkk.js";import"./chunk-2bbvvh0d.js";import"./chunk-f72j5yx8.js";import{z as BB}from"./chunk-39h565hz.js";import{A as t,C as r}from"./chunk-3w60y2x5.js";import{G as e}from"./chunk-zbvf09bm.js";import{L as JB}from"./chunk-hnzs3ywg.js";import"./chunk-9g05wsae.js";import"./chunk-x1dfc7qd.js";import{Od as s}from"./chunk-wmmck56g.js";import{Lf as p,Mf as T,Nf as R,Of as g}from"./chunk-18xhxdsh.js";import{Sf as H}from"./chunk-ntmn6epc.js";import{zg as o}from"./chunk-cckshvkb.js";import{qh as x}from"./chunk-0jv8r99k.js";import"./chunk-th189x63.js";import{Bh as i}from"./chunk-k6eyc1wv.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 L,Vk as a,Wj as n}from"./chunk-3f6t3wde.js";import"./chunk-b5h8vd5n.js";import{Ol as h}from"./chunk-jee9y4t0.js";import"./chunk-50aznc8e.js";import"./chunk-c4x99ayd.js";import"./chunk-73d0dy03.js";import"./chunk-ha5qct06.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-ds162xgb.js";import"./chunk-jfy6bfvv.js";import"./chunk-2p6w3w8f.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-2bxy8zm1.js";import"./chunk-qq9pvscd.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import{Es as I}from"./chunk-thbjhgw0.js";import{Js as d,Ks as v,Ls as f,Ns as c,Xs as l,gt as F}from"./chunk-p20ft5mj.js";import{Dt as u,Ft as N,pt as y}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{$H as D}from"./chunk-meaa7wrs.js";import"./chunk-0ddhkapd.js";import"./chunk-gvj8qg7x.js";import{pP as E}from"./chunk-fa03gsff.js";import k from"path";import{fileURLToPath as $B}from"url";import{writeHeapSnapshot as zB}from"v8";import WB,{EOL as K}from"os";var YB={free:"free",default:"default",fast:"fast",economy:"economical",power:"power"};function HB(B){for(let[V,X]of Object.entries(YB))if(B[V]){let Z=I[X];if(Z)return`${Z.providerID}/${Z.modelID}`}return}function GB(B){return async(X,Z)=>{let Y=new Request(X,Z),W=Y.body?await Y.text():void 0,$=await B.call("fetch",{url:Y.url,method:Y.method,headers:Object.fromEntries(Y.headers.entries()),body:W});return new Response($.body,{status:$.status,headers:$.headers})}}function KB(B){return{subscribe:async(V)=>{return B.on("global.event",(X)=>{V(X)})}}}async function MB(){if(typeof globalThis.QITQODE_WORKER_PATH<"u")return globalThis.QITQODE_WORKER_PATH;let B=new URL("./cli/cmd/tui/worker.js",import.meta.url);if(await u($B(B)))return B;return new URL("./worker.ts",import.meta.url)}async function QB(B){let V=process.stdin.isTTY?void 0:await Bun.stdin.text();if(!B)return V;if(!V)return B;return V+`
3
+ `+B}async function O(B){let V=i({baseUrl:B.url,fetch:B.fetch,directory:B.directory}),X=[{permission:"question",action:"deny",pattern:"*"},{permission:"plan_enter",action:"deny",pattern:"*"},{permission:"plan_exit",action:"deny",pattern:"*"}],Y=(await V.session.create({permission:X})).data?.id;if(!Y){H.error("headless: failed to create session");return}let W=await V.event.subscribe(),$=JB({sessionID:Y,query:async()=>{return(await V.session.status()).data?.[Y]}}),A=W.stream[Symbol.asyncIterator](),b=$.completion.then(()=>"DONE");(async()=>{try{while(!0){let z=await Promise.race([A.next(),b]);if(z==="DONE")break;let S=z;if(S.done)break;let M=S.value;$.onEvent(M);let G=M.properties;if(M.type==="message.part.updated"){let J=G?.part;if(!J||J.sessionID!==Y)continue;if(J.type==="text"&&J.time?.end){let q=String(J.text??"").trim();if(q)process.stdout.write(q+K)}}if(M.type==="permission.asked"){if(!G||G.sessionID!==Y)continue;await V.permission.reply({requestID:String(G.id),reply:"once"})}if(M.type==="session.error"){if(!G||G.sessionID!==Y||!G.error)continue;let J=G.error,q=J?.data!==null&&typeof J?.data==="object"&&"message"in J.data?String(J.data.message):String(J?.name??J);H.error(q)}}}finally{$.stop(),await A.return?.(void 0).catch(()=>{})}})().catch((z)=>{console.error(z),process.exit(1)});let P=B.model?a.parseModel(B.model):void 0;await V.session.prompt({sessionID:Y,agent:B.agent,model:P,parts:[{type:"text",text:B.prompt}]}),$.markStarted(),await $.completion}var uB=s({command:"$0 [project]",describe:"start qitqode tui",builder:(B)=>p(B).positional("project",{type:"string",describe:"path to start qitqode in"}).options(g).option("never-ask",{type:"boolean",describe:"start in never-ask mode \u2014 auto-decide without asking (permissions excluded), toggle at runtime with /never-ask",default:!1}).check((V)=>{if(V.dark&&V.light)throw Error("--dark and --light are mutually exclusive");if(V.sso&&!V.headless)throw Error("--sso requires --headless");if(V.sso&&V["api-key"]!==void 0)throw Error("--sso and --api-key are mutually exclusive");let X=Object.keys(YB).filter((Z)=>V[Z]);if(X.length>1)throw Error(`${X.map((Z)=>`--${Z}`).join(" and ")} are mutually exclusive \u2014 choose one tier flag`);if(X.length===1&&V.model)throw Error(`--${X[0]} and --model are mutually exclusive \u2014 use one or the other`);return!0}),handler:async(B)=>{if(B.monochrome)process.env.QITQODE_TUI_ACCESSIBLE="1",process.env.NO_COLOR="1";let V=r();try{t();let X=BB(B);if(X){H.error(X),process.exitCode=1;return}let Z=HB(B)??B.model,Y=N(process.env.PWD??process.cwd()),W=B.project?N(k.isAbsolute(B.project)?B.project:k.join(Y,B.project)):N(process.cwd()),$=h(W);if($){if(B.project){H.error("Cannot start in "+W+": "+$),process.exitCode=1;return}let J=N(WB.homedir());if(h(J)){H.error("Cannot start in "+W+": "+$),process.exitCode=1;return}F.warn("unsafe start directory, falling back to home",{requested:W,home:J}),W=J}let A=await MB();try{process.chdir(W)}catch{H.error("Failed to change directory to "+W);return}let b=N(process.cwd()),m=c({[v]:"worker",[d]:f()}),P=new Worker(A,{env:m});P.onerror=(J)=>{F.error("thread error",{message:J.message,filename:J.filename,lineno:J.lineno,colno:J.colno,error:J.error})};let z=l(P),S=()=>{z.call("reload",void 0).catch((J)=>{F.warn("worker reload failed",{error:y(J)})})};process.on("SIGUSR2",S);let M=!1,G=async()=>{if(M)return;M=!0,process.off("SIGUSR2",S),await n(z.call("shutdown",void 0),5000).catch((J)=>{F.warn("worker shutdown failed",{error:y(J)})}),P.terminate()};try{let J=import("./chunk-wg0849tq.js"),q=import("./chunk-v6kenrks.js").then(({TuiConfig:C})=>C.get()),U=await QB(B.prompt),ZB=await q;if(B.headless&&T(R(B))){H.error("--headless cannot be combined with network-listener flags (--port, --hostname, --mdns)"),process.exitCode=1;return}let w=R(B),_=T(w)?{url:(await z.call("server",w)).url,fetch:void 0,events:void 0}:{url:"http://qitqode.internal",fetch:GB(z),events:KB(z)};if(setTimeout(()=>{z.call("checkUpgrade",{directory:b}).catch(()=>{})},1000).unref?.(),B.headless){if(!U){H.error("--headless requires a prompt: pass --prompt or pipe input via stdin"),process.exitCode=1;return}if(B.sso){try{let Q=await o({tryOpen:!1,onCode:(j)=>{if(process.stdout.write(K),process.stdout.write(" To sign in, open: "+j.verificationUri+K),process.stdout.write(" and enter code: "+j.userCode+K),j.verificationUriComplete)process.stdout.write(K+" Or open this link directly:"+K+" "+j.verificationUriComplete+K);process.stdout.write(K+" Waiting for approval... (ctrl+c to cancel)"+K)}});await x.runPromise(D.gen(function*(){yield*(yield*L.Service).set("forgewise",e(Q,{rotateRefreshToken:!0}))})),process.stdout.write(" Signed in as "+(Q.name||Q.email)+K)}catch(Q){H.error("SSO sign-in failed: "+y(Q)),process.exitCode=1;return}await O({url:_.url,fetch:_.fetch,prompt:U,model:Z,agent:B.agent,directory:b});return}let C=VB(typeof B["api-key"]==="string"?String(B["api-key"]):"");if(C)await x.runPromise(XB(C));else if(!await x.runPromise(D.gen(function*(){return!!(yield*(yield*L.Service).get("forgewise"))}))){H.error(`Not signed in. Use one of:
4
4
  qode auth login (browser / device-code flow)
5
5
  qode auth login --api-key (paste a Qlex API key)
6
6
  --api-key <key> (inline for this run)
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Bd as j}from"./chunk-wmqcz5rb.js";import{Od as Q}from"./chunk-wmmck56g.js";import{Sf as M}from"./chunk-ntmn6epc.js";import{lg as N}from"./chunk-rmmrnx95.js";import{qh as $}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{Sj as J,el as X}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{sp as _}from"./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{Vs as Y,dt as Z}from"./chunk-v7yvnnmr.js";import{Gt as V,vt as E}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";import{EOL as L}from"os";import k from"path";function P(){let q=["-R","-S"];if(process.platform!=="win32")return["less",...q];let z=_("less");if(z){if(V.stat(z)?.size)return[z,...q]}if(Z.QITQODE_GIT_BASH_PATH){let G=k.join(Z.QITQODE_GIT_BASH_PATH,"..","..","usr","bin","less.exe");if(V.stat(G)?.size)return[G,...q]}let B=_("git");if(B){let G=k.join(B,"..","..","usr","bin","less.exe");if(V.stat(G)?.size)return[G,...q]}return["cmd","/c","more"]}var g=Q({command:"session",describe:"manage sessions",builder:(q)=>q.command(T).command(D).command(v).demandCommand(),async handler(){}}),v=Q({command:"import-claude",describe:"import Claude Code sessions (~/.claude/projects) into qitqode",builder:(q)=>q.option("force",{describe:"re-sync every session, ignoring the mtime cache",type:"boolean",default:!1}),handler:async(q)=>{let z=await N.run({force:q.force});M.println(`Claude import: scanned ${z.scanned}, imported ${z.imported}, resynced ${z.resynced}, skipped ${z.skipped}`+(z.errors.length?`, errors ${z.errors.length}`:""));for(let B of z.errors)M.error(B)}}),D=Q({command:"delete <sessionID>",describe:"delete a session",builder:(q)=>{return q.positional("sessionID",{describe:"session ID to delete",type:"string",demandOption:!0})},handler:async(q)=>{await j(process.cwd(),async()=>{let z=J.make(q.sessionID);try{await $.runPromise(X.Service.use((B)=>B.get(z)))}catch{M.error(`Session not found: ${q.sessionID}`),process.exit(1)}await $.runPromise(X.Service.use((B)=>B.remove(z))),M.println(M.Style.TEXT_SUCCESS_BOLD+`Session ${q.sessionID} deleted`+M.Style.TEXT_NORMAL)})}}),T=Q({command:"list",describe:"list sessions",builder:(q)=>{return q.option("max-count",{alias:"n",describe:"limit to N most recent sessions",type:"number"}).option("format",{describe:"output format",type:"string",choices:["table","json"],default:"table"})},handler:async(q)=>{await j(process.cwd(),async()=>{let z=[...X.list({roots:!0,limit:q.maxCount})];if(z.length===0)return;let B;if(q.format==="json")B=f(z);else B=b(z);if(process.stdout.isTTY&&!q.maxCount&&q.format==="table"){let H=E.spawn(P(),{stdin:"pipe",stdout:"inherit",stderr:"inherit"});if(!H.stdin){console.log(B);return}H.stdin.write(B),H.stdin.end(),await H.exited}else console.log(B)})}});function b(q){let z=[],B=Math.max(20,...q.map((K)=>K.id.length)),G=Math.max(25,...q.map((K)=>K.title.length)),H=`Session ID${" ".repeat(B-10)} Title${" ".repeat(G-5)} Updated`;z.push(H),z.push("\u2500".repeat(H.length));for(let K of q){let A=Y.truncate(K.title,G),R=Y.todayTimeOrDateTime(K.time.updated),w=`${K.id.padEnd(B)} ${A.padEnd(G)} ${R}`;z.push(w)}return z.join(L)}function f(q){let z=q.map((B)=>({id:B.id,title:B.title,updated:B.time.updated,created:B.time.created,projectId:B.projectID,directory:B.directory}));return JSON.stringify(z,null,2)}export{T as SessionListCommand,v as SessionImportClaudeCommand,D as SessionDeleteCommand,g as SessionCommand};
2
+ import{Bd as j}from"./chunk-07b36w5g.js";import{Od as Q}from"./chunk-wmmck56g.js";import{Sf as M}from"./chunk-ntmn6epc.js";import{lg as N}from"./chunk-xjdxyeja.js";import{qh as $}from"./chunk-0jv8r99k.js";import"./chunk-th189x63.js";import"./chunk-k6eyc1wv.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{Sj as J,el as X}from"./chunk-3f6t3wde.js";import"./chunk-b5h8vd5n.js";import"./chunk-jee9y4t0.js";import"./chunk-50aznc8e.js";import"./chunk-c4x99ayd.js";import"./chunk-73d0dy03.js";import"./chunk-ha5qct06.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-ds162xgb.js";import"./chunk-jfy6bfvv.js";import{sp as _}from"./chunk-2p6w3w8f.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-2bxy8zm1.js";import"./chunk-qq9pvscd.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import{Vs as Y,dt as Z}from"./chunk-p20ft5mj.js";import{Gt as V,vt as E}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";import{EOL as L}from"os";import k from"path";function P(){let q=["-R","-S"];if(process.platform!=="win32")return["less",...q];let z=_("less");if(z){if(V.stat(z)?.size)return[z,...q]}if(Z.QITQODE_GIT_BASH_PATH){let G=k.join(Z.QITQODE_GIT_BASH_PATH,"..","..","usr","bin","less.exe");if(V.stat(G)?.size)return[G,...q]}let B=_("git");if(B){let G=k.join(B,"..","..","usr","bin","less.exe");if(V.stat(G)?.size)return[G,...q]}return["cmd","/c","more"]}var g=Q({command:"session",describe:"manage sessions",builder:(q)=>q.command(T).command(D).command(v).demandCommand(),async handler(){}}),v=Q({command:"import-claude",describe:"import Claude Code sessions (~/.claude/projects) into qitqode",builder:(q)=>q.option("force",{describe:"re-sync every session, ignoring the mtime cache",type:"boolean",default:!1}),handler:async(q)=>{let z=await N.run({force:q.force});M.println(`Claude import: scanned ${z.scanned}, imported ${z.imported}, resynced ${z.resynced}, skipped ${z.skipped}`+(z.errors.length?`, errors ${z.errors.length}`:""));for(let B of z.errors)M.error(B)}}),D=Q({command:"delete <sessionID>",describe:"delete a session",builder:(q)=>{return q.positional("sessionID",{describe:"session ID to delete",type:"string",demandOption:!0})},handler:async(q)=>{await j(process.cwd(),async()=>{let z=J.make(q.sessionID);try{await $.runPromise(X.Service.use((B)=>B.get(z)))}catch{M.error(`Session not found: ${q.sessionID}`),process.exit(1)}await $.runPromise(X.Service.use((B)=>B.remove(z))),M.println(M.Style.TEXT_SUCCESS_BOLD+`Session ${q.sessionID} deleted`+M.Style.TEXT_NORMAL)})}}),T=Q({command:"list",describe:"list sessions",builder:(q)=>{return q.option("max-count",{alias:"n",describe:"limit to N most recent sessions",type:"number"}).option("format",{describe:"output format",type:"string",choices:["table","json"],default:"table"})},handler:async(q)=>{await j(process.cwd(),async()=>{let z=[...X.list({roots:!0,limit:q.maxCount})];if(z.length===0)return;let B;if(q.format==="json")B=f(z);else B=b(z);if(process.stdout.isTTY&&!q.maxCount&&q.format==="table"){let H=E.spawn(P(),{stdin:"pipe",stdout:"inherit",stderr:"inherit"});if(!H.stdin){console.log(B);return}H.stdin.write(B),H.stdin.end(),await H.exited}else console.log(B)})}});function b(q){let z=[],B=Math.max(20,...q.map((K)=>K.id.length)),G=Math.max(25,...q.map((K)=>K.title.length)),H=`Session ID${" ".repeat(B-10)} Title${" ".repeat(G-5)} Updated`;z.push(H),z.push("\u2500".repeat(H.length));for(let K of q){let A=Y.truncate(K.title,G),R=Y.todayTimeOrDateTime(K.time.updated),w=`${K.id.padEnd(B)} ${A.padEnd(G)} ${R}`;z.push(w)}return z.join(L)}function f(q){let z=q.map((B)=>({id:B.id,title:B.title,updated:B.time.updated,created:B.time.created,projectId:B.projectID,directory:B.directory}));return JSON.stringify(z,null,2)}export{T as SessionListCommand,v as SessionImportClaudeCommand,D as SessionDeleteCommand,g as SessionCommand};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{m as L}from"./chunk-gfm4vad7.js";import"./chunk-3makpbng.js";import{y as K}from"./chunk-8k1q3g8s.js";import{z as N}from"./chunk-39h565hz.js";import{A as F,C as J}from"./chunk-3w60y2x5.js";import"./chunk-wnjg8mmh.js";import"./chunk-jj7wrfty.js";import"./chunk-43xq4p51.js";import{M}from"./chunk-ghmctw8s.js";import"./chunk-3degq6rv.js";import"./chunk-fgqrcjsm.js";import"./chunk-fd1vbz1f.js";import"./chunk-7b69jj5g.js";import"./chunk-x1dfc7qd.js";import{Od as B}from"./chunk-wmmck56g.js";import"./chunk-en7nxqvn.js";import"./chunk-v9sfzkg5.js";import"./chunk-djcsvcby.js";import{Sf as z}from"./chunk-ntmn6epc.js";import"./chunk-5549c7mb.js";import"./chunk-pn77fh9b.js";import"./chunk-ckhhm2m8.js";import"./chunk-tp7sfreh.js";import"./chunk-tz8qhbk9.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-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-gvj8qg7x.js";import"./chunk-fa03gsff.js";var x=B({command:"attach <url>",describe:"attach to a running qitqode server",builder:(j)=>j.positional("url",{type:"string",describe:"http://localhost:4096",demandOption:!0}).option("dir",{type:"string",description:"directory to run in"}).option("continue",{alias:["c"],describe:"continue the last session",type:"boolean"}).option("session",{alias:["s"],type:"string",describe:"session id to continue"}).option("fork",{type:"boolean",describe:"fork the session when continuing (use with --continue or --session)"}).option("password",{alias:["p"],type:"string",describe:"basic auth password (defaults to QITQODE_SERVER_PASSWORD)"}),handler:async(j)=>{let Q=J();try{F();let q=N(j);if(q){z.error(q),process.exitCode=1;return}let R=(()=>{if(!j.dir)return;try{return process.chdir(j.dir),process.cwd()}catch{return j.dir}})(),S=M({password:j.password}),V=await K.get();await L({url:j.url,config:V,args:{continue:j.continue,sessionID:j.session,fork:j.fork},directory:R,headers:S})}finally{Q?.()}}});export{x as AttachCommand};
2
+ import{m as L}from"./chunk-vpp88hhd.js";import"./chunk-a3a9bbk7.js";import{y as K}from"./chunk-40vz0fhv.js";import{z as N}from"./chunk-39h565hz.js";import{A as F,C as J}from"./chunk-3w60y2x5.js";import"./chunk-zbvf09bm.js";import"./chunk-jj7wrfty.js";import"./chunk-43xq4p51.js";import{M}from"./chunk-tcp31yv0.js";import"./chunk-3degq6rv.js";import"./chunk-hf0gny5t.js";import"./chunk-fd1vbz1f.js";import"./chunk-7b69jj5g.js";import"./chunk-x1dfc7qd.js";import{Od as B}from"./chunk-wmmck56g.js";import"./chunk-en7nxqvn.js";import"./chunk-v9sfzkg5.js";import"./chunk-djcsvcby.js";import{Sf as z}from"./chunk-ntmn6epc.js";import"./chunk-1zb95qfx.js";import"./chunk-cckshvkb.js";import"./chunk-th189x63.js";import"./chunk-k6eyc1wv.js";import"./chunk-tz8qhbk9.js";import"./chunk-3f6t3wde.js";import"./chunk-b5h8vd5n.js";import"./chunk-jee9y4t0.js";import"./chunk-50aznc8e.js";import"./chunk-c4x99ayd.js";import"./chunk-73d0dy03.js";import"./chunk-ha5qct06.js";import"./chunk-w8xaw2dv.js";import"./chunk-tq258v8s.js";import"./chunk-ds162xgb.js";import"./chunk-jfy6bfvv.js";import"./chunk-2p6w3w8f.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-2bxy8zm1.js";import"./chunk-qq9pvscd.js";import"./chunk-3nc9wy1m.js";import"./chunk-r8ddb02d.js";import"./chunk-dhvwrrqx.js";import"./chunk-56cty7nr.js";import"./chunk-thbjhgw0.js";import"./chunk-p20ft5mj.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-gvj8qg7x.js";import"./chunk-fa03gsff.js";var x=B({command:"attach <url>",describe:"attach to a running qitqode server",builder:(j)=>j.positional("url",{type:"string",describe:"http://localhost:4096",demandOption:!0}).option("dir",{type:"string",description:"directory to run in"}).option("continue",{alias:["c"],describe:"continue the last session",type:"boolean"}).option("session",{alias:["s"],type:"string",describe:"session id to continue"}).option("fork",{type:"boolean",describe:"fork the session when continuing (use with --continue or --session)"}).option("password",{alias:["p"],type:"string",describe:"basic auth password (defaults to QITQODE_SERVER_PASSWORD)"}),handler:async(j)=>{let Q=J();try{F();let q=N(j);if(q){z.error(q),process.exitCode=1;return}let R=(()=>{if(!j.dir)return;try{return process.chdir(j.dir),process.cwd()}catch{return j.dir}})(),S=M({password:j.password}),V=await K.get();await L({url:j.url,config:V,args:{continue:j.continue,sessionID:j.session,fork:j.fork},directory:R,headers:S})}finally{Q?.()}}});export{x as AttachCommand};
@@ -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-k6eyc1wv.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(`