@qitqode/qitqode-android-arm64 0.2.14 → 0.2.15

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 (77) hide show
  1. package/bun +2 -2
  2. package/bundle/{chunk-6wmtbebc.js → chunk-2fged9vy.js} +1 -1
  3. package/bundle/{chunk-358wdvj7.js → chunk-2pw56zpj.js} +1 -1
  4. package/bundle/{chunk-6kch0q2d.js → chunk-2tkgtasa.js} +1 -1
  5. package/bundle/{chunk-07b4pkk6.js → chunk-4b56k59w.js} +1 -1
  6. package/bundle/{chunk-47jkx37s.js → chunk-4gzggzc0.js} +1 -1
  7. package/bundle/{chunk-fpzkyzny.js → chunk-4jfnhghx.js} +1 -1
  8. package/bundle/{chunk-4hvenszg.js → chunk-4xcwnwd6.js} +1 -1
  9. package/bundle/{chunk-1mfdmm2t.js → chunk-4yd2vvh6.js} +1 -1
  10. package/bundle/{chunk-y1v7mf1a.js → chunk-5asf8f41.js} +72 -72
  11. package/bundle/chunk-5re7995e.js +2 -0
  12. package/bundle/{chunk-nrzca9yd.js → chunk-6k0y2332.js} +1 -1
  13. package/bundle/{chunk-pp10epga.js → chunk-6qwnty59.js} +1 -1
  14. package/bundle/{chunk-fd04358e.js → chunk-6zdzbmzs.js} +298 -297
  15. package/bundle/{chunk-2w79k0mh.js → chunk-76wm7tw8.js} +1 -1
  16. package/bundle/{chunk-k6gdmqff.js → chunk-7t63wz2f.js} +1 -1
  17. package/bundle/{chunk-hx13a8es.js → chunk-83n11xym.js} +1 -1
  18. package/bundle/{chunk-e8s4mp5n.js → chunk-878sb0es.js} +1 -1
  19. package/bundle/{chunk-4p9fny77.js → chunk-8mqcar7f.js} +1 -1
  20. package/bundle/{chunk-j1bv93m4.js → chunk-ae1b15bd.js} +1 -1
  21. package/bundle/{chunk-avzaqy6a.js → chunk-apneazwv.js} +1 -1
  22. package/bundle/{chunk-gnh8c49b.js → chunk-aw5yv01t.js} +1 -1
  23. package/bundle/{chunk-1gdt9q05.js → chunk-b6m5tr80.js} +1 -1
  24. package/bundle/{chunk-7xc73qb1.js → chunk-baq0wk3q.js} +1 -1
  25. package/bundle/{chunk-ffz334ab.js → chunk-c1wc4b5q.js} +1 -1
  26. package/bundle/{chunk-2ascwm7j.js → chunk-csy1v12x.js} +1 -1
  27. package/bundle/{chunk-9z7y4x7q.js → chunk-djdfpezf.js} +1 -1
  28. package/bundle/{chunk-9zsp3qkh.js → chunk-dpbm03yh.js} +1 -1
  29. package/bundle/{chunk-7a4sb6q7.js → chunk-e37gd3p2.js} +1 -1
  30. package/bundle/{chunk-bga4kqd1.js → chunk-estc7tzt.js} +1 -1
  31. package/bundle/{chunk-9gxyt2ay.js → chunk-f0x3q5dj.js} +1 -1
  32. package/bundle/{chunk-vnstr4g1.js → chunk-ffynh19k.js} +1 -1
  33. package/bundle/{chunk-y3dpyz2d.js → chunk-fgr9xshx.js} +1 -1
  34. package/bundle/{chunk-qpggztkq.js → chunk-fswt9qc0.js} +1 -1
  35. package/bundle/{chunk-2g4kxtz0.js → chunk-gww6abk3.js} +1 -1
  36. package/bundle/{chunk-qqsj69m2.js → chunk-h6b5966p.js} +1 -1
  37. package/bundle/{chunk-jvx7jtm4.js → chunk-hmm0gj34.js} +1 -1
  38. package/bundle/{chunk-8b9z8j3z.js → chunk-hmmn62jg.js} +1 -1
  39. package/bundle/{chunk-26e51217.js → chunk-j89sv999.js} +1 -1
  40. package/bundle/{chunk-05bkxat0.js → chunk-k4wfq9cn.js} +1 -1
  41. package/bundle/{chunk-n6pn4f3r.js → chunk-k8dbc1p5.js} +1 -1
  42. package/bundle/{chunk-9thgxbze.js → chunk-k9b4005p.js} +1 -1
  43. package/bundle/{chunk-9znfb8f2.js → chunk-kegvr7wt.js} +1 -1
  44. package/bundle/{chunk-00r3he5x.js → chunk-kht2kwam.js} +1 -1
  45. package/bundle/{chunk-gkf7x1yj.js → chunk-knqpyc7s.js} +1 -1
  46. package/bundle/chunk-mdxtt9wv.js +8 -0
  47. package/bundle/{chunk-8jkqyf9n.js → chunk-mnjz8nqs.js} +1 -1
  48. package/bundle/{chunk-zpjtse0z.js → chunk-mq3w4z8k.js} +2 -2
  49. package/bundle/{chunk-0ks20gz1.js → chunk-mreacz8r.js} +1 -1
  50. package/bundle/{chunk-ykvgmje9.js → chunk-n4qbnecw.js} +1 -1
  51. package/bundle/{chunk-gvf6ek9f.js → chunk-pqzx9ha6.js} +1 -1
  52. package/bundle/{chunk-kdqhwa65.js → chunk-q896qkhe.js} +1 -1
  53. package/bundle/{chunk-ngygp66y.js → chunk-qk6jh32z.js} +1 -1
  54. package/bundle/{chunk-6d4xc6br.js → chunk-rk4c0zat.js} +1 -1
  55. package/bundle/{chunk-dn0437c1.js → chunk-rt49c6js.js} +1 -1
  56. package/bundle/{chunk-34yk99ep.js → chunk-tkbjcznz.js} +1 -1
  57. package/bundle/{chunk-7s9msscb.js → chunk-vgmgg994.js} +1 -1
  58. package/bundle/{chunk-chnr7pe5.js → chunk-vsv4p060.js} +1 -1
  59. package/bundle/{chunk-vzkdzhn0.js → chunk-w0t1ajhg.js} +1 -1
  60. package/bundle/{chunk-w4fr00s7.js → chunk-wne3v1fk.js} +1 -1
  61. package/bundle/{chunk-w214dwws.js → chunk-wyavgt96.js} +1 -1
  62. package/bundle/{chunk-ae1g5y4r.js → chunk-xxck1man.js} +1 -1
  63. package/bundle/{chunk-g738e799.js → chunk-y4cz5s3h.js} +1 -1
  64. package/bundle/{chunk-583d91xq.js → chunk-yhpwceqg.js} +1 -1
  65. package/bundle/{chunk-y5ydtbpd.js → chunk-yms3bsm7.js} +1 -1
  66. package/bundle/{chunk-wmj3xndt.js → chunk-ytfq6rn9.js} +1 -1
  67. package/bundle/{chunk-qz20b42s.js → chunk-yvtkx4x4.js} +1 -1
  68. package/bundle/{chunk-jwv6fda1.js → chunk-ywj77e0m.js} +1 -1
  69. package/bundle/{chunk-y18ptwk2.js → chunk-z93n3cbm.js} +1 -1
  70. package/bundle/{chunk-6y0wgz2j.js → chunk-zbt53cb5.js} +1 -1
  71. package/bundle/{chunk-bm8azfnt.js → chunk-zhhcfqhh.js} +1 -1
  72. package/bundle/{chunk-2q78bdtj.js → chunk-zwxp07yc.js} +1 -1
  73. package/bundle/index.js +3 -3
  74. package/bundle/worker.js +1 -1
  75. package/package.json +1 -1
  76. package/bundle/chunk-1a08ffyd.js +0 -2
  77. package/bundle/chunk-jvvctqjd.js +0 -8
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{fg as a,gg as b,hg as c,ig as d,jg as e}from"./chunk-g738e799.js";import"./chunk-583d91xq.js";import"./chunk-e8s4mp5n.js";import"./chunk-9gxyt2ay.js";import"./chunk-5qhsfjzq.js";import"./chunk-nfg7nt13.js";import"./chunk-4s1n38ds.js";import"./chunk-2w79k0mh.js";import"./chunk-fd04358e.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import"./chunk-y1v7mf1a.js";import"./chunk-358wdvj7.js";import"./chunk-dn0437c1.js";import"./chunk-47jkx37s.js";import"./chunk-31a47ptm.js";import"./chunk-jwv6fda1.js";import"./chunk-hx13a8es.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-j1bv93m4.js";import"./chunk-pp10epga.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-9znfb8f2.js";import"./chunk-6kch0q2d.js";import"./chunk-6cztstry.js";import"./chunk-1mfdmm2t.js";import"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-1a08ffyd.js";import"./chunk-8jkqyf9n.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import"./chunk-sh03ka27.js";export{c as url,b as openapi,d as listen,e as Server,a as Default};
2
+ import{fg as a,gg as b,hg as c,ig as d,jg as e}from"./chunk-y4cz5s3h.js";import"./chunk-yhpwceqg.js";import"./chunk-878sb0es.js";import"./chunk-f0x3q5dj.js";import"./chunk-5qhsfjzq.js";import"./chunk-nfg7nt13.js";import"./chunk-4s1n38ds.js";import"./chunk-76wm7tw8.js";import"./chunk-6zdzbmzs.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import"./chunk-5asf8f41.js";import"./chunk-2pw56zpj.js";import"./chunk-rt49c6js.js";import"./chunk-4gzggzc0.js";import"./chunk-31a47ptm.js";import"./chunk-ywj77e0m.js";import"./chunk-83n11xym.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-ae1b15bd.js";import"./chunk-6qwnty59.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-kegvr7wt.js";import"./chunk-2tkgtasa.js";import"./chunk-6cztstry.js";import"./chunk-4yd2vvh6.js";import"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-5re7995e.js";import"./chunk-mnjz8nqs.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import"./chunk-sh03ka27.js";export{c as url,b as openapi,d as listen,e as Server,a as Default};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ah as M}from"./chunk-fd04358e.js";import{bl as Y}from"./chunk-y1v7mf1a.js";import{Gs as F}from"./chunk-1mfdmm2t.js";import{et as W}from"./chunk-1a08ffyd.js";import{hu as y}from"./chunk-ffx0cr44.js";import{gI as K}from"./chunk-9kc2th5c.js";import{EOL as b}from"os";import B from"path";var z=W.tiers().map((q)=>({label:q.label,providerID:q.providerID,modelID:q.modelID})),$=Object.fromEntries(W.tiers().map((q)=>[`${q.providerID}/${q.modelID}`,q.label]));function H(q){return new Map((q??[]).map((w)=>[w.id,w]))}function T(q,w,C){return(q instanceof Map?q.get(w):Array.isArray(q)?q.find((Q)=>Q.id===w):void 0)?.models[C]}function N(q,w,C){let J=`${w}/${C}`;if($[J])return $[J];return T(q,w,C)?.name??C}function f(q,w){return q&&w===!0?`${q} (fallback)`:q}function I(q){if(!q.busy||!q.model)return!1;let w=[...q.messages].reverse().find((C)=>C.role==="assistant"&&C.time?.completed===void 0);return w?.providerID===q.model.providerID&&w.modelID===q.model.modelID&&w.freeTierFallback===!0}function D(q,w){let C=W.tiers().find((J)=>J.providerID===q&&J.modelID===w);return C?W.TIER_RATINGS[C.id]:void 0}async function n(q){return M.runPromise(Y.Service.use((w)=>K.gen(function*(){let C=yield*w.get(q),J=yield*w.messages({sessionID:C.id,agentID:"*"});return{info:C,messages:J}})))}function o(){let q=Y.list({limit:1}).next();return q.done?void 0:q.value}function d(q,w){return`session-${q.slice(0,8)}.${w==="markdown"?"md":"json"}`}function E(q,w){return B.resolve(q,w)}async function i(q,w,C){let J=E(q,w);return await y.write(J,C),J}function G(q,w,C){return C.trim()?`[redacted:${q}:${w}]`:C}function U(q,w,C){if(!C)return C;return Object.keys(C).length?{redacted:`${q}:${w}`}:C}function X(q,w){return{...w,value:G("file-text",q,w.value)}}function O(q,w){return w?.map((C,J)=>({...C,file:G(`${q}-file`,String(J),C.file),patch:G(`${q}-patch`,String(J),C.patch)}))}function L(q){if(!q.source)return q.source;if(q.source.type==="symbol")return{...q.source,path:G("file-path",q.id,q.source.path),name:G("file-symbol",q.id,q.source.name),text:X(q.id,q.source.text)};if(q.source.type==="resource")return{...q.source,clientName:G("file-client",q.id,q.source.clientName),uri:G("file-uri",q.id,q.source.uri),text:X(q.id,q.source.text)};return{...q.source,path:G("file-path",q.id,q.source.path),text:X(q.id,q.source.text)}}function x(q){return{...q,url:G("file-url",q.id,q.url),filename:q.filename===void 0?void 0:G("file-name",q.id,q.filename),source:L(q)}}function R(q){switch(q.type){case"text":return{...q,text:G("text",q.id,q.text),metadata:U("text-metadata",q.id,q.metadata)};case"reasoning":return{...q,text:G("reasoning",q.id,q.text),metadata:U("reasoning-metadata",q.id,q.metadata)};case"file":return x(q);case"subtask":return{...q,prompt:G("subtask-prompt",q.id,q.prompt),description:G("subtask-description",q.id,q.description),command:q.command===void 0?void 0:G("subtask-command",q.id,q.command)};case"tool":return{...q,metadata:U("tool-metadata",q.id,q.metadata),state:q.state.status==="pending"?{...q.state,input:U("tool-input",q.id,q.state.input)??q.state.input,raw:G("tool-raw",q.id,q.state.raw)}:q.state.status==="running"?{...q.state,input:U("tool-input",q.id,q.state.input)??q.state.input,title:q.state.title===void 0?void 0:G("tool-title",q.id,q.state.title),metadata:U("tool-state-metadata",q.id,q.state.metadata)}:q.state.status==="completed"?{...q.state,input:U("tool-input",q.id,q.state.input)??q.state.input,output:G("tool-output",q.id,q.state.output),title:G("tool-title",q.id,q.state.title),metadata:U("tool-state-metadata",q.id,q.state.metadata)??q.state.metadata,attachments:q.state.attachments?.map(x)}:{...q.state,input:U("tool-input",q.id,q.state.input)??q.state.input,error:G("tool-error",q.id,q.state.error),metadata:U("tool-state-metadata",q.id,q.state.metadata)}};case"patch":return{...q,hash:G("patch",q.id,q.hash),files:q.files.map((w,C)=>G("patch-file",`${q.id}-${C}`,w))};case"snapshot":return{...q,snapshot:G("snapshot",q.id,q.snapshot)};case"step-start":case"step-finish":return{...q,snapshot:q.snapshot===void 0?void 0:G("snapshot",q.id,q.snapshot)};case"agent":return{...q,source:!q.source?q.source:{...q.source,value:G("agent-source",q.id,q.source.value)}};default:return q}}function s(q){return{info:{...q.info,title:G("session-title",q.info.id,q.info.title),directory:G("session-directory",q.info.id,q.info.directory),summary:!q.info.summary?q.info.summary:{...q.info.summary,diffs:O("session-diff",q.info.summary.diffs)},revert:!q.info.revert?q.info.revert:{...q.info.revert,snapshot:q.info.revert.snapshot===void 0?void 0:G("revert-snapshot",q.info.id,q.info.revert.snapshot),diff:q.info.revert.diff===void 0?void 0:G("revert-diff",q.info.id,q.info.revert.diff)}},messages:q.messages.map((w)=>({info:w.info.role==="user"?{...w.info,system:w.info.system===void 0?void 0:G("system",w.info.id,w.info.system),summary:!w.info.summary?w.info.summary:{...w.info.summary,title:w.info.summary.title===void 0?void 0:G("summary-title",w.info.id,w.info.summary.title),body:w.info.summary.body===void 0?void 0:G("summary-body",w.info.id,w.info.summary.body),diffs:O("message-diff",w.info.summary.diffs)}}:{...w.info,path:{cwd:G("cwd",w.info.id,w.info.path.cwd),root:G("root",w.info.id,w.info.path.root)}},parts:w.parts.map(R)}))}}function e(q,w,C){let J=H(C.providers),Q=`# ${q.title}
2
+ import{Ah as M}from"./chunk-6zdzbmzs.js";import{bl as Y}from"./chunk-5asf8f41.js";import{Gs as F}from"./chunk-4yd2vvh6.js";import{et as W}from"./chunk-5re7995e.js";import{hu as y}from"./chunk-ffx0cr44.js";import{gI as K}from"./chunk-9kc2th5c.js";import{EOL as b}from"os";import B from"path";var z=W.tiers().map((q)=>({label:q.label,providerID:q.providerID,modelID:q.modelID})),$=Object.fromEntries(W.tiers().map((q)=>[`${q.providerID}/${q.modelID}`,q.label]));function H(q){return new Map((q??[]).map((w)=>[w.id,w]))}function T(q,w,C){return(q instanceof Map?q.get(w):Array.isArray(q)?q.find((Q)=>Q.id===w):void 0)?.models[C]}function N(q,w,C){let J=`${w}/${C}`;if($[J])return $[J];return T(q,w,C)?.name??C}function f(q,w){return q&&w===!0?`${q} (fallback)`:q}function I(q){if(!q.busy||!q.model)return!1;let w=[...q.messages].reverse().find((C)=>C.role==="assistant"&&C.time?.completed===void 0);return w?.providerID===q.model.providerID&&w.modelID===q.model.modelID&&w.freeTierFallback===!0}function D(q,w){let C=W.tiers().find((J)=>J.providerID===q&&J.modelID===w);return C?W.TIER_RATINGS[C.id]:void 0}async function n(q){return M.runPromise(Y.Service.use((w)=>K.gen(function*(){let C=yield*w.get(q),J=yield*w.messages({sessionID:C.id,agentID:"*"});return{info:C,messages:J}})))}function o(){let q=Y.list({limit:1}).next();return q.done?void 0:q.value}function d(q,w){return`session-${q.slice(0,8)}.${w==="markdown"?"md":"json"}`}function E(q,w){return B.resolve(q,w)}async function i(q,w,C){let J=E(q,w);return await y.write(J,C),J}function G(q,w,C){return C.trim()?`[redacted:${q}:${w}]`:C}function U(q,w,C){if(!C)return C;return Object.keys(C).length?{redacted:`${q}:${w}`}:C}function X(q,w){return{...w,value:G("file-text",q,w.value)}}function O(q,w){return w?.map((C,J)=>({...C,file:G(`${q}-file`,String(J),C.file),patch:G(`${q}-patch`,String(J),C.patch)}))}function L(q){if(!q.source)return q.source;if(q.source.type==="symbol")return{...q.source,path:G("file-path",q.id,q.source.path),name:G("file-symbol",q.id,q.source.name),text:X(q.id,q.source.text)};if(q.source.type==="resource")return{...q.source,clientName:G("file-client",q.id,q.source.clientName),uri:G("file-uri",q.id,q.source.uri),text:X(q.id,q.source.text)};return{...q.source,path:G("file-path",q.id,q.source.path),text:X(q.id,q.source.text)}}function x(q){return{...q,url:G("file-url",q.id,q.url),filename:q.filename===void 0?void 0:G("file-name",q.id,q.filename),source:L(q)}}function R(q){switch(q.type){case"text":return{...q,text:G("text",q.id,q.text),metadata:U("text-metadata",q.id,q.metadata)};case"reasoning":return{...q,text:G("reasoning",q.id,q.text),metadata:U("reasoning-metadata",q.id,q.metadata)};case"file":return x(q);case"subtask":return{...q,prompt:G("subtask-prompt",q.id,q.prompt),description:G("subtask-description",q.id,q.description),command:q.command===void 0?void 0:G("subtask-command",q.id,q.command)};case"tool":return{...q,metadata:U("tool-metadata",q.id,q.metadata),state:q.state.status==="pending"?{...q.state,input:U("tool-input",q.id,q.state.input)??q.state.input,raw:G("tool-raw",q.id,q.state.raw)}:q.state.status==="running"?{...q.state,input:U("tool-input",q.id,q.state.input)??q.state.input,title:q.state.title===void 0?void 0:G("tool-title",q.id,q.state.title),metadata:U("tool-state-metadata",q.id,q.state.metadata)}:q.state.status==="completed"?{...q.state,input:U("tool-input",q.id,q.state.input)??q.state.input,output:G("tool-output",q.id,q.state.output),title:G("tool-title",q.id,q.state.title),metadata:U("tool-state-metadata",q.id,q.state.metadata)??q.state.metadata,attachments:q.state.attachments?.map(x)}:{...q.state,input:U("tool-input",q.id,q.state.input)??q.state.input,error:G("tool-error",q.id,q.state.error),metadata:U("tool-state-metadata",q.id,q.state.metadata)}};case"patch":return{...q,hash:G("patch",q.id,q.hash),files:q.files.map((w,C)=>G("patch-file",`${q.id}-${C}`,w))};case"snapshot":return{...q,snapshot:G("snapshot",q.id,q.snapshot)};case"step-start":case"step-finish":return{...q,snapshot:q.snapshot===void 0?void 0:G("snapshot",q.id,q.snapshot)};case"agent":return{...q,source:!q.source?q.source:{...q.source,value:G("agent-source",q.id,q.source.value)}};default:return q}}function s(q){return{info:{...q.info,title:G("session-title",q.info.id,q.info.title),directory:G("session-directory",q.info.id,q.info.directory),summary:!q.info.summary?q.info.summary:{...q.info.summary,diffs:O("session-diff",q.info.summary.diffs)},revert:!q.info.revert?q.info.revert:{...q.info.revert,snapshot:q.info.revert.snapshot===void 0?void 0:G("revert-snapshot",q.info.id,q.info.revert.snapshot),diff:q.info.revert.diff===void 0?void 0:G("revert-diff",q.info.id,q.info.revert.diff)}},messages:q.messages.map((w)=>({info:w.info.role==="user"?{...w.info,system:w.info.system===void 0?void 0:G("system",w.info.id,w.info.system),summary:!w.info.summary?w.info.summary:{...w.info.summary,title:w.info.summary.title===void 0?void 0:G("summary-title",w.info.id,w.info.summary.title),body:w.info.summary.body===void 0?void 0:G("summary-body",w.info.id,w.info.summary.body),diffs:O("message-diff",w.info.summary.diffs)}}:{...w.info,path:{cwd:G("cwd",w.info.id,w.info.path.cwd),root:G("root",w.info.id,w.info.path.root)}},parts:w.parts.map(R)}))}}function e(q,w,C){let J=H(C.providers),Q=`# ${q.title}
3
3
 
4
4
  `;Q+=`**Session ID:** ${q.id}
5
5
  `,Q+=`**Created:** ${new Date(q.time.created).toLocaleString()}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{vg as a,wg as b,xg as c}from"./chunk-583d91xq.js";import"./chunk-y1v7mf1a.js";import"./chunk-358wdvj7.js";import"./chunk-dn0437c1.js";import"./chunk-47jkx37s.js";import"./chunk-31a47ptm.js";import"./chunk-jwv6fda1.js";import"./chunk-hx13a8es.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-j1bv93m4.js";import"./chunk-pp10epga.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-9znfb8f2.js";import"./chunk-6kch0q2d.js";import"./chunk-6cztstry.js";import"./chunk-1mfdmm2t.js";import"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-1a08ffyd.js";import"./chunk-8jkqyf9n.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-x0de4z05.js";import"./chunk-sh03ka27.js";export{b as run,a as encodeDir,c as ClaudeImport};
2
+ import{vg as a,wg as b,xg as c}from"./chunk-yhpwceqg.js";import"./chunk-5asf8f41.js";import"./chunk-2pw56zpj.js";import"./chunk-rt49c6js.js";import"./chunk-4gzggzc0.js";import"./chunk-31a47ptm.js";import"./chunk-ywj77e0m.js";import"./chunk-83n11xym.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-ae1b15bd.js";import"./chunk-6qwnty59.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-kegvr7wt.js";import"./chunk-2tkgtasa.js";import"./chunk-6cztstry.js";import"./chunk-4yd2vvh6.js";import"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-5re7995e.js";import"./chunk-mnjz8nqs.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-x0de4z05.js";import"./chunk-sh03ka27.js";export{b as run,a as encodeDir,c as ClaudeImport};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ud as n}from"./chunk-fpzkyzny.js";import{fe as i}from"./chunk-w8nj5ph5.js";import{Ah as r,Ng as y,Og as w,Xg as R,oh as K,ph as X}from"./chunk-fd04358e.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import{Mj as V,Nj as W,Qj as C,Sk as J,Yj as M,bl as Y,cl as F,wk as g}from"./chunk-y1v7mf1a.js";import"./chunk-358wdvj7.js";import{Kl as E,Ml as u}from"./chunk-dn0437c1.js";import"./chunk-47jkx37s.js";import"./chunk-31a47ptm.js";import"./chunk-jwv6fda1.js";import"./chunk-hx13a8es.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-j1bv93m4.js";import"./chunk-pp10epga.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-9znfb8f2.js";import"./chunk-6kch0q2d.js";import"./chunk-6cztstry.js";import{Is as U}from"./chunk-1mfdmm2t.js";import"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-1a08ffyd.js";import{Bt as z,Ct as B,Dt as _,Ft as H}from"./chunk-8jkqyf9n.js";import"./chunk-6yshpz0z.js";import{Yt as S}from"./chunk-5dvy83ms.js";import{mu as oo}from"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import{ZK as x,gI as d}from"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import{AP as P,zP as v}from"./chunk-sh03ka27.js";import{EOL as to}from"os";var I=i({command:"config",describe:"show resolved configuration",builder:(o)=>o,async handler(){await n(process.cwd(),async()=>{let o=await r.runPromise(F.Service.use((e)=>e.get()));process.stdout.write(JSON.stringify(o,null,2)+to)})}});import{EOL as b}from"os";var io=i({command:"search <query>",describe:"search files by query",builder:(o)=>o.positional("query",{type:"string",demandOption:!0,description:"Search query"}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(w.Service.use((t)=>t.search({query:o.query})));process.stdout.write(e.join(b)+b)})}}),ro=i({command:"read <path>",describe:"read file contents as JSON",builder:(o)=>o.positional("path",{type:"string",demandOption:!0,description:"File path to read"}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(w.Service.use((t)=>t.read(o.path)));process.stdout.write(JSON.stringify(e,null,2)+b)})}}),no=i({command:"status",describe:"show file status information",builder:(o)=>o,async handler(){await n(process.cwd(),async()=>{let o=await r.runPromise(w.Service.use((e)=>e.status()));process.stdout.write(JSON.stringify(o,null,2)+b)})}}),so=i({command:"list <path>",describe:"list files in a directory",builder:(o)=>o.positional("path",{type:"string",demandOption:!0,description:"File path to list"}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(w.Service.use((t)=>t.list(o.path)));process.stdout.write(JSON.stringify(e,null,2)+b)})}}),mo=i({command:"tree [dir]",describe:"show directory tree",builder:(o)=>o.positional("dir",{type:"string",description:"Directory to tree",default:process.cwd()}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(y.Service.use((t)=>t.tree({cwd:o.dir,limit:200})));console.log(JSON.stringify(e,null,2))})}}),L=i({command:"file",describe:"file system debugging utilities",builder:(o)=>o.command(ro).command(no).command(so).command(io).command(mo).demandCommand(),async handler(){}});import{EOL as A}from"os";var q=i({command:"lsp",describe:"LSP debugging utilities",builder:(o)=>o.command(ao).command(co).command(lo).demandCommand(),async handler(){}}),ao=i({command:"diagnostics <file>",describe:"get diagnostics for a file",builder:(o)=>o.positional("file",{type:"string",demandOption:!0}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(C.Service.use((t)=>d.gen(function*(){return yield*t.touchFile(o.file,!0),yield*d.sleep(1000),yield*t.diagnostics()})));process.stdout.write(JSON.stringify(e,null,2)+A)})}}),co=i({command:"symbols <query>",describe:"search workspace symbols",builder:(o)=>o.positional("query",{type:"string",demandOption:!0}),async handler(o){await n(process.cwd(),async()=>{let s=[];try{const e=v(s,S.Default.time("symbols"),0);let t=await r.runPromise(C.Service.use((m)=>m.workspaceSymbol(o.query)));process.stdout.write(JSON.stringify(t,null,2)+A)}catch(a){var c=a,l=1}finally{P(s,c,l)}})}}),lo=i({command:"document-symbols <uri>",describe:"get symbols from a document",builder:(o)=>o.positional("uri",{type:"string",demandOption:!0}),async handler(o){await n(process.cwd(),async()=>{let s=[];try{const e=v(s,S.Default.time("document-symbols"),0);let t=await r.runPromise(C.Service.use((m)=>m.documentSymbol(o.uri)));process.stdout.write(JSON.stringify(t,null,2)+A)}catch(a){var c=a,l=1}finally{P(s,c,l)}})}});import{EOL as O}from"os";var k=i({command:"rg",describe:"ripgrep debugging utilities",builder:(o)=>o.command(po).command(uo).command(fo).demandCommand(),async handler(){}}),po=i({command:"tree",describe:"show file tree using ripgrep",builder:(o)=>o.option("limit",{type:"number"}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(y.Service.use((t)=>t.tree({cwd:u.directory,limit:o.limit})));process.stdout.write(e+O)})}}),uo=i({command:"files",describe:"list files using ripgrep",builder:(o)=>o.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(o){await n(process.cwd(),async()=>{let e=await r.runPromise(d.gen(function*(){return yield*(yield*y.Service).files({cwd:u.directory,glob:o.glob?[o.glob]:void 0}).pipe(x.take(o.limit??1/0),x.runCollect,d.map((s)=>[...s]))}));process.stdout.write(e.join(O)+O)})}}),fo=i({command:"search <pattern>",describe:"search file contents using ripgrep",builder:(o)=>o.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(o){await n(process.cwd(),async()=>{let e=await r.runPromise(y.Service.use((t)=>t.search({cwd:u.directory,pattern:o.pattern,glob:o.glob,limit:o.limit})));process.stdout.write(JSON.stringify(e.items,null,2)+O)})}});import{EOL as yo}from"os";var T=i({command:"scrap",describe:"list all known projects",builder:(o)=>o,async handler(){let o=S.Default.time("scrap"),e=await E.list();process.stdout.write(JSON.stringify(e,null,2)+yo),o.stop()}});import{EOL as go}from"os";var $=i({command:"skill",describe:"list all available skills",builder:(o)=>o,async handler(){await n(process.cwd(),async()=>{let o=await r.runPromise(d.gen(function*(){return yield*(yield*R.Service).all()}));process.stdout.write(JSON.stringify(o,null,2)+go)})}});var j=i({command:"snapshot",describe:"snapshot debugging utilities",builder:(o)=>o.command(bo).command(wo).command(So).demandCommand(),async handler(){}}),D=(o)=>n(process.cwd(),async()=>{console.log(await r.runPromise(M.Service.use(o)))}),G=(o)=>o.positional("hash",{type:"string",description:"hash",demandOption:!0}),bo=i({command:"track",describe:"track current snapshot state",async handler(){await D((o)=>o.track())}}),wo=i({command:"patch <hash>",describe:"show patch for a snapshot hash",builder:G,async handler(o){await D((e)=>e.patch(o.hash))}}),So=i({command:"diff <hash>",describe:"show diff for a snapshot hash",builder:G,async handler(o){await D((e)=>e.diff(o.hash))}});import{EOL as h}from"os";import{basename as ho}from"path";var Z=i({command:"agent <name>",describe:"show agent configuration details",builder:(o)=>o.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(o){await n(process.cwd(),async()=>{let e=o.name,t=await r.runPromise(X.Service.use((m)=>m.get(e)));if(!t)process.stderr.write(`Agent ${e} not found, run '${ho(process.execPath)} agent list' to get an agent list`+h),process.exit(1);let s=await Co(t),a=await Oo(t,s),c=o.tool;if(c){let m=s.find((eo)=>eo.id===c);if(!m)process.stderr.write(`Tool ${c} not found for agent ${e}`+h),process.exit(1);if(a[c]===!1)process.stderr.write(`Tool ${c} is disabled for agent ${e}`+h),process.exit(1);let p=vo(o.params),f=await Po(t),N=await m.execute(p,f);process.stdout.write(JSON.stringify({tool:c,input:p,result:N},null,2)+h);return}let l={...t,tools:a};process.stdout.write(JSON.stringify(l,null,2)+h)})}});async function Co(o){return r.runPromise(d.gen(function*(){let e=yield*J.Service,t=yield*K.Service,s=o.model??(yield*e.defaultModel());return yield*t.tools({...s,agent:o})}))}async function Oo(o,e){let t=g.disabled(e.map((a)=>a.id),o.permission),s={};for(let a of e)s[a.id]=!t.has(a.id);return s}function vo(o){if(!o)return{};let e=o.trim();if(e.length===0)return{};let t=(()=>{try{return JSON.parse(e)}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 Po(o){let{session:e,messageID:t}=await r.runPromise(d.gen(function*(){let a=yield*Y.Service,c=yield*a.create({title:`Debug tool run (${o.name})`}),l=V.ascending(),m=o.model?o.model:yield*d.gen(function*(){return yield*(yield*J.Service).defaultModel()}),p=Date.now(),f={id:l,sessionID:c.id,role:"assistant",time:{created:p},parentID:l,modelID:m.modelID,providerID:m.providerID,mode:"debug",agent:o.name,path:{cwd:u.directory,root:u.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};return yield*a.updateMessage(f),{session:c,messageID:l}})),s=g.merge(o.permission,e.permission??[]);return{sessionID:e.id,messageID:t,callID:W.ascending(),agent:o.name,abort:new AbortController().signal,messages:[],metadata:()=>d.void,ask(a){return d.sync(()=>{for(let c of a.patterns)if(g.evaluate(a.permission,c,s).action==="deny")throw new g.DeniedError({ruleset:s})})}}}var Q=i({command:"worker-smoke",describe:"start the TUI background worker and verify it initialises",builder:(o)=>o.option("timeout",{type:"number",describe:"milliseconds to wait for the worker to answer",default:30000}),handler:async(o)=>{let e=typeof globalThis.QITQODE_WORKER_PATH<"u"?globalThis.QITQODE_WORKER_PATH:new URL("../tui/worker.ts",import.meta.url),t=H({[B]:"worker",[z]:_()}),s=new Worker(e,{env:t}),a=new Promise((m,p)=>{s.onerror=(f)=>{p(Error(`worker crashed during startup: ${f.message||String(f.error??"unknown error")}`))},s.addEventListener("close",()=>{p(Error("worker exited before answering ping"))})}),c=new Promise((m,p)=>{setTimeout(()=>p(Error(`worker did not answer ping within ${o.timeout}ms`)),o.timeout)}),l=U(s);try{let m=await Promise.race([l.call("ping",void 0),a,c]);if(m!=="pong")throw Error(`worker answered ping with unexpected reply: ${JSON.stringify(m)}`);console.log("worker initialised: ping ok"),process.exit(0)}catch(m){console.error(m instanceof Error?m.message:String(m)),process.exit(1)}}});var Be=i({command:"debug",describe:"debugging and troubleshooting tools",builder:(o)=>o.command(I).command(q).command(k).command(L).command(T).command($).command(j).command(Z).command(Q).command(Ao).command({command:"wait",describe:"wait indefinitely (for debugging)",async handler(){await n(process.cwd(),async()=>{await new Promise((e)=>setTimeout(e,86400000))})}}).demandCommand(),async handler(){}}),Ao=i({command:"paths",describe:"show global paths (data, config, cache, state)",handler(){for(let[o,e]of Object.entries(oo.Path))console.log(o.padEnd(10),e)}});export{Be as DebugCommand};
2
+ import{Ud as n}from"./chunk-4jfnhghx.js";import{fe as i}from"./chunk-w8nj5ph5.js";import{Ah as r,Ng as y,Og as w,Xg as R,oh as K,ph as X}from"./chunk-6zdzbmzs.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import{Mj as V,Nj as W,Qj as C,Sk as J,Yj as M,bl as Y,cl as F,wk as g}from"./chunk-5asf8f41.js";import"./chunk-2pw56zpj.js";import{Kl as E,Ml as u}from"./chunk-rt49c6js.js";import"./chunk-4gzggzc0.js";import"./chunk-31a47ptm.js";import"./chunk-ywj77e0m.js";import"./chunk-83n11xym.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-ae1b15bd.js";import"./chunk-6qwnty59.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-kegvr7wt.js";import"./chunk-2tkgtasa.js";import"./chunk-6cztstry.js";import{Is as U}from"./chunk-4yd2vvh6.js";import"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-5re7995e.js";import{Bt as z,Ct as B,Dt as _,Ft as H}from"./chunk-mnjz8nqs.js";import"./chunk-6yshpz0z.js";import{Yt as S}from"./chunk-5dvy83ms.js";import{mu as oo}from"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import{ZK as x,gI as d}from"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import{AP as P,zP as v}from"./chunk-sh03ka27.js";import{EOL as to}from"os";var I=i({command:"config",describe:"show resolved configuration",builder:(o)=>o,async handler(){await n(process.cwd(),async()=>{let o=await r.runPromise(F.Service.use((e)=>e.get()));process.stdout.write(JSON.stringify(o,null,2)+to)})}});import{EOL as b}from"os";var io=i({command:"search <query>",describe:"search files by query",builder:(o)=>o.positional("query",{type:"string",demandOption:!0,description:"Search query"}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(w.Service.use((t)=>t.search({query:o.query})));process.stdout.write(e.join(b)+b)})}}),ro=i({command:"read <path>",describe:"read file contents as JSON",builder:(o)=>o.positional("path",{type:"string",demandOption:!0,description:"File path to read"}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(w.Service.use((t)=>t.read(o.path)));process.stdout.write(JSON.stringify(e,null,2)+b)})}}),no=i({command:"status",describe:"show file status information",builder:(o)=>o,async handler(){await n(process.cwd(),async()=>{let o=await r.runPromise(w.Service.use((e)=>e.status()));process.stdout.write(JSON.stringify(o,null,2)+b)})}}),so=i({command:"list <path>",describe:"list files in a directory",builder:(o)=>o.positional("path",{type:"string",demandOption:!0,description:"File path to list"}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(w.Service.use((t)=>t.list(o.path)));process.stdout.write(JSON.stringify(e,null,2)+b)})}}),mo=i({command:"tree [dir]",describe:"show directory tree",builder:(o)=>o.positional("dir",{type:"string",description:"Directory to tree",default:process.cwd()}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(y.Service.use((t)=>t.tree({cwd:o.dir,limit:200})));console.log(JSON.stringify(e,null,2))})}}),L=i({command:"file",describe:"file system debugging utilities",builder:(o)=>o.command(ro).command(no).command(so).command(io).command(mo).demandCommand(),async handler(){}});import{EOL as A}from"os";var q=i({command:"lsp",describe:"LSP debugging utilities",builder:(o)=>o.command(ao).command(co).command(lo).demandCommand(),async handler(){}}),ao=i({command:"diagnostics <file>",describe:"get diagnostics for a file",builder:(o)=>o.positional("file",{type:"string",demandOption:!0}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(C.Service.use((t)=>d.gen(function*(){return yield*t.touchFile(o.file,!0),yield*d.sleep(1000),yield*t.diagnostics()})));process.stdout.write(JSON.stringify(e,null,2)+A)})}}),co=i({command:"symbols <query>",describe:"search workspace symbols",builder:(o)=>o.positional("query",{type:"string",demandOption:!0}),async handler(o){await n(process.cwd(),async()=>{let s=[];try{const e=v(s,S.Default.time("symbols"),0);let t=await r.runPromise(C.Service.use((m)=>m.workspaceSymbol(o.query)));process.stdout.write(JSON.stringify(t,null,2)+A)}catch(a){var c=a,l=1}finally{P(s,c,l)}})}}),lo=i({command:"document-symbols <uri>",describe:"get symbols from a document",builder:(o)=>o.positional("uri",{type:"string",demandOption:!0}),async handler(o){await n(process.cwd(),async()=>{let s=[];try{const e=v(s,S.Default.time("document-symbols"),0);let t=await r.runPromise(C.Service.use((m)=>m.documentSymbol(o.uri)));process.stdout.write(JSON.stringify(t,null,2)+A)}catch(a){var c=a,l=1}finally{P(s,c,l)}})}});import{EOL as O}from"os";var k=i({command:"rg",describe:"ripgrep debugging utilities",builder:(o)=>o.command(po).command(uo).command(fo).demandCommand(),async handler(){}}),po=i({command:"tree",describe:"show file tree using ripgrep",builder:(o)=>o.option("limit",{type:"number"}),async handler(o){await n(process.cwd(),async()=>{let e=await r.runPromise(y.Service.use((t)=>t.tree({cwd:u.directory,limit:o.limit})));process.stdout.write(e+O)})}}),uo=i({command:"files",describe:"list files using ripgrep",builder:(o)=>o.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(o){await n(process.cwd(),async()=>{let e=await r.runPromise(d.gen(function*(){return yield*(yield*y.Service).files({cwd:u.directory,glob:o.glob?[o.glob]:void 0}).pipe(x.take(o.limit??1/0),x.runCollect,d.map((s)=>[...s]))}));process.stdout.write(e.join(O)+O)})}}),fo=i({command:"search <pattern>",describe:"search file contents using ripgrep",builder:(o)=>o.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(o){await n(process.cwd(),async()=>{let e=await r.runPromise(y.Service.use((t)=>t.search({cwd:u.directory,pattern:o.pattern,glob:o.glob,limit:o.limit})));process.stdout.write(JSON.stringify(e.items,null,2)+O)})}});import{EOL as yo}from"os";var T=i({command:"scrap",describe:"list all known projects",builder:(o)=>o,async handler(){let o=S.Default.time("scrap"),e=await E.list();process.stdout.write(JSON.stringify(e,null,2)+yo),o.stop()}});import{EOL as go}from"os";var $=i({command:"skill",describe:"list all available skills",builder:(o)=>o,async handler(){await n(process.cwd(),async()=>{let o=await r.runPromise(d.gen(function*(){return yield*(yield*R.Service).all()}));process.stdout.write(JSON.stringify(o,null,2)+go)})}});var j=i({command:"snapshot",describe:"snapshot debugging utilities",builder:(o)=>o.command(bo).command(wo).command(So).demandCommand(),async handler(){}}),D=(o)=>n(process.cwd(),async()=>{console.log(await r.runPromise(M.Service.use(o)))}),G=(o)=>o.positional("hash",{type:"string",description:"hash",demandOption:!0}),bo=i({command:"track",describe:"track current snapshot state",async handler(){await D((o)=>o.track())}}),wo=i({command:"patch <hash>",describe:"show patch for a snapshot hash",builder:G,async handler(o){await D((e)=>e.patch(o.hash))}}),So=i({command:"diff <hash>",describe:"show diff for a snapshot hash",builder:G,async handler(o){await D((e)=>e.diff(o.hash))}});import{EOL as h}from"os";import{basename as ho}from"path";var Z=i({command:"agent <name>",describe:"show agent configuration details",builder:(o)=>o.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(o){await n(process.cwd(),async()=>{let e=o.name,t=await r.runPromise(X.Service.use((m)=>m.get(e)));if(!t)process.stderr.write(`Agent ${e} not found, run '${ho(process.execPath)} agent list' to get an agent list`+h),process.exit(1);let s=await Co(t),a=await Oo(t,s),c=o.tool;if(c){let m=s.find((eo)=>eo.id===c);if(!m)process.stderr.write(`Tool ${c} not found for agent ${e}`+h),process.exit(1);if(a[c]===!1)process.stderr.write(`Tool ${c} is disabled for agent ${e}`+h),process.exit(1);let p=vo(o.params),f=await Po(t),N=await m.execute(p,f);process.stdout.write(JSON.stringify({tool:c,input:p,result:N},null,2)+h);return}let l={...t,tools:a};process.stdout.write(JSON.stringify(l,null,2)+h)})}});async function Co(o){return r.runPromise(d.gen(function*(){let e=yield*J.Service,t=yield*K.Service,s=o.model??(yield*e.defaultModel());return yield*t.tools({...s,agent:o})}))}async function Oo(o,e){let t=g.disabled(e.map((a)=>a.id),o.permission),s={};for(let a of e)s[a.id]=!t.has(a.id);return s}function vo(o){if(!o)return{};let e=o.trim();if(e.length===0)return{};let t=(()=>{try{return JSON.parse(e)}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 Po(o){let{session:e,messageID:t}=await r.runPromise(d.gen(function*(){let a=yield*Y.Service,c=yield*a.create({title:`Debug tool run (${o.name})`}),l=V.ascending(),m=o.model?o.model:yield*d.gen(function*(){return yield*(yield*J.Service).defaultModel()}),p=Date.now(),f={id:l,sessionID:c.id,role:"assistant",time:{created:p},parentID:l,modelID:m.modelID,providerID:m.providerID,mode:"debug",agent:o.name,path:{cwd:u.directory,root:u.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};return yield*a.updateMessage(f),{session:c,messageID:l}})),s=g.merge(o.permission,e.permission??[]);return{sessionID:e.id,messageID:t,callID:W.ascending(),agent:o.name,abort:new AbortController().signal,messages:[],metadata:()=>d.void,ask(a){return d.sync(()=>{for(let c of a.patterns)if(g.evaluate(a.permission,c,s).action==="deny")throw new g.DeniedError({ruleset:s})})}}}var Q=i({command:"worker-smoke",describe:"start the TUI background worker and verify it initialises",builder:(o)=>o.option("timeout",{type:"number",describe:"milliseconds to wait for the worker to answer",default:30000}),handler:async(o)=>{let e=typeof globalThis.QITQODE_WORKER_PATH<"u"?globalThis.QITQODE_WORKER_PATH:new URL("../tui/worker.ts",import.meta.url),t=H({[B]:"worker",[z]:_()}),s=new Worker(e,{env:t}),a=new Promise((m,p)=>{s.onerror=(f)=>{p(Error(`worker crashed during startup: ${f.message||String(f.error??"unknown error")}`))},s.addEventListener("close",()=>{p(Error("worker exited before answering ping"))})}),c=new Promise((m,p)=>{setTimeout(()=>p(Error(`worker did not answer ping within ${o.timeout}ms`)),o.timeout)}),l=U(s);try{let m=await Promise.race([l.call("ping",void 0),a,c]);if(m!=="pong")throw Error(`worker answered ping with unexpected reply: ${JSON.stringify(m)}`);console.log("worker initialised: ping ok"),process.exit(0)}catch(m){console.error(m instanceof Error?m.message:String(m)),process.exit(1)}}});var Be=i({command:"debug",describe:"debugging and troubleshooting tools",builder:(o)=>o.command(I).command(q).command(k).command(L).command(T).command($).command(j).command(Z).command(Q).command(Ao).command({command:"wait",describe:"wait indefinitely (for debugging)",async handler(){await n(process.cwd(),async()=>{await new Promise((e)=>setTimeout(e,86400000))})}}).demandCommand(),async handler(){}}),Ao=i({command:"paths",describe:"show global paths (data, config, cache, state)",handler(){for(let[o,e]of Object.entries(oo.Path))console.log(o.padEnd(10),e)}});export{Be as DebugCommand};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{fe as q}from"./chunk-w8nj5ph5.js";import{cg as v}from"./chunk-psmwrvqs.js";import{Ah as S}from"./chunk-fd04358e.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import"./chunk-y1v7mf1a.js";import"./chunk-358wdvj7.js";import{Dl as Q,Ml as H}from"./chunk-dn0437c1.js";import"./chunk-47jkx37s.js";import"./chunk-31a47ptm.js";import"./chunk-jwv6fda1.js";import"./chunk-hx13a8es.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-j1bv93m4.js";import"./chunk-pp10epga.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-9znfb8f2.js";import"./chunk-6kch0q2d.js";import"./chunk-6cztstry.js";import"./chunk-1mfdmm2t.js";import{Ps as K}from"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-1a08ffyd.js";import"./chunk-8jkqyf9n.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import"./chunk-sh03ka27.js";var P=q({command:"pr <number>",describe:"fetch and checkout a GitHub PR branch, then run qitqode",builder:(Y)=>Y.positional("number",{type:"number",describe:"PR number to checkout",demandOption:!0}),async handler(Y){await H.provide({directory:process.cwd(),async fn(){if(H.project.vcs!=="git")v.error("Could not find git repository. Please run this command from a git repository."),process.exit(1);let J=Y.number,Z=`pr/${J}`;if(v.println(`Fetching and checking out PR #${J}...`),(await K.run(["gh","pr","checkout",`${J}`,"--branch",Z,"--force"],{nothrow:!0})).code!==0)v.error(`Failed to checkout PR #${J}. Make sure you have gh CLI installed and authenticated.`),process.exit(1);let _=await K.text(["gh","pr","view",`${J}`,"--json","headRepository,headRepositoryOwner,isCrossRepository,headRefName,body"],{nothrow:!0}),V;if(_.code===0){let j=_.text;if(j.trim()){let z=JSON.parse(j);if(z&&z.isCrossRepository&&z.headRepository&&z.headRepositoryOwner){let L=z.headRepositoryOwner.login,W=z.headRepository.name,C=L;if(!(await S.runPromise(Q.Service.use((F)=>F.run(["remote"],{cwd:H.worktree}))).then((F)=>F.text().trim())).split(`
2
+ import{fe as q}from"./chunk-w8nj5ph5.js";import{cg as v}from"./chunk-psmwrvqs.js";import{Ah as S}from"./chunk-6zdzbmzs.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import"./chunk-5asf8f41.js";import"./chunk-2pw56zpj.js";import{Dl as Q,Ml as H}from"./chunk-rt49c6js.js";import"./chunk-4gzggzc0.js";import"./chunk-31a47ptm.js";import"./chunk-ywj77e0m.js";import"./chunk-83n11xym.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-ae1b15bd.js";import"./chunk-6qwnty59.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-kegvr7wt.js";import"./chunk-2tkgtasa.js";import"./chunk-6cztstry.js";import"./chunk-4yd2vvh6.js";import{Ps as K}from"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-5re7995e.js";import"./chunk-mnjz8nqs.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import"./chunk-sh03ka27.js";var P=q({command:"pr <number>",describe:"fetch and checkout a GitHub PR branch, then run qitqode",builder:(Y)=>Y.positional("number",{type:"number",describe:"PR number to checkout",demandOption:!0}),async handler(Y){await H.provide({directory:process.cwd(),async fn(){if(H.project.vcs!=="git")v.error("Could not find git repository. Please run this command from a git repository."),process.exit(1);let J=Y.number,Z=`pr/${J}`;if(v.println(`Fetching and checking out PR #${J}...`),(await K.run(["gh","pr","checkout",`${J}`,"--branch",Z,"--force"],{nothrow:!0})).code!==0)v.error(`Failed to checkout PR #${J}. Make sure you have gh CLI installed and authenticated.`),process.exit(1);let _=await K.text(["gh","pr","view",`${J}`,"--json","headRepository,headRepositoryOwner,isCrossRepository,headRefName,body"],{nothrow:!0}),V;if(_.code===0){let j=_.text;if(j.trim()){let z=JSON.parse(j);if(z&&z.isCrossRepository&&z.headRepository&&z.headRepositoryOwner){let L=z.headRepositoryOwner.login,W=z.headRepository.name,C=L;if(!(await S.runPromise(Q.Service.use((F)=>F.run(["remote"],{cwd:H.worktree}))).then((F)=>F.text().trim())).split(`
3
3
  `).includes(C))await S.runPromise(Q.Service.use((F)=>F.run(["remote","add",C,`https://github.com/${L}/${W}.git`],{cwd:H.worktree}))),v.println(`Added fork remote: ${C}`);let X=z.headRefName;await S.runPromise(Q.Service.use((F)=>F.run(["branch",`--set-upstream-to=${C}/${X}`,Z],{cwd:H.worktree})))}if(z&&z.body){let L=z.body.match(/https:\/\/opncd\.ai\/s\/([a-zA-Z0-9_-]+)/);if(L){let W=L[0];v.println(`Found qitqode session: ${W}`),v.println("Importing session...");let C=await K.text(["qitqode","import",W],{nothrow:!0});if(C.code===0){let X=C.text.trim().match(/Imported session: ([a-zA-Z0-9_-]+)/);if(X)V=X[1],v.println(`Session imported: ${V}`)}}}}}v.println(`Successfully checked out PR #${J} as branch '${Z}'`),v.println(),v.println("Starting qitqode..."),v.println();let D=V?["-s",V]:[],$=await K.spawn(["qitqode",...D],{stdin:"inherit",stdout:"inherit",stderr:"inherit",cwd:process.cwd()}).exited;if($!==0)throw Error(`qitqode exited with code ${$}`)}})}});export{P as PrCommand};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{h as x}from"./chunk-6y0wgz2j.js";import{j as D}from"./chunk-rn3je2hv.js";import{I as A}from"./chunk-9z7y4x7q.js";import{fe as P}from"./chunk-w8nj5ph5.js";import{cg as j}from"./chunk-psmwrvqs.js";import{Dg as R,Eg as S,Fg as k}from"./chunk-9gxyt2ay.js";import{Ah as $}from"./chunk-fd04358e.js";import{wj as B}from"./chunk-y1v7mf1a.js";import{cp as G,ep as W,fp as Y,gp as _,hp as O,ip as b,rp as v,sp as K,xp as F}from"./chunk-pp10epga.js";import{gI as H}from"./chunk-9kc2th5c.js";var X="forgewise",p=(J,z=process.env)=>J.trim()||z.QLEX_API_KEY?.trim()||"",U=(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*B.Service).set(X,{type:"api",key:z,metadata:{method:"api-key"}}),yield*D(j.Style.TEXT_SUCCESS+"Signed in with API key."+j.Style.TEXT_NORMAL)}).pipe(H.withSpan("forgewise.login.apikey"));async function u(){let J=!Y();try{return await S({tryOpen:J,onCode:(z)=>{if(process.stdout.write(`
2
+ import{h as x}from"./chunk-zbt53cb5.js";import{j as D}from"./chunk-rn3je2hv.js";import{I as A}from"./chunk-djdfpezf.js";import{fe as P}from"./chunk-w8nj5ph5.js";import{cg as j}from"./chunk-psmwrvqs.js";import{Dg as R,Eg as S,Fg as k}from"./chunk-f0x3q5dj.js";import{Ah as $}from"./chunk-6zdzbmzs.js";import{wj as B}from"./chunk-5asf8f41.js";import{cp as G,ep as W,fp as Y,gp as _,hp as O,ip as b,rp as v,sp as K,xp as F}from"./chunk-6qwnty59.js";import{gI as H}from"./chunk-9kc2th5c.js";var X="forgewise",p=(J,z=process.env)=>J.trim()||z.QLEX_API_KEY?.trim()||"",U=(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*B.Service).set(X,{type:"api",key:z,metadata:{method:"api-key"}}),yield*D(j.Style.TEXT_SUCCESS+"Signed in with API key."+j.Style.TEXT_NORMAL)}).pipe(H.withSpan("forgewise.login.apikey"));async function u(){let J=!Y();try{return await S({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{Sl as an,Tl as _i,Ul as bn,Vl as Ni,Xl as Yr,Yl as zr}from"./chunk-47jkx37s.js";import{Am as go,Bm as Kn,Cm as lo,Dm as so,Em as _o,Fm as No,Gm as po,Hm as Ao,Im as To,Jm as Ir,Km as Oo,Lm as $o,Mm as Do,Nm as Lr,Om as vo,Pm as dr,Qm as Bo,Rm as Gr,Sm as Jr,Tm as Mr,Um as Sr,Vm as Cr,Wm as Hr,Xm as Qo,Ym as Io,Zl as uo,Zm as Fo,_l as yo,am as er,bm as mr,cm as ur,cn as ui,dm as yr,em as fr,fm as gr,gm as lr,hm as sr,im as _r,jm as Nr,km as pr,lm as Ar,mm as V,nm as Tr,om as Or,pm as $r,qm as Dr,rm as vr,sm as Br,tm as j,um as v,vm as yn,wm as un,xm as Xo,ym as Qr,zm as Z}from"./chunk-31a47ptm.js";import{Jn as Fn,Nn as jn}from"./chunk-j3agzs13.js";import{On as gi}from"./chunk-3152y1q9.js";import{Pn as Mo}from"./chunk-71jmhvef.js";import{Ar as hr,Br as ti,Dr as ni,xr as Wn,yr as hn,zr as Nn}from"./chunk-9znfb8f2.js";import{Er as ri}from"./chunk-6kch0q2d.js";import{Fs as gn}from"./chunk-1mfdmm2t.js";import{ct as ro}from"./chunk-fdmz0502.js";import{gt as Ro}from"./chunk-8jkqyf9n.js";import{Pt as nn,Yt as c}from"./chunk-5dvy83ms.js";import{$t as Xr,cu as qo,du as k,hu as mo,mu as $n}from"./chunk-ffx0cr44.js";import{nu as a}from"./chunk-33mzqyyb.js";import{cA as pn,kA as Jn,yA as Cn}from"./chunk-wfpnv00c.js";import{$E as ln,BC as vn,FF as h,NE as Ko,UE as Xn,VO as N,gI as r,jL as Zr,kK as Uo,nC as cn,oJ as Ln,pF as Ur}from"./chunk-9kc2th5c.js";import{wP as On}from"./chunk-sh03ka27.js";var Vo={};On(Vo,{run:()=>$i});var mn={time_created:j().notNull().$default(()=>Date.now()),time_updated:j().notNull().$onUpdate(()=>Date.now())};var J=un("project",{id:v().$type().primaryKey(),worktree:v().notNull(),vcs:v(),name:v(),icon_url:v(),icon_color:v(),...mn,time_initialized:j(),sandboxes:v({mode:"json"}).notNull().$type(),commands:v({mode:"json"}).$type()});var fn=un("session",{id:v().$type().primaryKey(),project_id:v().$type().notNull().references(()=>J.id,{onDelete:"cascade"}),workspace_id:v().$type(),parent_id:v().$type(),context_from:v().$type(),context_watermark:v().$type(),slug:v().notNull(),directory:v().notNull(),title:v().notNull(),version:v().notNull(),share_url:v(),summary_additions:j(),summary_deletions:j(),summary_files:j(),summary_diffs:v({mode:"json"}).$type(),revert:v({mode:"json"}).$type(),permission:v({mode:"json"}).$type(),...mn,time_compacting:j(),time_archived:j(),last_checkpoint_message_id:v().$type()},(n)=>[yn("session_project_idx").on(n.project_id),yn("session_workspace_idx").on(n.workspace_id),yn("session_parent_idx").on(n.parent_id),yn("session_context_from_idx").on(n.context_from)]),eo=un("message",{id:v().$type().primaryKey(),session_id:v().$type().notNull().references(()=>fn.id,{onDelete:"cascade"}),agent_id:v().notNull().default("main"),...mn,data:v({mode:"json"}).notNull().$type()},(n)=>[yn("message_session_time_created_id_idx").on(n.session_id,n.time_created,n.id),yn("message_session_agent_idx").on(n.session_id,n.agent_id,n.id)]),Yo=un("part",{id:v().$type().primaryKey(),message_id:v().$type().notNull().references(()=>eo.id,{onDelete:"cascade"}),session_id:v().$type().notNull(),...mn,data:v({mode:"json"}).notNull().$type()},(n)=>[yn("part_message_id_id_idx").on(n.message_id,n.id),yn("part_session_idx").on(n.session_id)]),zo=un("todo",{session_id:v().$type().notNull().references(()=>fn.id,{onDelete:"cascade"}),content:v().notNull(),status:v().notNull(),position:j().notNull(),...mn},(n)=>[Xo({columns:[n.session_id,n.position]}),yn("todo_session_idx").on(n.session_id)]),co=un("permission",{project_id:v().primaryKey().references(()=>J.id,{onDelete:"cascade"}),...mn,data:v({mode:"json"}).notNull().$type()});var ko=un("session_share",{session_id:v().primaryKey().references(()=>fn.id,{onDelete:"cascade"}),id:v().notNull(),secret:v().notNull(),url:v().notNull(),...mn});import z from"path";var U=c.create({service:"json-migration"});async function $i(n,o){let i=z.join($n.Path.data,"storage");if(!await mo.exists(i))return U.info("storage directory does not exist, skipping migration"),{projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]};U.info("starting json to sqlite migration",{storageDir:i});let l=performance.now();n.run("PRAGMA journal_mode = WAL"),n.run("PRAGMA synchronous = OFF"),n.run("PRAGMA cache_size = 10000"),n.run("PRAGMA temp_store = MEMORY");let e={projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]},A={sessions:0,todos:0,permissions:0,shares:0},_=e.errors,T=1000,M=Date.now();async function x(f){return qo.scan(f,{cwd:i,absolute:!0})}async function C(f,d,S){let B=S-d,p=Array(B);for(let E=0;E<B;E++)p[E]=mo.readJson(f[d+E]);let G=await Promise.allSettled(p),W=Array(B);for(let E=0;E<G.length;E++){let q=G[E];if(q.status==="fulfilled"){W[E]=q.value;continue}_.push(`failed to read ${f[d+E]}: ${q.reason}`)}return W}function H(f,d,S){if(f.length===0)return 0;try{return n.insert(d).values(f).onConflictDoNothing().run(),f.length}catch(B){return _.push(`failed to migrate ${S} batch: ${B}`),0}}U.info("scanning files...");let[K,$,Q,L,g,s,m]=await Promise.all([x("project/*.json"),x("session/*/*.json"),x("message/*/*.json"),x("part/*/*.json"),x("todo/*.json"),x("permission/*.json"),x("session_share/*.json")]);U.info("file scan complete",{projects:K.length,sessions:$.length,messages:Q.length,parts:L.length,todos:g.length,permissions:s.length,shares:m.length});let y=Math.max(1,K.length+$.length+Q.length+L.length+g.length+s.length+m.length),t=o?.progress,u=0,D=(f,d)=>{u=Math.min(y,u+d),t?.({current:u,total:y,label:f})};t?.({current:u,total:y,label:"starting"}),n.run("BEGIN TRANSACTION");let I=new Set,O=[];for(let f=0;f<K.length;f+=T){let d=Math.min(f+T,K.length),S=await C(K,f,d);O.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=z.basename(K[f+B],".json");I.add(G),O.push({id:G,worktree:p.worktree??"/",vcs:p.vcs,name:p.name??void 0,icon_url:p.icon?.url,icon_color:p.icon?.color,time_created:p.time?.created??M,time_updated:p.time?.updated??M,time_initialized:p.time?.initialized,sandboxes:p.sandboxes??[],commands:p.commands})}e.projects+=H(O,J,"project"),D("projects",d-f)}U.info("migrated projects",{count:e.projects,duration:Math.round(performance.now()-l)});let P=$.map((f)=>z.basename(z.dirname(f))),Y=new Set,en=[];for(let f=0;f<$.length;f+=T){let d=Math.min(f+T,$.length),S=await C($,f,d);en.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=z.basename($[f+B],".json"),W=P[f+B];if(!I.has(W)){A.sessions++;continue}Y.add(G),en.push({id:G,project_id:W,parent_id:p.parentID??null,slug:p.slug??"",directory:p.directory??"",title:p.title??"",version:p.version??"",share_url:p.share?.url??null,summary_additions:p.summary?.additions??null,summary_deletions:p.summary?.deletions??null,summary_files:p.summary?.files??null,summary_diffs:p.summary?.diffs??null,revert:p.revert??null,permission:p.permission??null,time_created:p.time?.created??M,time_updated:p.time?.updated??M,time_compacting:p.time?.compacting??null,time_archived:p.time?.archived??null})}e.sessions+=H(en,fn,"session"),D("sessions",d-f)}if(U.info("migrated sessions",{count:e.sessions}),A.sessions>0)U.warn("skipped orphaned sessions",{count:A.sessions});let sn=[],R=[],kn=new Map;for(let f of Q){let d=z.basename(z.dirname(f));if(!Y.has(d))continue;sn.push(f),R.push(d)}for(let f=0;f<sn.length;f+=T){let d=Math.min(f+T,sn.length),S=await C(sn,f,d),B=Array(S.length),p=0;for(let G=0;G<S.length;G++){let W=S[G];if(!W)continue;let E=sn[f+G],q=z.basename(E,".json"),xn=R[f+G];kn.set(q,xn);let Bn=W;delete Bn.id,delete Bn.sessionID,B[p++]={id:q,session_id:xn,time_created:W.time?.created??M,time_updated:W.time?.updated??M,data:Bn}}B.length=p,e.messages+=H(B,eo,"message"),D("messages",d-f)}U.info("migrated messages",{count:e.messages});for(let f=0;f<L.length;f+=T){let d=Math.min(f+T,L.length),S=await C(L,f,d),B=Array(S.length),p=0;for(let G=0;G<S.length;G++){let W=S[G];if(!W)continue;let E=L[f+G],q=z.basename(E,".json"),xn=z.basename(z.dirname(E)),Bn=kn.get(xn);if(!Bn){_.push(`part missing message session: ${E}`);continue}if(!Y.has(Bn))continue;let wn=W;delete wn.id,delete wn.messageID,delete wn.sessionID,B[p++]={id:q,message_id:xn,session_id:Bn,time_created:W.time?.created??M,time_updated:W.time?.updated??M,data:wn}}B.length=p,e.parts+=H(B,Yo,"part"),D("parts",d-f)}U.info("migrated parts",{count:e.parts});let Tn=g.map((f)=>z.basename(f,".json"));for(let f=0;f<g.length;f+=T){let d=Math.min(f+T,g.length),S=await C(g,f,d),B=[];for(let p=0;p<S.length;p++){let G=S[p];if(!G)continue;let W=Tn[f+p];if(!Y.has(W)){A.todos++;continue}if(!Array.isArray(G)){_.push(`todo not an array: ${g[f+p]}`);continue}for(let E=0;E<G.length;E++){let q=G[E];if(!q?.content||!q?.status)continue;B.push({session_id:W,content:q.content,status:q.status,position:E,time_created:M,time_updated:M})}}e.todos+=H(B,zo,"todo"),D("todos",d-f)}if(U.info("migrated todos",{count:e.todos}),A.todos>0)U.warn("skipped orphaned todos",{count:A.todos});let qn=s.map((f)=>z.basename(f,".json")),Hn=[];for(let f=0;f<s.length;f+=T){let d=Math.min(f+T,s.length),S=await C(s,f,d);Hn.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=qn[f+B];if(!I.has(G)){A.permissions++;continue}Hn.push({project_id:G,data:p})}e.permissions+=H(Hn,co,"permission"),D("permissions",d-f)}if(U.info("migrated permissions",{count:e.permissions}),A.permissions>0)U.warn("skipped orphaned permissions",{count:A.permissions});let Vn=m.map((f)=>z.basename(f,".json")),dn=[];for(let f=0;f<m.length;f+=T){let d=Math.min(f+T,m.length),S=await C(m,f,d);dn.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=Vn[f+B];if(!Y.has(G)){A.shares++;continue}if(!p?.id||!p?.secret||!p?.url){_.push(`session_share missing id/secret/url: ${m[f+B]}`);continue}dn.push({session_id:G,id:p.id,secret:p.secret,url:p.url})}e.shares+=H(dn,ko,"session_share"),D("shares",d-f)}if(U.info("migrated session shares",{count:e.shares}),A.shares>0)U.warn("skipped orphaned session shares",{count:A.shares});if(n.run("COMMIT"),U.info("json migration complete",{projects:e.projects,sessions:e.sessions,messages:e.messages,parts:e.parts,todos:e.todos,permissions:e.permissions,shares:e.shares,errorCount:e.errors.length,duration:Math.round(performance.now()-l)}),e.errors.length>0)U.warn("migration errors",{errors:e.errors.slice(0,20)});return t?.({current:y,total:y,label:"complete"}),e}var In={};On(In,{use:()=>Ce,transaction:()=>xe,textDecoder:()=>re,sumDistinct:()=>rr,sum:()=>or,sql:()=>V,relationsOrderToSQL:()=>Rt,relationsFilterToSQL:()=>Kt,relationToSQL:()=>xt,relationExtrasToSQL:()=>Ht,processRelations:()=>Ct,placeholder:()=>Or,param:()=>Ar,orderSelectedFields:()=>oe,orderByOperators:()=>St,or:()=>lo,operators:()=>Mt,notLike:()=>Gr,notInArray:()=>Ir,notIlike:()=>Mr,notExists:()=>Lr,notBetween:()=>dr,not:()=>so,noopMapper:()=>Nr,noopEncoder:()=>_r,noopDecoder:()=>sr,ne:()=>go,name:()=>gr,min:()=>tr,max:()=>ir,mapUpdateSet:()=>ne,mapResultRow:()=>ht,mapRelationalRow:()=>Jt,mapColumnsInSQLToAlias:()=>it,mapColumnsInAliasedSQLToAlias:()=>rt,lte:()=>Ao,lt:()=>po,like:()=>Bo,l2Distance:()=>Xt,l1Distance:()=>Zt,jaccardDistance:()=>Ut,isWithEnum:()=>bt,isView:()=>vr,isTable:()=>Yi,isSQLWrapper:()=>mr,isNull:()=>Oo,isNotNull:()=>$o,isDriverValueEncoder:()=>lr,isConfig:()=>at,is:()=>Mi,innerProduct:()=>Wt,inArray:()=>To,ilike:()=>Jr,haveSameKeys:()=>jt,hasOwnEntityKind:()=>Ji,hammingDistance:()=>Pt,gte:()=>No,gt:()=>_o,getViewSelectedFields:()=>Ft,getViewName:()=>Br,getTableUniqueName:()=>Xi,getTableName:()=>Zi,getTableLikeName:()=>wt,getTableColumns:()=>Vt,getTableAsAliasSQL:()=>Gt,getOriginalColumnFromAlias:()=>ot,getOrderByOperators:()=>dt,getColumns:()=>qt,getColumnTable:()=>Ci,getColumnNameAndConfig:()=>kt,getChannelPath:()=>li,fillPlaceholders:()=>$r,fieldSelectionToSQL:()=>Lt,extractTablesFromSchema:()=>It,extractExtendedColumnType:()=>mt,exists:()=>Do,eq:()=>Z,entityKind:()=>Gi,effect:()=>He,desc:()=>Io,defineRelationsPart:()=>Qt,defineRelations:()=>Bt,createRelationsHelper:()=>vt,countDistinct:()=>bo,count:()=>fo,cosineDistance:()=>Et,close:()=>Se,buildRelationsParts:()=>Dt,buildRelations:()=>$t,bindIfParam:()=>Qr,between:()=>vo,avgDistinct:()=>nr,avg:()=>ho,assertUnreachable:()=>ct,asc:()=>Qo,arrayOverlaps:()=>Hr,arrayContains:()=>Sr,arrayContained:()=>Cr,applyMixins:()=>zt,and:()=>Kn,aliasedTableColumn:()=>nt,aliasedTable:()=>hi,aliasedRelation:()=>bi,aliasedColumn:()=>ai,WithSubquery:()=>ci,ViewSelectionAliasProxyHandler:()=>ji,ViewBaseConfig:()=>ki,View:()=>Dr,TransactionRollbackError:()=>ft,TableSchema:()=>Ui,TableColumns:()=>Wi,TableAliasProxyHandler:()=>Fi,Table:()=>Pi,Subquery:()=>zi,StringChunk:()=>ur,SQL:()=>yr,RelationsHelperStatic:()=>Ot,RelationsBuilderTable:()=>Tt,RelationsBuilderJunctionColumn:()=>At,RelationsBuilderColumn:()=>pt,RelationTableAliasProxyHandler:()=>wi,Relation:()=>Nt,QueryPromise:()=>tt,Placeholder:()=>Tr,Path:()=>Eo,Param:()=>pr,OriginalName:()=>Ei,One:()=>_t,NotFoundError:()=>Me,NoopLogger:()=>di,Name:()=>fr,Many:()=>st,IsAlias:()=>Ri,FakePrimitiveParam:()=>er,ExtraConfigColumns:()=>Ki,ExtraConfigBuilder:()=>xi,DrizzleQueryError:()=>yt,DrizzleError:()=>ut,DefaultLogger:()=>Li,Count:()=>lt,ConsoleLogWriter:()=>Ii,ColumnTableAliasProxyHandler:()=>Vi,ColumnBuilder:()=>et,ColumnAliasProxyHandler:()=>qi,Column:()=>Si,Client:()=>Mn,CONSTANTS:()=>Yt,BaseName:()=>Hi,AggregatedField:()=>gt});import Di from"crypto";import wo,{existsSync as vi,readdirSync as Bi}from"fs";import{join as Qi}from"path";function jo(n){if(wo.existsSync(`${n.migrationsFolder}/meta/_journal.json`))throw Error('We detected that you have old drizzle-kit migration folders. You must upgrade drizzle-kit and run "drizzle-kit up"');let o=n.migrationsFolder,i=[],l=Bi(o).map((e)=>({path:Qi(o,e,"migration.sql"),name:e})).filter((e)=>vi(e.path));l.sort((e,A)=>e.name.localeCompare(A.name));for(let e of l){let A=e.path,_=e.name.slice(0,14),T=wo.readFileSync(A).toString(),M=T.split("--> statement-breakpoint").map((C)=>{return C}),x=Fo(_);i.push({sql:M,bps:!0,folderMillis:x,hash:Di.createHash("sha256").update(T).digest("hex"),name:e.name})}return i}function ao(n,o){if(Array.isArray(o)||"migrationsJournal"in o){let l=Array.isArray(o)?o:o.migrationsJournal,e=Array.isArray(o)?void 0:o.migrationsTable,A=l.map((_)=>({sql:_.sql.split("--> statement-breakpoint"),folderMillis:_.timestamp,hash:"",bps:!0,name:_.name}));return n.dialect.migrate(A,n.session,{migrationsTable:e})}let i=jo(o);return n.dialect.migrate(i,n.session,o)}function fo(n){return V`count(${n||V.raw("*")})`.mapWith(Number)}function bo(n){return V`count(distinct ${n})`.mapWith(Number)}function ho(n){return V`avg(${n})`.mapWith(String)}function nr(n){return V`avg(distinct ${n})`.mapWith(String)}function or(n){return V`sum(${n})`.mapWith(String)}function rr(n){return V`sum(distinct ${n})`.mapWith(String)}function ir(n){return V`max(${n})`.mapWith(uo(n,yo)?n:String)}function tr(n){return V`min(${n})`.mapWith(uo(n,yo)?n:String)}import oo from"path";var Un={};On(Un,{workspaceID:()=>De,useEffect:()=>Qe,use:()=>Be,make:()=>ve,invalidate:()=>Le,has:()=>Ie,get:()=>xo,directory:()=>no,context:()=>Ho,bind:()=>$e});import{EventEmitter as ie}from"events";var Rn=new ie;var Lo=new Set;function xr(n){return Lo.add(n),()=>{Lo.delete(n)}}async function Go(n){await Promise.allSettled([...Lo].map((o)=>o(n)))}function En(n){return n()}var jr={};On(jr,{setInitialized:()=>se,list:()=>ge,layer:()=>Fr,get:()=>le,fromRow:()=>_n,defaultLayer:()=>Co,UpdateInput:()=>fe,Service:()=>Gn,Info:()=>Vr,Event:()=>wr});import*as F from"fs/promises";import*as cr from"os";import*as Dn from"path";var te=N.String.pipe(N.brand("ProjectID")),w=te.pipe(Fn((n)=>({global:n.make("global"),zod:a.string().pipe(a.custom())})));import*as Qn from"fs/promises";import*as b from"path";import*as Er from"crypto";async function Jo(n){let o=b.resolve(n);while(!0){let i=b.join(o,".git"),l=await Qn.stat(i).catch(()=>null);if(l){if(l.isDirectory())return i;let _=(await Qn.readFile(i,"utf-8")).trim().match(/^gitdir:\s*(.+)$/);if(!_)return null;let T=b.isAbsolute(_[1])?_[1]:b.resolve(o,_[1]);return b.resolve(T,"../..")}let e=b.dirname(o);if(e===o)return null;o=e}}async function Kr(n){let o=await Qn.readFile(n,"utf-8").catch(()=>null);if(o===null)return null;return o.trim()||null}async function Rr(n){let o=await Kr(n);if(o)return o;let i=Er.randomUUID();try{return await Qn.writeFile(n,i,{flag:"wx"}),i}catch(l){if(l.code!=="EEXIST")throw l;let e=await Kr(n);if(e)return e;throw Error(`Project ID file was concurrently created but is empty: ${n}`)}}async function Pr(n){let o=await Jo(n);if(o){let l=b.join(o,"qitqode-project-id");return w.make(await Rr(l))}let i=b.join(n,".qitqode-project-id");return w.make(await Rr(i))}async function me(n){let o=await Jo(n);if(!o)return;let i=Dn.join(n,".qitqode-project-id"),l=Dn.join(o,"qitqode-project-id"),e=(T)=>F.access(T).then(()=>!0).catch(()=>!1);if(await e(i)){if(!await e(l)){let T=await F.readFile(i,"utf-8");await F.writeFile(l,T)}await F.unlink(i).catch(()=>{})}let A=Dn.join(o,"info","exclude");if(await F.mkdir(Dn.dirname(A),{recursive:!0}),!(await F.readFile(A,"utf-8").catch(()=>"")).includes(".qitqode-project-id"))await F.appendFile(A,`
2
+ import{Sl as an,Tl as _i,Ul as bn,Vl as Ni,Xl as Yr,Yl as zr}from"./chunk-4gzggzc0.js";import{Am as go,Bm as Kn,Cm as lo,Dm as so,Em as _o,Fm as No,Gm as po,Hm as Ao,Im as To,Jm as Ir,Km as Oo,Lm as $o,Mm as Do,Nm as Lr,Om as vo,Pm as dr,Qm as Bo,Rm as Gr,Sm as Jr,Tm as Mr,Um as Sr,Vm as Cr,Wm as Hr,Xm as Qo,Ym as Io,Zl as uo,Zm as Fo,_l as yo,am as er,bm as mr,cm as ur,cn as ui,dm as yr,em as fr,fm as gr,gm as lr,hm as sr,im as _r,jm as Nr,km as pr,lm as Ar,mm as V,nm as Tr,om as Or,pm as $r,qm as Dr,rm as vr,sm as Br,tm as j,um as v,vm as yn,wm as un,xm as Xo,ym as Qr,zm as Z}from"./chunk-31a47ptm.js";import{Jn as Fn,Nn as jn}from"./chunk-j3agzs13.js";import{On as gi}from"./chunk-3152y1q9.js";import{Pn as Mo}from"./chunk-71jmhvef.js";import{Ar as hr,Br as ti,Dr as ni,xr as Wn,yr as hn,zr as Nn}from"./chunk-kegvr7wt.js";import{Er as ri}from"./chunk-2tkgtasa.js";import{Fs as gn}from"./chunk-4yd2vvh6.js";import{ct as ro}from"./chunk-fdmz0502.js";import{gt as Ro}from"./chunk-mnjz8nqs.js";import{Pt as nn,Yt as c}from"./chunk-5dvy83ms.js";import{$t as Xr,cu as qo,du as k,hu as mo,mu as $n}from"./chunk-ffx0cr44.js";import{nu as a}from"./chunk-33mzqyyb.js";import{cA as pn,kA as Jn,yA as Cn}from"./chunk-wfpnv00c.js";import{$E as ln,BC as vn,FF as h,NE as Ko,UE as Xn,VO as N,gI as r,jL as Zr,kK as Uo,nC as cn,oJ as Ln,pF as Ur}from"./chunk-9kc2th5c.js";import{wP as On}from"./chunk-sh03ka27.js";var Vo={};On(Vo,{run:()=>$i});var mn={time_created:j().notNull().$default(()=>Date.now()),time_updated:j().notNull().$onUpdate(()=>Date.now())};var J=un("project",{id:v().$type().primaryKey(),worktree:v().notNull(),vcs:v(),name:v(),icon_url:v(),icon_color:v(),...mn,time_initialized:j(),sandboxes:v({mode:"json"}).notNull().$type(),commands:v({mode:"json"}).$type()});var fn=un("session",{id:v().$type().primaryKey(),project_id:v().$type().notNull().references(()=>J.id,{onDelete:"cascade"}),workspace_id:v().$type(),parent_id:v().$type(),context_from:v().$type(),context_watermark:v().$type(),slug:v().notNull(),directory:v().notNull(),title:v().notNull(),version:v().notNull(),share_url:v(),summary_additions:j(),summary_deletions:j(),summary_files:j(),summary_diffs:v({mode:"json"}).$type(),revert:v({mode:"json"}).$type(),permission:v({mode:"json"}).$type(),...mn,time_compacting:j(),time_archived:j(),last_checkpoint_message_id:v().$type()},(n)=>[yn("session_project_idx").on(n.project_id),yn("session_workspace_idx").on(n.workspace_id),yn("session_parent_idx").on(n.parent_id),yn("session_context_from_idx").on(n.context_from)]),eo=un("message",{id:v().$type().primaryKey(),session_id:v().$type().notNull().references(()=>fn.id,{onDelete:"cascade"}),agent_id:v().notNull().default("main"),...mn,data:v({mode:"json"}).notNull().$type()},(n)=>[yn("message_session_time_created_id_idx").on(n.session_id,n.time_created,n.id),yn("message_session_agent_idx").on(n.session_id,n.agent_id,n.id)]),Yo=un("part",{id:v().$type().primaryKey(),message_id:v().$type().notNull().references(()=>eo.id,{onDelete:"cascade"}),session_id:v().$type().notNull(),...mn,data:v({mode:"json"}).notNull().$type()},(n)=>[yn("part_message_id_id_idx").on(n.message_id,n.id),yn("part_session_idx").on(n.session_id)]),zo=un("todo",{session_id:v().$type().notNull().references(()=>fn.id,{onDelete:"cascade"}),content:v().notNull(),status:v().notNull(),position:j().notNull(),...mn},(n)=>[Xo({columns:[n.session_id,n.position]}),yn("todo_session_idx").on(n.session_id)]),co=un("permission",{project_id:v().primaryKey().references(()=>J.id,{onDelete:"cascade"}),...mn,data:v({mode:"json"}).notNull().$type()});var ko=un("session_share",{session_id:v().primaryKey().references(()=>fn.id,{onDelete:"cascade"}),id:v().notNull(),secret:v().notNull(),url:v().notNull(),...mn});import z from"path";var U=c.create({service:"json-migration"});async function $i(n,o){let i=z.join($n.Path.data,"storage");if(!await mo.exists(i))return U.info("storage directory does not exist, skipping migration"),{projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]};U.info("starting json to sqlite migration",{storageDir:i});let l=performance.now();n.run("PRAGMA journal_mode = WAL"),n.run("PRAGMA synchronous = OFF"),n.run("PRAGMA cache_size = 10000"),n.run("PRAGMA temp_store = MEMORY");let e={projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]},A={sessions:0,todos:0,permissions:0,shares:0},_=e.errors,T=1000,M=Date.now();async function x(f){return qo.scan(f,{cwd:i,absolute:!0})}async function C(f,d,S){let B=S-d,p=Array(B);for(let E=0;E<B;E++)p[E]=mo.readJson(f[d+E]);let G=await Promise.allSettled(p),W=Array(B);for(let E=0;E<G.length;E++){let q=G[E];if(q.status==="fulfilled"){W[E]=q.value;continue}_.push(`failed to read ${f[d+E]}: ${q.reason}`)}return W}function H(f,d,S){if(f.length===0)return 0;try{return n.insert(d).values(f).onConflictDoNothing().run(),f.length}catch(B){return _.push(`failed to migrate ${S} batch: ${B}`),0}}U.info("scanning files...");let[K,$,Q,L,g,s,m]=await Promise.all([x("project/*.json"),x("session/*/*.json"),x("message/*/*.json"),x("part/*/*.json"),x("todo/*.json"),x("permission/*.json"),x("session_share/*.json")]);U.info("file scan complete",{projects:K.length,sessions:$.length,messages:Q.length,parts:L.length,todos:g.length,permissions:s.length,shares:m.length});let y=Math.max(1,K.length+$.length+Q.length+L.length+g.length+s.length+m.length),t=o?.progress,u=0,D=(f,d)=>{u=Math.min(y,u+d),t?.({current:u,total:y,label:f})};t?.({current:u,total:y,label:"starting"}),n.run("BEGIN TRANSACTION");let I=new Set,O=[];for(let f=0;f<K.length;f+=T){let d=Math.min(f+T,K.length),S=await C(K,f,d);O.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=z.basename(K[f+B],".json");I.add(G),O.push({id:G,worktree:p.worktree??"/",vcs:p.vcs,name:p.name??void 0,icon_url:p.icon?.url,icon_color:p.icon?.color,time_created:p.time?.created??M,time_updated:p.time?.updated??M,time_initialized:p.time?.initialized,sandboxes:p.sandboxes??[],commands:p.commands})}e.projects+=H(O,J,"project"),D("projects",d-f)}U.info("migrated projects",{count:e.projects,duration:Math.round(performance.now()-l)});let P=$.map((f)=>z.basename(z.dirname(f))),Y=new Set,en=[];for(let f=0;f<$.length;f+=T){let d=Math.min(f+T,$.length),S=await C($,f,d);en.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=z.basename($[f+B],".json"),W=P[f+B];if(!I.has(W)){A.sessions++;continue}Y.add(G),en.push({id:G,project_id:W,parent_id:p.parentID??null,slug:p.slug??"",directory:p.directory??"",title:p.title??"",version:p.version??"",share_url:p.share?.url??null,summary_additions:p.summary?.additions??null,summary_deletions:p.summary?.deletions??null,summary_files:p.summary?.files??null,summary_diffs:p.summary?.diffs??null,revert:p.revert??null,permission:p.permission??null,time_created:p.time?.created??M,time_updated:p.time?.updated??M,time_compacting:p.time?.compacting??null,time_archived:p.time?.archived??null})}e.sessions+=H(en,fn,"session"),D("sessions",d-f)}if(U.info("migrated sessions",{count:e.sessions}),A.sessions>0)U.warn("skipped orphaned sessions",{count:A.sessions});let sn=[],R=[],kn=new Map;for(let f of Q){let d=z.basename(z.dirname(f));if(!Y.has(d))continue;sn.push(f),R.push(d)}for(let f=0;f<sn.length;f+=T){let d=Math.min(f+T,sn.length),S=await C(sn,f,d),B=Array(S.length),p=0;for(let G=0;G<S.length;G++){let W=S[G];if(!W)continue;let E=sn[f+G],q=z.basename(E,".json"),xn=R[f+G];kn.set(q,xn);let Bn=W;delete Bn.id,delete Bn.sessionID,B[p++]={id:q,session_id:xn,time_created:W.time?.created??M,time_updated:W.time?.updated??M,data:Bn}}B.length=p,e.messages+=H(B,eo,"message"),D("messages",d-f)}U.info("migrated messages",{count:e.messages});for(let f=0;f<L.length;f+=T){let d=Math.min(f+T,L.length),S=await C(L,f,d),B=Array(S.length),p=0;for(let G=0;G<S.length;G++){let W=S[G];if(!W)continue;let E=L[f+G],q=z.basename(E,".json"),xn=z.basename(z.dirname(E)),Bn=kn.get(xn);if(!Bn){_.push(`part missing message session: ${E}`);continue}if(!Y.has(Bn))continue;let wn=W;delete wn.id,delete wn.messageID,delete wn.sessionID,B[p++]={id:q,message_id:xn,session_id:Bn,time_created:W.time?.created??M,time_updated:W.time?.updated??M,data:wn}}B.length=p,e.parts+=H(B,Yo,"part"),D("parts",d-f)}U.info("migrated parts",{count:e.parts});let Tn=g.map((f)=>z.basename(f,".json"));for(let f=0;f<g.length;f+=T){let d=Math.min(f+T,g.length),S=await C(g,f,d),B=[];for(let p=0;p<S.length;p++){let G=S[p];if(!G)continue;let W=Tn[f+p];if(!Y.has(W)){A.todos++;continue}if(!Array.isArray(G)){_.push(`todo not an array: ${g[f+p]}`);continue}for(let E=0;E<G.length;E++){let q=G[E];if(!q?.content||!q?.status)continue;B.push({session_id:W,content:q.content,status:q.status,position:E,time_created:M,time_updated:M})}}e.todos+=H(B,zo,"todo"),D("todos",d-f)}if(U.info("migrated todos",{count:e.todos}),A.todos>0)U.warn("skipped orphaned todos",{count:A.todos});let qn=s.map((f)=>z.basename(f,".json")),Hn=[];for(let f=0;f<s.length;f+=T){let d=Math.min(f+T,s.length),S=await C(s,f,d);Hn.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=qn[f+B];if(!I.has(G)){A.permissions++;continue}Hn.push({project_id:G,data:p})}e.permissions+=H(Hn,co,"permission"),D("permissions",d-f)}if(U.info("migrated permissions",{count:e.permissions}),A.permissions>0)U.warn("skipped orphaned permissions",{count:A.permissions});let Vn=m.map((f)=>z.basename(f,".json")),dn=[];for(let f=0;f<m.length;f+=T){let d=Math.min(f+T,m.length),S=await C(m,f,d);dn.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=Vn[f+B];if(!Y.has(G)){A.shares++;continue}if(!p?.id||!p?.secret||!p?.url){_.push(`session_share missing id/secret/url: ${m[f+B]}`);continue}dn.push({session_id:G,id:p.id,secret:p.secret,url:p.url})}e.shares+=H(dn,ko,"session_share"),D("shares",d-f)}if(U.info("migrated session shares",{count:e.shares}),A.shares>0)U.warn("skipped orphaned session shares",{count:A.shares});if(n.run("COMMIT"),U.info("json migration complete",{projects:e.projects,sessions:e.sessions,messages:e.messages,parts:e.parts,todos:e.todos,permissions:e.permissions,shares:e.shares,errorCount:e.errors.length,duration:Math.round(performance.now()-l)}),e.errors.length>0)U.warn("migration errors",{errors:e.errors.slice(0,20)});return t?.({current:y,total:y,label:"complete"}),e}var In={};On(In,{use:()=>Ce,transaction:()=>xe,textDecoder:()=>re,sumDistinct:()=>rr,sum:()=>or,sql:()=>V,relationsOrderToSQL:()=>Rt,relationsFilterToSQL:()=>Kt,relationToSQL:()=>xt,relationExtrasToSQL:()=>Ht,processRelations:()=>Ct,placeholder:()=>Or,param:()=>Ar,orderSelectedFields:()=>oe,orderByOperators:()=>St,or:()=>lo,operators:()=>Mt,notLike:()=>Gr,notInArray:()=>Ir,notIlike:()=>Mr,notExists:()=>Lr,notBetween:()=>dr,not:()=>so,noopMapper:()=>Nr,noopEncoder:()=>_r,noopDecoder:()=>sr,ne:()=>go,name:()=>gr,min:()=>tr,max:()=>ir,mapUpdateSet:()=>ne,mapResultRow:()=>ht,mapRelationalRow:()=>Jt,mapColumnsInSQLToAlias:()=>it,mapColumnsInAliasedSQLToAlias:()=>rt,lte:()=>Ao,lt:()=>po,like:()=>Bo,l2Distance:()=>Xt,l1Distance:()=>Zt,jaccardDistance:()=>Ut,isWithEnum:()=>bt,isView:()=>vr,isTable:()=>Yi,isSQLWrapper:()=>mr,isNull:()=>Oo,isNotNull:()=>$o,isDriverValueEncoder:()=>lr,isConfig:()=>at,is:()=>Mi,innerProduct:()=>Wt,inArray:()=>To,ilike:()=>Jr,haveSameKeys:()=>jt,hasOwnEntityKind:()=>Ji,hammingDistance:()=>Pt,gte:()=>No,gt:()=>_o,getViewSelectedFields:()=>Ft,getViewName:()=>Br,getTableUniqueName:()=>Xi,getTableName:()=>Zi,getTableLikeName:()=>wt,getTableColumns:()=>Vt,getTableAsAliasSQL:()=>Gt,getOriginalColumnFromAlias:()=>ot,getOrderByOperators:()=>dt,getColumns:()=>qt,getColumnTable:()=>Ci,getColumnNameAndConfig:()=>kt,getChannelPath:()=>li,fillPlaceholders:()=>$r,fieldSelectionToSQL:()=>Lt,extractTablesFromSchema:()=>It,extractExtendedColumnType:()=>mt,exists:()=>Do,eq:()=>Z,entityKind:()=>Gi,effect:()=>He,desc:()=>Io,defineRelationsPart:()=>Qt,defineRelations:()=>Bt,createRelationsHelper:()=>vt,countDistinct:()=>bo,count:()=>fo,cosineDistance:()=>Et,close:()=>Se,buildRelationsParts:()=>Dt,buildRelations:()=>$t,bindIfParam:()=>Qr,between:()=>vo,avgDistinct:()=>nr,avg:()=>ho,assertUnreachable:()=>ct,asc:()=>Qo,arrayOverlaps:()=>Hr,arrayContains:()=>Sr,arrayContained:()=>Cr,applyMixins:()=>zt,and:()=>Kn,aliasedTableColumn:()=>nt,aliasedTable:()=>hi,aliasedRelation:()=>bi,aliasedColumn:()=>ai,WithSubquery:()=>ci,ViewSelectionAliasProxyHandler:()=>ji,ViewBaseConfig:()=>ki,View:()=>Dr,TransactionRollbackError:()=>ft,TableSchema:()=>Ui,TableColumns:()=>Wi,TableAliasProxyHandler:()=>Fi,Table:()=>Pi,Subquery:()=>zi,StringChunk:()=>ur,SQL:()=>yr,RelationsHelperStatic:()=>Ot,RelationsBuilderTable:()=>Tt,RelationsBuilderJunctionColumn:()=>At,RelationsBuilderColumn:()=>pt,RelationTableAliasProxyHandler:()=>wi,Relation:()=>Nt,QueryPromise:()=>tt,Placeholder:()=>Tr,Path:()=>Eo,Param:()=>pr,OriginalName:()=>Ei,One:()=>_t,NotFoundError:()=>Me,NoopLogger:()=>di,Name:()=>fr,Many:()=>st,IsAlias:()=>Ri,FakePrimitiveParam:()=>er,ExtraConfigColumns:()=>Ki,ExtraConfigBuilder:()=>xi,DrizzleQueryError:()=>yt,DrizzleError:()=>ut,DefaultLogger:()=>Li,Count:()=>lt,ConsoleLogWriter:()=>Ii,ColumnTableAliasProxyHandler:()=>Vi,ColumnBuilder:()=>et,ColumnAliasProxyHandler:()=>qi,Column:()=>Si,Client:()=>Mn,CONSTANTS:()=>Yt,BaseName:()=>Hi,AggregatedField:()=>gt});import Di from"crypto";import wo,{existsSync as vi,readdirSync as Bi}from"fs";import{join as Qi}from"path";function jo(n){if(wo.existsSync(`${n.migrationsFolder}/meta/_journal.json`))throw Error('We detected that you have old drizzle-kit migration folders. You must upgrade drizzle-kit and run "drizzle-kit up"');let o=n.migrationsFolder,i=[],l=Bi(o).map((e)=>({path:Qi(o,e,"migration.sql"),name:e})).filter((e)=>vi(e.path));l.sort((e,A)=>e.name.localeCompare(A.name));for(let e of l){let A=e.path,_=e.name.slice(0,14),T=wo.readFileSync(A).toString(),M=T.split("--> statement-breakpoint").map((C)=>{return C}),x=Fo(_);i.push({sql:M,bps:!0,folderMillis:x,hash:Di.createHash("sha256").update(T).digest("hex"),name:e.name})}return i}function ao(n,o){if(Array.isArray(o)||"migrationsJournal"in o){let l=Array.isArray(o)?o:o.migrationsJournal,e=Array.isArray(o)?void 0:o.migrationsTable,A=l.map((_)=>({sql:_.sql.split("--> statement-breakpoint"),folderMillis:_.timestamp,hash:"",bps:!0,name:_.name}));return n.dialect.migrate(A,n.session,{migrationsTable:e})}let i=jo(o);return n.dialect.migrate(i,n.session,o)}function fo(n){return V`count(${n||V.raw("*")})`.mapWith(Number)}function bo(n){return V`count(distinct ${n})`.mapWith(Number)}function ho(n){return V`avg(${n})`.mapWith(String)}function nr(n){return V`avg(distinct ${n})`.mapWith(String)}function or(n){return V`sum(${n})`.mapWith(String)}function rr(n){return V`sum(distinct ${n})`.mapWith(String)}function ir(n){return V`max(${n})`.mapWith(uo(n,yo)?n:String)}function tr(n){return V`min(${n})`.mapWith(uo(n,yo)?n:String)}import oo from"path";var Un={};On(Un,{workspaceID:()=>De,useEffect:()=>Qe,use:()=>Be,make:()=>ve,invalidate:()=>Le,has:()=>Ie,get:()=>xo,directory:()=>no,context:()=>Ho,bind:()=>$e});import{EventEmitter as ie}from"events";var Rn=new ie;var Lo=new Set;function xr(n){return Lo.add(n),()=>{Lo.delete(n)}}async function Go(n){await Promise.allSettled([...Lo].map((o)=>o(n)))}function En(n){return n()}var jr={};On(jr,{setInitialized:()=>se,list:()=>ge,layer:()=>Fr,get:()=>le,fromRow:()=>_n,defaultLayer:()=>Co,UpdateInput:()=>fe,Service:()=>Gn,Info:()=>Vr,Event:()=>wr});import*as F from"fs/promises";import*as cr from"os";import*as Dn from"path";var te=N.String.pipe(N.brand("ProjectID")),w=te.pipe(Fn((n)=>({global:n.make("global"),zod:a.string().pipe(a.custom())})));import*as Qn from"fs/promises";import*as b from"path";import*as Er from"crypto";async function Jo(n){let o=b.resolve(n);while(!0){let i=b.join(o,".git"),l=await Qn.stat(i).catch(()=>null);if(l){if(l.isDirectory())return i;let _=(await Qn.readFile(i,"utf-8")).trim().match(/^gitdir:\s*(.+)$/);if(!_)return null;let T=b.isAbsolute(_[1])?_[1]:b.resolve(o,_[1]);return b.resolve(T,"../..")}let e=b.dirname(o);if(e===o)return null;o=e}}async function Kr(n){let o=await Qn.readFile(n,"utf-8").catch(()=>null);if(o===null)return null;return o.trim()||null}async function Rr(n){let o=await Kr(n);if(o)return o;let i=Er.randomUUID();try{return await Qn.writeFile(n,i,{flag:"wx"}),i}catch(l){if(l.code!=="EEXIST")throw l;let e=await Kr(n);if(e)return e;throw Error(`Project ID file was concurrently created but is empty: ${n}`)}}async function Pr(n){let o=await Jo(n);if(o){let l=b.join(o,"qitqode-project-id");return w.make(await Rr(l))}let i=b.join(n,".qitqode-project-id");return w.make(await Rr(i))}async function me(n){let o=await Jo(n);if(!o)return;let i=Dn.join(n,".qitqode-project-id"),l=Dn.join(o,"qitqode-project-id"),e=(T)=>F.access(T).then(()=>!0).catch(()=>!1);if(await e(i)){if(!await e(l)){let T=await F.readFile(i,"utf-8");await F.writeFile(l,T)}await F.unlink(i).catch(()=>{})}let A=Dn.join(o,"info","exclude");if(await F.mkdir(Dn.dirname(A),{recursive:!0}),!(await F.readFile(A,"utf-8").catch(()=>"")).includes(".qitqode-project-id"))await F.appendFile(A,`
3
3
  .qitqode-project-id
4
4
  `)}var Wr=c.create({service:"project"}),ue=262144,So=N.Literal("git"),kr=N.Struct({url:N.optional(N.String),override:N.optional(N.String),color:N.optional(N.String)}),qr=N.Struct({start:N.optional(N.String.annotate({description:"Startup script to run when creating a new workspace (worktree)"}))}),ye=N.Struct({created:N.Number,updated:N.Number,initialized:N.optional(N.Number)}),Vr=N.Struct({id:w,worktree:N.String,vcs:N.optional(So),name:N.optional(N.String),icon:N.optional(kr),commands:N.optional(qr),time:ye,sandboxes:N.Array(N.String)}).annotate({identifier:"Project"}).pipe(Fn((n)=>({zod:jn(n)}))),wr={Updated:zr.define("project.updated",Vr.zod)};function _n(n){let o=n.icon_url||n.icon_color?{url:n.icon_url??void 0,color:n.icon_color??void 0}:void 0;return{id:n.id,worktree:n.worktree,vcs:n.vcs?N.decodeUnknownSync(So)(n.vcs):void 0,name:n.name??void 0,icon:o,time:{created:n.time_created,updated:n.time_updated,initialized:n.time_initialized??void 0},sandboxes:n.sandboxes,commands:n.commands??void 0}}var fe=a.object({projectID:w.zod,name:a.string().optional(),icon:jn(kr).optional(),commands:jn(qr).optional()});class Gn extends vn.Service()("@qitqode/Project"){}var Fr=h.effect(Gn,r.gen(function*(){let n=yield*k.Service,o=yield*Zr.Path,i=yield*an.ChildProcessSpawner,l=r.fnUntraced(function*(t,u){return yield*Yr(i,t,u)},r.catch(()=>r.succeed({code:1,text:"",stderr:""}))),e=(t)=>r.sync(()=>In.use(t)),A=(t)=>r.sync(()=>Rn.emit("event",{directory:"global",project:t.id,payload:{type:wr.Updated.type,properties:t}})),_=N.decodeUnknownSync(N.optional(So))(nn.QITQODE_FAKE_VCS),T=(t,u)=>{if(!u)return t;if(u=u.replace(/[\r\n]+$/,""),!u)return t;if(u=k.windowsPath(u),o.isAbsolute(u))return o.normalize(u);return o.resolve(t,u)},M=yield*Ur.Scope,x=r.fn("Project.fromDirectory")(function*(t){Wr.info("fromDirectory",{directory:t});let u=yield*r.gen(function*(){if(nn.QITQODE_DISABLE_GIT)return{id:w.global,worktree:t,sandbox:t,vcs:_};let Y=(yield*n.up({targets:[".git"],start:t}).pipe(r.orDie))[0];if(!Y)return{id:w.global,worktree:"/",sandbox:"/",vcs:_};let en=o.dirname(Y),sn=process.env.HOME??process.env.USERPROFILE??cr.homedir();if(en===sn||Dn.parse(en).root===en)return Wr.warn("ignoring .git at home or filesystem root, snapshots disabled",{dotgit:Y}),{id:w.global,worktree:t,sandbox:t,vcs:_};let R=en,kn=yield*r.sync(()=>Mo("git")),Tn;if(!kn)return{id:Tn??w.global,worktree:R,sandbox:R,vcs:_};let qn=yield*l(["rev-parse","--git-common-dir"],{cwd:R});if(qn.code!==0)return{id:Tn??w.global,worktree:R,sandbox:R,vcs:_};let Hn=(()=>{let dn=T(R,qn.text.trim());return dn===R?R:o.dirname(dn)})();if(Tn==null)yield*r.promise(()=>me(R)),Tn=yield*r.promise(()=>Pr(R));let Vn=yield*l(["rev-parse","--show-toplevel"],{cwd:R});if(Vn.code!==0)return{id:Tn,worktree:R,sandbox:R,vcs:_};return R=T(R,Vn.text.trim()),{id:Tn,sandbox:R,worktree:Hn,vcs:"git"}}),D=yield*e((P)=>P.select().from(J).where(Z(J.id,u.id)).get()),I=D?_n(D):{id:u.id,worktree:u.worktree,vcs:u.vcs,sandboxes:[],time:{created:Date.now(),updated:Date.now()}};if(nn.QITQODE_EXPERIMENTAL_ICON_DISCOVERY)yield*C(I).pipe(r.ignore,r.forkIn(M));let O={...I,worktree:u.worktree,vcs:u.vcs,time:{...I.time,updated:Date.now()}};if(u.sandbox!==O.worktree&&!O.sandboxes.includes(u.sandbox))O.sandboxes.push(u.sandbox);if(O.sandboxes=yield*r.forEach(O.sandboxes,(P)=>n.exists(P).pipe(r.orDie,r.map((Y)=>Y?P:void 0)),{concurrency:16}).pipe(r.map((P)=>P.filter((Y)=>Y!==void 0))),yield*e((P)=>P.insert(J).values({id:O.id,worktree:O.worktree,vcs:O.vcs??null,name:O.name,icon_url:O.icon?.url,icon_color:O.icon?.color,time_created:O.time.created,time_updated:O.time.updated,time_initialized:O.time.initialized,sandboxes:O.sandboxes,commands:O.commands}).onConflictDoUpdate({target:J.id,set:{worktree:O.worktree,vcs:O.vcs??null,name:O.name,icon_url:O.icon?.url,icon_color:O.icon?.color,time_updated:O.time.updated,time_initialized:O.time.initialized,sandboxes:O.sandboxes,commands:O.commands}}).run()),u.id!==w.global)yield*e((P)=>P.update(fn).set({project_id:u.id}).where(Kn(Z(fn.project_id,w.global),Z(fn.directory,u.worktree))).run());return yield*A(O),{project:O,sandbox:u.sandbox}}),C=r.fn("Project.discover")(function*(t){if(t.vcs!=="git")return;if(t.icon?.override)return;if(t.icon?.url)return;let D=(yield*n.glob("**/favicon.{ico,png,svg,jpg,jpeg,webp}",{cwd:t.worktree,absolute:!0,include:"file"}).pipe(r.orDie)).sort((sn,R)=>sn.length-R.length)[0];if(!D)return;let I=yield*n.stat(D).pipe(r.orDie);if(Number(I.size)>ue)return;let O=yield*n.readFile(D).pipe(r.orDie),P=Buffer.from(O).toString("base64"),en=`data:${k.mimeType(D)};base64,${P}`;yield*$({projectID:t.id,icon:{url:en}})}),H=r.fn("Project.list")(function*(){return yield*e((t)=>t.select().from(J).all().map(_n))}),K=r.fn("Project.get")(function*(t){let u=yield*e((D)=>D.select().from(J).where(Z(J.id,t)).get());return u?_n(u):void 0}),$=r.fn("Project.update")(function*(t){let u=yield*e((I)=>I.update(J).set({name:t.name,icon_url:t.icon?.url,icon_color:t.icon?.color,commands:t.commands,time_updated:Date.now()}).where(Z(J.id,t.projectID)).returning().get());if(!u)throw Error(`Project not found: ${t.projectID}`);let D=_n(u);return yield*A(D),D}),Q=r.fn("Project.initGit")(function*(t){if(t.project.vcs==="git")return t.project;if(!(yield*r.sync(()=>Mo("git"))))throw Error("Git is not installed");let u=yield*l(["init","--quiet"],{cwd:t.directory});if(u.code!==0)throw Error(u.stderr.trim()||u.text.trim()||"Failed to initialize git repository");let{project:D}=yield*x(t.directory);return D}),L=r.fn("Project.setInitialized")(function*(t){yield*e((u)=>u.update(J).set({time_initialized:Date.now()}).where(Z(J.id,t)).run())}),g=r.fn("Project.sandboxes")(function*(t){let u=yield*e((I)=>I.select().from(J).where(Z(J.id,t)).get());if(!u)return[];let D=_n(u);return yield*r.forEach(D.sandboxes,(I)=>n.isDir(I).pipe(r.orDie,r.map((O)=>O?I:void 0)),{concurrency:16}).pipe(r.map((I)=>I.filter((O)=>O!==void 0)))}),s=r.fnUntraced(function*(t,u){let D=yield*e((I)=>I.update(J).set({sandboxes:u,time_updated:Date.now()}).where(Z(J.id,t)).returning().get());if(!D)throw Error(`Project not found: ${t}`);yield*A(_n(D))}),m=r.fn("Project.addSandbox")(function*(t,u){let D=yield*e((O)=>O.select().from(J).where(Z(J.id,t)).get());if(!D)throw Error(`Project not found: ${t}`);let I=[...D.sandboxes];if(!I.includes(u))I.push(u);yield*s(t,I)}),y=r.fn("Project.removeSandbox")(function*(t,u){let D=yield*e((O)=>O.select().from(J).where(Z(J.id,t)).get());if(!D)throw Error(`Project not found: ${t}`);let I=D.sandboxes.filter((O)=>O!==u);yield*s(t,I)});return Gn.of({fromDirectory:x,discover:C,list:H,get:K,update:$,initGit:Q,setInitialized:L,sandboxes:g,addSandbox:m,removeSandbox:y})})),Co=Fr.pipe(h.provide(bn),h.provide(k.defaultLayer),h.provide(Xr.layer));function ge(){return In.use((n)=>n.select().from(J).all().map((o)=>_n(o)))}function le(n){let o=In.use((i)=>i.select().from(J).where(Z(J.id,n)).get());if(!o)return;return _n(o)}function se(n){In.use((o)=>o.update(J).set({time_initialized:Date.now()}).where(Z(J.id,n)).run())}import{parse as _e}from"path";var rn=gn.create("instance");hr(()=>rn.use());var tn=new Map,Ne=ni(Gn,Co),pe=new Set(["/etc","/proc","/sys","/dev","/boot","/root","/var","/private/etc","/private/var"]);function Ae(n){if(n===_e(n).root)return"filesystem root is not a valid project directory";for(let o of pe)if(n===o||k.contains(o,n))return"target is a protected system directory";return null}function Te(n){let o=Ae(n);if(o)throw Error("Access denied: "+o)}var Pn={all:void 0};function ar(n){return En(async()=>{let o=n.project&&n.worktree?{directory:n.directory,worktree:n.worktree,project:n.project}:await Ne.runPromise((i)=>i.fromDirectory(n.directory)).then(({project:i,sandbox:l})=>({directory:n.directory,worktree:l,project:i}));return await rn.provide(o,async()=>{await n.init?.()}),o})}function br(n,o){let i=o.catch((l)=>{if(tn.get(n)===i)tn.delete(n);throw l});return tn.set(n,i),i}var on={async provide(n){let o=k.resolve(n.directory);Te(o);let i=tn.get(o);if(!i)c.Default.info("creating instance",{directory:o}),i=br(o,ar({directory:o,init:n.init}));let l=await i;return rn.provide(l,async()=>{return n.fn()})},get current(){return rn.use()},get directory(){return rn.use().directory},get worktree(){return rn.use().worktree},get project(){return rn.use().project},containsPath(n,o){let i=o??on;if(k.contains(i.directory,n))return!0;if(i.worktree==="/")return!1;return k.contains(i.worktree,n)},bind(n){let o=rn.use();return(...i)=>rn.provide(o,()=>n(...i))},restore(n,o){return rn.provide(n,o)},async reload(n){let o=k.resolve(n.directory);c.Default.info("reloading instance",{directory:o}),await Go(o),tn.delete(o);let i=br(o,ar({...n,directory:o}));return Rn.emit("event",{directory:o,project:n.project?.id,workspace:Nn.workspaceID,payload:{type:"server.instance.disposed",properties:{directory:o}}}),await i},async dispose(){let{directory:n,project:o}=on;c.Default.info("disposing instance",{directory:n}),await Go(n),tn.delete(n),Rn.emit("event",{directory:n,project:o.id,workspace:Nn.workspaceID,payload:{type:"server.instance.disposed",properties:{directory:n}}})},async disposeAll(){if(Pn.all)return Pn.all;return Pn.all=En(async()=>{c.Default.info("disposing all instances");let n=[...tn.entries()];for(let[o,i]of n){if(tn.get(o)!==i)continue;let l=await i.catch((e)=>{c.Default.warn("instance dispose failed",{key:o,error:e});return});if(!l){if(tn.get(o)===i)tn.delete(o);continue}if(tn.get(o)!==i)continue;await rn.provide(l,async()=>{await on.dispose()})}}).finally(()=>{Pn.all=void 0}),Pn.all}};var oi="~qitqode/InstanceState",$e=(n)=>{try{return on.bind(n)}catch(l){if(!(l instanceof gn.NotFound))throw l}let o=Ln.getCurrent(),i=o?vn.getReferenceUnsafe(o.context,Wn):void 0;if(!i)return n;return(...l)=>on.restore(i,()=>n(...l))},Ho=r.gen(function*(){return(yield*Wn)??on.current}),De=r.gen(function*(){return(yield*hn)??Nn.workspaceID}),no=r.map(Ho,(n)=>n.directory),ve=(n)=>r.gen(function*(){let o=yield*Jn.make({capacity:Number.POSITIVE_INFINITY,lookup:()=>r.gen(function*(){return yield*n(yield*Ho)})}),i=xr((l)=>r.runPromise(Jn.invalidate(o,l).pipe(r.provide(ri))));return yield*r.addFinalizer(()=>r.sync(i)),{[oi]:oi,cache:o}}),xo=(n)=>r.gen(function*(){return yield*Jn.get(n.cache,yield*no)}),Be=(n,o)=>r.map(xo(n),o),Qe=(n,o)=>r.flatMap(xo(n),o),Ie=(n)=>r.gen(function*(){return yield*Jn.has(n.cache,yield*no)}),Le=(n)=>r.gen(function*(){return yield*Jn.invalidate(n.cache,yield*no)});var ei={};On(ei,{make:()=>de});function ii(n,o,i){if(n&&o!==void 0)return Nn.restore(o,()=>on.restore(n,i));if(n)return on.restore(n,i);if(o!==void 0)return Nn.restore(o,i);return i()}function de(){return r.gen(function*(){let n=yield*r.context(),i=(yield*Wn)??(()=>{try{return on.current}catch(_){if(!(_ instanceof gn.NotFound))throw _}})(),l=(yield*hn)??Nn.workspaceID,e=(_)=>ti(_,{instance:i,workspace:l}),A=(_)=>e(_).pipe(r.provide(n));return{promise:(_)=>ii(i,l,()=>r.runPromise(A(_))),fork:(_)=>ii(i,l,()=>r.runFork(A(_)))}})}var mi={};On(mi,{make:()=>Ge,Cancelled:()=>Zn});class Zn extends N.TaggedErrorClass()("RunnerCancelled",{}){}var Ge=(n,o)=>{let i=pn.makeUnsafe({_tag:"Idle"}),l=o?.onIdle??r.void,e=o?.onBusy??r.void,A=o?.onInterrupt,_=0,T=()=>pn.getUnsafe(i),M=()=>{return _+=1,_},x=(m,y)=>Xn.isFailure(y)&&Ko.hasInterruptsOnly(y.cause)?ln.fail(m,new Zn).pipe(r.asVoid):ln.done(m,y).pipe(r.asVoid),C=()=>pn.modify(i,(m)=>[m._tag==="Idle"?l:r.void,m]).pipe(r.flatten),H=(m,y,t)=>pn.modify(i,(u)=>[r.gen(function*(){if(u._tag==="Running"&&u.run.id===m)yield*l;yield*x(y,t)}),u._tag==="Running"&&u.run.id===m?{_tag:"Idle"}:u]).pipe(r.flatten),K=(m,y)=>r.gen(function*(){let t=M(),u=yield*m.pipe(r.onExit((D)=>H(t,y,D)),r.forkIn(n));return{id:t,done:y,fiber:u}}),$=(m)=>pn.modifyEffect(i,r.fnUntraced(function*(y){if(y._tag==="Shell"&&y.shell.id===m)return[l,{_tag:"Idle"}];if(y._tag==="ShellThenRun"&&y.shell.id===m){let t=yield*K(y.run.work,y.run.done);return[r.void,{_tag:"Running",run:t}]}return[r.void,y]})).pipe(r.flatten),Q=(m)=>Ln.interrupt(m.fiber),L=(m)=>pn.modifyEffect(i,r.fnUntraced(function*(y){switch(y._tag){case"Running":case"ShellThenRun":if(o?.onReentryWarn)yield*o.onReentryWarn({label:o.label??"(unlabeled)",existingRunId:y.run.id});return[ln.await(y.run.done),y];case"Shell":{let t={id:M(),done:yield*ln.make(),work:m};return[ln.await(t.done),{_tag:"ShellThenRun",shell:y.shell,run:t}]}case"Idle":{let t=yield*ln.make(),u=yield*K(m,t);return[ln.await(t),{_tag:"Running",run:u}]}}})).pipe(r.flatten,r.catch((y)=>y instanceof Zn?A??r.die(y):r.fail(y))),g=(m)=>pn.modifyEffect(i,r.fnUntraced(function*(y){if(y._tag!=="Idle")return[r.sync(()=>{if(o?.busy)o.busy();throw Error("Runner is busy")}),y];yield*e;let t=M(),u=yield*m.pipe(r.ensuring($(t)),r.forkChild),D={id:t,fiber:u};return[r.gen(function*(){let I=yield*Ln.await(u);if(Xn.isSuccess(I))return I.value;if(Ko.hasInterruptsOnly(I.cause)&&A)return yield*A;return yield*r.failCause(I.cause)}),{_tag:"Shell",shell:D}]})).pipe(r.flatten),s=pn.modify(i,(m)=>{switch(m._tag){case"Idle":return[r.void,m];case"Running":return[r.gen(function*(){yield*Ln.interrupt(m.run.fiber);let y=yield*Ln.await(m.run.fiber);yield*x(m.run.done,y),yield*ln.await(m.run.done).pipe(r.exit,r.asVoid),yield*C()}),{_tag:"Idle"}];case"Shell":return[r.gen(function*(){yield*Q(m.shell),yield*C()}),{_tag:"Idle"}];case"ShellThenRun":return[r.gen(function*(){yield*ln.fail(m.run.done,new Zn).pipe(r.asVoid),yield*Q(m.shell),yield*C()}),{_tag:"Idle"}]}}).pipe(r.flatten);return{get state(){return T()},get busy(){return T()._tag!=="Idle"},ensureRunning:L,startShell:g,cancel:s}};import{Database as Je}from"bun:sqlite";function yi(n){let o=new Je(n,{create:!0});return ui({client:o})}var Me=ro.create("NotFoundError",a.object({message:a.string()})),fi=c.create({service:"db"});function li(){if(["latest","beta","prod"].includes(Ro)||nn.QITQODE_DISABLE_CHANNEL_DB)return oo.join($n.Path.data,"qitqode.db");let n=Ro.replace(/[^a-zA-Z0-9._-]/g,"-");return oo.join($n.Path.data,`qitqode-${n}.db`)}var Eo=En(()=>{if(nn.QITQODE_DB){if(nn.QITQODE_DB===":memory:"||oo.isAbsolute(nn.QITQODE_DB))return nn.QITQODE_DB;return oo.join($n.Path.data,nn.QITQODE_DB)}return li()}),Mn=gi(()=>{fi.info("opening database",{path:Eo});let n=yi(Eo);n.run("PRAGMA journal_mode = WAL"),n.run("PRAGMA synchronous = NORMAL"),n.run("PRAGMA busy_timeout = 5000"),n.run("PRAGMA cache_size = -64000"),n.run("PRAGMA foreign_keys = ON"),n.run("PRAGMA wal_checkpoint(PASSIVE)");let o=[{sql:"CREATE TABLE `project` (\n\t`id` text PRIMARY KEY,\n\t`worktree` text NOT NULL,\n\t`vcs` text,\n\t`name` text,\n\t`icon_url` text,\n\t`icon_color` text,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`time_initialized` integer,\n\t`sandboxes` text NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE `message` (\n\t`id` text PRIMARY KEY,\n\t`session_id` text NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_message_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `part` (\n\t`id` text PRIMARY KEY,\n\t`message_id` text NOT NULL,\n\t`session_id` text NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_part_message_id_message_id_fk` FOREIGN KEY (`message_id`) REFERENCES `message`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `permission` (\n\t`project_id` text PRIMARY KEY,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_permission_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `session` (\n\t`id` text PRIMARY KEY,\n\t`project_id` text NOT NULL,\n\t`parent_id` text,\n\t`slug` text NOT NULL,\n\t`directory` text NOT NULL,\n\t`title` text NOT NULL,\n\t`version` text NOT NULL,\n\t`share_url` text,\n\t`summary_additions` integer,\n\t`summary_deletions` integer,\n\t`summary_files` integer,\n\t`summary_diffs` text,\n\t`revert` text,\n\t`permission` text,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`time_compacting` integer,\n\t`time_archived` integer,\n\tCONSTRAINT `fk_session_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `todo` (\n\t`session_id` text NOT NULL,\n\t`content` text NOT NULL,\n\t`status` text NOT NULL,\n\t`priority` text NOT NULL,\n\t`position` integer NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\tCONSTRAINT `todo_pk` PRIMARY KEY(`session_id`, `position`),\n\tCONSTRAINT `fk_todo_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `session_share` (\n\t`session_id` text PRIMARY KEY,\n\t`id` text NOT NULL,\n\t`secret` text NOT NULL,\n\t`url` text NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\tCONSTRAINT `fk_session_share_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE INDEX `message_session_idx` ON `message` (`session_id`);--> statement-breakpoint\nCREATE INDEX `part_message_idx` ON `part` (`message_id`);--> statement-breakpoint\nCREATE INDEX `part_session_idx` ON `part` (`session_id`);--> statement-breakpoint\nCREATE INDEX `session_project_idx` ON `session` (`project_id`);--> statement-breakpoint\nCREATE INDEX `session_parent_idx` ON `session` (`parent_id`);--> statement-breakpoint\nCREATE INDEX `todo_session_idx` ON `todo` (`session_id`);",timestamp:1769552633000,name:"20260127222353_familiar_lady_ursula"},{sql:"ALTER TABLE `project` ADD `commands` text;",timestamp:1770830228000,name:"20260211171708_add_project_commands"},{sql:"CREATE TABLE `control_account` (\n\t`email` text NOT NULL,\n\t`url` text NOT NULL,\n\t`access_token` text NOT NULL,\n\t`refresh_token` text NOT NULL,\n\t`token_expiry` integer,\n\t`active` integer NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\tCONSTRAINT `control_account_pk` PRIMARY KEY(`email`, `url`)\n);\n",timestamp:1770993676000,name:"20260213144116_wakeful_the_professor"},{sql:"CREATE TABLE `workspace` (\n\t`id` text PRIMARY KEY,\n\t`branch` text,\n\t`project_id` text NOT NULL,\n\t`config` text NOT NULL,\n\tCONSTRAINT `fk_workspace_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE\n);\n",timestamp:1772056728000,name:"20260225215848_workspace"},{sql:"ALTER TABLE `session` ADD `workspace_id` text;--> statement-breakpoint\nCREATE INDEX `session_workspace_idx` ON `session` (`workspace_id`);",timestamp:1772228279000,name:"20260227213759_add_session_workspace_id"},{sql:"CREATE TABLE `account` (\n\t`id` text PRIMARY KEY,\n\t`email` text NOT NULL,\n\t`url` text NOT NULL,\n\t`access_token` text NOT NULL,\n\t`refresh_token` text NOT NULL,\n\t`token_expiry` integer,\n\t`selected_org_id` text,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE `account_state` (\n\t`id` integer PRIMARY KEY NOT NULL,\n\t`active_account_id` text,\n\tFOREIGN KEY (`active_account_id`) REFERENCES `account`(`id`) ON UPDATE no action ON DELETE set null\n);\n",timestamp:1772310750000,name:"20260228203230_blue_harpoon"},{sql:"ALTER TABLE `workspace` ADD `type` text NOT NULL;--> statement-breakpoint\nALTER TABLE `workspace` ADD `name` text;--> statement-breakpoint\nALTER TABLE `workspace` ADD `directory` text;--> statement-breakpoint\nALTER TABLE `workspace` ADD `extra` text;--> statement-breakpoint\nALTER TABLE `workspace` DROP COLUMN `config`;",timestamp:1772579546000,name:"20260303231226_add_workspace_fields"},{sql:"ALTER TABLE `account_state` ADD `active_org_id` text;--> statement-breakpoint\nUPDATE `account_state` SET `active_org_id` = (SELECT `selected_org_id` FROM `account` WHERE `account`.`id` = `account_state`.`active_account_id`);--> statement-breakpoint\nALTER TABLE `account` DROP COLUMN `selected_org_id`;\n",timestamp:1773097200000,name:"20260309230000_move_org_to_state"},{sql:"DROP INDEX IF EXISTS `message_session_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `part_message_idx`;--> statement-breakpoint\nCREATE INDEX `message_session_time_created_id_idx` ON `message` (`session_id`,`time_created`,`id`);--> statement-breakpoint\nCREATE INDEX `part_message_id_id_idx` ON `part` (`message_id`,`id`);",timestamp:1773290071000,name:"20260312043431_session_message_cursor"},{sql:"CREATE TABLE `event_sequence` (\n\t`aggregate_id` text PRIMARY KEY,\n\t`seq` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE `event` (\n\t`id` text PRIMARY KEY,\n\t`aggregate_id` text NOT NULL,\n\t`seq` integer NOT NULL,\n\t`type` text NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_event_aggregate_id_event_sequence_aggregate_id_fk` FOREIGN KEY (`aggregate_id`) REFERENCES `event_sequence`(`aggregate_id`) ON DELETE CASCADE\n);\n",timestamp:1774309702000,name:"20260323234822_events"},{sql:"PRAGMA foreign_keys=OFF;--> statement-breakpoint\nCREATE TABLE `__new_workspace` (\n\t`id` text PRIMARY KEY,\n\t`type` text NOT NULL,\n\t`name` text DEFAULT '' NOT NULL,\n\t`branch` text,\n\t`directory` text,\n\t`extra` text,\n\t`project_id` text NOT NULL,\n\tCONSTRAINT `fk_workspace_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nINSERT INTO `__new_workspace`(`id`, `type`, `branch`, `name`, `directory`, `extra`, `project_id`) SELECT `id`, `type`, `branch`, `name`, `directory`, `extra`, `project_id` FROM `workspace`;--> statement-breakpoint\nDROP TABLE `workspace`;--> statement-breakpoint\nALTER TABLE `__new_workspace` RENAME TO `workspace`;--> statement-breakpoint\nPRAGMA foreign_keys=ON;",timestamp:1775843113000,name:"20260410174513_workspace-name"},{sql:"CREATE TABLE `session_entry` (\n\t`id` text PRIMARY KEY,\n\t`session_id` text NOT NULL,\n\t`type` text NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_session_entry_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE INDEX `session_entry_session_idx` ON `session_entry` (`session_id`);--> statement-breakpoint\nCREATE INDEX `session_entry_session_type_idx` ON `session_entry` (`session_id`,`type`);--> statement-breakpoint\nCREATE INDEX `session_entry_time_created_idx` ON `session_entry` (`time_created`);",timestamp:1776103196000,name:"20260413175956_chief_energizer"},{sql:"ALTER TABLE `session` ADD `context_from` text;--> statement-breakpoint\nALTER TABLE `session` ADD `context_watermark` text;--> statement-breakpoint\nCREATE INDEX `session_context_from_idx` ON `session` (`context_from`);\n",timestamp:1776873600000,name:"20260422160000_context_inheritance"},{sql:"CREATE TABLE `task_registry` (\n `id` text PRIMARY KEY,\n `parent_session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `status` text NOT NULL,\n `agent` text NOT NULL,\n `description` text NOT NULL,\n `context_mode` text NOT NULL,\n `background` integer NOT NULL,\n `last_turn_time` integer NOT NULL,\n `turn_count` integer NOT NULL DEFAULT 0,\n `error` text,\n `time_completed` integer,\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `task_registry_parent_idx` ON `task_registry` (`parent_session_id`);--> statement-breakpoint\nCREATE INDEX `task_registry_status_idx` ON `task_registry` (`status`);--> statement-breakpoint\nCREATE INDEX `task_registry_status_last_turn_idx` ON `task_registry` (`status`, `last_turn_time`);\n",timestamp:1776877200000,name:"20260422170000_task_registry"},{sql:"DROP INDEX IF EXISTS `session_entry_session_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `session_entry_session_type_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `session_entry_time_created_idx`;--> statement-breakpoint\nDROP TABLE IF EXISTS `session_entry`;\n",timestamp:1776956061000,name:"20260423145421_remove_session_entry"},{sql:"DROP INDEX IF EXISTS `task_registry_parent_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `task_registry_status_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `task_registry_status_last_turn_idx`;--> statement-breakpoint\nALTER TABLE `task_registry` RENAME TO `actor_registry`;--> statement-breakpoint\nCREATE INDEX `actor_registry_parent_idx` ON `actor_registry` (`parent_session_id`);--> statement-breakpoint\nCREATE INDEX `actor_registry_status_idx` ON `actor_registry` (`status`);--> statement-breakpoint\nCREATE INDEX `actor_registry_status_last_turn_idx` ON `actor_registry` (`status`, `last_turn_time`);\n",timestamp:1778803200000,name:"20260515000000_actor_rename"},{sql:"CREATE TABLE `memory_fts` (\n `path` text PRIMARY KEY NOT NULL,\n `scope` text NOT NULL,\n `scope_id` text DEFAULT '' NOT NULL,\n `type` text NOT NULL,\n `body` text NOT NULL,\n `fingerprint` text NOT NULL,\n `last_indexed_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `memory_fts_scope_idx` ON `memory_fts` (`scope`, `scope_id`);\n--> statement-breakpoint\nCREATE INDEX `memory_fts_type_idx` ON `memory_fts` (`type`);\n--> statement-breakpoint\nCREATE VIRTUAL TABLE `memory_fts_idx` USING fts5(\n body,\n content='memory_fts',\n content_rowid='rowid',\n tokenize='unicode61 remove_diacritics 1'\n);\n--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ai` AFTER INSERT ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.rowid, NEW.body);\nEND;\n--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ad` AFTER DELETE ON `memory_fts` BEGIN\n DELETE FROM `memory_fts_idx` WHERE rowid = OLD.rowid;\nEND;\n--> statement-breakpoint\nCREATE TRIGGER `memory_fts_au` AFTER UPDATE ON `memory_fts` BEGIN\n DELETE FROM `memory_fts_idx` WHERE rowid = OLD.rowid;\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.rowid, NEW.body);\nEND;\n",timestamp:1778806800000,name:"20260515010000_memory_fts"},{sql:"CREATE TABLE `task` (\n `id` text NOT NULL,\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `parent_task_id` text,\n `kind` text NOT NULL DEFAULT 'user',\n `status` text NOT NULL,\n `focus` integer NOT NULL DEFAULT 0,\n `summary` text NOT NULL,\n `created_at` integer NOT NULL,\n `last_event_at` integer NOT NULL,\n `ended_at` integer,\n `cleanup_after` integer,\n PRIMARY KEY (`session_id`, `id`)\n);--> statement-breakpoint\nCREATE INDEX `task_session_idx` ON `task` (`session_id`);--> statement-breakpoint\nCREATE INDEX `task_parent_idx` ON `task` (`session_id`, `parent_task_id`);--> statement-breakpoint\nCREATE INDEX `task_status_idx` ON `task` (`status`);--> statement-breakpoint\nCREATE INDEX `task_kind_idx` ON `task` (`kind`);--> statement-breakpoint\nCREATE UNIQUE INDEX `task_focus_per_session_idx` ON `task` (`session_id`) WHERE focus = 1;--> statement-breakpoint\nCREATE TABLE `task_event` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `task_id` text NOT NULL,\n `at` integer NOT NULL,\n `kind` text NOT NULL,\n `summary` text,\n FOREIGN KEY (`session_id`, `task_id`) REFERENCES `task`(`session_id`, `id`) ON DELETE CASCADE\n);--> statement-breakpoint\nCREATE INDEX `task_event_task_idx` ON `task_event` (`session_id`, `task_id`, `at`);\n",timestamp:1778810400000,name:"20260515020000_user_task"},{sql:"ALTER TABLE `session` ADD `last_checkpoint_message_id` text;\n",timestamp:1779148800000,name:"20260519000000_last_checkpoint_message_id"},{sql:"ALTER TABLE `message` ADD `agent_id` text;--> statement-breakpoint\nCREATE INDEX `message_session_agent_idx` ON `message` (`session_id`,`agent_id`,`id`);\n",timestamp:1779321600000,name:"20260521000000_message_agent_id"},{sql:"DROP TABLE `actor_registry`;--> statement-breakpoint\nCREATE TABLE `actor_registry` (\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `actor_id` text NOT NULL,\n `mode` text NOT NULL,\n `parent_actor_id` text,\n `status` text NOT NULL,\n `agent` text NOT NULL,\n `description` text NOT NULL,\n `context_mode` text NOT NULL,\n `context_watermark` text,\n `background` integer NOT NULL,\n `tools` text,\n `last_turn_time` integer NOT NULL,\n `turn_count` integer NOT NULL DEFAULT 0,\n `error` text,\n `time_completed` integer,\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL,\n PRIMARY KEY (`session_id`, `actor_id`)\n);--> statement-breakpoint\nCREATE INDEX `actor_registry_session_agent_idx` ON `actor_registry` (`session_id`, `agent`);--> statement-breakpoint\nCREATE INDEX `actor_registry_session_parent_idx` ON `actor_registry` (`session_id`, `parent_actor_id`);--> statement-breakpoint\nCREATE INDEX `actor_registry_status_idx` ON `actor_registry` (`status`);--> statement-breakpoint\nCREATE INDEX `actor_registry_status_last_turn_idx` ON `actor_registry` (`status`, `last_turn_time`);\n",timestamp:1779321660000,name:"20260521000100_actor_registry_v6"},{sql:"DROP TRIGGER IF EXISTS `memory_fts_ai`;--> statement-breakpoint\nDROP TRIGGER IF EXISTS `memory_fts_ad`;--> statement-breakpoint\nDROP TRIGGER IF EXISTS `memory_fts_au`;--> statement-breakpoint\nDROP TABLE IF EXISTS `memory_fts_idx`;--> statement-breakpoint\nDROP TABLE IF EXISTS `memory_fts`;--> statement-breakpoint\nCREATE TABLE `memory_fts` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `path` text NOT NULL UNIQUE,\n `scope` text NOT NULL,\n `scope_id` text DEFAULT '' NOT NULL,\n `type` text NOT NULL,\n `body` text NOT NULL,\n `fingerprint` text NOT NULL,\n `last_indexed_at` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `memory_fts_scope_idx` ON `memory_fts` (`scope`, `scope_id`);--> statement-breakpoint\nCREATE INDEX `memory_fts_type_idx` ON `memory_fts` (`type`);--> statement-breakpoint\nCREATE VIRTUAL TABLE `memory_fts_idx` USING fts5(\n body,\n content='memory_fts',\n content_rowid='id',\n tokenize='unicode61 remove_diacritics 1'\n);--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ai` AFTER INSERT ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.id, NEW.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ad` AFTER DELETE ON `memory_fts` BEGIN\n DELETE FROM `memory_fts_idx` WHERE rowid = OLD.id;\nEND;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_au` AFTER UPDATE ON `memory_fts` BEGIN\n DELETE FROM `memory_fts_idx` WHERE rowid = OLD.id;\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.id, NEW.body);\nEND;\n",timestamp:1779325200000,name:"20260521010000_memory_fts_v6"},{sql:"-- Fix v6.1 trigger pattern: external content FTS5 vtab requires the 'delete'\n-- magic command to remove OLD body's tokens, NOT a plain DELETE FROM the vtab.\n-- The previous DELETE FROM pattern was contentless-mode syntax misapplied to\n-- external-content mode, leaving stale tokens accumulating until vtab corrupts.\nDROP TRIGGER IF EXISTS `memory_fts_ai`;--> statement-breakpoint\nDROP TRIGGER IF EXISTS `memory_fts_ad`;--> statement-breakpoint\nDROP TRIGGER IF EXISTS `memory_fts_au`;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ai` AFTER INSERT ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.id, NEW.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ad` AFTER DELETE ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(`memory_fts_idx`, rowid, body) VALUES('delete', OLD.id, OLD.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_au` AFTER UPDATE ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(`memory_fts_idx`, rowid, body) VALUES('delete', OLD.id, OLD.body);\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.id, NEW.body);\nEND;\n",timestamp:1779328800000,name:"20260521020000_memory_fts_triggers"},{sql:"UPDATE `message` SET `agent_id` = 'main' WHERE `agent_id` IS NULL;--> statement-breakpoint\nCREATE TABLE `message_new` (\n `id` text PRIMARY KEY NOT NULL,\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `agent_id` text NOT NULL DEFAULT 'main',\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL,\n `data` text NOT NULL\n);--> statement-breakpoint\nINSERT INTO `message_new` SELECT `id`, `session_id`, COALESCE(`agent_id`, 'main'), `time_created`, `time_updated`, `data` FROM `message`;--> statement-breakpoint\nDROP TABLE `message`;--> statement-breakpoint\nALTER TABLE `message_new` RENAME TO `message`;--> statement-breakpoint\nCREATE INDEX `message_session_time_created_id_idx` ON `message` (`session_id`,`time_created`,`id`);--> statement-breakpoint\nCREATE INDEX `message_session_agent_idx` ON `message` (`session_id`,`agent_id`,`id`);\n",timestamp:1779753600000,name:"20260526000000_agent_id_main"},{sql:"ALTER TABLE `actor_registry` ADD COLUMN `last_outcome` text;--> statement-breakpoint\nALTER TABLE `actor_registry` ADD COLUMN `lifecycle` text NOT NULL DEFAULT 'ephemeral';--> statement-breakpoint\nALTER TABLE `actor_registry` RENAME COLUMN `error` TO `last_error`;--> statement-breakpoint\nUPDATE `actor_registry` SET `last_outcome` = 'success' WHERE `status` = 'completed';--> statement-breakpoint\nUPDATE `actor_registry` SET `last_outcome` = 'failure' WHERE `status` = 'failed';--> statement-breakpoint\nUPDATE `actor_registry` SET `last_outcome` = 'cancelled' WHERE `status` = 'cancelled';--> statement-breakpoint\nUPDATE `actor_registry` SET `status` = 'idle' WHERE `status` IN ('completed','failed','cancelled');--> statement-breakpoint\nUPDATE `actor_registry` SET `lifecycle` = CASE `mode` WHEN 'peer' THEN 'persistent' WHEN 'main' THEN 'persistent' ELSE 'ephemeral' END;\n",timestamp:1779840000000,name:"20260527000000_actor_lifecycle"},{sql:"CREATE TABLE `inbox` (\n `id` text PRIMARY KEY NOT NULL,\n `receiver_session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `receiver_actor_id` text NOT NULL,\n `sender_session_id` text,\n `sender_actor_id` text,\n `type` text NOT NULL DEFAULT 'text',\n `content` text NOT NULL,\n `created_at` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `inbox_receiver_idx` ON `inbox` (`receiver_session_id`,`receiver_actor_id`,`id`);--> statement-breakpoint\nCREATE INDEX `inbox_created_idx` ON `inbox` (`created_at`);\n",timestamp:1779840060000,name:"20260527000100_inbox"},{sql:"-- todo: drop priority column\nALTER TABLE `todo` DROP COLUMN `priority`;\n--> statement-breakpoint\n\n-- task: drop focus-dependent index before dropping its column\nDROP INDEX `task_focus_per_session_idx`;\n--> statement-breakpoint\nDROP INDEX `task_kind_idx`;\n--> statement-breakpoint\nALTER TABLE `task` DROP COLUMN `focus`;\n--> statement-breakpoint\nALTER TABLE `task` DROP COLUMN `kind`;\n--> statement-breakpoint\n\n-- migrate status values: proposed/active -> open\nUPDATE `task` SET `status` = 'open' WHERE `status` IN ('proposed', 'active');\n",timestamp:1780012800000,name:"20260529000000_task_todo_redesign"},{sql:"ALTER TABLE `task` ADD COLUMN `owner` text;\n",timestamp:1780444800000,name:"20260603000000_task_in_progress_owner"},{sql:"CREATE TABLE `workflow_run` (\n `id` text PRIMARY KEY NOT NULL,\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `name` text NOT NULL,\n `status` text NOT NULL,\n `running` integer NOT NULL DEFAULT 0,\n `succeeded` integer NOT NULL DEFAULT 0,\n `failed` integer NOT NULL DEFAULT 0,\n `current_phase` text,\n `parent_actor_id` text,\n `args` text,\n `error` text,\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `workflow_run_session_idx` ON `workflow_run` (`session_id`);--> statement-breakpoint\nCREATE INDEX `workflow_run_status_idx` ON `workflow_run` (`status`);\n",timestamp:1780444800000,name:"20260603000000_workflow_run"},{sql:"ALTER TABLE `workflow_run` ADD COLUMN `script_sha` text;\n",timestamp:1780531200000,name:"20260604000000_workflow_script_sha"},{sql:"CREATE TABLE `claude_import` (\n `source_uuid` text PRIMARY KEY NOT NULL,\n `session_id` text NOT NULL,\n `source_path` text NOT NULL,\n `source_mtime` integer NOT NULL,\n `time_imported` integer NOT NULL\n);\n",timestamp:1780876800000,name:"20260608000000_claude_import"},{sql:"ALTER TABLE `claude_import` ADD `message_ids` text;\n",timestamp:1780880400000,name:"20260608010000_claude_import_message_ids"},{sql:"CREATE TABLE `history_fts` (\n `part_id` text PRIMARY KEY NOT NULL,\n `session_id` text NOT NULL,\n `message_id` text NOT NULL,\n `project_id` text NOT NULL,\n `kind` text NOT NULL,\n `tool_name` text,\n `body` text NOT NULL,\n `time_created` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `history_fts_session_idx` ON `history_fts` (`session_id`, `time_created`);--> statement-breakpoint\nCREATE INDEX `history_fts_project_idx` ON `history_fts` (`project_id`, `time_created`);--> statement-breakpoint\nCREATE INDEX `history_fts_message_idx` ON `history_fts` (`message_id`);--> statement-breakpoint\nCREATE VIRTUAL TABLE `history_fts_idx` USING fts5(\n body,\n content='history_fts',\n content_rowid='rowid',\n tokenize='unicode61 remove_diacritics 1'\n);--> statement-breakpoint\nCREATE TRIGGER `history_fts_ai` AFTER INSERT ON `history_fts` BEGIN\n INSERT INTO `history_fts_idx`(rowid, body) VALUES (NEW.rowid, NEW.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `history_fts_ad` AFTER DELETE ON `history_fts` BEGIN\n INSERT INTO `history_fts_idx`(`history_fts_idx`, rowid, body) VALUES('delete', OLD.rowid, OLD.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `history_fts_au` AFTER UPDATE ON `history_fts` BEGIN\n INSERT INTO `history_fts_idx`(`history_fts_idx`, rowid, body) VALUES('delete', OLD.rowid, OLD.body);\n INSERT INTO `history_fts_idx`(rowid, body) VALUES (NEW.rowid, NEW.body);\nEND;\n",timestamp:1780963200000,name:"20260609000000_history_fts"},{sql:"ALTER TABLE `workflow_run` ADD COLUMN `agent_timeout_ms` integer;\n",timestamp:1781046000000,name:"20260609230000_workflow_agent_timeout"},{sql:"CREATE TABLE `external_import` (\n `source` text NOT NULL,\n `source_key` text NOT NULL,\n `session_id` text NOT NULL,\n `source_path` text NOT NULL,\n `source_mtime` integer NOT NULL,\n `time_imported` integer NOT NULL,\n `message_ids` text,\n PRIMARY KEY (`source`, `source_key`)\n);\n\nINSERT INTO `external_import` (`source`, `source_key`, `session_id`, `source_path`, `source_mtime`, `time_imported`, `message_ids`)\nSELECT 'cc', `source_uuid`, `session_id`, `source_path`, `source_mtime`, `time_imported`, `message_ids`\nFROM `claude_import`;\n\nDROP TABLE `claude_import`;\n",timestamp:1781222400000,name:"20260612000000_external_import"}];if(o.length>0){if(fi.info("applying migrations",{count:o.length,mode:"bundled"}),nn.QITQODE_SKIP_MIGRATIONS)for(let i of o)i.sql="select 1;";ao(n,o)}return n});function Se(){Mn().$client.close(),Mn.reset()}var Yn=gn.create("database");function Ce(n){try{return n(Yn.use().tx)}catch(o){if(o instanceof gn.NotFound){let i=[],l=Yn.provide({effects:i,tx:Mn()},()=>n(Mn()));for(let e of i)e();return l}throw o}}function He(n){let o=Un.bind(n);try{Yn.use().effects.push(o)}catch{o()}}function xe(n,o){try{return n(Yn.use().tx)}catch(i){if(i instanceof gn.NotFound){let l=[],e=Un.bind((_)=>Yn.provide({tx:_,effects:l},()=>n(_))),A=Mn().transaction(e,{behavior:o?.behavior});for(let _ of l)_();return A}throw i}}var Oi={};On(Oi,{layer:()=>Ti,defaultLayer:()=>we,Service:()=>to,NotFoundError:()=>Zo});import X from"path";var Sn={};On(Sn,{layer:()=>pi,defaultLayer:()=>Ee,Service:()=>io,Git:()=>Sn});var Ke=["--no-optional-locks","-c","core.autocrlf=false","-c","core.fsmonitor=false","-c","core.longpaths=true","-c","core.symlinks=true","-c","core.quotepath=false"],zn=(n)=>n.text().trim(),Po=(n)=>n.split("\x00").filter(Boolean),Re=(n)=>({exitCode:1,text:()=>"",stdout:Buffer.alloc(0),stderr:Buffer.from(n instanceof Error?n.message:String(n))}),si=(n)=>{if(n==="??")return"added";if(n.includes("U"))return"modified";if(n.includes("A")&&!n.includes("D"))return"added";if(n.includes("D")&&!n.includes("A"))return"deleted";return"modified"};class io extends vn.Service()("@qitqode/Git"){}var pi=h.effect(io,r.gen(function*(){let n=yield*an.ChildProcessSpawner,o=r.fn("Git.run")(function*(g,s){let m=_i.make("git",[...Ke,...g],{cwd:s.cwd,env:s.env,extendEnv:!0,stdin:"ignore",stdout:"pipe",stderr:"pipe"}),y=yield*Ni(n,m);return{exitCode:y.code,text:()=>y.text,stdout:Buffer.from(y.text),stderr:Buffer.from(y.stderr)}},r.scoped,r.catch((g)=>r.succeed(Re(g)))),i=r.fn("Git.text")(function*(g,s){return(yield*o(g,s)).text()}),l=r.fn("Git.lines")(function*(g,s){return(yield*i(g,s)).split(/\r?\n/).map((m)=>m.trim()).filter(Boolean)}),e=r.fnUntraced(function*(g){return yield*l(["for-each-ref","--format=%(refname:short)","refs/heads"],{cwd:g})}),A=r.fnUntraced(function*(g,s){let m=yield*o(["config","init.defaultBranch"],{cwd:g}),y=zn(m);if(!y||!s.includes(y))return;return{name:y,ref:y}}),_=r.fnUntraced(function*(g){let s=yield*l(["remote"],{cwd:g});if(s.includes("origin"))return"origin";if(s.length===1)return s[0];if(s.includes("upstream"))return"upstream";return s[0]}),T=r.fn("Git.branch")(function*(g){let s=yield*o(["symbolic-ref","--quiet","--short","HEAD"],{cwd:g});if(s.exitCode!==0)return;return zn(s)||void 0}),M=r.fn("Git.prefix")(function*(g){let s=yield*o(["rev-parse","--show-prefix"],{cwd:g});if(s.exitCode!==0)return"";return zn(s)}),x=r.fn("Git.defaultBranch")(function*(g){let s=yield*_(g);if(s){let t=yield*o(["symbolic-ref",`refs/remotes/${s}/HEAD`],{cwd:g});if(t.exitCode===0){let u=zn(t).replace(/^refs\/remotes\//,""),D=u.startsWith(`${s}/`)?u.slice(`${s}/`.length):"";if(D)return{name:D,ref:u}}}let m=yield*e(g),y=yield*A(g,m);if(y)return y;if(m.includes("main"))return{name:"main",ref:"main"};if(m.includes("master"))return{name:"master",ref:"master"}}),C=r.fn("Git.hasHead")(function*(g){return(yield*o(["rev-parse","--verify","HEAD"],{cwd:g})).exitCode===0}),H=r.fn("Git.mergeBase")(function*(g,s,m="HEAD"){let y=yield*o(["merge-base",s,m],{cwd:g});if(y.exitCode!==0)return;return zn(y)||void 0}),K=r.fn("Git.show")(function*(g,s,m,y=""){let t=y?`${y}${m}`:m,u=yield*o(["show",`${s}:${t}`],{cwd:g});if(u.exitCode!==0)return"";if(u.stdout.includes(0))return"";return u.text()}),$=r.fn("Git.status")(function*(g){return Po(yield*i(["status","--porcelain=v1","--untracked-files=all","--no-renames","-z","--","."],{cwd:g})).flatMap((s)=>{let m=s.slice(3);if(!m)return[];let y=s.slice(0,2);return[{file:m,code:y,status:si(y)}]})}),Q=r.fn("Git.diff")(function*(g,s){let m=Po(yield*i(["diff","--no-ext-diff","--no-renames","--name-status","-z",s,"--","."],{cwd:g}));return m.flatMap((y,t)=>{if(t%2!==0)return[];let u=m[t+1];if(!y||!u)return[];return[{file:u,code:y,status:si(y)}]})}),L=r.fn("Git.stats")(function*(g,s){return Po(yield*i(["diff","--no-ext-diff","--no-renames","--numstat","-z",s,"--","."],{cwd:g})).flatMap((m)=>{let y=m.indexOf("\t"),t=m.indexOf("\t",y+1);if(y===-1||t===-1)return[];let u=m.slice(t+1);if(!u)return[];let D=m.slice(0,y),I=m.slice(y+1,t),O=D==="-"?0:Number.parseInt(D||"0",10),P=I==="-"?0:Number.parseInt(I||"0",10);return[{file:u,additions:Number.isFinite(O)?O:0,deletions:Number.isFinite(P)?P:0}]})});return io.of({run:o,branch:T,prefix:M,defaultBranch:x,hasHead:C,mergeBase:H,show:K,status:$,diff:Q,stats:L})})),Ee=pi.pipe(h.provide(bn));var An=c.create({service:"storage"}),Zo=ro.create("NotFoundError",a.object({message:a.string()})),Pe=N.Struct({path:N.optional(N.Struct({root:N.optional(N.String)}))}),We=N.Struct({id:N.String}),Ue=N.Struct({id:N.String}),Ze=N.Struct({additions:N.Number,deletions:N.Number}),Xe=N.Struct({id:N.String,projectID:N.String,summary:N.Struct({diffs:N.Array(Ze)})}),Ye=N.decodeUnknownOption(Pe),ze=N.decodeUnknownOption(We),ce=N.decodeUnknownOption(Ue),ke=N.decodeUnknownOption(Xe);class to extends vn.Service()("@qitqode/Storage"){}function qe(n,o){return X.join(n,...o)+".json"}function Wo(n){if(!n||typeof n!=="object")return!1;if("code"in n&&n.code==="ENOENT")return!0;if("reason"in n&&n.reason&&typeof n.reason==="object"&&"_tag"in n.reason)return n.reason._tag==="NotFound";return!1}function Ve(n){let o=Number.parseInt(n,10);return Number.isNaN(o)?0:o}var Ai=[r.fn("Storage.migration.1")(function*(n,o,i){let l=X.resolve(n,"../project");if(!(yield*o.isDir(l)))return;let e=yield*o.glob("*",{cwd:l,include:"all"});for(let A of e){let _=X.join(l,A);if(!(yield*o.isDir(_)))continue;An.info(`migrating project ${A}`);let T=A,M="/";if(T!=="global"){for(let H of yield*o.glob("storage/session/message/*/*.json",{cwd:_,absolute:!0})){let K=Ye(yield*o.readJson(H),{onExcessProperty:"preserve"}),$=cn.isSome(K)?K.value.path?.root:void 0;if(!$)continue;M=$;break}if(!M)continue;if(!(yield*o.isDir(M)))continue;let x=yield*i.run(["rev-list","--max-parents=0","--all"],{cwd:M}),[C]=x.text().split(`
5
5
  `).filter(Boolean).map((H)=>H.trim()).toSorted();if(!C)continue;T=C,yield*o.writeWithDirs(X.join(n,"project",T+".json"),JSON.stringify({id:C,vcs:"git",worktree:M,time:{created:Date.now(),initialized:Date.now()}},null,2)),An.info(`migrating sessions for project ${T}`);for(let H of yield*o.glob("storage/session/info/*.json",{cwd:_,absolute:!0})){let K=X.join(n,"session",T,X.basename(H));An.info("copying",{sessionFile:H,dest:K});let $=yield*o.readJson(H),Q=ze($,{onExcessProperty:"preserve"});if(yield*o.writeWithDirs(K,JSON.stringify($,null,2)),cn.isNone(Q))continue;An.info(`migrating messages for session ${Q.value.id}`);for(let L of yield*o.glob(`storage/session/message/${Q.value.id}/*.json`,{cwd:_,absolute:!0})){let g=X.join(n,"message",Q.value.id,X.basename(L));An.info("copying",{msgFile:L,dest:g});let s=yield*o.readJson(L),m=ce(s,{onExcessProperty:"preserve"});if(yield*o.writeWithDirs(g,JSON.stringify(s,null,2)),cn.isNone(m))continue;An.info(`migrating parts for message ${m.value.id}`);for(let y of yield*o.glob(`storage/session/part/${Q.value.id}/${m.value.id}/*.json`,{cwd:_,absolute:!0})){let t=X.join(n,"part",m.value.id,X.basename(y)),u=yield*o.readJson(y);An.info("copying",{partFile:y,dest:t}),yield*o.writeWithDirs(t,JSON.stringify(u,null,2))}}}}}}),r.fn("Storage.migration.2")(function*(n,o){for(let i of yield*o.glob("session/*/*.json",{cwd:n,absolute:!0})){let l=yield*o.readJson(i),e=ke(l,{onExcessProperty:"preserve"});if(cn.isNone(e))continue;let A=e.value.summary.diffs;yield*o.writeWithDirs(X.join(n,"session_diff",e.value.id+".json"),JSON.stringify(A,null,2)),yield*o.writeWithDirs(X.join(n,"session",e.value.projectID,e.value.id+".json"),JSON.stringify({...l,summary:{additions:A.reduce((_,T)=>_+T.additions,0),deletions:A.reduce((_,T)=>_+T.deletions,0)}},null,2))}})],Ti=h.effect(to,r.gen(function*(){let n=yield*k.Service,o=yield*Sn.Service,i=yield*Uo.make({lookup:()=>Cn.make(),idleTimeToLive:0}),l=yield*r.cached(r.gen(function*(){let $=X.join($n.Path.data,"storage"),Q=X.join($,"migration"),L=yield*n.readFileString(Q).pipe(r.map(Ve),r.catchIf(Wo,()=>r.succeed(0)),r.orElseSucceed(()=>0));for(let g=L;g<Ai.length;g++){An.info("running migration",{index:g});let s=Ai[g],m=yield*r.exit(s($,n,o));if(Xn.isFailure(m)){An.error("failed to run migration",{index:g,cause:m.cause});break}yield*n.writeWithDirs(Q,String(g+1))}return{dir:$}})),e=($)=>r.fail(new Zo({message:`Resource not found: ${$}`})),A=($,Q)=>Q.pipe(r.catchIf(Wo,()=>e($))),_=r.fnUntraced(function*($,Q){yield*n.writeWithDirs($,JSON.stringify(Q,null,2))}),T=($,Q)=>r.scoped(r.gen(function*(){let L=qe((yield*l).dir,$);return yield*Q(L,yield*Uo.get(i,L))})),M=r.fn("Storage.remove")(function*($){yield*T($,(Q,L)=>Cn.withWriteLock(L,n.remove(Q).pipe(r.catchIf(Wo,()=>r.void))))}),x=($)=>r.gen(function*(){return yield*T($,(L,g)=>Cn.withReadLock(g,A(L,n.readJson(L))))}),C=($,Q)=>r.gen(function*(){return yield*T($,(g,s)=>Cn.withWriteLock(s,r.gen(function*(){let m=yield*A(g,n.readJson(g));return Q(m),yield*_(g,m),m})))}),H=($,Q)=>r.gen(function*(){yield*T($,(L,g)=>Cn.withWriteLock(g,_(L,Q)))}),K=r.fn("Storage.list")(function*($){let Q=(yield*l).dir,L=X.join(Q,...$);return(yield*n.glob("**/*",{cwd:L,include:"file"}).pipe(r.catch(()=>r.succeed([])))).map((s)=>[...$,...s.slice(0,-5).split(X.sep)]).toSorted((s,m)=>s.join("/").localeCompare(m.join("/")))});return to.of({remove:M,read:x,update:C,write:H,list:K})})),we=Ti.pipe(h.provide(k.defaultLayer),h.provide(Sn.defaultLayer));export{Rn as pl,xr as ql,En as rl,mn as sl,J as tl,fn as ul,eo as vl,Yo as wl,zo as xl,co as yl,ko as zl,Vo as Al,fo as Bl,In as Cl,Sn as Dl,Zo as El,Oi as Fl,w as Gl,Jo as Hl,Pr as Il,se as Jl,jr as Kl,Ae as Ll,on as Ml,Un as Nl,de as Ol,ei as Pl,mi as Ql};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{As as f,Bs as g,Ds as h,Es as i,Fs as j,Gs as k,Hs as l,Js as m,Ks as n,zs as e}from"./chunk-1mfdmm2t.js";import{Ps as d}from"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import{At as c}from"./chunk-8jkqyf9n.js";import"./chunk-6yshpz0z.js";import{Yt as b}from"./chunk-5dvy83ms.js";import{hu as a}from"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-sh03ka27.js";export{h as getEnvInfo,c as Wildcard,n as Token,m as Rpc,d as Process,b as Log,l as Lock,k as Locale,j as LocalContext,i as Keybind,a as Filesystem,g as EffectUtil,f as Color,e as Archive};
2
+ import{As as f,Bs as g,Ds as h,Es as i,Fs as j,Gs as k,Hs as l,Js as m,Ks as n,zs as e}from"./chunk-4yd2vvh6.js";import{Ps as d}from"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import{At as c}from"./chunk-mnjz8nqs.js";import"./chunk-6yshpz0z.js";import{Yt as b}from"./chunk-5dvy83ms.js";import{hu as a}from"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-sh03ka27.js";export{h as getEnvInfo,c as Wildcard,n as Token,m as Rpc,d as Process,b as Log,l as Lock,k as Locale,j as LocalContext,i as Keybind,a as Filesystem,g as EffectUtil,f as Color,e as Archive};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Fn as K,in as j,jn as R,kn as O,ln as A,rn as y,wn as q,xn as M,zn as C}from"./chunk-hx13a8es.js";import{Ps as D}from"./chunk-fkq0v5qv.js";import{Gt as m,Jt as v}from"./chunk-6yshpz0z.js";import{hu as d,ju as b,mu as I}from"./chunk-ffx0cr44.js";import{AP as _,zP as T}from"./chunk-sh03ka27.js";import P from"path";function pt(t){let e=t&&typeof t==="object"&&"cause"in t?t.cause??t:t;if(!(e instanceof D.RunFailedError))return{error:e,detail:v(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??I.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 b.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{Fn as K,in as j,jn as R,kn as O,ln as A,rn as y,wn as q,xn as M,zn as C}from"./chunk-83n11xym.js";import{Ps as D}from"./chunk-fkq0v5qv.js";import{Gt as m,Jt as v}from"./chunk-6yshpz0z.js";import{hu as d,ju as b,mu as I}from"./chunk-ffx0cr44.js";import{AP as _,zP as T}from"./chunk-sh03ka27.js";import P from"path";function pt(t){let e=t&&typeof t==="object"&&"cause"in t?t.cause??t:t;if(!(e instanceof D.RunFailedError))return{error:e,detail:v(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??I.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 b.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 p,z as q,gt as r,dt as s,mt as t};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ud as b}from"./chunk-fpzkyzny.js";import{fe as f}from"./chunk-w8nj5ph5.js";import{Ah as S}from"./chunk-fd04358e.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import{bl as v}from"./chunk-y1v7mf1a.js";import"./chunk-358wdvj7.js";import{Cl as R,Ml as k,ul as U}from"./chunk-dn0437c1.js";import"./chunk-47jkx37s.js";import"./chunk-31a47ptm.js";import"./chunk-jwv6fda1.js";import"./chunk-hx13a8es.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-j1bv93m4.js";import"./chunk-pp10epga.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-9znfb8f2.js";import"./chunk-6kch0q2d.js";import"./chunk-6cztstry.js";import{Gs as Z}from"./chunk-1mfdmm2t.js";import"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-1a08ffyd.js";import"./chunk-8jkqyf9n.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import"./chunk-sh03ka27.js";var i=f({command:"stats",describe:"show token usage and cost statistics",builder:(z)=>{return z.option("days",{describe:"show stats for the last N days (default: all time)",type:"number"}).option("tools",{describe:"number of tools to show (default: all)",type:"number"}).option("models",{describe:"show model statistics (default: hidden). Pass a number to show top N, otherwise shows all"}).option("project",{describe:"filter by project (default: all projects, empty string: current project)",type:"string"})},handler:async(z)=>{await b(process.cwd(),async()=>{let E=await y(z.days,z.project),_;if(z.models===!0)_=1/0;else if(typeof z.models==="number")_=z.models;u(E,z.tools,_)})}});async function w(){return k.project}async function p(){return R.use((E)=>E.select().from(U).all()).map((E)=>v.fromRow(E))}async function y(z,E){let _=await p(),L=86400000,J=(()=>{if(z===void 0)return 0;if(z===0){let V=new Date;return V.setHours(0,0,0,0),V.getTime()}return Date.now()-z*86400000})(),K=(()=>{if(z===void 0)return;if(z===0)return 1;return z})(),Y=J>0?_.filter((V)=>V.time.updated>=J):_;if(E!==void 0)if(E===""){let V=await w();Y=Y.filter((F)=>F.projectID===V.id)}else Y=Y.filter((V)=>V.projectID===E);let G={totalSessions:Y.length,totalMessages:0,totalCost:0,totalTokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},toolUsage:{},modelUsage:{},dateRange:{earliest:Date.now(),latest:Date.now()},days:0,costPerDay:0,tokensPerSession:0,medianTokensPerSession:0};if(Y.length>1000)console.log(`Large dataset detected (${Y.length} sessions). This may take a while...`);if(Y.length===0)return G.days=K??0,G;let C=Date.now(),x=0,X=[],h=20;for(let V=0;V<Y.length;V+=h){let D=Y.slice(V,V+h).map(async(Q)=>{let W=await S.runPromise(v.Service.use((O)=>O.messages({sessionID:Q.id,agentID:"*"}))),N=0,H={input:0,output:0,reasoning:0,cache:{read:0,write:0}},j={},A={};for(let O of W){if(O.info.role==="assistant"){N+=O.info.cost||0;let B=`${O.info.providerID}/${O.info.modelID}`;if(!A[B])A[B]={messages:0,tokens:{input:0,output:0,cache:{read:0,write:0}},cost:0};if(A[B].messages++,A[B].cost+=O.info.cost||0,O.info.tokens)H.input+=O.info.tokens.input||0,H.output+=O.info.tokens.output||0,H.reasoning+=O.info.tokens.reasoning||0,H.cache.read+=O.info.tokens.cache?.read||0,H.cache.write+=O.info.tokens.cache?.write||0,A[B].tokens.input+=O.info.tokens.input||0,A[B].tokens.output+=(O.info.tokens.output||0)+(O.info.tokens.reasoning||0),A[B].tokens.cache.read+=O.info.tokens.cache?.read||0,A[B].tokens.cache.write+=O.info.tokens.cache?.write||0}for(let B of O.parts)if(B.type==="tool"&&B.tool)j[B.tool]=(j[B.tool]||0)+1}return{messageCount:W.length,sessionCost:N,sessionTokens:H,sessionTotalTokens:H.input+H.output+H.reasoning+H.cache.read+H.cache.write,sessionToolUsage:j,sessionModelUsage:A,earliestTime:J>0?Q.time.updated:Q.time.created,latestTime:Q.time.updated}}),M=await Promise.all(D);for(let Q of M){C=Math.min(C,Q.earliestTime),x=Math.max(x,Q.latestTime),X.push(Q.sessionTotalTokens),G.totalMessages+=Q.messageCount,G.totalCost+=Q.sessionCost,G.totalTokens.input+=Q.sessionTokens.input,G.totalTokens.output+=Q.sessionTokens.output,G.totalTokens.reasoning+=Q.sessionTokens.reasoning,G.totalTokens.cache.read+=Q.sessionTokens.cache.read,G.totalTokens.cache.write+=Q.sessionTokens.cache.write;for(let[W,N]of Object.entries(Q.sessionToolUsage))G.toolUsage[W]=(G.toolUsage[W]||0)+N;for(let[W,N]of Object.entries(Q.sessionModelUsage)){if(!G.modelUsage[W])G.modelUsage[W]={messages:0,tokens:{input:0,output:0,cache:{read:0,write:0}},cost:0};G.modelUsage[W].messages+=N.messages,G.modelUsage[W].tokens.input+=N.tokens.input,G.modelUsage[W].tokens.output+=N.tokens.output,G.modelUsage[W].tokens.cache.read+=N.tokens.cache.read,G.modelUsage[W].tokens.cache.write+=N.tokens.cache.write,G.modelUsage[W].cost+=N.cost}}}let $=Math.max(1,Math.ceil((x-C)/86400000)),q=K??$;G.dateRange={earliest:C,latest:x},G.days=q,G.costPerDay=G.totalCost/q;let I=G.totalTokens.input+G.totalTokens.output+G.totalTokens.reasoning+G.totalTokens.cache.read+G.totalTokens.cache.write;G.tokensPerSession=Y.length>0?I/Y.length:0,X.sort((V,F)=>V-F);let P=Math.floor(X.length/2);return G.medianTokensPerSession=X.length===0?0:X.length%2===0?(X[P-1]+X[P])/2:X[P],G}function u(z,E,_){function J(x,X){let $=55-x.length-X.length,q=Math.max(0,$);return`\u2502${x}${" ".repeat(q)}${X} \u2502`}console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 OVERVIEW \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(J("Sessions",z.totalSessions.toLocaleString())),console.log(J("Messages",z.totalMessages.toLocaleString())),console.log(J("Days",z.days.toString())),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 COST & TOKENS \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");let K=isNaN(z.totalCost)?0:z.totalCost,Y=isNaN(z.costPerDay)?0:z.costPerDay,G=isNaN(z.tokensPerSession)?0:z.tokensPerSession;console.log(J("Total Cost",`$${K.toFixed(2)}`)),console.log(J("Avg Cost/Day",`$${Y.toFixed(2)}`)),console.log(J("Avg Tokens/Session",Z.number(Math.round(G))));let C=isNaN(z.medianTokensPerSession)?0:z.medianTokensPerSession;if(console.log(J("Median Tokens/Session",Z.number(Math.round(C)))),console.log(J("Input",Z.number(z.totalTokens.input))),console.log(J("Output",Z.number(z.totalTokens.output))),console.log(J("Cache Read",Z.number(z.totalTokens.cache.read))),console.log(J("Cache Write",Z.number(z.totalTokens.cache.write))),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(),_!==void 0&&Object.keys(z.modelUsage).length>0){let x=Object.entries(z.modelUsage).sort(([,h],[,$])=>$.messages-h.messages),X=_===1/0?x:x.slice(0,_);console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 MODEL USAGE \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");for(let[h,$]of X)console.log(`\u2502 ${h.padEnd(54)} \u2502`),console.log(J(" Messages",$.messages.toLocaleString())),console.log(J(" Input Tokens",Z.number($.tokens.input))),console.log(J(" Output Tokens",Z.number($.tokens.output))),console.log(J(" Cache Read",Z.number($.tokens.cache.read))),console.log(J(" Cache Write",Z.number($.tokens.cache.write))),console.log(J(" Cost",`$${$.cost.toFixed(4)}`)),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");process.stdout.write("\x1B[1A"),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")}if(console.log(),Object.keys(z.toolUsage).length>0){let x=Object.entries(z.toolUsage).sort(([,q],[,I])=>I-q),X=E?x.slice(0,E):x;console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 TOOL USAGE \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");let h=Math.max(...X.map(([,q])=>q)),$=Object.values(z.toolUsage).reduce((q,I)=>q+I,0);for(let[q,I]of X){let P=Math.max(1,Math.floor(I/h*20)),V="\u2588".repeat(P),F=(I/$*100).toFixed(1),D=18,W=` ${(q.length>18?q.substring(0,16)+"..":q).padEnd(18)} ${V.padEnd(20)} ${I.toString().padStart(3)} (${F.padStart(4)}%)`,N=Math.max(0,56-W.length-1);console.log(`\u2502${W}${" ".repeat(N)} \u2502`)}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")}console.log()}export{u as displayStats,y as aggregateSessionStats,i as StatsCommand};
2
+ import{Ud as b}from"./chunk-4jfnhghx.js";import{fe as f}from"./chunk-w8nj5ph5.js";import{Ah as S}from"./chunk-6zdzbmzs.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import{bl as v}from"./chunk-5asf8f41.js";import"./chunk-2pw56zpj.js";import{Cl as R,Ml as k,ul as U}from"./chunk-rt49c6js.js";import"./chunk-4gzggzc0.js";import"./chunk-31a47ptm.js";import"./chunk-ywj77e0m.js";import"./chunk-83n11xym.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-ae1b15bd.js";import"./chunk-6qwnty59.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-kegvr7wt.js";import"./chunk-2tkgtasa.js";import"./chunk-6cztstry.js";import{Gs as Z}from"./chunk-4yd2vvh6.js";import"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-5re7995e.js";import"./chunk-mnjz8nqs.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import"./chunk-sh03ka27.js";var i=f({command:"stats",describe:"show token usage and cost statistics",builder:(z)=>{return z.option("days",{describe:"show stats for the last N days (default: all time)",type:"number"}).option("tools",{describe:"number of tools to show (default: all)",type:"number"}).option("models",{describe:"show model statistics (default: hidden). Pass a number to show top N, otherwise shows all"}).option("project",{describe:"filter by project (default: all projects, empty string: current project)",type:"string"})},handler:async(z)=>{await b(process.cwd(),async()=>{let E=await y(z.days,z.project),_;if(z.models===!0)_=1/0;else if(typeof z.models==="number")_=z.models;u(E,z.tools,_)})}});async function w(){return k.project}async function p(){return R.use((E)=>E.select().from(U).all()).map((E)=>v.fromRow(E))}async function y(z,E){let _=await p(),L=86400000,J=(()=>{if(z===void 0)return 0;if(z===0){let V=new Date;return V.setHours(0,0,0,0),V.getTime()}return Date.now()-z*86400000})(),K=(()=>{if(z===void 0)return;if(z===0)return 1;return z})(),Y=J>0?_.filter((V)=>V.time.updated>=J):_;if(E!==void 0)if(E===""){let V=await w();Y=Y.filter((F)=>F.projectID===V.id)}else Y=Y.filter((V)=>V.projectID===E);let G={totalSessions:Y.length,totalMessages:0,totalCost:0,totalTokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},toolUsage:{},modelUsage:{},dateRange:{earliest:Date.now(),latest:Date.now()},days:0,costPerDay:0,tokensPerSession:0,medianTokensPerSession:0};if(Y.length>1000)console.log(`Large dataset detected (${Y.length} sessions). This may take a while...`);if(Y.length===0)return G.days=K??0,G;let C=Date.now(),x=0,X=[],h=20;for(let V=0;V<Y.length;V+=h){let D=Y.slice(V,V+h).map(async(Q)=>{let W=await S.runPromise(v.Service.use((O)=>O.messages({sessionID:Q.id,agentID:"*"}))),N=0,H={input:0,output:0,reasoning:0,cache:{read:0,write:0}},j={},A={};for(let O of W){if(O.info.role==="assistant"){N+=O.info.cost||0;let B=`${O.info.providerID}/${O.info.modelID}`;if(!A[B])A[B]={messages:0,tokens:{input:0,output:0,cache:{read:0,write:0}},cost:0};if(A[B].messages++,A[B].cost+=O.info.cost||0,O.info.tokens)H.input+=O.info.tokens.input||0,H.output+=O.info.tokens.output||0,H.reasoning+=O.info.tokens.reasoning||0,H.cache.read+=O.info.tokens.cache?.read||0,H.cache.write+=O.info.tokens.cache?.write||0,A[B].tokens.input+=O.info.tokens.input||0,A[B].tokens.output+=(O.info.tokens.output||0)+(O.info.tokens.reasoning||0),A[B].tokens.cache.read+=O.info.tokens.cache?.read||0,A[B].tokens.cache.write+=O.info.tokens.cache?.write||0}for(let B of O.parts)if(B.type==="tool"&&B.tool)j[B.tool]=(j[B.tool]||0)+1}return{messageCount:W.length,sessionCost:N,sessionTokens:H,sessionTotalTokens:H.input+H.output+H.reasoning+H.cache.read+H.cache.write,sessionToolUsage:j,sessionModelUsage:A,earliestTime:J>0?Q.time.updated:Q.time.created,latestTime:Q.time.updated}}),M=await Promise.all(D);for(let Q of M){C=Math.min(C,Q.earliestTime),x=Math.max(x,Q.latestTime),X.push(Q.sessionTotalTokens),G.totalMessages+=Q.messageCount,G.totalCost+=Q.sessionCost,G.totalTokens.input+=Q.sessionTokens.input,G.totalTokens.output+=Q.sessionTokens.output,G.totalTokens.reasoning+=Q.sessionTokens.reasoning,G.totalTokens.cache.read+=Q.sessionTokens.cache.read,G.totalTokens.cache.write+=Q.sessionTokens.cache.write;for(let[W,N]of Object.entries(Q.sessionToolUsage))G.toolUsage[W]=(G.toolUsage[W]||0)+N;for(let[W,N]of Object.entries(Q.sessionModelUsage)){if(!G.modelUsage[W])G.modelUsage[W]={messages:0,tokens:{input:0,output:0,cache:{read:0,write:0}},cost:0};G.modelUsage[W].messages+=N.messages,G.modelUsage[W].tokens.input+=N.tokens.input,G.modelUsage[W].tokens.output+=N.tokens.output,G.modelUsage[W].tokens.cache.read+=N.tokens.cache.read,G.modelUsage[W].tokens.cache.write+=N.tokens.cache.write,G.modelUsage[W].cost+=N.cost}}}let $=Math.max(1,Math.ceil((x-C)/86400000)),q=K??$;G.dateRange={earliest:C,latest:x},G.days=q,G.costPerDay=G.totalCost/q;let I=G.totalTokens.input+G.totalTokens.output+G.totalTokens.reasoning+G.totalTokens.cache.read+G.totalTokens.cache.write;G.tokensPerSession=Y.length>0?I/Y.length:0,X.sort((V,F)=>V-F);let P=Math.floor(X.length/2);return G.medianTokensPerSession=X.length===0?0:X.length%2===0?(X[P-1]+X[P])/2:X[P],G}function u(z,E,_){function J(x,X){let $=55-x.length-X.length,q=Math.max(0,$);return`\u2502${x}${" ".repeat(q)}${X} \u2502`}console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 OVERVIEW \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),console.log(J("Sessions",z.totalSessions.toLocaleString())),console.log(J("Messages",z.totalMessages.toLocaleString())),console.log(J("Days",z.days.toString())),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(),console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 COST & TOKENS \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");let K=isNaN(z.totalCost)?0:z.totalCost,Y=isNaN(z.costPerDay)?0:z.costPerDay,G=isNaN(z.tokensPerSession)?0:z.tokensPerSession;console.log(J("Total Cost",`$${K.toFixed(2)}`)),console.log(J("Avg Cost/Day",`$${Y.toFixed(2)}`)),console.log(J("Avg Tokens/Session",Z.number(Math.round(G))));let C=isNaN(z.medianTokensPerSession)?0:z.medianTokensPerSession;if(console.log(J("Median Tokens/Session",Z.number(Math.round(C)))),console.log(J("Input",Z.number(z.totalTokens.input))),console.log(J("Output",Z.number(z.totalTokens.output))),console.log(J("Cache Read",Z.number(z.totalTokens.cache.read))),console.log(J("Cache Write",Z.number(z.totalTokens.cache.write))),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),console.log(),_!==void 0&&Object.keys(z.modelUsage).length>0){let x=Object.entries(z.modelUsage).sort(([,h],[,$])=>$.messages-h.messages),X=_===1/0?x:x.slice(0,_);console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 MODEL USAGE \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");for(let[h,$]of X)console.log(`\u2502 ${h.padEnd(54)} \u2502`),console.log(J(" Messages",$.messages.toLocaleString())),console.log(J(" Input Tokens",Z.number($.tokens.input))),console.log(J(" Output Tokens",Z.number($.tokens.output))),console.log(J(" Cache Read",Z.number($.tokens.cache.read))),console.log(J(" Cache Write",Z.number($.tokens.cache.write))),console.log(J(" Cost",`$${$.cost.toFixed(4)}`)),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");process.stdout.write("\x1B[1A"),console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")}if(console.log(),Object.keys(z.toolUsage).length>0){let x=Object.entries(z.toolUsage).sort(([,q],[,I])=>I-q),X=E?x.slice(0,E):x;console.log("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),console.log("\u2502 TOOL USAGE \u2502"),console.log("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524");let h=Math.max(...X.map(([,q])=>q)),$=Object.values(z.toolUsage).reduce((q,I)=>q+I,0);for(let[q,I]of X){let P=Math.max(1,Math.floor(I/h*20)),V="\u2588".repeat(P),F=(I/$*100).toFixed(1),D=18,W=` ${(q.length>18?q.substring(0,16)+"..":q).padEnd(18)} ${V.padEnd(20)} ${I.toString().padStart(3)} (${F.padStart(4)}%)`,N=Math.max(0,56-W.length-1);console.log(`\u2502${W}${" ".repeat(N)} \u2502`)}console.log("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")}console.log()}export{u as displayStats,y as aggregateSessionStats,i as StatsCommand};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{W as I}from"./chunk-art8gejd.js";import{X as i,Z as r}from"./chunk-w4fr00s7.js";import{Md as c}from"./chunk-v5me0cj9.js";import{Nd as g}from"./chunk-fmcg649e.js";import{Od as y}from"./chunk-mbmaeq0a.js";import{Pd as k}from"./chunk-86reb44c.js";import{Qd as A}from"./chunk-k769v1ds.js";import{Vd as w,Wd as u,Yd as W,Zd as L,_d as T,ae as p,be as o,ce as b,de as P}from"./chunk-p0852vfn.js";import"./chunk-ej0yzstw.js";import{fe as z}from"./chunk-w8nj5ph5.js";import{cg as Y}from"./chunk-psmwrvqs.js";import{Ah as M}from"./chunk-fd04358e.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import{Pk as a,cl as s,wj as R}from"./chunk-y1v7mf1a.js";import{ol as V}from"./chunk-358wdvj7.js";import{Ml as n}from"./chunk-dn0437c1.js";import"./chunk-47jkx37s.js";import"./chunk-31a47ptm.js";import"./chunk-jwv6fda1.js";import"./chunk-hx13a8es.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-j1bv93m4.js";import"./chunk-pp10epga.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-9znfb8f2.js";import"./chunk-6kch0q2d.js";import"./chunk-6cztstry.js";import"./chunk-1mfdmm2t.js";import{Ps as l}from"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-1a08ffyd.js";import{mt as d}from"./chunk-8jkqyf9n.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import{mu as v}from"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import{gI as O}from"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import{yP as H1}from"./chunk-sh03ka27.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-ckw51fn6.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(v.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=l.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(d(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{W as I}from"./chunk-art8gejd.js";import{X as i,Z as r}from"./chunk-wne3v1fk.js";import{Md as c}from"./chunk-v5me0cj9.js";import{Nd as g}from"./chunk-fmcg649e.js";import{Od as y}from"./chunk-mbmaeq0a.js";import{Pd as k}from"./chunk-86reb44c.js";import{Qd as A}from"./chunk-k769v1ds.js";import{Vd as w,Wd as u,Yd as W,Zd as L,_d as T,ae as p,be as o,ce as b,de as P}from"./chunk-p0852vfn.js";import"./chunk-ej0yzstw.js";import{fe as z}from"./chunk-w8nj5ph5.js";import{cg as Y}from"./chunk-psmwrvqs.js";import{Ah as M}from"./chunk-6zdzbmzs.js";import"./chunk-qn1fhqyw.js";import"./chunk-674pexjx.js";import"./chunk-zjyaze0d.js";import"./chunk-xdcwx384.js";import"./chunk-rd08wx37.js";import"./chunk-fp2xgnjn.js";import{Pk as a,cl as s,wj as R}from"./chunk-5asf8f41.js";import{ol as V}from"./chunk-2pw56zpj.js";import{Ml as n}from"./chunk-rt49c6js.js";import"./chunk-4gzggzc0.js";import"./chunk-31a47ptm.js";import"./chunk-ywj77e0m.js";import"./chunk-83n11xym.js";import"./chunk-h036zy9e.js";import"./chunk-j3agzs13.js";import"./chunk-3152y1q9.js";import"./chunk-71jmhvef.js";import"./chunk-qrztx1b4.js";import"./chunk-ae1b15bd.js";import"./chunk-6qwnty59.js";import"./chunk-crqycrs4.js";import"./chunk-1bq15kf0.js";import"./chunk-pdcxmr6x.js";import"./chunk-cqtkxwd8.js";import"./chunk-a1mbach4.js";import"./chunk-m6967jtv.js";import"./chunk-j2snkw45.js";import"./chunk-bmdqb48f.js";import"./chunk-3cs1qf8x.js";import"./chunk-4xqwt6dr.js";import"./chunk-g77kddrs.js";import"./chunk-kegvr7wt.js";import"./chunk-2tkgtasa.js";import"./chunk-6cztstry.js";import"./chunk-4yd2vvh6.js";import{Ps as l}from"./chunk-fkq0v5qv.js";import"./chunk-1e75j4m1.js";import"./chunk-2w3n0q9m.js";import"./chunk-6dd2dx69.js";import"./chunk-fdmz0502.js";import"./chunk-5re7995e.js";import{mt as d}from"./chunk-mnjz8nqs.js";import"./chunk-6yshpz0z.js";import"./chunk-5dvy83ms.js";import{mu as v}from"./chunk-ffx0cr44.js";import"./chunk-33mzqyyb.js";import"./chunk-sg9enzsp.js";import"./chunk-5q98z8ck.js";import"./chunk-wfpnv00c.js";import{gI as O}from"./chunk-9kc2th5c.js";import"./chunk-hf39qx6t.js";import"./chunk-x0de4z05.js";import{yP as H1}from"./chunk-sh03ka27.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-ckw51fn6.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(v.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=l.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(d(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{jt as c,nt as s}from"./chunk-8jkqyf9n.js";var r=["openai","anthropic"],p=["deepseek","zai","zhipuai","moonshotai","moonshotai-cn","kimi-for-coding","stepfun"],d=["opencode","openrouter"],l=["alibaba","alibaba-cn","bytedance","alibaba-coding-plan","alibaba-coding-plan-cn","zai-coding-plan","zhipuai-coding-plan","tencent-coding-plan","minimax-coding-plan","minimax-cn-coding-plan","kuae-cloud-coding-plan"],R=["opencode-go","github-copilot","google","vercel"],P=[r,p,d,l,R],g=Object.fromEntries(P.flatMap((i,a,e)=>{let n=e.slice(0,a).reduce((o,t)=>o+t.length,0);return i.map((o,t)=>[o,n+t])}));function m(i){return i in g}function O(i,a,e){return c(i,s((n)=>a[n.id]??99,(n)=>n.name??n.id),(n)=>n.map((o)=>({label:o.name,value:o.id,hint:e(o)})))}
2
+ import{jt as c,nt as s}from"./chunk-mnjz8nqs.js";var r=["openai","anthropic"],p=["deepseek","zai","zhipuai","moonshotai","moonshotai-cn","kimi-for-coding","stepfun"],d=["opencode","openrouter"],l=["alibaba","alibaba-cn","bytedance","alibaba-coding-plan","alibaba-coding-plan-cn","zai-coding-plan","zhipuai-coding-plan","tencent-coding-plan","minimax-coding-plan","minimax-cn-coding-plan","kuae-cloud-coding-plan"],R=["opencode-go","github-copilot","google","vercel"],P=[r,p,d,l,R],g=Object.fromEntries(P.flatMap((i,a,e)=>{let n=e.slice(0,a).reduce((o,t)=>o+t.length,0);return i.map((o,t)=>[o,n+t])}));function m(i){return i in g}function O(i,a,e){return c(i,s((n)=>a[n.id]??99,(n)=>n.name??n.id),(n)=>n.map((o)=>({label:o.name,value:o.id,hint:e(o)})))}
3
3
  export{g as X,m as Y,O as Z};