draken 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ACCEPTANCE.md +4 -1
- package/CHANGELOG.md +32 -0
- package/CONTRIBUTING.md +1 -1
- package/MEMORY.md +26 -6
- package/README.md +18 -6
- package/SETUP.md +2 -2
- package/SOURCES.md +1 -1
- package/VOICE.md +11 -3
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +6 -0
- package/dist/db/schema.js.map +1 -1
- package/dist/memory/automatic.d.ts +1 -1
- package/dist/memory/automatic.d.ts.map +1 -1
- package/dist/memory/automatic.js +1 -1
- package/dist/memory/automatic.js.map +1 -1
- package/dist/memory/context.d.ts +4 -4
- package/dist/memory/context.d.ts.map +1 -1
- package/dist/memory/context.js +64 -16
- package/dist/memory/context.js.map +1 -1
- package/dist/memory/embedding-pool.d.ts +1 -1
- package/dist/memory/embedding-pool.d.ts.map +1 -1
- package/dist/memory/embedding-pool.js +1 -1
- package/dist/memory/embedding-pool.js.map +1 -1
- package/dist/memory/index.d.ts +8 -2
- package/dist/memory/index.d.ts.map +1 -1
- package/dist/memory/index.js +195 -37
- package/dist/memory/index.js.map +1 -1
- package/dist/memory/model-files.d.ts +9 -0
- package/dist/memory/model-files.d.ts.map +1 -0
- package/dist/memory/model-files.js +13 -0
- package/dist/memory/model-files.js.map +1 -0
- package/dist/memory/model.d.ts +1 -1
- package/dist/memory/model.d.ts.map +1 -1
- package/dist/memory/model.js +11 -16
- package/dist/memory/model.js.map +1 -1
- package/dist/memory/readiness.d.ts +16 -0
- package/dist/memory/readiness.d.ts.map +1 -0
- package/dist/memory/readiness.js +131 -0
- package/dist/memory/readiness.js.map +1 -0
- package/dist/memory/reconcile.d.ts +11 -0
- package/dist/memory/reconcile.d.ts.map +1 -0
- package/dist/memory/reconcile.js +132 -0
- package/dist/memory/reconcile.js.map +1 -0
- package/dist/memory/service.d.ts +4 -2
- package/dist/memory/service.d.ts.map +1 -1
- package/dist/memory/service.js +34 -8
- package/dist/memory/service.js.map +1 -1
- package/dist/memory/sources.d.ts +2 -2
- package/dist/memory/sources.d.ts.map +1 -1
- package/dist/memory/sources.js +12 -5
- package/dist/memory/sources.js.map +1 -1
- package/dist/memory/storage.d.ts.map +1 -1
- package/dist/memory/storage.js +9 -0
- package/dist/memory/storage.js.map +1 -1
- package/dist/memory/types.d.ts +22 -1
- package/dist/memory/types.d.ts.map +1 -1
- package/dist/memory/types.js.map +1 -1
- package/dist/memory/worker.js +4 -2
- package/dist/memory/worker.js.map +1 -1
- package/dist/routes/sync.d.ts.map +1 -1
- package/dist/routes/sync.js +22 -4
- package/dist/routes/sync.js.map +1 -1
- package/dist/sync/collector.d.ts +1 -1
- package/dist/sync/collector.d.ts.map +1 -1
- package/dist/sync/collector.js +109 -69
- package/dist/sync/collector.js.map +1 -1
- package/dist/sync/manager.d.ts +4 -1
- package/dist/sync/manager.d.ts.map +1 -1
- package/dist/sync/manager.js +89 -13
- package/dist/sync/manager.js.map +1 -1
- package/dist/sync/reconciliation.d.ts +16 -0
- package/dist/sync/reconciliation.d.ts.map +1 -0
- package/dist/sync/reconciliation.js +22 -0
- package/dist/sync/reconciliation.js.map +1 -0
- package/dist/sync/store.js +1 -1
- package/dist/types.d.ts +9 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/voice/continuation.d.ts.map +1 -1
- package/dist/voice/continuation.js +1 -0
- package/dist/voice/continuation.js.map +1 -1
- package/dist/voice/history-focus.d.ts +14 -0
- package/dist/voice/history-focus.d.ts.map +1 -0
- package/dist/voice/history-focus.js +39 -0
- package/dist/voice/history-focus.js.map +1 -0
- package/dist/voice/live-context.d.ts +1 -1
- package/dist/voice/live-context.d.ts.map +1 -1
- package/dist/voice/live-context.js +3 -3
- package/dist/voice/live-context.js.map +1 -1
- package/dist/voice/live.d.ts.map +1 -1
- package/dist/voice/live.js +47 -33
- package/dist/voice/live.js.map +1 -1
- package/dist/voice/preparation.d.ts +8 -0
- package/dist/voice/preparation.d.ts.map +1 -0
- package/dist/voice/preparation.js +59 -0
- package/dist/voice/preparation.js.map +1 -0
- package/package.json +1 -1
- package/public/assets/index-CYCbTSh1.js +131 -0
- package/public/assets/{index-DmRid5xE.css → index-DntUQtGK.css} +1 -1
- package/public/assets/{persona-XbLvCqRT.js → persona-BVIfx5k8.js} +1 -1
- package/public/index.html +3 -3
- package/public/persona/chat-avatar.webp +0 -0
- package/public/persona.html +3 -3
- package/voice/realtime/native.mjs +1 -1
- package/public/assets/index-CYz_kpAp.js +0 -126
- /package/public/assets/{index-Ymd62i3g.js → index-BQFBaSKm.js} +0 -0
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
var cs=Object.defineProperty;var He=t=>{throw TypeError(t)};var ls=(t,s,n)=>s in t?cs(t,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[s]=n;var T=(t,s,n)=>ls(t,typeof s!="symbol"?s+"":s,n),Ve=(t,s,n)=>s.has(t)||He("Cannot "+n);var h=(t,s,n)=>(Ve(t,s,"read from private field"),n?n.call(t):s.get(t)),O=(t,s,n)=>s.has(t)?He("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(t):s.set(t,n),D=(t,s,n,a)=>(Ve(t,s,"write to private field"),a?a.call(t,n):s.set(t,n),n);import{r as o,j as e,P as ds,R as hs,a as us}from"./index-Ymd62i3g.js";/**
|
|
2
|
-
* @license lucide-react v0.468.0 - ISC
|
|
3
|
-
*
|
|
4
|
-
* This source code is licensed under the ISC license.
|
|
5
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const ps=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Ze=(...t)=>t.filter((s,n,a)=>!!s&&s.trim()!==""&&a.indexOf(s)===n).join(" ").trim();/**
|
|
7
|
-
* @license lucide-react v0.468.0 - ISC
|
|
8
|
-
*
|
|
9
|
-
* This source code is licensed under the ISC license.
|
|
10
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/var ms={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
|
|
12
|
-
* @license lucide-react v0.468.0 - ISC
|
|
13
|
-
*
|
|
14
|
-
* This source code is licensed under the ISC license.
|
|
15
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const gs=o.forwardRef(({color:t="currentColor",size:s=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:r="",children:i,iconNode:d,...c},u)=>o.createElement("svg",{ref:u,...ms,width:s,height:s,stroke:t,strokeWidth:a?Number(n)*24/Number(s):n,className:Ze("lucide",r),...c},[...d.map(([k,v])=>o.createElement(k,v)),...Array.isArray(i)?i:[i]]));/**
|
|
17
|
-
* @license lucide-react v0.468.0 - ISC
|
|
18
|
-
*
|
|
19
|
-
* This source code is licensed under the ISC license.
|
|
20
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const L=(t,s)=>{const n=o.forwardRef(({className:a,...r},i)=>o.createElement(gs,{ref:i,iconNode:s,className:Ze(`lucide-${ps(t)}`,a),...r}));return n.displayName=`${t}`,n};/**
|
|
22
|
-
* @license lucide-react v0.468.0 - ISC
|
|
23
|
-
*
|
|
24
|
-
* This source code is licensed under the ISC license.
|
|
25
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const fs=L("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
|
|
27
|
-
* @license lucide-react v0.468.0 - ISC
|
|
28
|
-
*
|
|
29
|
-
* This source code is licensed under the ISC license.
|
|
30
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
-
*/const Le=L("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/**
|
|
32
|
-
* @license lucide-react v0.468.0 - ISC
|
|
33
|
-
*
|
|
34
|
-
* This source code is licensed under the ISC license.
|
|
35
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const xs=L("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
|
|
37
|
-
* @license lucide-react v0.468.0 - ISC
|
|
38
|
-
*
|
|
39
|
-
* This source code is licensed under the ISC license.
|
|
40
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
-
*/const ys=L("AudioLines",[["path",{d:"M2 10v3",key:"1fnikh"}],["path",{d:"M6 6v11",key:"11sgs0"}],["path",{d:"M10 3v18",key:"yhl04a"}],["path",{d:"M14 8v7",key:"3a1oy3"}],["path",{d:"M18 5v13",key:"123xd1"}],["path",{d:"M22 10v3",key:"154ddg"}]]);/**
|
|
42
|
-
* @license lucide-react v0.468.0 - ISC
|
|
43
|
-
*
|
|
44
|
-
* This source code is licensed under the ISC license.
|
|
45
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
-
*/const vs=L("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/**
|
|
47
|
-
* @license lucide-react v0.468.0 - ISC
|
|
48
|
-
*
|
|
49
|
-
* This source code is licensed under the ISC license.
|
|
50
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
-
*/const js=L("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/**
|
|
52
|
-
* @license lucide-react v0.468.0 - ISC
|
|
53
|
-
*
|
|
54
|
-
* This source code is licensed under the ISC license.
|
|
55
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
-
*/const ws=L("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
|
|
57
|
-
* @license lucide-react v0.468.0 - ISC
|
|
58
|
-
*
|
|
59
|
-
* This source code is licensed under the ISC license.
|
|
60
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const bs=L("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/**
|
|
62
|
-
* @license lucide-react v0.468.0 - ISC
|
|
63
|
-
*
|
|
64
|
-
* This source code is licensed under the ISC license.
|
|
65
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/const ks=L("Keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);/**
|
|
67
|
-
* @license lucide-react v0.468.0 - ISC
|
|
68
|
-
*
|
|
69
|
-
* This source code is licensed under the ISC license.
|
|
70
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
-
*/const Ns=L("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
|
|
72
|
-
* @license lucide-react v0.468.0 - ISC
|
|
73
|
-
*
|
|
74
|
-
* This source code is licensed under the ISC license.
|
|
75
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const Ss=L("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/**
|
|
77
|
-
* @license lucide-react v0.468.0 - ISC
|
|
78
|
-
*
|
|
79
|
-
* This source code is licensed under the ISC license.
|
|
80
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const Cs=L("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
|
|
82
|
-
* @license lucide-react v0.468.0 - ISC
|
|
83
|
-
*
|
|
84
|
-
* This source code is licensed under the ISC license.
|
|
85
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
86
|
-
*/const Es=L("MicOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
|
|
87
|
-
* @license lucide-react v0.468.0 - ISC
|
|
88
|
-
*
|
|
89
|
-
* This source code is licensed under the ISC license.
|
|
90
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
91
|
-
*/const As=L("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
|
|
92
|
-
* @license lucide-react v0.468.0 - ISC
|
|
93
|
-
*
|
|
94
|
-
* This source code is licensed under the ISC license.
|
|
95
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
96
|
-
*/const Ts=L("PhoneOff",[["path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91",key:"z86iuo"}],["line",{x1:"22",x2:"2",y1:"2",y2:"22",key:"11kh81"}]]);/**
|
|
97
|
-
* @license lucide-react v0.468.0 - ISC
|
|
98
|
-
*
|
|
99
|
-
* This source code is licensed under the ISC license.
|
|
100
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
101
|
-
*/const $e=L("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/**
|
|
102
|
-
* @license lucide-react v0.468.0 - ISC
|
|
103
|
-
*
|
|
104
|
-
* This source code is licensed under the ISC license.
|
|
105
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
106
|
-
*/const Is=L("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
|
|
107
|
-
* @license lucide-react v0.468.0 - ISC
|
|
108
|
-
*
|
|
109
|
-
* This source code is licensed under the ISC license.
|
|
110
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
111
|
-
*/const _s=L("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/**
|
|
112
|
-
* @license lucide-react v0.468.0 - ISC
|
|
113
|
-
*
|
|
114
|
-
* This source code is licensed under the ISC license.
|
|
115
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
116
|
-
*/const Ps=L("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
117
|
-
* @license lucide-react v0.468.0 - ISC
|
|
118
|
-
*
|
|
119
|
-
* This source code is licensed under the ISC license.
|
|
120
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
121
|
-
*/const Ms=L("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/**
|
|
122
|
-
* @license lucide-react v0.468.0 - ISC
|
|
123
|
-
*
|
|
124
|
-
* This source code is licensed under the ISC license.
|
|
125
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
-
*/const Oe=L("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Xe=o.createContext(null),Ee="draken_token",Ae="draken_username";function Ds({children:t}){const[s,n]=o.useState({isAuthenticated:!1,isLoading:!0,authEnabled:!0,username:null,token:null}),a=o.useCallback(async()=>{n(d=>({...d,isLoading:!0}));try{if(!(await(await fetch("/api/auth/status")).json()).enabled){n({isAuthenticated:!0,isLoading:!1,authEnabled:!1,username:null,token:null});return}const u=localStorage.getItem(Ee),k=localStorage.getItem(Ae);if(!u){n({isAuthenticated:!1,isLoading:!1,authEnabled:!0,username:null,token:null});return}(await fetch("/api/auth/verify",{headers:{Authorization:`Bearer ${u}`}})).ok?n({isAuthenticated:!0,isLoading:!1,authEnabled:!0,username:k,token:u}):(localStorage.removeItem(Ee),localStorage.removeItem(Ae),n({isAuthenticated:!1,isLoading:!1,authEnabled:!0,username:null,token:null}))}catch(d){console.error("Auth check failed:",d),n({isAuthenticated:!1,isLoading:!1,authEnabled:!0,username:null,token:null})}},[]),r=async(d,c)=>{const u=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:d,password:c})});if(!u.ok){const v=await u.json();throw new Error(v.error||"Login failed")}const k=await u.json();localStorage.setItem(Ee,k.token),localStorage.setItem(Ae,k.username),n({isAuthenticated:!0,isLoading:!1,authEnabled:!0,username:k.username,token:k.token})},i=()=>{localStorage.removeItem(Ee),localStorage.removeItem(Ae),n({isAuthenticated:!1,isLoading:!1,authEnabled:!0,username:null,token:null})};return o.useEffect(()=>{a()},[a]),e.jsx(Xe.Provider,{value:{...s,login:r,logout:i,checkAuth:a},children:t})}function es(){const t=o.useContext(Xe);if(!t)throw new Error("useAuth must be used within an AuthProvider");return t}function Ls(){const{login:t}=es(),[s,n]=o.useState(""),[a,r]=o.useState(""),[i,d]=o.useState(null),[c,u]=o.useState(!1),k=async v=>{v.preventDefault(),d(null),u(!0);try{await t(s,a)}catch(m){d(m instanceof Error?m.message:"Login failed")}finally{u(!1)}};return e.jsx("div",{className:"login-page",children:e.jsxs("div",{className:"login-card",children:[e.jsxs("div",{className:"login-header",children:[e.jsx("img",{src:"/favicon.png",alt:"Draken",className:"login-logo"}),e.jsx("h1",{children:"Draken"}),e.jsx("p",{className:"login-subtitle",children:"Your engineering sync across pi sessions"})]}),e.jsxs("form",{onSubmit:k,className:"login-form",children:[i&&e.jsxs("div",{className:"login-error",role:"alert",children:[e.jsx(js,{size:16}),i]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"username",children:"Username"}),e.jsxs("div",{className:"input-with-icon",children:[e.jsx(Ms,{size:18,className:"input-icon"}),e.jsx("input",{id:"username",type:"text",className:"input",placeholder:"Enter username",value:s,onChange:v=>n(v.target.value),autoComplete:"username",autoFocus:!0})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"input-with-icon",children:[e.jsx(Ns,{size:18,className:"input-icon"}),e.jsx("input",{id:"password",type:"password",className:"input",placeholder:"Enter password",value:a,onChange:v=>r(v.target.value),autoComplete:"current-password"})]})]}),e.jsx("button",{type:"submit",className:"btn btn-primary btn-lg login-btn",disabled:c||!s||!a,children:c?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"spinner spinner-sm"})," Signing in..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ss,{size:18})," Sign In"]})})]})]})})}async function P(t,s="GET",n,a){const r=localStorage.getItem("draken_token"),i=await fetch(`/api${t}`,{method:s,signal:a,headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:n===void 0?void 0:JSON.stringify(n)});if(i.status===401)throw localStorage.removeItem("draken_token"),localStorage.removeItem("draken_username"),window.location.reload(),new Error("Authentication required");if(i.status===204)return;const d=await i.json();if(!i.ok)throw new Error(d.error||`Request failed (${i.status})`);return d}const $s=(t=!1)=>P(`/setup${t?"?refresh=1":""}`),Os=()=>P("/settings/auto-index"),Rs=t=>P("/settings/auto-index","PATCH",{enabled:t}),Re=t=>P(`/home${t?`?before=${t}`:""}`),qs=t=>P("/syncs/start-call","POST",{request_id:t}),Be=t=>P(`/syncs/${t}/recap`,"POST"),Ye=()=>P("/overview"),Fs=()=>P("/scan","POST"),zs=(t,s)=>P(`/agents/${encodeURIComponent(t)}`,"PATCH",{enabled:s}),Us=(t,s)=>P(`/sessions/${encodeURIComponent(t)}`,"PATCH",{included:s}),We=t=>P(`/syncs/${t}`),Hs=t=>P(`/syncs/${t}/progress`),Vs=(t,s)=>P(`/syncs/${t}/tree/${s}`),Bs=t=>P(`/syncs/${t}/expand`,"POST"),Ys=t=>P(`/syncs/${t}/cancel`,"POST"),Ws=t=>P(`/syncs/${t}/briefing`,"POST"),Ks=(t,s)=>P(`/syncs/${t}/messages`,"POST",{message:s}),Gs=t=>P("/memory/progress","GET",void 0,t),Qs=(t,s)=>P("/memory/search","POST",t,s),Js=(t,s=0)=>P(`/memory/records/${encodeURIComponent(t)}?offset=${s}`),Te=(t,s,n)=>P(`/syncs/${t}/notes`,"PATCH",{decisions:s,carry_forward:n}),Zs=(t,s,n)=>P(`/syncs/${t}/complete`,"POST",{decisions:s,carry_forward:n,reviewed:!0}),Xs=t=>P(`/syncs/${t}/discard`,"POST"),ye=25;function Ke({items:t,title:s}){const[n,a]=o.useState(0),[r,i]=o.useState(""),[d,c]=o.useState("");if(o.useEffect(()=>{const g=l=>{const x=l.detail,j=t.findIndex(I=>I.ref===x);j<0||(i(""),a(Math.floor(j/ye)),c(x))};return window.addEventListener("draken:evidence",g),()=>window.removeEventListener("draken:evidence",g)},[t]),o.useEffect(()=>{if(!d)return;const g=document.getElementById(`evidence-${d}`);g&&(g.open=!0,g.scrollIntoView({behavior:"smooth",block:"center"}),c(""))},[d,n,r]),!t.length)return null;const u=r.toLocaleLowerCase(),k=u?t.filter(g=>`${g.ref} ${g.session_name} ${g.cwd} ${g.text}`.toLocaleLowerCase().includes(u)):t,v=Math.max(1,Math.ceil(k.length/ye)),m=Math.min(n,v-1);return e.jsxs("section",{className:"evidence-section",children:[e.jsxs("h3",{children:[s," ",e.jsx("span",{className:"count",children:t.length})]}),t.length>ye&&e.jsxs("div",{className:"evidence-controls",children:[e.jsx("input",{className:"input","aria-label":`Search ${s}`,placeholder:"Find a topic, workspace, or evidence ID…",value:r,onChange:g=>{i(g.target.value),a(0)}}),e.jsxs("div",{className:"pagination",children:[e.jsx("button",{className:"btn btn-secondary",disabled:m===0,onClick:()=>a(m-1),children:"Previous"}),e.jsxs("span",{children:[m+1," / ",v," · ",k.length," entries"]}),e.jsx("button",{className:"btn btn-secondary",disabled:m>=v-1,onClick:()=>a(m+1),children:"Next"})]})]}),e.jsx("div",{className:"evidence-list",children:k.slice(m*ye,(m+1)*ye).map(g=>e.jsxs("details",{className:"evidence",id:`evidence-${g.ref}`,children:[e.jsxs("summary",{children:[e.jsx("span",{className:"reference",children:g.ref}),e.jsxs("span",{className:"evidence-title",children:[e.jsxs("strong",{children:[g.agent&&g.agent!=="pi"&&`${g.agent} · `,g.session_name||g.cwd.split("/").filter(Boolean).pop()||g.cwd]}),e.jsx("span",{children:g.unavailable?"Original session source unavailable":g.text.slice(0,130)})]}),e.jsx("span",{className:"role-label",children:g.role})]}),e.jsxs("div",{className:"evidence-body",children:[e.jsxs("dl",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:g.cwd}),e.jsx("dt",{children:"Session"}),e.jsx("dd",{children:g.session_id}),e.jsx("dt",{children:"Source"}),e.jsx("dd",{children:g.source_path}),e.jsx("dt",{children:"Entry"}),e.jsxs("dd",{children:[g.entry_id," · ",g.timestamp]})]}),g.unavailable?e.jsx("p",{className:"alert warning",role:"status",children:g.unavailable}):e.jsx("pre",{children:g.text})]})]},g.ref))})]})}function _e({text:t,evidence:s}){const n=new Set(s.map(a=>a.ref));return e.jsx("div",{className:"prose",children:t.split(/(\[(?:[EC]\d+|H[a-f0-9]{24})\])/g).map((a,r)=>{const i=a.slice(1,-1);return/^H[a-f0-9]{24}$/.test(i)?e.jsxs("a",{className:"citation",href:`/history/${i}`,target:"_blank",rel:"noopener noreferrer","aria-label":`Inspect historical source ${i}`,children:["[history ",i.slice(-6),"]"]},r):!/^\[(E|C)\d+\]$/.test(a)||!n.has(i)?e.jsx("span",{children:a},r):e.jsx("button",{className:"citation",onClick:()=>window.dispatchEvent(new CustomEvent("draken:evidence",{detail:i})),"aria-label":`Inspect evidence ${i}`,children:a},r)})})}function et({syncId:t,progress:s,evidence:n,onCancel:a,onResume:r,resumeEnabled:i}){var N;const[d,c]=o.useState(new Set),[u,k]=o.useState(null),[v,m]=o.useState(""),[g,l]=o.useState(!1),x=s.run;if(o.useEffect(()=>{k(null),c(new Set)},[x==null?void 0:x.id]),!x)return null;const j=!s.busy&&["failed","cancelled","interrupted"].includes(x.status),I=new Map(s.nodes.map(f=>[f.key,f])),y=new Set(s.nodes.flatMap(f=>f.children)),C=s.nodes.filter(f=>!y.has(f.key)),w=async f=>{l(!0),m("");try{k(await Vs(t,f.key))}catch(S){m(S instanceof Error?S.message:"Could not load summary")}finally{l(!1)}},A=(f,S=new Set)=>{if(S.has(f.key))return null;const $=new Set([...S,f.key]),V=d.has(f.key);return e.jsxs("li",{children:[e.jsxs("div",{className:"tree-node",children:[e.jsx("button",{className:"tree-toggle","aria-label":`Expand ${f.label}`,disabled:!f.children.length,onClick:()=>c(_=>{const z=new Set(_);return z.has(f.key)?z.delete(f.key):z.add(f.key),z}),children:f.children.length?V?"▾":"▸":"·"}),e.jsxs("button",{className:"tree-label",disabled:!["done","cached"].includes(f.status)||g,onClick:()=>void w(f),title:f.error||f.label,children:[e.jsx("span",{className:"role-label",children:f.kind})," ",f.label]}),e.jsx("span",{className:`status ${f.status}`,children:f.status})]}),V&&e.jsx("ul",{children:f.children.map(_=>I.has(_)?A(I.get(_),$):null)})]},f.key)};return e.jsxs("section",{className:"card tree-card",children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h2",{children:"Summary tree"}),e.jsx("span",{className:`status ${x.status}`,children:x.status})]}),e.jsx("p",{className:"small muted",children:"Complete source batches → compact reconciliation → final verdict"}),e.jsx("progress",{max:Math.max(1,x.total_entries),value:x.processed_entries,"aria-label":"Evidence compression progress"}),e.jsxs("div",{className:"tree-stats",children:[e.jsxs("span",{children:[x.processed_entries," / ",x.total_entries," entries processed"]}),e.jsxs("span",{children:[x.invocations," / ",x.max_invocations," pi invocations"]}),e.jsxs("span",{children:[x.cache_hits," cached nodes reused"]})]}),!!((N=x.metrics)!=null&&N.length)&&e.jsxs("details",{className:"small",children:[e.jsx("summary",{children:"Model request timing"}),e.jsxs("p",{children:[(x.metrics.reduce((f,S)=>f+S.elapsed_ms,0)/1e3).toFixed(1)," seconds across ",x.metrics.length," requests · ",x.metrics.reduce((f,S)=>f+S.input_tokens_estimate,0).toLocaleString()," estimated input tokens."]}),e.jsx("p",{className:"muted",children:"Includes pi startup and provider waiting/generation, not separately measured. Token counts are local planning estimates with input headroom, not billed usage. A completed request can still fail summary validation."}),e.jsx("ul",{children:x.metrics.map((f,S)=>e.jsxs("li",{children:[f.stage||f.task,f.repair?" (repair)":""," · ",(f.elapsed_ms/1e3).toFixed(1)," s · ",f.status]},S))})]}),e.jsxs("p",{className:"small",children:[j?"Stopped at: ":"",x.stage]}),x.question&&e.jsxs("p",{className:"small muted",children:["Question: ",x.question]}),x.error&&e.jsxs("div",{className:"alert error",role:"alert",children:[e.jsx("strong",{children:"Last run’s error:"})," ",x.error]}),j&&e.jsxs("div",{className:"alert warning",children:[e.jsx("strong",{children:"Generation stopped. No model calls are running."}),e.jsxs("p",{className:"small",children:[x.processed_entries<x.total_entries?`${x.total_entries-x.processed_entries} entries still need compression.`:"Raw chunks were processed, but reconciliation or the final reply did not finish."," Successful chunks are cached; nothing was marked reviewed."]}),r&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"small",children:"Resume to continue from cached chunks instead of generating them again."}),e.jsx("button",{className:"btn btn-primary",disabled:!i,onClick:r,children:"Resume generation"})]})]}),s.busy&&e.jsx("button",{className:"btn btn-secondary",onClick:a,children:"Cancel generation"}),e.jsxs("details",{className:"tree-browser",children:[e.jsxs("summary",{children:["Inspect ",s.nodes.length," summary nodes"]}),e.jsx("ul",{children:C.map(f=>A(f))})]}),v&&e.jsx("p",{role:"alert",className:"error",children:v}),u&&e.jsxs("div",{className:"node-inspector",children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h3",{children:u.label}),e.jsx("button",{className:"btn btn-ghost",onClick:()=>k(null),children:"Close"})]}),"observations"in u.output?e.jsxs(e.Fragment,{children:[u.output.observations.map((f,S)=>e.jsxs("div",{className:"node-observation",children:[e.jsx("strong",{children:f.topic})," ",e.jsx("span",{className:"status",children:f.state}),e.jsx(_e,{text:`${f.summary} ${f.evidence.map($=>u.refs[$]?`[${u.refs[$]}]`:"[source unavailable]").join(" ")}`,evidence:n})]},S)),u.output.limitations.map((f,S)=>e.jsx("p",{className:"muted small",children:f},S))]}):u.output.groups.map((f,S)=>e.jsxs("p",{className:"small",children:[f.topic," · ",f.members.length," related observations"]},S))]})]})}const qe={phase:"connecting",muted:!1,microphone:!1,voiceInterruption:!1,question:"",answer:"",evidence:[],error:"",notice:"",startedAt:0,turnId:0,replyPendingSince:0,historyReady:!1};function ss(t=!0){const s=localStorage.getItem("draken_token");return{...t?{"Content-Type":"application/json"}:{},...s?{Authorization:`Bearer ${s}`}:{}}}async function G(t,s={}){const n=await fetch(`/api/voice${t}`,{...s,headers:ss()});if(!n.ok){const a=await n.json().catch(()=>({}));throw new Error(a.error||(n.status===401?"Sign in again to use the call.":"The live connection failed."))}return n.status===204?void 0:n.json()}function ts({cost:t}){if(!t)return null;const s=t.usd===null?"unavailable":t.usd>0&&t.usd<1e-6?"<$0.000001":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:t.usd<.01?6:2}).format(t.usd),n="Sync preparation only: summaries, consolidation, preparation recaps and final briefing, including retries. Excludes later questions, calls and conversation recaps. API-equivalent estimate from pi usage and catalog prices, not a subscription charge or invoice.",a=t.usd===null?" Usage/pricing was not captured or is unavailable for this preparation.":t.complete?"":" Partial total: some preparation usage/pricing is missing or work is still running.";return e.jsxs("span",{className:"sync-cost small muted",title:n+a,children:["Est. cost: ",s,t.usd!==null&&!t.complete?" (partial)":""]})}function ns({active:t=!0,firstRun:s=!1,always:n=!1,onReady:a}){const[r,i]=o.useState(null),[d,c]=o.useState(null),[u,k]=o.useState(""),[v,m]=o.useState(!1),[g,l]=o.useState(0);if(o.useEffect(()=>{if(!t)return;let j=!0;const I=async(C=!1)=>{m(!0);try{const[w,A]=await Promise.all([$s(C),G("/status")]);if(!j)return;i(w),c(A),k(""),a==null||a(w.pi.state==="configured"&&A.installed)}catch{j&&(k("Could not check setup or reach Draken. The last displayed state may be stale. Check the server terminal, then retry."),a==null||a(!1))}finally{j&&m(!1)}};I(g>0);const y=setInterval(()=>void I(),6e4);return()=>{j=!1,clearInterval(y)}},[t,g,a]),!t||!n&&!s&&!u&&(r==null?void 0:r.pi.state)==="configured"&&(d!=null&&d.installed))return null;const x=r==null?void 0:r.pi;return e.jsxs("section",{className:"setup-panel","aria-label":"Draken setup",children:[e.jsx("h2",{children:s?"First-time setup":"Runtime & sign-in"}),e.jsx("p",{className:"small muted",children:"Draken reads agent histories, but pi runs all summaries. Voice uses a separate ChatGPT sign-in. Setup and login are explicit terminal commands—not browser downloads or credential forms."}),!r&&!u&&e.jsx("p",{className:"small",role:"status",children:"Checking setup…"}),x&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:[e.jsxs("strong",{children:["Summarization: ",x.state==="configured"?"credentials configured":x.state==="missing"?"pi not found":x.state==="needs_login"?"sign-in needed":"needs attention"]}),e.jsxs("span",{className:"small muted",children:[" · ",x.source==="managed"?"Draken-private pi":"Existing / external pi",x.version&&` ${x.version}`]})]}),e.jsx("p",{className:"small",children:x.message}),x.state!=="configured"&&e.jsxs("div",{className:"setup-commands",children:[["missing","incompatible"].includes(x.state)&&e.jsxs("p",{children:[e.jsx("code",{children:"draken setup"})," — install a pinned, private pi after confirmation. An explicit ",e.jsx("code",{children:"DRAKEN_PI_BIN"})," must be fixed or unset first."]}),e.jsxs("p",{children:[e.jsx("code",{children:"draken login"})," — open pi; type ",e.jsx("code",{children:"/login"}),", follow its prompts, then ",e.jsx("code",{children:"/quit"}),"."]}),e.jsxs("p",{children:[e.jsx("code",{children:"draken doctor"})," — inspect configuration without a generation request."]})]}),e.jsx("ul",{className:"small muted",children:x.models.map(j=>e.jsxs("li",{children:[j.model," · ",j.state.replace(/_/g," ")]},j.model))}),e.jsxs("p",{className:"small muted source-path",children:["Pi credential directory: ",x.agent_dir]})]}),d&&e.jsx("p",{children:e.jsxs("strong",{children:["ChatGPT voice: ",d.installed?"helper and sign-in configured":"setup needed"]})}),d&&!d.installed&&e.jsxs("div",{className:"setup-commands",children:[e.jsxs("p",{children:[e.jsx("code",{children:"draken voice setup"})," — install the native helper."]}),e.jsxs("p",{children:[e.jsx("code",{children:"draken voice login"})," — use its separate official ChatGPT sign-in. No pi tokens are copied."]})]}),(n||s||(x==null?void 0:x.state)!=="configured"||!(d!=null&&d.installed))&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"small muted",children:["Run commands on the server as its user, with the same environment. After login, click Check setup again. Keep the server terminal open; Ctrl+C stops it. ",e.jsx("code",{children:"draken status"})," checks connectivity."]}),r&&e.jsxs("p",{className:"small muted source-path",children:["Draken data: ",r.data_dir]}),e.jsxs("p",{className:"small muted",children:["Choose sources in ",e.jsx("strong",{children:"Settings → Agents & sessions"}),", then ",e.jsx("strong",{children:"Sync with Draken"}),". Source scanning works before sign-in. Credential presence does not verify model access, billing or voice playback."]})]}),u&&e.jsx("p",{className:"small",role:"alert",children:u}),e.jsx("button",{type:"button",className:"btn btn-secondary",disabled:v,onClick:()=>l(j=>j+1),children:v?"Checking…":"Check setup again"})]})}const ie=(t,s,n)=>{t.button||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),s(n))},st=t=>new Date(t).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"});function tt({navigate:t}){const[s,n]=o.useState(null),[a,r]=o.useState(""),[i,d]=o.useState(""),[c,u]=o.useState(""),[k,v]=o.useState(!1),m=o.useRef(!0),g=o.useRef(!1),l=o.useRef(),x=async()=>{const y=await Re();m.current&&n(C=>C&&C.syncs.length>20?{...y,syncs:[...y.syncs,...C.syncs.filter(w=>{var A;return w.id<((A=y.syncs[y.syncs.length-1])==null?void 0:A.id)})],next_cursor:C.next_cursor}:y)};o.useEffect(()=>{m.current=!0,x().catch(C=>d(C.message)),window.isSecureContext||G("/status").then(C=>{if(m.current&&C.httpsPort){const w=new URL("/",location.href);w.protocol="https:",w.port=String(C.httpsPort),u(w.href)}}).catch(()=>{});const y=setInterval(()=>{g.current||x().catch(()=>{})},4e3);return()=>{m.current=!1,clearInterval(y)}},[]);const j=async()=>{if(!g.current){g.current=!0,r("Collecting new activity…"),d(""),l.current||(l.current=crypto.randomUUID());try{const y=await G("/status");if(!y.installed)throw new Error("Voice is not ready on this server. Complete voice setup before starting a sync call.");if(y.activeCall)throw new Error("End the existing call before starting another sync.");const C=await qs(l.current);m.current&&t(`/syncs/${C.sync.id}`,!0)}catch(y){m.current&&d(y instanceof Error?y.message:"Could not start the sync")}finally{g.current=!1,m.current&&r("")}}},I=!!(!k||a||s!=null&&s.busy||s!=null&&s.active_call);return e.jsxs("main",{className:"sync-home",children:[e.jsxs("div",{className:"page-heading",children:[e.jsxs("div",{children:[e.jsx("h1",{children:"Pick up where you left off."}),e.jsx("p",{className:"muted",children:"New activity. A little memory. One conversation."})]}),c?e.jsxs("a",{className:"btn btn-primary",href:c,children:["Open secure Draken",e.jsx(Le,{size:17})]}):e.jsxs("button",{className:"btn btn-primary",disabled:!s||I||!window.isSecureContext,onClick:()=>void j(),children:[e.jsx($e,{size:17}),"Sync with Draken"]})]}),!window.isSecureContext&&e.jsx("p",{className:"small muted",children:"Use trusted HTTPS or localhost for the combined sync and call."}),e.jsx("p",{className:"home-hint muted small",children:"New entries → a prepared snapshot → your call. Previous syncs come along as short recaps."}),e.jsxs("div",{className:"home-counts","aria-label":"Sync tracking",children:[e.jsxs("span",{children:[e.jsx("strong",{children:(s==null?void 0:s.available)??"—"})," waiting"]}),e.jsxs("span",{children:[e.jsx("strong",{children:(s==null?void 0:s.included_unreviewed)??"—"})," included, not reviewed"]}),e.jsxs("span",{children:[e.jsx("strong",{children:(s==null?void 0:s.covered)??"—"})," reviewed"]})]}),a&&e.jsxs("p",{role:"status",className:"working",children:[e.jsx("span",{className:"spinner"}),a]}),(s==null?void 0:s.busy)&&!a&&e.jsx("p",{className:"small muted",role:"status",children:"Draken is updating a sync. Open its card to follow progress."}),(s==null?void 0:s.active_call)&&e.jsx("p",{className:"small muted",children:"A call is active. End it before starting another sync."}),i&&e.jsx("div",{className:"alert error",role:"alert",children:i}),e.jsx(ns,{firstRun:!!(s&&!s.syncs.length),onReady:v}),e.jsxs("section",{className:"sync-feed","aria-label":"Sync history",children:[s==null?void 0:s.syncs.map(y=>e.jsxs("a",{className:"card sync-tile",href:`/syncs/${y.id}`,onClick:C=>ie(C,t,`/syncs/${y.id}`),children:[e.jsxs("div",{className:"sync-tile-heading",children:[e.jsxs("strong",{children:["Sync #",y.id]}),e.jsx("span",{className:`status ${y.status}`,children:y.busy?"working":y.active_call?"in call":y.needs_retry?"needs retry":y.status==="completed"?"reviewed":y.status==="open"?"open":"discarded"}),e.jsx(Le,{size:17,"aria-hidden":"true"})]}),e.jsxs("div",{className:"small muted",children:[st(y.created_at)," · ",y.item_count," ",y.item_count===1?"entry":"entries"," · ",y.calls," ",y.calls===1?"call":"calls",y.aggregation_cost&&e.jsxs(e.Fragment,{children:[" · ",e.jsx(ts,{cost:y.aggregation_cost})]})]}),e.jsx("p",{className:"sync-tile-preview",children:y.preview||(y.needs_retry?"Preparation stopped. Open this sync to retry; its entries and cached work are retained.":y.busy?"Bringing the new activity together. Open this sync to follow preparation.":"No recap yet. Open this sync to continue the conversation.")}),e.jsx("span",{className:"sync-tile-kind small muted",children:y.preview_kind==="recap"?"Conversation recap · not saved decisions":y.preview_kind==="previous_recap"?"Earlier recap · conversation changed":y.preview_kind==="briefing"?"Briefing preview":"Frozen snapshot"})]},y.id)),s&&!s.syncs.length&&e.jsxs("div",{className:"card welcome",children:[e.jsx("h2",{children:"Your next conversation starts here."}),e.jsx("p",{children:"Draken keeps track of the work you’ve already brought into a sync. Start above; the details can wait until you need them."})]})]}),(s==null?void 0:s.next_cursor)&&e.jsx("button",{className:"btn btn-secondary",onClick:async()=>{try{const y=await Re(s.next_cursor);n(C=>C?{...C,syncs:[...C.syncs,...y.syncs.filter(w=>!C.syncs.some(A=>A.id===w.id))],next_cursor:y.next_cursor}:y)}catch(y){d(y instanceof Error?y.message:"Could not load history")}},children:"Older syncs"})]})}const nt={scanning:"Checking history for changes…",downloading:"Downloading the local search model…",loading:"Preparing the local search model…",indexing:"Indexing new and changed history…",searching:"Finding matching history…",reading:"Reading a historical source…"},Me=t=>t<60?`${Math.ceil(t)} sec`:`${Math.ceil(t/60)} min`,Ie=t=>t.toLocaleString();function ve({enabled:t,waiting:s=!1,backgroundOnly:n=!1,onLookupChange:a}){const[r,i]=o.useState(null),[d,c]=o.useState(!1);if(o.useEffect(()=>{if(a==null||a(!1),!t)return;i(null),c(!1);const j=new AbortController;let I;const y=async()=>{try{const C=await Gs(j.signal);j.signal.aborted||(i(C),c(!1),a==null||a(!!(C.active&&!C.background&&C.work&&["scanning","searching","reading"].includes(C.work.stage)&&C.updated_at&&Math.abs(Date.now()-C.updated_at)<5e3)))}catch{j.signal.aborted||(c(!0),a==null||a(!1))}j.signal.aborted||(I=setTimeout(()=>void y(),1e3))};return y(),()=>{j.abort(),clearTimeout(I),a==null||a(!1)}},[t,a]),!t)return null;if(!(r!=null&&r.active)||!r.work||n&&!r.background)return s?e.jsx("p",{className:"small muted",role:"status",children:d?"Progress is unavailable; your search is still pending.":"Waiting for local history work…"}):null;const u=r.work,k=u.stage==="indexing",v=u.stage==="downloading",m=v?u.downloaded_bytes:u.completed,g=v?u.download_total_bytes:u.total,l=g?Math.floor(m/g*100):0,x=r.updated_at?Math.floor((Date.now()-r.updated_at)/1e3):0;return e.jsxs("section",{className:"history-progress","aria-label":"Local history progress",children:[e.jsx("p",{role:"status",children:e.jsx("strong",{children:k&&!g?"History is up to date.":nt[u.stage]})}),(k&&g>0||v)&&e.jsxs(e.Fragment,{children:[e.jsx("progress",{"aria-label":v?"Model download":"History indexing",max:g||1,value:g?m:void 0}),e.jsxs("p",{children:[v?`${(m/1e6).toFixed(1)} / ${(g/1e6).toFixed(1)} MB`:`${Ie(m)} / ${Ie(g)} new or changed passages ready`," · ",l,"%"]})]}),e.jsxs("p",{className:"small muted",children:[k&&`${Ie(u.reused)} unchanged passages reused (not part of this progress). `,"Elapsed ",Me(r.elapsed_ms/1e3),".",k&&u.remaining_seconds!==null&&u.remaining_seconds>0&&` About ${Me(u.remaining_seconds)} remaining (estimate).`,k&&g>0&&u.parallelism&&` Up to ${u.parallelism.workers} embedding worker${u.parallelism.workers===1?"":"s"}, ${u.parallelism.threads} CPU threads total.`,r.queued>0&&` ${Ie(r.queued)} other history request${r.queued===1?"":"s"} waiting.`]}),(d||x>=15)&&e.jsxs("p",{className:"small muted",children:[d?"Progress updates are temporarily unavailable.":`No new progress for ${Me(x)}.`," Cancelling keeps completed embeddings for the next request."]})]})}const at=t=>t?new Date(t).toLocaleString():"Edit date not retained";function Fe({record:t}){return e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"small muted",children:[at(t.at)," · ",t.role," · ",t.kind,t.sync_id?` · Sync #${t.sync_id}`:""]}),e.jsx("p",{className:"small muted",children:t.qualification})]})}function as({reference:t}){const[s,n]=o.useState(null),[a,r]=o.useState(0),[i,d]=o.useState("");return o.useEffect(()=>{r(0)},[t]),o.useEffect(()=>{let c=!0;return d(""),n(null),Js(t,a).then(u=>{c&&n(u)}).catch(u=>{c&&d(u.message)}),()=>{c=!1}},[t,a]),e.jsxs("section",{className:"history-source","aria-label":"Historical source",children:[i&&e.jsx("p",{role:"alert",children:i}),!s&&!i&&e.jsx("p",{role:"status",children:"Reading historical source…"}),s&&e.jsxs(e.Fragment,{children:[e.jsx("h2",{children:s.record.title}),e.jsx(Fe,{record:s.record}),s.record.workspace&&e.jsx("p",{className:"source-path",children:s.record.workspace}),e.jsx("pre",{className:"history-excerpt",children:s.record.text}),e.jsxs("p",{className:"small muted",children:["Characters ",Math.min(a+1,s.total),"–",Math.min(a+4e3,s.total)," of ",s.total," in the retained record. Source logs may contain more."]}),s.total>4e3&&e.jsxs("div",{className:"pagination",children:[e.jsx("button",{className:"btn btn-secondary",disabled:!a,onClick:()=>r(Math.max(0,a-4e3)),children:"Earlier text"}),e.jsx("button",{className:"btn btn-secondary",disabled:a+4e3>=s.total,onClick:()=>r(a+4e3),children:"Later text"})]}),s.record.sync_id&&e.jsxs("p",{children:[e.jsxs("a",{href:`/syncs/${s.record.sync_id}`,target:"_blank",rel:"noopener noreferrer",children:["Open original sync #",s.record.sync_id]}),s.record.origin_ref&&` · original reference ${s.record.origin_ref}`]}),s.neighbors.length>0&&e.jsxs("details",{children:[e.jsx("summary",{children:"Surrounding retained records"}),e.jsx("p",{className:"small muted",children:"Nearby records in this session or discussion—not necessarily the full conversation."}),s.neighbors.map(c=>e.jsxs("article",{children:[e.jsx("h3",{children:e.jsx("a",{href:`/history/${c.ref}`,target:"_blank",rel:"noopener noreferrer",children:c.title})}),e.jsx(Fe,{record:c}),e.jsx("pre",{className:"history-excerpt",children:c.text})]},c.ref))]})]})]})}function it({navigate:t,reference:s}){const[n,a]=o.useState(null),[r,i]=o.useState(""),[d,c]=o.useState(""),[u,k]=o.useState(!1),v=o.useRef();return o.useEffect(()=>()=>{var m;return(m=v.current)==null?void 0:m.abort()},[]),e.jsxs("main",{className:"sync-home history-page",children:[e.jsx("a",{className:"back-link",href:"/",onClick:m=>ie(m,t,"/"),children:"All syncs"}),e.jsx("h1",{children:s?"Historical source":"Find earlier work."}),e.jsx("p",{className:"muted",children:"Search retained sessions, sync discussions and explicitly saved notes. Results are historical evidence—not new progress, agreement or proof of execution."}),s?e.jsxs(e.Fragment,{children:[e.jsx(as,{reference:s},s),e.jsx("p",{children:e.jsx("a",{href:"/history",onClick:m=>ie(m,t,"/history"),children:"Search history"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"small muted",children:"Draken combines meaning and keyword matches automatically. First use prepares a local model (about 136 MB); later searches reuse it and update changed records. Search text stays on this server. Your source exclusions and history baseline still apply."}),e.jsxs("form",{className:"history-search",onSubmit:async m=>{m.preventDefault(),k(!0),c(""),a(null);const g=new AbortController;v.current=g;try{const l=await Qs({question:r},g.signal);g.signal.aborted||a(l)}catch(l){g.signal.aborted||c(l instanceof Error?l.message:"Search failed")}finally{k(!1)}},children:[e.jsx("label",{htmlFor:"history-question",children:"What do you want to find?"}),e.jsx("textarea",{id:"history-question",rows:3,maxLength:2e3,value:r,onChange:m=>i(m.target.value),placeholder:"Why did we change that approach?"}),e.jsxs("div",{className:"history-actions",children:[e.jsx("button",{className:"btn btn-primary",disabled:u||!r.trim(),children:u?"Searching…":"Search history"}),u&&e.jsx("button",{type:"button",className:"btn btn-secondary",onClick:()=>{var m;return(m=v.current)==null?void 0:m.abort()},children:"Cancel search"})]}),e.jsx(ve,{enabled:u,waiting:!0})]}),d&&e.jsx("p",{className:"alert error",role:"alert",children:d}),n&&e.jsxs("section",{"aria-label":"History search results",children:[e.jsx("p",{className:"small muted",children:"Meaning + keyword matches"}),!n.results.length&&e.jsx("p",{children:"No matches in this search. That does not prove the event never happened; try different wording or a wider scope."}),n.results.map(m=>e.jsxs("article",{className:"card history-result",children:[e.jsx("h2",{children:e.jsx("a",{href:`/history/${m.ref}`,target:"_blank",rel:"noopener noreferrer",children:m.title})}),e.jsx(Fe,{record:m}),e.jsx("pre",{className:"history-excerpt",children:m.text}),e.jsx("a",{href:`/history/${m.ref}`,target:"_blank",rel:"noopener noreferrer",children:"Read source and surrounding context"})]},m.ref)),e.jsx("p",{className:"small muted",children:n.limitations})]})]})]})}const Ge=["[Thinking...]","[Hmmm...]","[Hmmmmmm...]"],Qe=["[Checking...]","[Looking that up...]"];function De(t){const s=Array.from(t.trim().replace(/\s+/g," "));if(s.length<=140)return s.join("");const n=s.slice(-140).join(""),a=n.indexOf(" ");return"…"+(a>=0&&a<25?n.slice(a+1):n)}function rt({call:t,historyLookup:s}){const[n,a]=o.useState(0),r=!!t.replyPendingSince&&!["connecting","hearing","speaking","paused","ended"].includes(t.phase)&&!t.error;o.useEffect(()=>{if(a(0),!r)return;const c=setInterval(()=>a(u=>(u+1)%6),5e3);return()=>clearInterval(c)},[r,t.replyPendingSince,s]);let i,d="";return t.phase==="ended"?i="[Call ended]":t.error?i="[Reply unavailable]":t.phase==="paused"?i="[Sound paused]":t.phase==="connecting"?i=t.notice.startsWith("Preparing history")?"[Preparing history...]":t.notice.includes("microphone permission")?"[Waiting for microphone...]":"[Connecting...]":t.phase==="hearing"?(i=t.question?De(t.question):"[Listening...]",d=t.question?"You":""):r?i=s?Qe[n%Qe.length]:Ge[n%Ge.length]:t.notice.startsWith("Reply muted locally;")?i="[Reply stopped]":t.answer?(i=De(t.answer),d="Draken"):t.question?(i=De(t.question),d="You"):i=t.phase==="speaking"?"[Speaking...]":t.muted?"[Microphone off]":"[Listening...]",e.jsxs("div",{className:"voice-captions",role:"region","aria-label":"Live captions","aria-live":"off","data-kind":d?"transcript":"status",children:[d&&e.jsx("span",{className:"voice-caption-speaker",children:d}),e.jsx("div",{className:"voice-caption-window",children:e.jsx("p",{children:i})})]})}var U,R,Y,ne,he,me,J,ee,W,ae,je,q,we,be,ue,ge,ke,Ne;class ot{constructor({onClose:s=()=>{},onEvent:n=()=>{}}={}){O(this,U);O(this,R);O(this,Y);O(this,ne);O(this,he,new Set);O(this,me,[]);O(this,J);O(this,ee);O(this,W);O(this,ae,new Float32Array(1024));O(this,je,new AbortController);O(this,q,!1);O(this,we,!1);O(this,be,!1);O(this,ue);O(this,ge);O(this,ke);O(this,Ne);D(this,ke,s),D(this,Ne,n)}get closed(){return h(this,q)}get clock(){var s;return!h(this,q)&&((s=h(this,R))==null?void 0:s.state)==="running"?h(this,R).currentTime:NaN}get audioState(){var s;return((s=h(this,R))==null?void 0:s.state)||"closed"}async resume(){var s,n;h(this,q)||(await((s=h(this,R))==null?void 0:s.resume()),await((n=h(this,W))==null?void 0:n.play()))}gateInput(s){var n;(n=h(this,Y))==null||n.getAudioTracks().forEach(a=>{a.enabled=!!s})}get inputActive(){var s;return!!((s=h(this,Y))!=null&&s.getAudioTracks().some(n=>n.readyState==="live"))}get level(){var n;if(h(this,q)||h(this,be)||((n=h(this,R))==null?void 0:n.state)!=="running"||!h(this,J))return 0;h(this,J).getFloatTimeDomainData(h(this,ae));const s=Math.sqrt(h(this,ae).reduce((a,r)=>a+r*r,0)/h(this,ae).length);return Number.isFinite(s)?Math.min(1,s*12):0}async open(s,n){if(h(this,we)||h(this,q))throw s.getTracks().forEach(a=>a.stop()),new Error("A voice peer can open only once.");D(this,we,!0),D(this,Y,s);try{if(s.getAudioTracks().length!==1||s.getVideoTracks().length)throw new Error("Exactly one audio track is required.");if(D(this,U,new RTCPeerConnection),D(this,R,new AudioContext),D(this,J,h(this,R).createAnalyser()),h(this,J).fftSize=h(this,ae).length,D(this,ee,h(this,R).createGain()),h(this,J).connect(h(this,ee)),h(this,ee).connect(h(this,R).destination),D(this,ge,setTimeout(()=>this.close("Voice connection timed out."),6e4)),await h(this,R).resume(),h(this,q)||h(this,R).state!=="running")throw new Error("Voice playback could not start.");D(this,ne,h(this,U).addTrack(s.getAudioTracks()[0],s));const a=h(this,U).createDataChannel("oai-events"),r=new Promise((d,c)=>{D(this,ue,c);const u=()=>{h(this,U).connectionState==="connected"&&a.readyState==="open"?(D(this,ue,void 0),clearTimeout(h(this,ge)),d()):["failed","disconnected","closed"].includes(h(this,U).connectionState)&&this.close("Voice connection lost. Start a new call explicitly.")};h(this,U).onconnectionstatechange=u,a.onopen=u,a.onclose=()=>this.close("Voice event connection closed."),a.onerror=()=>this.close("Voice event connection failed.")});if(r.catch(()=>{}),a.onmessage=d=>{if(!h(this,q)){if(typeof d.data!="string"||d.data.length>2e5){this.close("Voice event exceeds its limit.");return}try{h(this,Ne).call(this,JSON.parse(d.data))}catch{this.close("Invalid voice event.")}}},h(this,U).ontrack=d=>{if(h(this,q)){d.track.stop();return}if(d.track.kind!=="audio"||h(this,he).size){this.close("Unexpected remote media track.");return}h(this,he).add(d.track);const c=new MediaStream([d.track]);D(this,W,new Audio),h(this,W).muted=!0,h(this,W).srcObject=c,h(this,W).play().catch(()=>this.close("Voice playback could not start."));const u=h(this,R).createMediaStreamSource(c);h(this,me).push(u),u.connect(h(this,J)),d.track.onended=()=>this.close("Voice output ended.")},await h(this,U).setLocalDescription(await h(this,U).createOffer()),h(this,q))throw new Error("Voice connection cancelled.");const i=await n(h(this,U).localDescription.sdp,h(this,je).signal);if(h(this,q))throw new Error("Voice connection cancelled.");if(typeof i!="string"||i.length>64e3||!i.startsWith("v=0"))throw new Error("Invalid voice answer.");await h(this,U).setRemoteDescription({type:"answer",sdp:i}),await r}catch(a){throw this.close("Voice connection failed or cancelled."),a}}muteOutput(s){D(this,be,!!s),h(this,ee)&&(h(this,ee).gain.value=s?0:1)}stopInput(){var s;(s=h(this,Y))==null||s.getTracks().forEach(n=>n.stop()),D(this,Y,void 0),h(this,ne)&&!h(this,q)&&h(this,ne).replaceTrack(null).catch(()=>this.close("Cannot mute voice input."))}async replaceInput(s){if(h(this,q)||!h(this,ne)||s.getAudioTracks().length!==1||s.getVideoTracks().length)throw s.getTracks().forEach(a=>a.stop()),new Error("Cannot attach voice input.");const n=h(this,Y);D(this,Y,s),n==null||n.getTracks().forEach(a=>a.stop());try{await h(this,ne).replaceTrack(s.getAudioTracks()[0])}catch(a){throw s.getTracks().forEach(r=>r.stop()),this.close("Cannot attach voice input."),a}if(h(this,q)||h(this,Y)!==s)throw s.getTracks().forEach(a=>a.stop()),new Error("Voice input was superseded.")}close(s="Call ended."){var n,a,r,i,d;if(!h(this,q)){D(this,q,!0),clearTimeout(h(this,ge)),h(this,je).abort(),(n=h(this,ue))==null||n.call(this,new Error(s)),D(this,ue,void 0),(a=h(this,U))==null||a.close(),(r=h(this,Y))==null||r.getTracks().forEach(c=>c.stop()),h(this,he).forEach(c=>c.stop()),h(this,he).clear(),h(this,me).forEach(c=>c.disconnect()),D(this,me,[]),(i=h(this,J))==null||i.disconnect(),(d=h(this,ee))==null||d.disconnect(),h(this,ae).fill(0),h(this,W)&&(h(this,W).pause(),h(this,W).srcObject=null,D(this,W,void 0)),h(this,R)&&h(this,R).state!=="closed"&&h(this,R).close().catch(()=>{});try{h(this,ke).call(this,s)}catch{}}}}U=new WeakMap,R=new WeakMap,Y=new WeakMap,ne=new WeakMap,he=new WeakMap,me=new WeakMap,J=new WeakMap,ee=new WeakMap,W=new WeakMap,ae=new WeakMap,je=new WeakMap,q=new WeakMap,we=new WeakMap,be=new WeakMap,ue=new WeakMap,ge=new WeakMap,ke=new WeakMap,Ne=new WeakMap;class ct{constructor(s){T(this,"state",{...qe,phase:"connecting"});T(this,"alive",!0);T(this,"id","");T(this,"pageExit",()=>{this.end()});T(this,"peer");T(this,"life",new AbortController);T(this,"inputContext",new AudioContext);T(this,"inputMeter",this.inputContext.createAnalyser());T(this,"inputSource");T(this,"input");T(this,"changing",!1);T(this,"cursor",0);T(this,"timer",0);T(this,"speechAt",0);T(this,"providerDone",!0);T(this,"stopped",!1);T(this,"newQuestion",!1);T(this,"pendingAnswer",!1);T(this,"answerSettled",!1);T(this,"awaitingUser",!1);T(this,"userId",0);T(this,"inputEpoch",0);T(this,"pendingNotice","Preparing the answer. I’ll continue automatically.");T(this,"assistantId",null);T(this,"observed",0);T(this,"reportedAt",0);T(this,"micBuffer",new Float32Array(1024));this.options=s,window.addEventListener("pagehide",this.pageExit),this.inputMeter.fftSize=1024,this.inputContext.resume().catch(()=>{}),this.peer=new ot({onEvent:n=>this.providerEvent(n),onClose:n=>{this.alive&&(this.set({error:n}),this.end())}}),this.set({})}set(s){this.state={...this.state,...s},this.options.onState(this.state)}async request(s,n){return G(`/live/calls/${this.id}${s}`,{method:n?"POST":"GET",...n?{body:JSON.stringify(n)}:{},signal:this.life.signal})}async microphone(){var n;const s=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});if(!this.alive)throw s.getTracks().forEach(a=>a.stop()),new Error("Call ended");(n=this.inputSource)==null||n.disconnect(),this.inputSource=this.inputContext.createMediaStreamSource(s),this.inputSource.connect(this.inputMeter),this.input=s,this.set({microphone:!0});for(const a of s.getAudioTracks())a.addEventListener("ended",()=>{this.alive&&!this.state.muted&&this.input===s&&(this.set({muted:!0,microphone:!1,notice:"Microphone disconnected. Type, or turn the microphone on again."}),this.peer.stopInput())});return s}silentInput(){const s=this.inputContext.createMediaStreamDestination(),n=this.inputContext.createConstantSource();return n.offset.value=0,n.connect(s),n.start(),s.stream}async start(s,n){var a,r;try{if(await(n==null?void 0:n()),!this.alive)return;this.set({notice:"Preparing history. Your microphone is still off."}),this.id=crypto.randomUUID();const i=await G("/live/calls",{method:"POST",body:JSON.stringify({syncId:s,requestId:this.id}),signal:this.life.signal});if(i.id!==this.id)throw new Error("The call reservation identity did not match.");if(!this.alive){G(`/live/calls/${this.id}/end`,{method:"POST",keepalive:!0}).catch(()=>{});return}if(document.visibilityState!=="visible")throw new Error("History is ready. Return to this page and start the call again to enable the microphone.");this.set({historyReady:!0,startedAt:i.startedAt,notice:"History is ready. Waiting for microphone permission…"}),this.poll();let d;try{d=await this.microphone(),this.set({notice:""})}catch{if(!this.alive)return;d=this.silentInput(),this.set({muted:!0,notice:"Microphone unavailable. You can type instead."})}if(this.input=d,await this.peer.open(d,async(c,u)=>(await G(`/live/calls/${i.id}/connect`,{method:"POST",body:JSON.stringify({sdp:c}),signal:u})).sdp),!this.alive)return;try{(r=(a=this.options).onPlayback)==null||r.call(a,{text:"",samples:new Float32Array(0),sampleRate:0,duration:1/0,startedAt:0,now:()=>this.peer.clock,level:()=>this.peer.level})}catch{}this.set({phase:this.state.replyPendingSince?"thinking":"listening"}),this.timer=window.setInterval(()=>this.meter(),80)}catch(i){this.alive&&(this.set({error:i instanceof Error?i.message:"Live voice could not start"}),await this.end())}}providerEvent(s){var n,a;this.alive&&(s.type==="input_transcript.added"&&this.stopped&&this.newQuestion&&(this.stopped=!1,this.peer.muteOutput(!1),this.set({notice:""})),s.type==="turn.created"&&((n=s.turn)==null?void 0:n.role)==="assistant"&&(this.stopped&&this.newQuestion&&(this.stopped=!1,this.newQuestion=!1,this.peer.muteOutput(!1)),this.providerDone=!1),s.type==="output_transcript.added"&&!this.stopped&&(this.providerDone=!1,this.state.voiceInterruption||this.peer.gateInput(!1)),s.type==="turn.done"&&((a=s.turn)==null?void 0:a.role)==="assistant"&&(this.providerDone=!0))}meter(){var r,i;if(!this.alive)return;const s=performance.now(),n=this.peer.level;let a=0;this.state.muted||(this.inputMeter.getFloatTimeDomainData(this.micBuffer),a=Math.sqrt(this.micBuffer.reduce((d,c)=>d+c*c,0)/this.micBuffer.length)*10),this.stopped&&a>.08&&(this.newQuestion=!0),(i=(r=this.options).onLevel)==null||i.call(r,Math.min(1,Math.max(n,a))),n>.02?(this.speechAt=s,this.observed+=80,this.state.phase!=="speaking"&&this.set({phase:"speaking"}),this.state.voiceInterruption||this.peer.gateInput(!1),this.assistantId&&s-this.reportedAt>1e3&&(this.reportedAt=s,this.request("/observed",{messageId:this.assistantId,milliseconds:this.observed}).catch(()=>{}))):(this.providerDone||this.pendingAnswer||this.answerSettled)&&s-this.speechAt>400&&this.state.phase==="speaking"&&(this.set({phase:this.state.replyPendingSince?"thinking":"listening"}),this.peer.gateInput(!this.state.muted)),this.peer.audioState==="suspended"&&this.state.phase!=="paused"&&this.set({phase:"paused"})}async poll(){var s,n;try{for(;this.alive;){const a=await this.request(`/events?after=${this.cursor}`);if(!this.alive)return;for(const r of a.events){if(this.cursor=r.sequence,r.type==="sources"&&this.set({evidence:r.evidence}),r.type==="message"){if(r.role==="user"){if(r.id<this.userId)continue;r.id>this.userId&&(this.awaitingUser||this.inputEpoch++,this.pendingAnswer=!1,this.answerSettled=!1,this.set({answer:"",error:"",replyPendingSince:this.awaitingUser?this.state.replyPendingSince:0,...!this.awaitingUser&&!this.stopped?{phase:"hearing"}:{},...this.state.notice===this.pendingNotice?{notice:""}:{}}),this.awaitingUser=!1),this.userId=r.id,this.set({question:r.text}),r.final&&!this.answerSettled&&(!this.stopped||this.newQuestion)&&(this.pendingAnswer=!0,this.set({replyPendingSince:this.state.replyPendingSince||Date.now(),...["speaking","paused"].includes(this.state.phase)?{}:{phase:"thinking"}}))}else this.assistantId!==r.id&&(this.assistantId=r.id,this.observed=0),this.set({turnId:r.id,answer:r.text,evidence:r.evidence});(n=(s=this.options).onTurn)==null||n.call(s,r.role==="user"?r.text:"",r.role==="assistant"?r.text:"",r.evidence,r.id)}r.type==="answer_pending"&&r.id===this.userId&&!this.awaitingUser&&(!this.stopped||this.newQuestion)&&(this.pendingAnswer=r.pending===!0,this.answerSettled=!this.pendingAnswer,this.set({replyPendingSince:this.pendingAnswer?this.state.replyPendingSince||Date.now():0,...["thinking","listening","hearing"].includes(this.state.phase)?{phase:this.pendingAnswer?"thinking":"listening"}:{},...!this.state.notice||this.state.notice===this.pendingNotice?{notice:this.pendingAnswer?this.pendingNotice:""}:{},...r.error?{error:r.error}:{}})),r.type==="error"&&this.set({error:r.error})}if(!a.active){await this.end();return}await new Promise(r=>setTimeout(r,250))}}catch(a){this.alive&&(this.set({error:a instanceof Error?a.message:"Live connection lost"}),await this.end())}}async sendText(s){if(!this.alive||!this.id||!s.trim()||s.length>2e3)return;const n=++this.inputEpoch;this.newQuestion=!0,this.awaitingUser=!0,this.answerSettled=!1,this.pendingAnswer=!1,this.set({phase:"thinking",error:"",question:s,answer:"",replyPendingSince:Date.now()});try{await this.request("/text",{question:s,requestId:crypto.randomUUID()}),this.alive&&n===this.inputEpoch&&this.stopped&&(this.stopped=!1,this.peer.muteOutput(!1),this.set({notice:""}))}catch(a){this.alive&&n===this.inputEpoch&&(this.awaitingUser=!1,this.pendingAnswer=!1,this.answerSettled=!0,this.set({phase:"listening",replyPendingSince:0,error:a instanceof Error?a.message:"Question could not be sent"}))}}async toggleMute(){var s;if(!(!this.alive||this.changing)){this.changing=!0;try{if(!this.state.muted)this.set({muted:!0}),this.peer.stopInput(),(s=this.inputSource)==null||s.disconnect();else{const n=await this.microphone();await this.peer.replaceInput(n),this.alive&&(this.set({muted:!1,notice:""}),this.peer.gateInput(this.state.voiceInterruption||this.state.phase!=="speaking"))}}catch{this.alive&&this.set({muted:!0,notice:"Microphone unavailable. You can type instead."})}finally{this.changing=!1}}}setVoiceInterruption(s){this.set({voiceInterruption:s}),this.peer.gateInput(!this.state.muted&&(s||this.state.phase!=="speaking"))}async interrupt(){if(this.alive){this.inputEpoch++,this.pendingAnswer=!1,this.awaitingUser=!1,this.answerSettled=!0,this.stopped=!0,this.newQuestion=!1,this.peer.muteOutput(!0),this.peer.gateInput(!this.state.muted),this.set({phase:"listening",replyPendingSince:0,notice:"Reply muted locally; a stop request was sent. Ask another question to continue."});try{await this.request("/interrupt",{})}catch{this.alive&&(this.set({error:"The remote stop could not be confirmed. The call was ended."}),await this.end())}}}async resumeSound(){await this.peer.resume(),this.alive&&this.set({phase:this.state.replyPendingSince?"thinking":"listening"})}async end(){var s,n,a,r,i,d;if(this.alive){this.alive=!1,window.removeEventListener("pagehide",this.pageExit),clearInterval(this.timer),this.life.abort(),(s=this.input)==null||s.getTracks().forEach(c=>c.stop()),(n=this.inputSource)==null||n.disconnect(),this.peer.close(),this.inputContext.close().catch(()=>{});try{(r=(a=this.options).onPlayback)==null||r.call(a,null)}catch{}if(this.pendingAnswer=!1,this.awaitingUser=!1,(d=(i=this.options).onLevel)==null||d.call(i,0),this.set({phase:"ended",muted:!0,notice:"",replyPendingSince:0}),this.id){const c=new AbortController,u=setTimeout(()=>c.abort(),4e3);try{await G(`/live/calls/${this.id}/end`,{method:"POST",keepalive:!0,signal:c.signal})}catch{}finally{clearTimeout(u)}}}}}const lt={connecting:"Getting ready",listening:"Your turn",hearing:"Listening to you",thinking:"Preparing your answer",speaking:"Draken is speaking",paused:"Sound paused",ended:"Call ended"},dt=t=>`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`;function ht({sync:t,disabled:s,beforeStart:n,onActiveChange:a,onClosed:r,autoStart:i=!1,onAutoStartHandled:d}){const[c,u]=o.useState(null),[k,v]=o.useState(""),[m,g]=o.useState(!1),[l,x]=o.useState(qe),[j,I]=o.useState(0),[y,C]=o.useState(!1),[w,A]=o.useState(""),[N,f]=o.useState([]),[S,$]=o.useState(null),[V,_]=o.useState(""),[z,re]=o.useState(!1),[Q,fe]=o.useState(!1),oe=o.useRef(null),ce=o.useRef(null),le=o.useRef(null),pe=o.useRef(null),F=o.useRef(null),K=o.useRef(!0),de=o.useRef(!1),xe=[...t.items,...t.context],se=xe.find(p=>p.ref===V),b=t.status==="open"&&(t.tree.complete||!t.items.length),H=window.isSecureContext,B=new URL(window.location.href);B.protocol="https:",B.port=String((c==null?void 0:c.httpsPort)||443),o.useEffect(()=>{V&&ce.current&&le.current&&(ce.current.scrollTop+=le.current.getBoundingClientRect().top-ce.current.getBoundingClientRect().top)},[V]);const te=async()=>{try{const p=await G("/status");K.current&&(u(p),v(""))}catch(p){K.current&&v(p instanceof Error?p.message:"Could not check ChatGPT voice")}};o.useEffect(()=>{K.current=!0,te();const p=setInterval(()=>{F.current||te()},15e3);return()=>{var E;clearInterval(p),K.current=!1,(E=F.current)==null||E.end()}},[]),o.useEffect(()=>{var p,E,M;m&&!((p=oe.current)!=null&&p.open)?(E=oe.current)==null||E.showModal():m||(M=oe.current)==null||M.close()},[m]),o.useEffect(()=>{if(!m||!l.startedAt||l.phase==="ended")return;const p=()=>I(Math.max(0,Math.floor((Date.now()-l.startedAt)/1e3)));p();const E=setInterval(p,1e3);return()=>clearInterval(E)},[m,l.startedAt,l.phase==="ended"]);const Z=async()=>{var p;if(!(F.current||de.current)){x({...qe}),I(0),f([]),A(""),_(""),C(!1),re(!1),fe(!1),g(!0),a(!0);try{const E=new ct({onState:M=>{K.current&&(x(M),!M.microphone&&M.muted&&C(!0))},onLevel:()=>{},onPlayback:M=>{pe.current=M},onTurn:(M,ze,Ue,Se)=>{K.current&&f(Pe=>Pe.some(Ce=>Ce.id===Se)?Pe.map(Ce=>Ce.id===Se?{id:Se,question:M,answer:ze,refs:Ue}:Ce):[...Pe,{id:Se,question:M,answer:ze,refs:Ue}])}});F.current=E,await n(),F.current===E&&await E.start(t.id)}catch(E){await((p=F.current)==null?void 0:p.end()),K.current&&x(M=>({...M,phase:"ended",error:E instanceof Error?E.message:"The call could not start"}))}}};o.useEffect(()=>{!i||s||!b||!c||(d==null||d(),c.installed&&!c.activeCall&&H&&document.visibilityState==="visible"?Z():v("Your snapshot is ready. Start the call explicitly when audio is available and this page is visible."))},[i,s,b,c]);const X=async()=>{var p;if(!de.current){de.current=!0,await((p=F.current)==null?void 0:p.end()),F.current=null,K.current&&(g(!1),$(null),a(!1));try{await r(),await te()}finally{de.current=!1}}},is=async()=>{try{$(await G(`/syncs/${t.id}/history`))}catch(p){v(p instanceof Error?p.message:"Could not load call history")}},rs=async()=>{try{const p=await fetch("/api/voice/certificate",{headers:ss(!1)});if(!p.ok)throw new Error("Could not download the local certificate. Check your dashboard login.");const E=URL.createObjectURL(await p.blob()),M=document.createElement("a");M.href=E,M.download="draken-local-root.crt",M.click(),setTimeout(()=>URL.revokeObjectURL(E),1e3)}catch(p){v(p instanceof Error?p.message:"Certificate download failed")}},os=()=>{var E;if(!w.trim())return;const p=w.trim();A(""),(E=F.current)==null||E.sendText(p)};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"card voice-entry","aria-label":"Voice calls",children:[e.jsxs("div",{className:"voice-entry-main",children:[e.jsx("div",{className:"voice-entry-icon","aria-hidden":"true",children:e.jsx($e,{size:22})}),e.jsxs("div",{children:[e.jsx("h2",{children:"Talk it through. Out loud."}),e.jsx("p",{className:"muted small",children:"Live voice through ChatGPT. Audio goes to OpenAI; replies may paraphrase."})]}),!H&&(c!=null&&c.httpsPort)?e.jsxs("a",{className:"btn btn-primary",href:B.href,children:["Open secure call page ",e.jsx(ws,{size:15})]}):e.jsxs("button",{className:"btn btn-primary",disabled:s||!b||!(c!=null&&c.installed)||!!(c!=null&&c.activeCall)||!H,onClick:()=>void Z(),children:[e.jsx($e,{size:16}),"Call Draken"]})]}),e.jsx("p",{className:"small muted",children:"Relevant earlier history is found automatically. Retrieved excerpts go to ChatGPT, separately from this frozen snapshot; no review or saved decisions change."}),!H&&e.jsxs("p",{className:"small muted",children:["The microphone needs trusted HTTPS. ",c!=null&&c.httpsPort?"The secure page uses your existing dashboard login. Install the local certificate once on this device before opening it.":"Use localhost, or enable HTTPS on the server."]}),(c==null?void 0:c.certificateAvailable)&&e.jsxs("details",{className:"voice-history",children:[e.jsx("summary",{children:"First-time browser setup"}),e.jsx("p",{className:"small",children:"Trust only your own Draken server’s certificate. This is a one-time device setup, not another account or voice subscription."}),e.jsx("button",{className:"btn btn-secondary",onClick:()=>void rs(),children:"Download local certificate"}),e.jsxs("ul",{className:"small",children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Windows:"})," open the downloaded certificate → Install Certificate → Current User → place in Trusted Root Certification Authorities."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"macOS:"})," import into Keychain Access → login keychain. Open its Trust section and choose Always Trust."]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Firefox/Linux:"})," Settings → Privacy & Security → Certificates → View Certificates → Authorities → Import. Trust it to identify websites."]})]}),e.jsxs("p",{className:"small muted",children:["Restart the browser if needed, open the secure page, sign in, and allow the microphone when you start a call. Keep the server’s private keys private. See ",e.jsx("code",{children:"VOICE.md"})," for an SSH-tunnel alternative."]})]}),t.status==="open"&&!b&&e.jsx("p",{className:"small muted",children:"Prepare the briefing first so the call starts with the full picture."}),t.status!=="open"&&e.jsx("p",{className:"small muted",children:"This sync is closed. Start a new sync for another call."}),c&&!c.installed&&e.jsxs("p",{className:"small muted",children:["ChatGPT voice needs server setup and sign-in: ",e.jsx("code",{children:"npm run voice:realtime:setup"}),", then ",e.jsx("code",{children:"npm run voice:realtime:login"}),"."]}),k&&e.jsxs("p",{className:"small",role:"alert",children:[k," ",e.jsx("button",{className:"btn btn-secondary",onClick:()=>void te(),children:"Retry"})]}),(c==null?void 0:c.activeCall)&&!m&&e.jsxs("div",{className:"small voice-reconnect",children:["A call is still open in another tab or device.",e.jsx("button",{className:"btn btn-secondary",disabled:s,onClick:()=>{window.confirm("End the existing voice call? Its completed transcript is kept.")&&G(`/live/calls/${c.activeCall.id}/end`,{method:"POST",body:"{}"}).then(te).catch(p=>v(p.message))},children:"End previous call"})]}),e.jsxs("details",{className:"voice-history",onToggle:p=>{p.currentTarget.open&&is()},children:[e.jsx("summary",{children:"Call history"}),(S==null?void 0:S.length)===0&&e.jsx("p",{className:"muted small",children:"No calls yet. Transcripts are saved here; raw audio is not recorded."}),S==null?void 0:S.map(p=>e.jsxs("details",{className:"voice-history-call",children:[e.jsxs("summary",{children:[new Date(p.started_at).toLocaleString()," · ",p.turns.length," ",p.mode==="native"?"messages":"turns"," · ",p.status]}),e.jsx("p",{className:"small muted",children:p.end_reason||"Call in progress"}),p.mode==="native"?e.jsx("p",{className:"small muted",children:"Ordered live transcripts, not verified question–answer pairs. Sources are supplied context, not verified citations. Exact playback is not confirmed."}):e.jsx("p",{className:"small muted",children:"Historical call from the retired local speech engine. These records are preserved; this engine cannot start new calls."}),p.turns.map(E=>e.jsxs("div",{className:"voice-history-turn",children:[E.question&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{className:"message-author",children:"You"}),e.jsx("p",{className:"prose",children:E.question})]}),(E.answer||!E.question||p.mode!=="native")&&e.jsxs(e.Fragment,{children:[e.jsxs("strong",{className:"message-author",children:["Draken · ",E.status]}),e.jsx(_e,{text:`${E.answer||E.error||"No reply generated."} ${JSON.parse(E.evidence_json).map(M=>`[${M}]`).join(" ")}`,evidence:xe}),E.status!=="completed"&&e.jsxs("p",{className:"small muted",children:["Generated text is shown above. ",E.heard_text?`Confirmed played: ${E.heard_text}`:"Playback was not confirmed."]})]})]},E.id))]},p.id))]})]}),e.jsxs("dialog",{ref:oe,className:"voice-dialog","aria-labelledby":"voice-title",onCancel:p=>{p.preventDefault(),X()},children:[e.jsxs("div",{className:"voice-dialog-header",children:[e.jsxs("div",{children:[e.jsx("span",{className:"eyebrow",children:"DRAKEN / VOICE SYNC"}),e.jsxs("h2",{id:"voice-title",children:["Sync #",t.id]})]}),e.jsx("span",{className:"voice-clock","aria-label":"Call duration",children:dt(j)}),e.jsx("button",{className:"icon-button","aria-label":"Close call",onClick:()=>void X(),children:e.jsx(Oe,{size:18})})]}),e.jsxs("div",{className:"voice-call-body",children:[l.historyReady?e.jsxs("div",{className:"voice-scene",children:[m&&l.phase!=="ended"?e.jsx(ds,{playback:pe,mode:l.phase==="speaking"?"speaking":l.phase==="hearing"?"listening":l.replyPendingSince&&!l.error?"thinking":"idle"}):e.jsx("img",{loading:"lazy",className:"voice-scene-poster",src:"/persona/call-poster.webp",alt:"Draken’s workshop"}),e.jsx(rt,{call:l,historyLookup:Q})]}):e.jsxs("section",{className:"voice-preparation","aria-label":"Call preparation",children:[e.jsx("h3",{children:l.phase==="ended"?"Preparation stopped":"Preparing history"}),e.jsx("p",{className:"small muted",children:"Your microphone is off. Draken will appear when indexing is ready."}),e.jsx(ve,{enabled:m&&l.phase!=="ended",waiting:!0})]}),e.jsx("p",{className:"sr-only",role:"status","aria-label":"Call state","aria-live":"polite",children:l.muted&&l.phase==="listening"?"Microphone muted":lt[l.phase]})]}),l.error&&e.jsx("div",{className:"alert error",role:"alert",children:l.error}),l.error&&l.question&&l.phase==="listening"&&e.jsx("button",{className:"btn btn-primary",onClick:()=>{var p;return void((p=F.current)==null?void 0:p.sendText(l.question))},children:"Retry question"}),l.phase==="paused"&&e.jsx("button",{className:"btn btn-primary",onClick:()=>{var p;return void((p=F.current)==null?void 0:p.resumeSound())},children:"Resume sound"}),e.jsxs("div",{className:"voice-controls",children:[e.jsxs("button",{className:`btn btn-secondary ${l.muted?"is-muted":""}`,disabled:l.phase==="connecting"||l.phase==="ended",onClick:()=>{var p;return void((p=F.current)==null?void 0:p.toggleMute())},children:[l.muted?e.jsx(Es,{size:18}):e.jsx(As,{size:18}),l.muted?l.microphone?"Unmute":"Enable mic":"Mute"]}),e.jsxs("button",{className:"btn btn-secondary",disabled:!["thinking","speaking","paused"].includes(l.phase),onClick:()=>{var p;return void((p=F.current)==null?void 0:p.interrupt().catch(()=>{}))},children:[e.jsx(Ps,{size:15}),"Stop reply"]}),e.jsxs("button",{className:"btn btn-danger",onClick:()=>void X(),children:[e.jsx(Ts,{size:18}),l.phase==="ended"?"Close":"End call"]})]}),e.jsxs("div",{className:"voice-options",children:[e.jsxs("button",{className:"voice-keyboard-toggle","aria-pressed":l.voiceInterruption,disabled:l.phase==="connecting"||l.phase==="ended",onClick:()=>{var p;return(p=F.current)==null?void 0:p.setVoiceInterruption(!l.voiceInterruption)},children:[e.jsx(bs,{size:16}),"Headphone mode"]}),e.jsxs("button",{className:"voice-keyboard-toggle",onClick:()=>C(p=>!p),"aria-expanded":y,children:[e.jsx(ks,{size:16}),y?"Hide keyboard":"Type a question"]})]}),y&&e.jsxs("form",{className:"voice-compose",onSubmit:p=>{p.preventDefault(),os()},children:[e.jsx("input",{className:"input","aria-label":"Type a question for this call",placeholder:"Or ask here…",maxLength:2e3,disabled:l.phase==="connecting"||l.phase==="ended",value:w,onChange:p=>A(p.target.value)}),e.jsx("button",{className:"btn btn-primary","aria-label":"Send voice-call question",disabled:!w.trim()||l.phase==="connecting"||l.phase==="ended",children:e.jsx(xs,{size:18})})]}),e.jsxs("details",{className:"voice-conversation",open:z,onToggle:p=>re(p.currentTarget.open),children:[e.jsx("summary",{children:"Conversation & details"}),e.jsxs("div",{className:"voice-call-details",ref:ce,children:[l.notice&&e.jsx("p",{className:"small muted voice-notice",children:l.notice}),e.jsx(ve,{enabled:m&&l.historyReady&&(!!l.replyPendingSince||["connecting","thinking"].includes(l.phase)),onLookupChange:fe}),e.jsx("p",{className:"small muted",children:l.phase==="speaking"?l.voiceInterruption?"Speak to interrupt. Use headphones to avoid speaker feedback.":"Listening pauses during replies to prevent echo. Tap Stop reply to speak.":"Speak naturally. A short pause sends your question."}),e.jsx("div",{className:"voice-transcript",children:N.map(p=>e.jsxs("div",{children:[p.question&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"You"}),e.jsx("p",{children:p.question})]}),p.answer&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Draken · generated reply"}),e.jsx("p",{className:p.id===l.turnId?"voice-answer":void 0,children:p.answer})]})]},p.id))}),!N.length&&e.jsx("p",{className:"small muted",children:"No transcript yet."}),e.jsx("p",{className:"small muted",children:"Live generated transcripts, not word-timed subtitles. Exact playback and agreement are not confirmed. Full text is retained here even when the scene shows only its latest lines."}),l.evidence.length>0&&e.jsxs("details",{className:"voice-history",children:[e.jsxs("summary",{children:["Sources supplied (",l.evidence.length,")"]}),e.jsx("p",{className:"small muted",children:"Context available to the voice model, not verified citations for every spoken claim."}),e.jsx("div",{className:"voice-sources",children:l.evidence.map(p=>e.jsx("button",{className:"citation",onClick:E=>{const M=E.currentTarget.closest("details");M&&(M.open=!1),_(V===p?"":p)},children:p.startsWith("H")?`History ${p.slice(-6)}`:`Source ${p}`},p))})]}),/^H[a-f0-9]{24}$/.test(V)&&e.jsxs("section",{className:"voice-source",ref:le,children:[e.jsx("button",{className:"btn btn-secondary",onClick:()=>_(""),children:"Close historical source"}),e.jsx(as,{reference:V})]}),se&&e.jsxs("section",{className:"voice-source",ref:le,children:[e.jsxs("div",{className:"section-heading",children:[e.jsxs("strong",{children:[se.ref," · ",se.session_name||se.cwd]}),e.jsx("button",{className:"icon-button","aria-label":"Close source",onClick:()=>_(""),children:e.jsx(Oe,{size:16})})]}),e.jsx("pre",{children:se.text})]})]})]}),e.jsxs("div",{className:"voice-footer",children:[e.jsx(ys,{size:14}),e.jsx("span",{children:"Experimental live audio to OpenAI · Generated, not verified · 30-minute limit"})]})]})]})}function ut({id:t,callIntent:s,consumeIntent:n,navigate:a,setGuard:r}){var F,K,de,xe,se;const[i,d]=o.useState(null),[c,u]=o.useState(""),[k,v]=o.useState(""),[m,g]=o.useState(!1),[l,x]=o.useState(!1),[j,I]=o.useState(""),[y,C]=o.useState(""),[w,A]=o.useState(""),N=o.useRef(!0),f=b=>{N.current&&(d(b),I(b.decisions),C(b.carry_forward))},S=async(b,H)=>{u(b),v("");try{await H()}catch(B){N.current&&v(B instanceof Error?B.message:"Something went wrong")}finally{N.current&&u("")}};o.useEffect(()=>(N.current=!0,We(t).then(f).catch(b=>{N.current&&v(b.message)}),()=>{N.current=!1}),[t]),o.useEffect(()=>{if(!(i!=null&&i.busy))return;let b=!1,H;const B=async()=>{var te;try{const Z=await Hs(t);if(b)return;if(Z.busy)d(X=>X&&{...X,tree:Z});else{const X=await We(t);b||(f(X),((te=Z.run)==null?void 0:te.status)==="completed"&&A(""));return}}catch(Z){b||v(Z instanceof Error?Z.message:"Could not refresh progress")}b||(H=setTimeout(()=>void B(),1e3))};return B(),()=>{b=!0,clearTimeout(H)}},[t,i==null?void 0:i.busy]);const $=!!(i&&(j!==i.decisions||y!==i.carry_forward));o.useEffect(()=>{r(()=>!($||m)||window.confirm(m?"Leave this page and end the call?":"Leave without saving your notes?"));const H=B=>{($||m)&&(B.preventDefault(),B.returnValue="")};return window.addEventListener("beforeunload",H),()=>{r(null),window.removeEventListener("beforeunload",H)}},[$,m,r]);const V=()=>{n(),x(!1)},_=!!(c||i!=null&&i.busy||m),z=(i==null?void 0:i.status)==="open",re=i?[...i.items,...i.context]:[],Q=re.some(b=>b.unavailable),fe=()=>void S("Preparing your conversation…",async()=>{i&&(x(!0),$&&await Te(t,j,y),f(await Ws(t)))}),oe=(b=w)=>void S("Starting discussion…",async()=>{$&&await Te(t,j,y),f(await Ks(t,b))}),ce=()=>{var b;return(b=i==null?void 0:i.tree.run)!=null&&b.question?oe(i.tree.run.question):fe()},le=()=>{V(),S("Stopping preparation…",async()=>{await Ys(t)})},pe=!(i!=null&&i.busy)&&(i==null?void 0:i.tree.run)&&["failed","cancelled","interrupted"].includes(i.tree.run.status);return e.jsxs("main",{className:"sync-detail",children:[e.jsxs("a",{className:"back-link",href:"/",onClick:b=>ie(b,a,"/"),children:[e.jsx(fs,{size:16}),"All syncs"]}),k&&e.jsx("div",{className:"alert error",role:"alert",children:k}),!i&&!k&&e.jsx("p",{role:"status",children:"Opening sync…"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"page-heading",children:[e.jsxs("div",{children:[e.jsx("span",{className:"eyebrow",children:"FROZEN CONVERSATION"}),e.jsxs("h1",{children:["Sync #",t]}),e.jsxs("p",{className:"muted",children:[new Date(i.snapshot_at).toLocaleString()," · ",i.item_count," entries · ",e.jsx("span",{className:`status ${i.status}`,children:i.status==="completed"?"reviewed":i.status})]}),e.jsx(ts,{cost:i.aggregation_cost})]}),z&&e.jsxs("button",{className:"btn btn-secondary",disabled:_||Q||!!(i.tree.run&&!i.tree.complete),onClick:()=>{window.confirm(`Mark these ${i.item_count} snapshot entries reviewed? Later activity is not affected. This does not mean every spoken suggestion was agreed.`)&&S("Marking snapshot reviewed…",async()=>{f(await Zs(t,j,y))})},children:[e.jsx(vs,{size:16}),"Mark reviewed"]})]}),Q&&e.jsxs("div",{className:"alert warning",role:"alert",children:[e.jsx("strong",{children:"Original session evidence unavailable."}),e.jsx("p",{children:"Restore the original session files to inspect the missing excerpts, prepare replies, call or mark this snapshot reviewed. Your conversation and saved notes are still available; Draken keeps pointers, not copies of original session text."})]}),(c||i.busy)&&e.jsxs("div",{className:"working",role:"status",children:[e.jsx("span",{className:"spinner"}),c||(i.recap_state==="running"?"Making a short conversation recap…":((F=i.tree.run)==null?void 0:F.stage)||"Preparing your conversation…"),i.busy&&e.jsx("button",{className:"btn btn-secondary",onClick:le,children:"Cancel preparation"})]}),e.jsx(ve,{enabled:!!(i.busy&&((K=i.tree.run)!=null&&K.question))}),i.busy&&i.recap_state!=="running"&&e.jsx("p",{className:"small muted",children:"The complete new snapshot is being reconciled. Large histories can take a while. Leaving or reloading will not start your microphone."}),pe&&e.jsxs("div",{className:"alert warning",role:"alert",children:[e.jsx("strong",{children:(de=i.tree.run)!=null&&de.question?"Reply stopped.":"Preparation stopped."}),e.jsx("p",{children:((xe=i.tree.run)==null?void 0:xe.error)||"Your snapshot is retained. Nothing was marked reviewed."}),e.jsx("button",{className:"btn btn-primary",disabled:_||Q,onClick:ce,children:(se=i.tree.run)!=null&&se.question?"Retry reply":"Retry preparation & call"})]}),z&&!i.briefing&&!i.busy&&!pe&&i.snapshot_version===2&&e.jsx("button",{className:"btn btn-primary",disabled:_||Q,onClick:fe,children:"Prepare & call"}),e.jsx(ht,{sync:i,disabled:_||Q,onActiveChange:g,autoStart:(s||l)&&!pe&&!Q,onAutoStartHandled:V,beforeStart:async()=>{$&&f(await Te(t,j,y))},onClosed:async()=>{await S("Saving a short recap…",async()=>{f(await Be(t))})}},t),e.jsxs("section",{className:"card recap-card",children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h2",{children:"At a glance"}),e.jsx("button",{className:"btn btn-secondary",disabled:_,onClick:()=>void S("Summarizing the conversation…",async()=>f(await Be(t))),children:i.recap?"Refresh recap":"Make recap"})]}),e.jsx("p",{className:"prose",children:i.recap||"The call and this sync will be condensed here after you talk. The full briefing and original history remain below."}),e.jsx("p",{className:"small muted",children:"Automatic summary, not saved decisions or proof of agreement."}),i.recap_error&&e.jsx("p",{role:"alert",className:"small",children:i.recap_error})]}),i.memory.length>0&&e.jsxs("details",{className:"detail-section",children:[e.jsx("summary",{children:"Previous sync recaps"}),i.memory.map(b=>e.jsxs("article",{className:"memory-recap",children:[e.jsxs("a",{href:`/syncs/${b.sync_id}`,onClick:H=>ie(H,a,`/syncs/${b.sync_id}`),children:["Sync #",b.sync_id]})," ",e.jsx("span",{className:"small muted",children:b.status==="open"?"not marked reviewed":b.status||"historical"}),e.jsx("p",{className:"prose",children:b.recap||"No automatic recap in this older snapshot."}),b.decisions&&e.jsxs("p",{className:"small prose",children:["Saved decisions: ",b.decisions]}),b.carry_forward&&e.jsxs("p",{className:"small prose",children:["Carried forward: ",b.carry_forward]})]},b.sync_id))]}),e.jsxs("details",{className:"detail-section",open:!i.messages.length&&!!i.briefing,children:[e.jsx("summary",{children:"Full briefing"}),e.jsxs("section",{className:"briefing-card",children:[e.jsxs("p",{className:"small muted",children:["New activity after ",new Date(i.snapshot_at).toLocaleString()," stays outside this snapshot."]}),i.briefing?e.jsx(_e,{text:i.briefing,evidence:re}):e.jsx("p",{children:"No briefing yet."}),i.snapshot_version<2&&e.jsxs("div",{className:"alert warning",children:["This is a historical capped snapshot. Notes and discussion are preserved.",z&&e.jsx("button",{className:"btn btn-secondary",disabled:_,onClick:()=>{window.confirm("Expand this legacy snapshot to currently eligible history? Existing notes and citations are retained.")&&S("Expanding snapshot…",async()=>f((await Bs(t)).sync))},children:"Expand to full history"})]})]})]}),e.jsxs("details",{className:"detail-section",children:[e.jsxs("summary",{children:["Conversation & text discussion (",i.messages.length,")"]}),e.jsxs("section",{className:"discussion",children:[i.messages.map(b=>e.jsxs("div",{className:`message ${b.role}`,children:[e.jsx("span",{className:"message-author",children:b.role==="user"?"You":"Draken"}),e.jsx(_e,{text:b.content,evidence:re})]},b.id)),z&&e.jsxs("form",{onSubmit:b=>{b.preventDefault(),oe()},children:[e.jsx("label",{className:"sr-only",htmlFor:"question",children:"Ask Draken about this sync"}),e.jsx("textarea",{id:"question",rows:3,maxLength:4e3,value:w,disabled:_,onChange:b=>A(b.target.value),placeholder:"Or continue in text…"}),e.jsx("p",{className:"small muted",children:"Relevant earlier history is found automatically and supplied to the discussion model, separately from this snapshot. Nothing is marked reviewed."}),e.jsx("div",{className:"form-footer",children:e.jsxs("button",{className:"btn btn-primary",disabled:_||Q||!w.trim(),children:["Ask Draken",e.jsx(Le,{size:16})]})})]})]})]}),e.jsxs("details",{className:"detail-section",children:[e.jsxs("summary",{children:["Decisions & carry-forward",$?" · unsaved":""]}),e.jsxs("section",{className:"notes-card",children:[e.jsxs("div",{className:"notes-grid",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"decisions",children:"Decisions"}),e.jsx("textarea",{id:"decisions",rows:4,maxLength:4e3,disabled:!z||_,value:j,onChange:b=>I(b.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"carry-forward",children:"Carry into the next sync"}),e.jsx("textarea",{id:"carry-forward",rows:4,maxLength:4e3,disabled:!z||_,value:y,onChange:b=>C(b.target.value)})]})]}),e.jsx("p",{className:"small muted",children:"Only these explicitly saved notes are decisions. A call or its automatic recap does not mark anything agreed or reviewed."}),z&&e.jsx("button",{className:"btn btn-secondary",disabled:_||!$,onClick:()=>void S("Saving notes…",async()=>f(await Te(t,j,y))),children:"Save notes"})]})]}),e.jsxs("details",{className:"detail-section",children:[e.jsx("summary",{children:"Evidence & preparation details"}),e.jsx(et,{syncId:t,progress:i.tree,evidence:re,onResume:z?ce:void 0,resumeEnabled:!_&&!Q,onCancel:le}),e.jsx(Ke,{items:i.items,title:"New evidence in this snapshot"}),e.jsx(Ke,{items:i.context,title:"Earlier context — not new progress"})]}),z&&e.jsxs("div",{className:"detail-footer",children:[e.jsx("p",{className:"small muted",children:"Included does not mean reviewed. You can return to this sync at this URL, or start a separate one for new activity."}),e.jsx("button",{className:"btn btn-ghost",disabled:_,onClick:()=>{window.confirm("Discard this sync and release its unreviewed entries? Its history is retained.")&&S("Discarding sync…",async()=>f(await Xs(t)))},children:"Discard sync"})]})]})]})}const Je=t=>new Date(t).toLocaleString(),pt={pi:"pi v3 JSONL",codex:"Rollout JSONL",claude:"Transcript JSONL"};function mt({open:t}){const[s,n]=o.useState(!1),[a,r]=o.useState(null),[i,d]=o.useState(!0),[c,u]=o.useState(!1),[k,v]=o.useState(""),[m,g]=o.useState(""),[l,x]=o.useState(null),j=o.useRef(!0),I=o.useRef(!1);o.useEffect(()=>(j.current=!0,()=>{j.current=!1}),[]),o.useEffect(()=>{if(!t||!s||c)return;let w=!0;const A=async()=>{try{const[f,S]=await Promise.all([Ye(),Re()]);w&&!I.current&&(r(f),d(S.busy||S.active_call),g(""))}catch(f){w&&!I.current&&g(f instanceof Error?f.message:"Could not read session sources")}};A();const N=setInterval(()=>void A(),4e3);return()=>{w=!1,clearInterval(N)}},[t,s,c]);const y=async(w,A)=>{if(!a||i||m||I.current)return;const N=a;I.current=!0,u(!0),v(""),A&&r(A);try{const f=await w();j.current&&r(f)}catch(f){j.current&&(A&&r(N),v(f instanceof Error?f.message:"Could not update session sources"))}finally{I.current=!1,j.current&&u(!1)}},C=!a||i||c||!!m;return e.jsxs("details",{className:"source-settings",onToggle:w=>n(w.currentTarget.open),children:[e.jsx("summary",{children:"Agents & sessions"}),e.jsx("p",{className:"small muted",children:"Directory presence is not an installation check. Opening this panel reads recorded metadata; it does not scan transcripts, index embeddings or call a model."}),e.jsx("p",{className:"small muted",children:"Enable each history source before importing it. Codex and Claude history start off; existing pi choices are preserved. Enabling a source allows its logs into the next scan, sync or opted-in background batch. New sessions from enabled agents are selected by default. Summarization still runs through pi, regardless of which agent produced the history."}),!a&&e.jsx("p",{className:"small muted",role:"status",children:"Loading session inventory…"}),e.jsxs("button",{type:"button",className:"btn btn-secondary",disabled:C||!(a!=null&&a.agents.some(w=>w.enabled)),onClick:()=>void y(async()=>{const w=await Fs();return j.current&&x(w),Ye()}),children:[e.jsx(Is,{size:15,"aria-hidden":"true"}),"Scan enabled agents"]}),i&&a&&e.jsx("p",{className:"small muted",children:"Source changes are paused while a call or sync preparation is active."}),c&&e.jsx("p",{className:"small muted",role:"status",children:"Updating session sources…"}),a==null?void 0:a.agents.map(w=>{const A=a.sessions.filter(N=>N.agent===w.id);return e.jsxs("section",{className:"agent-source","aria-labelledby":`${w.id}-source-title`,children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h3",{id:`${w.id}-source-title`,children:w.name}),e.jsx("span",{className:"status",children:pt[w.id]})]}),e.jsxs("label",{className:"index-toggle",children:[e.jsx("input",{type:"checkbox",role:"switch","aria-label":`Enable ${w.name} history`,checked:w.enabled,disabled:C,onChange:N=>{const f=N.target.checked;y(()=>zs(w.id,f),{...a,agents:a.agents.map(S=>S.id===w.id?{...S,enabled:f}:S)})}}),e.jsxs("span",{children:[e.jsxs("strong",{children:["Include ",w.name," history"]}),e.jsx("span",{className:"small muted",children:w.enabled?"Enabled for scanning and future syncs":"Off — transcripts are not scanned or indexed"})]})]}),w.roots.map(N=>e.jsxs("div",{children:[e.jsx("p",{className:"small muted",children:N.status==="present"?"Directory found":N.status==="missing"?"Directory not found":"Directory unavailable"}),e.jsx("code",{className:"source-path",children:N.path})]},N.path)),e.jsxs("p",{className:"small muted",children:[A.length," recorded sessions · ",A.filter(N=>N.included).length," selected · ",A.filter(N=>N.missing).length," unavailable at last scan"]}),!A.length&&e.jsxs("p",{className:"small muted",children:["No ",w.name," sessions recorded yet.",w.enabled?" Scan enabled agents to discover them.":" Enable this source before scanning."]}),e.jsx("div",{className:"session-list","aria-label":`Discovered ${w.name} sessions`,children:A.map(N=>e.jsxs("label",{className:"session-source",children:[e.jsx("input",{type:"checkbox",checked:!!N.included,disabled:C||!w.enabled||!!N.missing,"aria-label":`Include ${N.name||"session"} (${N.id})`,onChange:f=>{const S=f.target.checked;y(()=>Us(N.id,S),{...a,sessions:a.sessions.map($=>$.id===N.id?{...$,included:Number(S)}:$)})}}),e.jsxs("span",{children:[e.jsx("strong",{children:N.name||N.cwd.split(/[\\/]/).filter(Boolean).pop()||N.id}),e.jsx("span",{className:"source-cwd",title:N.cwd,children:N.cwd||"Workspace unavailable"}),e.jsxs("span",{className:"small",children:[N.included?"Selected":"Excluded"," · ",N.pending," unreviewed ",N.pending===1?"entry":"entries",N.missing?" · unavailable at last scan":""]}),e.jsxs("span",{className:"source-session-meta small muted",children:["Session ",N.external_id||N.id," · Last recorded change: ",Je(N.modified_at)]}),e.jsx("code",{className:"source-path",children:N.path})]})]},N.id))})]},w.id)}),a&&e.jsxs("p",{className:"small muted",children:[a.history_initialized&&a.history_since?`Existing history baseline: ${Je(a.history_since)}. It is preserved.`:"All indexed history is eligible; there is no rolling time window."," Source choices do not edit existing frozen syncs or mark evidence reviewed. Scanning does not generate summaries or start a call. Keep the original logs: evidence is verified from them, not copied into Draken."]}),l&&e.jsxs("p",{className:"small muted",role:"status",children:["Last requested scan: ",l.files," candidate log files checked · ",l.added," new records recorded."]}),l&&l.warnings.length>0&&e.jsx("ul",{className:"source-warnings small","aria-label":"Scan warnings",children:l.warnings.map((w,A)=>e.jsx("li",{children:w},A))}),(k||m)&&e.jsx("p",{className:"small",role:"alert",children:k||m})]})}function gt(){const[t,s]=o.useState(!1),[n,a]=o.useState(null),[r,i]=o.useState(!1),[d,c]=o.useState(""),u=o.useRef(null);o.useEffect(()=>{var v,m,g;t&&!((v=u.current)!=null&&v.open)?(m=u.current)==null||m.showModal():t||(g=u.current)==null||g.close()},[t]),o.useEffect(()=>{if(!t||r)return;let v=!0;const m=async()=>{try{const l=await Os();v&&(a(l),c(""))}catch(l){v&&c(l instanceof Error?l.message:"Could not read settings")}};m();const g=setInterval(()=>void m(),4e3);return()=>{v=!1,clearInterval(g)}},[t,r]);const k=n&&{off:"Off",waiting:n.pending_records?`${n.pending_records} source changes waiting for a batch`:"Waiting for the next background check",scanning:"Checking session sources",indexing:"Indexing in the background",paused:"Paused for foreground work",stopping:"Stopping background work",error:"Background indexing needs attention"}[n.phase];return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"btn btn-secondary header-settings","aria-haspopup":"dialog",onClick:()=>s(!0),children:[e.jsx(_s,{size:16,"aria-hidden":"true"}),"Settings"]}),e.jsxs("dialog",{ref:u,className:"settings-dialog","aria-labelledby":"settings-title",onCancel:v=>{v.preventDefault(),s(!1)},onClose:v=>{v.currentTarget.open||s(!1)},children:[e.jsxs("div",{className:"section-heading",children:[e.jsx("h2",{id:"settings-title",children:"Settings"}),e.jsx("button",{type:"button",className:"icon-button","aria-label":"Close settings",autoFocus:!0,onClick:()=>s(!1),children:e.jsx(Oe,{size:18,"aria-hidden":"true"})})]}),e.jsxs("label",{className:"index-toggle",children:[e.jsx("input",{type:"checkbox",role:"switch",checked:(n==null?void 0:n.enabled)||!1,disabled:!n||r,onChange:async v=>{const m=v.target.checked,g=n;i(!0),c(""),a(l=>l&&{...l,enabled:m});try{a(await Rs(m))}catch(l){a(g),c(l instanceof Error?l.message:"Could not save settings")}finally{i(!1)}}}),e.jsxs("span",{children:[e.jsx("strong",{children:"Automatically index history"}),e.jsx("span",{className:"small muted",children:"Local background preparation, off by default."})]})]}),e.jsx("p",{className:"small muted",children:"While the server is running, check once a minute and index only when at least 64 changed source records have accumulated. Smaller batches wait until you sync, start a call or search; there is no timed flush. Calls, sync preparation and searches take priority. Newly discovered sessions from enabled agents are selected by default; agent and session exclusions remain respected."}),e.jsx("p",{className:"small muted",children:"This scans text logs and prepares local search embeddings; first use may download the pinned search model. It does not create or change frozen syncs, mark anything reviewed, use your microphone, or run summary models. The final aggregation still runs when you click Sync with Draken."}),n&&e.jsxs("p",{className:"small muted",role:"status",children:[r?"Saving…":k,n.last_completed_at&&` · Last completed batch: ${new Date(n.last_completed_at).toLocaleString()}`]}),(d||(n==null?void 0:n.error))&&e.jsx("p",{className:"small",role:"alert",children:d||(n==null?void 0:n.error)}),e.jsx(ve,{enabled:t&&(n==null?void 0:n.phase)==="indexing",backgroundOnly:!0}),e.jsx(mt,{open:t}),e.jsx(ns,{active:t,always:!0})]})]})}function ft(){const{isAuthenticated:t,isLoading:s,authEnabled:n,username:a,logout:r}=es(),[i,d]=o.useState(window.location.pathname),[c,u]=o.useState(null),k=o.useRef(null),v=o.useRef(i),m=o.useCallback(j=>{k.current=j},[]),g=o.useCallback((j,I=!1)=>{k.current&&!k.current()||(window.history.pushState(null,"",j),v.current=j,d(j),u(I?Number(j.split("/").pop()):null),window.scrollTo(0,0))},[]);if(o.useEffect(()=>{const j=()=>{if(k.current&&!k.current()){window.history.pushState(null,"",v.current);return}v.current=window.location.pathname,d(v.current),u(null)};return window.addEventListener("popstate",j),()=>window.removeEventListener("popstate",j)},[]),s)return e.jsxs("div",{className:"app-loading",children:[e.jsx("span",{className:"spinner"}),"Opening Draken…"]});if(!t)return e.jsx(Ls,{});const l=/^\/syncs\/([1-9]\d*)\/?$/.exec(i),x=l?Number(l[1]):null;return e.jsxs("div",{className:"app-container",children:[e.jsxs("header",{className:"header",children:[e.jsxs("a",{className:"brand",href:"/",onClick:j=>ie(j,g,"/"),"aria-label":"Draken sync history",children:[e.jsx("img",{src:"/favicon.png",alt:""}),e.jsxs("div",{children:[e.jsx("strong",{children:"Draken"}),e.jsx("span",{children:"Session sync"})]})]}),e.jsxs("div",{className:"header-right",children:[e.jsx("a",{href:"/history",onClick:j=>ie(j,g,"/history"),children:"Search history"}),e.jsx(gt,{}),n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"muted small",children:a}),e.jsx("button",{className:"icon-button",onClick:()=>{(!k.current||k.current())&&r()},"aria-label":"Sign out",children:e.jsx(Cs,{size:18})})]})]})]}),x&&Number.isSafeInteger(x)?e.jsx(ut,{id:x,callIntent:c===x,consumeIntent:()=>u(null),navigate:g,setGuard:m},x):/^\/history(?:\/H[a-f0-9]{24})?\/?$/.test(i)?e.jsx(it,{navigate:g,reference:i.split("/")[2]},i):i==="/"?e.jsx(tt,{navigate:g}):e.jsxs("main",{className:"sync-home",children:[e.jsx("h1",{children:"Page not found"}),e.jsx("a",{href:"/",onClick:j=>ie(j,g,"/"),children:"All syncs"})]})]})}function xt(){return e.jsx(Ds,{children:e.jsx(ft,{})})}hs.createRoot(document.getElementById("root")).render(e.jsx(us.StrictMode,{children:e.jsx(xt,{})}));
|
|
File without changes
|