diff --git a/docs/MCP.md b/docs/MCP.md index 448e9fa7b8..0322670792 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -131,3 +131,9 @@ They use the same list and the same per-provider config as Settings. Part 2 (`SKIP_REAL=1` runs it alone) imports from a sample `~/.codex/config.toml` and `~/.claude.json`. - **Screenshots:** `scripts/desktop-mcp-shot.sh` (desktop, `THEME=dark|light`), `test/e2e/ios/mcp-shot.sh`, and the Android shot script. + +## Project MCP discovery follow-up + +The thread’s Context & Prompt inspector reviews project MCP commands and URLs before enabling their configuration. Approval applies to the file’s exact bytes at its reviewed checkout path. Changes take effect at the next provider launch. + +Grok, Muse, and Antigravity can also discover project MCP files directly. Backplane refuses launches when it detects a conflicting native configuration in those runtimes. Standalone Antigravity also lacks a verified way to pass Backplane’s approved list. Follow-up work is to suppress native discovery per launch, pass the approved list explicitly, and verify both behaviors against each supported CLI with a harmless stand-in MCP server. diff --git a/i18n/en.msg b/i18n/en.msg index 7ffc0c3d51..583b36e243 100644 --- a/i18n/en.msg +++ b/i18n/en.msg @@ -4910,3 +4910,33 @@ web.composer.voice = Voice dictation web.composer.unsupported = Unsupported image type: {type} web.composer.maximages = At most {max} images per message. web.logout.failed = Could not confirm sign-out. Try again. + +# ---- thread-context: inspector ---- +thread.context.title = Context & Prompt +thread.context.instructions = Instructions +thread.context.system = System Prompt +thread.context.skills = Skills +thread.context.mcp = Project MCPs +thread.context.mcp.short = MCPs +thread.context.reading = Reading thread context… +thread.context.none.instructions = No project instructions found. +thread.context.none.mcp = No project MCP configurations found. +thread.context.native.note = Backplane’s launch prompt. Native files are loaded by the provider. +thread.context.copy = Copy prompt +thread.context.copied = Prompt copied. +thread.context.base = Backplane +thread.context.injected.label = Injected project instructions +thread.context.index = Available skills index +thread.context.scope.user = User +thread.context.scope.bundled = Bundled +thread.context.native = Native +thread.context.injected = Injected +thread.context.cross = Cross-provider +thread.context.explicit = Explicit invocation +thread.context.untrusted = Untrusted +thread.context.invalid = Invalid +thread.context.trust = Trust and enable +thread.context.enable = Enable +thread.context.disable = Disable +thread.context.size = {bytes} B · ≈{tokens} tokens +thread.context.unreachable = Could not reach the hub. diff --git a/i18n/es.msg b/i18n/es.msg index 6e6f43a231..0213b38c45 100644 --- a/i18n/es.msg +++ b/i18n/es.msg @@ -4910,3 +4910,33 @@ web.composer.voice = Dictado por voz web.composer.unsupported = Tipo de imagen no compatible: {type} web.composer.maximages = Como máximo {max} imágenes por mensaje. web.logout.failed = No se pudo confirmar el cierre de sesión. Inténtalo de nuevo. + +# ---- thread-context: inspector ---- +thread.context.title = Contexto e instrucciones +thread.context.instructions = Instrucciones +thread.context.system = Instrucciones del sistema +thread.context.skills = Habilidades +thread.context.mcp = MCP del proyecto +thread.context.mcp.short = MCP +thread.context.reading = Leyendo el contexto del hilo… +thread.context.none.instructions = No se encontraron instrucciones del proyecto. +thread.context.none.mcp = No se encontraron configuraciones MCP del proyecto. +thread.context.native.note = Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos. +thread.context.copy = Copiar instrucciones +thread.context.copied = Se copiaron las instrucciones. +thread.context.base = Backplane +thread.context.injected.label = Instrucciones del proyecto añadidas +thread.context.index = Índice de habilidades disponibles +thread.context.scope.user = Usuario +thread.context.scope.bundled = Incluidas +thread.context.native = Nativo +thread.context.injected = Añadido +thread.context.cross = Entre proveedores +thread.context.explicit = Invocación explícita +thread.context.untrusted = Sin aprobar +thread.context.invalid = No válido +thread.context.trust = Confiar y activar +thread.context.enable = Activar +thread.context.disable = Desactivar +thread.context.size = {bytes} B · ≈{tokens} tokens +thread.context.unreachable = No se pudo conectar con el hub. diff --git a/i18n/ja.msg b/i18n/ja.msg index c6c05a04a1..cfce51ed33 100644 --- a/i18n/ja.msg +++ b/i18n/ja.msg @@ -4933,3 +4933,33 @@ web.composer.voice = 音声入力 web.composer.unsupported = 未対応の画像形式です: {type} web.composer.maximages = 1 件のメッセージに添付できる画像は最大 {max} 枚です。 web.logout.failed = サインアウトを確認できませんでした。もう一度お試しください。 + +# ---- thread-context: inspector ---- +thread.context.title = コンテキストとプロンプト +thread.context.instructions = 指示 +thread.context.system = システムプロンプト +thread.context.skills = スキル +thread.context.mcp = プロジェクトの MCP +thread.context.mcp.short = MCP +thread.context.reading = スレッドのコンテキストを読み込み中… +thread.context.none.instructions = プロジェクトの指示が見つかりません。 +thread.context.none.mcp = プロジェクトの MCP 設定が見つかりません。 +thread.context.native.note = Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。 +thread.context.copy = プロンプトをコピー +thread.context.copied = プロンプトをコピーしました。 +thread.context.base = Backplane +thread.context.injected.label = 追加されたプロジェクトの指示 +thread.context.index = 利用可能なスキルの一覧 +thread.context.scope.user = ユーザー +thread.context.scope.bundled = 同梱 +thread.context.native = ネイティブ +thread.context.injected = 追加済み +thread.context.cross = プロバイダー共通 +thread.context.explicit = 明示的な呼び出し +thread.context.untrusted = 未承認 +thread.context.invalid = 無効 +thread.context.trust = 承認して有効にする +thread.context.enable = 有効にする +thread.context.disable = 無効にする +thread.context.size = {bytes} B・約{tokens}トークン +thread.context.unreachable = ハブに接続できませんでした。 diff --git a/i18n/native.keys b/i18n/native.keys index 4a4a7db2f3..d44a43f276 100644 --- a/i18n/native.keys +++ b/i18n/native.keys @@ -373,3 +373,4 @@ reply.action reply.cancel reply.replying reply.to +thread.context.size diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataExtras.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataExtras.kt index aee8ca0768..4f02940973 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataExtras.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataExtras.kt @@ -96,7 +96,11 @@ fun threadActions(t: DThread, rename: () -> Unit, confirmDelete: () -> Unit, sea fun ThreadMenus(t: DThread, shown: Boolean, close: () -> Unit, deleted: () -> Unit = {}, search: (() -> Unit)? = null, buy: Pair Unit>? = null) { var renaming by remember(t.id) { mutableStateOf(false) } var deleting by remember(t.id) { mutableStateOf(false) } - if (shown) ActionSheet(t.title, threadActions(t, { renaming = true }, { deleting = true }, search, buy), close) + var contextOpen by remember(t.id) { mutableStateOf(false) } + val contextAction: List Unit>> = + if (DataClient.has("threadContext")) listOf("Context & Prompt" to { contextOpen = true }) else emptyList() + if (shown) ActionSheet(t.title, contextAction + threadActions(t, { renaming = true }, { deleting = true }, search, buy), close) + if (contextOpen) ThreadContextSheet(t.id) { contextOpen = false } if (renaming) TextPrompt(Msg.android_thread_rename, t.title, Msg.menu_rename, { renaming = false }) { DataClient.threadAct(t.id, "rename", it) } if (deleting) ActionSheet(Msg.android_thread_delete_ask(t.title), listOf("Delete thread" to { DataClient.threadAct(t.id, "delete"); deleted() }, "Keep it" to {}), { deleting = false }) } diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt index 182ce8a99b..e35d19bcaf 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/Msg.kt @@ -4811,6 +4811,34 @@ object Msg { "web.composer.unsupported", "web.composer.maximages", "web.logout.failed", + "thread.context.title", + "thread.context.instructions", + "thread.context.system", + "thread.context.skills", + "thread.context.mcp", + "thread.context.mcp.short", + "thread.context.reading", + "thread.context.none.instructions", + "thread.context.none.mcp", + "thread.context.native.note", + "thread.context.copy", + "thread.context.copied", + "thread.context.base", + "thread.context.injected.label", + "thread.context.index", + "thread.context.scope.user", + "thread.context.scope.bundled", + "thread.context.native", + "thread.context.injected", + "thread.context.cross", + "thread.context.explicit", + "thread.context.untrusted", + "thread.context.invalid", + "thread.context.trust", + "thread.context.enable", + "thread.context.disable", + "thread.context.size", + "thread.context.unreachable", ) internal val keys: Array by lazy { arrayOf(*keys0(), *keys1(), *keys2(), *keys3(), *keys4(), *keys5(), *keys6(), *keys7(), *keys8(), *keys9(), *keys10(), *keys11(), *keys12(), *keys13(), *keys14(), *keys15(), *keys16(), *keys17(), *keys18(), *keys19()) } private fun en0(): Array = arrayOf( @@ -9621,6 +9649,34 @@ object Msg { "Unsupported image type: {type}", "At most {max} images per message.", "Could not confirm sign-out. Try again.", + "Context & Prompt", + "Instructions", + "System Prompt", + "Skills", + "Project MCPs", + "MCPs", + "Reading thread context…", + "No project instructions found.", + "No project MCP configurations found.", + "Backplane’s launch prompt. Native files are loaded by the provider.", + "Copy prompt", + "Prompt copied.", + "Backplane", + "Injected project instructions", + "Available skills index", + "User", + "Bundled", + "Native", + "Injected", + "Cross-provider", + "Explicit invocation", + "Untrusted", + "Invalid", + "Trust and enable", + "Enable", + "Disable", + "{bytes} B · ≈{tokens} tokens", + "Could not reach the hub.", ) internal val en: Array by lazy { arrayOf(*en0(), *en1(), *en2(), *en3(), *en4(), *en5(), *en6(), *en7(), *en8(), *en9(), *en10(), *en11(), *en12(), *en13(), *en14(), *en15(), *en16(), *en17(), *en18(), *en19()) } private fun ja0(): Array = arrayOf( @@ -14431,6 +14487,34 @@ object Msg { "未対応の画像形式です: {type}", "1 件のメッセージに添付できる画像は最大 {max} 枚です。", "サインアウトを確認できませんでした。もう一度お試しください。", + "コンテキストとプロンプト", + "指示", + "システムプロンプト", + "スキル", + "プロジェクトの MCP", + "MCP", + "スレッドのコンテキストを読み込み中…", + "プロジェクトの指示が見つかりません。", + "プロジェクトの MCP 設定が見つかりません。", + "Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。", + "プロンプトをコピー", + "プロンプトをコピーしました。", + "Backplane", + "追加されたプロジェクトの指示", + "利用可能なスキルの一覧", + "ユーザー", + "同梱", + "ネイティブ", + "追加済み", + "プロバイダー共通", + "明示的な呼び出し", + "未承認", + "無効", + "承認して有効にする", + "有効にする", + "無効にする", + "{bytes} B・約{tokens}トークン", + "ハブに接続できませんでした。", ) internal val ja: Array by lazy { arrayOf(*ja0(), *ja1(), *ja2(), *ja3(), *ja4(), *ja5(), *ja6(), *ja7(), *ja8(), *ja9(), *ja10(), *ja11(), *ja12(), *ja13(), *ja14(), *ja15(), *ja16(), *ja17(), *ja18(), *ja19()) } private fun es0(): Array = arrayOf( @@ -19241,6 +19325,34 @@ object Msg { "Tipo de imagen no compatible: {type}", "Como máximo {max} imágenes por mensaje.", "No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.", + "Contexto e instrucciones", + "Instrucciones", + "Instrucciones del sistema", + "Habilidades", + "MCP del proyecto", + "MCP", + "Leyendo el contexto del hilo…", + "No se encontraron instrucciones del proyecto.", + "No se encontraron configuraciones MCP del proyecto.", + "Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.", + "Copiar instrucciones", + "Se copiaron las instrucciones.", + "Backplane", + "Instrucciones del proyecto añadidas", + "Índice de habilidades disponibles", + "Usuario", + "Incluidas", + "Nativo", + "Añadido", + "Entre proveedores", + "Invocación explícita", + "Sin aprobar", + "No válido", + "Confiar y activar", + "Activar", + "Desactivar", + "{bytes} B · ≈{tokens} tokens", + "No se pudo conectar con el hub.", ) internal val es: Array by lazy { arrayOf(*es0(), *es1(), *es2(), *es3(), *es4(), *es5(), *es6(), *es7(), *es8(), *es9(), *es10(), *es11(), *es12(), *es13(), *es14(), *es15(), *es16(), *es17(), *es18(), *es19()) } private fun exactText0(): Array = arrayOf( @@ -22535,11 +22647,38 @@ object Msg { "Attach image", "Voice dictation", "Could not confirm sign-out. Try again.", + "Context & Prompt", + "Instructions", + "System Prompt", + "Skills", + "Project MCPs", + "MCPs", + "Reading thread context…", + "No project instructions found.", + "No project MCP configurations found.", + "Backplane’s launch prompt. Native files are loaded by the provider.", + "Copy prompt", + "Prompt copied.", + "Backplane", + "Injected project instructions", + "Available skills index", + "User", + "Bundled", + "Native", + "Injected", + "Cross-provider", + "Explicit invocation", + "Untrusted", + "Invalid", + "Trust and enable", + "Enable", + "Disable", + "Could not reach the hub.", ) internal val exactText: Array by lazy { arrayOf(*exactText0(), *exactText1(), *exactText2(), *exactText3(), *exactText4(), *exactText5(), *exactText6(), *exactText7(), *exactText8(), *exactText9(), *exactText10(), *exactText11(), *exactText12(), *exactText13()) } - internal val exactKey: IntArray by lazy { intArrayOf(0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3123, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 3691, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3730, 87, 88, 98, 99, 3052, 3729, 102, 103, 105, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 159, 161, 162, 163, 3172, 165, 166, 3174, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3133, 183, 187, 189, 193, 194, 195, 197, 198, 199, 200, 201, 202, 206, 209, 213, 215, 216, 217, 219, 220, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 234, 235, 2939, 237, 238, 239, 240, 3690, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 260, 262, 263, 264, 265, 266, 267, 270, 271, 272, 273, 275, 279, 280, 281, 282, 286, 287, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 301, 3144, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3738, 336, 3737, 3740, 340, 3750, 342, 343, 344, 345, 354, 3121, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2942, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 2934, 2935, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3151, 457, 458, 459, 460, 461, 2924, 463, 464, 465, 3054, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 556, 557, 558, 559, 560, 561, 562, 563, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 592, 628, 629, 630, 3159, 3160, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3803, 654, 656, 657, 659, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 680, 681, 682, 683, 684, 686, 687, 689, 690, 692, 693, 694, 695, 698, 704, 724, 728, 729, 730, 731, 732, 3735, 734, 735, 736, 737, 3158, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 3718, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 843, 844, 845, 847, 848, 3154, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3728, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 3805, 903, 904, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 3124, 964, 965, 966, 967, 968, 969, 3753, 971, 2979, 3036, 974, 975, 976, 978, 979, 987, 988, 989, 991, 992, 993, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 3756, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2931, 3005, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1045, 1046, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1074, 1082, 1083, 1086, 1087, 1088, 1090, 1091, 1092, 3770, 1094, 1095, 1098, 1099, 1100, 3153, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3755, 1120, 1123, 1124, 1125, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1150, 1151, 1152, 1153, 1154, 1155, 1158, 1162, 1163, 1165, 1170, 1171, 1172, 1173, 1176, 1178, 1180, 1181, 1182, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1220, 1222, 1223, 2933, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1240, 1241, 1244, 1245, 1246, 1247, 1248, 1250, 1253, 1254, 1255, 1256, 1257, 1258, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1277, 1278, 1279, 1280, 1281, 1288, 1289, 1290, 1291, 1294, 1296, 1297, 1298, 1299, 1301, 1305, 1306, 1308, 1309, 1310, 1311, 1315, 1316, 1318, 1319, 1320, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1335, 1338, 1339, 1340, 1341, 1344, 1347, 1348, 1355, 1356, 3009, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 2936, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 3053, 3546, 1407, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 3548, 1444, 1445, 1446, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1464, 1465, 3693, 1467, 1468, 1469, 3705, 3711, 1472, 1473, 1474, 1475, 1476, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1494, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1539, 1540, 1541, 1542, 1544, 1545, 1546, 1547, 1548, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 3012, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1616, 1617, 1618, 1619, 1620, 1621, 1622, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 3422, 1636, 1637, 1638, 1639, 3423, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 2945, 1658, 1660, 1662, 1664, 1668, 1672, 1678, 1680, 1681, 1682, 1684, 1685, 1686, 1687, 1688, 1689, 1691, 1693, 1694, 1695, 1696, 1697, 1699, 1700, 3717, 1702, 1703, 1704, 1705, 1706, 1707, 1708, 1710, 1711, 1713, 1714, 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725, 1726, 1727, 1728, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1792, 1793, 2988, 1802, 1804, 1808, 2970, 1810, 1811, 2971, 1813, 1814, 1818, 3035, 1820, 1821, 1822, 1823, 1824, 1825, 1826, 1827, 1828, 1830, 1835, 1837, 1838, 1839, 1840, 1841, 1842, 3050, 1844, 1845, 1848, 1849, 1859, 1860, 1864, 1865, 1866, 1867, 1868, 1869, 1870, 1871, 1873, 1874, 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1908, 1909, 1911, 1912, 1922, 1924, 1925, 1928, 1929, 1932, 1933, 1934, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950, 1951, 1952, 1954, 1960, 1961, 1962, 1963, 1967, 3111, 1973, 1974, 1976, 1977, 1978, 1979, 3763, 3764, 1988, 1990, 1991, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2005, 2006, 2008, 2009, 2012, 2013, 3096, 3097, 3098, 2021, 3324, 2023, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2040, 2041, 2042, 2043, 2044, 2045, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2078, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 3038, 2096, 2097, 2098, 2100, 2102, 2103, 2104, 2105, 2961, 3086, 3087, 3088, 3089, 3090, 2112, 2113, 2114, 2116, 2963, 2964, 2954, 2953, 2122, 2955, 2124, 2959, 2126, 3322, 2131, 2135, 2137, 2138, 2139, 2140, 2141, 2142, 2143, 2144, 2145, 2146, 2147, 2989, 2151, 2152, 2153, 2154, 3022, 2156, 2157, 2158, 2159, 2160, 2161, 2162, 2163, 2164, 2167, 3335, 2169, 2170, 2171, 2172, 3004, 2174, 2175, 2176, 2177, 2952, 2179, 3067, 2182, 2186, 2187, 3612, 2189, 2190, 3699, 3700, 2194, 3149, 2197, 3688, 2200, 2201, 2202, 2203, 2204, 3748, 2206, 3119, 2208, 3118, 2210, 2212, 2214, 2215, 2216, 2220, 2223, 2225, 2227, 2228, 2229, 2230, 2231, 2232, 2233, 2234, 2235, 2236, 2237, 2239, 2240, 2241, 3706, 2243, 2244, 2246, 2996, 2994, 2998, 2252, 2254, 2255, 2261, 2262, 2263, 2264, 3034, 2269, 2270, 2272, 2277, 2278, 2978, 3547, 2941, 2940, 2943, 3063, 3066, 2291, 2292, 2294, 2295, 2297, 2298, 2299, 2300, 2301, 2302, 2303, 2304, 2305, 3767, 2309, 2310, 2311, 2312, 2313, 2314, 2315, 2316, 2317, 2318, 2319, 2320, 2321, 2322, 2323, 2328, 2330, 2331, 2332, 2336, 2337, 2340, 2341, 2348, 2349, 2350, 2351, 2352, 2353, 2354, 2355, 2356, 2357, 2358, 2359, 2360, 2362, 2363, 2364, 2365, 2366, 2367, 2389, 2390, 2393, 2394, 2395, 2396, 2397, 2398, 2399, 2409, 2413, 2414, 2415, 2416, 2417, 2418, 2419, 2420, 2421, 2423, 2424, 2425, 2426, 2428, 2429, 2430, 2432, 2435, 2436, 2437, 2440, 2441, 2442, 2443, 2444, 2445, 2446, 2447, 2453, 2454, 2455, 2456, 2457, 2458, 2459, 2460, 2461, 2462, 2463, 2464, 2465, 2466, 2467, 2468, 2469, 2470, 2471, 2472, 2473, 2474, 2475, 2477, 2478, 2479, 2480, 2481, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2500, 2501, 2502, 2503, 3100, 2505, 2507, 2508, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2519, 2520, 2521, 2522, 2525, 2526, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2541, 2542, 2543, 2544, 2547, 2548, 2549, 2550, 2551, 2552, 2553, 2554, 2555, 2557, 2558, 2559, 2560, 2561, 2562, 2563, 2564, 2565, 2568, 2570, 2571, 2574, 2575, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2584, 2585, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2595, 2596, 2597, 2599, 2601, 2604, 2606, 3696, 2611, 2612, 2613, 2614, 2615, 2616, 2617, 2621, 2622, 2624, 2625, 2626, 2627, 2628, 2629, 2630, 2632, 2633, 2634, 2639, 2640, 2641, 2643, 2644, 2645, 2646, 2648, 2649, 2650, 2651, 2652, 2653, 2654, 2655, 2656, 2657, 2658, 2659, 2660, 3669, 2662, 2663, 2665, 3666, 2667, 2668, 3670, 3667, 2680, 2684, 3677, 3173, 3678, 2688, 3679, 2690, 2692, 3681, 2694, 3682, 2696, 2698, 3686, 3664, 3657, 3665, 2717, 2718, 2720, 2721, 2731, 2732, 2734, 2735, 2736, 2737, 2738, 2739, 2740, 2741, 2742, 2746, 2749, 2752, 2754, 2756, 2762, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2772, 2773, 2774, 3344, 2776, 2777, 2778, 2779, 2780, 2782, 2784, 2785, 3376, 2791, 2792, 2793, 2794, 2795, 2796, 2797, 2798, 2799, 2800, 2801, 2802, 2804, 2805, 2806, 2807, 2810, 2811, 2813, 2814, 2815, 2816, 2968, 2818, 2820, 2821, 2823, 2824, 2825, 2826, 2827, 2829, 2830, 2834, 2837, 2838, 2839, 2841, 2842, 2843, 2845, 2846, 2847, 2848, 2850, 2851, 2854, 2857, 2858, 2859, 2860, 2861, 2863, 2865, 2866, 2868, 2869, 2870, 2871, 2872, 2873, 2874, 2875, 2877, 2878, 2879, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2887, 2888, 2889, 2890, 2891, 2892, 2893, 2894, 2895, 2896, 2902, 2903, 2904, 2906, 2907, 2908, 2912, 2913, 2914, 2915, 2916, 2920, 2921, 2925, 2926, 2927, 2928, 2929, 2930, 2932, 2937, 2938, 2944, 2949, 2951, 2956, 2957, 2958, 2960, 2962, 2965, 2966, 2967, 2969, 2973, 2980, 2981, 2982, 2983, 2984, 2985, 2986, 2987, 2990, 2991, 2992, 2993, 2997, 2999, 3000, 3001, 3002, 3006, 3007, 3011, 3013, 3014, 3015, 3017, 3018, 3019, 3020, 3021, 3024, 3025, 3026, 3027, 3028, 3029, 3030, 3031, 3032, 3039, 3040, 3041, 3042, 3047, 3048, 3049, 3051, 3055, 3056, 3057, 3058, 3059, 3062, 3064, 3065, 3068, 3069, 3070, 3071, 3072, 3073, 3074, 3075, 3076, 3078, 3080, 3081, 3082, 3083, 3084, 3085, 3091, 3092, 3093, 3094, 3095, 3099, 3101, 3102, 3103, 3104, 3105, 3106, 3107, 3109, 3110, 3113, 3115, 3116, 3117, 3120, 3125, 3126, 3127, 3129, 3132, 3134, 3135, 3137, 3138, 3139, 3141, 3142, 3143, 3145, 3146, 3147, 3148, 3152, 3157, 3162, 3163, 3164, 3165, 3166, 3167, 3168, 3170, 3175, 3176, 3177, 3178, 3179, 3180, 3181, 3182, 3183, 3184, 3185, 3186, 3187, 3190, 3191, 3194, 3195, 3196, 3197, 3198, 3199, 3200, 3201, 3204, 3205, 3206, 3207, 3208, 3209, 3210, 3211, 3212, 3213, 3214, 3217, 3218, 3220, 3221, 3222, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3230, 3231, 3232, 3233, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3244, 3245, 3246, 3249, 3250, 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3276, 3277, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3287, 3288, 3289, 3290, 3291, 3292, 3295, 3296, 3297, 3298, 3299, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3318, 3319, 3323, 3325, 3326, 3327, 3329, 3330, 3331, 3334, 3336, 3337, 3338, 3339, 3340, 3343, 3345, 3348, 3350, 3351, 3356, 3357, 3358, 3359, 3362, 3369, 3370, 3371, 3372, 3373, 3374, 3377, 3378, 3379, 3380, 3383, 3384, 3385, 3386, 3387, 3388, 3389, 3390, 3391, 3392, 3394, 3395, 3396, 3397, 3398, 3399, 3401, 3402, 3404, 3405, 3406, 3407, 3408, 3414, 3415, 3416, 3417, 3418, 3419, 3420, 3421, 3424, 3427, 3430, 3431, 3432, 3433, 3434, 3435, 3436, 3437, 3438, 3439, 3440, 3441, 3442, 3443, 3444, 3445, 3446, 3447, 3448, 3450, 3451, 3452, 3453, 3454, 3455, 3456, 3458, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3467, 3468, 3472, 3478, 3480, 3481, 3482, 3483, 3484, 3485, 3486, 3487, 3488, 3489, 3490, 3491, 3492, 3493, 3494, 3496, 3497, 3498, 3499, 3500, 3501, 3505, 3506, 3510, 3511, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3524, 3525, 3527, 3528, 3529, 3530, 3533, 3534, 3535, 3536, 3537, 3549, 3550, 3551, 3552, 3553, 3554, 3555, 3556, 3557, 3558, 3559, 3560, 3561, 3562, 3563, 3564, 3565, 3566, 3568, 3569, 3570, 3574, 3575, 3576, 3577, 3583, 3584, 3585, 3586, 3590, 3592, 3593, 3594, 3596, 3599, 3600, 3604, 3611, 3613, 3616, 3618, 3619, 3620, 3621, 3622, 3623, 3625, 3626, 3627, 3628, 3629, 3630, 3631, 3632, 3633, 3634, 3635, 3636, 3637, 3638, 3639, 3640, 3641, 3642, 3643, 3644, 3645, 3646, 3647, 3648, 3649, 3650, 3651, 3652, 3653, 3654, 3655, 3656, 3674, 3689, 3692, 3694, 3695, 3697, 3701, 3703, 3707, 3716, 3719, 3720, 3721, 3722, 3723, 3724, 3726, 3732, 3733, 3736, 3739, 3741, 3742, 3743, 3744, 3745, 3746, 3749, 3752, 3754, 3758, 3759, 3760, 3761, 3762, 3765, 3766, 3768, 3769, 3771, 3772, 3773, 3774, 3775, 3776, 3777, 3778, 3780, 3781, 3782, 3783, 3784, 3785, 3786, 3787, 3788, 3789, 3790, 3791, 3792, 3793, 3794, 3795, 3796, 3797, 3800, 3802, 3804, 3813, 3814, 3816, 3817, 3826, 3832, 3838, 3847, 3849, 3850, 3851, 3852, 3855, 3856, 3858, 3864, 3868, 3872, 3877, 3878, 3880, 3881, 3882, 3884, 3885, 3886, 3891, 3892, 3893, 3894, 3895, 3896, 3897, 3898, 3899, 3902, 3903, 3904, 3949, 3950, 3955, 3957, 3958, 3960, 3966, 3969, 3984, 3985, 3986, 3987, 3988, 3989, 3991, 3992, 3994, 3995, 3997, 3999, 4000, 4013, 4016, 4017, 4019, 4020, 4024, 4029, 4032, 4033, 4035, 4036, 4042, 4044, 4045, 4048, 4050, 4055, 4056, 4057, 4062, 4073, 4096, 4112, 4120, 4129, 4130, 4134, 4139, 4155, 4156, 4157, 4158, 4160, 4162, 4163, 4165, 4168, 4172, 4175, 4178, 4179, 4180, 4181, 4185, 4186, 4187, 4188, 4191, 4192, 4193, 4194, 4195, 4196, 4197, 4198, 4199, 4200, 4201, 4202, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4210, 4211, 4212, 4213, 4214, 4222, 4225, 4226, 4232, 4237, 4238, 4239, 4240, 4244, 4248, 4250, 4251, 4252, 4253, 4254, 4255, 4256, 4257, 4259, 4260, 4261, 4262, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4280, 4292, 4293, 4295, 4296, 4297, 4298, 4302, 4303, 4304, 4305, 4306, 4307, 4309, 4310, 4311, 4317, 4318, 4319, 4320, 4321, 4322, 4326, 4330, 4331, 4333, 4334, 4335, 4336, 4337, 4339, 4349, 4351, 4356, 4357, 4358, 4359, 4360, 4361, 4362, 4363, 4364, 4365, 4366, 4367, 4368, 4369, 4370, 4371, 4373, 4374, 4375, 4376, 4377, 4378, 4379, 4384, 4387, 4388, 4389, 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397, 4398, 4399, 4400, 4401, 4402, 4403, 4404, 4405, 4406, 4407, 4409, 4410, 4411, 4413, 4414, 4415, 4416, 4419, 4420, 4421, 4423, 4424, 4425, 4427, 4428, 4429, 4430, 4431, 4432, 4434, 4436, 4439, 4440, 4441, 4442, 4444, 4445, 4446, 4447, 4448, 4449, 4450, 4451, 4452, 4453, 4454, 4458, 4460, 4461, 4462, 4463, 4464, 4468, 4469, 4473, 4474, 4475, 4477, 4479, 4480, 4481, 4482, 4483, 4484, 4485, 4487, 4488, 4489, 4490, 4491, 4492, 4493, 4500, 4501, 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4517, 4518, 4520, 4521, 4522, 4523, 4524, 4525, 4526, 4527, 4528, 4529, 4530, 4531, 4532, 4533, 4534, 4535, 4539, 4540, 4541, 4542, 4543, 4544, 4545, 4546, 4547, 4552, 4553, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4565, 4566, 4567, 4568, 4569, 4571, 4572, 4573, 4574, 4583, 4584, 4585, 4586, 4587, 4588, 4590, 4593, 4594, 4595, 4597, 4598, 4599, 4600, 4601, 4602, 4603, 4604, 4605, 4606, 4607, 4608, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, 4619, 4620, 4621, 4622, 4623, 4624, 4625, 4626, 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642, 4643, 4644, 4645, 4646, 4647, 4648, 4649, 4650, 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4703, 4704, 4705, 4711, 4724, 4728, 4729, 4730, 4731, 4732, 4733, 4734, 4735, 4736, 4737, 4738, 4739, 4740, 4741, 4742, 4743, 4745, 4746, 4747, 4748, 4749, 4751, 4752, 4753, 4754, 4755, 4756, 4757, 4760, 4761, 4763, 4764, 4765, 4768) } - internal val templates: IntArray by lazy { intArrayOf(2329, 2808, 2620, 2619, 2618, 2840, 2862, 3342, 2583, 418, 2753, 2751, 2647, 2338, 2344, 2755, 2852, 2567, 2566, 285, 2296, 2757, 2864, 3192, 4144, 2506, 2556, 2016, 2334, 3676, 2081, 2683, 2339, 3193, 1336, 4164, 4184, 3675, 2524, 2681, 1833, 4159, 2092, 2130, 2136, 4513, 283, 2082, 4455, 3354, 3375, 2039, 2307, 3672, 452, 2715, 2747, 2748, 3355, 3671, 2716, 3603, 609, 1677, 3680, 1834, 2691, 3683, 2697, 3346, 616, 617, 2733, 3044, 3658, 1625, 2750, 3602, 303, 614, 69, 711, 621, 2306, 4182, 1121, 2448, 3425, 3798, 1242, 2165, 2535, 3347, 2128, 3687, 714, 1729, 1930, 2703, 2712, 2923, 4189, 3349, 3361, 136, 594, 596, 2523, 2678, 1831, 4177, 2995, 610, 2249, 2546, 3835, 1302, 4176, 3471, 3608, 3609, 158, 2046, 2048, 2083, 2803, 4312, 2134, 2333, 2476, 3597, 214, 284, 1276, 1980, 4744, 3466, 3475, 3476, 67, 83, 218, 619, 4549, 3495, 4271, 3320, 3685, 726, 1023, 2347, 2439, 2701, 4314, 89, 2346, 2361, 2876, 624, 1623, 1920, 2790, 4443, 3368, 1543, 2067, 2253, 2537, 4495, 3363, 3429, 3479, 650, 1854, 3890, 3128, 3470, 3516, 3580, 3799, 1317, 1832, 2011, 2385, 2672, 3818, 4514, 3382, 3428, 1807, 1829, 3317, 593, 1292, 1346, 1919, 3457, 3659, 221, 1667, 2704, 2901, 3046, 3114, 3403, 258, 591, 1026, 1931, 1955, 4097, 3400, 3526, 655, 1342, 1683, 2017, 3122, 3321, 3582, 3601, 710, 1283, 1353, 1624, 1698, 1861, 2335, 2438, 2536, 3905, 4183, 4380, 3381, 3449, 3595, 649, 699, 1044, 2572, 3140, 3259, 3662, 108, 184, 606, 721, 1081, 1935, 2015, 2077, 2132, 2371, 2452, 2708, 2744, 2788, 3910, 4426, 4767, 3341, 3412, 3573, 160, 623, 701, 1332, 1333, 1345, 1491, 1626, 2129, 2133, 2226, 2370, 2598, 4152, 4456, 3077, 3169, 3216, 3294, 3508, 3663, 3673, 703, 1183, 1538, 1863, 2221, 2224, 2451, 2709, 2729, 2730, 2898, 2899, 3920, 3940, 4173, 4417, 4750, 4766, 3581, 3598, 3704, 1463, 1550, 1669, 1921, 2391, 2403, 2728, 4116, 4174, 4457, 4548, 3043, 3045, 3060, 3578, 3591, 3757, 723, 1024, 1798, 2101, 2166, 2381, 2724, 2725, 3925, 4171, 4247, 4258, 3247, 3367, 91, 93, 595, 715, 1027, 1350, 1986, 2293, 2386, 2671, 2723, 2727, 3887, 4496, 2974, 2975, 3477, 3541, 3684, 94, 1251, 1259, 1490, 1549, 1846, 2149, 2181, 2431, 2449, 2699, 3827, 3828, 4170, 4323, 4386, 3293, 3332, 3333, 3411, 3567, 299, 599, 618, 700, 1109, 1117, 1175, 1489, 1592, 1914, 2093, 2099, 2117, 2184, 2401, 2406, 2408, 2631, 2664, 2722, 2900, 2917, 2918, 4141, 4167, 4284, 2976, 3130, 3507, 3540, 3709, 211, 585, 590, 605, 717, 720, 906, 990, 1084, 1159, 1334, 1441, 1495, 1671, 1852, 1872, 1892, 1927, 1957, 2038, 2276, 2384, 2450, 2905, 3854, 3906, 4124, 4497, 4515, 4516, 4715, 3037, 3393, 3588, 3589, 92, 96, 269, 603, 648, 712, 980, 1331, 1673, 1853, 1910, 2080, 2379, 2405, 2407, 2410, 2499, 2637, 2673, 2855, 2867, 4215, 4499, 4727, 2950, 3215, 3248, 3328, 3426, 3545, 3579, 208, 277, 316, 329, 330, 1287, 1492, 1493, 1915, 1985, 2010, 2079, 2183, 2211, 2259, 2373, 2388, 2400, 2674, 2677, 2758, 2759, 3825, 4512, 4710, 2972, 3360, 3364, 3413, 3469, 3624, 3661, 3714, 6, 244, 304, 600, 604, 1047, 1221, 1286, 1674, 1675, 1850, 1923, 1926, 1984, 1987, 2115, 2150, 2198, 2372, 2380, 2600, 2706, 2745, 2822, 3822, 3823, 3883, 4140, 4713, 4725, 4726, 3410, 3532, 3539, 3544, 3606, 3614, 268, 318, 322, 331, 583, 707, 722, 1076, 1160, 1164, 1284, 1285, 1312, 1488, 1676, 1794, 1855, 1975, 2185, 2191, 2343, 2369, 2375, 2402, 2534, 2635, 3888, 4113, 4166, 4229, 4315, 4385, 4596, 4714, 3023, 3108, 3473, 3474, 3572, 3605, 65, 210, 274, 587, 608, 613, 708, 713, 984, 1075, 1167, 1679, 1709, 1795, 1800, 1815, 1851, 2014, 2047, 2238, 2256, 2265, 2368, 2422, 2434, 2726, 4151, 3003, 3353, 3538, 3607, 3615, 3660, 90, 207, 288, 320, 323, 324, 349, 597, 607, 709, 855, 905, 1166, 1169, 1252, 1408, 1856, 1971, 1981, 2374, 2383, 2427, 2705, 2743, 2897, 2911, 3860, 4758, 4759, 4762, 2977, 3008, 3061, 3131, 3189, 3202, 3203, 3366, 3514, 3515, 3587, 3610, 3617, 3668, 110, 186, 190, 191, 212, 321, 327, 328, 352, 375, 580, 582, 589, 625, 727, 851, 977, 1077, 1118, 1147, 1243, 1304, 1314, 1712, 1796, 1797, 1805, 1916, 1917, 1918, 2007, 2217, 2219, 2245, 2257, 2258, 2280, 2342, 2376, 2377, 2433, 2539, 2540, 2623, 2638, 2670, 2675, 2676, 2713, 2760, 2761, 3806, 3824, 3870, 3924, 4169, 4263, 4281, 4313, 4383, 4418, 4470, 4494, 4555, 3010, 3112, 3136, 3150, 3171, 3352, 3365, 3509, 3513, 3543, 3571, 3702, 3712, 3713, 3725, 3727, 3734, 5, 8, 82, 185, 188, 192, 257, 276, 325, 326, 348, 351, 356, 598, 620, 658, 696, 705, 856, 985, 1048, 1122, 1148, 1149, 1168, 1179, 1239, 1354, 1462, 1615, 1659, 1670, 1816, 1847, 1913, 1959, 1972, 1993, 2213, 2218, 2268, 2274, 2275, 2282, 2387, 2573, 2609, 2783, 3871, 3879, 3909, 3926, 4093, 4128, 4142, 4190, 4230, 4282, 4308, 4471, 4498, 3033, 3079, 3155, 3156, 3161, 3219, 3503, 154, 259, 261, 347, 350, 353, 579, 602, 612, 702, 706, 982, 1078, 1352, 1559, 1799, 1891, 1953, 1956, 2266, 2279, 2345, 2392, 2538, 2586, 2828, 3829, 3876, 3942, 4109, 4467, 4554, 3409, 3502, 3504, 3512, 3531, 3542, 3710, 3731, 3751, 95, 196, 203, 204, 205, 242, 243, 346, 581, 586, 601, 615, 622, 626, 627, 691, 716, 725, 983, 986, 1085, 1089, 1161, 1174, 1204, 1349, 1442, 1477, 1654, 1655, 1657, 1692, 1817, 1857, 2196, 2271, 2281, 2382, 2404, 2412, 2919, 4095, 4125, 4126, 4216, 4241, 4279, 4381, 4437, 4478) } - internal val argNames: Map> by lazy { mapOf(5 to arrayOf("n"), 6 to arrayOf("n"), 7 to arrayOf("who"), 8 to arrayOf("title"), 65 to arrayOf("state"), 67 to arrayOf("listen"), 69 to arrayOf("listen"), 82 to arrayOf("version"), 83 to arrayOf("count", "plural"), 89 to arrayOf("size", "limit"), 90 to arrayOf("name"), 91 to arrayOf("dir"), 92 to arrayOf("dir"), 93 to arrayOf("name"), 94 to arrayOf("name"), 95 to arrayOf("path"), 96 to arrayOf("path"), 97 to arrayOf("name"), 108 to arrayOf("first"), 110 to arrayOf("n"), 136 to arrayOf("count", "plural"), 154 to arrayOf("tool"), 158 to arrayOf("n"), 160 to arrayOf("name"), 184 to arrayOf("pid", "cmd"), 185 to arrayOf("title", "ago"), 186 to arrayOf("name", "who", "n"), 188 to arrayOf("line"), 190 to arrayOf("n"), 191 to arrayOf("n"), 192 to arrayOf("n"), 196 to arrayOf("name"), 203 to arrayOf("when"), 204 to arrayOf("text", "when"), 205 to arrayOf("when"), 207 to arrayOf("count", "plural"), 208 to arrayOf("count", "plural"), 210 to arrayOf("took", "ago"), 211 to arrayOf("ago"), 212 to arrayOf("kind"), 214 to arrayOf("kind", "code", "why"), 218 to arrayOf("clock"), 221 to arrayOf("build"), 242 to arrayOf("step"), 243 to arrayOf("turn"), 244 to arrayOf("branch"), 257 to arrayOf("step", "total"), 258 to arrayOf("step", "total"), 259 to arrayOf("when"), 261 to arrayOf("tool"), 268 to arrayOf("count", "plural"), 269 to arrayOf("count", "total"), 274 to arrayOf("old", "new"), 276 to arrayOf("version"), 277 to arrayOf("count"), 278 to arrayOf("tag"), 283 to arrayOf("version"), 284 to arrayOf("old", "version"), 285 to arrayOf("version"), 288 to arrayOf("version"), 299 to arrayOf("project", "location"), 303 to arrayOf("account"), 304 to arrayOf("account"), 316 to arrayOf("n"), 318 to arrayOf("n"), 320 to arrayOf("minute"), 321 to arrayOf("time"), 322 to arrayOf("time"), 323 to arrayOf("clock"), 324 to arrayOf("clock", "took"), 325 to arrayOf("clock"), 326 to arrayOf("clock", "took"), 327 to arrayOf("clock"), 328 to arrayOf("clock", "took"), 329 to arrayOf("clock"), 330 to arrayOf("clock", "took"), 331 to arrayOf("clock"), 346 to arrayOf("target"), 347 to arrayOf("target"), 348 to arrayOf("target"), 349 to arrayOf("target"), 350 to arrayOf("target"), 351 to arrayOf("target"), 352 to arrayOf("target"), 353 to arrayOf("target"), 356 to arrayOf("name"), 375 to arrayOf("t"), 418 to arrayOf("minutes", "plural"), 452 to arrayOf("path"), 579 to arrayOf("count"), 580 to arrayOf("count"), 581 to arrayOf("title"), 582 to arrayOf("path"), 583 to arrayOf("path", "error"), 584 to arrayOf("first", "last", "count"), 585 to arrayOf("task", "step"), 586 to arrayOf("count"), 587 to arrayOf("path"), 588 to arrayOf("count", "plural"), 589 to arrayOf("label"), 590 to arrayOf("provider"), 591 to arrayOf("version"), 593 to arrayOf("key"), 594 to arrayOf("device"), 595 to arrayOf("kind", "device"), 596 to arrayOf("status"), 597 to arrayOf("kind", "title"), 598 to arrayOf("layer"), 599 to arrayOf("error"), 600 to arrayOf("page"), 601 to arrayOf("page", "kind", "total"), 602 to arrayOf("reason"), 603 to arrayOf("tag"), 604 to arrayOf("tag"), 605 to arrayOf("title"), 606 to arrayOf("title"), 607 to arrayOf("text", "time"), 608 to arrayOf("kind", "device"), 609 to arrayOf("device"), 610 to arrayOf("device"), 611 to arrayOf("word"), 612 to arrayOf("word", "kind", "count"), 613 to arrayOf("error"), 614 to arrayOf("count"), 615 to arrayOf("time", "relative", "rel", "zoned", "zone"), 616 to arrayOf("zone"), 617 to arrayOf("zone"), 618 to arrayOf("id", "state", "count", "age"), 619 to arrayOf("id"), 620 to arrayOf("name"), 621 to arrayOf("name"), 622 to arrayOf("clock", "count", "plural"), 623 to arrayOf("name"), 624 to arrayOf("name"), 625 to arrayOf("name"), 626 to arrayOf("count"), 627 to arrayOf("count"), 631 to arrayOf("name", "state"), 632 to arrayOf("author", "place", "state"), 633 to arrayOf("title", "state"), 648 to arrayOf("error"), 649 to arrayOf("error"), 650 to arrayOf("host"), 655 to arrayOf("email"), 658 to arrayOf("version"), 660 to arrayOf("first", "last", "count"), 661 to arrayOf("n"), 662 to arrayOf("n"), 691 to arrayOf("ref"), 696 to arrayOf("name"), 697 to arrayOf("name"), 699 to arrayOf("name"), 700 to arrayOf("name"), 701 to arrayOf("action"), 702 to arrayOf("label"), 703 to arrayOf("count", "plural"), 705 to arrayOf("path"), 706 to arrayOf("word", "kind", "count"), 707 to arrayOf("name"), 708 to arrayOf("name"), 709 to arrayOf("name"), 710 to arrayOf("name"), 711 to arrayOf("url"), 712 to arrayOf("count"), 713 to arrayOf("count"), 714 to arrayOf("device"), 715 to arrayOf("device"), 716 to arrayOf("count"), 717 to arrayOf("label"), 718 to arrayOf("label"), 719 to arrayOf("label"), 720 to arrayOf("title"), 721 to arrayOf("title"), 722 to arrayOf("state"), 723 to arrayOf("open", "kind"), 725 to arrayOf("count"), 726 to arrayOf("email"), 727 to arrayOf("email"), 851 to arrayOf("at", "count"), 855 to arrayOf("name"), 856 to arrayOf("name"), 905 to arrayOf("name"), 906 to arrayOf("name"), 977 to arrayOf("count"), 980 to arrayOf("name"), 981 to arrayOf("name", "count"), 982 to arrayOf("label", "n"), 983 to arrayOf("action"), 984 to arrayOf("count", "plural"), 985 to arrayOf("count"), 986 to arrayOf("waiting", "busy", "done"), 990 to arrayOf("count", "plural"), 1023 to arrayOf("name"), 1024 to arrayOf("name"), 1026 to arrayOf("seconds", "long"), 1027 to arrayOf("size", "triangles", "delayed", "waited", "built"), 1028 to arrayOf("size", "delayed", "waited"), 1044 to arrayOf("name"), 1047 to arrayOf("name"), 1048 to arrayOf("count"), 1075 to arrayOf("state"), 1076 to arrayOf("bytes"), 1077 to arrayOf("count"), 1078 to arrayOf("when"), 1079 to arrayOf("state", "name"), 1080 to arrayOf("name", "state"), 1081 to arrayOf("reason", "code"), 1084 to arrayOf("kind", "code"), 1085 to arrayOf("number"), 1089 to arrayOf("x", "y"), 1096 to arrayOf("state"), 1097 to arrayOf("label", "example"), 1109 to arrayOf("text"), 1117 to arrayOf("error"), 1118 to arrayOf("kind", "count"), 1121 to arrayOf("name"), 1122 to arrayOf("n"), 1147 to arrayOf("ago"), 1148 to arrayOf("name"), 1149 to arrayOf("kind", "place", "hub"), 1159 to arrayOf("label"), 1160 to arrayOf("word"), 1161 to arrayOf("count"), 1164 to arrayOf("hub"), 1166 to arrayOf("count"), 1167 to arrayOf("state"), 1168 to arrayOf("label"), 1169 to arrayOf("label"), 1174 to arrayOf("state", "text"), 1175 to arrayOf("text"), 1177 to arrayOf("question"), 1179 to arrayOf("label"), 1183 to arrayOf("title"), 1204 to arrayOf("count"), 1205 to arrayOf("name", "counts"), 1219 to arrayOf("n"), 1221 to arrayOf("mode"), 1238 to arrayOf("first", "last", "total"), 1239 to arrayOf("count"), 1242 to arrayOf("n"), 1243 to arrayOf("who", "name"), 1251 to arrayOf("name"), 1252 to arrayOf("when"), 1259 to arrayOf("why"), 1276 to arrayOf("name"), 1283 to arrayOf("kind"), 1284 to arrayOf("title"), 1285 to arrayOf("title"), 1286 to arrayOf("title"), 1287 to arrayOf("title"), 1292 to arrayOf("name"), 1302 to arrayOf("heard"), 1303 to arrayOf("out", "heard"), 1304 to arrayOf("heard"), 1312 to arrayOf("name", "mb"), 1314 to arrayOf("name"), 1317 to arrayOf("platform"), 1321 to arrayOf("heard", "out", "yes"), 1331 to arrayOf("name", "done", "total", "percent"), 1332 to arrayOf("name", "done"), 1333 to arrayOf("name"), 1334 to arrayOf("error"), 1336 to arrayOf("mb"), 1342 to arrayOf("mb"), 1345 to arrayOf("n"), 1346 to arrayOf("n"), 1349 to arrayOf("n"), 1350 to arrayOf("pct"), 1351 to arrayOf("px"), 1352 to arrayOf("key"), 1353 to arrayOf("key"), 1354 to arrayOf("why"), 1408 to arrayOf("n"), 1441 to arrayOf("title"), 1442 to arrayOf("note"), 1462 to arrayOf("title"), 1463 to arrayOf("more"), 1477 to arrayOf("bots"), 1488 to arrayOf("name"), 1489 to arrayOf("name", "time"), 1490 to arrayOf("name", "n"), 1491 to arrayOf("name", "time", "n"), 1492 to arrayOf("to"), 1493 to arrayOf("to", "step"), 1495 to arrayOf("note"), 1538 to arrayOf("why"), 1543 to arrayOf("e"), 1549 to arrayOf("max"), 1550 to arrayOf("secs", "max", "mib"), 1559 to arrayOf("path"), 1592 to arrayOf("secs"), 1615 to arrayOf("pct", "scope"), 1623 to arrayOf("n"), 1624 to arrayOf("n"), 1625 to arrayOf("n"), 1626 to arrayOf("n"), 1654 to arrayOf("d", "h"), 1655 to arrayOf("h", "m"), 1656 to arrayOf("m"), 1657 to arrayOf("window", "pct"), 1659 to arrayOf("when"), 1661 to arrayOf("label", "e"), 1663 to arrayOf("from", "to", "total"), 1667 to arrayOf("messages", "lines", "left"), 1669 to arrayOf("pct", "view", "max"), 1670 to arrayOf("pct"), 1671 to arrayOf("done", "total"), 1673 to arrayOf("n"), 1674 to arrayOf("n"), 1675 to arrayOf("time"), 1676 to arrayOf("view", "max"), 1677 to arrayOf("view", "max"), 1679 to arrayOf("more"), 1683 to arrayOf("n"), 1692 to arrayOf("n"), 1698 to arrayOf("page"), 1709 to arrayOf("title"), 1712 to arrayOf("n"), 1729 to arrayOf("name"), 1794 to arrayOf("line"), 1795 to arrayOf("quote"), 1796 to arrayOf("n"), 1797 to arrayOf("n"), 1798 to arrayOf("n"), 1799 to arrayOf("n"), 1800 to arrayOf("n"), 1805 to arrayOf("held"), 1806 to arrayOf("machine"), 1807 to arrayOf("machine"), 1815 to arrayOf("count", "total"), 1816 to arrayOf("count"), 1817 to arrayOf("n"), 1829 to arrayOf("name"), 1831 to arrayOf("n", "c", "total"), 1832 to arrayOf("n", "c"), 1833 to arrayOf("n", "c", "total", "before"), 1834 to arrayOf("n", "c", "before"), 1846 to arrayOf("name"), 1847 to arrayOf("path"), 1850 to arrayOf("file"), 1851 to arrayOf("path", "n"), 1852 to arrayOf("why"), 1853 to arrayOf("n"), 1854 to arrayOf("name"), 1855 to arrayOf("name"), 1856 to arrayOf("name"), 1857 to arrayOf("n"), 1858 to arrayOf("shown", "n"), 1861 to arrayOf("path"), 1863 to arrayOf("n"), 1872 to arrayOf("status"), 1889 to arrayOf("name", "pct"), 1890 to arrayOf("name", "mb"), 1891 to arrayOf("name"), 1892 to arrayOf("name", "why"), 1910 to arrayOf("machine"), 1913 to arrayOf("n"), 1914 to arrayOf("ref"), 1915 to arrayOf("ref", "sheet"), 1916 to arrayOf("name"), 1917 to arrayOf("name"), 1918 to arrayOf("file", "folder"), 1919 to arrayOf("name", "error"), 1920 to arrayOf("name", "status"), 1921 to arrayOf("name", "error"), 1923 to arrayOf("name"), 1926 to arrayOf("code"), 1927 to arrayOf("error"), 1930 to arrayOf("error"), 1931 to arrayOf("error"), 1935 to arrayOf("error"), 1953 to arrayOf("done", "of"), 1955 to arrayOf("why"), 1956 to arrayOf("path"), 1957 to arrayOf("error"), 1958 to arrayOf("secs"), 1959 to arrayOf("secs"), 1971 to arrayOf("code"), 1972 to arrayOf("code"), 1975 to arrayOf("state"), 1980 to arrayOf("hide", "copy", "paste"), 1981 to arrayOf("n"), 1984 to arrayOf("name"), 1985 to arrayOf("name", "folder"), 1986 to arrayOf("name"), 1987 to arrayOf("name", "percent"), 1993 to arrayOf("folder"), 2003 to arrayOf("w", "h"), 2007 to arrayOf("path"), 2010 to arrayOf("why"), 2011 to arrayOf("mb"), 2014 to arrayOf("n"), 2015 to arrayOf("delete", "undo"), 2016 to arrayOf("delete", "undo"), 2017 to arrayOf("undo"), 2038 to arrayOf("what", "secs"), 2039 to arrayOf("file", "holder"), 2046 to arrayOf("what"), 2047 to arrayOf("what"), 2048 to arrayOf("editor", "why"), 2067 to arrayOf("files"), 2077 to arrayOf("why"), 2079 to arrayOf("title"), 2080 to arrayOf("title"), 2081 to arrayOf("version"), 2082 to arrayOf("version", "size", "folder"), 2083 to arrayOf("version", "size", "folder"), 2092 to arrayOf("title"), 2093 to arrayOf("dir", "files"), 2099 to arrayOf("why"), 2101 to arrayOf("code"), 2115 to arrayOf("origin"), 2117 to arrayOf("why"), 2128 to arrayOf("dir"), 2129 to arrayOf("path"), 2130 to arrayOf("home", "other"), 2132 to arrayOf("path"), 2133 to arrayOf("code", "log"), 2134 to arrayOf("log"), 2136 to arrayOf("addr"), 2149 to arrayOf("home"), 2150 to arrayOf("addr"), 2165 to arrayOf("dir", "why"), 2166 to arrayOf("dir"), 2181 to arrayOf("phase"), 2183 to arrayOf("why"), 2184 to arrayOf("what"), 2185 to arrayOf("code"), 2191 to arrayOf("label"), 2196 to arrayOf("kind"), 2198 to arrayOf("project"), 2211 to arrayOf("what"), 2213 to arrayOf("when"), 2217 to arrayOf("n"), 2218 to arrayOf("n"), 2219 to arrayOf("n"), 2221 to arrayOf("agent"), 2222 to arrayOf("effort"), 2224 to arrayOf("n"), 2226 to arrayOf("model"), 2238 to arrayOf("word"), 2245 to arrayOf("more", "step"), 2249 to arrayOf("name"), 2253 to arrayOf("max", "skipped"), 2256 to arrayOf("name"), 2257 to arrayOf("n"), 2258 to arrayOf("name"), 2259 to arrayOf("name"), 2265 to arrayOf("n"), 2266 to arrayOf("name"), 2268 to arrayOf("price"), 2271 to arrayOf("name"), 2273 to arrayOf("name"), 2274 to arrayOf("name"), 2275 to arrayOf("name"), 2276 to arrayOf("text"), 2279 to arrayOf("key"), 2280 to arrayOf("key"), 2281 to arrayOf("pct"), 2282 to arrayOf("when"), 2293 to arrayOf("n", "upstream"), 2296 to arrayOf("mb"), 2306 to arrayOf("path"), 2307 to arrayOf("path"), 2329 to arrayOf("id"), 2333 to arrayOf("model"), 2334 to arrayOf("platform"), 2335 to arrayOf("version"), 2338 to arrayOf("version", "from", "into"), 2339 to arrayOf("version", "from"), 2342 to arrayOf("version", "path"), 2343 to arrayOf("version", "path"), 2344 to arrayOf("version", "pin", "from"), 2345 to arrayOf("path"), 2346 to arrayOf("version", "path"), 2347 to arrayOf("version", "path", "set"), 2361 to arrayOf("turns", "input", "cread", "cwrite", "output", "cost"), 2368 to arrayOf("tool"), 2369 to arrayOf("tool"), 2370 to arrayOf("tool", "word"), 2371 to arrayOf("tool", "word"), 2372 to arrayOf("tool"), 2373 to arrayOf("tool"), 2374 to arrayOf("due"), 2375 to arrayOf("due"), 2376 to arrayOf("due"), 2377 to arrayOf("due"), 2378 to arrayOf("zone"), 2379 to arrayOf("zone"), 2380 to arrayOf("zone"), 2381 to arrayOf("zone"), 2382 to arrayOf("n"), 2383 to arrayOf("who"), 2384 to arrayOf("n", "who"), 2385 to arrayOf("harness"), 2386 to arrayOf("path"), 2387 to arrayOf("path"), 2388 to arrayOf("path"), 2391 to arrayOf("error", "line"), 2392 to arrayOf("label"), 2400 to arrayOf("who"), 2401 to arrayOf("who"), 2402 to arrayOf("label", "left", "when"), 2403 to arrayOf("left"), 2404 to arrayOf("name", "left"), 2405 to arrayOf("used"), 2406 to arrayOf("used", "limit"), 2407 to arrayOf("used", "reason"), 2408 to arrayOf("used", "limit", "reason"), 2410 to arrayOf("provider"), 2411 to arrayOf("used", "window", "pct"), 2412 to arrayOf("rate"), 2422 to arrayOf("n", "r"), 2427 to arrayOf("time", "n"), 2431 to arrayOf("n", "m"), 2433 to arrayOf("pct"), 2434 to arrayOf("cost", "n"), 2438 to arrayOf("in", "out", "cread", "cwrite"), 2439 to arrayOf("in", "out", "cread", "cwrite", "n"), 2448 to arrayOf("turns", "input", "cread", "cwrite", "output"), 2449 to arrayOf("left", "when"), 2450 to arrayOf("left", "when"), 2451 to arrayOf("left", "when"), 2452 to arrayOf("left", "when"), 2476 to arrayOf("n"), 2499 to arrayOf("when"), 2506 to arrayOf("phrase", "now"), 2517 to arrayOf("s"), 2523 to arrayOf("now"), 2524 to arrayOf("now", "nudge", "sent", "undone"), 2534 to arrayOf("e"), 2535 to arrayOf("a", "ams", "b", "bms"), 2536 to arrayOf("ms"), 2537 to arrayOf("e"), 2538 to arrayOf("t"), 2539 to arrayOf("t"), 2540 to arrayOf("t"), 2546 to arrayOf("why"), 2556 to arrayOf("apps"), 2566 to arrayOf("n"), 2567 to arrayOf("n", "k"), 2572 to arrayOf("stt", "conf"), 2573 to arrayOf("words"), 2583 to arrayOf("into"), 2586 to arrayOf("origin"), 2598 to arrayOf("url"), 2600 to arrayOf("url"), 2608 to arrayOf("i", "n"), 2609 to arrayOf("d", "n"), 2618 to arrayOf("version"), 2619 to arrayOf("version"), 2620 to arrayOf("version"), 2623 to arrayOf("path"), 2631 to arrayOf("addr"), 2635 to arrayOf("label"), 2637 to arrayOf("label"), 2638 to arrayOf("label"), 2642 to arrayOf("label"), 2647 to arrayOf("from"), 2664 to arrayOf("done", "of"), 2670 to arrayOf("n"), 2671 to arrayOf("t", "m"), 2672 to arrayOf("m"), 2673 to arrayOf("b", "m"), 2674 to arrayOf("r", "p"), 2675 to arrayOf("n"), 2676 to arrayOf("n"), 2677 to arrayOf("n"), 2678 to arrayOf("n"), 2681 to arrayOf("n"), 2683 to arrayOf("n"), 2691 to arrayOf("n"), 2697 to arrayOf("name", "gb", "path"), 2699 to arrayOf("path", "why"), 2701 to arrayOf("names"), 2703 to arrayOf("why"), 2704 to arrayOf("p", "pn", "t", "tn", "e", "en"), 2705 to arrayOf("done", "total"), 2706 to arrayOf("n"), 2707 to arrayOf("what"), 2708 to arrayOf("n"), 2709 to arrayOf("n"), 2712 to arrayOf("what"), 2713 to arrayOf("n"), 2715 to arrayOf("why", "from"), 2716 to arrayOf("why"), 2722 to arrayOf("path"), 2723 to arrayOf("path", "who"), 2724 to arrayOf("path"), 2725 to arrayOf("path", "cmd"), 2726 to arrayOf("version", "path"), 2727 to arrayOf("version", "path"), 2728 to arrayOf("version", "path", "who"), 2729 to arrayOf("version", "path"), 2730 to arrayOf("version", "path", "cmd"), 2733 to arrayOf("cmd"), 2743 to arrayOf("name", "version", "path"), 2744 to arrayOf("path", "why"), 2745 to arrayOf("name"), 2747 to arrayOf("version", "cli"), 2748 to arrayOf("cli"), 2750 to arrayOf("version"), 2751 to arrayOf("version"), 2753 to arrayOf("version"), 2755 to arrayOf("version"), 2757 to arrayOf("computer"), 2758 to arrayOf("version", "cli"), 2759 to arrayOf("cli"), 2760 to arrayOf("version", "cli"), 2761 to arrayOf("cli"), 2783 to arrayOf("n"), 2788 to arrayOf("code"), 2790 to arrayOf("e"), 2803 to arrayOf("n"), 2808 to arrayOf("channel"), 2822 to arrayOf("project"), 2828 to arrayOf("n"), 2840 to arrayOf("m"), 2852 to arrayOf("m"), 2855 to arrayOf("m"), 2862 to arrayOf("pages"), 2864 to arrayOf("name"), 2867 to arrayOf("name"), 2876 to arrayOf("d", "n"), 2897 to arrayOf("n", "tools"), 2898 to arrayOf("n", "tools", "d"), 2899 to arrayOf("n", "d"), 2900 to arrayOf("n", "what"), 2901 to arrayOf("n", "d", "what"), 2905 to arrayOf("head"), 2911 to arrayOf("name", "path"), 2917 to arrayOf("page", "net", "near"), 2918 to arrayOf("page", "what"), 2919 to arrayOf("ref"), 2923 to arrayOf("page"), 2946 to arrayOf("n"), 2947 to arrayOf("n"), 2948 to arrayOf("n"), 2950 to arrayOf("hub"), 2972 to arrayOf("project"), 2974 to arrayOf("n"), 2975 to arrayOf("n"), 2976 to arrayOf("word"), 2977 to arrayOf("n"), 2995 to arrayOf("name"), 3003 to arrayOf("answer"), 3008 to arrayOf("why"), 3010 to arrayOf("hub"), 3016 to arrayOf("from", "to"), 3023 to arrayOf("project"), 3033 to arrayOf("name"), 3037 to arrayOf("n"), 3043 to arrayOf("code"), 3044 to arrayOf("hub"), 3045 to arrayOf("hub"), 3046 to arrayOf("hub"), 3060 to arrayOf("n"), 3061 to arrayOf("n"), 3077 to arrayOf("status"), 3079 to arrayOf("status"), 3108 to arrayOf("project"), 3112 to arrayOf("code"), 3114 to arrayOf("why"), 3122 to arrayOf("title"), 3128 to arrayOf("title"), 3130 to arrayOf("q"), 3131 to arrayOf("title"), 3136 to arrayOf("room"), 3140 to arrayOf("q"), 3150 to arrayOf("title"), 3155 to arrayOf("n"), 3156 to arrayOf("n"), 3161 to arrayOf("at"), 3169 to arrayOf("size"), 3171 to arrayOf("n", "total"), 3188 to arrayOf("n"), 3189 to arrayOf("what"), 3192 to arrayOf("device"), 3193 to arrayOf("device"), 3202 to arrayOf("word", "count"), 3203 to arrayOf("heard"), 3215 to arrayOf("files"), 3216 to arrayOf("files"), 3219 to arrayOf("name"), 3247 to arrayOf("n"), 3248 to arrayOf("n"), 3259 to arrayOf("n"), 3293 to arrayOf("root"), 3294 to arrayOf("path"), 3317 to arrayOf("name"), 3320 to arrayOf("until"), 3321 to arrayOf("error"), 3328 to arrayOf("url"), 3332 to arrayOf("name"), 3333 to arrayOf("name"), 3341 to arrayOf("code", "hub", "until"), 3342 to arrayOf("url"), 3346 to arrayOf("kinds"), 3347 to arrayOf("address"), 3349 to arrayOf("address"), 3352 to arrayOf("url"), 3353 to arrayOf("url"), 3354 to arrayOf("url"), 3355 to arrayOf("url", "via"), 3360 to arrayOf("name"), 3361 to arrayOf("url", "check", "left"), 3363 to arrayOf("check"), 3364 to arrayOf("address"), 3365 to arrayOf("name"), 3366 to arrayOf("error"), 3367 to arrayOf("url"), 3368 to arrayOf("url"), 3375 to arrayOf("code", "address", "left"), 3381 to arrayOf("name"), 3382 to arrayOf("name"), 3393 to arrayOf("address"), 3400 to arrayOf("code", "body"), 3403 to arrayOf("code", "body"), 3409 to arrayOf("window", "used"), 3410 to arrayOf("window", "used", "when"), 3411 to arrayOf("window", "used"), 3412 to arrayOf("window", "used", "when"), 3413 to arrayOf("provider"), 3425 to arrayOf("label"), 3426 to arrayOf("when"), 3428 to arrayOf("provider"), 3429 to arrayOf("provider", "title", "why"), 3449 to arrayOf("reason"), 3457 to arrayOf("code"), 3466 to arrayOf("name"), 3469 to arrayOf("version"), 3470 to arrayOf("version"), 3471 to arrayOf("version"), 3473 to arrayOf("version"), 3474 to arrayOf("version"), 3475 to arrayOf("version"), 3476 to arrayOf("version", "why"), 3477 to arrayOf("version"), 3479 to arrayOf("code"), 3495 to arrayOf("name"), 3502 to arrayOf("count"), 3503 to arrayOf("title"), 3504 to arrayOf("name"), 3507 to arrayOf("n", "holder"), 3508 to arrayOf("n", "title"), 3509 to arrayOf("title"), 3512 to arrayOf("n"), 3513 to arrayOf("n"), 3514 to arrayOf("n"), 3515 to arrayOf("n"), 3516 to arrayOf("harness", "typed", "type", "remote", "host", "wt", "branch"), 3526 to arrayOf("pid"), 3531 to arrayOf("left"), 3532 to arrayOf("left"), 3538 to arrayOf("left"), 3539 to arrayOf("left"), 3540 to arrayOf("left"), 3541 to arrayOf("left"), 3542 to arrayOf("label", "left"), 3543 to arrayOf("when"), 3544 to arrayOf("used"), 3545 to arrayOf("used", "limit"), 3567 to arrayOf("tracking"), 3571 to arrayOf("total"), 3572 to arrayOf("price"), 3573 to arrayOf("price"), 3578 to arrayOf("n"), 3579 to arrayOf("parts"), 3580 to arrayOf("note"), 3581 to arrayOf("error"), 3582 to arrayOf("error", "parts"), 3587 to arrayOf("state"), 3588 to arrayOf("name", "path"), 3589 to arrayOf("name", "path", "why"), 3591 to arrayOf("code"), 3595 to arrayOf("detail"), 3597 to arrayOf("why"), 3598 to arrayOf("parts"), 3601 to arrayOf("build", "to"), 3602 to arrayOf("build"), 3603 to arrayOf("build", "skip"), 3605 to arrayOf("why"), 3606 to arrayOf("why"), 3607 to arrayOf("build"), 3608 to arrayOf("build", "why"), 3609 to arrayOf("build"), 3610 to arrayOf("build"), 3614 to arrayOf("build"), 3615 to arrayOf("build"), 3617 to arrayOf("build"), 3624 to arrayOf("build"), 3658 to arrayOf("step"), 3659 to arrayOf("p", "pt", "t", "tt", "e", "et"), 3660 to arrayOf("done", "total"), 3661 to arrayOf("n"), 3662 to arrayOf("n"), 3663 to arrayOf("n"), 3668 to arrayOf("n"), 3671 to arrayOf("why"), 3672 to arrayOf("why", "from"), 3673 to arrayOf("error"), 3675 to arrayOf("n"), 3676 to arrayOf("n"), 3680 to arrayOf("n"), 3683 to arrayOf("name", "gb", "path"), 3684 to arrayOf("path", "why"), 3685 to arrayOf("names"), 3687 to arrayOf("why"), 3698 to arrayOf("n", "total"), 3702 to arrayOf("title"), 3704 to arrayOf("n"), 3708 to arrayOf("name"), 3709 to arrayOf("title"), 3710 to arrayOf("note"), 3712 to arrayOf("machine"), 3713 to arrayOf("machines"), 3714 to arrayOf("machine"), 3725 to arrayOf("n"), 3727 to arrayOf("n"), 3731 to arrayOf("name"), 3734 to arrayOf("name"), 3751 to arrayOf("why"), 3757 to arrayOf("project"), 3798 to arrayOf("path"), 3799 to arrayOf("path"), 3801 to arrayOf("have", "total"), 3806 to arrayOf("n"), 3815 to arrayOf("hub"), 3818 to arrayOf("title"), 3822 to arrayOf("project"), 3823 to arrayOf("project"), 3824 to arrayOf("n"), 3825 to arrayOf("hub"), 3827 to arrayOf("n"), 3828 to arrayOf("n"), 3829 to arrayOf("model"), 3835 to arrayOf("name"), 3854 to arrayOf("word"), 3860 to arrayOf("answer"), 3870 to arrayOf("version", "build"), 3871 to arrayOf("hub"), 3876 to arrayOf("name"), 3879 to arrayOf("when", "who", "mark"), 3883 to arrayOf("who"), 3887 to arrayOf("time"), 3888 to arrayOf("address"), 3890 to arrayOf("kind", "name"), 3905 to arrayOf("title"), 3906 to arrayOf("query"), 3909 to arrayOf("room"), 3910 to arrayOf("query"), 3912 to arrayOf("n"), 3913 to arrayOf("n"), 3914 to arrayOf("n"), 3920 to arrayOf("size"), 3924 to arrayOf("n"), 3925 to arrayOf("n"), 3926 to arrayOf("n"), 3940 to arrayOf("status"), 3942 to arrayOf("status"), 4093 to arrayOf("code"), 4095 to arrayOf("n"), 4097 to arrayOf("why"), 4109 to arrayOf("done", "of"), 4113 to arrayOf("thread"), 4116 to arrayOf("n"), 4124 to arrayOf("title"), 4125 to arrayOf("note"), 4126 to arrayOf("label"), 4127 to arrayOf("machine"), 4128 to arrayOf("machine"), 4135 to arrayOf("at", "total"), 4136 to arrayOf("at", "total"), 4140 to arrayOf("machine"), 4141 to arrayOf("machine"), 4142 to arrayOf("machines"), 4144 to arrayOf("device"), 4151 to arrayOf("price"), 4152 to arrayOf("price"), 4159 to arrayOf("home"), 4164 to arrayOf("from"), 4166 to arrayOf("note"), 4167 to arrayOf("note"), 4169 to arrayOf("v"), 4170 to arrayOf("v"), 4171 to arrayOf("v", "who"), 4173 to arrayOf("who"), 4174 to arrayOf("v"), 4176 to arrayOf("v", "cmd"), 4177 to arrayOf("cmd"), 4182 to arrayOf("v", "path"), 4183 to arrayOf("v", "note"), 4184 to arrayOf("v"), 4189 to arrayOf("tool"), 4190 to arrayOf("tool"), 4215 to arrayOf("n", "w"), 4216 to arrayOf("why"), 4217 to arrayOf("state", "why"), 4229 to arrayOf("project"), 4230 to arrayOf("n"), 4241 to arrayOf("why"), 4247 to arrayOf("name"), 4258 to arrayOf("project"), 4263 to arrayOf("n"), 4271 to arrayOf("names"), 4279 to arrayOf("dest"), 4281 to arrayOf("repo"), 4282 to arrayOf("repo"), 4284 to arrayOf("url"), 4308 to arrayOf("group"), 4312 to arrayOf("project"), 4313 to arrayOf("n"), 4314 to arrayOf("n"), 4315 to arrayOf("n"), 4323 to arrayOf("n"), 4380 to arrayOf("n"), 4381 to arrayOf("n"), 4382 to arrayOf("a", "b"), 4383 to arrayOf("n"), 4385 to arrayOf("parts", "lines"), 4386 to arrayOf("n"), 4417 to arrayOf("what", "project", "fab"), 4418 to arrayOf("rev", "day"), 4426 to arrayOf("n"), 4437 to arrayOf("layer"), 4438 to arrayOf("n"), 4443 to arrayOf("board"), 4455 to arrayOf("others"), 4456 to arrayOf("must", "should", "notes"), 4457 to arrayOf("id", "w"), 4467 to arrayOf("what"), 4470 to arrayOf("why"), 4471 to arrayOf("why"), 4478 to arrayOf("n"), 4494 to arrayOf("price", "n"), 4495 to arrayOf("n", "need"), 4496 to arrayOf("n"), 4497 to arrayOf("n"), 4498 to arrayOf("cost"), 4499 to arrayOf("cost"), 4512 to arrayOf("day", "n"), 4513 to arrayOf("day"), 4514 to arrayOf("cost", "n", "lines"), 4515 to arrayOf("stock", "price"), 4516 to arrayOf("lines"), 4537 to arrayOf("host"), 4548 to arrayOf("n"), 4549 to arrayOf("a", "b"), 4550 to arrayOf("n"), 4551 to arrayOf("n"), 4554 to arrayOf("day"), 4555 to arrayOf("n"), 4596 to arrayOf("turn"), 4710 to arrayOf("text"), 4713 to arrayOf("repo", "dest"), 4714 to arrayOf("repo", "dest"), 4715 to arrayOf("repo"), 4720 to arrayOf("dir"), 4721 to arrayOf("dir"), 4725 to arrayOf("editor", "job", "secs"), 4726 to arrayOf("editor", "secs"), 4727 to arrayOf("editor"), 4744 to arrayOf("time"), 4750 to arrayOf("status"), 4758 to arrayOf("time"), 4759 to arrayOf("time", "dur"), 4762 to arrayOf("answer"), 4766 to arrayOf("type"), 4767 to arrayOf("max")) } + internal val exactKey: IntArray by lazy { intArrayOf(0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3123, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 3691, 61, 62, 63, 64, 66, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 84, 85, 3730, 87, 88, 98, 99, 3052, 3729, 102, 103, 105, 106, 107, 109, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 155, 156, 157, 159, 161, 162, 163, 3172, 165, 166, 3174, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 3133, 183, 187, 189, 193, 194, 195, 197, 198, 199, 200, 201, 202, 206, 209, 213, 215, 216, 217, 219, 220, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 234, 235, 2939, 237, 238, 239, 240, 3690, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 260, 262, 263, 264, 265, 266, 267, 270, 271, 272, 273, 275, 279, 280, 281, 282, 286, 287, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 300, 301, 3144, 305, 306, 307, 308, 309, 310, 311, 313, 314, 315, 317, 319, 333, 3738, 336, 3737, 3740, 340, 3750, 342, 343, 344, 345, 354, 3121, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 2942, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 2934, 2935, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 453, 454, 455, 3151, 457, 458, 459, 460, 461, 2924, 463, 464, 465, 3054, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 556, 557, 558, 559, 560, 561, 562, 563, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 592, 628, 629, 630, 3159, 3160, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 651, 652, 3803, 654, 656, 657, 659, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 680, 681, 682, 683, 684, 686, 687, 689, 690, 692, 693, 694, 695, 698, 704, 724, 728, 729, 730, 731, 732, 3735, 734, 735, 736, 737, 3158, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 3718, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 843, 844, 845, 847, 848, 3154, 850, 852, 853, 854, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 3728, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 3805, 903, 904, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 3124, 964, 965, 966, 967, 968, 969, 3753, 971, 2979, 3036, 974, 975, 976, 978, 979, 987, 988, 989, 991, 992, 993, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 3756, 1020, 1021, 1022, 1025, 1029, 1030, 1031, 2931, 3005, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1045, 1046, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072, 1074, 1082, 1083, 1086, 1087, 1088, 1090, 1091, 1092, 3770, 1094, 1095, 1098, 1099, 1100, 3153, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 3755, 1120, 1123, 1124, 1125, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1150, 1151, 1152, 1153, 1154, 1155, 1158, 1162, 1163, 1165, 1170, 1171, 1172, 1173, 1176, 1178, 1180, 1181, 1182, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1206, 1207, 1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1220, 1222, 1223, 2933, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1240, 1241, 1244, 1245, 1246, 1247, 1248, 1250, 1253, 1254, 1255, 1256, 1257, 1258, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1277, 1278, 1279, 1280, 1281, 1288, 1289, 1290, 1291, 1294, 1296, 1297, 1298, 1299, 1301, 1305, 1306, 1308, 1309, 1310, 1311, 1315, 1316, 1318, 1319, 1320, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1335, 1338, 1339, 1340, 1341, 1344, 1347, 1348, 1355, 1356, 3009, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 2936, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 3053, 3546, 1407, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 3548, 1444, 1445, 1446, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1464, 1465, 3693, 1467, 1468, 1469, 3705, 3711, 1472, 1473, 1474, 1475, 1476, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1494, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1539, 1540, 1541, 1542, 1544, 1545, 1546, 1547, 1548, 1551, 1552, 1553, 1554, 1555, 1556, 1557, 1558, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 3012, 1602, 1603, 1604, 1605, 1606, 1607, 1608, 1609, 1610, 1611, 1612, 1613, 1614, 1616, 1617, 1618, 1619, 1620, 1621, 1622, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 3422, 1636, 1637, 1638, 1639, 3423, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 2945, 1658, 1660, 1662, 1664, 1668, 1672, 1678, 1680, 1681, 1682, 1684, 1685, 1686, 1687, 1688, 1689, 1691, 1693, 1694, 1695, 1696, 1697, 1699, 1700, 3717, 1702, 1703, 1704, 1705, 1706, 1707, 1708, 1710, 1711, 1713, 1714, 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725, 1726, 1727, 1728, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742, 1743, 1744, 1745, 1746, 1747, 1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1792, 1793, 2988, 1802, 1804, 1808, 2970, 1810, 1811, 2971, 1813, 1814, 1818, 3035, 1820, 1821, 1822, 1823, 1824, 1825, 1826, 1827, 1828, 1830, 1835, 1837, 1838, 1839, 1840, 1841, 1842, 3050, 1844, 1845, 1848, 1849, 1859, 1860, 1864, 1865, 1866, 1867, 1868, 1869, 1870, 1871, 1873, 1874, 1875, 1876, 1877, 1878, 1879, 1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1908, 1909, 1911, 1912, 1922, 1924, 1925, 1928, 1929, 1932, 1933, 1934, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950, 1951, 1952, 1954, 1960, 1961, 1962, 1963, 1967, 3111, 1973, 1974, 1976, 1977, 1978, 1979, 3763, 3764, 1988, 1990, 1991, 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2005, 2006, 2008, 2009, 2012, 2013, 3096, 3097, 3098, 2021, 3324, 2023, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2040, 2041, 2042, 2043, 2044, 2045, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2068, 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2078, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 3038, 2096, 2097, 2098, 2100, 2102, 2103, 2104, 2105, 2961, 3086, 3087, 3088, 3089, 3090, 2112, 2113, 2114, 2116, 2963, 2964, 2954, 2953, 2122, 2955, 2124, 2959, 2126, 3322, 2131, 2135, 2137, 2138, 2139, 2140, 2141, 2142, 2143, 2144, 2145, 2146, 2147, 2989, 2151, 2152, 2153, 2154, 3022, 2156, 2157, 2158, 2159, 2160, 2161, 2162, 2163, 2164, 2167, 3335, 2169, 2170, 2171, 2172, 3004, 2174, 2175, 2176, 2177, 2952, 2179, 3067, 2182, 2186, 2187, 3612, 2189, 2190, 3699, 3700, 2194, 3149, 2197, 3688, 2200, 2201, 2202, 2203, 2204, 3748, 2206, 3119, 2208, 3118, 2210, 2212, 2214, 2215, 2216, 2220, 2223, 2225, 2227, 2228, 2229, 2230, 2231, 2232, 2233, 2234, 2235, 2236, 2237, 2239, 2240, 2241, 3706, 2243, 2244, 2246, 2996, 2994, 2998, 2252, 2254, 2255, 2261, 2262, 2263, 2264, 3034, 2269, 2270, 2272, 2277, 2278, 2978, 3547, 2941, 2940, 2943, 3063, 3066, 2291, 2292, 2294, 2295, 2297, 2298, 2299, 2300, 2301, 2302, 2303, 2304, 2305, 3767, 2309, 2310, 2311, 2312, 2313, 2314, 2315, 2316, 2317, 2318, 2319, 2320, 2321, 2322, 2323, 2328, 2330, 2331, 2332, 2336, 2337, 2340, 2341, 2348, 2349, 2350, 2351, 2352, 2353, 2354, 2355, 2356, 2357, 2358, 2359, 2360, 2362, 2363, 2364, 2365, 2366, 2367, 2389, 2390, 2393, 2394, 2395, 2396, 2397, 2398, 2399, 2409, 2413, 2414, 2415, 2416, 2417, 2418, 2419, 2420, 2421, 2423, 2424, 2425, 2426, 2428, 2429, 2430, 2432, 2435, 2436, 2437, 2440, 2441, 2442, 2443, 2444, 2445, 2446, 2447, 2453, 2454, 2455, 2456, 2457, 2458, 2459, 2460, 2461, 2462, 2463, 2464, 2465, 2466, 2467, 2468, 2469, 2470, 2471, 2472, 2473, 2474, 2475, 2477, 2478, 2479, 2480, 2481, 2482, 2483, 2484, 2485, 2486, 2487, 2488, 2489, 2490, 2491, 2492, 2493, 2494, 2495, 2496, 2497, 2498, 2500, 2501, 2502, 2503, 3100, 2505, 2507, 2508, 2510, 2511, 2512, 2513, 2514, 2515, 2516, 2519, 2520, 2521, 2522, 2525, 2526, 2527, 2528, 2529, 2530, 2531, 2532, 2533, 2541, 2542, 2543, 2544, 2547, 2548, 2549, 2550, 2551, 2552, 2553, 2554, 2555, 2557, 2558, 2559, 2560, 2561, 2562, 2563, 2564, 2565, 2568, 2570, 2571, 2574, 2575, 2576, 2577, 2578, 2579, 2580, 2581, 2582, 2584, 2585, 2587, 2588, 2589, 2590, 2591, 2592, 2593, 2594, 2595, 2596, 2597, 2599, 2601, 2604, 2606, 3696, 2611, 2612, 2613, 2614, 2615, 2616, 2617, 2621, 2622, 2624, 2625, 2626, 2627, 2628, 2629, 2630, 2632, 2633, 2634, 2639, 2640, 2641, 2643, 2644, 2645, 2646, 2648, 2649, 2650, 2651, 2652, 2653, 2654, 2655, 2656, 2657, 2658, 2659, 2660, 3669, 2662, 2663, 2665, 3666, 2667, 2668, 3670, 3667, 2680, 2684, 3677, 3173, 3678, 2688, 3679, 2690, 2692, 3681, 2694, 3682, 2696, 2698, 3686, 3664, 3657, 3665, 2717, 2718, 2720, 2721, 2731, 2732, 2734, 2735, 2736, 2737, 2738, 2739, 2740, 2741, 2742, 2746, 2749, 2752, 2754, 2756, 2762, 2763, 2764, 2765, 2766, 2767, 2768, 2769, 2770, 2771, 2772, 2773, 2774, 3344, 2776, 2777, 2778, 2779, 2780, 2782, 2784, 2785, 3376, 2791, 2792, 2793, 2794, 2795, 2796, 2797, 2798, 2799, 2800, 2801, 2802, 2804, 2805, 2806, 2807, 2810, 2811, 2813, 2814, 2815, 2816, 2968, 2818, 2820, 2821, 2823, 2824, 2825, 2826, 2827, 2829, 2830, 2834, 2837, 2838, 2839, 2841, 2842, 2843, 2845, 2846, 2847, 2848, 2850, 2851, 2854, 2857, 2858, 2859, 2860, 2861, 2863, 2865, 2866, 2868, 2869, 2870, 2871, 2872, 2873, 2874, 2875, 2877, 2878, 2879, 2880, 2881, 2882, 2883, 2884, 2885, 2886, 2887, 2888, 2889, 2890, 2891, 2892, 2893, 2894, 2895, 2896, 2902, 2903, 2904, 2906, 2907, 2908, 2912, 2913, 2914, 2915, 2916, 2920, 2921, 2925, 2926, 2927, 2928, 2929, 2930, 2932, 2937, 2938, 2944, 2949, 2951, 2956, 2957, 2958, 2960, 2962, 2965, 2966, 2967, 2969, 2973, 2980, 2981, 2982, 2983, 2984, 2985, 2986, 2987, 2990, 2991, 2992, 2993, 2997, 2999, 3000, 3001, 3002, 3006, 3007, 3011, 3013, 3014, 3015, 3017, 3018, 3019, 3020, 3021, 3024, 3025, 3026, 3027, 3028, 3029, 3030, 3031, 3032, 3039, 3040, 3041, 3042, 3047, 3048, 3049, 3051, 3055, 3056, 3057, 3058, 3059, 3062, 3064, 3065, 3068, 3069, 3070, 3071, 3072, 3073, 3074, 3075, 3076, 3078, 3080, 3081, 3082, 3083, 3084, 3085, 3091, 3092, 3093, 3094, 3095, 3099, 3101, 3102, 3103, 3104, 3105, 3106, 3107, 3109, 3110, 3113, 3115, 3116, 3117, 3120, 3125, 3126, 3127, 3129, 3132, 3134, 3135, 3137, 3138, 3139, 3141, 3142, 3143, 3145, 3146, 3147, 3148, 3152, 3157, 3162, 3163, 3164, 3165, 3166, 3167, 3168, 3170, 3175, 3176, 3177, 3178, 3179, 3180, 3181, 3182, 3183, 3184, 3185, 3186, 3187, 3190, 3191, 3194, 3195, 3196, 3197, 3198, 3199, 3200, 3201, 3204, 3205, 3206, 3207, 3208, 3209, 3210, 3211, 3212, 3213, 3214, 3217, 3218, 3220, 3221, 3222, 3223, 3224, 3225, 3226, 3227, 3228, 3229, 3230, 3231, 3232, 3233, 3234, 3235, 3236, 3237, 3238, 3239, 3240, 3241, 3242, 3243, 3244, 3245, 3246, 3249, 3250, 3251, 3252, 3253, 3254, 3255, 3256, 3257, 3258, 3260, 3261, 3262, 3263, 3264, 3265, 3266, 3267, 3268, 3269, 3270, 3271, 3272, 3273, 3274, 3275, 3276, 3277, 3278, 3279, 3280, 3281, 3282, 3283, 3284, 3285, 3286, 3287, 3288, 3289, 3290, 3291, 3292, 3295, 3296, 3297, 3298, 3299, 3300, 3301, 3302, 3303, 3304, 3305, 3306, 3307, 3308, 3309, 3310, 3311, 3312, 3313, 3314, 3315, 3316, 3318, 3319, 3323, 3325, 3326, 3327, 3329, 3330, 3331, 3334, 3336, 3337, 3338, 3339, 3340, 3343, 3345, 3348, 3350, 3351, 3356, 3357, 3358, 3359, 3362, 3369, 3370, 3371, 3372, 3373, 3374, 3377, 3378, 3379, 3380, 3383, 3384, 3385, 3386, 3387, 3388, 3389, 3390, 3391, 3392, 3394, 3395, 3396, 3397, 3398, 3399, 3401, 3402, 3404, 3405, 3406, 3407, 3408, 3414, 3415, 3416, 3417, 3418, 3419, 3420, 3421, 3424, 3427, 3430, 3431, 3432, 3433, 3434, 3435, 3436, 3437, 3438, 3439, 3440, 3441, 3442, 3443, 3444, 3445, 3446, 3447, 3448, 3450, 3451, 3452, 3453, 3454, 3455, 3456, 3458, 3459, 3460, 3461, 3462, 3463, 3464, 3465, 3467, 3468, 3472, 3478, 3480, 3481, 3482, 3483, 3484, 3485, 3486, 3487, 3488, 3489, 3490, 3491, 3492, 3493, 3494, 3496, 3497, 3498, 3499, 3500, 3501, 3505, 3506, 3510, 3511, 3517, 3518, 3519, 3520, 3521, 3522, 3523, 3524, 3525, 3527, 3528, 3529, 3530, 3533, 3534, 3535, 3536, 3537, 3549, 3550, 3551, 3552, 3553, 3554, 3555, 3556, 3557, 3558, 3559, 3560, 3561, 3562, 3563, 3564, 3565, 3566, 3568, 3569, 3570, 3574, 3575, 3576, 3577, 3583, 3584, 3585, 3586, 3590, 3592, 3593, 3594, 3596, 3599, 3600, 3604, 3611, 3613, 3616, 3618, 3619, 3620, 3621, 3622, 3623, 3625, 3626, 3627, 3628, 3629, 3630, 3631, 3632, 3633, 3634, 3635, 3636, 3637, 3638, 3639, 3640, 3641, 3642, 3643, 3644, 3645, 3646, 3647, 3648, 3649, 3650, 3651, 3652, 3653, 3654, 3655, 3656, 3674, 3689, 3692, 3694, 3695, 3697, 3701, 3703, 3707, 3716, 3719, 3720, 3721, 3722, 3723, 3724, 3726, 3732, 3733, 3736, 3739, 3741, 3742, 3743, 3744, 3745, 3746, 3749, 3752, 3754, 3758, 3759, 3760, 3761, 3762, 3765, 3766, 3768, 3769, 3771, 3772, 3773, 3774, 3775, 3776, 3777, 3778, 3780, 3781, 3782, 3783, 3784, 3785, 3786, 3787, 3788, 3789, 3790, 3791, 3792, 3793, 3794, 3795, 3796, 3797, 3800, 3802, 3804, 3813, 3814, 3816, 3817, 3826, 3832, 3838, 3847, 3849, 3850, 3851, 3852, 3855, 3856, 3858, 3864, 3868, 3872, 3877, 3878, 3880, 3881, 3882, 3884, 3885, 3886, 3891, 3892, 3893, 3894, 3895, 3896, 3897, 3898, 3899, 3902, 3903, 3904, 3949, 3950, 3955, 3957, 3958, 3960, 3966, 3969, 3984, 3985, 3986, 3987, 3988, 3989, 3991, 3992, 3994, 3995, 3997, 3999, 4000, 4013, 4016, 4017, 4019, 4020, 4024, 4029, 4032, 4033, 4035, 4036, 4042, 4044, 4045, 4048, 4050, 4055, 4056, 4057, 4062, 4073, 4096, 4112, 4120, 4129, 4130, 4134, 4139, 4155, 4156, 4157, 4158, 4160, 4162, 4163, 4165, 4168, 4172, 4175, 4178, 4179, 4180, 4181, 4185, 4186, 4187, 4188, 4191, 4192, 4193, 4194, 4195, 4196, 4197, 4198, 4199, 4200, 4201, 4202, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4210, 4211, 4212, 4213, 4214, 4222, 4225, 4226, 4232, 4237, 4238, 4239, 4240, 4244, 4248, 4250, 4251, 4252, 4253, 4254, 4255, 4256, 4257, 4259, 4260, 4261, 4262, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4280, 4292, 4293, 4295, 4296, 4297, 4298, 4302, 4303, 4304, 4305, 4306, 4307, 4309, 4310, 4311, 4317, 4318, 4319, 4320, 4321, 4322, 4326, 4330, 4331, 4333, 4334, 4335, 4336, 4337, 4339, 4349, 4351, 4356, 4357, 4358, 4359, 4360, 4361, 4362, 4363, 4364, 4365, 4366, 4367, 4368, 4369, 4370, 4371, 4373, 4374, 4375, 4376, 4377, 4378, 4379, 4384, 4387, 4388, 4389, 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397, 4398, 4399, 4400, 4401, 4402, 4403, 4404, 4405, 4406, 4407, 4409, 4410, 4411, 4413, 4414, 4415, 4416, 4419, 4420, 4421, 4423, 4424, 4425, 4427, 4428, 4429, 4430, 4431, 4432, 4434, 4436, 4439, 4440, 4441, 4442, 4444, 4445, 4446, 4447, 4448, 4449, 4450, 4451, 4452, 4453, 4454, 4458, 4460, 4461, 4462, 4463, 4464, 4468, 4469, 4473, 4474, 4475, 4477, 4479, 4480, 4481, 4482, 4483, 4484, 4485, 4487, 4488, 4489, 4490, 4491, 4492, 4493, 4500, 4501, 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509, 4510, 4511, 4517, 4518, 4520, 4521, 4522, 4523, 4524, 4525, 4526, 4527, 4528, 4529, 4530, 4531, 4532, 4533, 4534, 4535, 4539, 4540, 4541, 4542, 4543, 4544, 4545, 4546, 4547, 4552, 4553, 4556, 4557, 4558, 4559, 4560, 4561, 4562, 4563, 4564, 4565, 4566, 4567, 4568, 4569, 4571, 4572, 4573, 4574, 4583, 4584, 4585, 4586, 4587, 4588, 4590, 4593, 4594, 4595, 4597, 4598, 4599, 4600, 4601, 4602, 4603, 4604, 4605, 4606, 4607, 4608, 4609, 4610, 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618, 4619, 4620, 4621, 4622, 4623, 4624, 4625, 4626, 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634, 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642, 4643, 4644, 4645, 4646, 4647, 4648, 4649, 4650, 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658, 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666, 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674, 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682, 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690, 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698, 4703, 4704, 4705, 4711, 4724, 4728, 4729, 4730, 4731, 4732, 4733, 4734, 4735, 4736, 4737, 4738, 4739, 4740, 4741, 4742, 4743, 4745, 4746, 4747, 4748, 4749, 4751, 4752, 4753, 4754, 4755, 4756, 4757, 4760, 4761, 4763, 4764, 4765, 4768, 4769, 4770, 4771, 4772, 4773, 4774, 4775, 4776, 4777, 4778, 4779, 4780, 4781, 4782, 4783, 4784, 4785, 4786, 4787, 4788, 4789, 4790, 4791, 4792, 4793, 4794, 4796) } + internal val templates: IntArray by lazy { intArrayOf(2329, 2808, 2620, 2619, 2618, 2840, 2862, 3342, 2583, 418, 2753, 2751, 2647, 2338, 2344, 2755, 2852, 2567, 2566, 285, 2296, 2757, 2864, 3192, 4144, 2506, 2556, 2016, 2334, 3676, 2081, 2683, 2339, 3193, 1336, 4164, 4184, 3675, 2524, 2681, 1833, 4159, 2092, 2130, 2136, 4513, 283, 2082, 4455, 3354, 3375, 2039, 2307, 3672, 452, 2715, 2747, 2748, 3355, 3671, 2716, 3603, 609, 1677, 3680, 1834, 2691, 3683, 2697, 3346, 616, 617, 2733, 3044, 3658, 1625, 2750, 3602, 303, 614, 69, 711, 621, 2306, 4182, 1121, 2448, 3425, 3798, 1242, 2165, 2535, 3347, 2128, 3687, 714, 1729, 1930, 2703, 2712, 2923, 4189, 3349, 3361, 136, 594, 596, 2523, 2678, 1831, 4177, 2995, 610, 2249, 2546, 3835, 1302, 4176, 3471, 3608, 3609, 158, 2046, 2048, 2083, 2803, 4312, 2134, 2333, 2476, 3597, 214, 284, 1276, 1980, 4744, 3466, 3475, 3476, 67, 83, 218, 619, 4549, 3495, 4271, 3320, 3685, 726, 1023, 2347, 2439, 2701, 4314, 89, 2346, 2361, 2876, 624, 1623, 1920, 2790, 4443, 3368, 1543, 2067, 2253, 2537, 4495, 3363, 3429, 3479, 650, 1854, 3890, 3128, 3470, 3516, 3580, 3799, 1317, 1832, 2011, 2385, 2672, 3818, 4514, 3382, 3428, 1807, 1829, 3317, 593, 1292, 1346, 1919, 3457, 3659, 221, 1667, 2704, 2901, 3046, 3114, 3403, 258, 591, 1026, 1931, 1955, 4097, 3400, 3526, 655, 1342, 1683, 2017, 3122, 3321, 3582, 3601, 710, 1283, 1353, 1624, 1698, 1861, 2335, 2438, 2536, 3905, 4183, 4380, 3381, 3449, 3595, 649, 699, 1044, 2572, 3140, 3259, 3662, 108, 184, 606, 721, 1081, 1935, 2015, 2077, 2132, 2371, 2452, 2708, 2744, 2788, 3910, 4426, 4767, 3341, 3412, 3573, 160, 623, 701, 1332, 1333, 1345, 1491, 1626, 2129, 2133, 2226, 2370, 2598, 4152, 4456, 3077, 3169, 3216, 3294, 3508, 3663, 3673, 703, 1183, 1538, 1863, 2221, 2224, 2451, 2709, 2729, 2730, 2898, 2899, 3920, 3940, 4173, 4417, 4750, 4766, 3581, 3598, 3704, 1463, 1550, 1669, 1921, 2391, 2403, 2728, 4116, 4174, 4457, 4548, 3043, 3045, 3060, 3578, 3591, 3757, 723, 1024, 1798, 2101, 2166, 2381, 2724, 2725, 3925, 4171, 4247, 4258, 3247, 3367, 91, 93, 595, 715, 1027, 1350, 1986, 2293, 2386, 2671, 2723, 2727, 3887, 4496, 2974, 2975, 3477, 3541, 3684, 94, 1251, 1259, 1490, 1549, 1846, 2149, 2181, 2431, 2449, 2699, 3827, 3828, 4170, 4323, 4386, 3293, 3332, 3333, 3411, 3567, 299, 599, 618, 700, 1109, 1117, 1175, 1489, 1592, 1914, 2093, 2099, 2117, 2184, 2401, 2406, 2408, 2631, 2664, 2722, 2900, 2917, 2918, 4141, 4167, 4284, 2976, 3130, 3507, 3540, 3709, 211, 585, 590, 605, 717, 720, 906, 990, 1084, 1159, 1334, 1441, 1495, 1671, 1852, 1872, 1892, 1927, 1957, 2038, 2276, 2384, 2450, 2905, 3854, 3906, 4124, 4497, 4515, 4516, 4715, 3037, 3393, 3588, 3589, 92, 96, 269, 603, 648, 712, 980, 1331, 1673, 1853, 1910, 2080, 2379, 2405, 2407, 2410, 2499, 2637, 2673, 2855, 2867, 4215, 4499, 4727, 2950, 3215, 3248, 3328, 3426, 3545, 3579, 208, 277, 316, 329, 330, 1287, 1492, 1493, 1915, 1985, 2010, 2079, 2183, 2211, 2259, 2373, 2388, 2400, 2674, 2677, 2758, 2759, 3825, 4512, 4710, 2972, 3360, 3364, 3413, 3469, 3624, 3661, 3714, 6, 244, 304, 600, 604, 1047, 1221, 1286, 1674, 1675, 1850, 1923, 1926, 1984, 1987, 2115, 2150, 2198, 2372, 2380, 2600, 2706, 2745, 2822, 3822, 3823, 3883, 4140, 4713, 4725, 4726, 3410, 3532, 3539, 3544, 3606, 3614, 268, 318, 322, 331, 583, 707, 722, 1076, 1160, 1164, 1284, 1285, 1312, 1488, 1676, 1794, 1855, 1975, 2185, 2191, 2343, 2369, 2375, 2402, 2534, 2635, 3888, 4113, 4166, 4229, 4315, 4385, 4596, 4714, 3023, 3108, 3473, 3474, 3572, 3605, 65, 210, 274, 587, 608, 613, 708, 713, 984, 1075, 1167, 1679, 1709, 1795, 1800, 1815, 1851, 2014, 2047, 2238, 2256, 2265, 2368, 2422, 2434, 2726, 4151, 3003, 3353, 3538, 3607, 3615, 3660, 90, 207, 288, 320, 323, 324, 349, 597, 607, 709, 855, 905, 1166, 1169, 1252, 1408, 1856, 1971, 1981, 2374, 2383, 2427, 2705, 2743, 2897, 2911, 3860, 4758, 4759, 4762, 2977, 3008, 3061, 3131, 3189, 3202, 3203, 3366, 3514, 3515, 3587, 3610, 3617, 3668, 110, 186, 190, 191, 212, 321, 327, 328, 352, 375, 580, 582, 589, 625, 727, 851, 977, 1077, 1118, 1147, 1243, 1304, 1314, 1712, 1796, 1797, 1805, 1916, 1917, 1918, 2007, 2217, 2219, 2245, 2257, 2258, 2280, 2342, 2376, 2377, 2433, 2539, 2540, 2623, 2638, 2670, 2675, 2676, 2713, 2760, 2761, 3806, 3824, 3870, 3924, 4169, 4263, 4281, 4313, 4383, 4418, 4470, 4494, 4555, 4795, 3010, 3112, 3136, 3150, 3171, 3352, 3365, 3509, 3513, 3543, 3571, 3702, 3712, 3713, 3725, 3727, 3734, 5, 8, 82, 185, 188, 192, 257, 276, 325, 326, 348, 351, 356, 598, 620, 658, 696, 705, 856, 985, 1048, 1122, 1148, 1149, 1168, 1179, 1239, 1354, 1462, 1615, 1659, 1670, 1816, 1847, 1913, 1959, 1972, 1993, 2213, 2218, 2268, 2274, 2275, 2282, 2387, 2573, 2609, 2783, 3871, 3879, 3909, 3926, 4093, 4128, 4142, 4190, 4230, 4282, 4308, 4471, 4498, 3033, 3079, 3155, 3156, 3161, 3219, 3503, 154, 259, 261, 347, 350, 353, 579, 602, 612, 702, 706, 982, 1078, 1352, 1559, 1799, 1891, 1953, 1956, 2266, 2279, 2345, 2392, 2538, 2586, 2828, 3829, 3876, 3942, 4109, 4467, 4554, 3409, 3502, 3504, 3512, 3531, 3542, 3710, 3731, 3751, 95, 196, 203, 204, 205, 242, 243, 346, 581, 586, 601, 615, 622, 626, 627, 691, 716, 725, 983, 986, 1085, 1089, 1161, 1174, 1204, 1349, 1442, 1477, 1654, 1655, 1657, 1692, 1817, 1857, 2196, 2271, 2281, 2382, 2404, 2412, 2919, 4095, 4125, 4126, 4216, 4241, 4279, 4381, 4437, 4478) } + internal val argNames: Map> by lazy { mapOf(5 to arrayOf("n"), 6 to arrayOf("n"), 7 to arrayOf("who"), 8 to arrayOf("title"), 65 to arrayOf("state"), 67 to arrayOf("listen"), 69 to arrayOf("listen"), 82 to arrayOf("version"), 83 to arrayOf("count", "plural"), 89 to arrayOf("size", "limit"), 90 to arrayOf("name"), 91 to arrayOf("dir"), 92 to arrayOf("dir"), 93 to arrayOf("name"), 94 to arrayOf("name"), 95 to arrayOf("path"), 96 to arrayOf("path"), 97 to arrayOf("name"), 108 to arrayOf("first"), 110 to arrayOf("n"), 136 to arrayOf("count", "plural"), 154 to arrayOf("tool"), 158 to arrayOf("n"), 160 to arrayOf("name"), 184 to arrayOf("pid", "cmd"), 185 to arrayOf("title", "ago"), 186 to arrayOf("name", "who", "n"), 188 to arrayOf("line"), 190 to arrayOf("n"), 191 to arrayOf("n"), 192 to arrayOf("n"), 196 to arrayOf("name"), 203 to arrayOf("when"), 204 to arrayOf("text", "when"), 205 to arrayOf("when"), 207 to arrayOf("count", "plural"), 208 to arrayOf("count", "plural"), 210 to arrayOf("took", "ago"), 211 to arrayOf("ago"), 212 to arrayOf("kind"), 214 to arrayOf("kind", "code", "why"), 218 to arrayOf("clock"), 221 to arrayOf("build"), 242 to arrayOf("step"), 243 to arrayOf("turn"), 244 to arrayOf("branch"), 257 to arrayOf("step", "total"), 258 to arrayOf("step", "total"), 259 to arrayOf("when"), 261 to arrayOf("tool"), 268 to arrayOf("count", "plural"), 269 to arrayOf("count", "total"), 274 to arrayOf("old", "new"), 276 to arrayOf("version"), 277 to arrayOf("count"), 278 to arrayOf("tag"), 283 to arrayOf("version"), 284 to arrayOf("old", "version"), 285 to arrayOf("version"), 288 to arrayOf("version"), 299 to arrayOf("project", "location"), 303 to arrayOf("account"), 304 to arrayOf("account"), 316 to arrayOf("n"), 318 to arrayOf("n"), 320 to arrayOf("minute"), 321 to arrayOf("time"), 322 to arrayOf("time"), 323 to arrayOf("clock"), 324 to arrayOf("clock", "took"), 325 to arrayOf("clock"), 326 to arrayOf("clock", "took"), 327 to arrayOf("clock"), 328 to arrayOf("clock", "took"), 329 to arrayOf("clock"), 330 to arrayOf("clock", "took"), 331 to arrayOf("clock"), 346 to arrayOf("target"), 347 to arrayOf("target"), 348 to arrayOf("target"), 349 to arrayOf("target"), 350 to arrayOf("target"), 351 to arrayOf("target"), 352 to arrayOf("target"), 353 to arrayOf("target"), 356 to arrayOf("name"), 375 to arrayOf("t"), 418 to arrayOf("minutes", "plural"), 452 to arrayOf("path"), 579 to arrayOf("count"), 580 to arrayOf("count"), 581 to arrayOf("title"), 582 to arrayOf("path"), 583 to arrayOf("path", "error"), 584 to arrayOf("first", "last", "count"), 585 to arrayOf("task", "step"), 586 to arrayOf("count"), 587 to arrayOf("path"), 588 to arrayOf("count", "plural"), 589 to arrayOf("label"), 590 to arrayOf("provider"), 591 to arrayOf("version"), 593 to arrayOf("key"), 594 to arrayOf("device"), 595 to arrayOf("kind", "device"), 596 to arrayOf("status"), 597 to arrayOf("kind", "title"), 598 to arrayOf("layer"), 599 to arrayOf("error"), 600 to arrayOf("page"), 601 to arrayOf("page", "kind", "total"), 602 to arrayOf("reason"), 603 to arrayOf("tag"), 604 to arrayOf("tag"), 605 to arrayOf("title"), 606 to arrayOf("title"), 607 to arrayOf("text", "time"), 608 to arrayOf("kind", "device"), 609 to arrayOf("device"), 610 to arrayOf("device"), 611 to arrayOf("word"), 612 to arrayOf("word", "kind", "count"), 613 to arrayOf("error"), 614 to arrayOf("count"), 615 to arrayOf("time", "relative", "rel", "zoned", "zone"), 616 to arrayOf("zone"), 617 to arrayOf("zone"), 618 to arrayOf("id", "state", "count", "age"), 619 to arrayOf("id"), 620 to arrayOf("name"), 621 to arrayOf("name"), 622 to arrayOf("clock", "count", "plural"), 623 to arrayOf("name"), 624 to arrayOf("name"), 625 to arrayOf("name"), 626 to arrayOf("count"), 627 to arrayOf("count"), 631 to arrayOf("name", "state"), 632 to arrayOf("author", "place", "state"), 633 to arrayOf("title", "state"), 648 to arrayOf("error"), 649 to arrayOf("error"), 650 to arrayOf("host"), 655 to arrayOf("email"), 658 to arrayOf("version"), 660 to arrayOf("first", "last", "count"), 661 to arrayOf("n"), 662 to arrayOf("n"), 691 to arrayOf("ref"), 696 to arrayOf("name"), 697 to arrayOf("name"), 699 to arrayOf("name"), 700 to arrayOf("name"), 701 to arrayOf("action"), 702 to arrayOf("label"), 703 to arrayOf("count", "plural"), 705 to arrayOf("path"), 706 to arrayOf("word", "kind", "count"), 707 to arrayOf("name"), 708 to arrayOf("name"), 709 to arrayOf("name"), 710 to arrayOf("name"), 711 to arrayOf("url"), 712 to arrayOf("count"), 713 to arrayOf("count"), 714 to arrayOf("device"), 715 to arrayOf("device"), 716 to arrayOf("count"), 717 to arrayOf("label"), 718 to arrayOf("label"), 719 to arrayOf("label"), 720 to arrayOf("title"), 721 to arrayOf("title"), 722 to arrayOf("state"), 723 to arrayOf("open", "kind"), 725 to arrayOf("count"), 726 to arrayOf("email"), 727 to arrayOf("email"), 851 to arrayOf("at", "count"), 855 to arrayOf("name"), 856 to arrayOf("name"), 905 to arrayOf("name"), 906 to arrayOf("name"), 977 to arrayOf("count"), 980 to arrayOf("name"), 981 to arrayOf("name", "count"), 982 to arrayOf("label", "n"), 983 to arrayOf("action"), 984 to arrayOf("count", "plural"), 985 to arrayOf("count"), 986 to arrayOf("waiting", "busy", "done"), 990 to arrayOf("count", "plural"), 1023 to arrayOf("name"), 1024 to arrayOf("name"), 1026 to arrayOf("seconds", "long"), 1027 to arrayOf("size", "triangles", "delayed", "waited", "built"), 1028 to arrayOf("size", "delayed", "waited"), 1044 to arrayOf("name"), 1047 to arrayOf("name"), 1048 to arrayOf("count"), 1075 to arrayOf("state"), 1076 to arrayOf("bytes"), 1077 to arrayOf("count"), 1078 to arrayOf("when"), 1079 to arrayOf("state", "name"), 1080 to arrayOf("name", "state"), 1081 to arrayOf("reason", "code"), 1084 to arrayOf("kind", "code"), 1085 to arrayOf("number"), 1089 to arrayOf("x", "y"), 1096 to arrayOf("state"), 1097 to arrayOf("label", "example"), 1109 to arrayOf("text"), 1117 to arrayOf("error"), 1118 to arrayOf("kind", "count"), 1121 to arrayOf("name"), 1122 to arrayOf("n"), 1147 to arrayOf("ago"), 1148 to arrayOf("name"), 1149 to arrayOf("kind", "place", "hub"), 1159 to arrayOf("label"), 1160 to arrayOf("word"), 1161 to arrayOf("count"), 1164 to arrayOf("hub"), 1166 to arrayOf("count"), 1167 to arrayOf("state"), 1168 to arrayOf("label"), 1169 to arrayOf("label"), 1174 to arrayOf("state", "text"), 1175 to arrayOf("text"), 1177 to arrayOf("question"), 1179 to arrayOf("label"), 1183 to arrayOf("title"), 1204 to arrayOf("count"), 1205 to arrayOf("name", "counts"), 1219 to arrayOf("n"), 1221 to arrayOf("mode"), 1238 to arrayOf("first", "last", "total"), 1239 to arrayOf("count"), 1242 to arrayOf("n"), 1243 to arrayOf("who", "name"), 1251 to arrayOf("name"), 1252 to arrayOf("when"), 1259 to arrayOf("why"), 1276 to arrayOf("name"), 1283 to arrayOf("kind"), 1284 to arrayOf("title"), 1285 to arrayOf("title"), 1286 to arrayOf("title"), 1287 to arrayOf("title"), 1292 to arrayOf("name"), 1302 to arrayOf("heard"), 1303 to arrayOf("out", "heard"), 1304 to arrayOf("heard"), 1312 to arrayOf("name", "mb"), 1314 to arrayOf("name"), 1317 to arrayOf("platform"), 1321 to arrayOf("heard", "out", "yes"), 1331 to arrayOf("name", "done", "total", "percent"), 1332 to arrayOf("name", "done"), 1333 to arrayOf("name"), 1334 to arrayOf("error"), 1336 to arrayOf("mb"), 1342 to arrayOf("mb"), 1345 to arrayOf("n"), 1346 to arrayOf("n"), 1349 to arrayOf("n"), 1350 to arrayOf("pct"), 1351 to arrayOf("px"), 1352 to arrayOf("key"), 1353 to arrayOf("key"), 1354 to arrayOf("why"), 1408 to arrayOf("n"), 1441 to arrayOf("title"), 1442 to arrayOf("note"), 1462 to arrayOf("title"), 1463 to arrayOf("more"), 1477 to arrayOf("bots"), 1488 to arrayOf("name"), 1489 to arrayOf("name", "time"), 1490 to arrayOf("name", "n"), 1491 to arrayOf("name", "time", "n"), 1492 to arrayOf("to"), 1493 to arrayOf("to", "step"), 1495 to arrayOf("note"), 1538 to arrayOf("why"), 1543 to arrayOf("e"), 1549 to arrayOf("max"), 1550 to arrayOf("secs", "max", "mib"), 1559 to arrayOf("path"), 1592 to arrayOf("secs"), 1615 to arrayOf("pct", "scope"), 1623 to arrayOf("n"), 1624 to arrayOf("n"), 1625 to arrayOf("n"), 1626 to arrayOf("n"), 1654 to arrayOf("d", "h"), 1655 to arrayOf("h", "m"), 1656 to arrayOf("m"), 1657 to arrayOf("window", "pct"), 1659 to arrayOf("when"), 1661 to arrayOf("label", "e"), 1663 to arrayOf("from", "to", "total"), 1667 to arrayOf("messages", "lines", "left"), 1669 to arrayOf("pct", "view", "max"), 1670 to arrayOf("pct"), 1671 to arrayOf("done", "total"), 1673 to arrayOf("n"), 1674 to arrayOf("n"), 1675 to arrayOf("time"), 1676 to arrayOf("view", "max"), 1677 to arrayOf("view", "max"), 1679 to arrayOf("more"), 1683 to arrayOf("n"), 1692 to arrayOf("n"), 1698 to arrayOf("page"), 1709 to arrayOf("title"), 1712 to arrayOf("n"), 1729 to arrayOf("name"), 1794 to arrayOf("line"), 1795 to arrayOf("quote"), 1796 to arrayOf("n"), 1797 to arrayOf("n"), 1798 to arrayOf("n"), 1799 to arrayOf("n"), 1800 to arrayOf("n"), 1805 to arrayOf("held"), 1806 to arrayOf("machine"), 1807 to arrayOf("machine"), 1815 to arrayOf("count", "total"), 1816 to arrayOf("count"), 1817 to arrayOf("n"), 1829 to arrayOf("name"), 1831 to arrayOf("n", "c", "total"), 1832 to arrayOf("n", "c"), 1833 to arrayOf("n", "c", "total", "before"), 1834 to arrayOf("n", "c", "before"), 1846 to arrayOf("name"), 1847 to arrayOf("path"), 1850 to arrayOf("file"), 1851 to arrayOf("path", "n"), 1852 to arrayOf("why"), 1853 to arrayOf("n"), 1854 to arrayOf("name"), 1855 to arrayOf("name"), 1856 to arrayOf("name"), 1857 to arrayOf("n"), 1858 to arrayOf("shown", "n"), 1861 to arrayOf("path"), 1863 to arrayOf("n"), 1872 to arrayOf("status"), 1889 to arrayOf("name", "pct"), 1890 to arrayOf("name", "mb"), 1891 to arrayOf("name"), 1892 to arrayOf("name", "why"), 1910 to arrayOf("machine"), 1913 to arrayOf("n"), 1914 to arrayOf("ref"), 1915 to arrayOf("ref", "sheet"), 1916 to arrayOf("name"), 1917 to arrayOf("name"), 1918 to arrayOf("file", "folder"), 1919 to arrayOf("name", "error"), 1920 to arrayOf("name", "status"), 1921 to arrayOf("name", "error"), 1923 to arrayOf("name"), 1926 to arrayOf("code"), 1927 to arrayOf("error"), 1930 to arrayOf("error"), 1931 to arrayOf("error"), 1935 to arrayOf("error"), 1953 to arrayOf("done", "of"), 1955 to arrayOf("why"), 1956 to arrayOf("path"), 1957 to arrayOf("error"), 1958 to arrayOf("secs"), 1959 to arrayOf("secs"), 1971 to arrayOf("code"), 1972 to arrayOf("code"), 1975 to arrayOf("state"), 1980 to arrayOf("hide", "copy", "paste"), 1981 to arrayOf("n"), 1984 to arrayOf("name"), 1985 to arrayOf("name", "folder"), 1986 to arrayOf("name"), 1987 to arrayOf("name", "percent"), 1993 to arrayOf("folder"), 2003 to arrayOf("w", "h"), 2007 to arrayOf("path"), 2010 to arrayOf("why"), 2011 to arrayOf("mb"), 2014 to arrayOf("n"), 2015 to arrayOf("delete", "undo"), 2016 to arrayOf("delete", "undo"), 2017 to arrayOf("undo"), 2038 to arrayOf("what", "secs"), 2039 to arrayOf("file", "holder"), 2046 to arrayOf("what"), 2047 to arrayOf("what"), 2048 to arrayOf("editor", "why"), 2067 to arrayOf("files"), 2077 to arrayOf("why"), 2079 to arrayOf("title"), 2080 to arrayOf("title"), 2081 to arrayOf("version"), 2082 to arrayOf("version", "size", "folder"), 2083 to arrayOf("version", "size", "folder"), 2092 to arrayOf("title"), 2093 to arrayOf("dir", "files"), 2099 to arrayOf("why"), 2101 to arrayOf("code"), 2115 to arrayOf("origin"), 2117 to arrayOf("why"), 2128 to arrayOf("dir"), 2129 to arrayOf("path"), 2130 to arrayOf("home", "other"), 2132 to arrayOf("path"), 2133 to arrayOf("code", "log"), 2134 to arrayOf("log"), 2136 to arrayOf("addr"), 2149 to arrayOf("home"), 2150 to arrayOf("addr"), 2165 to arrayOf("dir", "why"), 2166 to arrayOf("dir"), 2181 to arrayOf("phase"), 2183 to arrayOf("why"), 2184 to arrayOf("what"), 2185 to arrayOf("code"), 2191 to arrayOf("label"), 2196 to arrayOf("kind"), 2198 to arrayOf("project"), 2211 to arrayOf("what"), 2213 to arrayOf("when"), 2217 to arrayOf("n"), 2218 to arrayOf("n"), 2219 to arrayOf("n"), 2221 to arrayOf("agent"), 2222 to arrayOf("effort"), 2224 to arrayOf("n"), 2226 to arrayOf("model"), 2238 to arrayOf("word"), 2245 to arrayOf("more", "step"), 2249 to arrayOf("name"), 2253 to arrayOf("max", "skipped"), 2256 to arrayOf("name"), 2257 to arrayOf("n"), 2258 to arrayOf("name"), 2259 to arrayOf("name"), 2265 to arrayOf("n"), 2266 to arrayOf("name"), 2268 to arrayOf("price"), 2271 to arrayOf("name"), 2273 to arrayOf("name"), 2274 to arrayOf("name"), 2275 to arrayOf("name"), 2276 to arrayOf("text"), 2279 to arrayOf("key"), 2280 to arrayOf("key"), 2281 to arrayOf("pct"), 2282 to arrayOf("when"), 2293 to arrayOf("n", "upstream"), 2296 to arrayOf("mb"), 2306 to arrayOf("path"), 2307 to arrayOf("path"), 2329 to arrayOf("id"), 2333 to arrayOf("model"), 2334 to arrayOf("platform"), 2335 to arrayOf("version"), 2338 to arrayOf("version", "from", "into"), 2339 to arrayOf("version", "from"), 2342 to arrayOf("version", "path"), 2343 to arrayOf("version", "path"), 2344 to arrayOf("version", "pin", "from"), 2345 to arrayOf("path"), 2346 to arrayOf("version", "path"), 2347 to arrayOf("version", "path", "set"), 2361 to arrayOf("turns", "input", "cread", "cwrite", "output", "cost"), 2368 to arrayOf("tool"), 2369 to arrayOf("tool"), 2370 to arrayOf("tool", "word"), 2371 to arrayOf("tool", "word"), 2372 to arrayOf("tool"), 2373 to arrayOf("tool"), 2374 to arrayOf("due"), 2375 to arrayOf("due"), 2376 to arrayOf("due"), 2377 to arrayOf("due"), 2378 to arrayOf("zone"), 2379 to arrayOf("zone"), 2380 to arrayOf("zone"), 2381 to arrayOf("zone"), 2382 to arrayOf("n"), 2383 to arrayOf("who"), 2384 to arrayOf("n", "who"), 2385 to arrayOf("harness"), 2386 to arrayOf("path"), 2387 to arrayOf("path"), 2388 to arrayOf("path"), 2391 to arrayOf("error", "line"), 2392 to arrayOf("label"), 2400 to arrayOf("who"), 2401 to arrayOf("who"), 2402 to arrayOf("label", "left", "when"), 2403 to arrayOf("left"), 2404 to arrayOf("name", "left"), 2405 to arrayOf("used"), 2406 to arrayOf("used", "limit"), 2407 to arrayOf("used", "reason"), 2408 to arrayOf("used", "limit", "reason"), 2410 to arrayOf("provider"), 2411 to arrayOf("used", "window", "pct"), 2412 to arrayOf("rate"), 2422 to arrayOf("n", "r"), 2427 to arrayOf("time", "n"), 2431 to arrayOf("n", "m"), 2433 to arrayOf("pct"), 2434 to arrayOf("cost", "n"), 2438 to arrayOf("in", "out", "cread", "cwrite"), 2439 to arrayOf("in", "out", "cread", "cwrite", "n"), 2448 to arrayOf("turns", "input", "cread", "cwrite", "output"), 2449 to arrayOf("left", "when"), 2450 to arrayOf("left", "when"), 2451 to arrayOf("left", "when"), 2452 to arrayOf("left", "when"), 2476 to arrayOf("n"), 2499 to arrayOf("when"), 2506 to arrayOf("phrase", "now"), 2517 to arrayOf("s"), 2523 to arrayOf("now"), 2524 to arrayOf("now", "nudge", "sent", "undone"), 2534 to arrayOf("e"), 2535 to arrayOf("a", "ams", "b", "bms"), 2536 to arrayOf("ms"), 2537 to arrayOf("e"), 2538 to arrayOf("t"), 2539 to arrayOf("t"), 2540 to arrayOf("t"), 2546 to arrayOf("why"), 2556 to arrayOf("apps"), 2566 to arrayOf("n"), 2567 to arrayOf("n", "k"), 2572 to arrayOf("stt", "conf"), 2573 to arrayOf("words"), 2583 to arrayOf("into"), 2586 to arrayOf("origin"), 2598 to arrayOf("url"), 2600 to arrayOf("url"), 2608 to arrayOf("i", "n"), 2609 to arrayOf("d", "n"), 2618 to arrayOf("version"), 2619 to arrayOf("version"), 2620 to arrayOf("version"), 2623 to arrayOf("path"), 2631 to arrayOf("addr"), 2635 to arrayOf("label"), 2637 to arrayOf("label"), 2638 to arrayOf("label"), 2642 to arrayOf("label"), 2647 to arrayOf("from"), 2664 to arrayOf("done", "of"), 2670 to arrayOf("n"), 2671 to arrayOf("t", "m"), 2672 to arrayOf("m"), 2673 to arrayOf("b", "m"), 2674 to arrayOf("r", "p"), 2675 to arrayOf("n"), 2676 to arrayOf("n"), 2677 to arrayOf("n"), 2678 to arrayOf("n"), 2681 to arrayOf("n"), 2683 to arrayOf("n"), 2691 to arrayOf("n"), 2697 to arrayOf("name", "gb", "path"), 2699 to arrayOf("path", "why"), 2701 to arrayOf("names"), 2703 to arrayOf("why"), 2704 to arrayOf("p", "pn", "t", "tn", "e", "en"), 2705 to arrayOf("done", "total"), 2706 to arrayOf("n"), 2707 to arrayOf("what"), 2708 to arrayOf("n"), 2709 to arrayOf("n"), 2712 to arrayOf("what"), 2713 to arrayOf("n"), 2715 to arrayOf("why", "from"), 2716 to arrayOf("why"), 2722 to arrayOf("path"), 2723 to arrayOf("path", "who"), 2724 to arrayOf("path"), 2725 to arrayOf("path", "cmd"), 2726 to arrayOf("version", "path"), 2727 to arrayOf("version", "path"), 2728 to arrayOf("version", "path", "who"), 2729 to arrayOf("version", "path"), 2730 to arrayOf("version", "path", "cmd"), 2733 to arrayOf("cmd"), 2743 to arrayOf("name", "version", "path"), 2744 to arrayOf("path", "why"), 2745 to arrayOf("name"), 2747 to arrayOf("version", "cli"), 2748 to arrayOf("cli"), 2750 to arrayOf("version"), 2751 to arrayOf("version"), 2753 to arrayOf("version"), 2755 to arrayOf("version"), 2757 to arrayOf("computer"), 2758 to arrayOf("version", "cli"), 2759 to arrayOf("cli"), 2760 to arrayOf("version", "cli"), 2761 to arrayOf("cli"), 2783 to arrayOf("n"), 2788 to arrayOf("code"), 2790 to arrayOf("e"), 2803 to arrayOf("n"), 2808 to arrayOf("channel"), 2822 to arrayOf("project"), 2828 to arrayOf("n"), 2840 to arrayOf("m"), 2852 to arrayOf("m"), 2855 to arrayOf("m"), 2862 to arrayOf("pages"), 2864 to arrayOf("name"), 2867 to arrayOf("name"), 2876 to arrayOf("d", "n"), 2897 to arrayOf("n", "tools"), 2898 to arrayOf("n", "tools", "d"), 2899 to arrayOf("n", "d"), 2900 to arrayOf("n", "what"), 2901 to arrayOf("n", "d", "what"), 2905 to arrayOf("head"), 2911 to arrayOf("name", "path"), 2917 to arrayOf("page", "net", "near"), 2918 to arrayOf("page", "what"), 2919 to arrayOf("ref"), 2923 to arrayOf("page"), 2946 to arrayOf("n"), 2947 to arrayOf("n"), 2948 to arrayOf("n"), 2950 to arrayOf("hub"), 2972 to arrayOf("project"), 2974 to arrayOf("n"), 2975 to arrayOf("n"), 2976 to arrayOf("word"), 2977 to arrayOf("n"), 2995 to arrayOf("name"), 3003 to arrayOf("answer"), 3008 to arrayOf("why"), 3010 to arrayOf("hub"), 3016 to arrayOf("from", "to"), 3023 to arrayOf("project"), 3033 to arrayOf("name"), 3037 to arrayOf("n"), 3043 to arrayOf("code"), 3044 to arrayOf("hub"), 3045 to arrayOf("hub"), 3046 to arrayOf("hub"), 3060 to arrayOf("n"), 3061 to arrayOf("n"), 3077 to arrayOf("status"), 3079 to arrayOf("status"), 3108 to arrayOf("project"), 3112 to arrayOf("code"), 3114 to arrayOf("why"), 3122 to arrayOf("title"), 3128 to arrayOf("title"), 3130 to arrayOf("q"), 3131 to arrayOf("title"), 3136 to arrayOf("room"), 3140 to arrayOf("q"), 3150 to arrayOf("title"), 3155 to arrayOf("n"), 3156 to arrayOf("n"), 3161 to arrayOf("at"), 3169 to arrayOf("size"), 3171 to arrayOf("n", "total"), 3188 to arrayOf("n"), 3189 to arrayOf("what"), 3192 to arrayOf("device"), 3193 to arrayOf("device"), 3202 to arrayOf("word", "count"), 3203 to arrayOf("heard"), 3215 to arrayOf("files"), 3216 to arrayOf("files"), 3219 to arrayOf("name"), 3247 to arrayOf("n"), 3248 to arrayOf("n"), 3259 to arrayOf("n"), 3293 to arrayOf("root"), 3294 to arrayOf("path"), 3317 to arrayOf("name"), 3320 to arrayOf("until"), 3321 to arrayOf("error"), 3328 to arrayOf("url"), 3332 to arrayOf("name"), 3333 to arrayOf("name"), 3341 to arrayOf("code", "hub", "until"), 3342 to arrayOf("url"), 3346 to arrayOf("kinds"), 3347 to arrayOf("address"), 3349 to arrayOf("address"), 3352 to arrayOf("url"), 3353 to arrayOf("url"), 3354 to arrayOf("url"), 3355 to arrayOf("url", "via"), 3360 to arrayOf("name"), 3361 to arrayOf("url", "check", "left"), 3363 to arrayOf("check"), 3364 to arrayOf("address"), 3365 to arrayOf("name"), 3366 to arrayOf("error"), 3367 to arrayOf("url"), 3368 to arrayOf("url"), 3375 to arrayOf("code", "address", "left"), 3381 to arrayOf("name"), 3382 to arrayOf("name"), 3393 to arrayOf("address"), 3400 to arrayOf("code", "body"), 3403 to arrayOf("code", "body"), 3409 to arrayOf("window", "used"), 3410 to arrayOf("window", "used", "when"), 3411 to arrayOf("window", "used"), 3412 to arrayOf("window", "used", "when"), 3413 to arrayOf("provider"), 3425 to arrayOf("label"), 3426 to arrayOf("when"), 3428 to arrayOf("provider"), 3429 to arrayOf("provider", "title", "why"), 3449 to arrayOf("reason"), 3457 to arrayOf("code"), 3466 to arrayOf("name"), 3469 to arrayOf("version"), 3470 to arrayOf("version"), 3471 to arrayOf("version"), 3473 to arrayOf("version"), 3474 to arrayOf("version"), 3475 to arrayOf("version"), 3476 to arrayOf("version", "why"), 3477 to arrayOf("version"), 3479 to arrayOf("code"), 3495 to arrayOf("name"), 3502 to arrayOf("count"), 3503 to arrayOf("title"), 3504 to arrayOf("name"), 3507 to arrayOf("n", "holder"), 3508 to arrayOf("n", "title"), 3509 to arrayOf("title"), 3512 to arrayOf("n"), 3513 to arrayOf("n"), 3514 to arrayOf("n"), 3515 to arrayOf("n"), 3516 to arrayOf("harness", "typed", "type", "remote", "host", "wt", "branch"), 3526 to arrayOf("pid"), 3531 to arrayOf("left"), 3532 to arrayOf("left"), 3538 to arrayOf("left"), 3539 to arrayOf("left"), 3540 to arrayOf("left"), 3541 to arrayOf("left"), 3542 to arrayOf("label", "left"), 3543 to arrayOf("when"), 3544 to arrayOf("used"), 3545 to arrayOf("used", "limit"), 3567 to arrayOf("tracking"), 3571 to arrayOf("total"), 3572 to arrayOf("price"), 3573 to arrayOf("price"), 3578 to arrayOf("n"), 3579 to arrayOf("parts"), 3580 to arrayOf("note"), 3581 to arrayOf("error"), 3582 to arrayOf("error", "parts"), 3587 to arrayOf("state"), 3588 to arrayOf("name", "path"), 3589 to arrayOf("name", "path", "why"), 3591 to arrayOf("code"), 3595 to arrayOf("detail"), 3597 to arrayOf("why"), 3598 to arrayOf("parts"), 3601 to arrayOf("build", "to"), 3602 to arrayOf("build"), 3603 to arrayOf("build", "skip"), 3605 to arrayOf("why"), 3606 to arrayOf("why"), 3607 to arrayOf("build"), 3608 to arrayOf("build", "why"), 3609 to arrayOf("build"), 3610 to arrayOf("build"), 3614 to arrayOf("build"), 3615 to arrayOf("build"), 3617 to arrayOf("build"), 3624 to arrayOf("build"), 3658 to arrayOf("step"), 3659 to arrayOf("p", "pt", "t", "tt", "e", "et"), 3660 to arrayOf("done", "total"), 3661 to arrayOf("n"), 3662 to arrayOf("n"), 3663 to arrayOf("n"), 3668 to arrayOf("n"), 3671 to arrayOf("why"), 3672 to arrayOf("why", "from"), 3673 to arrayOf("error"), 3675 to arrayOf("n"), 3676 to arrayOf("n"), 3680 to arrayOf("n"), 3683 to arrayOf("name", "gb", "path"), 3684 to arrayOf("path", "why"), 3685 to arrayOf("names"), 3687 to arrayOf("why"), 3698 to arrayOf("n", "total"), 3702 to arrayOf("title"), 3704 to arrayOf("n"), 3708 to arrayOf("name"), 3709 to arrayOf("title"), 3710 to arrayOf("note"), 3712 to arrayOf("machine"), 3713 to arrayOf("machines"), 3714 to arrayOf("machine"), 3725 to arrayOf("n"), 3727 to arrayOf("n"), 3731 to arrayOf("name"), 3734 to arrayOf("name"), 3751 to arrayOf("why"), 3757 to arrayOf("project"), 3798 to arrayOf("path"), 3799 to arrayOf("path"), 3801 to arrayOf("have", "total"), 3806 to arrayOf("n"), 3815 to arrayOf("hub"), 3818 to arrayOf("title"), 3822 to arrayOf("project"), 3823 to arrayOf("project"), 3824 to arrayOf("n"), 3825 to arrayOf("hub"), 3827 to arrayOf("n"), 3828 to arrayOf("n"), 3829 to arrayOf("model"), 3835 to arrayOf("name"), 3854 to arrayOf("word"), 3860 to arrayOf("answer"), 3870 to arrayOf("version", "build"), 3871 to arrayOf("hub"), 3876 to arrayOf("name"), 3879 to arrayOf("when", "who", "mark"), 3883 to arrayOf("who"), 3887 to arrayOf("time"), 3888 to arrayOf("address"), 3890 to arrayOf("kind", "name"), 3905 to arrayOf("title"), 3906 to arrayOf("query"), 3909 to arrayOf("room"), 3910 to arrayOf("query"), 3912 to arrayOf("n"), 3913 to arrayOf("n"), 3914 to arrayOf("n"), 3920 to arrayOf("size"), 3924 to arrayOf("n"), 3925 to arrayOf("n"), 3926 to arrayOf("n"), 3940 to arrayOf("status"), 3942 to arrayOf("status"), 4093 to arrayOf("code"), 4095 to arrayOf("n"), 4097 to arrayOf("why"), 4109 to arrayOf("done", "of"), 4113 to arrayOf("thread"), 4116 to arrayOf("n"), 4124 to arrayOf("title"), 4125 to arrayOf("note"), 4126 to arrayOf("label"), 4127 to arrayOf("machine"), 4128 to arrayOf("machine"), 4135 to arrayOf("at", "total"), 4136 to arrayOf("at", "total"), 4140 to arrayOf("machine"), 4141 to arrayOf("machine"), 4142 to arrayOf("machines"), 4144 to arrayOf("device"), 4151 to arrayOf("price"), 4152 to arrayOf("price"), 4159 to arrayOf("home"), 4164 to arrayOf("from"), 4166 to arrayOf("note"), 4167 to arrayOf("note"), 4169 to arrayOf("v"), 4170 to arrayOf("v"), 4171 to arrayOf("v", "who"), 4173 to arrayOf("who"), 4174 to arrayOf("v"), 4176 to arrayOf("v", "cmd"), 4177 to arrayOf("cmd"), 4182 to arrayOf("v", "path"), 4183 to arrayOf("v", "note"), 4184 to arrayOf("v"), 4189 to arrayOf("tool"), 4190 to arrayOf("tool"), 4215 to arrayOf("n", "w"), 4216 to arrayOf("why"), 4217 to arrayOf("state", "why"), 4229 to arrayOf("project"), 4230 to arrayOf("n"), 4241 to arrayOf("why"), 4247 to arrayOf("name"), 4258 to arrayOf("project"), 4263 to arrayOf("n"), 4271 to arrayOf("names"), 4279 to arrayOf("dest"), 4281 to arrayOf("repo"), 4282 to arrayOf("repo"), 4284 to arrayOf("url"), 4308 to arrayOf("group"), 4312 to arrayOf("project"), 4313 to arrayOf("n"), 4314 to arrayOf("n"), 4315 to arrayOf("n"), 4323 to arrayOf("n"), 4380 to arrayOf("n"), 4381 to arrayOf("n"), 4382 to arrayOf("a", "b"), 4383 to arrayOf("n"), 4385 to arrayOf("parts", "lines"), 4386 to arrayOf("n"), 4417 to arrayOf("what", "project", "fab"), 4418 to arrayOf("rev", "day"), 4426 to arrayOf("n"), 4437 to arrayOf("layer"), 4438 to arrayOf("n"), 4443 to arrayOf("board"), 4455 to arrayOf("others"), 4456 to arrayOf("must", "should", "notes"), 4457 to arrayOf("id", "w"), 4467 to arrayOf("what"), 4470 to arrayOf("why"), 4471 to arrayOf("why"), 4478 to arrayOf("n"), 4494 to arrayOf("price", "n"), 4495 to arrayOf("n", "need"), 4496 to arrayOf("n"), 4497 to arrayOf("n"), 4498 to arrayOf("cost"), 4499 to arrayOf("cost"), 4512 to arrayOf("day", "n"), 4513 to arrayOf("day"), 4514 to arrayOf("cost", "n", "lines"), 4515 to arrayOf("stock", "price"), 4516 to arrayOf("lines"), 4537 to arrayOf("host"), 4548 to arrayOf("n"), 4549 to arrayOf("a", "b"), 4550 to arrayOf("n"), 4551 to arrayOf("n"), 4554 to arrayOf("day"), 4555 to arrayOf("n"), 4596 to arrayOf("turn"), 4710 to arrayOf("text"), 4713 to arrayOf("repo", "dest"), 4714 to arrayOf("repo", "dest"), 4715 to arrayOf("repo"), 4720 to arrayOf("dir"), 4721 to arrayOf("dir"), 4725 to arrayOf("editor", "job", "secs"), 4726 to arrayOf("editor", "secs"), 4727 to arrayOf("editor"), 4744 to arrayOf("time"), 4750 to arrayOf("status"), 4758 to arrayOf("time"), 4759 to arrayOf("time", "dur"), 4762 to arrayOf("answer"), 4766 to arrayOf("type"), 4767 to arrayOf("max"), 4795 to arrayOf("bytes", "tokens")) } val common_cancel: String get() = Tr.s(0) val common_delete: String get() = Tr.s(1) @@ -27310,4 +27449,32 @@ object Msg { fun web_composer_unsupported(type: Any): String = Tr.f(4766, arrayOf(type)) fun web_composer_maximages(max: Any): String = Tr.f(4767, arrayOf(max)) val web_logout_failed: String get() = Tr.s(4768) + val thread_context_title: String get() = Tr.s(4769) + val thread_context_instructions: String get() = Tr.s(4770) + val thread_context_system: String get() = Tr.s(4771) + val thread_context_skills: String get() = Tr.s(4772) + val thread_context_mcp: String get() = Tr.s(4773) + val thread_context_mcp_short: String get() = Tr.s(4774) + val thread_context_reading: String get() = Tr.s(4775) + val thread_context_none_instructions: String get() = Tr.s(4776) + val thread_context_none_mcp: String get() = Tr.s(4777) + val thread_context_native_note: String get() = Tr.s(4778) + val thread_context_copy: String get() = Tr.s(4779) + val thread_context_copied: String get() = Tr.s(4780) + val thread_context_base: String get() = Tr.s(4781) + val thread_context_injected_label: String get() = Tr.s(4782) + val thread_context_index: String get() = Tr.s(4783) + val thread_context_scope_user: String get() = Tr.s(4784) + val thread_context_scope_bundled: String get() = Tr.s(4785) + val thread_context_native: String get() = Tr.s(4786) + val thread_context_injected: String get() = Tr.s(4787) + val thread_context_cross: String get() = Tr.s(4788) + val thread_context_explicit: String get() = Tr.s(4789) + val thread_context_untrusted: String get() = Tr.s(4790) + val thread_context_invalid: String get() = Tr.s(4791) + val thread_context_trust: String get() = Tr.s(4792) + val thread_context_enable: String get() = Tr.s(4793) + val thread_context_disable: String get() = Tr.s(4794) + fun thread_context_size(bytes: Any, tokens: Any): String = Tr.f(4795, arrayOf(bytes, tokens)) + val thread_context_unreachable: String get() = Tr.s(4796) } diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/ThreadContext.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/ThreadContext.kt new file mode 100644 index 0000000000..65f06a0817 --- /dev/null +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/ThreadContext.kt @@ -0,0 +1,155 @@ +package dev.backplane.mobile + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import kotlinx.coroutines.launch +import org.json.JSONObject + +private fun JSONObject.rows(key: String): List = + optJSONArray(key)?.let { a -> (0 until a.length()).mapNotNull(a::optJSONObject) }.orEmpty() + +@Composable +internal fun ThreadContextSheet(thread: String, close: () -> Unit) { + val scope = rememberCoroutineScope() + val context = LocalContext.current + var snapshot by remember(thread) { mutableStateOf(null) } + var tab by remember(thread) { mutableIntStateOf(0) } + var expanded by remember(thread) { mutableStateOf("") } + var busy by remember(thread) { mutableStateOf(false) } + var error by remember(thread) { mutableStateOf("") } + suspend fun load(action: String = "", config: JSONObject? = null) { + if (busy) return + busy = true + error = "" + try { + val params = JSONObject().put("thread", thread) + if (config != null) params.put("path", config.optString("path")).put("sha256", config.optString("sha256")).put("action", action) + snapshot = DataClient.call(if (config == null) "thread.context" else "thread.context.mcp", params) + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (e: Exception) { + error = e.message.orEmpty() + } finally { + busy = false + } + } + LaunchedEffect(thread) { load() } + Dialog(onDismissRequest = close, properties = DialogProperties(usePlatformDefaultWidth = false)) { + Column(Modifier.fillMaxWidth(.95f).fillMaxHeight(.9f).background(dcs.surface).padding(12.dp)) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text(Tr.t("Context & Prompt"), Modifier.weight(1f), color = dcs.onSurface) + TextButton(onClick = { scope.launch { load() } }, enabled = !busy) { Text(Tr.t("Refresh")) } + TextButton(onClick = close) { Text(Tr.t("Close")) } + } + snapshot?.optString("cwd")?.let { DMono(it, dcs.onSurfaceVariant, 11) } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + listOf("Instructions", "Prompt", "Skills", "MCPs").forEachIndexed { index, title -> + TextButton(onClick = { tab = index }, modifier = Modifier.weight(1f)) { + Text(Tr.t(title), color = if (tab == index) dcs.primary else dcs.onSurfaceVariant) + } + } + } + DLine() + if (busy) DMono(Tr.t("Reading thread context…"), dcs.onSurfaceVariant, 11) + if (error.isNotEmpty()) Text(error, color = dcs.error) + val data = snapshot + if (data != null) key(tab) { + LazyColumn(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) { + when (tab) { + 0 -> { + val files = data.rows("instructions") + if (files.isEmpty()) item { Text(Tr.t("No project instructions found.")) } + files.forEach { row -> item { + val path = row.optString("path") + Column(Modifier.fillMaxWidth().clickable { expanded = if (expanded == path) "" else path }.padding(6.dp)) { + ContextStatus(path, row.optString("status")) + DMono(Msg.thread_context_size(row.optLong("bytes"), row.optLong("estimated_tokens")), dcs.onSurfaceVariant, 11) + if (expanded == path) { + ContextCode(row.optString("preview")) + if (row.optString("note").isNotEmpty()) Text(row.optString("note")) + } + } + DLine() + } } + } + 1 -> { + item { + Text(Tr.t("Backplane’s launch prompt. Native files are loaded by the provider.")) + TextButton(onClick = { + val clipboard = context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager + clipboard.setPrimaryClip(android.content.ClipData.newPlainText("Backplane", data.optString("prompt"))) + }) { Text(Tr.t("Copy prompt")) } + } + val sections = data.optJSONObject("sections") + listOf("base" to "Backplane", "instructions" to "Injected project instructions", "skills" to "Available skills index").forEach { (key, label) -> + val text = sections?.optString(key).orEmpty() + if (text.isNotEmpty()) item { Text(Tr.t(label), color = dcs.primary); ContextCode(text) } + } + } + 2 -> listOf("Project", "User", "Bundled").forEach { group -> + val skills = data.rows("skills").filter { it.optString("scope") == group } + if (skills.isNotEmpty()) item { Text(Tr.t(group), color = dcs.primary) } + skills.forEach { row -> item { + ContextStatus(row.optString("name"), row.optString("status")) + Text(row.optString("description")) + DMono(listOf("source", "provider", "model").map { row.optString(it) }.filter { it.isNotEmpty() }.joinToString(" · "), dcs.onSurfaceVariant, 11) + DMono(row.optString("path"), dcs.onSurfaceVariant, 10) + DLine() + } } + } + else -> { + val configs = data.rows("mcp") + if (configs.isEmpty()) item { Text(Tr.t("No project MCP configurations found.")) } + configs.forEach { config -> item { + val state = config.optString("state") + ContextStatus(config.optString("path"), state) + config.rows("servers").forEach { server -> + ContextStatus(server.optString("name"), server.optString("status")) + val args = server.optJSONArray("args") + val argv = listOf(server.optString("command")) + (0 until (args?.length() ?: 0)).map { args!!.optString(it) } + ContextCode(server.optString("url").ifEmpty { argv.joinToString(" ") { JSONObject.quote(it) } }) + } + if (config.optString("error").isNotEmpty()) Text(config.optString("error"), color = dcs.error) + val action = when (state) { + "Untrusted" -> "trust" to "Trust and enable" + "Enabled" -> "disable" to "Disable" + "Disabled" -> "enable" to "Enable" + else -> null + } + if (action != null) TextButton(onClick = { scope.launch { load(action.first, config) } }, enabled = !busy) { Text(Tr.t(action.second)) } + DLine() + } } + } + } + } + } + } + } +} + +@Composable +private fun ContextStatus(title: String, status: String) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + Text(title, Modifier.weight(1f), color = dcs.onSurface) + DMono(Tr.t(status), if (status == "Native" || status == "Enabled") dcs.primary else dcs.onSurfaceVariant, 11) + } +} + +@Composable +private fun ContextCode(text: String) { + SelectionContainer { + DMono(text, dcs.onSurface, 12, Modifier.fillMaxWidth().background(dcs.surfaceVariant).padding(8.dp)) + } +} diff --git a/mobile/ios/Backplane/DataViews.swift b/mobile/ios/Backplane/DataViews.swift index 85444c21eb..9288ce9e2d 100644 --- a/mobile/ios/Backplane/DataViews.swift +++ b/mobile/ios/Backplane/DataViews.swift @@ -776,6 +776,7 @@ struct DataThreadView: View { @State private var reviewing = false @State private var buy: DBuy? // Buy it, when the hub offers it for this thread @State private var buying = false + @State private var contextOpen = false @State private var finding = false // Search in thread @State private var findGo: String? // the message to go to (Search in thread, the find bar, a search hit), read older pages until it is held @State private var mark: String? // the message marked there, until the find bar closes @@ -903,6 +904,7 @@ struct DataThreadView: View { // the review bar (#1305): asked again when the thread's entries or turn change (a review starts with a turn; a press anywhere logs a line) .task(id: "r|\(list.count)|\(thread?.state ?? "")|\(client.conn == .online)") { if client.has("reviewmode") { if let r = try? await client.review(id) { review = r } } else { review = nil } } .task(id: "\(thread?.state ?? "")|\(client.conn == .online)") { if client.conn == .online, thread?.state != "working" { buy = await client.buyOf(id) } } + .sheet(isPresented: $contextOpen) { DThreadContext(client: client, thread: id) } .background(BackplaneDesign.background) .dataBar(thread?.title.isEmpty == false ? thread!.title : Tr.t("Thread")) // Run in terminal in this chat (a project's thread, a bot's chat, the uberbot's): its own shell (term.new {chat}) @@ -924,6 +926,7 @@ struct DataThreadView: View { // the find bar when the hub has `find`; else the older sheet of hits if client.has("find") { Button(Tr.k("ios.find.bar"), systemImage: "magnifyingglass") { findOpen = true; findFocus = true } } else if client.has("search") { Button(Tr.t("Search in thread"), systemImage: "magnifyingglass") { finding = true } } + if client.has("threadContext") { Button(Tr.t("Context & Prompt"), systemImage: "doc.text.magnifyingglass") { contextOpen = true } } DataThreadActions(client: client, thread: t, renaming: $renaming, deleting: $deleting) } label: { Image(systemName: "ellipsis").foregroundStyle(BackplaneDesign.dim) } .accessibilityLabel(Tr.t("Thread actions")).accessibilityIdentifier("data.thread.more") @@ -1748,3 +1751,151 @@ struct MemoryBar: View { }.accessibilityElement(children: .combine).accessibilityIdentifier("data.thread.memory") } } + +private struct DThreadContext: View { + struct Snapshot: Decodable { + struct Instruction: Decodable { let path: String; let bytes: Int; let estimated_tokens: Int; let status: String; let preview: String; let note: String } + struct Skill: Decodable { let name: String; let description: String; let scope: String; let status: String; let path: String; let source: String; let provider: String; let model: String } + struct Server: Decodable { let name: String; let command: String; let args: [String]; let url: String; let cwd: String; let status: String } + struct Config: Decodable { let path: String; let sha256: String; let state: String; let error: String; let servers: [Server] } + struct Sections: Decodable { let base: String; let instructions: String; let skills: String } + let cwd: String + let instructions: [Instruction] + let skills: [Skill] + let mcp: [Config] + let sections: Sections + let prompt: String + } + + let client: DataClient + let thread: String + @Environment(\.dismiss) private var dismiss + @State private var data: Snapshot? + @State private var selected = 0 + @State private var busy = false + @State private var problem = "" + + var body: some View { + NavigationStack { + VStack(spacing: 0) { + Picker(Tr.t("Context & Prompt"), selection: $selected) { + Text(Tr.t("Instructions")).tag(0) + Text(Tr.t("Prompt")).tag(1) + Text(Tr.t("Skills")).tag(2) + Text(Tr.t("MCPs")).tag(3) + } + .pickerStyle(.segmented) + .padding() + if busy { ProgressView().padding(.bottom, 8) } + if !problem.isEmpty { Text(problem).foregroundStyle(.red).padding() } + if let data { + List { + switch selected { + case 0: + if data.instructions.isEmpty { Text(Tr.t("No project instructions found.")) } + ForEach(data.instructions, id: \.path) { item in + DisclosureGroup { + code(item.preview) + if !item.note.isEmpty { Text(item.note).font(.caption).foregroundStyle(.secondary) } + } label: { + VStack(alignment: .leading, spacing: 4) { + summary(URL(fileURLWithPath: item.path).lastPathComponent, item.status) + Text(item.path).font(.caption).foregroundStyle(.secondary) + Text(Tr.thread_context_size(bytes: String(item.bytes), tokens: String(item.estimated_tokens))).font(.caption2).foregroundStyle(.secondary) + } + } + } + case 1: + Text(Tr.t("Backplane’s launch prompt. Native files are loaded by the provider.")).foregroundStyle(.secondary) + Button(Tr.t("Copy prompt"), systemImage: "doc.on.doc") { UIPasteboard.general.string = data.prompt } + promptSection("Backplane", data.sections.base) + promptSection("Injected project instructions", data.sections.instructions) + promptSection("Available skills index", data.sections.skills) + case 2: + ForEach(["Project", "User", "Bundled"], id: \.self) { scope in + let items = data.skills.filter { $0.scope == scope } + if !items.isEmpty { + Section(Tr.t(scope)) { + ForEach(items, id: \.path) { item in + VStack(alignment: .leading, spacing: 5) { + summary(item.name, item.status) + Text(item.description).font(.subheadline) + Text([item.source, item.provider, item.model].filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary) + Text(item.path).font(.caption2).foregroundStyle(.secondary).textSelection(.enabled) + } + } + } + } + } + default: + if data.mcp.isEmpty { Text(Tr.t("No project MCP configurations found.")) } + ForEach(data.mcp, id: \.path) { config in + Section { + ForEach(config.servers, id: \.name) { server in + VStack(alignment: .leading, spacing: 6) { + summary(server.name, server.status) + code(server.url.isEmpty ? ([server.command] + server.args).map { String(reflecting: $0) }.joined(separator: " ") : server.url) + if !server.cwd.isEmpty { Text(server.cwd).font(.caption2).foregroundStyle(.secondary) } + } + } + if !config.error.isEmpty { Text(config.error).font(.caption).foregroundStyle(.red) } + if let action = action(for: config.state) { + Button(Tr.t(action.label)) { Task { await load(action: action.id, config: config) } }.disabled(busy) + } + } header: { + Text(config.path).textCase(nil) + } + } + } + } + .listStyle(.insetGrouped) + } else { Spacer() } + } + .navigationTitle(Tr.t("Context & Prompt")) + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button(Tr.t("Close")) { dismiss() } } + ToolbarItem(placement: .primaryAction) { Button { Task { await load() } } label: { Image(systemName: "arrow.clockwise") }.accessibilityLabel(Tr.t("Refresh")).disabled(busy) } + } + .task { await load() } + } + } + + private func summary(_ title: String, _ status: String) -> some View { + HStack(alignment: .firstTextBaseline) { + Text(title).font(.subheadline.weight(.semibold)) + Spacer(minLength: 8) + Text(Tr.t(status)).font(.caption.weight(.medium)) + .foregroundStyle(status == "Native" || status == "Enabled" ? BackplaneDesign.accent : Color(uiColor: .secondaryLabel)) + } + } + + private func code(_ text: String) -> some View { + Text(verbatim: text).font(.system(.caption, design: .monospaced)).textSelection(.enabled) + } + + @ViewBuilder private func promptSection(_ label: String, _ text: String) -> some View { + if !text.isEmpty { Section(Tr.t(label)) { code(text) } } + } + + private func action(for state: String) -> (id: String, label: String)? { + switch state { + case "Untrusted": ("trust", "Trust and enable") + case "Enabled": ("disable", "Disable") + case "Disabled": ("enable", "Enable") + default: nil + } + } + + @MainActor private func load(action: String? = nil, config: Snapshot.Config? = nil) async { + guard !busy else { return } + busy = true + problem = "" + defer { busy = false } + do { + if let action, let config { + data = try await client.call("thread.context.mcp", ["thread": thread, "action": action, "path": config.path, "sha256": config.sha256]) + } else { data = try await client.call("thread.context", ["thread": thread]) } + } catch { problem = error.localizedDescription } + } +} diff --git a/mobile/ios/Shared/TrCatalog.swift b/mobile/ios/Shared/TrCatalog.swift index cbd342df29..aaeb6fc547 100644 --- a/mobile/ios/Shared/TrCatalog.swift +++ b/mobile/ios/Shared/TrCatalog.swift @@ -4772,6 +4772,34 @@ web.composer.voice Voice dictation 音声入力 Dictado por voz web.composer.unsupported Unsupported image type: {type} 未対応の画像形式です: {type} Tipo de imagen no compatible: {type} web.composer.maximages At most {max} images per message. 1 件のメッセージに添付できる画像は最大 {max} 枚です。 Como máximo {max} imágenes por mensaje. web.logout.failed Could not confirm sign-out. Try again. サインアウトを確認できませんでした。もう一度お試しください。 No se pudo confirmar el cierre de sesión. Inténtalo de nuevo. +thread.context.title Context & Prompt コンテキストとプロンプト Contexto e instrucciones +thread.context.instructions Instructions 指示 Instrucciones +thread.context.system System Prompt システムプロンプト Instrucciones del sistema +thread.context.skills Skills スキル Habilidades +thread.context.mcp Project MCPs プロジェクトの MCP MCP del proyecto +thread.context.mcp.short MCPs MCP MCP +thread.context.reading Reading thread context… スレッドのコンテキストを読み込み中… Leyendo el contexto del hilo… +thread.context.none.instructions No project instructions found. プロジェクトの指示が見つかりません。 No se encontraron instrucciones del proyecto. +thread.context.none.mcp No project MCP configurations found. プロジェクトの MCP 設定が見つかりません。 No se encontraron configuraciones MCP del proyecto. +thread.context.native.note Backplane’s launch prompt. Native files are loaded by the provider. Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。 Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos. +thread.context.copy Copy prompt プロンプトをコピー Copiar instrucciones +thread.context.copied Prompt copied. プロンプトをコピーしました。 Se copiaron las instrucciones. +thread.context.base Backplane Backplane Backplane +thread.context.injected.label Injected project instructions 追加されたプロジェクトの指示 Instrucciones del proyecto añadidas +thread.context.index Available skills index 利用可能なスキルの一覧 Índice de habilidades disponibles +thread.context.scope.user User ユーザー Usuario +thread.context.scope.bundled Bundled 同梱 Incluidas +thread.context.native Native ネイティブ Nativo +thread.context.injected Injected 追加済み Añadido +thread.context.cross Cross-provider プロバイダー共通 Entre proveedores +thread.context.explicit Explicit invocation 明示的な呼び出し Invocación explícita +thread.context.untrusted Untrusted 未承認 Sin aprobar +thread.context.invalid Invalid 無効 No válido +thread.context.trust Trust and enable 承認して有効にする Confiar y activar +thread.context.enable Enable 有効にする Activar +thread.context.disable Disable 無効にする Desactivar +thread.context.size {bytes} B · ≈{tokens} tokens {bytes} B・約{tokens}トークン {bytes} B · ≈{tokens} tokens +thread.context.unreachable Could not reach the hub. ハブに接続できませんでした。 No se pudo conectar con el hub. """# /// thread.count = {n, plural, one {# thread} other {# threads}} @@ -7680,4 +7708,7 @@ web.logout.failed Could not confirm sign-out. Try again. サインアウトを /// web.composer.maximages = At most {max} images per message. static func web_composer_maximages(max: String) -> String { f("web.composer.maximages", ["max": max]) } + + /// thread.context.size = {bytes} B · ≈{tokens} tokens + static func thread_context_size(bytes: String, tokens: String) -> String { f("thread.context.size", ["bytes": bytes, "tokens": tokens]) } } diff --git a/native/gpui/src/hub.rs b/native/gpui/src/hub.rs index ceed783156..f50632d0e8 100644 --- a/native/gpui/src/hub.rs +++ b/native/gpui/src/hub.rs @@ -420,7 +420,7 @@ async fn session(config:&Config,commands:&mut mpsc::Receiver,queued:&mu continue; } if let Some(tag)=v.asks.remove(&id) {let _=events.send(Event::Answer(tag,x)).await;continue;} - if let Some(tag)=v.rpcs.remove(&id) {if tag=="kicad" {let m=v.rpc_names.remove(&id).unwrap_or_default();let why=if x["ok"]==true {String::new()} else {rpc_error(&x)};eprintln!("GPUI_LOG {}",json!({"kicad_rpc_reply":m,"id":id,"at_ms":crate::screens::kcomment::epoch_ms() as u64,"ok":x["ok"]==true,"state":x["state"],"mode":x["mode"],"pid":x["pid"],"warm":x["warm"],"started":x["started"],"why":x["why"],"prewarming":x["prewarming"],"error":why.chars().take(160).collect::()}));let _=events.send(Event::KicadReply(m,x)).await;continue;}if tag=="star" {let _=events.send(Event::Star(if x["ok"]==true {x["result"]["offer"].clone()} else {Value::Null})).await;continue;}if tag=="tmnotice" {let _=events.send(Event::TmNotice(if x["ok"]==true {x["result"]["notice"].clone()} else {Value::Null})).await;continue;}if tag=="gpnotice" {let _=events.send(Event::GpNotice(if x["ok"]==true {x["result"]["notice"].clone()} else {Value::Null})).await;continue;}if tag==crate::streamer::TAG {if x["ok"]==true {let _=events.send(Event::Data(crate::streamer::TAG,x["result"].clone())).await;}continue;}if tag=="google" && x["ok"]==true {let _=events.send(Event::Data(tag.clone(),x["result"].clone())).await;}if tag=="acct" || (tag=="acct-moveall" && x["ok"]==true) {let _=events.send(Event::Data(tag.clone(),x["result"].clone())).await;}if tag=="steps" {let _=events.send(Event::Steps(if x["ok"]==true {x["result"].clone()} else {Value::Null})).await;continue;}if tag.starts_with("probe") {let slot:usize=tag[5..].parse().unwrap_or(0);let m=x["result"]["matches"].as_array().map(|a|a.iter().filter_map(|p|Some((p[0].as_u64()? as usize,p[1].as_u64()? as usize))).collect()).unwrap_or_default();let _=events.send(Event::Probe(slot,m)).await;continue;}if tag=="resolve" {let _=events.send(Event::Refs(serde_json::json!({"resolved":x["result"]["resolved"].clone(),"error":x["result"]["error"].clone()}))).await;continue;}if tag=="refs" {let _=events.send(Event::Refs(if x["ok"]==true {x["result"].clone()} else {Value::Null})).await;continue;}if tag=="names"||tag=="xsel"||tag=="xsel-tap" {let _=events.send(Event::Data(if tag=="names" {"names"} else if tag=="xsel" {"xsel"} else {"xsel-tap"},x)).await;continue;}if tag=="pick" {let _=events.send(Event::Pick(if x["ok"]==true {x["result"]["info"].as_str().unwrap_or("").to_string()} else {String::new()})).await;continue;}let ok=x["ok"]==true;let why=if ok&&tag.starts_with("hook"){crate::screens::bots::hook_answer(&x).to_string()}else if ok&&tag.starts_with("files"){x["result"].to_string()}else{crate::screens::settings::reply_error(&x)};let _=events.send(Event::Rpc(tag,ok,why)).await;continue;} + if let Some(tag)=v.rpcs.remove(&id) {if tag=="thread-context" {let _=events.send(Event::Data("thread-context",x)).await;continue;}if tag=="kicad" {let m=v.rpc_names.remove(&id).unwrap_or_default();let why=if x["ok"]==true {String::new()} else {rpc_error(&x)};eprintln!("GPUI_LOG {}",json!({"kicad_rpc_reply":m,"id":id,"at_ms":crate::screens::kcomment::epoch_ms() as u64,"ok":x["ok"]==true,"state":x["state"],"mode":x["mode"],"pid":x["pid"],"warm":x["warm"],"started":x["started"],"why":x["why"],"prewarming":x["prewarming"],"error":why.chars().take(160).collect::()}));let _=events.send(Event::KicadReply(m,x)).await;continue;}if tag=="star" {let _=events.send(Event::Star(if x["ok"]==true {x["result"]["offer"].clone()} else {Value::Null})).await;continue;}if tag=="tmnotice" {let _=events.send(Event::TmNotice(if x["ok"]==true {x["result"]["notice"].clone()} else {Value::Null})).await;continue;}if tag=="gpnotice" {let _=events.send(Event::GpNotice(if x["ok"]==true {x["result"]["notice"].clone()} else {Value::Null})).await;continue;}if tag==crate::streamer::TAG {if x["ok"]==true {let _=events.send(Event::Data(crate::streamer::TAG,x["result"].clone())).await;}continue;}if tag=="google" && x["ok"]==true {let _=events.send(Event::Data(tag.clone(),x["result"].clone())).await;}if tag=="acct" || (tag=="acct-moveall" && x["ok"]==true) {let _=events.send(Event::Data(tag.clone(),x["result"].clone())).await;}if tag=="steps" {let _=events.send(Event::Steps(if x["ok"]==true {x["result"].clone()} else {Value::Null})).await;continue;}if tag.starts_with("probe") {let slot:usize=tag[5..].parse().unwrap_or(0);let m=x["result"]["matches"].as_array().map(|a|a.iter().filter_map(|p|Some((p[0].as_u64()? as usize,p[1].as_u64()? as usize))).collect()).unwrap_or_default();let _=events.send(Event::Probe(slot,m)).await;continue;}if tag=="resolve" {let _=events.send(Event::Refs(serde_json::json!({"resolved":x["result"]["resolved"].clone(),"error":x["result"]["error"].clone()}))).await;continue;}if tag=="refs" {let _=events.send(Event::Refs(if x["ok"]==true {x["result"].clone()} else {Value::Null})).await;continue;}if tag=="names"||tag=="xsel"||tag=="xsel-tap" {let _=events.send(Event::Data(if tag=="names" {"names"} else if tag=="xsel" {"xsel"} else {"xsel-tap"},x)).await;continue;}if tag=="pick" {let _=events.send(Event::Pick(if x["ok"]==true {x["result"]["info"].as_str().unwrap_or("").to_string()} else {String::new()})).await;continue;}let ok=x["ok"]==true;let why=if ok&&tag.starts_with("hook"){crate::screens::bots::hook_answer(&x).to_string()}else if ok&&tag.starts_with("files"){x["result"].to_string()}else{crate::screens::settings::reply_error(&x)};let _=events.send(Event::Rpc(tag,ok,why)).await;continue;} if dock_watch.as_ref().is_some_and(|(rid, _)| *rid == id) { let (_, mut watch) = dock_watch.take().unwrap(); watch["tiles"] = x["result"]["tiles"].clone(); diff --git a/native/gpui/src/main.rs b/native/gpui/src/main.rs index 6a25dc7ce3..39a8c61ad2 100644 --- a/native/gpui/src/main.rs +++ b/native/gpui/src/main.rs @@ -204,6 +204,7 @@ impl Backplane { Event::Data(tag,v) if tag=="names" => { screens::xprobe::got_names(self,&v); cx.notify(); } Event::Data(tag,v) if tag=="xsel" => { screens::xprobe::got_select(self,&v); cx.notify(); } Event::Data(tag,v) if tag=="xsel-tap" => { eprintln!("GPUI_LOG {}",serde_json::json!({"event":"xprobe_tap","ok":v["ok"],"kicad":v["kicad"],"found":v["found"],"error":v["error"]})); } + Event::Data("thread-context", v) => screens::thread_context::got(self, v, cx), Event::Data("layout-refusal", v) => screens::tile_menu::refused(self, &v, cx), Event::Data(tag,v)=>if tag=="google-changed" {screens::google::changed(self)} else if tag=="google" {screens::google::got(self,v,cx)} else if tag=="acct-moveall" {screens::accounts::moved(self,&v)} else {screens::accounts::got(self,v,cx)}, Event::Voice(f)=>self.voice_frame(f,cx), @@ -380,7 +381,7 @@ impl Backplane { fn user_entries(&self)->usize {self.data["thread"]["entries"].as_array().map_or(0,|e|e.iter().filter(|e|e["kind"]=="user").count())} /// Ctrl/Cmd-C with no text field focused (a click in the timeline leaves none): copy what is selected there. fn copy_selection(&mut self,_:&CopySelection,_:&mut Window,cx:&mut Context){self.timeline_copy(cx);} - fn close_popup(&mut self,_:&ClosePopup,window:&mut Window,cx:&mut Context){if self.screens.dock.cancel_drag(){cx.notify();return;}if screens::migrate::is_up(&self.data){return;}if self.kcomment_escape(cx){return;}if self.screens.plots[0].part_search.is_some() && self.screens.plots[0].part_search.take().is_some(){cx.notify();return;}if viewers::boards::escape(self,cx){return;}if screens::sheets::escape(self,cx){return;}if viewers::layers::escape(self,cx){return;}if self.pad_escape(window,cx){return;}if self.ctx_close(cx){return;}if self.screens.acct.menu{screens::accounts::toggle(self,window,cx);return;}if self.picker_keys(){self.picker_close(cx);return;}if screens::filesui::escape(self,window,cx){return;}if self.palette_close(cx){return;}if self.keysheet_close(cx){return;}if self.find_close(cx){return;}if screens::histbar::escape(self){cx.notify();return;}if self.lightbox_close(window,cx){return;}if self.screens.picker_open{self.picker_close(cx);return;}if screens::settings::is_open(self){screens::settings::close(self,cx);return;}if self.data["tour"].is_object(){screens::settings::flush_fields(self);let _=self.tx.try_send(Command::Action("ob-skip".into(),String::new()));cx.notify();return;}if screens::improvements::escape(self,cx){return;}if self.term_hide(cx){return;}if self.screens.panels.sub_view.is_some(){self.sub_back(cx);return;}if let Some(a)=screens::projects::close_on_escape(&self.data){let _=self.tx.try_send(a);cx.notify();return;}if let Some(a)=screens::tools::close_question(&self.data) {let _=self.tx.try_send(a);}else if self.data["settings"].is_object() {let _=self.tx.try_send(Command::Action("flag".into(),"settings".into()));}else if let Some(a)=screens::bots::close_form(&self.data) {let _=self.tx.try_send(a);}else if self.input.read(cx).popup_open {let draft=self.input.read(cx).content.to_string();self.screens.popup_off=Some(draft);}else{self.escape_rest(window,cx);}cx.notify();} + fn close_popup(&mut self,_:&ClosePopup,window:&mut Window,cx:&mut Context){if self.screens.dock.cancel_drag(){cx.notify();return;}if screens::migrate::is_up(&self.data){return;}if self.kcomment_escape(cx){return;}if self.screens.plots[0].part_search.is_some() && self.screens.plots[0].part_search.take().is_some(){cx.notify();return;}if viewers::boards::escape(self,cx){return;}if screens::sheets::escape(self,cx){return;}if viewers::layers::escape(self,cx){return;}if self.pad_escape(window,cx){return;}if self.ctx_close(cx){return;}if screens::thread_context::close(self,cx){return;}if self.screens.acct.menu{screens::accounts::toggle(self,window,cx);return;}if self.picker_keys(){self.picker_close(cx);return;}if screens::filesui::escape(self,window,cx){return;}if self.palette_close(cx){return;}if self.keysheet_close(cx){return;}if self.find_close(cx){return;}if screens::histbar::escape(self){cx.notify();return;}if self.lightbox_close(window,cx){return;}if self.screens.picker_open{self.picker_close(cx);return;}if screens::settings::is_open(self){screens::settings::close(self,cx);return;}if self.data["tour"].is_object(){screens::settings::flush_fields(self);let _=self.tx.try_send(Command::Action("ob-skip".into(),String::new()));cx.notify();return;}if screens::improvements::escape(self,cx){return;}if self.term_hide(cx){return;}if self.screens.panels.sub_view.is_some(){self.sub_back(cx);return;}if let Some(a)=screens::projects::close_on_escape(&self.data){let _=self.tx.try_send(a);cx.notify();return;}if let Some(a)=screens::tools::close_question(&self.data) {let _=self.tx.try_send(a);}else if self.data["settings"].is_object() {let _=self.tx.try_send(Command::Action("flag".into(),"settings".into()));}else if let Some(a)=screens::bots::close_form(&self.data) {let _=self.tx.try_send(a);}else if self.input.read(cx).popup_open {let draft=self.input.read(cx).content.to_string();self.screens.popup_off=Some(draft);}else{self.escape_rest(window,cx);}cx.notify();} } /// Every key binding, from the defaults and this device's shortcut choices (called again when one changes). pub fn bind_all(cx:&mut App,l:&local::Local){keys::bind_all(cx,l);} diff --git a/native/gpui/src/screens/ctxmenu.rs b/native/gpui/src/screens/ctxmenu.rs index 5b8dc6617e..e00c09203b 100644 --- a/native/gpui/src/screens/ctxmenu.rs +++ b/native/gpui/src/screens/ctxmenu.rs @@ -116,6 +116,7 @@ pub fn title_items(data: &Value) -> Vec { /* i18n-ok: menu labels, drawn through trs in render */ let mut v = vec![item("Find in thread", LOCAL_SEARCH, &rid, false), item("Rename", "row-rename", &rid, false), item("Regenerate title", "row-retitle", &rid, false)]; /* i18n-ok: menu labels, drawn through trs in render */ if !project.is_empty() && row.map_or(false, |r| r["canChild"].as_bool().unwrap_or(true)) { v.push(item("New subthread", "thread-child", &format!("{rid}|{project}"), false)); } /* i18n-ok: menu labels, drawn through trs in render */ if row.map_or(false, |r| r["depth"].as_u64().unwrap_or(0) > 0) { v.push(item("Move to top level", "row-detach", &rid, false)); } + /* i18n-ok: menu label translated in render */ v.push(item("Context & Prompt", "local:thread-context", &rid, false)); v.extend(super::tools::context_items(thread)); v } @@ -218,6 +219,7 @@ impl Backplane { let Some(m) = self.screens.ctx.as_mut() else { return }; match m.items.get(i).map(|it| (it.action.clone(), it.value.clone())) { // the window's own items: the menu shuts as Esc shuts it (an armed Delete is disarmed), then the item opens its place + Some((a, v)) if a == "local:thread-context" => { self.ctx_close(cx); super::thread_context::open(self, v, cx); return } Some((a, v)) if a == LOCAL_SEARCH => { self.ctx_close(cx); self.find_open_for(&v, cx); return } Some((a, v)) if a == LOCAL_INTENT => { self.ctx_close(cx); self.open_project(v, cx); return } Some((a, v)) if a == LOCAL_FILE_OPEN || a == LOCAL_FILE_REVEAL => { self.ctx_close(cx); self.file_open(&v, a == LOCAL_FILE_REVEAL); return } @@ -347,7 +349,7 @@ mod tests { let d = j(r#"{"thread":{"id":"http://h:1|t7","menu":[{"label":"Diff","action":"diff","value":""},{"label":"Snooze","action":"snooze","value":"","options":[{"label":"1 hour","value":"1h"}]},{"label":"Delete","action":"row-delete","value":"t7","danger":true}]}, "projects":[{"id":"http://h:1|p1","threads":[{"id":"http://h:1|t7","title":"x","canChild":true,"depth":0}]}]}"#); let it = title_items(&d); - assert_eq!(it.iter().map(|i| i.label.as_str()).collect::>(), ["Find in thread", "Rename", "Regenerate title", "New subthread", "Diff", "Snooze 1 hour", "Delete"]); + assert_eq!(it.iter().map(|i| i.label.as_str()).collect::>(), ["Find in thread", "Rename", "Regenerate title", "New subthread", "Context & Prompt", "Diff", "Snooze 1 hour", "Delete"]); assert_eq!(it[0].action, LOCAL_SEARCH); assert_eq!((it[1].action.as_str(), it[1].value.as_str()), ("row-rename", "t7")); assert_eq!(it[3].value, "t7|p1"); assert!(title_items(&j(r#"{"thread":null}"#)).is_empty(), "no thread, no menu"); let sub = j(r#"{"thread":{"id":"h|c1"},"projects":[{"id":"h|p1","threads":[{"id":"h|t1","title":"a","children":[{"id":"h|c1","title":"b","depth":1,"canChild":false}]}]}]}"#); diff --git a/native/gpui/src/screens/mod.rs b/native/gpui/src/screens/mod.rs index 5334b797f5..6753333f1f 100644 --- a/native/gpui/src/screens/mod.rs +++ b/native/gpui/src/screens/mod.rs @@ -1,5 +1,6 @@ //! Screens the hub's screen model describes beyond generic nodes. Each one reads a plain JSON shape the //! hub already sends the phones and answers with a view action; no decision lives here. +pub mod thread_context; pub mod asks; pub mod review; pub mod popover; @@ -226,6 +227,7 @@ pub struct Screens { pub popup_shut: bool, /// the Context chip's panel (screens/usage.rs), and the chip's bounds as last drawn (the panel floats from it) pub ctx_open: bool, + pub thread_context: thread_context::Inspector, pub ctx_chip: std::rc::Rc>>, pub box_at: std::rc::Rc>>, pub fields: HashMap, @@ -468,6 +470,6 @@ impl Screens { pub fn new(_cx: &mut Context, target: Option, drafts_path: std::path::PathBuf, saved: HashMap) -> Self { let imp = improvements::Imp::new(&drafts_path, target.clone()); let unsent = unsent::Unsent::open(drafts_path.with_file_name("gpui-unsent.json")); - Self { tile_menu: Default::default(), parts: Default::default(), side_force: false, side_shown: true, runs_at: Default::default(), hubbar: Default::default(), elsewhere: None, offers: Default::default(), star: None, tm_notice: None, tm_shown: String::new(), gp_notice: None, term: term::Term::new(_cx.focus_handle()), pad: None, voice: Default::default(), streamer: Default::default(), setup: Default::default(), setup_focus: _cx.focus_handle(), keysheet: false, halt_open: Default::default(), kcomment: None, acct: Default::default(), ctx_open: false, ctx_chip: Default::default(), box_at: Default::default(), pick_slot: None, last_state: String::new(), kicad_shown: (false, String::new()), ask_inputs: HashMap::new(), attacher: attach::Attacher::new(target), drafts: drafts::Writer::start(drafts_path, saved), unsent, offsets: HashMap::new(), seeking: None, streamed: String::new(), restore_ask: String::new(), paging: None, reg: Default::default(), projects: Default::default(), files: Default::default(), downloads: Default::default(), solids: Default::default(), solid_slot: None, solid_order: Default::default(), tile_pages: Default::default(), retired_solids: Vec::new(), browser: None, kicad: None, kicad_loan: None, kicad_update: kicad_update::Update::from_env(), kicad_infos: HashMap::new(), kicad_closed: Default::default(), kicad_adrift_tried: Default::default(), host_sends: Default::default(), mgmt: Default::default(), kicad_window: None, kicad_full: false, kicad_screen: false, kicad_comments_seen: Default::default(), xprobe: Default::default(), rail_scroll: Default::default(), rail_last_lit: None, rail_pending: None, rail_at: None, rail_metric: None, focus_field: None, bots_open: String::new(), plot_click: None, plot: Default::default(), dock: Default::default(), plots: Default::default(), picker_open: false, pick: Default::default(), panels: Default::default(), head: Default::default(), palette: Default::default(), find: Default::default(), lightbox: None, known_refs: vec![], popup_off: None, popup_shut: false, fields: HashMap::new(), settings_focus: _cx.focus_handle(), focus_settings: false, settings_was_open: false, settings_ui: Default::default(), parsed: Default::default(), born: HashMap::new(), pages_read: Default::default(), shown_at: std::time::Instant::now(), images: Default::default(), ctx_img: None, ctx_save: None, img_poll: false, home_scroll: Default::default(), home_list: gpui::ListState::new(0, gpui::ListAlignment::Top, gpui::px(1200.)), home_list_key: String::new(), home_doc_w: 600., home_anchors: Default::default(), await_draft: None, pending_draft: None, draft_timer: false, imp, devbar: None, devbar_confirm: None, ctx: None, scroll_logged: None, popup_ix: 0, popup_key: String::new(), popup_scroll: Default::default(), held: Default::default(), hold_threads: vec![], hold_projects: vec![], root_focus: _cx.focus_handle(), side_focus: _cx.focus_handle(), side_hover: None, edit_after: None, rail_labels: Default::default() } + Self { tile_menu: Default::default(), parts: Default::default(), side_force: false, side_shown: true, runs_at: Default::default(), hubbar: Default::default(), elsewhere: None, offers: Default::default(), star: None, tm_notice: None, tm_shown: String::new(), gp_notice: None, term: term::Term::new(_cx.focus_handle()), pad: None, voice: Default::default(), streamer: Default::default(), setup: Default::default(), setup_focus: _cx.focus_handle(), keysheet: false, halt_open: Default::default(), kcomment: None, acct: Default::default(), ctx_open: false, thread_context: Default::default(), ctx_chip: Default::default(), box_at: Default::default(), pick_slot: None, last_state: String::new(), kicad_shown: (false, String::new()), ask_inputs: HashMap::new(), attacher: attach::Attacher::new(target), drafts: drafts::Writer::start(drafts_path, saved), unsent, offsets: HashMap::new(), seeking: None, streamed: String::new(), restore_ask: String::new(), paging: None, reg: Default::default(), projects: Default::default(), files: Default::default(), downloads: Default::default(), solids: Default::default(), solid_slot: None, solid_order: Default::default(), tile_pages: Default::default(), retired_solids: Vec::new(), browser: None, kicad: None, kicad_loan: None, kicad_update: kicad_update::Update::from_env(), kicad_infos: HashMap::new(), kicad_closed: Default::default(), kicad_adrift_tried: Default::default(), host_sends: Default::default(), mgmt: Default::default(), kicad_window: None, kicad_full: false, kicad_screen: false, kicad_comments_seen: Default::default(), xprobe: Default::default(), rail_scroll: Default::default(), rail_last_lit: None, rail_pending: None, rail_at: None, rail_metric: None, focus_field: None, bots_open: String::new(), plot_click: None, plot: Default::default(), dock: Default::default(), plots: Default::default(), picker_open: false, pick: Default::default(), panels: Default::default(), head: Default::default(), palette: Default::default(), find: Default::default(), lightbox: None, known_refs: vec![], popup_off: None, popup_shut: false, fields: HashMap::new(), settings_focus: _cx.focus_handle(), focus_settings: false, settings_was_open: false, settings_ui: Default::default(), parsed: Default::default(), born: HashMap::new(), pages_read: Default::default(), shown_at: std::time::Instant::now(), images: Default::default(), ctx_img: None, ctx_save: None, img_poll: false, home_scroll: Default::default(), home_list: gpui::ListState::new(0, gpui::ListAlignment::Top, gpui::px(1200.)), home_list_key: String::new(), home_doc_w: 600., home_anchors: Default::default(), await_draft: None, pending_draft: None, draft_timer: false, imp, devbar: None, devbar_confirm: None, ctx: None, scroll_logged: None, popup_ix: 0, popup_key: String::new(), popup_scroll: Default::default(), held: Default::default(), hold_threads: vec![], hold_projects: vec![], root_focus: _cx.focus_handle(), side_focus: _cx.focus_handle(), side_hover: None, edit_after: None, rail_labels: Default::default() } } } diff --git a/native/gpui/src/screens/thread_context.rs b/native/gpui/src/screens/thread_context.rs new file mode 100644 index 0000000000..52a5144e18 --- /dev/null +++ b/native/gpui/src/screens/thread_context.rs @@ -0,0 +1,174 @@ +//! The Context & Prompt inspector. Every row comes from the thread's hub. +use crate::{hub::Command, i18n::trs, string, theme, Backplane}; +use gpui::{prelude::*, *}; +use serde_json::{json, Value}; +use super::{accounts::button, settings::Secret}; + +#[derive(Default)] +pub struct Inspector { + thread: String, + reply: Value, + tab: usize, + expanded: String, + busy: bool, + error: String, + scroll: ScrollHandle, +} + +pub fn open(app: &mut Backplane, thread: String, cx: &mut Context) { + app.screens.thread_context = Inspector { thread, ..Default::default() }; + request(app, None, cx); +} + +fn request(app: &mut Backplane, action: Option<(&str, &Value)>, cx: &mut Context) { + let state = &mut app.screens.thread_context; + state.busy = true; + state.error.clear(); + let (method, params) = match action { + Some((action, row)) => ("thread.context.mcp", json!({"thread":state.thread,"action":action,"path":row["path"],"sha256":row["sha256"]})), + None => ("thread.context", json!({"thread":state.thread})), + }; + if app.tx.try_send(Command::Rpc(method.into(), Secret(params), "thread-context")).is_err() { + state.busy = false; + state.error = trs("Could not reach the hub."); + } + cx.notify(); +} + +pub fn got(app: &mut Backplane, reply: Value, cx: &mut Context) { + let state = &mut app.screens.thread_context; + if state.thread.is_empty() { return } + if reply["ok"] == true { + let thread = reply["result"]["thread"].as_str(); + if Some(state.thread.as_str()) != thread && state.thread.rsplit('~').next() != thread { return } + state.reply = reply["result"].clone(); + state.error.clear(); + } else { state.error = super::settings::reply_error(&reply); } + state.busy = false; + cx.notify(); +} + +pub fn close(app: &mut Backplane, cx: &mut Context) -> bool { + if app.screens.thread_context.thread.is_empty() { return false } + app.screens.thread_context = Inspector::default(); + cx.notify(); + true +} + +fn rows<'a>(data: &'a Value, key: &str) -> impl Iterator { + data[key].as_array().into_iter().flatten() +} + +fn code(text: String, light: bool) -> Div { + div().p_3().bg(theme::color(light, "raise")).text_size(px(12.)).child(text) +} + +fn badge(text: &str, light: bool) -> Div { + let tone = match text { "Native" | "Enabled" => "accent", "Invalid" | "Untrusted" => "warn", _ => "dim" }; + div().flex_shrink_0().px_2().py_1().bg(theme::color(light, "raise")).text_color(theme::color(light, tone)).text_size(px(11.)).child(trs(text)) +} + +pub fn view(state: &Inspector, cx: &mut Context, light: bool, viewport: Size) -> Option { + if state.thread.is_empty() { return None } + let c = |k: &str| theme::color(light, k); + let data = &state.reply; + let loaded = data.is_object(); + let mut tabs = div().flex().gap_1().px_4().pb_3(); + /* i18n-ok: button translates these labels */ for (i, title) in ["Instructions", "System Prompt", "Skills", "Project MCPs"].into_iter().enumerate() { + tabs = tabs.child(button(cx, light, format!("context-tab-{i}"), title, state.tab == i, false, move |app, _| { + let state = &mut app.screens.thread_context; + state.tab = i; + state.expanded.clear(); + state.scroll = ScrollHandle::new(); + })); + } + let mut body = div().id("context-records").flex_1().min_h_0().overflow_y_scroll().track_scroll(&state.scroll).px_4().py_3().flex().flex_col().gap_3(); + if state.busy { body = body.child(div().text_color(c("dim")).child(trs("Reading thread context…"))); } + if !state.error.is_empty() { body = body.child(div().text_color(c("bad")).child(state.error.clone())); } + if loaded { + match state.tab { + 0 => { + if data["instructions"].as_array().is_some_and(Vec::is_empty) { body = body.child(trs("No project instructions found.")); } + for (i, f) in rows(data, "instructions").enumerate() { + let path = string(f, "path"); + let key = path.clone(); + let expanded = state.expanded == path; + let row = div().id(("instruction", i)).p_3().flex().flex_col().gap_2().border_1().border_color(c("line")) + .cursor_pointer().hover(|d| d.bg(c("raise"))) + .child(div().flex().justify_between().gap_2().child(div().min_w_0().child(path)).child(badge(f["status"].as_str().unwrap_or(""), light))) + .child(div().text_size(px(11.)).text_color(c("dim")).child(crate::i18n::tf("thread.context.size", &[("bytes", f["bytes"].as_u64().unwrap_or_default().into()), ("tokens", f["estimated_tokens"].as_u64().unwrap_or_default().into())]))) + .on_click(cx.listener(move |app, _, _, cx| { + app.screens.thread_context.expanded = if expanded { String::new() } else { key.clone() }; + cx.notify(); + })) + .when(expanded, |d| d.child(code(string(f, "preview"), light)).child(div().text_color(c("dim")).child(string(f, "note")))); + body = body.child(row); + } + } + 1 => { + let full = string(data, "prompt"); + body = body.child(div().flex().justify_between().items_center().gap_2() + .child(div().text_color(c("dim")).child(trs("Backplane’s launch prompt. Native files are loaded by the provider."))) + .child(button(cx, light, "context-copy".into(), "Copy prompt", false, false, move |_, cx| cx.write_to_clipboard(ClipboardItem::new_string(full.clone()))))); // i18n-ok: button translates its label + /* i18n-ok: labels translated below */ for (key, title) in [("base", "Backplane"), ("instructions", "Injected project instructions"), ("skills", "Available skills index")] { + let text = string(&data["sections"], key); + if !text.is_empty() { body = body.child(div().font_weight(FontWeight::SEMIBOLD).child(trs(title))).child(code(text, light)); } + } + } + 2 => { + /* i18n-ok: scope names translated below */ for scope in ["Project", "User", "Bundled"] { + let group: Vec<_> = rows(data, "skills").filter(|s| s["scope"] == scope).collect(); + if group.is_empty() { continue } + body = body.child(div().font_weight(FontWeight::SEMIBOLD).child(trs(scope))); + for s in group { + body = body.child(div().p_3().border_1().border_color(c("line")).flex().flex_col().gap_1() + .child(div().flex().justify_between().gap_2().child(div().font_weight(FontWeight::SEMIBOLD).child(string(s, "name"))).child(badge(s["status"].as_str().unwrap_or(""), light))) + .child(string(s, "description")) + .child(div().text_size(px(11.)).text_color(c("dim")).child([string(s, "source"), string(s, "provider"), string(s, "model")].into_iter().filter(|s| !s.is_empty()).collect::>().join(" · "))) + .child(div().text_size(px(11.)).text_color(c("dim")).child(string(s, "path")))); + } + } + } + _ => { + if data["mcp"].as_array().is_some_and(Vec::is_empty) { body = body.child(trs("No project MCP configurations found.")); } + for (i, config) in rows(data, "mcp").enumerate() { + let state_label = config["state"].as_str().unwrap_or(""); + let mut card = div().p_3().border_1().border_color(c("line")).flex().flex_col().gap_2() + .child(div().flex().justify_between().gap_2().child(div().min_w_0().child(string(config, "path"))).child(badge(state_label, light))); + for server in rows(config, "servers") { + let url = string(server, "url"); + let endpoint = if url.is_empty() { + let args = rows(server, "args").filter_map(Value::as_str).map(|a| format!("{a:?}")).collect::>().join(" "); + format!("{:?} {args}", string(server, "command")) // i18n-ok: exact executable and arguments + } else { url }; + card = card.child(div().flex().justify_between() + .child(div().font_weight(FontWeight::SEMIBOLD).child(string(server, "name"))) + .child(badge(server["status"].as_str().unwrap_or(""), light))) + .child(code(endpoint, light)); + } + let error = string(config, "error"); + if !error.is_empty() { card = card.child(div().text_color(c("bad")).child(error)); } + /* i18n-ok: labels translated by button */ let action = match state_label { "Untrusted" => Some(("trust", "Trust and enable")), "Enabled" => Some(("disable", "Disable")), "Disabled" => Some(("enable", "Enable")), _ => None }; + if let Some((action, label)) = action.filter(|_| !state.busy) { + let config = config.clone(); + card = card.child(div().flex().justify_end().child(button(cx, light, format!("context-mcp-{i}"), label, action == "trust", false, move |app, cx| request(app, Some((action, &config)), cx)))); + } + body = body.child(card); + } + } + } + } + Some(div().absolute().inset_0().bg(rgba(0x00000066)).flex().items_center().justify_center() + .on_mouse_down(MouseButton::Left, cx.listener(|_, _, _, cx| cx.stop_propagation())) + .child(div().w((viewport.width - px(32.)).min(px(840.))).h((viewport.height - px(32.)).min(px(700.))) + .bg(c("panel")).border_1().border_color(c("line")).shadow_lg().flex().flex_col() + .child(div().px_4().py_3().flex().justify_between().items_start() + .child(div().min_w_0().flex().flex_col().gap_1() + .child(div().text_size(px(19.)).font_weight(FontWeight::SEMIBOLD).child(trs("Context & Prompt"))) + .child(div().text_size(px(12.)).text_color(c("dim")).child(string(data, "cwd")))) + .child(div().flex().gap_2() + .child(button(cx, light, "context-refresh".into(), "Refresh", false, false, |app, cx| request(app, None, cx))) // i18n-ok: button translates its label + .child(button(cx, light, "context-close".into(), "Close", false, false, |app, cx| { close(app, cx); })))) // i18n-ok: button translates its label + .child(tabs).child(div().h(px(1.)).bg(c("line"))).child(body)) + .into_any_element()) +} diff --git a/native/gpui/src/ui.rs b/native/gpui/src/ui.rs index a9a2711d4d..4c6f06cae6 100644 --- a/native/gpui/src/ui.rs +++ b/native/gpui/src/ui.rs @@ -1328,6 +1328,7 @@ impl Render for Backplane { .children(crate::perf::mark("over")) // Settings over the whole window: its dialog is sized from the window (settings::fit), so it must not sit in the thread column .children(crate::screens::settings::view(cx, light, &self.screens.fields, &self.data["settings"], &self.screens.settings_focus, &self.screens.settings_ui, &self.local, &self.screens.acct, crate::screens::settings::fit(f32::from(window.viewport_size().width), f32::from(window.viewport_size().height)),&self.hubs,self.screens.offers.on_home.as_deref())) + .children(crate::screens::thread_context::view(&self.screens.thread_context, cx, light, window.viewport_size())) .children(crate::screens::improvements::view(cx, light, &self.screens.imp)) .children(crate::screens::improvements::indicator(cx, light, &self.screens.imp)) .children({ let title = crate::screens::badge::from_machine(&self.data["thread"]["mark"], &string(&self.data["thread"], "title")); crate::screens::term::view(cx, window, light, &self.local, &title, &self.screens.term) }) diff --git a/native/host/src/agents/bundled.rs b/native/host/src/agents/bundled.rs index 1b7745fd4b..36b58c03f9 100644 --- a/native/host/src/agents/bundled.rs +++ b/native/host/src/agents/bundled.rs @@ -95,7 +95,7 @@ pub fn install(home: &Path) -> Option { pub fn list(d: &Path) -> Vec<(String, String, String)> { FILES.iter().filter(|(rel, _)| rel.ends_with("/SKILL.md")).map(|(rel, text)| { let p = d.join(rel); let folder = rel.trim_end_matches("/SKILL.md").rsplit('/').next().unwrap_or(""); - let s = crate::agents::inputs::parse_skill(text, folder, &p.to_string_lossy()); (s.name, s.description, s.path) + let s = crate::agents::skills::parse_skill(text, folder, &p.to_string_lossy()); (s.name, s.description, s.path) }).collect() } diff --git a/native/host/src/agents/context.rs b/native/host/src/agents/context.rs new file mode 100644 index 0000000000..3a249bca54 --- /dev/null +++ b/native/host/src/agents/context.rs @@ -0,0 +1,368 @@ +//! Worktree context shared by launch and the thread inspector. +use serde::Serialize; +use std::{fs, io::Read, path::Path}; + +const FILE_LIMIT: usize = 8 * 1024; +const TOTAL_LIMIT: usize = 32 * 1024; +const NAMES: &[&str] = &[ + "AGENTS.md", "AGENTS.override.md", ".claude/AGENTS.md", "CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md", + "GEMINI.md", ".backplane/instructions.md", ".cursorrules", + ".github/copilot-instructions.md", +]; + +#[derive(Serialize)] +pub struct Instruction { + pub path: String, + pub bytes: u64, + pub estimated_tokens: u64, + pub status: &'static str, + pub preview: String, + pub note: String, +} + +#[derive(Clone, Copy, Default, PartialEq)] +pub enum ClaudeFiles { + #[default] + ClaudeOnly, + Fallback, + Both, + ManagedOnly, +} + +impl ClaudeFiles { + pub fn configured(version: &str, settings: &serde_json::Value) -> Self { + if !crate::settings::agent_versions::parse(version).is_some_and(|v| v.as_slice() >= &[2, 1, 277]) { + return Self::ClaudeOnly + } + for plugin in ["cc-plugin-agents-md@builtin", "agents-md@builtin"] { + if settings["enabledPlugins"][plugin] == false { return Self::ClaudeOnly } + match settings["pluginConfigs"][plugin]["options"]["instructionFiles"].as_str() { + Some("claude-md") => return Self::ClaudeOnly, + Some("managed-only") => return Self::ManagedOnly, + Some("claude-md-and-agents-md") => return Self::Both, + _ => {} + }; + } + Self::Fallback + } +} + +fn disposition(provider: &str, name: &str, dir: &Path, has_agents: bool, claude: ClaudeFiles, has_claude: bool) -> &'static str { + let overridden = dir.join("AGENTS.override.md").is_file(); + let agents = dir.join("AGENTS.md").is_file(); + match (provider, name) { + ("claude", "CLAUDE.md" | ".claude/CLAUDE.md" | "CLAUDE.local.md") => { + if claude == ClaudeFiles::ManagedOnly { "Skipped" } else { "Native" } + } + ("claude", "AGENTS.md" | ".claude/AGENTS.md") if claude == ClaudeFiles::Both || claude == ClaudeFiles::Fallback && !has_claude => "Native", + ("claude", _) if claude == ClaudeFiles::ManagedOnly => "Skipped", + (_, "CLAUDE.local.md") => "Skipped", + + ("antigravity", "AGENTS.md" | "GEMINI.md") | + ("grok" | "muse", "AGENTS.md") | + ("codex" | "pi", "AGENTS.override.md") => "Native", + ("omp", "AGENTS.md") | ("omp", "CLAUDE.md") if !dir.join(".claude/CLAUDE.md").is_file() => "Native", + ("omp", ".cursorrules") => "Native", + ("codex" | "pi", "AGENTS.md") if overridden => "Skipped", + ("codex" | "pi" | "opencode", "AGENTS.md") => "Native", + ("pi", "CLAUDE.md") if !overridden && !agents => "Native", + ("opencode", "CLAUDE.md") if !has_agents && std::env::var_os("OPENCODE_DISABLE_CLAUDE_CODE_PROMPT").is_none() && std::env::var_os("OPENCODE_DISABLE_CLAUDE_CODE").is_none() => "Native", + _ => "Injected", + } +} + +#[cfg(test)] +fn instructions(cwd: &str, provider: &str) -> (Vec, String) { + instructions_for(cwd, provider, ClaudeFiles::default()) +} + +fn instructions_for(cwd: &str, provider: &str, claude: ClaudeFiles) -> (Vec, String) { + let dirs = super::skills::directories(Path::new(cwd)); + let root = dirs.first(); + let has_agents = dirs.iter().any(|p| p.join("AGENTS.md").is_file()); + let has_claude = dirs.last().is_some_and(|cwd| cwd.ancestors().any(|p| { + ["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"].iter().any(|name| p.join(name).is_file()) + })); + let mut candidates = Vec::new(); + let mut native = std::collections::HashSet::new(); + for dir in dirs.iter().rev() { + for name in NAMES.iter().rev() { + let path = dir.join(name); + let Ok(real) = crate::plat::fs::canonicalize(&path) else { continue }; + if !root.is_some_and(|r| real.starts_with(r)) { continue } + let Ok(meta) = fs::metadata(&real) else { continue }; + if !meta.is_file() { continue } + let status = disposition(provider, name, dir, has_agents, claude, has_claude); + if status == "Native" { native.insert(real.clone()); } + candidates.push((path, real, meta.len(), status)); + } + } + if provider == "claude" { + // A standard Claude import (for example @AGENTS.md) is itself native context. + let known: std::collections::HashSet<_> = candidates.iter().map(|(_, real, _, _)| real.clone()).collect(); + let mut pending: Vec<_> = native.iter().cloned().collect(); + while let Some(p) = pending.pop() { + let mut bytes = Vec::new(); + if fs::File::open(&p).and_then(|f| f.take(FILE_LIMIT as u64).read_to_end(&mut bytes)).is_err() { continue } + let Ok(text) = std::str::from_utf8(&bytes) else { continue }; + for line in text.lines() { + let Some(import) = line.trim().strip_prefix('@') else { continue }; + if import.is_empty() || import.chars().any(char::is_whitespace) { continue } + let Some(dir) = p.parent() else { continue }; + let Ok(target) = crate::plat::fs::canonicalize(dir.join(import)) else { continue }; + if known.contains(&target) && native.insert(target.clone()) { pending.push(target); } + } + } + } + let mut rows = Vec::new(); + let mut injected = String::new(); + // Reserve space for closer instructions before allocating the root's budget. + let mut remaining = TOTAL_LIMIT; + for (path, real, size, mut status) in candidates { + let path_str = path.to_string_lossy().into_owned(); + let alias = status == "Injected" && native.contains(&real); + if alias { status = "Skipped"; } + let limit = if status == "Injected" { FILE_LIMIT.min(remaining) } else { FILE_LIMIT }; + let mut bytes = Vec::new(); + let read = fs::File::open(&real).and_then(|f| f.take(limit as u64 + 1).read_to_end(&mut bytes)); + let mut note = if read.is_err() { + status = "Skipped"; + format!("Could not read {path_str}") + } else if alias { + "The provider already loads this file by another path".into() + } else if limit == 0 { + status = "Skipped"; + format!("Context limit reached before {path_str}") + } else if status == "Skipped" { + if claude == ClaudeFiles::ManagedOnly { "The provider is configured for managed instructions only".into() } + else if path.ends_with("CLAUDE.local.md") { "Local Claude instructions".into() } + else { "AGENTS.override.md takes precedence".into() } + } else if size > limit as u64 || bytes.len() > limit { + if status == "Native" { + format!("Preview truncated at {limit} bytes. The provider decides its own limit.") + } else { format!("Truncated {path_str} at {limit} bytes") } + } else { String::new() }; + bytes.truncate(limit); + let preview = match std::str::from_utf8(&bytes) { + Ok(s) => s, + Err(e) if e.error_len().is_none() && size > bytes.len() as u64 => { + std::str::from_utf8(&bytes[..e.valid_up_to()]).unwrap_or_default() + } + Err(_) => { + status = "Skipped"; + note = format!("{path_str} is not UTF-8"); + "" + } + }.trim_start_matches('\u{feff}').to_string(); + if status == "Injected" { remaining -= preview.len(); } + rows.push(Instruction { path: path_str, bytes: size, estimated_tokens: size.div_ceil(4), status, preview, note }); + } + rows.reverse(); + for row in rows.iter().filter(|r| r.status == "Injected" || r.note.starts_with("Context limit reached")) { + use std::fmt::Write; + if row.status == "Injected" { + let _ = writeln!(injected, "\n## {}\n\n{}", row.path, row.preview); + } + if !row.note.is_empty() { let _ = writeln!(injected, "\n[{}]", row.note); } + } + // Bound the extra markup as well as the file bodies. + if injected.len() > TOTAL_LIMIT + FILE_LIMIT { + let end = injected.floor_char_boundary(TOTAL_LIMIT + FILE_LIMIT); + injected.truncate(end); + injected.push_str("\n[Project instructions reached the context limit.]\n"); + } + if !injected.is_empty() { injected = format!("\n{injected}"); } + (rows, injected) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn linked_worktree_context_stops_at_its_own_root() { + let main = crate::plat::tmp::dir("context-worktree"); + let work = main.join(".backplane/worktrees/thread"); + let cwd = work.join("src"); + fs::create_dir_all(&cwd).unwrap(); + fs::write(main.join(".git"), "").unwrap(); + fs::write(main.join("AGENTS.md"), "MAIN ONLY").unwrap(); + fs::write(work.join(".git"), "gitdir: ignored").unwrap(); + fs::write(work.join("AGENTS.md"), "WORKTREE").unwrap(); + fs::write(cwd.join("CLAUDE.md"), "LOCAL").unwrap(); + for (provider, agents_native, claude_native) in [ + ("claude", false, true), ("codex", true, false), ("antigravity", true, false), + ("grok", true, false), ("opencode", true, false), ("pi", true, true), + ("omp", true, true), + ] { + let (rows, prompt) = instructions(&cwd.to_string_lossy(), provider); + assert_eq!(rows.len(), 2, "{provider}"); + assert_eq!(prompt.contains("WORKTREE"), !agents_native, "{provider}"); + assert_eq!(prompt.contains("LOCAL"), !claude_native, "{provider}"); + assert!(!prompt.contains("MAIN ONLY")); + } + } + + #[test] + fn claude_native_fallback_respects_its_version_mode_and_imports() { + use serde_json::{json, Value}; + let dir = crate::plat::tmp::dir("claude-instructions"); + fs::write(dir.join("AGENTS.md"), "TEAM GUIDANCE").unwrap(); + let cwd = dir.to_string_lossy(); + let mode = |v| ClaudeFiles::configured(v, &Value::Null); + assert!(instructions_for(&cwd, "claude", mode("2.1.268")).1.contains("TEAM GUIDANCE")); + assert!(instructions_for(&cwd, "claude", mode("2.1.328")).1.is_empty()); + fs::write(dir.join("CLAUDE.md"), "Additional memory").unwrap(); + assert!(instructions_for(&cwd, "claude", mode("2.1.328")).1.contains("TEAM GUIDANCE")); + let both = ClaudeFiles::configured("2.1.328", &json!({ + "pluginConfigs":{"cc-plugin-agents-md@builtin":{"options":{"instructionFiles":"claude-md-and-agents-md"}}} + })); + assert!(instructions_for(&cwd, "claude", both).1.is_empty()); + fs::write(dir.join("CLAUDE.md"), "@AGENTS.md\n").unwrap(); + assert!(instructions_for(&cwd, "claude", mode("2.1.268")).1.is_empty()); + } + + #[test] + fn truncation_preserves_utf8_and_reports_the_path() { + let dir = crate::plat::tmp::dir("context-truncate"); + let path = dir.join("AGENTS.md"); + fs::write(&path, "€".repeat(FILE_LIMIT)).unwrap(); + let (rows, prompt) = instructions(&dir.to_string_lossy(), "claude"); + assert_eq!(rows[0].bytes, (3 * FILE_LIMIT) as u64); + assert!(rows[0].preview.len() <= FILE_LIMIT); + assert!(!prompt.contains('�')); + assert!(prompt.contains(&format!("Truncated {}", path.display()))); + } +} + +#[derive(Default)] +pub struct Prompt { + pub base: String, + pub project: String, + pub index: String, + pub instructions: Vec, + pub skills: Vec, +} + +impl Prompt { + pub fn build(base: String, env: &super::skills::Env, cwd: &str, provider: &str, model: &str, isolated: bool, claude: ClaudeFiles) -> Self { + use super::skills; + use serde_json::json; + let (instructions, project) = instructions_for(cwd, provider, claude); + let discovered = skills::index(env, cwd); + let active = skills::for_model(&discovered, provider, model); + let index = skills::prompt_index(&active, provider, isolated); + let skills = discovered.iter().map(|s| { + let status = if !active.contains(s) { "Skipped" } + else if skills::native(s, provider, isolated) { "Native" } + else if !s.model { "Explicit invocation" } + else { "Cross-provider" }; + json!({"name":s.name, "description":s.description, "path":s.path, "scope":s.scope, + "source":s.group, "status":status, "provider":super::skills::provider_scope(s), "model":s.model_pattern}) + }).collect(); + Self { base, project, index, instructions, skills } + } + + pub fn text(&self) -> String { + [&self.base, &self.project, &self.index].into_iter().filter(|s| !s.is_empty()).map(String::as_str).collect::>().join("\n\n") + } +} + +#[cfg(test)] +mod launch_tests { + use super::*; + use crate::agents::{providers::{self, TurnIn}, rules}; + use serde_json::{json, Value}; + + #[test] + fn project_and_model_scope_select_the_metadata_only() { + let dir = crate::plat::tmp::dir("context-skill-scope"); + let home = dir.join("home"); + let repo = dir.join("repo"); + let cwd = repo.join("sub"); + let bundle = dir.join("hub"); + let put = |base: &Path, rel: &str, body: &str| { + let path = base.join(rel); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, body).unwrap(); + }; + put(&repo, ".git", ""); + put(&repo, ".backplane/skills/a/SKILL.md", "---\nname: a\ndescription: repo skill\n---\nBODY"); + put(&cwd, ".backplane/skills/a/SKILL.md", "---\nname: a\ndescription: closest skill\n---\nBODY"); + put(&home, ".backplane/skills/a/SKILL.md", "---\nname: a\ndescription: home skill\n---\nBODY"); + put(&bundle, "bundled/skills/a/SKILL.md", "---\nname: a\ndescription: bundled skill\n---\nBODY"); + put(&repo, ".backplane/skills/be/SKILL.md", "---\nname: be\nprovider: codex\nmodel: gpt-*\ndescription: model scoped\n---\nBODY"); + put(&repo, ".claude/commands/deploy.md", "---\ndescription: command marker\n---\nBODY"); + let env = crate::agents::skills::env_from(home.to_str().unwrap(), &bundle, None); + let prompt = |provider, model| Prompt::build("BASE".into(), &env, cwd.to_str().unwrap(), provider, model, false, ClaudeFiles::default()); + let codex = prompt("codex", "gpt-6"); + assert!(codex.index.contains("closest skill") && codex.index.contains("model scoped")); + for absent in ["repo skill", "home skill", "bundled skill", "command marker", "BODY"] { + assert!(!codex.index.contains(absent), "{absent}"); + } + assert!(!prompt("codex", "other").index.contains("model scoped")); + let claude = prompt("claude", "sonnet"); + assert!(claude.skills.iter().any(|row| row["name"] == "deploy" && row["status"] == "Native")); + assert!(!claude.index.contains("command marker")); + } + + #[test] + fn provider_payloads_carry_the_assembled_prompt() { + let dir = crate::plat::tmp::dir("context-launch-payload"); + fs::write(dir.join("AGENTS.md"), "NATIVE AGENT TEXT").unwrap(); + fs::create_dir(dir.join(".backplane")).unwrap(); + fs::write(dir.join(".backplane/instructions.md"), "BACKPLANE PROJECT TEXT").unwrap(); + let cwd = dir.to_string_lossy().into_owned(); + let home = dir.join("home"); + let env = crate::agents::skills::env_from(dir.to_str().unwrap(), &home, None); + let prompt = |provider| Prompt::build("BASE".into(), &env, &cwd, provider, "", false, ClaudeFiles::default()).text(); + let a = |provider| TurnIn { prompt: prompt(provider), text: "MESSAGE".into(), cwd: cwd.clone(), + home: home.to_string_lossy().into_owned(), thread: "context".into(), ..Default::default() }; + let expected = "BACKPLANE PROJECT TEXT"; + let p = prompt("claude"); + let claude = rules::claude_args(&rules::ArgsIn { model:"", session:"", runtime:"", interaction:"", + prompt:&p, dirs:&[], effort:"", think:false, plugins:&[], mcp_url:"", mcp_json:"", disallowed:&[], speed:"" }); + assert_eq!(claude.windows(2).find(|a| a[0] == "--append-system-prompt").unwrap()[1], p); + assert!(p.contains(expected) && p.contains("NATIVE AGENT TEXT")); + assert!(claude.iter().any(|arg| arg == "--strict-mcp-config")); + for id in ["codex", "pi", "omp"] { + let mut driver = providers::driver(id).unwrap().driver; + let a = a(id); + driver.prepare(&a).unwrap(); + let argv = driver.argv(&a); + let payload = if id == "omp" { + let p = argv.windows(2).find(|a| a[0] == "--append-system-prompt").unwrap(); + fs::read_to_string(&p[1]).unwrap() + } else if id == "pi" { + let p = &argv.windows(2).find(|a| a[0] == "--append-system-prompt").unwrap()[1]; + fs::read_to_string(p).unwrap_or_else(|_| p.clone()) + } else if cfg!(windows) { + let profile = argv.windows(2).find(|a| a[0] == "-p" || a[0] == "--profile").unwrap(); + fs::read_to_string(crate::agents::proc::run_dir(&home).join(format!("{}.config.toml", profile[1]))).unwrap() + } else { argv.join("\n") }; + assert!(payload.contains(expected), "{id}"); + assert!(!payload.contains("NATIVE AGENT TEXT"), "{id}"); + drop(driver.take_files()); + } + let print_input = providers::agy_cli::input(&a("antigravity")); + assert!(print_input.contains(expected) && !print_input.contains("NATIVE AGENT TEXT")); + for id in ["grok", "opencode", "antigravity", "muse"] { + let mut driver = providers::driver(id).unwrap().driver; + let a = a(id); + driver.start(&a); + let init = driver.on_line(&json!({"id":1,"result":{"protocolVersion":1,"agentCapabilities":{}}})); + let open = if id == "antigravity" { + assert!(init.send.iter().any(|r| r.contains("authenticate"))); + driver.on_line(&json!({"id":4,"result":{}})) + } else { init }; + assert!(open.send.iter().any(|r| r.contains("session/new") || r.contains("session/start")), "{id}"); + let replies = driver.on_line(&json!({"id":2,"result":{"sessionId":"session"}})).send; + let next: Vec<_> = replies.iter().filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|r| r["method"].as_str().is_some_and(|m| m != "session/prompt")).collect(); + let followups: Vec<_> = next.iter().flat_map(|r| driver.on_line(&json!({"id":r["id"],"result":{}})).send).collect(); + let payload = [replies, followups].concat().join("\n"); + assert!(payload.contains(expected), "{id}: {payload}"); + assert!(!payload.contains("NATIVE AGENT TEXT"), "{id}"); + } + } +} diff --git a/native/host/src/agents/inputs.rs b/native/host/src/agents/inputs.rs index 7a2360a411..cd754e7f36 100644 --- a/native/host/src/agents/inputs.rs +++ b/native/host/src/agents/inputs.rs @@ -1,69 +1,5 @@ -//! What a message and a project give an agent besides the prompt: skills, `$skill` mentions, and attached images. +//! Message attachments and Claude stream-json input. use serde_json::{json, Value}; -use std::path::{Path, PathBuf}; - -// ---- skills ---- -#[derive(Clone, Debug, PartialEq)] -pub struct USkill { pub name: String, pub description: String, pub path: String, pub model: bool, pub user: bool } - -fn unquote(s: &str) -> String { if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 { s[1..s.len() - 1].to_string() } else { s.to_string() } } -fn field(line: &str, key: &str) -> Option { line.strip_prefix(&format!("{key}:")).map(|r| unquote(r.trim())) } -/// Front.join / Front.cont / Front.fold: a value carried on to indented lines is read whole on its key's line. -fn fold(ls: &[&str]) -> Vec { - let mut acc: Vec = vec![]; let mut open = true; - for l in ls { - let cont = open && (l.starts_with(' ') || l.starts_with('\t')) && !l.trim().is_empty() && l.trim() != "---"; - if cont && !acc.is_empty() { - let h = acc.pop().unwrap().trim_end().to_string(); let s = l.trim(); - let one = h.ends_with(": >") || h.ends_with(": |"); let two = [": >-", ": |-", ": >+", ": |+"].iter().any(|e| h.ends_with(e)); - acc.push(if one { format!("{}{s}", &h[..h.len() - 1]) } else if two { format!("{}{s}", &h[..h.len() - 2]) } else { format!("{h} {s}") }); - } else { acc.push(l.to_string()) } - if l.trim() == "---" { open = false } - } - acc -} -/// USkill.parse: the leading --- block's name, description, disable-model-invocation, user-invocable. -pub fn parse_skill(text: &str, dflt: &str, path: &str) -> USkill { - let ls: Vec<&str> = text.split('\n').collect(); - let (mut n, mut d, mut m, mut u) = (dflt.to_string(), String::new(), String::new(), String::new()); - if ls.first().map_or(false, |l| l.trim() == "---") { - for l in fold(&ls[1..]) { if l.trim() == "---" { break } - if let Some(v) = field(&l, "name") { n = v } if let Some(v) = field(&l, "description") { d = v } - if let Some(v) = field(&l, "disable-model-invocation") { m = v } if let Some(v) = field(&l, "user-invocable") { u = v } } - } - let flag = |v: &str, dv: bool| match v.to_lowercase().as_str() { "true" => true, "false" => false, _ => dv }; - USkill { name: n, description: d, path: path.into(), model: !flag(&m, false), user: flag(&u, true) } -} -fn dir_skills(root: &Path) -> Vec { - let mut ns: Vec = std::fs::read_dir(root).map(|r| r.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); ns.sort(); - ns.into_iter().filter_map(|d| { let p = root.join(&d).join("SKILL.md"); let t = std::fs::read_to_string(&p).ok()?; if t.is_empty() { None } else { Some(parse_skill(&t, &d, &p.to_string_lossy())) } }).collect() -} -/// USkill.merge: the first list wins a name both use. -pub fn merge(us: Vec, ps: Vec) -> Vec { let mut v = us; for p in ps { if !v.iter().any(|x| x.name == p.name) { v.push(p) } } v } -/// Skills.scan: ~/.claude/skills, then /.claude/skills (the user's win a clash), then KiStack's. -pub fn scan(home: &str, cwd: &str, kistack: Option<&Path>) -> Vec { - let ks = kistack.map(|k| dir_skills(&k.join("skills"))).unwrap_or_default(); - merge(merge(dir_skills(&PathBuf::from(home).join(".claude/skills")), dir_skills(&PathBuf::from(cwd).join(".claude/skills"))), ks) -} -fn namec(c: char) -> bool { c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == ':' } -/// Mention.name: "$pcb-review," -> "pcb-review"; "" for a word that is no mention. -pub fn mention_name(w: &str) -> String { match w.strip_prefix('$') { Some(r) => r.chars().take_while(|c| namec(*c)).collect(), None => String::new() } } -/// Mention.expand for Claude: `$name` of a skill the user may invoke becomes `/name`, any other `$word` stays. -pub fn expand_claude(text: &str, ss: &[USkill]) -> String { - if !text.contains('$') { return text.to_string() } - text.split('\n').map(|l| l.split(' ').map(|w| { let n = mention_name(w); if !n.is_empty() && ss.iter().any(|s| s.user && s.name == n) { format!("/{}", &w[1..]) } else { w.to_string() } }).collect::>().join(" ")).collect::>().join("\n") -} - -/// Mention.note / Mention.others: for providers without skills of their own, the text as written after one instruction per named skill (once each) to read its SKILL.md. -pub fn mention_others(text: &str, ss: &[USkill]) -> String { - if !text.contains('$') { return text.to_string() } - let mut seen: Vec = vec![]; let mut notes: Vec = vec![]; - for w in text.split('\n').flat_map(|l| l.split(' ')) { - let n = mention_name(w); if n.is_empty() || seen.contains(&n) { continue } - if let Some(s) = ss.iter().find(|s| s.user && s.name == n) { seen.push(n.clone()); notes.push(format!("The user invoked the ${} skill: read \"{}\" completely before anything else and follow its instructions for this request.", s.name, s.path)) } - } - if notes.is_empty() { text.to_string() } else { format!("\n{}\n\n\n{}", notes.join("\n"), text) } -} // ---- attachments ---- pub const INLINE_MAX: u64 = 3_932_160; @@ -105,18 +41,6 @@ mod tests { let l: Value = serde_json::from_str(&claude_line_p("x", &[], "U", true)).unwrap(); assert_eq!(l["priority"], "now"); let l: Value = serde_json::from_str(&claude_line("x", &[], "U")).unwrap(); assert!(l.get("priority").is_none()); } - #[test] fn skills_read_their_frontmatter_including_folded_values() { - let s = parse_skill("---\nname: pcb-review\ndescription: >\n Review a board\n with care.\nuser-invocable: false\n---\nbody", "dir", "/p"); - assert_eq!((s.name.as_str(), s.description.as_str(), s.user, s.model), ("pcb-review", "Review a board with care.", false, true)); - let t = parse_skill("no frontmatter", "dflt", "/p"); assert_eq!(t.name, "dflt"); assert!(t.user); - let q = parse_skill("---\ndescription: \"Quoted: yes\"\ndisable-model-invocation: true\n---", "d", "/p"); assert_eq!(q.description, "Quoted: yes"); assert!(!q.model); - } - #[test] fn dollar_mentions_become_slash_commands_for_known_user_skills_only() { - let ss = vec![USkill { name: "pcb-review".into(), description: "".into(), path: "".into(), model: true, user: true }, USkill { name: "secret".into(), description: "".into(), path: "".into(), model: true, user: false }]; - assert_eq!(expand_claude("run $pcb-review, then $secret and $other\nnext $pcb-review", &ss), "run /pcb-review, then $secret and $other\nnext /pcb-review"); - assert_eq!(expand_claude("cost is 5", &ss), "cost is 5"); assert_eq!(mention_name("$a:b-c_d."), "a:b-c_d"); assert_eq!(mention_name("a$b"), ""); - } - #[test] fn user_skills_win_a_name_clash() { let u = |n: &str, p: &str| USkill { name: n.into(), description: "".into(), path: p.into(), model: true, user: true }; let m = merge(vec![u("a", "user")], vec![u("a", "proj"), u("b", "proj")]); assert_eq!(m.iter().map(|s| s.path.as_str()).collect::>(), ["user", "proj"]); } #[test] fn attachment_lines_at_the_end_are_the_attachments() { assert_eq!(att_paths("Look\n\n[attachment: /a/x.png]\n\n[attachment: /a/y.pdf]"), ["/a/x.png", "/a/y.pdf"]); assert!(att_paths("no\n[attachment: /a/x.png]\nmore").is_empty()); assert_eq!(mime("/a/X.JPEG"), "image/jpeg"); assert_eq!(mime("/a/x.pdf"), ""); } @@ -128,14 +52,3 @@ mod tests { let l: Value = serde_json::from_str(&claude_line(&text, &imgs, "U")).unwrap(); assert_eq!(l["uuid"], "U"); assert_eq!(l["message"]["content"][0]["type"], "image"); assert_eq!(l["message"]["content"][1]["text"], text.as_str()); } } - -#[cfg(test)] mod others_tests { - use super::*; - fn sk(n: &str) -> USkill { USkill { name: n.into(), description: String::new(), path: format!("/s/{n}/SKILL.md"), model: true, user: true } } - #[test] fn mention_others_names_each_skill_once_and_keeps_the_text() { - let t = "use $pcb, then $pcb again and $nope\nplus $bom."; let o = mention_others(t, &[sk("pcb"), sk("bom")]); - assert!(o.starts_with("\nThe user invoked the $pcb skill: read \"/s/pcb/SKILL.md\" completely before anything else and follow its instructions for this request.\nThe user invoked the $bom skill")); - assert!(o.ends_with("\n\nuse $pcb, then $pcb again and $nope\nplus $bom.")); assert_eq!(o.matches("$pcb skill").count(), 1); - assert_eq!(mention_others("no skills here", &[sk("pcb")]), "no skills here"); assert_eq!(mention_others("$unknown", &[sk("pcb")]), "$unknown"); - } -} diff --git a/native/host/src/agents/kistack.rs b/native/host/src/agents/kistack.rs index 77ab5b4422..f2a2ee35cb 100644 --- a/native/host/src/agents/kistack.rs +++ b/native/host/src/agents/kistack.rs @@ -47,7 +47,7 @@ pub fn describe(d: &Path) -> Copy { let rev = std::fs::read_to_string(d.join("REVISION")).map(|s| s.trim().to_string()).unwrap_or_default(); let mut skills: Vec<(String, String, String)> = std::fs::read_dir(d.join("skills")).into_iter().flatten().flatten().filter_map(|e| { let p = e.path().join("SKILL.md"); let t = std::fs::read_to_string(&p).ok()?; - let s = crate::agents::inputs::parse_skill(&t, &e.file_name().to_string_lossy(), &p.to_string_lossy()); Some((s.name, s.description, s.path)) + let s = crate::agents::skills::parse_skill(&t, &e.file_name().to_string_lossy(), &p.to_string_lossy()); Some((s.name, s.description, s.path)) }).collect(); skills.sort(); Copy { dir: d.to_string_lossy().into_owned(), pinned: rev == REV, rev, skills } @@ -103,9 +103,9 @@ mod tests { std::fs::write(&stale, "---\nname: kicad-schematic\ndescription: an older copy\n---\nold\n").unwrap(); let ss = crate::agents::skills::scan_all(&env, &home.to_string_lossy()); let f = crate::agents::skills::lookup(&ss, "kicad-schematic").expect("listed"); - assert_eq!((f.group.as_str(), f.kind), ("Backplane", crate::agents::skills::Kind::Hub), "the pinned copy wins the name"); + assert_eq!((f.group.as_str(), f.kind), ("Agents · yours", crate::agents::skills::Kind::Agents), "the user copy wins the name"); assert_eq!(ss.iter().filter(|f| f.name == "kicad-schematic" && f.kind == crate::agents::skills::Kind::Hub).count(), 1, "one entry, not one per root"); - assert!(crate::agents::skills::prepare("$kicad-schematic draw it", &ss, "codex", false).replace('\\', "/").contains("hub/kistack/skills/schematic/SKILL.md"), "Codex is told the file"); + assert!(crate::agents::skills::prepare("$kicad-schematic draw it", &ss, "codex", false).replace('\\', "/").contains(".agents/skills/schematic/SKILL.md"), "Codex is told the user file"); let _ = std::fs::remove_dir_all(&h); } } diff --git a/native/host/src/agents/mod.rs b/native/host/src/agents/mod.rs index 852a109d23..8cf0ac2daa 100644 --- a/native/host/src/agents/mod.rs +++ b/native/host/src/agents/mod.rs @@ -8,6 +8,7 @@ //! subagents and background tasks, todo tools, the allowance stream, the legacy queue, mail provenance beyond carry, //! and the hub's time-driven policies (liveness, autosettle, alert/told/summary, star nudge), which belong to M4. pub mod account_tools; pub mod halt; pub mod halt_view; pub mod review_mode; pub mod kicadsel; pub mod mcp_stdio; pub mod bundled; pub mod kistack; pub mod speed; pub mod mailroom; pub mod recall; pub mod devturns; pub mod bg; pub mod lockrec; pub mod locks; pub mod refs; pub mod person; pub mod work; pub mod textgen; pub mod iconpick; pub mod groupname; pub mod launch; pub mod far; pub mod review; pub mod tasks; pub mod codex; pub mod providers; pub mod cmds; pub mod design; pub mod snapguard; pub mod hist; pub mod host; pub mod inputs; pub mod skills; pub mod lines; pub mod mcp; pub mod proc; pub mod prompt; pub mod prompt_text; pub mod rules; pub mod settle; pub mod tools; pub mod unanswered; pub mod wake; pub mod world; +pub mod context; #[cfg(test)] mod tests; #[cfg(test)] mod laws; @@ -166,10 +167,30 @@ impl Agents { { if let Err(e) = w.sync(&self.hub.store) { eprintln!("agents: reading the log: {e:#}") } } w } - /// Hub.prompt for one thread: the host's facts, the project's files, the settings that change the words. + /// The exact context Backplane prepares for this provider, shared by the launch paths and inspector. + async fn prompt_context(&self, th: &str, cwd: &str, provider: &str, model: &str, isolated: bool) -> context::Prompt { + let bot = match self.mailroom() { Some(m) => m.prompt(th).await, None => String::new() }; + let base = format!("{}{bot}", self.prompt_base(th, cwd).await); + let env = skills::env_from(&self.host.user_home, &self.host.home, self.host.kistack.as_deref()); + let (cwd, provider, model) = (cwd.to_string(), provider.to_string(), model.to_string()); + let use_versions = !self.cli.test_mode(); + tokio::task::spawn_blocking(move || { + let claude = if provider == "claude" && use_versions { + let models: Value = serde_json::from_str(&crate::settings::models::info()).unwrap_or_default(); + let version = models["about"]["claude"]["cli"].as_str().unwrap_or(""); + let settings = if isolated { Value::Null } else { + let dir = std::env::var_os("CLAUDE_CONFIG_DIR").map(std::path::PathBuf::from) + .unwrap_or_else(|| std::path::Path::new(&env.home).join(".claude")); + std::fs::read_to_string(dir.join("settings.json")).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default() + }; + context::ClaudeFiles::configured(version, &settings) + } else { context::ClaudeFiles::default() }; + context::Prompt::build(base, &env, &cwd, &provider, &model, isolated, claude) + }).await.unwrap_or_default() + } pub async fn prompt_for(&self, th: &str, cwd: &str) -> String { - let bot = match self.mailroom() { Some(m) => m.prompt(th).await, None => String::new() }; // Bots.prompt - format!("{}{bot}", self.prompt_base(th, cwd).await) + let (provider, model) = self.world().await.threads.get(th).map(|t| (t.provider.clone(), t.model.clone())).unwrap_or_default(); + self.prompt_context(th, cwd, &provider, &model, false).await.text() } async fn prompt_base(&self, th: &str, cwd: &str) -> String { let (ipc, orders, lang, buy, code, plan) = { let w = self.world().await; @@ -192,7 +213,8 @@ impl Agents { let design = if f.pcb.is_empty() && f.sch.is_empty() { String::new() } else { prompt::design_words(&main, code.as_ref().filter(|c| !c.0.is_empty()).map(|c| (c.0.as_str(), c.1.as_str())), &locks) }; let keys = prompt::api_keys(&keys_path.to_string_lossy(), &prompt::key_names(&std::fs::read_to_string(&keys_path).unwrap_or_default())) + &prompt::secrets(&crate::settings::vault::names()); prompt::build(&prompt::PromptEnv { fc: crate::files::kicad::stepglb::told_freecad(&host.home, &host.fc), render: host.render.clone(), kicad: host.kicad.clone(), kicad_ipc: ipc, models: host.models_text(), may_delegate: true, orders_on: orders, routing_plan: plan, - root: main, pro: f.pro, pcb: f.pcb, sch: f.sch, all: cad.kicad.join("\n"), altium_projects: cad.altium, design, keys, machines, buy, lang, skills: host.bundled.as_deref().map(bundled::list).unwrap_or_default(), kistack: host.kistack.as_deref().map(kistack::describe) }) + // The context index supplies the skill catalog once, with provider scoping and overrides. + root: main, pro: f.pro, pcb: f.pcb, sch: f.sch, all: cad.kicad.join("\n"), altium_projects: cad.altium, design, keys, machines, buy, lang, skills: vec![], kistack: None }) }).await.unwrap_or_default() } /// PendingChanged: the number of open asks on a thread, written after an ask opens or closes (`extra` asks counted on top). @@ -466,7 +488,7 @@ impl Agents { struct Rpc(Arc); impl RpcHandler for Rpc { - fn methods(&self) -> &'static [&'static str] { &["turn.start", "turn.interrupt", "ask.answer", "thread.retitle", "thread.btw", "thread.halt", "thread.again", "thread.restore", "thread.review", "lock.release", "lock.cancel", "work.cancel", "task.stop", "text.write", "thread.hand", "thread.deliver"] } + fn methods(&self) -> &'static [&'static str] { &["turn.start", "turn.interrupt", "ask.answer", "thread.retitle", "thread.btw", "thread.halt", "thread.again", "thread.restore", "thread.review", "lock.release", "lock.cancel", "work.cancel", "task.stop", "text.write", "thread.hand", "thread.deliver", "thread.context", "thread.context.mcp"] } fn call<'a>(&'a self, hub: &'a Arc, who: &'a Caller, id: &'a Value, method: &'a str, p: &'a Value) -> Fut<'a, Vec> { Box::pin(async move { // the hub's own requests (`/give`, from commands/give.rs): a connection (client 1 and up) could say anything there, so it is never heard @@ -494,6 +516,42 @@ impl RpcHandler for Rpc { if method == "ask.answer" { return match self.0.answer(p.get("id").and_then(Value::as_str).unwrap_or(""), p.get("answer").and_then(Value::as_str).unwrap_or("")).await { Ok(()) => vec![ok(id)], Err(e) => vec![err(id, &e)] } } let th = p.get("thread").and_then(Value::as_str).unwrap_or(""); if th.is_empty() || !self.0.world().await.threads.contains_key(th) { eprintln!("agents: {method} refused: unknown thread {th:?}"); return vec![err(id, "unknown thread")] } // refused, and said so on the hub's log + if matches!(method, "thread.context" | "thread.context.mcp") { + if who.client == 0 { return vec![err(id, "A signed-in client is required")] } + let (cwd, provider, model) = { + let world = self.0.world().await; + let t = &world.threads[th]; + (world.cwd(th), t.provider.clone(), t.model.clone()) + }; + let home = hub.cfg.home.clone(); + let standalone = provider == "antigravity" && !providers::agy::pinned(&home.to_string_lossy()); + let (scan_cwd, scan_provider) = (cwd.clone(), provider.clone()); + let action = (method == "thread.context.mcp").then(|| { + (p["path"].as_str().unwrap_or("").to_string(), p["sha256"].as_str().unwrap_or("").to_string(), p["action"].as_str().unwrap_or("").to_string()) + }); + let mcp = tokio::task::spawn_blocking(move || { + use crate::mcpx::project; + if let Some((path, hash, action)) = action { + project::act(&home, &scan_cwd, &path, &hash, &action)?; + } + let blocked = standalone || project::ambient_conflict(&scan_cwd, &scan_provider, standalone).is_some(); + Ok::<_, String>(project::scan(&scan_cwd).iter().map(|c| c.view(&home, &scan_provider, blocked)).collect::>()) + }).await; + let mcp = match mcp { + Ok(Ok(mcp)) => mcp, + Ok(Err(e)) => return vec![err(id, &e)], + Err(_) => return vec![err(id, "Could not read project MCP configurations")], + }; + let binding = hub.setting(&crate::settings::accounts::binding_key(th, &provider)).await.unwrap_or_default(); + let isolated = serde_json::from_str::(&binding).ok().is_some_and(|b| b["id"].as_str().is_some_and(|s| !s.is_empty())); + let prompt = self.0.prompt_context(th, &cwd, &provider, &model, isolated).await; + return vec![json!({"t":"reply","id":id,"ok":true,"result":{ + "thread":th, "provider":provider, "model":model, "cwd":cwd, "instructions":prompt.instructions, + "skills":prompt.skills, "mcp":mcp, "prompt":prompt.text(), "sections":{ + "base":prompt.base, "instructions":prompt.project, "skills":prompt.index + } + }})] + } if method == "thread.btw" { let q = p.get("q").and_then(Value::as_str).unwrap_or("").trim().to_string(); if q.is_empty() { return vec![err(id, crate::session::composer::BTW_EMPTY)] } @@ -956,7 +1014,7 @@ impl Actor { } } let gen = format!("{now}-{}", self.ag.seq()); self.ag.set_gen(&th, &gen); - let prompt = self.ag.prompt_for(&th, cwd).await; + let prompt = self.ag.prompt_context(&th, cwd, &t.provider, &t.model, self.person || !acct_env.is_empty()).await.text(); let (effort, think, session) = { let w = self.ag.world().await; (w.setting(&format!("effort.{th}")).to_string(), self.cx.think, w.threads.get(&th).map(|x| x.session.clone()).unwrap_or_else(|| t.session.clone())) }; let session = if self.person { String::new() } else { session_over.unwrap_or(session) }; // a copied session is never resumed in side-by-side mode; another login's is not either (`account_route`) // infinite context (agents/recall.rs): a new turn runs in a fresh session with the view ahead of its text; a steer keeps the running turn's session @@ -964,15 +1022,15 @@ impl Actor { let session = if fresh { String::new() } else { session }; let text = if fresh { let v = self.ag.recall_view(&th).await; if v.is_empty() { text.to_string() } else { format!("{v}\n\n{text}") } } else { text.to_string() }; let url = self.ag.mcp.get().map(|m| m.url(&th, &gen)).unwrap_or_default(); - let (host, cwd2, text2, prov2) = (self.ag.host.clone(), cwd.to_string(), text.to_string(), t.provider.clone()); - let (body, imgs) = tokio::task::spawn_blocking(move || { let body = if text2.contains('$') { let ss = skills::scan_all(&skills::env_from(&host.user_home, &host.home, host.kistack.as_deref()), &cwd2); skills::prepare(&text2, &ss, &prov2, false) } else { text2.clone() }; (body, inputs::att_paths(&text2).into_iter().filter(|p| !inputs::mime(p).is_empty()).collect::>()) }).await.unwrap_or_default(); + let (host, cwd2, text2, prov2, model2) = (self.ag.host.clone(), cwd.to_string(), text.to_string(), t.provider.clone(), t.model.clone()); + let (body, imgs) = tokio::task::spawn_blocking(move || { let body = if text2.contains('$') { let ss = skills::scan_all(&skills::env_from(&host.user_home, &host.home, host.kistack.as_deref()), &cwd2); skills::prepare(&text2, &skills::for_model(&ss, &prov2, &model2), &prov2, false) } else { text2.clone() }; (body, inputs::att_paths(&text2).into_iter().filter(|p| !inputs::mime(p).is_empty()).collect::>()) }).await.unwrap_or_default(); if self.ag.stopped.load(Relaxed) || !self.ag.hub.cfg.home.exists() { return } let codex_home = if !cfg!(windows) { String::new() } else if let Some((_, dir)) = acct_env.iter().find(|(k, _)| k == "CODEX_HOME") { dir.clone() } else if self.ag.cli.test_mode() { String::new() } else if self.person { self.person_child().map(|pc| pc.home.join(".codex").to_string_lossy().into_owned()).unwrap_or_default() } else { std::env::var_os("CODEX_HOME").filter(|v| !v.is_empty()).map(|v| v.to_string_lossy().into_owned()).unwrap_or_else(|| std::path::Path::new(&self.ag.host.user_home).join(".codex").to_string_lossy().into_owned()) }; - let a = providers::TurnIn { thread: th.clone(), cwd: cwd.into(), home: self.ag.host.home.to_string_lossy().into_owned(), model: t.model.clone(), session, runtime: t.runtime.clone(), interaction: t.interaction.clone(), effort, think, text: body, images: imgs, prompt, mcp_url: url.clone(), pcbparts_url: String::new(), gen: gen.clone(), settings: { let w = self.ag.world().await; providers::SETTINGS.iter().map(|k| (k.to_string(), w.setting(k).to_string())).collect() }, mcp: crate::mcpx::svc::launch(&th, &t.provider, &url).await, speed: String::new(), speed_args: vec![], codex_home }; + let a = providers::TurnIn { thread: th.clone(), cwd: cwd.into(), home: self.ag.host.home.to_string_lossy().into_owned(), model: t.model.clone(), session, runtime: t.runtime.clone(), interaction: t.interaction.clone(), effort, think, text: body, images: imgs, prompt, mcp_url: url.clone(), pcbparts_url: String::new(), gen: gen.clone(), settings: { let w = self.ag.world().await; providers::SETTINGS.iter().map(|k| (k.to_string(), w.setting(k).to_string())).collect() }, mcp: crate::mcpx::svc::launch(&th, &t.provider, &url, cwd).await, speed: String::new(), speed_args: vec![], codex_home }; let a = providers::TurnIn { pcbparts_url: if a.mcp.pcbparts { crate::mcpx::gen::PCBPARTS.into() } else { String::new() }, ..a }; // the speed dial (agents/speed.rs): the mode the thread's model takes, passed the provider's way; recorded for the thread's usage (`turn.tier.`) let a = { let info = speed::info_now(); let want = self.ag.world().await.setting(&format!("speed.{th}")).to_string(); @@ -1109,7 +1167,7 @@ impl Actor { // the thread's MCP servers are part of the key: a list changed in Settings > MCP (or by an agent) starts Claude again at its next turn, on the same session // the speed dial too: a thread turned to Fast starts Claude again at its next turn with fast mode in its settings, on the same session let want = self.ag.world().await.setting(&format!("speed.{th}")).to_string(); let tier = speed::effective(&speed::info_now(), "claude", &t.model, &want); - let key = format!("{}|speed:{tier}|mcp:{}{}", rules::agent_key(&t.model, &t.runtime, &t.interaction, self.cx.think), crate::mcpx::svc::fingerprint(&th, "claude").await, if self.ag.in_review(&th).await { "|review" } else { "" }); // a review runs with deny rules for design files (snapguard.rs): a change of mode starts Claude again + let key = format!("{}|speed:{tier}|mcp:{}{}", rules::agent_key(&t.model, &t.runtime, &t.interaction, self.cx.think), crate::mcpx::svc::fingerprint(&th, "claude", &cwd).await, if self.ag.in_review(&th).await { "|review" } else { "" }); // a review runs with deny rules for design files (snapguard.rs): a change of mode starts Claude again self.tier_set(&th, tier, now).await; self.cx.tier_want = tier.to_string(); self.cx.tier = tier.to_string(); // a live process with a command still open (a turn in flight) is never replaced for a changed model/mode key: the message goes on its input (the CLI queues it) and the new key applies from the next process // infinite context (agents/recall.rs): a new turn (no command open: a message into a running turn goes on its input) starts a fresh session with the view @@ -1132,8 +1190,9 @@ impl Actor { let steer = std::mem::take(&mut self.steer_now); let bound = { let raw = self.ag.hub.setting(&crate::settings::accounts::binding_key(&th, "claude")).await.unwrap_or_default(); !serde_json::from_str::(&raw).ok().map_or(String::new(), |b| b["id"].as_str().unwrap_or("").to_string()).is_empty() }; let isolated = self.person || bound; // an account profile or the person mode runs Claude without the person's own skills and plugins + let model = t.model.clone(); let line = { let (text2, cwd2, host, uuid2) = (agent_text.clone(), cwd.clone(), self.ag.host.clone(), uuid.clone()); // Media.claude: images read, `$skill` mentions made real - tokio::task::spawn_blocking(move || { let body = if text2.contains('$') { let ss = skills::scan_all(&skills::env_from(&host.user_home, &host.home, host.kistack.as_deref()), &cwd2); skills::prepare(&text2, &ss, "claude", isolated) } else { text2.clone() }; let imgs = inputs::read_images(&text2); inputs::claude_line_p(&body, &imgs, &uuid2, steer) }).await.unwrap_or_default() }; + tokio::task::spawn_blocking(move || { let body = if text2.contains('$') { let ss = skills::scan_all(&skills::env_from(&host.user_home, &host.home, host.kistack.as_deref()), &cwd2); skills::prepare(&text2, &skills::for_model(&ss, "claude", &model), "claude", isolated) } else { text2.clone() }; let imgs = inputs::read_images(&text2); inputs::claude_line_p(&body, &imgs, &uuid2, steer) }).await.unwrap_or_default() }; let sent = self.live_proc.as_ref().map(|p| p.input.try_send(line)); if matches!(sent, Some(Ok(()))) { self.cmds = self.cmds.sent(&uuid) } else { self.fail("the agent is not taking input".into(), "input", &hub_id("in", now, 0)).await } } @@ -1294,7 +1353,7 @@ impl Actor { } if std::mem::take(&mut self.recall_fresh) { session = String::new(); self.handover = false; } // a new turn with infinite context: a fresh session, the view goes with its message let gen = format!("{now}-{}", self.ag.seq()); // Hub.gen: the process's generation, which its MCP URL names - let prompt = self.ag.prompt_for(&th, cwd).await; + let prompt = self.ag.prompt_context(&th, cwd, &t.provider, &t.model, self.person || !acct_env.is_empty()).await.text(); if self.ag.stopped.load(Relaxed) || !self.ag.hub.cfg.home.exists() { return Err("agents shut down".into()) } let own: Vec = self.ag.host.kistack.iter().chain(self.ag.host.bundled.iter()).map(|k| k.to_string_lossy().into_owned()).collect(); // KiStack's and Backplane's own skills let mut dirs = own.clone(); dirs.push(self.ag.host.home.join("attachments").to_string_lossy().into_owned()); @@ -1302,7 +1361,7 @@ impl Actor { let (effort, think, want) = { let w = self.ag.world().await; (w.setting(&format!("effort.{th}")).to_string(), self.cx.think, w.setting(&format!("speed.{th}")).to_string()) }; let speed = speed::effective(&speed::info_now(), "claude", &t.model, &want); let url = self.ag.mcp.get().map(|m| m.url(&th, &gen)).unwrap_or_default(); - let mcp = crate::mcpx::svc::launch(&th, "claude", &url).await; + let mcp = crate::mcpx::svc::launch(&th, "claude", &url, cwd).await; let mut disallowed = mcp.disallowed.clone(); if self.ag.in_review(&th).await { disallowed.extend(snapguard::CLAUDE_DENY.iter().map(|x| x.to_string())) } // a review's design files are read-only to Claude's own tools too let mut args = rules::claude_args(&rules::ArgsIn { model: &t.model, session: &session, runtime: &t.runtime, interaction: &t.interaction, prompt: &prompt, dirs: &dirs, effort: &effort, think, plugins: &plugins, mcp_url: &url, mcp_json: &mcp.claude, disallowed: &disallowed, speed }); let mut keep = vec![]; // the files Claude reads at its start, removed when it ends diff --git a/native/host/src/agents/providers/agy.rs b/native/host/src/agents/providers/agy.rs index 1d3137fdbb..65997ca434 100644 --- a/native/host/src/agents/providers/agy.rs +++ b/native/host/src/agents/providers/agy.rs @@ -455,7 +455,11 @@ impl Driver for AgyDriver { /// Agx.write before the run: the runner script, renamed into place, so a turn starting from it never sees half of it. Without the pinned agent, /// the person's agy CLI if there is one, with Backplane's MCP server kept in its mcp_config.json. fn prepare(&mut self, a: &TurnIn) -> Result<(), String> { - if !pinned(&a.home) { if let Some(p) = super::agy_cli::find() { + let standalone = !pinned(&a.home); + if let Some(path) = crate::mcpx::project::ambient_conflict(&a.cwd, "antigravity", standalone) { + return Err(format!("Antigravity can start project MCP servers outside Backplane’s approval. This runtime cannot safely open {}", path.display())) + } + if standalone { if let Some(p) = super::agy_cli::find() { let home = std::path::PathBuf::from(crate::plat::dirs::home_or_empty()); if let super::agy_cli::Mcp::Skipped(why) = super::agy_cli::ensure_mcp(&super::agy_cli::mcp_config(&home), !a.pcbparts_url.is_empty()) { self.cs.note = format!("Backplane's tools are not available to Antigravity this turn: {why}.") } self.bases = bases_from(&std::fs::read_to_string(bases_path(&a.home)).unwrap_or_default()); // the probe's folded list: model + effort -> agy's variant diff --git a/native/host/src/agents/providers/grok.rs b/native/host/src/agents/providers/grok.rs index ba0a118bfe..3e68f88da8 100644 --- a/native/host/src/agents/providers/grok.rs +++ b/native/host/src/agents/providers/grok.rs @@ -25,6 +25,15 @@ pub const INSTALL: &str = "Install Grok Build with `curl -fsSL https://x.ai/cli/ pub struct GrokDriver { pub turn: AcpTurn, pub a: Acp } impl GrokDriver { pub fn new() -> GrokDriver { GrokDriver { turn: AcpTurn::default(), a: Acp::new() } } } impl Driver for GrokDriver { + fn prepare(&mut self, a: &TurnIn) -> Result<(), String> { + if let Some(path) = crate::mcpx::project::ambient_conflict(&a.cwd, "grok", false) { + return Err(format!("Grok can start project MCP servers outside Backplane’s approval. This runtime cannot safely open {}", path.display())) + } + Ok(()) + } + fn env(&self, _a: &TurnIn) -> Vec<(String, String)> { + vec![("GROK_MCP_RECURSIVE_CONFIG_WATCH".into(), "false".into())] + } fn argv(&self, a: &TurnIn) -> Vec { args(&a.runtime, &a.model, &a.effort) } fn start(&mut self, a: &TurnIn) -> Vec { self.turn = AcpTurn { cwd: a.cwd.clone(), mcp: a.mcp_url.clone(), prompt: a.prompt.clone(), text: a.text.clone(), session: a.session.clone(), ask: asks(&a.runtime), servers: a.mcp.acp.clone(), model: if a.model == "default" { String::new() } else { a.model.clone() } }; diff --git a/native/host/src/agents/providers/msp.rs b/native/host/src/agents/providers/msp.rs index d31eb6a86b..12ab79a82f 100644 --- a/native/host/src/agents/providers/msp.rs +++ b/native/host/src/agents/providers/msp.rs @@ -5,7 +5,7 @@ use serde_json::{json, Value}; /// MspTurn: what a turn needs. `nonce` is the turn's gen: Muse refuses a command id it has seen, in any session. #[derive(Clone, Debug, Default)] -pub struct MspTurn { pub cwd: String, pub mcp: String, /** the built-in parts search's URL; empty when it is off */ pub pcbparts: String, pub prompt: String, pub text: String, pub session: String, pub mode: String, pub effort: String, pub nonce: String, pub model: String } +pub struct MspTurn { pub cwd: String, pub mcp: String, /** the built-in parts search's URL; empty when it is off */ pub pcbparts: String, pub prompt: String, pub text: String, pub session: String, pub mode: String, pub effort: String, pub nonce: String, pub model: String, pub servers: Value } /// AcpOut: lines to write to Muse, shapes for the log, approval requests for the person (the raw request line each). #[derive(Debug, Default)] @@ -41,6 +41,20 @@ pub fn init() -> String { fn config(t: &MspTurn) -> Value { let mut m = json!({"backplane":{"transport":"streamableHttp","url":t.mcp,"mode":"optional"}}); if !t.pcbparts.is_empty() { m["pcbparts"] = json!({"transport":"streamableHttp","url":t.pcbparts,"mode":"optional"}) } + let pairs = |v: &Value| -> Value { + Value::Object(v.as_array().into_iter().flatten().filter_map(|entry| { + Some((entry["name"].as_str()?.to_string(), entry["value"].clone())) + }).collect()) + }; + for server in t.servers.as_array().into_iter().flatten() { + let Some(name) = server["name"].as_str().filter(|n| n.starts_with("project-")) else { continue }; + if server["command"].is_string() { + m[name] = json!({"transport":"stdio","command":server["command"],"args":server["args"], + "env":pairs(&server["env"]),"mode":"optional"}); + } else if server["type"] == "http" { + m[name] = json!({"transport":"streamableHttp","url":server["url"],"headers":pairs(&server["headers"]),"mode":"optional"}); + } + } json!({"mcpServers": m}) } /// Msp.open: a new session or the thread's own. @@ -186,7 +200,7 @@ pub fn mode(runtime: &str) -> &'static str { mode_k(match runtime { "approval-re mod tests { use super::*; fn j(s: &str) -> Value { serde_json::from_str(s).unwrap() } - fn turn(sid: &str) -> MspTurn { MspTurn { cwd: "/tmp/p".into(), mcp: "http://127.0.0.1:1/mcp/t?token=x".into(), pcbparts: "https://pcbparts.dev/mcp".into(), prompt: "RULES".into(), text: "hello".into(), session: sid.into(), mode: "promptUnmatched".into(), effort: "".into(), nonce: "1791825557-42".into(), model: "".into() } } + fn turn(sid: &str) -> MspTurn { MspTurn { cwd: "/tmp/p".into(), mcp: "http://127.0.0.1:1/mcp/t?token=x".into(), pcbparts: "https://pcbparts.dev/mcp".into(), prompt: "RULES".into(), text: "hello".into(), session: sid.into(), mode: "promptUnmatched".into(), effort: "".into(), nonce: "1791825557-42".into(), model: "".into(), servers: Value::Null } } fn turn_hi(sid: &str) -> MspTurn { MspTurn { mode: "allowAll".into(), effort: "high".into(), nonce: "1791825557-43".into(), ..turn(sid) } } fn m(l: &str) -> String { j(l)["method"].as_str().unwrap_or("").to_string() } fn p(l: &str) -> Value { j(l)["params"].clone() } diff --git a/native/host/src/agents/providers/muse.rs b/native/host/src/agents/providers/muse.rs index a95222964e..b3aabaea10 100644 --- a/native/host/src/agents/providers/muse.rs +++ b/native/host/src/agents/providers/muse.rs @@ -27,10 +27,16 @@ pub fn ask_shape(request_line: &str) -> Value { json!({"type":"bp.ask","request" pub struct MuseDriver { turn: msp::MspTurn, st: msp::Msp, runtime: String } impl MuseDriver { pub fn new() -> MuseDriver { MuseDriver { turn: msp::MspTurn::default(), st: msp::Msp::new(), runtime: String::new() } } pub fn done(&self) -> bool { self.st.done } } impl Driver for MuseDriver { + fn prepare(&mut self, a: &TurnIn) -> Result<(), String> { + if let Some(path) = crate::mcpx::project::ambient_conflict(&a.cwd, "muse", false) { + return Err(format!("Muse can start project MCP servers outside Backplane’s approval. This runtime cannot safely open {}", path.display())) + } + Ok(()) + } fn argv(&self, a: &TurnIn) -> Vec { args(&a.runtime, &a.model) } fn start(&mut self, a: &TurnIn) -> Vec { self.runtime = a.runtime.clone(); - self.turn = msp::MspTurn { cwd: a.cwd.clone(), mcp: a.mcp_url.clone(), pcbparts: a.pcbparts_url.clone(), prompt: a.prompt.clone(), text: a.text.clone(), session: a.session.clone(), mode: msp::mode(&a.runtime).into(), effort: effort(&a.effort).into(), nonce: nonce(&a.gen), model: if a.model == "default" { String::new() } else { a.model.clone() } }; + self.turn = msp::MspTurn { cwd: a.cwd.clone(), mcp: a.mcp_url.clone(), pcbparts: a.pcbparts_url.clone(), prompt: a.prompt.clone(), text: a.text.clone(), session: a.session.clone(), mode: msp::mode(&a.runtime).into(), effort: effort(&a.effort).into(), nonce: nonce(&a.gen), servers: a.mcp.acp.clone(), model: if a.model == "default" { String::new() } else { a.model.clone() } }; self.st = msp::Msp::new(); vec![msp::init()] } diff --git a/native/host/src/agents/providers/omp.rs b/native/host/src/agents/providers/omp.rs index e63100f449..0db00acde6 100644 --- a/native/host/src/agents/providers/omp.rs +++ b/native/host/src/agents/providers/omp.rs @@ -136,21 +136,31 @@ pub fn prepare(home: &str, prompt: &str, extension: &str) -> std::io::Result std::io::Result<()> { std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(dir.join(name))?.write_all(text.as_bytes()) }; - if let Err(e) = put("system-prompt.txt", prompt).and_then(|_| put("backplane.js", extension)) { let _ = std::fs::remove_dir_all(&dir); return Err(e) } + if let Err(e) = put("system-prompt.txt", prompt).and_then(|_| put("backplane.js", extension)).and_then(|_| put("settings.yml", "mcp:\n enableProjectConfig: false\n")) { let _ = std::fs::remove_dir_all(&dir); return Err(e) } Ok(dir) } /// OmpLaunch.remove: only the folder `prepare` returned. pub fn remove(dir: &std::path::Path) { let _ = std::fs::remove_dir_all(dir); } /// The driver of one Oh My Pi turn. -pub struct OmpDriver { acp: Acp, turn: pi::Turn, launch: std::cell::RefCell> } -impl OmpDriver { pub fn new() -> OmpDriver { OmpDriver { acp: Acp::default(), turn: pi::Turn::default(), launch: std::cell::RefCell::new(None) } } } +pub struct OmpDriver { acp: Acp, turn: pi::Turn, launch: std::cell::RefCell>, overlays: std::cell::RefCell } +impl OmpDriver { pub fn new() -> OmpDriver { OmpDriver { acp: Acp::default(), turn: pi::Turn::default(), launch: std::cell::RefCell::new(None), overlays: Default::default() } } } impl Default for OmpDriver { fn default() -> Self { Self::new() } } impl OmpDriver { /// OmpLaunch.prepare + Grok.failed: the turn's private launch folder, or the words of a turn that could not start (the actor says "could not start omp: " first). pub fn prepare_turn(&self, a: &TurnIn) -> Result<(), String> { - match prepare(&a.home, &a.prompt, EXT) { Ok(d) => { *self.launch.borrow_mut() = Some(d); Ok(()) } Err(e) => Err(launch_why(&e)) } + let dir = prepare(&a.home, &a.prompt, EXT).map_err(|e| launch_why(&e))?; + let inherited = std::env::var_os("PI_CONFIG_FILES").unwrap_or_default(); + let paths = std::env::split_paths(&inherited).filter(|p| !p.as_os_str().is_empty()).chain([dir.join("settings.yml")]); + let overlays = std::env::join_paths(paths).ok().and_then(|p| p.into_string().ok()); + let Some(overlays) = overlays else { + remove(&dir); + return Err("Oh My Pi could not load Backplane’s project MCP policy overlay".into()) + }; + *self.overlays.borrow_mut() = overlays; + *self.launch.borrow_mut() = Some(dir); + Ok(()) } } /// Proto.install @@ -178,7 +188,13 @@ impl Driver for OmpDriver { let mut v = args(mode(&a.runtime), &dir(&a.home, &a.thread), &files, pi::model(&a.model), effort(&a.effort)); v.extend(a.speed_args.iter().cloned()); v // the speed dial: `--service-tier priority|ultrafast` (agents/speed.rs) } - fn env(&self, a: &TurnIn) -> Vec<(String, String)> { vec![("BACKPLANE_OMP_MCP".into(), a.mcp_url.clone()), ("BACKPLANE_OMP_PCBPARTS".into(), a.pcbparts_url.clone())] } + fn env(&self, a: &TurnIn) -> Vec<(String, String)> { + let mut env = vec![("BACKPLANE_OMP_MCP".into(), a.mcp_url.clone()), ("BACKPLANE_OMP_PCBPARTS".into(), a.pcbparts_url.clone())]; + env.extend(crate::mcpx::gen::extension_env(&a.mcp.acp, "BACKPLANE_OMP_SERVERS")); + let overlay = self.overlays.borrow(); + if !overlay.is_empty() { env.push(("PI_CONFIG_FILES".into(), overlay.clone())); } + env + } fn start(&mut self, a: &TurnIn) -> Vec { self.turn = pi::Turn { text: a.text.clone(), session: a.session.clone(), ask: pi::asks(&a.runtime) }; self.acp = Acp::default(); init() } @@ -214,7 +230,9 @@ mod tests { let a = TurnIn { thread: "th".into(), home: dir_.to_string_lossy().into(), model: "openai/gpt".into(), session: "S9".into(), runtime: "approval-required".into(), text: "say this".into(), prompt: "P".into(), mcp_url: "http://mcp".into(), ..TurnIn::default() }; let argv = d.argv(&a); assert!(argv.windows(2).any(|w| w == ["--model", "openai/gpt"]) && argv.windows(2).any(|w| w == ["--approval-mode", "always-ask"]), "model and runtime reach argv"); - assert_eq!(d.env(&a), vec![("BACKPLANE_OMP_MCP".to_string(), "http://mcp".to_string()), ("BACKPLANE_OMP_PCBPARTS".into(), String::new())]); + let env = d.env(&a); + assert_eq!(&env[..2], [("BACKPLANE_OMP_MCP".to_string(), "http://mcp".to_string()), ("BACKPLANE_OMP_PCBPARTS".into(), String::new())]); + assert!(env.iter().any(|(k, v)| k == "PI_CONFIG_FILES" && v.ends_with("settings.yml"))); let on = TurnIn { pcbparts_url: "https://pcbparts.dev/mcp".into(), ..a.clone() }; assert_eq!(d.env(&on)[1], ("BACKPLANE_OMP_PCBPARTS".to_string(), "https://pcbparts.dev/mcp".to_string()), "the parts search, as Claude gets it"); assert!(EXT.contains("connect(pi, 'pcbparts', parts)")); d.start(&a); @@ -249,7 +267,8 @@ mod tests { assert!(!v.iter().any(|x| x == "THE PROMPT")); // never in argv assert_eq!(std::fs::read_to_string(launch.join("system-prompt.txt")).unwrap(), "THE PROMPT"); assert_eq!(std::fs::read_to_string(launch.join("backplane.js")).unwrap(), EXT); { use crate::plat::fs::PermissionsExt; assert_eq!(crate::plat::fs::mode_bits(std::fs::metadata(launch.join("system-prompt.txt")).unwrap().permissions().mode() & 0o777, 0o600), 0o600); assert_eq!(crate::plat::fs::mode_bits(std::fs::metadata(&launch).unwrap().permissions().mode() & 0o777, 0o700), 0o700); } - assert_eq!(d.env(&a), vec![("BACKPLANE_OMP_MCP".to_string(), "http://m".to_string()), ("BACKPLANE_OMP_PCBPARTS".into(), String::new())]); + assert_eq!(&d.env(&a)[..2], [("BACKPLANE_OMP_MCP".to_string(), "http://m".to_string()), ("BACKPLANE_OMP_PCBPARTS".into(), String::new())]); + assert_eq!(std::fs::read_to_string(launch.join("settings.yml")).unwrap(), "mcp:\n enableProjectConfig: false\n"); drop(d); assert!(!launch.exists()); a.model = "openai/gpt".into(); a.effort = "turbo".into(); let d2 = OmpDriver::new(); let v2 = d2.argv(&a); assert_eq!(&v2[v2.len() - 2..], ["--model", "openai/gpt"]); drop(d2); } @@ -319,5 +338,5 @@ mod tests { assert_eq!(r[0].plain()[1], json!({"type":"notice","message":"Oh My Pi had no saved conversation for this thread, so this turn starts without the earlier context. This thread's history in Backplane is kept."})); } // the file is generated from omp by test/agents/prov-pi/gen_ext.py (its source, the Bend hub, is gone: this file is the source now, with pcbparts added); its bytes are pinned - #[test] fn the_extension_is_omp_byte_for_byte() { use sha2::{Digest, Sha256}; assert_eq!(hex::encode(Sha256::digest(EXT.as_bytes())), "2cc26e2377ddd0c2f9aeb205dde788d0cdf7e1dc997a0fb21ff1c60563ab15dd") } + #[test] fn the_extension_is_omp_byte_for_byte() { use sha2::{Digest, Sha256}; assert_eq!(hex::encode(Sha256::digest(EXT.as_bytes())), "d416263c66f5e4e2082cf4167d7ec0493fedd1fe2a63e6774d6e0e3c4e49b0f8") } } diff --git a/native/host/src/agents/providers/omp_ext.js b/native/host/src/agents/providers/omp_ext.js index ebc7f8820b..ac54fe1157 100644 --- a/native/host/src/agents/providers/omp_ext.js +++ b/native/host/src/agents/providers/omp_ext.js @@ -2,15 +2,64 @@ // Backplane's MCP tools for this thread (BACKPLANE_OMP_MCP) and the built-in // parts search (BACKPLANE_OMP_PCBPARTS, unset when it is off), as omp tools // named as Claude sees them (mcp____), each a call to its server. -const connect = async (pi, server, url) => { +import { spawn } from 'node:child_process'; +import { createInterface } from 'node:readline'; + +const stdio = (server) => { + const child = spawn(server.command, server.args, { + env: { ...process.env, ...Object.fromEntries(server.env.map(({ name, value }) => [name, value])) }, + stdio: ['pipe', 'pipe', 'ignore'], + }); + const pending = new Map(); + const rejectAll = error => { + for (const done of pending.values()) done(null, error); + }; + child.on('error', rejectAll); + child.on('close', () => rejectAll(new Error('MCP server closed its connection'))); + createInterface({ input: child.stdout }).on('line', line => { + try { + const reply = JSON.parse(line); + pending.get(reply.id)?.(reply, null); + } catch { /* stdio transports require newline-delimited JSON */ } + }); + return (request, signal) => new Promise((resolve, reject) => { + if (signal?.aborted) return reject(signal.reason); + const cleanup = () => { + clearTimeout(timer); + signal?.removeEventListener('abort', cancel); + pending.delete(request.id); + }; + const done = (reply, error) => { + cleanup(); + if (error) reject(error); else resolve(reply); + }; + const cancel = () => done(null, signal.reason); + const timer = setTimeout(() => done(null, new Error('MCP request timed out')), 30_000); + signal?.addEventListener('abort', cancel, { once: true }); + if (request.id !== undefined) pending.set(request.id, done); + child.stdin.write(JSON.stringify(request) + '\n', error => { + if (error || request.id === undefined) done({}, error); + }); + }); +}; + +const connect = async (pi, server, url, config = null) => { + if (config?.type === 'sse') return; + const pipe = config?.command ? stdio(config) : null; let session = '', n = 0; const post = (body, signal) => { - const headers = { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }; + const headers = { ...Object.fromEntries((config?.headers || []).map(({ name, value }) => [name, value])), 'content-type': 'application/json', accept: 'application/json, text/event-stream' }; if (session) headers['mcp-session-id'] = session; return fetch(url, { method: 'POST', headers, signal, body: JSON.stringify(body) }); }; const call = async (method, params, signal) => { - const r = await post({ jsonrpc: '2.0', id: ++n, method, params }, signal); + const request = { jsonrpc: '2.0', id: ++n, method, params }; + if (pipe) { + const reply = await pipe(request, signal); + if (reply.error) throw new Error(reply.error.message || server + ' MCP error'); + return reply.result || {}; + } + const r = await post(request, signal); session = r.headers.get('mcp-session-id') || session; const text = (await r.text()).trim(); const body = text.startsWith('{') ? text : (text.split('\n').filter(l => l.startsWith('data:')).map(l => l.slice(5)).pop() || '{}'); @@ -21,7 +70,8 @@ const connect = async (pi, server, url) => { let tools = []; try { await call('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'backplane-omp', version: '1' } }); - await post({ jsonrpc: '2.0', method: 'notifications/initialized' }).then(r => r.text()).catch(() => {}); + const ready = { jsonrpc: '2.0', method: 'notifications/initialized' }; + if (pipe) await pipe(ready); else await post(ready).then(r => r.text()).catch(() => {}); tools = (await call('tools/list', {})).tools || []; } catch (e) { const who = server === 'backplane' ? 'Backplane tools' : 'The ' + server + ' tools'; @@ -33,7 +83,7 @@ const connect = async (pi, server, url) => { name: 'mcp__' + server + '__' + t.name, label: server + '/' + t.name, description: t.description || (server + ': ' + t.name), parameters: t.inputSchema || { type: 'object', properties: {} }, - approval: 'read', loadMode: 'essential', strict: false, + approval: config ? undefined : 'read', loadMode: 'essential', strict: false, async execute(_id, params, signal) { const r = await call('tools/call', { name: t.name, arguments: params || {} }, signal); return { content: Array.isArray(r.content) ? r.content : [{ type: 'text', text: JSON.stringify(r) }], isError: !!r.isError }; @@ -45,5 +95,8 @@ export default async function (pi) { const url = process.env.BACKPLANE_OMP_MCP || ''; if (!url) return; const parts = process.env.BACKPLANE_OMP_PCBPARTS || ''; - await Promise.all([connect(pi, 'backplane', url), parts ? connect(pi, 'pcbparts', parts) : null]); + const servers = JSON.parse(process.env.BACKPLANE_OMP_SERVERS || '[]'); + delete process.env.BACKPLANE_OMP_SERVERS; + await Promise.all([connect(pi, 'backplane', url), parts ? connect(pi, 'pcbparts', parts) : null, + ...servers.map(server => connect(pi, server.name, server.url, server))]); } diff --git a/native/host/src/agents/providers/pi.rs b/native/host/src/agents/providers/pi.rs index a97f6a27b2..d81dc9dba2 100644 --- a/native/host/src/agents/providers/pi.rs +++ b/native/host/src/agents/providers/pi.rs @@ -280,7 +280,11 @@ impl Driver for PiDriver { v.extend(kistack_arg(&a.home)); v } /// BACKPLANE_PI_MCP and BACKPLANE_PI_MODE: what Backplane's extension reads. - fn env(&self, a: &TurnIn) -> Vec<(String, String)> { vec![("BACKPLANE_PI_MCP".into(), a.mcp_url.clone()), ("BACKPLANE_PI_PCBPARTS".into(), a.pcbparts_url.clone()), ("BACKPLANE_PI_MODE".into(), mode(&a.runtime).into())] } + fn env(&self, a: &TurnIn) -> Vec<(String, String)> { + let mut env = vec![("BACKPLANE_PI_MCP".into(), a.mcp_url.clone()), ("BACKPLANE_PI_PCBPARTS".into(), a.pcbparts_url.clone()), ("BACKPLANE_PI_MODE".into(), mode(&a.runtime).into())]; + env.extend(crate::mcpx::gen::extension_env(&a.mcp.acp, "BACKPLANE_PI_SERVERS")); + env + } fn start(&mut self, a: &TurnIn) -> Vec { self.turn = Turn { text: a.text.clone(), session: a.session.clone(), ask: asks(&a.runtime) }; self.acp = Acp::default(); vec![init()] } @@ -350,7 +354,7 @@ mod tests { assert_eq!(d.argv(&a)[3], "sess-1"); assert_eq!(d.argv(&a).len(), 8); } // the file is generated from pi by test/agents/prov-pi/gen_ext.py (its source, the Bend hub, is gone: this file is the source now, with pcbparts added); its bytes are pinned - #[test] fn the_extension_is_pi_byte_for_byte() { use sha2::{Digest, Sha256}; assert_eq!(hex::encode(Sha256::digest(EXT.as_bytes())), "83f96d0c0cb7d68d42bd9e0a8948ae5077b3554d62bcb8c53b6465bea0756c42") } + #[test] fn the_extension_is_pi_byte_for_byte() { use sha2::{Digest, Sha256}; assert_eq!(hex::encode(Sha256::digest(EXT.as_bytes())), "e8fcfc311e8ff453d7db88e4f9122cbaec8adebc0b3f64eb7481fbf8cd2fc405") } #[test] fn a_turn_streams_a_reply_and_ends() { let mut d = PiDriver::new(); assert_eq!(d.start(&ti("full-access")), vec![r#"{"id":"1","type":"get_state"}"#]); diff --git a/native/host/src/agents/providers/pi_ext.js b/native/host/src/agents/providers/pi_ext.js index 9adfc2e989..7977b8b7bb 100644 --- a/native/host/src/agents/providers/pi_ext.js +++ b/native/host/src/agents/providers/pi_ext.js @@ -8,6 +8,18 @@ export default function (pi) { const mode = process.env.BACKPLANE_PI_MODE || 'ask'; if (url) pi.registerMcpServer('backplane', { url, exposure: 'direct', description: 'Backplane: this thread, its project, viewers and other threads' }); if (parts) pi.registerMcpServer('pcbparts', { url: parts, exposure: 'direct', description: "Parts search: the fab's stock, Mouser, DigiKey" }); + const servers = JSON.parse(process.env.BACKPLANE_PI_SERVERS || '[]'); + delete process.env.BACKPLANE_PI_SERVERS; + for (const server of servers) { + const entries = values => Object.fromEntries(values.map(({ name, value }) => [name, value])); + if (server.type === 'sse') continue; // Pi supports streamable HTTP and stdio. + // Pi's file format treats !command and ${VAR} as expressions. ACP headers are literals. + if ((server.headers || []).some(({ value }) => value.startsWith('!') || value.includes('${'))) continue; + const transport = server.command + ? { command: server.command, args: server.args, env: entries(server.env || []) } + : { url: server.url, headers: entries(server.headers || []) }; + pi.registerMcpServer(server.name, { ...transport, exposure: 'direct' }); + } const reads = new Set(['read', 'grep', 'find', 'ls']); const edits = new Set(['edit', 'write']); pi.on('tool_call', async (event, ctx) => { diff --git a/native/host/src/agents/rules.rs b/native/host/src/agents/rules.rs index a5dafbc9eb..575eb3e5a3 100644 --- a/native/host/src/agents/rules.rs +++ b/native/host/src/agents/rules.rs @@ -54,6 +54,7 @@ pub fn claude_args(a: &ArgsIn) -> Vec { if a.think { v.push(s("--thinking-display")); v.push(s("summarized")); } for d in a.plugins { v.push(s("--plugin-dir")); v.push(s(d)); } v.push(s("--settings")); v.push(super::speed::claude_settings(a.speed)); + v.push(s("--strict-mcp-config")); v.push(s("--mcp-config")); v.push(if a.mcp_json.is_empty() { mcp_config(a.mcp_url) } else { a.mcp_json.to_string() }); v } @@ -270,12 +271,12 @@ mod tests { #[test] fn modes_map_to_claudes_permission_flags() { assert_eq!(permission("full-access", "default"), "bypassPermissions"); assert_eq!(permission("approval-required", "default"), "default"); assert_eq!(permission("full-access", "plan"), "plan"); let mk = |m: &'static str, s: &'static str, r: &'static str| ArgsIn { model: m, session: s, runtime: r, interaction: "default", prompt: "P", dirs: &[], effort: "", think: false, plugins: &[], mcp_url: "http://u", mcp_json: "", disallowed: &[], speed: "" }; - let a = claude_args(&mk("opus", "S", "full-access")); assert!(!a.contains(&"--permission-prompt-tool".to_string())); assert_eq!(&a[a.len() - 8..a.len() - 4], ["--model", "opus", "--resume", "S"]); - assert_eq!(&a[a.len() - 4..a.len() - 2], ["--settings", r#"{"fastMode":false}"#], "Normal says fast mode off, whatever the person's own settings saved"); - let mut f = mk("opus", "", "full-access"); f.speed = "fast"; let fa = claude_args(&f); assert_eq!(fa[fa.len() - 3], r#"{"fastMode":true}"#); + let a = claude_args(&mk("opus", "S", "full-access")); assert!(!a.contains(&"--permission-prompt-tool".to_string())); assert_eq!(&a[a.len() - 9..a.len() - 5], ["--model", "opus", "--resume", "S"]); + assert_eq!(&a[a.len() - 5..a.len() - 3], ["--settings", r#"{"fastMode":false}"#], "Normal says fast mode off, whatever the person's own settings saved"); + let mut f = mk("opus", "", "full-access"); f.speed = "fast"; let fa = claude_args(&f); assert_eq!(fa[fa.len() - 4], r#"{"fastMode":true}"#); assert!(claude_args(&mk("", "", "auto")).contains(&"--permission-prompt-tool".to_string())); let mut x = mk("", "", "full-access"); let dirs = vec!["/k".to_string(), "/h/attachments".to_string()]; x.dirs = &dirs; x.effort = "high"; x.think = true; x.plugins = &dirs[..1]; - let a = claude_args(&x); assert_eq!(&a[a.len() - 14..a.len() - 4], ["--add-dir", "/k", "--add-dir", "/h/attachments", "--effort", "high", "--thinking-display", "summarized", "--plugin-dir", "/k"]); assert_eq!(a[a.len() - 2], "--mcp-config"); + let a = claude_args(&x); assert_eq!(&a[a.len() - 15..a.len() - 5], ["--add-dir", "/k", "--add-dir", "/h/attachments", "--effort", "high", "--thinking-display", "summarized", "--plugin-dir", "/k"]); assert_eq!(a[a.len() - 2], "--mcp-config"); } #[test] fn the_restart_note_reads_the_person_zone() { assert_eq!(clock("", 0), "00:00"); assert_eq!(clock("UTC", 3600 * 5 + 60 * 7), "05:07"); diff --git a/native/host/src/agents/skills.rs b/native/host/src/agents/skills.rs index 23de79aaf5..8298567421 100644 --- a/native/host/src/agents/skills.rs +++ b/native/host/src/agents/skills.rs @@ -3,17 +3,99 @@ //! `settings.json` turns off is left out; a directory marketplace of a missing install is read in place). Codex: ~/.codex/skills (or $CODEX_HOME/skills), //! ~/.agents/skills, /.agents/skills. Backplane's own: KiStack's skills, /skills and the bundled ones (/bundled/skills, bundled.rs). //! A skill the thread's provider loads itself is "native": Claude gets `/name`, Codex its own `$name`. Any other is "read": the turn's text names the SKILL.md to read first. -use crate::agents::inputs::{mention_name, mention_others, parse_skill, USkill}; use serde_json::{json, Value}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; +// ---- skills ---- +#[derive(Clone, Debug, Default, PartialEq)] +pub struct USkill { pub name: String, pub description: String, pub path: String, pub model: bool, pub user: bool, pub provider: String, pub model_pattern: String } + +fn unquote(s: &str) -> String { if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 { s[1..s.len() - 1].to_string() } else { s.to_string() } } +fn field(line: &str, key: &str) -> Option { line.strip_prefix(&format!("{key}:")).map(|r| unquote(r.trim())) } +/// Front.join / Front.cont / Front.fold: a value carried on to indented lines is read whole on its key's line. +fn fold(ls: &[&str]) -> Vec { + let mut acc: Vec = vec![]; let mut open = true; + for l in ls { + let cont = open && (l.starts_with(' ') || l.starts_with('\t')) && !l.trim().is_empty() && l.trim() != "---"; + if cont && !acc.is_empty() { + let h = acc.pop().unwrap().trim_end().to_string(); let s = l.trim(); + let one = h.ends_with(": >") || h.ends_with(": |"); let two = [": >-", ": |-", ": >+", ": |+"].iter().any(|e| h.ends_with(e)); + acc.push(if one { format!("{}{s}", &h[..h.len() - 1]) } else if two { format!("{}{s}", &h[..h.len() - 2]) } else { format!("{h} {s}") }); + } else { acc.push(l.to_string()) } + if l.trim() == "---" { open = false } + } + acc +} +/// USkill.parse: the leading --- block's name, description, disable-model-invocation, user-invocable. +pub fn parse_skill(text: &str, dflt: &str, path: &str) -> USkill { + let ls: Vec<&str> = text.split('\n').collect(); + let (mut n, mut d, mut m, mut u) = (dflt.to_string(), String::new(), String::new(), String::new()); + let (mut provider, mut model_pattern) = (String::new(), String::new()); + if ls.first().map_or(false, |l| l.trim() == "---") { + for l in fold(&ls[1..]) { if l.trim() == "---" { break } + if let Some(v) = field(&l, "provider") { provider = v } + if let Some(v) = field(&l, "model") { model_pattern = v } + if let Some(v) = field(&l, "name") { n = v } if let Some(v) = field(&l, "description") { d = v } + if let Some(v) = field(&l, "disable-model-invocation") { m = v } if let Some(v) = field(&l, "user-invocable") { u = v } } + } + let flag = |v: &str, dv: bool| match v.to_lowercase().as_str() { "true" => true, "false" => false, _ => dv }; + USkill { name: n, description: d, path: path.into(), model: !flag(&m, false), user: flag(&u, true), provider, model_pattern } +} +fn namec(c: char) -> bool { c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == ':' } +/// Mention.name: "$pcb-review," -> "pcb-review"; "" for a word that is no mention. +pub fn mention_name(w: &str) -> String { match w.strip_prefix('$') { Some(r) => r.chars().take_while(|c| namec(*c)).collect(), None => String::new() } } +/// Mention.expand for Claude: `$name` of a skill the user may invoke becomes `/name`, any other `$word` stays. +pub fn expand_claude(text: &str, ss: &[USkill]) -> String { + if !text.contains('$') { return text.to_string() } + text.split('\n').map(|l| l.split(' ').map(|w| { let n = mention_name(w); if !n.is_empty() && ss.iter().any(|s| s.user && s.name == n) { format!("/{}", &w[1..]) } else { w.to_string() } }).collect::>().join(" ")).collect::>().join("\n") +} + +/// Mention.note / Mention.others: for providers without skills of their own, the text as written after one instruction per named skill (once each) to read its SKILL.md. +pub fn mention_others(text: &str, ss: &[USkill]) -> String { + if !text.contains('$') { return text.to_string() } + let mut seen: Vec = vec![]; let mut notes: Vec = vec![]; + for w in text.split('\n').flat_map(|l| l.split(' ')) { + let n = mention_name(w); if n.is_empty() || seen.contains(&n) { continue } + if let Some(s) = ss.iter().find(|s| s.user && s.name == n) { seen.push(n.clone()); notes.push(format!("The user invoked the ${} skill: read \"{}\" completely before anything else and follow its instructions for this request.", s.name, s.path)) } + } + if notes.is_empty() { text.to_string() } else { format!("\n{}\n\n\n{}", notes.join("\n"), text) } +} + +#[cfg(test)] mod others_tests { + use super::*; + fn sk(n: &str) -> USkill { USkill { name: n.into(), description: String::new(), path: format!("/s/{n}/SKILL.md"), model: true, user: true, ..Default::default() } } + #[test] fn mention_others_names_each_skill_once_and_keeps_the_text() { + let t = "use $pcb, then $pcb again and $nope\nplus $bom."; let o = mention_others(t, &[sk("pcb"), sk("bom")]); + assert!(o.starts_with("\nThe user invoked the $pcb skill: read \"/s/pcb/SKILL.md\" completely before anything else and follow its instructions for this request.\nThe user invoked the $bom skill")); + assert!(o.ends_with("\n\nuse $pcb, then $pcb again and $nope\nplus $bom.")); assert_eq!(o.matches("$pcb skill").count(), 1); + assert_eq!(mention_others("no skills here", &[sk("pcb")]), "no skills here"); assert_eq!(mention_others("$unknown", &[sk("pcb")]), "$unknown"); + } +} + +#[cfg(test)] +mod parsing_tests { + use super::*; + #[test] fn skills_read_their_frontmatter_including_folded_values() { + let s = parse_skill("---\nname: pcb-review\ndescription: >\n Review a board\n with care.\nuser-invocable: false\n---\nbody", "dir", "/p"); + assert_eq!((s.name.as_str(), s.description.as_str(), s.user, s.model), ("pcb-review", "Review a board with care.", false, true)); + let t = parse_skill("no frontmatter", "dflt", "/p"); assert_eq!(t.name, "dflt"); assert!(t.user); + let q = parse_skill("---\ndescription: \"Quoted: yes\"\ndisable-model-invocation: true\n---", "d", "/p"); assert_eq!(q.description, "Quoted: yes"); assert!(!q.model); + } + #[test] fn dollar_mentions_become_slash_commands_for_known_user_skills_only() { + let ss = vec![USkill { name: "pcb-review".into(), description: "".into(), path: "".into(), model: true, user: true, ..Default::default() }, USkill { name: "secret".into(), description: "".into(), path: "".into(), model: true, user: false, ..Default::default() }]; + assert_eq!(expand_claude("run $pcb-review, then $secret and $other\nnext $pcb-review", &ss), "run /pcb-review, then $secret and $other\nnext /pcb-review"); + assert_eq!(expand_claude("cost is 5", &ss), "cost is 5"); assert_eq!(mention_name("$a:b-c_d."), "a:b-c_d"); assert_eq!(mention_name("a$b"), ""); + } +} + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Kind { ClaudeUser, ClaudeProject, ClaudePlugin, Codex, Hub } +pub enum Kind { ClaudeUser, ClaudeProject, ClaudePlugin, Codex, Agents, Gemini, Cursor, Universal, Pi, Omp, Grok, Hub, HubLocal } #[derive(Clone, Debug, PartialEq)] -pub struct Found { pub name: String, pub bare: String, pub description: String, pub path: String, pub group: String, pub kind: Kind } +pub struct Found { pub name: String, pub bare: String, pub description: String, pub path: String, pub group: String, pub kind: Kind, pub provider: String, pub model_pattern: String, pub model: bool, pub user: bool, pub scope: &'static str } /// Where to look: the person's home, the hub's home, KiStack, and Codex's own home when set. #[derive(Clone, Debug, Default)] @@ -24,24 +106,31 @@ static ENV: OnceLock = OnceLock::new(); pub fn set_env(e: Env) { let _ = ENV.set(e); } pub fn env_from(home: &str, hub_home: &Path, kistack: Option<&Path>) -> Env { Env { home: home.into(), hub_home: hub_home.into(), kistack: kistack.map(Path::to_path_buf), codex_home: std::env::var("CODEX_HOME").ok().filter(|s| !s.is_empty()) } } -struct Root { dir: PathBuf, kind: Kind, group: String, plugin: String } +/// A linked worktree has a .git file. Its parent checkout is outside its scope. +pub fn directories(cwd: &Path) -> Vec { + if cwd.as_os_str().is_empty() || !cwd.is_absolute() { return vec![] } + let cwd = crate::plat::fs::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()); + let mut dirs = vec![cwd.clone()]; + if let Some(root) = cwd.ancestors().find(|p| p.join(".git").exists()) { + dirs = cwd.ancestors().take_while(|p| *p != root).map(Path::to_path_buf).collect(); + dirs.push(root.to_path_buf()); + dirs.reverse(); + } + dirs +} + +struct Root { dir: PathBuf, kind: Kind, group: String, plugin: String, scope: &'static str } fn read_json(p: &Path) -> Value { std::fs::read_to_string(p).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null) } /// Every folder skills may sit in, for a thread working in `cwd`. fn roots(env: &Env, cwd: &str) -> Vec { let home = PathBuf::from(&env.home); let mut v: Vec = vec![]; - let mut add = |dir: PathBuf, kind: Kind, group: &str, plugin: &str| if !v.iter().any(|r| r.dir == dir) { v.push(Root { dir, kind, group: group.into(), plugin: plugin.into() }) }; - // Backplane's pinned KiStack first: a person's older copy of the same skill (~/.agents/skills, ~/.claude/skills, a project) never wins `$name` - if let Some(k) = &env.kistack { add(k.join("skills"), Kind::Hub, "Backplane", "") } - add(env.hub_home.join("kistack/skills"), Kind::Hub, "Backplane", ""); - // the folder and its parents, up to (not including) the person's home - let mut d = PathBuf::from(cwd); let mut n = 0; - while !cwd.is_empty() && n < 8 && d != home && d.parent().is_some() { - add(d.join(".claude/skills"), Kind::ClaudeProject, "Claude · project", ""); add(d.join(".agents/skills"), Kind::Codex, "Codex · project", ""); - d = d.parent().unwrap().to_path_buf(); n += 1; + let mut add = |dir: PathBuf, kind: Kind, group: &str, plugin: &str, scope| if !v.iter().any(|r| r.dir == dir) { v.push(Root { dir, kind, group: group.into(), plugin: plugin.into(), scope }) }; + for dir in directories(Path::new(cwd)).into_iter().rev().filter(|d| *d != home) { + for (rel, kind, group) in locations(true) { add(dir.join(rel), kind, group, "", "Project"); } } - add(home.join(".claude/skills"), Kind::ClaudeUser, "Claude · yours", ""); + for (rel, kind, group) in locations(false) { add(home.join(rel), kind, group, "", "User"); } let enabled = read_json(&home.join(".claude/settings.json")); let installed = read_json(&home.join(".claude/plugins/installed_plugins.json")); for (key, list) in installed["plugins"].as_object().into_iter().flatten() { @@ -51,32 +140,112 @@ fn roots(env: &Env, cwd: &str) -> Vec { let mut any = false; for i in list.as_array().into_iter().flatten() { let p = PathBuf::from(i["installPath"].as_str().unwrap_or("")); if !p.is_dir() { continue } - any = true; add(p.join("skills"), Kind::ClaudePlugin, &group, plugin); + any = true; add(p.join("skills"), Kind::ClaudePlugin, &group, plugin, "User"); } if !any { // the install is gone: a directory marketplace is read where it is - if let Some(m) = enabled["extraKnownMarketplaces"][market]["source"]["path"].as_str() { add(PathBuf::from(m).join("skills"), Kind::ClaudePlugin, &group, plugin); add(PathBuf::from(m), Kind::ClaudePlugin, &group, plugin); } + if let Some(m) = enabled["extraKnownMarketplaces"][market]["source"]["path"].as_str() { add(PathBuf::from(m).join("skills"), Kind::ClaudePlugin, &group, plugin, "User"); add(PathBuf::from(m), Kind::ClaudePlugin, &group, plugin, "User"); } } } let codex = env.codex_home.as_ref().map(PathBuf::from).unwrap_or_else(|| home.join(".codex")); - add(codex.join("skills"), Kind::Codex, "Codex · yours", ""); - add(home.join(".agents/skills"), Kind::Codex, "Agents · yours", ""); - add(env.hub_home.join("skills"), Kind::Hub, "Backplane", ""); add(env.hub_home.join("bundled/skills"), Kind::Hub, "Backplane", ""); // bundled.rs dir() + add(codex.join("skills"), Kind::Codex, "Codex · yours", "", "User"); + if let Some(k) = &env.kistack { add(k.join("skills"), Kind::Hub, "Backplane", "", "Bundled"); } + add(env.hub_home.join("kistack/skills"), Kind::Hub, "Backplane", "", "Bundled"); + add(env.hub_home.join("skills"), Kind::HubLocal, "Backplane", "", "Bundled"); add(env.hub_home.join("bundled/skills"), Kind::Hub, "Backplane", "", "Bundled"); // bundled.rs dir() v } +fn locations(project: bool) -> [(&'static str, Kind, &'static str); 11] { + let (claude, group, agents, pi, omp) = if project { + (Kind::ClaudeProject, "Claude · project", "Agents · project", ".pi/skills", ".omp/skills") + } else { (Kind::ClaudeUser, "Claude · yours", "Agents · yours", ".pi/agent/skills", ".omp/agent/skills") }; + [ + (".backplane/skills", Kind::Universal, "Backplane"), + (".agents/skills", Kind::Agents, agents), + (".claude/skills", claude, group), + (".claude/commands", claude, group), + (".codex/skills", Kind::Codex, if project { "Codex · project" } else { "Codex · yours" }), + (".cursor/skills", Kind::Cursor, "Cursor"), + (".gemini/skills", Kind::Gemini, "Gemini"), + (".gemini/config/skills", Kind::Gemini, "Gemini"), + (pi, Kind::Pi, "Pi"), (omp, Kind::Omp, "Oh My Pi"), (".grok/skills", Kind::Grok, "Grok"), + ] +} + +fn skill_path(root: &Path, entry: &str) -> PathBuf { + let path = root.join(entry); + if root.ends_with(".claude/commands") && entry.ends_with(".md") { path } + else { path.join("SKILL.md") } +} + fn child_dirs(dir: &Path) -> Vec { let mut ns: Vec = std::fs::read_dir(dir).map(|r| r.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).filter(|n| !n.starts_with('.')).collect()).unwrap_or_default(); ns.sort(); ns } /// Every skill a thread in `cwd` may be given, the first of a name in a group order winning nothing: a name two places hold is listed in both (the group tells them apart). +fn read_skill(path: &Path) -> Option { + use std::io::Read; + if !path.metadata().ok()?.is_file() { return None } + let mut bytes = Vec::new(); + std::fs::File::open(path).ok()?.take(16 * 1024).read_to_end(&mut bytes).ok()?; + if bytes.is_empty() { return None } + Some(String::from_utf8_lossy(&bytes).into_owned()) +} + +fn matches_scope(spec: &str, value: &str) -> bool { + spec.is_empty() || spec.trim_matches(['[', ']']).split(',').any(|s| { + let s = s.trim().trim_matches(['"', '\'']); + s == "*" || s == value || s.strip_suffix('*').is_some_and(|prefix| value.starts_with(prefix)) + }) +} + +pub fn provider_scope(f: &Found) -> &str { + let implied = match f.kind { + Kind::Codex => "codex", Kind::Gemini => "antigravity", Kind::Cursor => "cursor", + Kind::Pi => "pi", Kind::Omp => "omp", Kind::Grok => "grok", + Kind::ClaudeUser | Kind::ClaudeProject | Kind::ClaudePlugin => "claude", + _ => "", + }; + if f.provider.is_empty() { implied } else { &f.provider } +} + +fn applicable(f: &Found, provider: &str, model: &str) -> bool { + let scope = provider_scope(f); + (matches_scope(scope, provider) || provider == "antigravity" && matches_scope(scope, "gemini")) + && matches_scope(&f.model_pattern, model) +} + +pub fn for_model(ss: &[Found], provider: &str, model: &str) -> Vec { + let mut candidates: Vec<_> = ss.iter().filter(|f| applicable(f, provider, model)).collect(); + // Stable sort keeps the closest directory ahead of its ancestors within the same scope. + candidates.sort_by_key(|f| (match f.scope { "Project" => 0, "User" => 1, _ => 2 }, + f.provider.is_empty() && matches!(f.kind, Kind::Universal | Kind::Agents | Kind::Hub | Kind::HubLocal), f.model_pattern.is_empty())); + let mut seen = std::collections::HashSet::new(); + candidates.into_iter().filter(|f| seen.insert(&f.name)).cloned().collect() +} + +pub fn prompt_index(ss: &[Found], provider: &str, isolated: bool) -> String { + let mut lines = String::new(); + for f in ss.iter().filter(|f| f.model && !native(f, provider, isolated)) { + let description: String = f.description.chars().take(300).collect(); + let entry = json!({"name":f.name, "description":description, "path":f.path}).to_string() + .replace('<', "\\u003c").replace('>', "\\u003e"); + if lines.len() + entry.len() > 16 * 1024 { break } + lines.push_str(&entry); + lines.push('\n'); + } + if lines.is_empty() { lines } else { + format!("\nRead the matching skill file completely before applying it.\n{lines}") + } +} + pub fn scan_all(env: &Env, cwd: &str) -> Vec { let mut out: Vec = vec![]; for r in roots(env, cwd) { for d in child_dirs(&r.dir) { - let p = r.dir.join(&d).join("SKILL.md"); - let Ok(t) = std::fs::read_to_string(&p) else { continue }; if t.is_empty() { continue } - let s = parse_skill(&t, &d, &p.to_string_lossy()); if !s.user { continue } + let p = skill_path(&r.dir, &d); + let Some(t) = read_skill(&p) else { continue }; + let s = parse_skill(&t, d.strip_suffix(".md").unwrap_or(&d), &p.to_string_lossy()); let name = if r.plugin.is_empty() { s.name.clone() } else { format!("{}:{}", r.plugin, s.name) }; if out.iter().any(|f| f.path == s.path) { continue } - out.push(Found { name, bare: s.name, description: s.description, path: s.path, group: r.group.clone(), kind: r.kind }); + out.push(Found { name, bare: s.name, description: s.description, path: s.path, group: r.group.clone(), kind: r.kind, provider: s.provider, model_pattern: s.model_pattern, model: s.model, user: s.user, scope: r.scope }); } } out @@ -89,7 +258,7 @@ fn fingerprint(env: &Env, cwd: &str) -> u64 { for f in ["settings.json", "plugins/installed_plugins.json"] { mt(&Path::new(&env.home).join(".claude").join(f)).hash(&mut h) } for r in roots(env, cwd) { r.dir.hash(&mut h); mt(&r.dir).hash(&mut h); - for d in child_dirs(&r.dir) { mt(&r.dir.join(&d)).hash(&mut h); mt(&r.dir.join(&d).join("SKILL.md")).hash(&mut h) } + for d in child_dirs(&r.dir) { mt(&r.dir.join(&d)).hash(&mut h); mt(&skill_path(&r.dir, &d)).hash(&mut h) } } h.finish() } @@ -110,7 +279,13 @@ pub fn native(f: &Found, provider: &str, isolated: bool) -> bool { match (provider, f.kind) { ("claude", Kind::Hub | Kind::ClaudeProject) => true, ("claude", Kind::ClaudeUser | Kind::ClaudePlugin) => !isolated, - ("codex", Kind::Codex) => true, + ("codex", Kind::Codex) => !isolated && f.scope != "Project", + ("codex" | "pi" | "omp" | "opencode", Kind::Agents) => true, + ("antigravity", Kind::Agents) => f.scope == "Project", + ("antigravity", Kind::Gemini) => f.scope == "User", + ("pi", Kind::Pi) | ("omp", Kind::Omp | Kind::ClaudeUser | Kind::ClaudeProject | Kind::ClaudePlugin | Kind::Codex) | + ("grok", Kind::Grok) | ("opencode", Kind::ClaudeUser | Kind::ClaudeProject) => true, + ("pi", Kind::Hub) => f.path.replace('\\', "/").contains("/kistack/skills/"), _ => false, } } @@ -118,7 +293,7 @@ pub fn native(f: &Found, provider: &str, isolated: bool) -> bool { pub fn lookup<'a>(ss: &'a [Found], name: &str) -> Option<&'a Found> { ss.iter().find(|f| f.name == name).or_else(|| { let m: Vec<&Found> = ss.iter().filter(|f| f.bare == name).collect(); if m.len() == 1 { Some(m[0]) } else { None } }) } -fn as_u(f: &Found) -> USkill { USkill { name: f.name.clone(), description: f.description.clone(), path: f.path.clone(), model: true, user: true } } +fn as_u(f: &Found) -> USkill { USkill { name: f.name.clone(), description: f.description.clone(), path: f.path.clone(), model: f.model, user: f.user, ..Default::default() } } fn canon(text: &str, ss: &[Found]) -> String { // a bare plugin skill word becomes its full name if !text.contains('$') { return text.to_string() } text.split('\n').map(|l| l.split(' ').map(|w| { let n = mention_name(w); match lookup(ss, &n) { Some(f) if !n.is_empty() && f.name != n => format!("${}{}", f.name, &w[1 + n.len()..]), _ => w.to_string() } }).collect::>().join(" ")).collect::>().join("\n") @@ -132,12 +307,12 @@ pub fn prepare(text: &str, ss: &[Found], provider: &str, isolated: bool) -> Stri let (nat, rd): (Vec<&Found>, Vec<&Found>) = ss.iter().partition(|f| native(f, provider, isolated)); let reads: Vec = rd.into_iter().map(as_u).collect(); let noted = if provider == "claude" { mention_others(&text, &reads) } else { mention_others(&text, &ss.iter().map(as_u).collect::>()) }; // Codex and the rest are told the file as well: it is the same instruction - if provider == "claude" { let n: Vec = nat.into_iter().map(as_u).collect(); crate::agents::inputs::expand_claude(¬ed, &n) } else { noted } + if provider == "claude" { let n: Vec = nat.into_iter().map(as_u).collect(); expand_claude(¬ed, &n) } else { noted } } /// How a mentioned skill stands for the thread's provider: "" loaded by the provider, "read from file" named to the agent, and None for a word that is no skill. pub fn status(ss: &[Found], word: &str, provider: &str, isolated: bool) -> Option<(Found, &'static str)> { - let f = lookup(ss, word)?; Some((f.clone(), if native(f, provider, isolated) { "" } else { "read from file" })) + let f = lookup(ss, word).filter(|f| f.user)?; Some((f.clone(), if native(f, provider, isolated) { "" } else { "read from file" })) } /// Chips for the `$skill` words of a sent message: `{word, kind:"skill", id:"", label, note}`. A lower-case word with a dash or colon that names nothing says so (`$HOME`, `$5` are left alone). @@ -182,7 +357,7 @@ pub fn rows(ss: &[Found], word: &str, provider: &str, isolated: bool) -> Vec = ss.iter().map(|f| (score(f, &q), native(f, provider, isolated), 0, f)).filter(|x| x.0 > 0).collect(); + let mut c: Vec<(u32, bool, usize, &Found)> = ss.iter().filter(|f| f.user).map(|f| (score(f, &q), native(f, provider, isolated), 0, f)).filter(|x| x.0 > 0).collect(); let rank = |g: &str| -> usize { let pre = match provider { "claude" => "Claude", "codex" => "Codex", _ => "" }; if g == "Backplane" { 2 } else if g.starts_with("Agents") && provider == "codex" { 1 } else if !pre.is_empty() && g.starts_with(pre) { 0 } else { 3 } }; for x in c.iter_mut() { x.2 = rank(&x.3.group) } c.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)).then(a.3.name.cmp(&b.3.name))); c.truncate(MAX); @@ -237,7 +412,7 @@ mod tests { let ss = scan_all(&env, &proj.to_string_lossy()); let get = |n: &str| ss.iter().find(|f| f.name == n).unwrap_or_else(|| panic!("{n} in {ss:?}")); assert_eq!((get("unslop").group.as_str(), get("unslop").kind), ("Claude · yours", Kind::ClaudeUser)); assert_eq!(get("local").group, "Claude · project"); assert_eq!(get("cdx").group, "Codex · yours"); assert_eq!(get("shared").group, "Agents · yours"); assert_eq!(get("pk:review").group, "Claude · plugin pk"); assert_eq!(get("pk:review").bare, "review"); - assert_eq!(get("own").group, "Backplane"); assert!(ss.iter().all(|f| f.name != "hidden")); + assert_eq!(get("own").group, "Backplane"); assert!(!get("hidden").user); assert!(lookup(&ss, "review").is_some(), "a plugin's skill by its bare name when it is the only one"); std::fs::remove_dir_all(&t).ok(); } @@ -252,7 +427,7 @@ mod tests { put(&home, ".claude/skills/new/SKILL.md", &sk("new", "changed text")); assert_eq!(index(&env, "")[0].description, "changed text"); std::fs::remove_dir_all(&t).ok(); } - fn f(n: &str, kind: Kind, group: &str) -> Found { Found { name: n.into(), bare: n.rsplit(':').next().unwrap().into(), description: format!("{n} does things"), path: format!("/s/{n}/SKILL.md"), group: group.into(), kind } } + fn f(n: &str, kind: Kind, group: &str) -> Found { Found { name: n.into(), bare: n.rsplit(':').next().unwrap().into(), description: format!("{n} does things"), path: format!("/s/{n}/SKILL.md"), group: group.into(), kind, provider: String::new(), model_pattern: String::new(), model: true, user: true, scope: "User" } } #[test] fn claude_gets_slash_for_what_it_loads_and_a_file_note_for_the_rest() { let ss = vec![f("unslop", Kind::ClaudeUser, "Claude · yours"), f("cdx", Kind::Codex, "Codex · yours"), f("pk:review", Kind::ClaudePlugin, "p")]; let o = prepare("run $unslop and $cdx then $review and $nope", &ss, "claude", false); diff --git a/native/host/src/agents/tests.rs b/native/host/src/agents/tests.rs index 24d2fab0ac..cdb8ea8ddb 100644 --- a/native/host/src/agents/tests.rs +++ b/native/host/src/agents/tests.rs @@ -1938,11 +1938,11 @@ async fn a_dollar_skill_of_the_persons_own_reaches_the_agent_as_a_slash_command_ // (\\* and not \\?: macOS's sed has no \? in a basic expression, and the stand-in then never found the file) let find = r#"p=$(printf '%s' "$X" | sed -n 's/.*read \\*"\([^"\\]*SKILL.md\)\\*".*/\1/p' | head -1); w=$(sed -n 's/^SECRET=//p' "$p" 2>/dev/null | head -1)"#; let uh = dir("sc-userhome"); // the skill sits where the other provider's agent does not load it itself, so the turn text must hand over the file - for rel in [".agents/skills/zqwhale", ".claude/skills/zqwhale"] { let d = uh.join(rel); std::fs::create_dir_all(&d).unwrap(); std::fs::write(d.join("SKILL.md"), "---\nname: zqwhale\ndescription: d\n---\nSECRET=PURPLE-OTTER-77\n").unwrap(); } + for rel in [".agents/skills/zqwhale", ".claude/skills/zqwhale"] { let d = uh.join(rel); std::fs::create_dir_all(&d).unwrap(); std::fs::write(d.join("SKILL.md"), "---\nname: zqwhale\ndescription: d\nprovider: \"*\"\n---\nSECRET=PURPLE-OTTER-77\n").unwrap(); } std::fs::remove_dir_all(uh.join(".claude/skills/zqwhale")).unwrap(); // placeholder: each provider below gets only the foreign copy for provider in ["claude", "codex"] { let (keep, drop) = if provider == "claude" { (".agents/skills/zqwhale", ".claude/skills/zqwhale") } else { (".claude/skills/zqwhale", ".agents/skills/zqwhale") }; - let _ = std::fs::remove_dir_all(uh.join(drop)); std::fs::create_dir_all(uh.join(keep)).unwrap(); std::fs::write(uh.join(keep).join("SKILL.md"), "---\nname: zqwhale\ndescription: d\n---\nSECRET=PURPLE-OTTER-77\n").unwrap(); + let _ = std::fs::remove_dir_all(uh.join(drop)); std::fs::create_dir_all(uh.join(keep)).unwrap(); std::fs::write(uh.join(keep).join("SKILL.md"), "---\nname: zqwhale\ndescription: d\nprovider: \"*\"\n---\nSECRET=PURPLE-OTTER-77\n").unwrap(); let sd = dir(&format!("sc-bin-{provider}")); if provider == "claude" { script(&sd, "claude", &format!("#!/bin/sh\nwhile IFS= read -r X; do case \"$X\" in *'\"type\":\"user\"'*) {find}; printf '%s\\n' '{{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":\"s1\",\"cwd\":\"/tmp\",\"tools\":[],\"model\":\"fake\",\"permissionMode\":\"default\"}}'; printf '%s\\n' '{{\"type\":\"assistant\",\"message\":{{\"id\":\"m1\",\"role\":\"assistant\",\"content\":[{{\"type\":\"text\",\"text\":\"The skill says '\"$w\"'\"}}],\"usage\":{{\"input_tokens\":1}}}},\"session_id\":\"s1\"}}'; printf '%s\\n' '{{\"type\":\"result\",\"subtype\":\"success\",\"is_error\":false,\"result\":\"done\",\"session_id\":\"s1\"}}';; esac; done\n")) } else { script(&sd, "codex", &format!("#!/bin/sh\ncase \"$1\" in --version) echo codex-cli 0.0.0; exit 0;; esac\nfor a in \"$@\"; do X=\"$a\"; done\n[ \"$X\" = \"-\" ] && X=$(cat)\n{find}\necho '{{\"type\":\"thread.started\",\"thread_id\":\"cs-1\"}}'\nprintf '{{\"type\":\"item.completed\",\"item\":{{\"id\":\"i\",\"type\":\"agent_message\",\"text\":\"The skill says %s\"}}}}\\n' \"$w\"\necho '{{\"type\":\"turn.completed\",\"usage\":{{\"input_tokens\":1,\"cached_input_tokens\":0,\"output_tokens\":1}}}}'\n")) } diff --git a/native/host/src/data/ext.rs b/native/host/src/data/ext.rs index fc091c167d..93d348aa00 100644 --- a/native/host/src/data/ext.rs +++ b/native/host/src/data/ext.rs @@ -21,7 +21,7 @@ //! through (never for a turn's end or an ask by themselves: native/host/src/push), and `{"k":"clear","keys","badge"}` when one is dealt with. use super::*; -pub const FEATURES: &[&str] = &["actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "layers", "onboard", "push", "commands", "work", "star", "accounts", "machines", "history", "devices", "find", "notifysettings", "ring"]; +pub const FEATURES: &[&str] = &["actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "layers", "onboard", "push", "commands", "work", "star", "accounts", "machines", "history", "devices", "find", "notifysettings", "ring", "threadContext"]; const THREAD_ACTS: &[&str] = &["pin", "unpin", "settle", "unsettle", "archive", "unarchive", "delete", "detach"]; @@ -256,6 +256,7 @@ pub async fn call(hub: &Arc, c: &mut Conn, m: &str, p: &Value, is_browser: } "mentions.list" => mentions(hub, p).await, "viewer.files" | "viewer.watch" | "viewer.probe" | "viewer.info" | "viewer.layers" | "viewer.refs" | "viewer.compare" | "viewer.rail" | "viewer.follow" | "viewer.layout" | "viewer.layout.act" | "files.entries" | "mech.list" | "browser" => viewers(hub, c, m, p, is_browser).await?, + "thread.context" | "thread.context.mcp" => rpc(hub, c, m, p.clone()).await.map(result), "thread.again" => { let th = s(p, "thread"); if th.is_empty() { return Some(Err(err("thread"))) } rpc(hub, c, "thread.again", json!({"thread":th})).await.map(|_| json!({})) } "voice.start" | "voice.stop" | "voice.act" | "voice.view" | "voice.key" | "voice.page" | "voice.page.act" | "voice.always" => voice(hub, c, m, p).await, "machines.page" | "machines.page.act" | "devices.page" | "devices.page.act" | "notify.page" | "notify.page.act" | "ring.list" | "ring.get" | "ring.search" | "ring.hear" | "ring.send" | "ring.setup" | "ring.page" | "ring.page.act" | "mcp.page" | "mcp.page.act" | "browser.page" | "browser.page.act" => { diff --git a/native/host/src/data/mod.rs b/native/host/src/data/mod.rs index 9ac7fe922e..5dab7bb34f 100644 --- a/native/host/src/data/mod.rs +++ b/native/host/src/data/mod.rs @@ -24,7 +24,7 @@ use tokio_tungstenite::tungstenite::{protocol::WebSocketConfig, Message}; pub const PROTO: &str = "data/1"; /// What this hub does beyond the base of data/1; a hub from before an addition does not list it (the app can warn instead of sending what would be dropped). -pub const FEATURES: &[&str] = &["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks"]; +pub const FEATURES: &[&str] = &["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks", "threadContext"]; const PREVIEW: usize = 140; const ASK_SCAN: usize = 4000; diff --git a/native/host/src/data/tests.rs b/native/host/src/data/tests.rs index cb9135f5a6..b5e45fab68 100644 --- a/native/host/src/data/tests.rs +++ b/native/host/src/data/tests.rs @@ -65,10 +65,10 @@ async fn ask(ws: &mut Ws, id: u64, m: &str, p: Value) -> Value { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn data_hello_capabilities_and_both_encodings() { - assert_eq!(crate::hub::capabilities()["data"]["proto"], "data/1"); assert_eq!(crate::hub::capabilities()["data"]["features"], json!(["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks"])); + assert_eq!(crate::hub::capabilities()["data"]["proto"], "data/1"); assert_eq!(crate::hub::capabilities()["data"]["features"], json!(["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks", "threadContext"])); let (_h, port) = up("hello").await; let mut ws = open(port, "&enc=json").await; let v = next(&mut ws).await; - assert_eq!((v["t"].as_str(), v["proto"].as_str()), (Some("hello"), Some("data/1"))); assert_eq!(v["hub"], format!("127.0.0.1:{port}"), "the hub as asked (the Host header)"); assert!(v["name"].is_string(), "the machine's name: {v}"); assert_eq!(v["features"], json!(["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks"]), "a hub from before images does not list it"); assert!(v["now"].as_u64().unwrap() > 1_600_000_000_000); + assert_eq!((v["t"].as_str(), v["proto"].as_str()), (Some("hello"), Some("data/1"))); assert_eq!(v["hub"], format!("127.0.0.1:{port}"), "the hub as asked (the Host header)"); assert!(v["name"].is_string(), "the machine's name: {v}"); assert_eq!(v["features"], json!(["images", "actions", "search", "models", "mentions", "bots", "notify", "viewers", "files", "browser", "diff", "review", "fold", "picker", "voice", "order", "layers", "onboard", "push", "settled", "commands", "work", "star", "accounts", "machines", "history", "terms", "links", "devices", "queue", "buy", "status", "subview", "find", "notifysettings", "ring", "hubOffer", "swarm", "sections", "telemetryNotice", "mcpsettings", "fabprofile", "plan", "mgmt", "replyImages", "cats", "projectcard", "termChat", "copy", "reviewmode", "rail", "gerbers", "follow", "unanswered", "browserstart", "restarting", "fileLinks", "layout", "clone", "reply", "deflate", "open", "shell", "home", "fork", "blobs", "keptChunks", "threadContext"]), "a hub from before images does not list it"); assert!(v["now"].as_u64().unwrap() > 1_600_000_000_000); // the default is binary CBOR with plain string keys let mut c = open(port, "").await; let m = tokio::time::timeout(Duration::from_secs(5), c.next()).await.unwrap().unwrap().unwrap(); let Message::Binary(b) = m else { panic!("binary") }; assert!(b.windows(5).any(|w| w == b"proto"), "plain keys, not the hub's dictionary"); diff --git a/native/host/src/data/webpolicy.rs b/native/host/src/data/webpolicy.rs index a415fbf7d0..a871c1fe0b 100644 --- a/native/host/src/data/webpolicy.rs +++ b/native/host/src/data/webpolicy.rs @@ -46,6 +46,7 @@ fn classify(method: &str, params: &Value) -> Option { | "term.write" | "thread.act" | "thread.again" + | "thread.context.mcp" | "thread.create" | "thread.model" | "thread.review" @@ -117,6 +118,7 @@ fn classify(method: &str, params: &Value) -> Option { | "thread.work" | "threads.list" | "unsubscribe" + | "thread.context" | "viewer.diff" | "viewer.files" | "viewer.info" diff --git a/native/host/src/mcpx/gen.rs b/native/host/src/mcpx/gen.rs index ee5a76af29..77dbcf80b3 100644 --- a/native/host/src/mcpx/gen.rs +++ b/native/host/src/mcpx/gen.rs @@ -17,6 +17,10 @@ pub struct Ctx { pub exe: String, pub url: String, pub pcbparts: bool } pub type Vault<'a> = &'a dyn Fn(&str) -> Option; /// A header's value with its secret put in; None when the vault does not hold it. +fn private_header(server: &Server, kv: &Kv) -> bool { + server.id.starts_with("project-") || kv.secret +} + pub fn value(kv: &Kv, vault: Vault) -> Option { if kv.secret { vault(&kv.v).map(|x| format!("{}{x}", kv.pre)) } else { Some(kv.v.clone()) } } /// The wrapper an agent starts for a stdio server: (command, args, env). @@ -35,9 +39,9 @@ pub fn claude(servers: &[&Server], c: &Ctx, vault: Vault) -> Value { for s in servers { let v = if s.remote() { let mut o = json!({"type": s.transport, "url": s.url}); - let plain: Vec<(String, String)> = s.headers.iter().filter(|k| !k.secret).map(|k| (k.k.clone(), k.v.clone())).collect(); + let plain: Vec<(String, String)> = s.headers.iter().filter(|k| !private_header(s, k)).map(|k| (k.k.clone(), k.v.clone())).collect(); if !plain.is_empty() { o["headers"] = obj(&plain) } - if s.headers.iter().any(|k| k.secret) { o["headersHelper"] = json!(format!("{} --mcp-headers {} {}", sh_quote(&c.exe), sh_quote(&s.id), sh_quote(&c.url))) } + if s.headers.iter().any(|k| private_header(s, k)) { o["headersHelper"] = json!(format!("{} --mcp-headers {} {}", sh_quote(&c.exe), sh_quote(&s.id), sh_quote(&c.url))) } let _ = vault; o } else { let (cmd, args, env) = wrapper(s, c); json!({"type":"stdio","command":cmd,"args":args,"env":obj(&env)}) }; m.insert(s.id.clone(), v); @@ -64,10 +68,10 @@ pub fn codex(servers: &[&Server], c: &Ctx, vault: Vault) -> (Vec, Vec<(S let p = format!("mcp_servers.{}", s.id); if s.remote() { set(format!("{p}.url"), toml_str(&s.url)); - let plain: Vec<(String, String)> = s.headers.iter().filter(|k| !k.secret).map(|k| (k.k.clone(), k.v.clone())).collect(); + let plain: Vec<(String, String)> = s.headers.iter().filter(|k| !private_header(s, k)).map(|k| (k.k.clone(), k.v.clone())).collect(); if !plain.is_empty() { set(format!("{p}.http_headers"), toml_tbl(&plain)) } let mut envh = vec![]; - for (i, h) in s.headers.iter().filter(|k| k.secret).enumerate() { if let Some(v) = value(h, vault) { let var = codex_var(&s.id, i); envh.push((h.k.clone(), var.clone())); env.push((var, v)) } } + for (i, h) in s.headers.iter().filter(|k| private_header(s, k)).enumerate() { if let Some(v) = value(h, vault) { let var = codex_var(&s.id, i); envh.push((h.k.clone(), var.clone())); env.push((var, v)) } } if !envh.is_empty() { set(format!("{p}.env_http_headers"), toml_tbl(&envh)) } if !s.disabled_tools.is_empty() { set(format!("{p}.disabled_tools"), toml_arr(&s.disabled_tools)) } } else { @@ -104,6 +108,13 @@ pub fn acp(servers: &[&Server], c: &Ctx, vault: Vault) -> Value { Value::Array(out) } +/// Provider extensions get ACP's normalized servers over the agent's private environment. +pub fn extension_env(acp: &Value, key: &str) -> Option<(String, String)> { + let entries: Vec<_> = acp.as_array().into_iter().flatten() + .filter(|s| s["name"].as_str().is_some_and(|n| n.starts_with("project-"))).collect(); + (!entries.is_empty()).then(|| (key.into(), json!(entries).to_string())) +} + /// What the list means for one thread, as a short hash: a long-lived agent (Claude) whose servers changed is started again at its next turn. pub fn fingerprint(servers: &[&Server], pcbparts: bool) -> String { use sha2::{Digest, Sha256}; @@ -143,6 +154,27 @@ mod tests { let (_, env) = codex(&[&rem()], &c(), &|_| None); assert!(env.is_empty(), "a secret the vault lacks is left out"); assert_eq!(codex_approve(&["gh".into()], ""), ["-c", "mcp_servers.gh.default_tools_approval_mode=\"approve\""]); assert!(codex_approve(&["gh".into()], "approval-required").is_empty()); } + #[test] fn project_configs_keep_credentials_out_of_provider_arguments() { + let mut local = st(); + local.id = "project-test_stdio".into(); + let mut remote = rem(); + remote.id = "project-test_http".into(); + remote.headers.push(Kv::lit("X-Example-Key", "example-sensitive-value")); + let servers = [&local, &remote]; + let claude_config = claude(&servers, &c(), &vault); + assert!(claude_config["mcpServers"][&remote.id].get("headers").is_none()); + assert!(!claude_config.to_string().contains("example-sensitive-value")); + let (argv, env) = codex(&servers, &c(), &vault); + assert!(!argv.join(" ").contains("example-sensitive-value")); + assert!(env.iter().any(|(_, v)| v == "example-sensitive-value")); + let acp = acp(&servers, &c(), &vault); + assert_eq!(acp[2]["args"], json!(["--mcp-run", local.id])); + let (_, config) = extension_env(&acp, "BACKPLANE_TEST_SERVERS").unwrap(); + let extension: Value = serde_json::from_str(&config).unwrap(); + assert_eq!(extension.as_array().unwrap().len(), 2); + assert_eq!(extension[0]["env"][0]["name"], "BACKPLANE_MCP_URL"); + assert_eq!(extension[1]["headers"][2]["value"], "example-sensitive-value"); + } #[test] fn acp_gets_name_value_lists() { let (a, b) = (st(), rem()); let v = acp(&[&a, &b], &c(), &vault); assert_eq!(v[0]["name"], "backplane"); assert_eq!(v[1], json!({"type":"http","name":"pcbparts","url":PCBPARTS,"headers":[]}), "the built-in parts search, as Claude and Codex get it"); diff --git a/native/host/src/mcpx/import.rs b/native/host/src/mcpx/import.rs index 742a1aa0e2..e9901e9e24 100644 --- a/native/host/src/mcpx/import.rs +++ b/native/host/src/mcpx/import.rs @@ -11,6 +11,14 @@ pub struct Source { pub tool: &'static str, pub path: PathBuf } #[derive(Debug, Default)] pub struct Scan { pub tool: &'static str, pub path: String, pub found: Found, pub error: String } +pub const PROJECT_FILES: &[(&str, &str)] = &[ + ("Claude Code", ".mcp.json"), + ("Cursor", ".cursor/mcp.json"), + ("VS Code", ".vscode/mcp.json"), + ("Gemini CLI", ".gemini/settings.json"), + ("Antigravity", ".agents/mcp_config.json"), +]; + /// Every place a tool keeps its servers, for this home and these project roots (the files that exist). pub fn sources(home: &Path, roots: &[String]) -> Vec { let mut v: Vec<(&'static str, PathBuf)> = vec![("Claude Code", home.join(".claude.json"))]; @@ -26,7 +34,7 @@ pub fn sources(home: &Path, roots: &[String]) -> Vec { v.push(("OpenCode", home.join(".config/opencode/opencode.json"))); for r in roots.iter().filter(|r| !r.is_empty()) { let r = Path::new(r); - v.push(("Claude Code", r.join(".mcp.json"))); v.push(("Cursor", r.join(".cursor/mcp.json"))); v.push(("VS Code", r.join(".vscode/mcp.json"))); v.push(("Gemini CLI", r.join(".gemini/settings.json"))); + v.extend(PROJECT_FILES.iter().map(|(tool, file)| (*tool, r.join(file)))); } let mut seen = vec![]; v.into_iter().filter(|(_, p)| p.is_file()).filter(|(_, p)| { let k = p.clone(); if seen.contains(&k) { false } else { seen.push(k); true } }).map(|(tool, path)| Source { tool, path }).collect() diff --git a/native/host/src/mcpx/mod.rs b/native/host/src/mcpx/mod.rs index 9b597d9a1f..f375cfe26c 100644 --- a/native/host/src/mcpx/mod.rs +++ b/native/host/src/mcpx/mod.rs @@ -9,6 +9,7 @@ pub mod import; pub mod model; pub mod page; pub mod parse; +pub mod project; pub mod run; pub mod svc; pub mod toml; diff --git a/native/host/src/mcpx/project.rs b/native/host/src/mcpx/project.rs new file mode 100644 index 0000000000..e0fe21a95b --- /dev/null +++ b/native/host/src/mcpx/project.rs @@ -0,0 +1,273 @@ +//! Discover project MCP from the active checkout. The bytes hashed are the bytes parsed. +use super::{model::{Kv, Server}, parse}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{fs, io::Read, path::{Path, PathBuf}}; + +const LIMIT: u64 = 256 * 1024; + +pub struct Config { + pub path: PathBuf, + pub hash: String, + pub key: String, + pub servers: Vec, + pub error: String, +} + +fn digest(bytes: &[u8]) -> String { format!("{:x}", Sha256::digest(bytes)) } + +fn base(cwd: &str) -> Vec { crate::agents::skills::directories(Path::new(cwd)) } + +/// These runtimes have native project loaders with no verified per-launch suppression. +pub fn ambient_conflict(cwd: &str, provider: &str, agy_print: bool) -> Option { + let files: &[&str] = match provider { + "grok" => &[".mcp.json", ".cursor/mcp.json", ".grok/config.toml"], + "muse" => &[".mcp.json"], + "antigravity" if agy_print => &[".agents/mcp_config.json"], + "antigravity" => &[".agents/mcp_config.json", ".gemini/settings.json"], + _ => return None, + }; + base(cwd).iter().flat_map(|dir| files.iter().map(move |f| dir.join(f))).find(|p| fs::symlink_metadata(p).is_ok()) +} + +pub fn scan(cwd: &str) -> Vec { + let dirs = base(cwd); + let Some(root) = dirs.first() else { return vec![] }; + let canonical = crate::files::kicad::canonical::main_of(&root.to_string_lossy()); + let mut configs = Vec::new(); + for dir in &dirs { + for (_, name) in super::import::PROJECT_FILES { + let path = dir.join(name); + let Ok(real) = crate::plat::fs::canonicalize(&path) else { continue }; + if !real.starts_with(root) || !real.is_file() { continue } + let mut bytes = Vec::new(); + let read = fs::File::open(&real).and_then(|f| f.take(LIMIT + 1).read_to_end(&mut bytes)); + let hash = digest(&bytes); + let key = digest(format!("{canonical}\0{}\0{hash}", path.display()).as_bytes()); + let mut c = Config { path, hash, key, servers: vec![], error: String::new() }; + let parsed = if read.is_err() || bytes.len() as u64 > LIMIT { + Err("Configuration is unreadable or exceeds 256 KiB".into()) + } else { + parse_config(&bytes, dir, root, name, &c.hash) + }; + match parsed { + Ok(servers) if !servers.is_empty() => c.servers = servers, + Ok(_) => continue, + Err(error) => c.error = error, + } + configs.push(c); + } + } + configs +} + +fn parse_config(bytes: &[u8], dir: &Path, root: &Path, file: &str, hash: &str) -> Result, String> { + let text = std::str::from_utf8(bytes).map_err(|_| "Configuration must be UTF-8")?; + let value: Value = serde_json::from_str(&parse::strip_jsonc(text)).map_err(|e| e.to_string())?; + if file == ".gemini/settings.json" && value.get("mcpServers").is_none() { return Ok(vec![]) } + let found = parse::json_doc(&value, &[])?; + if !found.notes.is_empty() { return Err(found.notes.join("\n")) } + let map = value.get("mcpServers").or_else(|| value.get("servers")).and_then(Value::as_object); + let mut servers = found.servers; + for server in &mut servers { + let raw = map.and_then(|m| m.get(&server.name)).ok_or("Expected a named MCP server map")?; + server.env = bindings(raw.get("env").or_else(|| raw.get("environment")))?; + server.headers = bindings(raw.get("headers").or_else(|| raw.get("http_headers")))?; + // Keep executable, arguments and destination fixed to the reviewed configuration. + // The workspace substitution has no access to ambient credentials. + let workspace = root.to_str().ok_or("Workspace path must be UTF-8")?; + for value in std::iter::once(&mut server.command).chain(server.args.iter_mut()).chain([&mut server.url, &mut server.cwd]) { + *value = value.replace("${workspaceFolder}", workspace); + if value.contains("${") || value.contains('\0') { + return Err("Variable references belong in environment values or headers, except ${workspaceFolder}".into()) + } + } + if !server.remote() { + let directory = if server.cwd.is_empty() { dir.to_path_buf() } else { dir.join(&server.cwd) }; + server.cwd = directory.to_string_lossy().into_owned(); + } + let identity = digest(format!("{}\0{}\0{file}\0{hash}\0{}", root.display(), dir.display(), server.id).as_bytes()); + server.id = format!("project-{}", &identity[..24]); + if let Some(problem) = server.problem() { return Err(problem) } + } + Ok(servers) +} + +fn bindings(value: Option<&Value>) -> Result, String> { + let Some(value) = value else { return Ok(vec![]) }; + let map = value.as_object().ok_or("Environment and headers must be objects")?; + map.iter().map(|(name, value)| { + let text = value.as_str().ok_or("Environment and header values must be strings")?; + if let Some((prefix, name_ref)) = text.split_once("${secret:") { + let secret = name_ref.strip_suffix('}').ok_or("A vault reference must end the value")?; + if prefix.contains("${") || !crate::settings::vault::valid_name(secret) { return Err("Invalid vault reference".into()) } + return Ok(Kv::sec(name, secret, prefix)) + } + // Keep interpolation unresolved until after trust has been checked. + Ok(Kv::lit(name, text)) + }).collect() +} + +pub fn environment_values(text: &str, env: &dyn Fn(&str) -> Option) -> Option { + let mut text = text; + let mut out = String::new(); + while let Some((prefix, rest)) = text.split_once("${") { + let (name, tail) = rest.split_once('}')?; + let name = name.strip_prefix("env:").unwrap_or(name); + if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { return None } + out.push_str(prefix); + out.push_str(&env(name)?); + text = tail; + } + out.push_str(text); + Some(out) +} + +fn trust_file(home: &Path, key: &str) -> PathBuf { home.join("mcp/project-trust").join(key) } + +impl Config { + fn state(&self, home: &Path) -> &'static str { + if !self.error.is_empty() { return "Invalid" } + match fs::read_to_string(trust_file(home, &self.key)).as_deref() { + Ok("enabled") => "Enabled", + Ok("disabled") => "Disabled", + _ => "Untrusted", + } + } + + pub fn view(&self, home: &Path, provider: &str, provider_blocked: bool) -> Value { + json!({"path": self.path, "sha256": self.hash, "state": self.state(home), "error": self.error, + "servers": self.servers.iter().map(|s| json!({"name":s.name, "command":s.command, + "args":s.args, "cwd":s.cwd, "url":s.url, "enabled":s.enabled, + "status": self.server_status(s, home, provider, provider_blocked)})).collect::>()}) + } + + fn server_status(&self, s: &Server, home: &Path, provider: &str, provider_blocked: bool) -> &'static str { + let state = self.state(home); + if !s.enabled { return "Disabled" } + if state != "Enabled" { return state } + if provider_blocked || matches!(provider, "pi" | "omp" | "muse") && s.transport == "sse" { return "Unavailable" } + if !s.missing(&|n| crate::settings::vault::person_get(n).is_some()).is_empty() { return "Missing vault secret" } + if s.env.iter().chain(&s.headers).filter(|kv| !kv.secret).any(|kv| environment_values(&kv.v, &|n| std::env::var(n).ok()).is_none()) { return "Missing environment value" } + state + } +} + +pub fn act(home: &Path, cwd: &str, path: &str, hash: &str, action: &str) -> Result<(), String> { + let c = scan(cwd).into_iter().find(|c| c.path == Path::new(path) && c.hash == hash) + .ok_or("Configuration changed. Review it again before trusting it.")?; + let state = c.state(home); + let value = match (action, state) { + ("trust", "Untrusted") | ("enable", "Disabled") => "enabled", + ("disable", "Enabled") => "disabled", + _ => return Err("That action does not apply to this configuration".into()), + }; + let file = trust_file(home, &c.key); + // A trust marker stays on the hub, outside the repo and out of synced settings. + let write = || -> std::io::Result<()> { + fs::create_dir_all(file.parent().unwrap())?; + let tmp = file.with_extension(crate::agents::proc::unique().to_string()); + fs::write(&tmp, value)?; + let result = fs::rename(&tmp, &file); + if result.is_err() { let _ = fs::remove_file(tmp); } + result + }; + write().map_err(|e| e.to_string()) +} + +pub fn selected(home: &Path, cwd: &str) -> Vec { + scan(cwd).into_iter().filter(|c| c.state(home) == "Enabled") + .flat_map(|c| c.servers.into_iter().filter_map(move |mut s| { + if !s.enabled { return None } + for kv in s.env.iter_mut().chain(s.headers.iter_mut()).filter(|kv| !kv.secret) { + let raw = &kv.v; + // Resolve project values without shell expansion or recursive evaluation. + let value = environment_values(raw, &|name| std::env::var(name).ok())?; + if value != *raw { + kv.v = value; + } + } + Some(s) + })).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trust_is_content_addressed_and_scoped_to_the_repository() { + let temp = crate::plat::tmp::dir("project-mcp-trust"); + let home = temp.join("hub"); + let repo = temp.join("repo"); + let sub = repo.join("sub"); + fs::create_dir_all(&sub).unwrap(); + fs::create_dir(repo.join(".git")).unwrap(); + let path = repo.join(".mcp.json"); + let config = r#"{"mcpServers":{"index":{"command":"indexer","args":["--quiet"],"env":{"TOKEN":"${secret:inventory-token}"}}}}"#; + fs::write(&path, config).unwrap(); + let cwd = sub.to_str().unwrap(); + let name = path.to_str().unwrap(); + let first = scan(cwd).remove(0); + assert!(selected(&home, cwd).is_empty()); + assert_eq!(first.view(&home, "claude", false)["state"], "Untrusted"); + assert_eq!(first.view(&home, "claude", false)["servers"][0]["command"], "indexer"); + assert!(!first.view(&home, "claude", false).to_string().contains("inventory-token")); + assert!(act(&home, cwd, name, &first.hash, "enable").is_err()); + act(&home, cwd, name, &first.hash, "trust").unwrap(); + let chosen = selected(&home, cwd).remove(0); + assert_eq!(chosen.env, vec![Kv::sec("TOKEN", "inventory-token", "")]); + assert_eq!(chosen.cwd, repo.to_string_lossy()); + act(&home, cwd, name, &first.hash, "disable").unwrap(); + assert!(selected(&home, cwd).is_empty()); + act(&home, cwd, name, &first.hash, "enable").unwrap(); + fs::write(&path, config.replace("--quiet", "--strict")).unwrap(); + assert!(selected(&home, cwd).is_empty()); + assert!(act(&home, cwd, name, &first.hash, "trust").is_err()); + let changed = scan(cwd).remove(0); + act(&home, cwd, name, &changed.hash, "trust").unwrap(); + assert_ne!(selected(&home, cwd)[0].id, chosen.id); + let nested = sub.join(".mcp.json"); + fs::write(&nested, config.replace("--quiet", "--strict")).unwrap(); + assert_eq!(selected(&home, cwd).len(), 1, "an identical file in another directory has a different effective cwd"); + assert_eq!(scan(cwd).iter().find(|c| c.path == nested).unwrap().view(&home, "claude", false)["state"], "Untrusted"); + let another = temp.join("another"); + fs::create_dir(&another).unwrap(); + fs::write(another.join(".mcp.json"), config).unwrap(); + assert!(selected(&home, another.to_str().unwrap()).is_empty()); + } + + #[test] + fn native_launch_conflicts_are_visible_even_before_a_file_can_be_reviewed() { + let d = crate::plat::tmp::dir("project-mcp-provider"); + let cwd = d.to_string_lossy(); + fs::write(d.join(".mcp.json"), "not valid JSON").unwrap(); + assert!(ambient_conflict(&cwd, "claude", false).is_none()); + assert!(ambient_conflict(&cwd, "omp", false).is_none()); + assert_eq!(ambient_conflict(&cwd, "grok", false), Some(d.join(".mcp.json"))); + assert!(ambient_conflict(&cwd, "muse", false).is_some()); + fs::create_dir(d.join(".agents")).unwrap(); + fs::write(d.join(".agents/mcp_config.json"), "{}").unwrap(); + assert!(ambient_conflict(&cwd, "antigravity", true).is_some()); + assert!(ambient_conflict(&cwd, "antigravity", false).is_some()); + } + + #[test] + fn formats_keep_exact_argv_and_do_not_evaluate_shell_syntax() { + let dir = crate::plat::tmp::dir("project-mcp-formats"); + for (file, key) in [(".mcp.json", "mcpServers"), (".cursor/mcp.json", "mcpServers"), + (".vscode/mcp.json", "servers"), (".gemini/settings.json", "mcpServers")] { + let body = json!({(key): {"x": {"command":"example", "args":["with space", "$(literal)"], + "env":{"A":"${A} ${env:B}", "B":"Bearer ${secret:example-secret}"}}}}); + let servers = parse_config(body.to_string().as_bytes(), &dir, &dir, file, "sample").unwrap(); + let s = &servers[0]; + assert_eq!(s.args, ["with space", "$(literal)"]); + assert_eq!(s.env, [Kv::lit("A", "${A} ${env:B}"), Kv::sec("B", "example-secret", "Bearer ")]); + } + let resolve = |s: &str| match s { "A" => Some("${env:B}".into()), "B" => Some("value".into()), _ => None }; + assert_eq!(environment_values("${A} ${env:B}", &resolve).as_deref(), Some("${env:B} value")); + for bad in ["${MISSING}", "${A", "${env:A:-default}", "${secret:A}"] { + assert!(environment_values(bad, &resolve).is_none(), "{bad}"); + } + } +} diff --git a/native/host/src/mcpx/run.rs b/native/host/src/mcpx/run.rs index bcc3f5ca6d..becfb68f0b 100644 --- a/native/host/src/mcpx/run.rs +++ b/native/host/src/mcpx/run.rs @@ -41,9 +41,17 @@ pub fn main(args: &[String]) -> i32 { let s = |k: &str| spec[k].as_str().unwrap_or("").to_string(); let off: Vec = spec["disabled_tools"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default(); let mut c = crate::proc::std_cmd(crate::proc::Kind::Shell, s("command")); + if id.starts_with("project-") { + c.env_clear(); + for name in ["HOME", "USERPROFILE", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", "APPDATA", "LOCALAPPDATA"] { + if let Some(value) = std::env::var_os(name) { c.env(name, value); } + } + } c.args(spec["args"].as_array().into_iter().flatten().filter_map(Value::as_str)); for kv in spec["env"].as_array().into_iter().flatten() { if let (Some(k), Some(v)) = (kv[0].as_str(), kv[1].as_str()) { c.env(k, v); } } - c.env_remove("BACKPLANE_MCP_URL"); c.env_remove(super::gen::CODEX_URL_VAR); + for name in ["BACKPLANE_MCP_URL", super::gen::CODEX_URL_VAR, "BACKPLANE_PI_MCP", "BACKPLANE_OMP_MCP"] { + c.env_remove(name); + } let cwd = s("cwd"); if !cwd.is_empty() { c.current_dir(&cwd); } c.stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()); let mut child = match c.spawn() { Ok(ch) => ch, Err(e) => { diff --git a/native/host/src/mcpx/svc.rs b/native/host/src/mcpx/svc.rs index 2e8aef0f6b..4e37bff2ef 100644 --- a/native/host/src/mcpx/svc.rs +++ b/native/host/src/mcpx/svc.rs @@ -97,18 +97,34 @@ impl Mcpx { } /// The servers an agent of this thread gets now (launch). pub fn for_thread(&self, provider: &str, project: &str, bot: &str) -> Vec { self.list.lock().unwrap().for_thread(provider, project, bot).into_iter().cloned().collect() } + async fn launch_servers(&self, thread: &str, provider: &str, cwd: &str) -> Vec { + let (_, project, bot) = self.thread_ctx(thread).await; + let mut servers = self.for_thread(provider, &project, &bot); + let own: std::collections::HashSet<_> = servers.iter().map(|s| s.id.clone()).collect(); + let (home, cwd) = (self.hub.cfg.home.clone(), cwd.to_string()); + let project = tokio::task::spawn_blocking(move || super::project::selected(&home, &cwd)).await.unwrap_or_default(); + servers.extend(project.into_iter().filter(|s| !own.contains(&s.id) && s.missing(&|n| vault::person_get(n).is_some()).is_empty())); + servers + } + + async fn active_server(&self, thread: &str, id: &str) -> Option { + let (provider, project, bot) = self.thread_ctx(thread).await; + if !id.starts_with("project-") { + return self.for_thread(&provider, &project, &bot).into_iter().find(|s| s.id == id) + } + let cwd = self.agents()?.world().await.cwd(thread); + self.launch_servers(thread, &provider, &cwd).await.into_iter().find(|s| s.id == id) + } /// The wrapper's ask (`backplane/mcp_spec`): only for a server this thread gets. pub async fn spec(&self, thread: &str, id: &str) -> Result { - let (p, pr, b) = self.thread_ctx(thread).await; - let s = self.for_thread(&p, &pr, &b).into_iter().find(|s| s.id == id).ok_or_else(|| format!("{id} is not one of this thread's MCP servers (Settings > MCP)"))?; + let s = self.active_server(thread, id).await.ok_or_else(|| format!("{id} is not one of this thread's MCP servers (Settings > MCP)"))?; if s.remote() { return Err(format!("{id} is a remote server")) } let r = self.resolve(&s).map_err(|e| { self.failed(id, &e, ""); e })?; Ok(json!({"command": r.command, "args": r.args, "env": r.env.iter().map(|(k, v)| json!([k, v])).collect::>(), "cwd": r.cwd, "disabled_tools": s.disabled_tools})) } /// Claude's headersHelper (`backplane/mcp_headers`). pub async fn headers(&self, thread: &str, id: &str) -> Result { - let (p, pr, b) = self.thread_ctx(thread).await; - let s = self.for_thread(&p, &pr, &b).into_iter().find(|s| s.id == id).ok_or_else(|| format!("{id} is not one of this thread's MCP servers"))?; + let s = self.active_server(thread, id).await.ok_or_else(|| format!("{id} is not one of this thread's MCP servers"))?; let r = self.resolve(&s)?; Ok(Value::Object(r.headers.into_iter().map(|(k, v)| (k, json!(v))).collect())) } pub fn used(&self, id: &str, tool: &str, ok: bool, err: &str) { @@ -192,8 +208,8 @@ pub struct Launch { /** the list's server ids (Codex approves their tools in ful /// The hub's own program, for the wrapper (a replaced binary's " (deleted)" is dropped: the new one is at the same path). pub fn hub_exe() -> String { std::env::current_exe().map(|p| p.to_string_lossy().trim_end_matches(" (deleted)").to_string()).unwrap_or_default() } /// The servers of `thread` (a `provider` agent) as its launch needs them. No hub MCP list (tests, a hub without it): Backplane's own and pcbparts only. -pub async fn launch(thread: &str, provider: &str, url: &str) -> Launch { - let (servers, pcb) = match get() { Some(m) => { let (_, pr, b) = m.thread_ctx(thread).await; (m.for_thread(provider, &pr, &b), m.pcbparts().await) } None => (vec![], true) }; +pub async fn launch(thread: &str, provider: &str, url: &str, cwd: &str) -> Launch { + let (servers, pcb) = match get() { Some(m) => { (m.launch_servers(thread, provider, cwd).await, m.pcbparts().await) } None => (vec![], true) }; let refs: Vec<&Server> = servers.iter().collect(); let c = gen::Ctx { exe: hub_exe(), url: url.to_string(), pcbparts: pcb }; let vault_get = |n: &str| vault::person_get(n); @@ -201,6 +217,6 @@ pub async fn launch(thread: &str, provider: &str, url: &str) -> Launch { Launch { ids: refs.iter().map(|s| s.id.clone()).collect(), claude: gen::claude(&refs, &c, &vault_get).to_string(), disallowed: gen::claude_disallowed(&refs), acp: gen::acp(&refs, &c, &vault_get), codex_args, codex_env, fingerprint: gen::fingerprint(&refs, pcb), pcbparts: pcb } } /// The launch's fingerprint alone (what decides whether a live Claude is started again). -pub async fn fingerprint(thread: &str, provider: &str) -> String { - match get() { Some(m) => { let (_, pr, b) = m.thread_ctx(thread).await; let s = m.for_thread(provider, &pr, &b); gen::fingerprint(&s.iter().collect::>(), m.pcbparts().await) } None => gen::fingerprint(&[], true) } +pub async fn fingerprint(thread: &str, provider: &str, cwd: &str) -> String { + match get() { Some(m) => { let s = m.launch_servers(thread, provider, cwd).await; gen::fingerprint(&s.iter().collect::>(), m.pcbparts().await) } None => gen::fingerprint(&[], true) } } diff --git a/native/host/src/net/far.rs b/native/host/src/net/far.rs index fc7fa2a2ea..127691afa7 100644 --- a/native/host/src/net/far.rs +++ b/native/host/src/net/far.rs @@ -54,7 +54,7 @@ use K::*; /// Every variant `change` renames; the test below checks each field against codec's wire names. /// Requests to a thing elsewhere: only these may go to a linked machine (thread.delete is not one: law far_no_delete). pub const METHODS: &[&str] = &["turn.start", "turn.interrupt", "ask.answer", "queue.move", "queue.remove", "queue.resume", "queue.steer", "queue.edit", - "thread.settle", "thread.unsettle", "thread.back", "thread.rename", "thread.btw", "thread.modes", "thread.provider", "thread.effort", "thread.speed", "bots.space", "bots.routine_run", + "thread.settle", "thread.unsettle", "thread.back", "thread.rename", "thread.btw", "thread.modes", "thread.provider", "thread.effort", "thread.speed", "thread.context", "thread.context.mcp", "bots.space", "bots.routine_run", "thread.create", "thread.fork", "thread.archive", "thread.unarchive", "thread.pin", "thread.unpin", "project.add", "project.new", "project.remove", "fs.list", "fs.mkdir", "fs.find", "thread.detach", "todos.edit", "kicad.open", "viewer.state", "boards.list", // the viewers of a thread whose project is there: its Diff and its Files (listing, and a file's bytes to show here) diff --git a/native/host/src/present/thread.rs b/native/host/src/present/thread.rs index fafd6d1410..e29b72912b 100644 --- a/native/host/src/present/thread.rs +++ b/native/host/src/present/thread.rs @@ -704,7 +704,7 @@ pub fn thread_object_checked(st: &State, hub: &str, thread: &str, params: &Value for e in entries.iter_mut() { if e["kind"] == "term" { let id = e["id"].as_str().unwrap_or("").to_string(); e["key"] = json!(term_key(thread, &id)); } if e["kind"] == "user" { let text = e["text"].as_str().unwrap_or("").to_string(); let mut refs = crate::session::composer::mention::refs_in(st, hub, &text); - if text.contains('$') { let (cwd, prov, iso) = crate::session::composer::mention::thread_skill_facts(st, thread); refs.extend(crate::agents::skills::chips(&crate::agents::skills::popup_index(&cwd), &text, &prov, iso)); } + if text.contains('$') { let (cwd, prov, iso) = crate::session::composer::mention::thread_skill_facts(st, thread); let model = st.threads.get(thread).map(|t| t.model.as_str()).unwrap_or(""); let skills = crate::agents::skills::for_model(&crate::agents::skills::popup_index(&cwd), &prov, model); refs.extend(crate::agents::skills::chips(&skills, &text, &prov, iso)); } if !refs.is_empty() { e["refs"] = Value::Array(refs); } } } o.insert("entries".into(), Value::Array(entries)); diff --git a/native/host/src/session/mention.rs b/native/host/src/session/mention.rs index da131a9766..98d76b3376 100644 --- a/native/host/src/session/mention.rs +++ b/native/host/src/session/mention.rs @@ -68,7 +68,7 @@ struct Cand { word: String, about: String, score: u32, same: bool, at: u64 } /// What the `$` popup and the chips need of a thread: the folder it works in, its provider, and whether its Claude runs under an account profile. pub fn thread_skill_facts(st: &State, thread: &str) -> (String, String, bool) { let Some(t) = st.threads.get(thread) else { return (String::new(), String::new(), false) }; - let cwd = if !t.worktree.is_empty() { t.worktree.clone() } else { st.projects.get(&t.project).map(|p| p.root.clone()).unwrap_or_default() }; + let cwd = if !t.worktree.is_empty() && st.settings.get(&format!("kicad.main.{thread}")).is_none_or(|s| s != "on") { t.worktree.clone() } else { st.projects.get(&t.project).map(|p| p.root.clone()).unwrap_or_default() }; let bound = st.settings.get(&format!("account.thread.{thread}.{}", t.provider)).map_or(false, |r| serde_json::from_str::(r).ok().map_or(true, |j| !j["id"].as_str().unwrap_or("").is_empty())); (cwd, t.provider.clone(), bound) } @@ -80,7 +80,9 @@ pub fn about(st: &State, id: &str, plain: String) -> String { st.settings.get(&f pub fn rows(st: &State, here: &str, draft: &str) -> Vec { if token(draft).starts_with('$') { let (cwd, provider, isolated) = thread_skill_facts(st, here); - return crate::agents::skills::rows(&crate::agents::skills::popup_index(&cwd), token(draft), &provider, isolated); + let model = st.threads.get(here).map(|t| t.model.as_str()).unwrap_or(""); + let skills = crate::agents::skills::for_model(&crate::agents::skills::popup_index(&cwd), &provider, model); + return crate::agents::skills::rows(&skills, token(draft), &provider, isolated); } let Some((sig, q)) = typing(token(draft)) else { return vec![] }; let ms = machines(); diff --git a/test/agents/fixtures/argv-default.json b/test/agents/fixtures/argv-default.json index ed93639593..2004cc9ed2 100644 --- a/test/agents/fixtures/argv-default.json +++ b/test/agents/fixtures/argv-default.json @@ -16,6 +16,6 @@ "/home/h/Documents/i2cjak/backplane-gpui/build/gpui/results/agents/argv2/work/home/attachments", "--settings", "{\"fastMode\":false}", - "--mcp-config", + "--strict-mcp-config", "--mcp-config", "{\"mcpServers\":{\"backplane\":{\"type\":\"http\",\"url\":\"http://127.0.0.1:3845/mcp/t1700000001-2.1793846406-157?k=REDACTED\"},\"pcbparts\":{\"type\":\"http\",\"url\":\"https://pcbparts.dev/mcp\"}}}" ] diff --git a/web/dist/assets/app.js b/web/dist/assets/app.js index d6304b9439..507d93b58f 100644 --- a/web/dist/assets/app.js +++ b/web/dist/assets/app.js @@ -1,15 +1,15 @@ -function At(e=Date.now(),t=Math.random){let n=Math.floor(t()*1099511627776).toString(36);return`w${e}-${n}`.replace(/[^A-Za-z0-9_-]/g,"").slice(0,64)}function nn(e){return e==="done"||e==="failed"||e==="cancelled"}function sn(e,t){if(!e||e.id!==t.id)return!0;let n=nn(e.state),i=nn(t.state);if(n!==i)return i;return(t.ended??0)>=(e.ended??0)}function rn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var ct={en:{"agy.signout":"Sign out","android.load.earlier":"load earlier","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.stop":"Stop routing","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection."},es:{"agy.signout":"Cerrar sesión","android.load.earlier":"cargar anteriores","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.stop":"Detener ruteo","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet."},ja:{"agy.signout":"サインアウト","android.load.earlier":"以前のメッセージを読み込む","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.stop":"配線を止める","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。"}};function on(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var lt=gi(),Lt=new Set,Nt=new Map;for(let[e,t]of Object.entries(ct.en||{}))if(typeof t==="string"&&!Nt.has(t))Nt.set(t,e);function gi(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function an(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=lt}an();function gt(e){return Lt.add(e),()=>{Lt.delete(e)}}function cn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==lt;if(lt=n,an(),i)for(let s of Lt)s(lt);return i}function v(e,t,n){let s=(ct[lt]||ct.en||{})[e]??ct.en?.[e]??t??e;return on(s,n)}function ke(e){if(!e)return"";let t=Nt.get(e);if(!t)return e;return v(t,e)}function V(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Pe(e,t="",n){let i=V("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function vi(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function wi(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Tt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=V("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=V("div","bp-fb-head");this.upBtn=Pe("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=v("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",v("web.clone.up","Up")),this.pathInput=V("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(o)=>{if(o.key==="Enter"){o.preventDefault();let c=this.pathInput.value.trim();if(c)this.go(c)}}),s.append(this.upBtn,this.pathInput),this.listEl=V("div","bp-fb-list"),this.errEl=V("div","bp-ap-err bp-hidden");let r=V("div","bp-ap-foot");this.actBtn=Pe("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(V("div","bp-fb-empty",v("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(ke(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=v("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(V("div","bp-fb-empty",v("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Pe("","bp-fb-row",()=>{this.go(wi(this.path,n))});i.append(V("span","bp-fb-icon","▸"),V("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(vi(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(ke(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class Pt{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=V("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=V("div","bp-modal bp-ap"),n=V("div","bp-modal-head"),i=V("h2","",v("sidebar.add.project","Add project")),s=Pe("×","icon",()=>this.close());s.title=v("common.close","Close"),s.setAttribute("aria-label",v("common.close","Close")),n.append(i,s),this.tabsEl=V("div","bp-ap-tabs"),this.bodyEl=V("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(r)=>{if(r.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=v("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Pe(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",v("gpui.e.open.folder","Open folder")),e("clone",v("web.clone.tab","Clone from git")))}renderFolder(){let e=new Tt(this.host.hub,(t)=>v("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=V("div","bp-ap-form"),n=V("div","bp-ap-repo"),i=V("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=v("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",v("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(d)=>this.repoKey(d)),this.repoInput=i,this.suggestEl=V("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=V("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=V("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=V("label","bp-ap-check"),r=V("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,V("span","",v("web.clone.start.thread","Start a thread")));let o=[n,this.signinEl,this.destEl,s];if(this.firstText)o.push(V("div","bp-ap-first bp-dim",v("web.clone.first","First message: {text}",{text:this.firstText})));let c=V("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);c.setAttribute("data-testid","clone-start-error");let a=V("div","bp-ap-foot");this.cloneBtn=Pe(v("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),a.append(this.cloneBtn),o.push(c,a),t.append(...o),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,r)=>{let o=Pe("","bp-ap-sug"+(r===this.suggestIdx?" active":""));o.setAttribute("data-testid","clone-suggestion"),o.addEventListener("mousedown",(a)=>a.preventDefault()),o.addEventListener("click",()=>this.pickRepo(s));let c=V("div","bp-ap-sug-top");if(c.append(V("span","bp-ap-sug-name",s.name)),s.private)c.append(V("span","bp-ap-tag",v("web.clone.private","private")));if(o.append(c),s.description)o.append(V("div","bp-ap-sug-desc",s.description));i.push(o)}),n.length===0&&t){if(t.loading)i.push(V("div","bp-ap-sug-note",v("web.clone.loading","Loading…")));else if(t.hint){let s=V("div","bp-ap-sug-note");if(s.append(V("span","",ke(t.hint))),t.state==="signedout"){let r=Pe(v("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(o)=>o.preventDefault()),r.setAttribute("data-testid","clone-signin-btn"),s.append(r)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(ke(t.error)))}else if(t){let o=V("div","bp-ap-where"),c=V("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");c.setAttribute("data-testid","clone-dest-shown");let a=Pe(v("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});a.setAttribute("data-testid","clone-change-folder"),o.append(c,a),n.push(o);let d=V("label","bp-ap-name");d.append(V("span","bp-ap-lbl",v("web.clone.folder.name","Folder name")));let l=V("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(h)=>{if(h.key==="Enter"&&this.canStart())h.preventDefault(),this.startClone()}),d.append(l),n.push(d),!t.ok&&t.error)n.push(this.errLine(ke(t.error)));else if(t.same)n.push(V("div","bp-ap-note bp-dim",v("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let o=e.querySelector('[data-testid="clone-name"]');if(o){if(o.focus(),r!==null)o.setSelectionRange(r,r)}}this.updateCloneBtn()}errLine(e){let t=V("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Pe(v("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Tt(this.host.hub,(i)=>v("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=At();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=ke(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=At(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let r=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(r)}catch(r){let o=ke(r instanceof Error?r.message:String(r));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let c=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(c&&c.id===i){this.apply(c);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(o)}}apply(e){if(!e||e.id!==this.jobId)return;if(!sn(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&rn(e))this.goTo(e)}renderJobView(){this.jobEl=V("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=V("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?v("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?v("web.clone.stopped","Stopped cloning {repo}",{repo:i}):v("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[V("div","bp-ap-job-title",s)];if(t.state==="running"){let o=V("div","bp-ap-phase",ke(t.phase||""));o.setAttribute("data-testid","clone-phase");let c=V("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),a=V("div","bp-ap-bar-fill");if(typeof t.pct==="number")a.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(c.appendChild(a),c.setAttribute("role","progressbar"),typeof t.pct==="number")c.setAttribute("aria-valuenow",String(t.pct));if(r.push(o,c),t.detail)r.push(V("div","bp-ap-detail bp-dim",t.detail));let d=V("div","bp-ap-foot"),l=Pe(v("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((h)=>this.apply(h)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),d.append(l),r.push(d)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let d=V("div","bp-ap-err",ke(t.error));d.setAttribute("data-testid","clone-error"),r.push(d)}let o=V("div","bp-ap-foot"),c=Pe(v("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(o.append(c),t.signin){let d=Pe(v("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});d.setAttribute("data-testid","clone-signin-btn"),o.append(d)}let a=Pe(v("web.clone.retry","Try again"),"primary",()=>{this.retry(t,a)});a.setAttribute("data-testid","clone-retry"),o.append(a),r.push(o)}else if(t.state==="done"){let o=t.notes??[];if(o.length>0){let l=V("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let h of o)l.appendChild(V("li","",ke(h)));r.push(l)}let c=V("div","bp-ap-foot"),a=t.thread?v("web.clone.open.thread","Open the thread"):v("web.clone.open.project","Open the project"),d=Pe(a,"primary",()=>this.goTo(t));d.setAttribute("data-testid","clone-open"),c.append(d),r.push(c)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=V("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(V("div","bp-dim",v("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(V("div","",v("web.clone.signin.enter","Enter this code on GitHub:")));let i=V("div","bp-ap-code-row"),s=V("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=Pe(this.copied?v("web.clone.copied","Copied"):v("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let o=V("a","bp-ap-link",t.url);o.href=t.url,o.target="_blank",o.rel="noopener noreferrer",o.setAttribute("data-testid","clone-signin-url"),n.push(o)}}else if(t.state==="done")n.push(V("div","bp-ok",v("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(V("div","bp-ap-err",ke(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function yi(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function dt(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let r=s[0];if(r.startsWith("`")&&r.endsWith("`")){let o=document.createElement("code");o.className="bp-code-inline",o.textContent=r.slice(1,-1),e.appendChild(o)}else if(r.startsWith("**")&&r.endsWith("**")){let o=document.createElement("strong");o.textContent=r.slice(2,-2),e.appendChild(o)}else if(r.startsWith("*")&&r.endsWith("*")){let o=document.createElement("em");o.textContent=r.slice(1,-1),e.appendChild(o)}else if(r.startsWith("[")){let o=s[2]??"",c=yi(s[3]??"");if(c){let a=document.createElement("a");a.href=c,a.target="_blank",a.rel="noopener noreferrer",a.textContent=o,e.appendChild(a)}else e.appendChild(document.createTextNode(o))}i=n.lastIndex}if(i=(e.ended??0)}function pn(e){if(e.state!=="done")return!1;if(typeof e.hold==="boolean")return!e.hold;return(e.notes??[]).length===0}var ct={en:{"agy.signout":"Sign out","android.load.earlier":"load earlier","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.stop":"Stop routing","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection."},es:{"agy.signout":"Cerrar sesión","android.load.earlier":"cargar anteriores","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.stop":"Detener ruteo","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet."},ja:{"agy.signout":"サインアウト","android.load.earlier":"以前のメッセージを読み込む","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.stop":"配線を止める","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。"}};function hn(e,t){if(!t)return e;return e.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(n,i)=>Object.prototype.hasOwnProperty.call(t,i)?String(t[i]):n)}var lt=Ci(),Pt=new Set,Mt=new Map;for(let[e,t]of Object.entries(ct.en||{}))if(typeof t==="string"&&!Mt.has(t))Mt.set(t,e);function Ci(){let e=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(e.startsWith("ja"))return"ja";if(e.startsWith("es"))return"es";return"en"}function un(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=lt}un();function wt(e){return Pt.add(e),()=>{Pt.delete(e)}}function mn(e){if(!e)return!1;let t=e.toLowerCase(),n=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!n)return!1;let i=n!==lt;if(lt=n,un(),i)for(let s of Pt)s(lt);return i}function f(e,t,n){let s=(ct[lt]||ct.en||{})[e]??ct.en?.[e]??t??e;return hn(s,n)}function Ee(e){if(!e)return"";let t=Mt.get(e);if(!t)return e;return f(t,e)}function V(e,t="",n=""){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function Ie(e,t="",n){let i=V("button",t,e);if(i.type="button",n)i.addEventListener("click",n);return i}function ki(e){let t=e.replace(/[\\/]+$/,"");if(!t)return e||"/";let n=t.split(/[\\/]/);return n[n.length-1]||t}function Si(e,t){let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?e+t:e+n+t}class Bt{hub;actionLabel;action;root;pathInput;upBtn;listEl;errEl;actBtn;path="";parent=null;gen=0;busy=!1;constructor(e,t,n,i=[]){this.hub=e;this.actionLabel=t;this.action=n;this.root=V("div","bp-fb"),this.root.setAttribute("data-testid","folder-browser");let s=V("div","bp-fb-head");this.upBtn=Ie("↑","bp-btn-ghost bp-fb-up",()=>{if(this.parent)this.go(this.parent)}),this.upBtn.title=f("web.clone.up","Up"),this.upBtn.setAttribute("aria-label",f("web.clone.up","Up")),this.pathInput=V("input","bp-input bp-fb-path"),this.pathInput.spellcheck=!1,this.pathInput.setAttribute("data-testid","folder-path"),this.pathInput.addEventListener("keydown",(o)=>{if(o.key==="Enter"){o.preventDefault();let c=this.pathInput.value.trim();if(c)this.go(c)}}),s.append(this.upBtn,this.pathInput),this.listEl=V("div","bp-fb-list"),this.errEl=V("div","bp-ap-err bp-hidden");let r=V("div","bp-ap-foot");this.actBtn=Ie("","primary",()=>{this.run()}),this.actBtn.setAttribute("data-testid","folder-act"),r.append(...i,this.actBtn),this.root.append(s,this.listEl,this.errEl,r)}currentPath(){return this.path}async go(e){let t=++this.gen;this.setError(""),this.listEl.replaceChildren(V("div","bp-fb-empty",f("web.clone.loading","Loading…")));try{let n=await this.hub.rpc("dirs.list",{path:e});if(t!==this.gen)return;this.path=n.path,this.parent=n.parent??null,this.render(n.dirs??[])}catch(n){if(t!==this.gen)return;this.setError(Ee(n instanceof Error?n.message:String(n))),this.render(null)}}refreshLocale(){this.upBtn.title=f("web.clone.up","Up"),this.updateAct()}render(e){if(this.pathInput.value=this.path,this.upBtn.disabled=!this.parent,this.updateAct(),e===null){this.listEl.replaceChildren();return}if(e.length===0){this.listEl.replaceChildren(V("div","bp-fb-empty",f("web.clone.no.folders","No folders here")));return}let t=document.createDocumentFragment();for(let n of e){let i=Ie("","bp-fb-row",()=>{this.go(Si(this.path,n))});i.append(V("span","bp-fb-icon","▸"),V("span","bp-fb-name",n)),t.appendChild(i)}this.listEl.replaceChildren(t),this.listEl.scrollTop=0}updateAct(){this.actBtn.textContent=this.path?this.actionLabel(ki(this.path)):this.actionLabel("…"),this.actBtn.disabled=!this.path||this.busy}async run(){if(!this.path||this.busy)return;this.busy=!0,this.updateAct(),this.setError("");try{await this.action(this.path)}catch(e){this.setError(Ee(e instanceof Error?e.message:String(e)))}finally{this.busy=!1,this.updateAct()}}setError(e){this.errEl.textContent=e,this.errEl.classList.toggle("bp-hidden",!e)}}class It{container;host;backdrop=null;bodyEl=null;tabsEl=null;mode="folder";repoText="";repoValue="";firstText="";wantThread=!0;userParent="";nameText="";nameTouched=!1;dest=null;destGen=0;destPending=!1;destTimer=null;repos=null;reposGen=0;reposTimer=null;showSuggest=!1;suggestIdx=-1;startErr="";starting=!1;picking=!1;jobId="";job=null;specs=new Map;signin=null;copied=!1;repoInput=null;suggestEl=null;destEl=null;signinEl=null;cloneBtn=null;jobEl=null;constructor(e,t){this.container=e;this.host=t}isOpen(){return this.backdrop!==null}open(e={}){let t=this.host.hub.hasFeature("clone"),n=!e.repo&&Boolean(this.jobId)&&(!this.job||this.job.state==="running"||this.job.state==="done");if(!this.backdrop)this.build();if(!n)this.jobId="",this.job=null,this.resetForm();if(e.repo!==void 0||e.text!==void 0)this.repoText=(e.repo??"").trim(),this.repoValue="",this.firstText=(e.text??"").trim();if(this.mode=t&&(e.mode==="clone"||n)?"clone":"folder",this.render(),n){if(this.job)this.maybeGo(this.job);this.reconcile()}else if(this.mode==="clone"&&this.repoText)this.askDest()}reconcile(){let e=this.jobId;if(!e)return;this.host.hub.rpc("clone.status",{id:e}).then((t)=>this.apply(t)).catch(()=>{})}close(){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.reposTimer=null,this.destTimer=null,this.backdrop?.remove(),this.backdrop=null,this.bodyEl=null,this.tabsEl=null}escape(){if(this.picking){this.picking=!1,this.render();return}if(this.showSuggest){this.showSuggest=!1,this.renderSuggest();return}this.close()}refreshLocale(){if(this.backdrop)this.render()}handleFrame(e){if(e.k==="clone"){let t=e.clone;if(t)this.apply(t)}else if(e.k==="clone.repos"){if(this.isOpen()&&this.mode==="clone"&&!this.jobId)this.askRepos(0)}else if(e.k==="clone.signin"){if(!this.signin)return;let t=this.signin.state;if(this.signin=e.signin??null,this.signin?.state==="cancelled")this.signin=null;if(t!=="done"&&this.signin?.state==="done")this.askRepos(0);this.renderSignin()}}build(){let e=V("div","bp-modal-backdrop");e.setAttribute("data-testid","add-project");let t=V("div","bp-modal bp-ap"),n=V("div","bp-modal-head"),i=V("h2","",f("sidebar.add.project","Add project")),s=Ie("×","icon",()=>this.close());s.title=f("common.close","Close"),s.setAttribute("aria-label",f("common.close","Close")),n.append(i,s),this.tabsEl=V("div","bp-ap-tabs"),this.bodyEl=V("div","bp-modal-body bp-ap-body"),t.append(n,this.tabsEl,this.bodyEl),e.appendChild(t),e.addEventListener("mousedown",(r)=>{if(r.target===e)this.close()}),this.container.appendChild(e),this.backdrop=e}resetForm(){this.repoText="",this.repoValue="",this.firstText="",this.wantThread=!0,this.userParent="",this.nameText="",this.nameTouched=!1,this.dest=null,this.destPending=!1,this.repos=null,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",this.starting=!1,this.picking=!1,this.signin=null,this.copied=!1}render(){if(!this.bodyEl||!this.tabsEl||!this.backdrop)return;let e=this.backdrop.querySelector(".bp-modal-head h2");if(e)e.textContent=f("sidebar.add.project","Add project");if(this.renderTabs(),this.repoInput=null,this.suggestEl=null,this.destEl=null,this.signinEl=null,this.cloneBtn=null,this.jobEl=null,this.mode==="folder")this.renderFolder();else if(this.jobId&&this.job)this.renderJobView();else if(this.picking)this.renderPickParent();else this.renderCloneForm()}renderTabs(){if(!this.tabsEl)return;if(!this.host.hub.hasFeature("clone")){this.tabsEl.classList.add("bp-hidden");return}this.tabsEl.classList.remove("bp-hidden");let e=(t,n)=>{let i=Ie(n,"bp-ap-tab"+(this.mode===t?" on":""),()=>{if(this.mode===t)return;if(this.mode=t,this.render(),t==="clone"&&!this.jobId&&this.repos===null)this.askRepos(0)});return i.setAttribute("data-testid",`ap-tab-${t}`),i.setAttribute("aria-pressed",String(this.mode===t)),i};this.tabsEl.replaceChildren(e("folder",f("gpui.e.open.folder","Open folder")),e("clone",f("web.clone.tab","Clone from git")))}renderFolder(){let e=new Bt(this.host.hub,(t)=>f("web.clone.add.dir","Add {dir}",{dir:t}),async(t)=>{let n=await this.host.hub.rpc("project.add",{path:t},30000);if(this.close(),n.project)this.host.onProjectAdded(n.project)});this.bodyEl.replaceChildren(e.root),e.go("")}renderCloneForm(){let e=this.bodyEl,t=V("div","bp-ap-form"),n=V("div","bp-ap-repo"),i=V("input","bp-input");i.type="text",i.spellcheck=!1,i.autocomplete="off",i.placeholder=f("web.clone.repo.placeholder","https or ssh URL, or owner/repo"),i.setAttribute("aria-label",f("web.clone.repo.placeholder","https or ssh URL, or owner/repo")),i.setAttribute("data-testid","clone-repo"),i.value=this.repoText,i.addEventListener("input",()=>{if(this.repoText=i.value,this.repoValue="",this.showSuggest=!0,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";this.askRepos(200),this.askDest(250)}),i.addEventListener("focus",()=>{if(this.showSuggest=!0,this.repos===null)this.askRepos(0);else this.renderSuggest()}),i.addEventListener("blur",()=>{window.setTimeout(()=>{if(document.activeElement!==i)this.showSuggest=!1,this.renderSuggest()},120)}),i.addEventListener("keydown",(d)=>this.repoKey(d)),this.repoInput=i,this.suggestEl=V("div","bp-ap-suggest bp-hidden"),this.suggestEl.setAttribute("data-testid","clone-suggest"),n.append(i,this.suggestEl),this.signinEl=V("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.destEl=V("div","bp-ap-dest"),this.destEl.setAttribute("data-testid","clone-dest");let s=V("label","bp-ap-check"),r=V("input");r.type="checkbox",r.checked=this.wantThread,r.setAttribute("data-testid","clone-thread"),r.addEventListener("change",()=>{this.wantThread=r.checked}),s.append(r,V("span","",f("web.clone.start.thread","Start a thread")));let o=[n,this.signinEl,this.destEl,s];if(this.firstText)o.push(V("div","bp-ap-first bp-dim",f("web.clone.first","First message: {text}",{text:this.firstText})));let c=V("div","bp-ap-err"+(this.startErr?"":" bp-hidden"),this.startErr);c.setAttribute("data-testid","clone-start-error");let a=V("div","bp-ap-foot");this.cloneBtn=Ie(f("web.clone.go","Clone"),"primary",()=>{this.startClone()}),this.cloneBtn.setAttribute("data-testid","clone-go"),a.append(this.cloneBtn),o.push(c,a),t.append(...o),e.replaceChildren(t),this.renderSuggest(),this.renderSignin(),this.renderDest(),window.setTimeout(()=>{if(this.repoInput===i&&!this.repoText)i.focus()},0)}repoKey(e){let t=this.repos?.repos??[],n=this.showSuggest&&t.length>0;if(e.key==="ArrowDown"&&n)e.preventDefault(),this.suggestIdx=Math.min(t.length-1,this.suggestIdx+1),this.renderSuggest();else if(e.key==="ArrowUp"&&n)e.preventDefault(),this.suggestIdx=Math.max(-1,this.suggestIdx-1),this.renderSuggest();else if(e.key==="Enter"){e.preventDefault();let i=n&&this.suggestIdx>=0?t[this.suggestIdx]:void 0;if(i)this.pickRepo(i);else if(this.canStart())this.startClone()}}pickRepo(e){if(this.repoText=e.name,this.repoValue=e.value,this.showSuggest=!1,this.suggestIdx=-1,this.startErr="",!this.nameTouched)this.nameText="";if(this.repoInput)this.repoInput.value=e.name;this.renderSuggest(),this.askDest()}repoArg(){return this.repoValue||this.repoText.trim()}askRepos(e){if(this.reposTimer!==null)window.clearTimeout(this.reposTimer);this.reposTimer=window.setTimeout(()=>{this.reposTimer=null;let t=++this.reposGen,n=this.repoValue?"":this.repoText.trim();this.host.hub.rpc("clone.repos",{q:n,limit:12},30000).then((i)=>{if(t!==this.reposGen)return;this.repos=i,this.renderSuggest(),this.renderSignin()}).catch(()=>{if(t!==this.reposGen)return;this.repos={repos:[],state:"error",hint:"Couldn't list your GitHub repositories."},this.renderSuggest()})},e)}renderSuggest(){let e=this.suggestEl;if(!e)return;let t=this.repos,n=t?.repos??[],i=[];if(this.showSuggest&&!this.repoValue){if(n.forEach((s,r)=>{let o=Ie("","bp-ap-sug"+(r===this.suggestIdx?" active":""));o.setAttribute("data-testid","clone-suggestion"),o.addEventListener("mousedown",(a)=>a.preventDefault()),o.addEventListener("click",()=>this.pickRepo(s));let c=V("div","bp-ap-sug-top");if(c.append(V("span","bp-ap-sug-name",s.name)),s.private)c.append(V("span","bp-ap-tag",f("web.clone.private","private")));if(o.append(c),s.description)o.append(V("div","bp-ap-sug-desc",s.description));i.push(o)}),n.length===0&&t){if(t.loading)i.push(V("div","bp-ap-sug-note",f("web.clone.loading","Loading…")));else if(t.hint){let s=V("div","bp-ap-sug-note");if(s.append(V("span","",Ee(t.hint))),t.state==="signedout"){let r=Ie(f("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});r.addEventListener("mousedown",(o)=>o.preventDefault()),r.setAttribute("data-testid","clone-signin-btn"),s.append(r)}i.push(s)}}}e.replaceChildren(...i),e.classList.toggle("bp-hidden",i.length===0)}askDest(e=0){if(this.destTimer!==null)window.clearTimeout(this.destTimer);this.destPending=!0,this.updateCloneBtn(),this.destTimer=window.setTimeout(()=>{this.destTimer=null;let t=++this.destGen,n=this.repoArg();if(!n){this.dest=null,this.destPending=!1,this.renderDest();return}let i={repo:n};if(this.userParent)i.parent=this.userParent;if(this.nameTouched&&this.nameText.trim())i.name=this.nameText.trim();else if(this.userParent)i.name="";this.host.hub.rpc("clone.dest",i).then((s)=>{if(t!==this.destGen)return;if(this.dest=s,this.destPending=!1,!this.nameTouched&&s.folder)this.nameText=s.folder;this.renderDest()}).catch((s)=>{if(t!==this.destGen)return;this.dest={ok:!1,error:s instanceof Error?s.message:String(s)},this.destPending=!1,this.renderDest()})},e)}renderDest(){let e=this.destEl;if(!e)return;let t=this.dest,n=[];if(t&&!t.repo){if(t.error&&this.repoText.trim())n.push(this.errLine(Ee(t.error)))}else if(t){let o=V("div","bp-ap-where"),c=V("span","bp-ap-dest-path",t.destShown||t.dest||t.defaultParentShown||"");c.setAttribute("data-testid","clone-dest-shown");let a=Ie(f("web.clone.change.folder","Change folder"),"bp-btn-line",()=>{this.picking=!0,this.render()});a.setAttribute("data-testid","clone-change-folder"),o.append(c,a),n.push(o);let d=V("label","bp-ap-name");d.append(V("span","bp-ap-lbl",f("web.clone.folder.name","Folder name")));let l=V("input","bp-input");if(l.type="text",l.spellcheck=!1,l.value=this.nameText,l.setAttribute("data-testid","clone-name"),l.addEventListener("input",()=>{this.nameText=l.value,this.nameTouched=l.value.trim()!=="",this.startErr="",this.askDest(250)}),l.addEventListener("keydown",(h)=>{if(h.key==="Enter"&&this.canStart())h.preventDefault(),this.startClone()}),d.append(l),n.push(d),!t.ok&&t.error)n.push(this.errLine(Ee(t.error)));else if(t.same)n.push(V("div","bp-ap-note bp-dim",f("web.clone.same","Already cloned there: it is added as it is.")))}let i=document.activeElement,s=i&&e.contains(i)&&i.getAttribute("data-testid")==="clone-name",r=s?i.selectionStart:null;if(e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0),s){let o=e.querySelector('[data-testid="clone-name"]');if(o){if(o.focus(),r!==null)o.setSelectionRange(r,r)}}this.updateCloneBtn()}errLine(e){let t=V("div","bp-ap-err",e);return t.setAttribute("data-testid","clone-dest-error"),t}canStart(){return Boolean(this.dest?.ok&&this.dest.repo&&!this.destPending&&!this.starting&&this.repoArg())}updateCloneBtn(){if(this.cloneBtn)this.cloneBtn.disabled=!this.canStart()}renderPickParent(){let e=this.dest?.parent||this.userParent||this.dest?.defaultParent||"",t=Ie(f("web.clone.back","Back"),"bp-btn-line",()=>{this.picking=!1,this.render()}),n=new Bt(this.host.hub,(i)=>f("web.clone.use.dir","Use {dir}",{dir:i}),async(i)=>{this.userParent=i,this.picking=!1,this.render(),this.askDest()},[t]);this.bodyEl.replaceChildren(n.root),n.go(e)}async startClone(){if(!this.canStart()||!this.dest)return;this.starting=!0,this.startErr="",this.updateCloneBtn();let e={repo:this.repoArg(),thread:this.wantThread,text:this.firstText},t=Tt();this.jobId=t,this.job=null,this.specs.set(t,e);try{let n=await this.host.hub.rpc("clone.start",{id:t,repo:e.repo,parent:this.dest.parent??"",name:this.dest.folder??this.nameText.trim(),thread:e.thread,text:e.text});this.starting=!1,this.apply(n)}catch(n){this.starting=!1;let i=Ee(n instanceof Error?n.message:String(n));if(this.jobId===t&&!this.job){let s=await this.host.hub.rpc("clone.status",{id:t}).catch(()=>null);if(s&&s.id===t){this.apply(s);return}}if(this.jobId===t&&!this.job){if(this.jobId="",this.startErr=i,this.mode==="clone")this.render()}}}async retry(e,t){let n=this.specs.get(e.id)??{repo:e.origin||e.repo||"",thread:!0,text:""},i=Tt(),s=this.jobId;this.jobId=i,this.specs.set(i,n),t.disabled=!0;try{let r=await this.host.hub.rpc("clone.start",{id:i,repo:n.repo,dest:e.dest??"",thread:n.thread,text:n.text});this.apply(r)}catch(r){let o=Ee(r instanceof Error?r.message:String(r));if(this.jobId!==i)return;if(!this.job||this.job.id!==i){let c=await this.host.hub.rpc("clone.status",{id:i}).catch(()=>null);if(c&&c.id===i){this.apply(c);return}}if(this.jobId===i&&(!this.job||this.job.id!==i))this.jobId=s,t.disabled=!1,this.showJobError(o)}}apply(e){if(!e||e.id!==this.jobId)return;if(!dn(this.job,e))return;if(this.job=e,this.copied=!1,this.isOpen()&&this.mode==="clone")if(this.jobEl&&this.jobEl.isConnected)this.renderJob();else this.render();this.maybeGo(e)}maybeGo(e){if(this.isOpen()&&e.id===this.jobId&&pn(e))this.goTo(e)}renderJobView(){this.jobEl=V("div","bp-ap-job"),this.jobEl.setAttribute("data-testid","clone-job"),this.signinEl=V("div","bp-ap-signin bp-hidden"),this.signinEl.setAttribute("data-testid","clone-signin"),this.bodyEl.replaceChildren(this.jobEl,this.signinEl),this.renderJob(),this.renderSignin()}renderJob(){let e=this.jobEl,t=this.job;if(!e||!t)return;let n=t.destShown||t.dest||"",i=t.repo||"",s=t.state==="done"?f("web.clone.cloned","Cloned {repo} into {dest}",{repo:i,dest:n}):t.state==="cancelled"?f("web.clone.stopped","Stopped cloning {repo}",{repo:i}):f("web.clone.cloning","Cloning {repo} into {dest}",{repo:i,dest:n}),r=[V("div","bp-ap-job-title",s)];if(t.state==="running"){let o=V("div","bp-ap-phase",Ee(t.phase||""));o.setAttribute("data-testid","clone-phase");let c=V("div","bp-ap-bar"+(typeof t.pct==="number"?"":" indeterminate")),a=V("div","bp-ap-bar-fill");if(typeof t.pct==="number")a.style.width=`${Math.max(0,Math.min(100,t.pct))}%`;if(c.appendChild(a),c.setAttribute("role","progressbar"),typeof t.pct==="number")c.setAttribute("aria-valuenow",String(t.pct));if(r.push(o,c),t.detail)r.push(V("div","bp-ap-detail bp-dim",t.detail));let d=V("div","bp-ap-foot"),l=Ie(f("common.cancel","Cancel"),"bp-btn-line",()=>{this.host.hub.rpc("clone.cancel",{id:t.id}).then((h)=>this.apply(h)).catch(()=>{})});l.setAttribute("data-testid","clone-cancel"),d.append(l),r.push(d)}else if(t.state==="failed"||t.state==="cancelled"){if(t.state==="failed"&&t.error){let d=V("div","bp-ap-err",Ee(t.error));d.setAttribute("data-testid","clone-error"),r.push(d)}let o=V("div","bp-ap-foot"),c=Ie(f("web.clone.back","Back"),"bp-btn-line",()=>{this.jobId="",this.job=null,this.signin=null,this.render(),this.askDest()});if(o.append(c),t.signin){let d=Ie(f("web.clone.signin","Sign in to GitHub"),"bp-btn-line",()=>{this.startSignin()});d.setAttribute("data-testid","clone-signin-btn"),o.append(d)}let a=Ie(f("web.clone.retry","Try again"),"primary",()=>{this.retry(t,a)});a.setAttribute("data-testid","clone-retry"),o.append(a),r.push(o)}else if(t.state==="done"){let o=t.notes??[];if(o.length>0){let l=V("ul","bp-ap-notes");l.setAttribute("data-testid","clone-notes");for(let h of o)l.appendChild(V("li","",Ee(h)));r.push(l)}let c=V("div","bp-ap-foot"),a=t.thread?f("web.clone.open.thread","Open the thread"):f("web.clone.open.project","Open the project"),d=Ie(a,"primary",()=>this.goTo(t));d.setAttribute("data-testid","clone-open"),c.append(d),r.push(c)}e.replaceChildren(...r)}showJobError(e){if(!this.jobEl)return;this.jobEl.querySelector(".bp-ap-job-err")?.remove();let t=V("div","bp-ap-err bp-ap-job-err",e);this.jobEl.appendChild(t)}goTo(e){this.jobId="",this.job=null,this.close(),this.host.onCloneDone(e)}async startSignin(){this.signin={state:"starting"},this.copied=!1,this.renderSignin();try{let e=await this.host.hub.rpc("clone.signin",{restart:!0},30000);if(!this.signin||this.signin.state==="starting")this.signin=e}catch(e){this.signin={state:"failed",error:e instanceof Error?e.message:String(e)}}if(this.signin?.state==="done")this.askRepos(0);this.renderSignin()}renderSignin(){let e=this.signinEl;if(!e)return;let t=this.signin,n=[];if(t&&t.state){if(t.state==="starting"||t.state==="waiting"&&!t.code)n.push(V("div","bp-dim",f("web.clone.signin.wait","Starting GitHub sign-in…")));else if(t.state==="waiting"){n.push(V("div","",f("web.clone.signin.enter","Enter this code on GitHub:")));let i=V("div","bp-ap-code-row"),s=V("span","bp-ap-code",t.code||"");s.setAttribute("data-testid","clone-signin-code");let r=Ie(this.copied?f("web.clone.copied","Copied"):f("common.copy","Copy"),"bp-btn-line",()=>{navigator.clipboard?.writeText(t.code||"").then(()=>{this.copied=!0,this.renderSignin()}).catch(()=>{})});if(i.append(s,r),n.push(i),t.url){let o=V("a","bp-ap-link",t.url);o.href=t.url,o.target="_blank",o.rel="noopener noreferrer",o.setAttribute("data-testid","clone-signin-url"),n.push(o)}}else if(t.state==="done")n.push(V("div","bp-ok",f("web.clone.signin.done","Signed in to GitHub")));else if(t.state==="failed")n.push(V("div","bp-ap-err",Ee(t.error||"")))}e.replaceChildren(...n),e.classList.toggle("bp-hidden",n.length===0)}}function Ai(e){try{let t=new URL(e,window.location.origin);if(t.protocol==="https:"||t.protocol==="http:")return t.href}catch{}return null}function dt(e,t){let n=/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*|\[([^\]]+)\]\(([^)]+)\))/g,i=0,s;while((s=n.exec(t))!==null){if(s.index>i)e.appendChild(document.createTextNode(t.slice(i,s.index)));let r=s[0];if(r.startsWith("`")&&r.endsWith("`")){let o=document.createElement("code");o.className="bp-code-inline",o.textContent=r.slice(1,-1),e.appendChild(o)}else if(r.startsWith("**")&&r.endsWith("**")){let o=document.createElement("strong");o.textContent=r.slice(2,-2),e.appendChild(o)}else if(r.startsWith("*")&&r.endsWith("*")){let o=document.createElement("em");o.textContent=r.slice(1,-1),e.appendChild(o)}else if(r.startsWith("[")){let o=s[2]??"",c=Ai(s[3]??"");if(c){let a=document.createElement("a");a.href=c,a.target="_blank",a.rel="noopener noreferrer",a.textContent=o,e.appendChild(a)}else e.appendChild(document.createTextNode(o))}i=n.lastIndex}if(i{navigator.clipboard?.writeText(l).then(()=>{y.textContent="✓",window.setTimeout(()=>{y.textContent=E},1200)}).catch(()=>{})}),p.append(u,y);let g=document.createElement("pre"),f=document.createElement("code");f.textContent=l,g.appendChild(f),h.append(p,g),t.appendChild(h);continue}if(!s.trim()){i++;continue}let r=/^(#{1,4})\s+(.+)$/.exec(s);if(r){let a=document.createElement(`h${Math.min(4,r[1].length+1)}`);a.className="bp-md-h",dt(a,r[2]),t.appendChild(a),i++;continue}if(s.startsWith("> ")){let a=document.createElement("blockquote");a.className="bp-md-quote";let d=[];while(i "))d.push(n[i].slice(2)),i++;dt(a,d.join(` -`)),t.appendChild(a);continue}if(/^\s*[-*]\s+/.test(s)){let a=document.createElement("ul");a.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))o.push(n[i]),i++;let c=document.createElement("p");c.className="bp-md-p";for(let a=0;a0)c.appendChild(document.createElement("br"));dt(c,o[a])}t.appendChild(c)}return t}var ln="http://www.w3.org/2000/svg";function dn(e){let t=document.createElementNS(ln,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(ln,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Bt(e){return e<10000000000?e*1000:e}function Ei(e){if(!e)return"";return new Date(Bt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function xi(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Mt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class It{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=v("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=v("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let r=document.createElement("button");r.type="button",r.textContent=v("tools.retry","Retry"),r.addEventListener("click",n),i.append(s,r),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=v("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){this.thread=e,this.entries=t.filter((r)=>!Mt(r)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((r)=>r.id)),s=e.filter((r)=>!Mt(r)&&!i.has(r.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(Mt(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((o)=>o.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let r=this.liveNodes.get(e);if(r){if(r.replaceChildren(vt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||v("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let r=document.createElement("button");if(r.type="button",s.primary)r.className="primary";r.textContent=s.label,r.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(r)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(vt(this.btwNote.a)),n.append(i,s);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,r),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let r=v("common.copy","Copy"),o=document.createElement("span");o.textContent=r,s.append(dn(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),o),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{o.textContent="✓",window.setTimeout(()=>{o.textContent=r},1000)}).catch(()=>{})});let c=document.createElement("button");c.type="button",c.className="bp-entry-act";let a=document.createElement("span");a.textContent=v("reply.action","Reply"),c.append(dn(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),a),c.addEventListener("click",()=>this.cb.onReplyEntry(e));let d=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let h=Ei(e.at);if(t)l.textContent=h,i.append(s,...d?[c]:[],l);else{let p=n&&e.at?xi(Bt(e.at)-Bt(n)):"",u=h?p?v("web.chat.finished.dur","Finished {time} · {dur}",{time:h,dur:p}):v("web.chat.finished","Finished {time}",{time:h}):"";l.textContent=e.live?v("web.chat.streaming","Streaming…"):u,i.append(l,s,...d?[c]:[])}return i}renderEntries(e){this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let t=document.createDocumentFragment();if(!this.thread){let i=document.createElement("div");i.className="bp-empty-state",i.textContent=v("web.chat.choose","Choose a project thread on the left to begin."),t.appendChild(i),this.listEl.replaceChildren(t);return}if(this.entries.length===0){let i=document.createElement("div");i.className="bp-empty-state",i.textContent=v("web.chat.empty","No messages yet. Type below to start a turn."),t.appendChild(i),this.listEl.replaceChildren(t);return}let n=0;for(let i of this.entries){if(i.kind==="user"&&i.at)n=i.at;let s=document.createElement("article");if(s.className=`bp-entry bp-entry-${i.kind}`+(i.live?" is-live":""),s.setAttribute("data-entry-id",i.id),i.kind==="tool"&&i.tool){let a=document.createElement("div");a.className=`bp-tool-pill bp-tool-${i.tool.state||"done"}`;let d=document.createElement("span");if(d.className="bp-tool-name",d.textContent=i.tool.name,a.appendChild(d),i.tool.summary){let l=document.createElement("span");l.className="bp-tool-summary",l.textContent=i.tool.summary,a.appendChild(l)}s.appendChild(a),t.appendChild(s);continue}if(i.kind==="ask"&&i.ask){let a=i.ask,d=document.createElement("div");d.className="bp-ask-card",d.setAttribute("data-testid",`ask-${a.id}`);let l=document.createElement("div");if(l.className="bp-ask-q",l.textContent=a.question,d.appendChild(l),a.state==="open"){let h=document.createElement("div");if(h.className="bp-ask-opts",a.options&&a.options.length>0)for(let p of a.options){let u=document.createElement("button");u.type="button",u.textContent=p.label,u.addEventListener("click",()=>this.cb.onAnswerAsk(a.id,p.id)),h.appendChild(u)}else{let p=document.createElement("input");p.type="text",p.className="bp-input",p.placeholder=v("web.chat.answer.placeholder","Type answer…");let u=document.createElement("button");u.type="button",u.className="primary",u.textContent=v("web.chat.answer.btn","Answer"),u.addEventListener("click",()=>{if(p.value.trim())this.cb.onAnswerAsk(a.id,p.value.trim())}),h.append(p,u)}d.appendChild(h)}else{let h=document.createElement("div");h.className="bp-ask-answered",h.textContent=v("web.chat.answered","Answered: {answer}",{answer:a.answered??""}),d.appendChild(h)}s.appendChild(d),t.appendChild(s);continue}let r=Boolean(i.text&&i.text.trim().length>0),o=Boolean(i.images&&i.images.length>0),c=Boolean(i.attachments&&i.attachments.length>0);if(!r&&!o&&!c&&!i.live)continue;if(i.replyTo?.quote){let a=document.createElement("div");a.className="bp-reply-quote",a.textContent=v("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:i.replyTo.quote});let d=i.replyTo.id;a.setAttribute("role","button"),a.tabIndex=0,a.setAttribute("data-testid","entry-reply-quote");let l=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(d);else this.goTo(d)};a.addEventListener("click",l),a.addEventListener("keydown",(h)=>{if(h.key==="Enter"||h.key===" ")h.preventDefault(),l()}),s.appendChild(a)}if(r||i.live){let a=document.createElement("div");if(a.className="bp-entry-body",i.kind==="user")a.textContent=i.text;else a.appendChild(vt(i.text||""));if(i.live)this.liveNodes.set(i.id,a);s.appendChild(a)}if(c&&i.attachments){let a=document.createElement("div");a.className="bp-entry-images";for(let d of i.attachments)if(d.previewUrl){let l=document.createElement("img");l.className="bp-reply-img",l.src=d.previewUrl,l.alt=d.name||"attachment",a.appendChild(l)}else if(d.path||d.name){let l=document.createElement("span");l.className="bp-tool-pill",l.textContent=d.name||d.path||"image",a.appendChild(l)}if(a.childElementCount>0)s.appendChild(a)}if(i.images&&i.images.length>0){let a=document.createElement("div");a.className="bp-entry-images";for(let d of i.images){let l=document.createElement("img");l.className="bp-reply-img",l.alt=d;let h=`${i.id}|${d}`,p=this.imageCache.get(h);if(p)l.src=p;else this.cb.onLoadImage(i.id,d).then((u)=>{if(!u)return;let y=u.url??(u.mime&&u.data?`data:${u.mime};base64,${u.data}`:"");if(!y)return;this.imageCache.set(h,y),l.src=y});a.appendChild(l)}s.appendChild(a)}s.appendChild(this.makeEntryActions(i,i.kind==="user",i.kind==="assistant"?n:void 0)),t.appendChild(s)}if(this.listEl.replaceChildren(t),e)this.scrollToBottom()}}var pn="http://www.w3.org/2000/svg",hn=4,un=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function mn(e){let t=document.createElementNS(pn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(pn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ci(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Rt{popupEl;attachStripEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=v("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let r=document.createElement("div");r.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let o=document.createElement("div");o.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",o.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(o,this.memoryText);let c=document.createElement("div");c.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=v("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",v("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(mn(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=v("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",v("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(mn(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=v("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=v("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),c.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.memoryEl,c),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(a)=>{let d=a.clipboardData?.items;if(!d)return;let l=[];for(let h=0;h0)a.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(a)=>{if(this.popupMode!=="none"){let d=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(a.key==="ArrowDown"){a.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,d),this.renderPopup();return}if(a.key==="ArrowUp"){a.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,d))%Math.max(1,d),this.renderPopup();return}if(a.key==="Tab"||a.key==="Enter"&&!a.shiftKey&&this.shouldCompleteOnEnter()){a.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(a.key==="Escape"){a.preventDefault(),this.closePopup();return}}if(a.key==="Enter"&&!a.shiftKey)a.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Ci(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` -`)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=v("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let o=document.createElement("button");o.type="button",o.className="icon bp-reply-strip-drop",o.textContent="×";let c=v("reply.cancel","Cancel reply");if(o.title=c,o.setAttribute("aria-label",c),o.setAttribute("data-testid","composer-reply-drop"),n)o.addEventListener("click",n);this.replyEl.replaceChildren(i,o),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} -${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=v("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=v("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",v("web.composer.attach","Attach image")),this.voiceBtn.title=v("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",v("web.composer.voice","Voice dictation")),this.sendBtn.textContent=v("composer.send","Send"),this.stopBtn.textContent=v("composer.stop","Stop")}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` -`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(o)=>{o.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.detail||t.label,i.append(s,r),i.addEventListener("mousedown",(o)=>{o.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),r=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=r+s,this.textarea.selectionStart=this.textarea.selectionEnd=r.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!un.has(t.type)){this.showError(v("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=hn){this.showError(v("web.composer.maximages","At most {max} images per message.",{max:hn}));break}let n=await new Promise((s,r)=>{let o=new FileReader;o.onload=()=>s(String(o.result||"")),o.onerror=()=>r(Error("read failed")),o.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let r=document.createElement("button");r.type="button",r.className="icon bp-attach-rm",r.textContent="×",r.title=v("common.remove","Remove"),r.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,r),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function bn(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var ki=new Set(["bom","checks","life","plan","fab"]);function wt(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&ki.has(t.id))}function fn(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function yt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${c}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=o}return i}function tt(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function nt(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var Si=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),Ai=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function gn(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let o of i)if(Si.has(o))return o;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(Ai.has(r)){let o=s.split("-");if(o.length>=2&&/^\d+$/.test(o[1]))return`${o[0]}-${o[1]}`;return o[0]}return i.slice(0,2).join("_")}function vn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${tt(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${tt(n)}`,tone:"warn"};return{text:tt(n),tone:"ok"}}function wn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((r)=>r==="dnp"&&Boolean(i.dnp)||s.includes(r))})}function yn(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function jt(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Et(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function En(e){return e.state==="routed"||e.state==="verified"}function xn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function Cn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function kn(e){return e==="extra"?"costs-more limits":"base-price limits"}function Dt(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Sn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Ht(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}class Ft{hostEl;panelEl;stripEl;cb;infos=new Map;digest="";project="";askedProject="";watchGen=0;openPanel="";errorMsg="";bomFilter="";bomSelectedId="";bomEditingId="";bomEditGen=0;bomEditDraft="";bomEditStatus="";bomLastUndo=null;checksSource="";checksSelectedId="";checksStatus="";lifeSelectedKey="";lifePartSamples=null;lifePartLoading=!1;planHideDone=!1;planStatus="";fabStatus="";constructor(e,t,n){this.cb=n,this.hostEl=t,this.panelEl=document.createElement("aside"),this.panelEl.className="bp-mgmt-panel bp-hidden",this.panelEl.setAttribute("aria-label","Project management panel"),this.stripEl=document.createElement("div"),this.stripEl.className="bp-mgmt-strip bp-hidden",this.stripEl.setAttribute("data-testid","mgmt-strip"),this.stripEl.setAttribute("aria-label","Project management tabs"),e.appendChild(this.panelEl),t.appendChild(this.stripEl)}openTab(e){let t=this.getStateInfo();if(!wt(t).some((n)=>n.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return wt(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,r]of Object.entries(n.data))if(r&&typeof r==="object")this.infos.set(`mgmt.${s}.${i}`,r)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){let e=this.getStateInfo(),t=wt(e);if(!this.digest||t.length===0){this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let c=this.openPanel===r.id;o.className="bp-mgmt-tab"+(c?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",c?"true":"false");let a=document.createElement("span");a.textContent=ke(r.label),o.appendChild(a);let d=this.getPanelData(r.id),l=fn(d);if(l){let h=document.createElement("span");h.className=`bp-mgmt-badge bp-tone-${l.tone}`,h.textContent=l.text,o.appendChild(h)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=v("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",v("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,s.appendChild(r)}switch(this.openPanel){case"bom":s.appendChild(this.renderBom());break;case"checks":s.appendChild(this.renderChecks());break;case"life":s.appendChild(this.renderLife());break;case"plan":s.appendChild(this.renderPlan());break;case"fab":s.appendChild(this.renderFab());break}this.panelEl.replaceChildren(s)}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let r=document.createElement("span"),o=t.source==="kicad";if(r.className="bp-mgmt-pill"+(o?" accent":""),r.textContent=o?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let d=document.createElement("span");d.className="bp-dim",d.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${nt(t.cost)}/board`:`${nt(t.cost)}/board`,i.appendChild(d)}if(t.paused){let d=document.createElement("span");d.className="bp-mgmt-faint",d.textContent="Stock check paused",i.appendChild(d)}if(e.appendChild(i),t.stock_note){let d=document.createElement("div");d.className="bp-mgmt-note bp-mgmt-faint",d.textContent=ke(t.stock_note),e.appendChild(d)}let c=this.bomEditingId?n.find((d)=>d.id===this.bomEditingId)??null:null;if(c)e.appendChild(this.renderBomEditor(c));else{let d=document.createElement("div");d.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(a,n)}),d.appendChild(l),e.appendChild(d)}let a=document.createElement("div");return a.className="bp-mgmt-rows",a.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(a,n),e.appendChild(a),e}renderBomRows(e,t){let n=wn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((r)=>Boolean(r.mpn)||Boolean(r.fab)),s=document.createDocumentFragment();for(let r of n){let o=Array.isArray(r.refs)?r.refs:[],c=document.createElement("div");c.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),c.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let a=document.createElement("div");a.className="bp-mgmt-row-line";let d=document.createElement("span");if(d.className="bp-mgmt-strong bp-mgmt-flex1",d.textContent=yt(o,24),a.appendChild(d),r.dnp){let E=document.createElement("span");E.className="bp-mgmt-pill",E.textContent=v("gpui.mgmt.bom.dnp","DNP"),a.appendChild(E)}else{let E=vn(r.stock);if(E){let g=document.createElement("span");g.className=`bp-tone-${E.tone}`,g.textContent=E.text,a.appendChild(g)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(E)=>{E.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),a.appendChild(l);let h=document.createElement("div");h.className="bp-mgmt-row-sub";let p=[`${r.qty??o.length}×`,r.value??"",gn(r.footprint??"")].filter(Boolean).join(" · "),u=document.createElement("span");u.className="bp-dim",u.textContent=p;let y=document.createElement("span");if(y.className="bp-mgmt-flex1",r.mpn)y.textContent=r.mpn;else if(i&&!r.dnp)y.className+=" bp-tone-warn",y.textContent=v("gpui.mgmt.bom.nompn","no MPN");if(h.append(u,y),!r.dnp&&typeof r.stock?.price==="number"){let E=document.createElement("span");E.className="bp-dim",E.textContent=nt(r.stock.price),h.appendChild(E)}if(!r.dnp&&r.stock?.class){let E=document.createElement("span");E.className="bp-mgmt-faint",E.textContent=ke(r.stock.class),h.appendChild(E)}c.append(a,h),c.addEventListener("click",()=>{this.bomSelectedId=r.id,this.renderBomRows(e,t)}),s.appendChild(c)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=yt(n,30);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,r);let o=document.createElement("input");o.type="text",o.className="bp-mgmt-filter",o.placeholder="MPN",o.value=this.bomEditDraft,o.addEventListener("input",()=>{this.bomEditDraft=o.value});let c=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),a=async(p,u=!1)=>{let y=c();this.bomEditStatus="Writing…",this.render();try{let E=await this.cb.hub.rpc("mgmt.bom.edit",p);if(!Dt(y,c()))return;this.bomLastUndo=!u&&(E.changed??0)>0?{project:p.project,editId:y.editId,refs:p.refs.slice(),field:p.field,was:typeof E.was==="string"?E.was:p.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=u?"Restored":(E.changed??0)===0?"No change":E.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(E){if(!Dt(y,c()))return;this.bomEditStatus=E instanceof Error?E.message:"Could not save edit"}this.render()},d=document.createElement("div");d.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{a({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn",h.textContent=e.dnp?"Clear DNP":"Mark DNP",h.addEventListener("click",()=>{a({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),d.append(l,h),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let p=this.bomLastUndo,u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn",u.textContent="Undo",u.addEventListener("click",()=>{a(Sn(p),!0)}),d.appendChild(u)}if(t.append(i,o,d),this.bomEditStatus){let p=document.createElement("div");p.className="bp-mgmt-faint",p.textContent=this.bomEditStatus,t.appendChild(p)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((p)=>p.source).filter(Boolean))),s=(p)=>t.sources?.[p]?.label||p.toUpperCase(),r=(p)=>t.sources?.[p]?.judged===!0,o=document.createElement("div");o.className="bp-mgmt-head bp-mgmt-scroll-x";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),c.textContent=v("gpui.mgmt.checks.all","All"),c.addEventListener("click",()=>{this.checksSource="",this.render()}),o.appendChild(c);for(let p of i){let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn"+(this.checksSource===p?" active":""),u.textContent=s(p)+(r(p)?" · judged":""),u.addEventListener("click",()=>{this.checksSource=this.checksSource===p?"":p,this.render()}),o.appendChild(u)}let a=document.createElement("span");a.className="bp-mgmt-flex1";let d=document.createElement("button");if(d.type="button",d.className="bp-mgmt-btn",d.textContent=v("gpui.mgmt.checks.run","Run"),d.addEventListener("click",()=>{let p=this.watchGen,u=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:u}).then(()=>{if(p!==this.watchGen||u!==this.project)return;this.checksStatus="",this.render()}).catch((y)=>{if(p!==this.watchGen||u!==this.project)return;this.checksStatus=y instanceof Error?y.message:"Could not run checks",this.render()})}),o.append(a,d),e.appendChild(o),this.checksStatus){let p=document.createElement("div");p.className="bp-mgmt-note bp-dim",p.textContent=this.checksStatus,e.appendChild(p)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let h=yn(n,this.checksSource);if(h.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let p of h){let u=p.severity==="error"?"bad":p.severity==="warning"?"warn":"faint",y=document.createElement("div");y.className="bp-mgmt-group-head";let E=document.createElement("span");E.className=`bp-mgmt-dot bp-tone-bg-${u}`;let g=document.createElement("span");g.className="bp-mgmt-flex1",g.textContent=`${s(p.source)} · ${p.rule}`;let f=document.createElement("span");f.className=`bp-tone-${u}`,f.textContent=String(p.n),y.append(E,g,f),l.appendChild(y);for(let w of p.rows??[]){let x=document.createElement("div");x.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let S=document.createElement("div");if(S.textContent=ke(w.title??""),x.appendChild(S),w.names||this.checksSelectedId===w.id){let L=document.createElement("div");L.className="bp-mgmt-row-sub";let T=document.createElement("span");if(T.className="bp-dim bp-mgmt-flex1",T.textContent=w.names??"",L.appendChild(T),this.checksSelectedId===w.id){let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn accent",N.textContent=v("gpui.mgmt.checks.fix","Fix with agent"),N.addEventListener("click",(F)=>{F.stopPropagation();let U={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:U.project,id:w.id}).then((G)=>{let I={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Ht(U,I))return;if(G.text)this.cb.onSendText(G.text),this.checksStatus="Sent to agent",this.render()}).catch((G)=>{let I={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Ht(U,I))return;this.checksStatus=G instanceof Error?G.message:"Could not send finding",this.render()})}),L.appendChild(N)}x.appendChild(L)}x.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(x)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let a of["active","nrnd","eol"]){let d=i[a]??0,l=jt(a),h=document.createElement("span");h.className=d>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",h.textContent=`${l.label} ${d}`,n.appendChild(h)}if((i.unknown??0)>0){let a=document.createElement("span");a.className="bp-mgmt-faint",a.textContent=`${i.unknown} unknown`,n.appendChild(a)}if(t.since){let a=document.createElement("span");a.className="bp-mgmt-flex1";let d=document.createElement("span");d.className="bp-mgmt-faint",d.textContent=`since ${Et(t.since)} (${t.samples??0})`,n.append(a,d)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],o=t.bom?.instock??[],c=t.bom?.lines??0;if(r.length===0)s.appendChild(this.makeEmpty(c===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let a=r[r.length-1],d=o[o.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${nt(a[1])} · ${Math.round(d?.[1]??0)}/${c} lines in stock (${Et(a[0])})`,s.appendChild(l)}for(let a of t.parts??[]){let d=this.lifeSelectedKey===a.key,l=jt(a.lifecycle??"unknown"),h=document.createElement("div");h.className="bp-mgmt-row"+(d?" active":"");let p=document.createElement("div");p.className="bp-mgmt-row-line";let u=document.createElement("span");u.className="bp-mgmt-strong",u.textContent=yt(a.refs??[],14);let y=document.createElement("span");y.className="bp-mgmt-flex1 bp-dim",y.textContent=a.mpn||a.key;let E=document.createElement("span");if(E.className=`bp-tone-${l.tone}`,E.textContent=l.label,p.append(u,y,E),typeof a.stock==="number"){let g=document.createElement("span");g.className="bp-dim",g.textContent=tt(a.stock),p.appendChild(g)}if(h.appendChild(p),d){let g=document.createElement("div");if(g.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)g.textContent=v("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let f=this.lifePartSamples[this.lifePartSamples.length-1];g.textContent=`${this.lifePartSamples.length} samples · latest ${f.at?Et(f.at):""}`+(typeof f.stock==="number"?` · stock ${tt(f.stock)}`:"")+(typeof f.price==="number"?` · ${nt(f.price)}`:"")}else g.textContent=v("gpui.mgmt.life.nopart","No reading of this part yet.");h.appendChild(g)}h.addEventListener("click",()=>{if(this.lifeSelectedKey===a.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=a.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:a.key}).then((g)=>{if(this.lifeSelectedKey!==a.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(g.samples)?g.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==a.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(h)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty("Reading the routing plan…")),e;let n=(a,d)=>{let l=this.watchGen,h=this.project;this.planStatus="",this.cb.hub.rpc(a,{pro:h,...d}).catch((p)=>{if(l!==this.watchGen||h!==this.project)return;this.planStatus=p instanceof Error?p.message:"Plan action refused",this.render()})};if(t.empty)return e.appendChild(this.makeEmpty("No routing plan for this board.")),e;let i=document.createElement("div");i.className="bp-mgmt-head";let s=t.awaiting??0,r=document.createElement("span");if(r.className="bp-mgmt-flex1 "+(s>0?"bp-tone-warn":"bp-dim"),r.textContent=s>0?`${s} awaiting approval`:"Nothing awaits your approval",i.appendChild(r),!t.live){let a=document.createElement("span");a.className="bp-mgmt-faint",a.textContent=v("gpui.mgmt.plan.saved","saved plan"),i.appendChild(a)}if(s>0){let a=document.createElement("button");a.type="button",a.className="bp-mgmt-btn",a.textContent=v("gpui.mgmt.plan.all","Approve all"),a.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),i.appendChild(a)}if(t.routing){let a=document.createElement("button");a.type="button",a.className="bp-mgmt-btn",a.textContent=v("gpui.mgmt.plan.stop","Stop routing"),a.addEventListener("click",()=>n("plan.stop",{})),i.appendChild(a)}let o=document.createElement("button");if(o.type="button",o.className="bp-mgmt-btn",o.textContent=this.planHideDone?"Show done":"Hide done",o.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),i.appendChild(o),e.appendChild(i),this.planStatus){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.planStatus,e.appendChild(a)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-plan-rows");for(let a of t.layers??[]){let d=a.items??[],l=document.createElement("div");l.className="bp-mgmt-group-head";let h=document.createElement("span");h.className="bp-mgmt-strong",h.textContent=a.layer;let p=document.createElement("span");if(p.className="bp-dim bp-mgmt-flex1",p.textContent=`${a.role?`${a.role} · `:""}${a.done??0}/${d.length} done`,l.append(h,p),a.status!=="approved"&&d.length>0){let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn",u.textContent=v("gpui.mgmt.plan.layer","Approve layer"),u.addEventListener("click",()=>n("plan.approve",{layer:a.layer,ids:[],approve:!0}));let y=document.createElement("button");y.type="button",y.className="bp-mgmt-btn",y.textContent=v("gpui.mgmt.plan.reject","Reject"),y.addEventListener("click",()=>n("plan.approve",{layer:a.layer,ids:[],approve:!1})),l.append(u,y)}c.appendChild(l);for(let u of d){if(this.planHideDone&&En(u))continue;let y=document.createElement("div");y.className="bp-mgmt-row";let E=document.createElement("div");E.className="bp-mgmt-row-line";let g=document.createElement("span");g.className="bp-mgmt-flex1"+(u.state==="blocked"?" bp-tone-bad":u.state==="edited"?" bp-tone-warn":""),g.textContent=`${u.name||u.id}${u.locked?" \uD83D\uDD12":""}`;let f=document.createElement("span");f.className="bp-dim",f.textContent=u.kind==="plane"?u.reference?`ref ${u.reference}`:"":`${u.nets??0} nets`;let w=document.createElement("span");if(w.className=u.state==="blocked"?"bp-tone-bad":"bp-dim",w.textContent=xn(u),E.append(g,f,w),u.state==="proposed"||u.state==="edited"){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.textContent="✓",x.addEventListener("click",(L)=>{L.stopPropagation(),n("plan.approve",{layer:"",ids:[u.id],approve:!0})});let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.textContent="✗",S.addEventListener("click",(L)=>{L.stopPropagation(),n("plan.approve",{layer:"",ids:[u.id],approve:!1})}),E.append(x,S)}y.appendChild(E),y.addEventListener("click",()=>n("plan.focus",{id:u.id})),c.appendChild(y)}}return e.appendChild(c),e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,x={})=>{let S=this.watchGen,L=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:L,action:w,...x}).catch((T)=>{if(S!==this.watchGen||L!==this.project)return;this.fabStatus=T instanceof Error?T.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=v("gpui.mgmt.fab.thefab","The fab");let r=document.createElement("span");r.className="bp-dim bp-mgmt-flex1",r.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${kn(t.tier??"")}`;let o=document.createElement("button");if(o.type="button",o.className="bp-mgmt-btn",o.textContent=v("gpui.mgmt.fab.refresh","Refresh"),o.addEventListener("click",()=>n("refresh")),i.append(s,r,o),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-fab-rows");let a=t.review,d=document.createElement("div");d.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let h=document.createElement("span"),p=(a?.counts?.error??0)>0;if(h.className="bp-mgmt-flex1 "+(p?"bp-tone-bad":"bp-dim"),h.textContent=a?.running?"Reviewing the design…":a?.at==null?"No design review yet":`${a.counts?.error??0} must-fix · ${a.counts?.warning??0} should-fix · ${a.counts?.info??0} notes${a.scope?` (${a.scope})`:""}`,l.appendChild(h),a?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=v("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!a?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=v("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(a?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=v("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(a.judge)this.cb.onSendText(a.judge)}),l.appendChild(w)}d.appendChild(l),c.appendChild(d);let u=Cn(t.drc?.state??""),y=document.createElement("div");y.className="bp-mgmt-row";let E=document.createElement("div");E.className="bp-mgmt-row-line";let g=document.createElement("span");if(g.className="bp-mgmt-flex1 "+(u.button?"bp-tone-warn":"bp-dim"),g.textContent=u.text,E.appendChild(g),u.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=u.button,w.addEventListener("click",()=>n("drc")),E.appendChild(w)}y.appendChild(E),c.appendChild(y);for(let w of t.conflicts??[]){let x=document.createElement("div");x.className="bp-mgmt-row bp-tone-bad",x.textContent=w,c.appendChild(x)}for(let w of t.suggestions??[]){let x=document.createElement("div");x.className="bp-mgmt-row";let S=document.createElement("div");S.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let T=document.createElement("button");T.type="button",T.className="bp-mgmt-btn",T.textContent=v("gpui.mgmt.fab.apply","Apply"),T.addEventListener("click",()=>n("apply",{key:w.key})),S.append(L,T),x.appendChild(S),c.appendChild(x)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let S=t.stackup.by==="proposed",L=document.createElement("span");if(L.className="bp-mgmt-flex1 "+(S?"bp-tone-warn":"bp-dim"),L.textContent=`${S?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(L),S){let T=t.stackup.chosen,N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=v("gpui.mgmt.fab.use","Use"),N.addEventListener("click",()=>n("stackup",{id:T})),x.appendChild(N)}w.appendChild(x),c.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let S=document.createElement("span");S.className="bp-mgmt-flex1 bp-tone-warn",S.textContent=v("gpui.mgmt.fab.changed","Changed since you last looked");let L=document.createElement("button");L.type="button",L.className="bp-mgmt-btn",L.textContent=v("gpui.mgmt.fab.seen","Seen"),L.addEventListener("click",()=>n("seen")),x.append(S,L),w.appendChild(x);for(let T of t.changed.slice(0,12)){let N=document.createElement("div");N.className="bp-mgmt-faint",N.textContent=T,w.appendChild(N)}c.appendChild(w)}let f=Array.isArray(t.limits)?t.limits:[];if(f.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=v("gpui.mgmt.fab.limit","Limit");let S=document.createElement("span");S.className="bp-mgmt-col",S.textContent=v("gpui.mgmt.fab.free","Base price");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=v("gpui.mgmt.fab.extra","Costs more");let T=document.createElement("span");T.className="bp-mgmt-col bp-mgmt-col-read",T.textContent=v("gpui.mgmt.fab.readcol","Read"),w.append(x,S,L,T),c.appendChild(w);for(let F of f){let U=document.createElement("div");U.className="bp-mgmt-row";let G=document.createElement("div");G.className="bp-mgmt-row-line";let I=document.createElement("span");I.className="bp-mgmt-flex1"+(F.changed?" bp-tone-warn":F.inherited?" bp-dim":""),I.textContent=`${F.changed?"• ":""}${F.label??""}`;let we=document.createElement("span");we.className="bp-mgmt-col",we.textContent=F.free?.text||"—";let X=document.createElement("span");X.className="bp-mgmt-col bp-dim",X.textContent=F.extra?.text||"—";let re=F.free&&typeof F.free==="object"?F.free:F.extra,ne=re?.fetched??"",Se=Boolean(ne)&&re?.confidence!=="published",ge=ne?Se?`${ne}*`:ne:"—",he=re?.source??"",P;if(he.startsWith("https://")&&ne){let Q=document.createElement("a");Q.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",Q.href=he,Q.target="_blank",Q.rel="noopener noreferrer",Q.textContent=ge,P=Q}else{let Q=document.createElement("span");Q.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",Q.textContent=ge,P=Q}G.append(I,we,X,P),U.appendChild(G),c.appendChild(U)}let N=document.createElement("div");N.className="bp-mgmt-note bp-mgmt-faint",N.textContent=v("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),c.appendChild(N)}return e.appendChild(c),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var Li={trs:(e)=>e,t:(e,t)=>t},Ni=new Set(["/settle"]);function An(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((o)=>o.startsWith(n)))return 2;let r=0;for(let o=0;o0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function Nn(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Tn(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function Pn(e,t=Li){let{t:n,trs:i}=t,s=[],r=new Map;for(let c of e.projects)r.set(c.id,c.title||c.id);let o=e.threads.find((c)=>c.id===e.selectedThreadId)??null;for(let c of e.railItems){if(c.state==="disabled"||c.id==="commands")continue;if(!o&&c.id!=="terminal")continue;s.push({label:i(c.label),place:c.id==="terminal"?"":"viewer",kind:"action",shortcut:c.key?c.key.toUpperCase():void 0,action:{type:"rail",id:c.id}})}if(o)s.push({label:o.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:o.pinned?"unpin":"pin"}}),s.push({label:o.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:o.settled?"unsettle":"settle"}}),s.push({label:o.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:o.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(o)for(let c of e.commands){if(!c.word)continue;let a=Ni.has(c.word.toLowerCase());s.push({label:c.label?`${c.word} — ${c.label}`:c.word,place:c.desc||"command",kind:"command",action:{type:"command",word:c.word,runDirectly:a}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let c of e.projects)s.push({label:`New thread in ${c.title||c.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:c.id}});for(let c of e.threads){let{urgency:a,want:d}=Ln(c);s.push({label:c.title||"Untitled thread",place:c.project?r.get(c.project)??"":"",kind:"thread",urgency:a,want:d,dotClass:Nn(c),action:{type:"thread",id:c.id}})}for(let c of e.bots){if(!c.name||!c.thread)continue;s.push({label:c.name,place:"",kind:"bot",action:{type:"thread",id:c.thread}})}return s}function Mn(e,t,n,i=[],s=10,r=14){let o=t.trim(),c=o.length===0,a=e.slice();if(n?.threads&&n.threads.length>0){let p=new Map;for(let y of i)p.set(y.id,y.title||y.id);let u=new Set;for(let y of a)if(y.action.type==="thread")u.add(y.action.id);for(let y of n.threads){if(!y.id||u.has(y.id))continue;u.add(y.id);let{urgency:E,want:g}=Ln(y);a.push({label:y.title||"Untitled thread",place:y.project?p.get(y.project)??"":"",kind:"thread",urgency:E,want:g,dotClass:Nn(y),action:{type:"thread",id:y.id}})}}let d=[];for(let p=0;p0)d.push({score:g,index:p,item:u})}d.sort((p,u)=>{if(c){let g=(u.item.urgency??0)-(p.item.urgency??0);if(g!==0)return g}if(u.score!==p.score)return u.score-p.score;let y=p.item.kind==="thread"?0:1,E=u.item.kind==="thread"?0:1;if(y!==E)return y-E;return p.index-u.index});let l=new Set,h=[];for(let p of d){let u=`${p.item.label}\x00${p.item.place}\x00${p.item.kind}`;if(l.has(u))continue;if(l.add(u),h.push(p.item),h.length>=s)break}if(n?.messages&&n.messages.length>0&&h.length{if(o.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(o)=>{if(o.key==="Escape")o.preventDefault(),o.stopPropagation(),this.close();else if(o.key==="ArrowDown"){if(o.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(o.key==="ArrowUp"){if(o.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(o.key==="Enter")o.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=r,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=Pn(t,{t:v,trs:ke}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Mn(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let o=document.createElement("div");o.className="bp-palette-empty",o.textContent=v("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(o);return}let s=document.createDocumentFragment(),r=null;for(let o=0;o0)d.appendChild(document.createTextNode(c.label.slice(0,p)));let y=document.createElement("strong");if(y.className="bp-palette-mark",y.textContent=c.label.slice(p,u),d.appendChild(y),u{if(this.activeIdx!==o)this.activeIdx=o,this.updateActiveClass()}),a.addEventListener("click",()=>this.runAt(o)),o===this.activeIdx)r=a;s.appendChild(a)}if(this.listEl.replaceChildren(s),e&&r)r.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return r}render(){let e=this.items.filter((o)=>o.group!=="tools"),t=this.items.filter((o)=>o.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let o of e){if(i!==void 0&&o.group!==i){let c=document.createElement("div");c.className="bp-rail-rule",n.appendChild(c)}i=o.group,n.appendChild(this.renderButton(o))}let s=()=>{let o=n.scrollLeft>2,c=n.scrollLeft+n.clientWidth0){let o=document.createElement("div");o.className="bp-rail-tools";for(let c of t)o.appendChild(this.renderButton(c));r.appendChild(o)}this.el.replaceChildren(r)}}var Pi=new Set(["resume","raise","retry","move","signin"]);function Rn(e){if(!e||typeof e!=="object")return null;let t=e,n=(r)=>typeof r==="string"?r:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((r)=>Boolean(r)&&typeof r==="object").map((r)=>({label:n(r.label),act:n(r.act),room:n(r.room),thread:n(r.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function xt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(Pi.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function jn(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class Gt{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${v("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",v("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${v("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",v("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let d=document.createElement("section");d.className="bp-set-section",d.setAttribute("data-testid","settings-home");let l=document.createElement("div");l.className="bp-set-head",l.textContent=v("home.machine","Home machine");let h=document.createElement("div");h.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let u=document.createElement("div"),y=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";u.textContent=y,p.appendChild(u);let E=document.createElement("div");if(E.className="bp-dim",t.moving?.state==="moving")E.textContent=t.moving.step?v("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):v("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")E.textContent=t.moving.note?v("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):v("home.move.failed","Home move failed");else if(!t.online)E.textContent=t.queuedCount>0?v("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):v("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else E.textContent="Online";if(p.appendChild(E),h.appendChild(p),t.canMoveHere&&this.cb.onMoveHomeHere){let g=document.createElement("button");g.type="button",g.className="primary",g.textContent=v("home.move.here","Make this machine the home"),g.setAttribute("data-testid","home-move-here-btn"),g.addEventListener("click",()=>{g.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),h.appendChild(g)}d.append(l,h),e.appendChild(d)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let r=document.createElement("span");r.className="bp-dim",r.textContent="Sign out and revoke this browser's session cookie.";let o=document.createElement("button");o.type="button",o.className="primary stop",o.textContent=v("agy.signout","Sign out"),o.setAttribute("data-testid","logout-btn"),o.addEventListener("click",()=>{o.disabled=!0,this.cb.onLogout().catch(()=>{r.setAttribute("role","alert"),r.textContent=v("web.logout.failed","Could not confirm sign-out. Try again."),o.disabled=!1})}),s.append(r,o),n.append(i,s),e.appendChild(n);let c=document.createElement("section");c.className="bp-set-section";let a=document.createElement("div");a.className="bp-set-head",a.textContent="Paired devices",c.appendChild(a);try{let d=await this.cb.onLoadDevices();if(d.length===0){let l=document.createElement("div");l.className="bp-dim",l.textContent="No devices listed.",c.appendChild(l)}else for(let l of d){let h=document.createElement("div");h.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let u=document.createElement("div");if(u.textContent=l.title||l.head||"",p.appendChild(u),l.text||l.detail){let y=document.createElement("div");y.className="bp-dim",y.textContent=l.text||l.detail||"",p.appendChild(y)}if(h.appendChild(p),l.buttons?.length){let y=document.createElement("div");y.className="bp-set-btns";for(let E of l.buttons){let g=document.createElement("button");if(g.type="button",E.primary)g.className="primary";if(E.danger)g.className="primary stop";g.textContent=E.label||v("common.remove","Remove"),g.addEventListener("click",()=>{g.disabled=!0,this.cb.onDevicesAct(E.action,E.value).finally(()=>{this.refresh()})}),y.appendChild(g)}h.appendChild(y)}c.appendChild(h)}}catch(d){let l=document.createElement("div");l.className="bp-dim";let h=d instanceof Error&&d.message?d.message:"Not available from a browser";l.textContent=`${h} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,c.appendChild(l)}e.appendChild(c),this.bodyEl.replaceChildren(e)}}var Dn="http://www.w3.org/2000/svg";function Hn(){let e=document.createElementNS(Dn,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(Dn,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function Mi(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Fn(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class Ot{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let o=document.createElement("div");o.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let c=v("sidebar.search.projects","Search projects");this.filterInput.placeholder=c,this.filterInput.setAttribute("aria-label",c),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let a=document.createElement("button");a.type="button",a.className="icon bp-side-add",a.textContent="+",a.title=v("thread.new","New thread"),a.setAttribute("aria-label",v("thread.new","New thread")),a.setAttribute("data-testid","sidebar-new-thread"),a.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),o.append(this.filterInput,a),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let d=document.createElement("div");d.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),d.appendChild(this.connEl),this.el.append(n,o,this.homeBanner,this.listEl,d)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?v("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):v("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?v("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):v("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=v("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=v("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=v("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=v("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=v("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=v("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let h=document.createElement("span");h.className="bp-tree-branch",h.setAttribute("aria-hidden","true"),n.appendChild(h)}let i=document.createElement("span");i.className=`bp-dot ${Mi(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let h=document.createElement("span");if(h.className="bp-badge-need",h.textContent=e.want==="approval"?"!":"•",e.say)h.title=e.say;n.appendChild(h)}else if(e.ago){let h=document.createElement("span");if(h.className="bp-thread-age",h.textContent=e.ago,e.pinned)h.title=v("tools.pinned","Pinned");n.appendChild(h)}let r=e.nav||e.id;if(!e.off&&r&&!r.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(r));let o=e.kind==="swarm"?Rn(e.need):null;if(!o)return n;let c=document.createElement("div");c.className="bp-need-wrap";let a=document.createElement("div");a.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),a.setAttribute("data-testid",`need-${e.id}`);let d=document.createElement("span");d.className="bp-need-line",d.textContent=o.line,d.title=o.line,a.appendChild(d);for(let h of o.actions){if(!xt(h,Boolean(this.cb.hasRoomView)))continue;let p=document.createElement("button");p.type="button",p.className="bp-need-btn",p.textContent=h.label,p.setAttribute("data-testid",`need-${h.act}-${e.id}`),p.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,p.addEventListener("click",(u)=>{u.stopPropagation();let y=this.cb.onNeedAct;if(!y)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),y(h).catch((E)=>{this.needErr.set(e.id,E instanceof Error?E.message:String(E))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),a.appendChild(p)}c.append(n,a);let l=this.needErr.get(e.id);if(l){let h=document.createElement("div");h.className="bp-need-err"+(t?" nested":""),h.textContent=l,c.appendChild(h)}return c}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let o of n)if(o.kind==="threads")for(let c of o.rows)i.add(c.id);else if(o.kind==="projects")for(let c of o.rows)for(let a of c.threads??[])i.add(a.id);let s=this.selectedThreadId?this.threads.find((o)=>o.id===this.selectedThreadId)??null:null,r=!1;for(let o of n)if(o.kind==="projects"&&o.rows.length>0)r=!0;for(let o of n){if(o.kind==="bub")continue;if(o.kind==="threads"){let c=o.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(c.length===0)continue;let a=document.createElement("section");a.className="bp-side-section",a.setAttribute("data-section-id",o.id);let d=document.createElement("div");d.className="bp-side-section-head",d.textContent=o.title.toUpperCase(),a.appendChild(d);for(let l of c)a.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(a);continue}if(o.kind==="projects"){let c=o.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;return!1}),a=Boolean(o.fold&&o.toggle);if(t&&c.length===0)continue;if(!a&&o.id!=="active"&&c.length===0)continue;let d=document.createElement("section");if(d.className="bp-side-section",d.setAttribute("data-section-id",o.id),a){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let h=o.count??c.length,p=o.open?"▾":"▸";if(l.textContent=`${o.title.toUpperCase()} (${h}) ${p}`,o.hint)l.title=o.hint;l.addEventListener("click",()=>{if(o.toggle)this.cb.onToggleSection?.(o.toggle)}),d.appendChild(l)}else d.appendChild(this.projectsHead(o.title.toUpperCase()));if(!a||o.open||Boolean(t)){if(o.id==="active"&&!r&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",d.appendChild(l)}for(let l of c){let h=document.createElement("div");if(h.className="bp-proj-group"+(l.off?" bp-dim":""),h.setAttribute("data-project-id",l.id),l.nav||l.key)h.setAttribute("data-project-key",l.nav||l.key||"");let p=document.createElement("div");p.className="bp-proj-head";let u=document.createElement("button");u.type="button",u.className="bp-proj-toggle";let y=Hn();if(l.css)y.style.color=l.css;let E=document.createElement("span");if(E.className="bp-proj-name",E.textContent=l.title||l.id,u.append(y,E),l.fold==="project-fold"&&l.nav)u.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let g=document.createElement("button");if(g.type="button",g.className="icon bp-proj-add",g.title=v("thread.new","New thread"),g.textContent="+",g.setAttribute("data-testid",`new-thread-${l.id}`),l.off)g.disabled=!0;if(g.addEventListener("click",(f)=>{f.stopPropagation(),this.cb.onNewThread(l.id)}),p.append(u,g),h.appendChild(p),!l.folded||Boolean(t)){let f=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!f&&!w.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||f||s.title.toLowerCase().includes(t)))h.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Fn(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}d.appendChild(h)}}e.appendChild(d)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let o=document.createElement("div");o.className="bp-proj-head";let c=document.createElement("button");c.type="button",c.className="bp-proj-toggle";let a=this.collapsedProjects.has(i.id)&&!t,d=Hn();if(i.css)d.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,c.append(d,l),c.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=v("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${i.id}`),h.addEventListener("click",(p)=>{p.stopPropagation(),this.cb.onNewThread(i.id)}),o.append(c,h),r.appendChild(o),!a)for(let p of s)r.appendChild(this.renderSectionThreadRow({id:p.id,title:p.title,status:p.status,state:p.state,ago:Fn(p.updatedAt),pinned:p.pinned,nav:p.id},!0));e.appendChild(r)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=v("tour.title.bots","Bots").toUpperCase();let r=document.createElement("span");r.className="bp-side-sec-plus",r.textContent="+",r.setAttribute("aria-hidden","true"),i.append(s,r),n.appendChild(i);for(let l of this.bots){let h=document.createElement("div");h.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let p=document.createElement("span");if(p.className="bp-dot bp-dot-idle",l.color)p.style.backgroundColor=l.color;let u=document.createElement("div");u.className="bp-thread-title",u.textContent=`@${l.name}`,h.append(p,u),h.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(h)}e.appendChild(n);let o=document.createElement("section");o.className="bp-proj-group";let c=document.createElement("div");c.className="bp-side-section-head bp-side-section-row";let a=document.createElement("span");a.textContent=v("bots.rooms","Rooms").toUpperCase();let d=document.createElement("span");d.className="bp-side-sec-plus",d.textContent="+",d.setAttribute("aria-hidden","true"),c.append(a,d),o.appendChild(c);for(let l of this.rooms){let h=document.createElement("div");h.className="bp-thread-row";let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`#${l.name}`,h.appendChild(p),o.appendChild(h)}e.appendChild(o)}this.listEl.replaceChildren(e)}}function Bi(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function pt(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Ii(e,t){if(t===16000){let r=new Int16Array(e.length);for(let o=0;o0?a/d:0));s[r]=l<0?l*32768:l*32767}return s}class Vt{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){pt(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(pt(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(pt(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?Bi(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(pt(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let r=this.stopDrain.then(async()=>{if(t&&i){let o=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(o.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=r,await r}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),r=String(e.ins??""),o=Math.max(0,Math.min(i.length,this.mark)),c=Math.max(0,o-s),a=i.slice(0,c)+r+i.slice(o);this.mark=c+r.length,this.cb.setDraft(a)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),r=i.createScriptProcessor(4096,1,1);r.onaudioprocess=(o)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let c=Ii(o.inputBuffer.getChannelData(0),i.sampleRate);for(let a=0;a=3200){let a=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(a.buffer),!1,t)}},s.connect(r),r.connect(i.destination),this.audioCtx=i,this.processor=r}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let r=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!r.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${r.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;pt(this.stream),this.stream=null}}var $n=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],Un=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Gn=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],On=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Ri=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function ht(e,t){let n=new Int32Array(16),i=0;for(let c=0;c0){if(n[a]++,a>i)i=a}}let s=new Int32Array(16),r=0;for(let c=1;c<=15;c++)s[c]=r,r+=n[c];let o=new Int32Array(r);for(let c=0;c0)o[s[a]++]=c}return{counts:n,symbols:o,maxBits:i}}var ji=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),ht(e,288)})(),Di=(()=>{let e=new Uint8Array(32);return e.fill(5),ht(e,32)})();class Wt{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(h)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=h,s-=h,p},o=(h)=>{let p=0,u=0,y=0;for(let E=1;E<=h.maxBits;E++){p|=r(1);let g=h.counts[E];if(p-g{let p=a+h;if(p>t)throw Error("inflated frame exceeds limit");if(p<=c.length)return;let u=c.length;while(u{d(1),c[a++]=h,this.win[this.winPos]=h,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let h=r(1),p=r(2);if(p===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let u=e[n]|e[n+1]<<8,y=e[n+2]|e[n+3]<<8;if(n+=4,(u^65535)!==y)throw Error("invalid stored block length");if(n+u>e.length)throw Error("truncated stored payload");d(u);for(let E=0;E=e.length)break}else if(p===1||p===2){let u=ji,y=Di;if(p===2){let E=r(5)+257,g=r(5)+1,f=r(4)+4,w=new Uint8Array(19);for(let N=0;NS)throw Error("code length overflow");for(let G=0;GS)throw Error("code length overflow");T+=F}else if(N===18){let F=r(7)+11;if(T+F>S)throw Error("code length overflow");T+=F}else throw Error("invalid code length symbol")}u=ht(L,E),y=ht(L.subarray(E),g)}while(!0){let E=o(u);if(E<256)l(E);else if(E===256)break;else{let g=E-257;if(g>=$n.length)throw Error("invalid length symbol");let f=$n[g]+(Un[g]?r(Un[g]):0),w=o(y);if(w>=Gn.length)throw Error("invalid distance symbol");let x=Gn[w]+(On[w]?r(On[w]):0);d(f);let S=this.winPos-x&32767;for(let L=0;L{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,o=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:o}),this.ws.send(JSON.stringify({id:r,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new Wt:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let o=this.pending.get(r.id);if(o)if(this.pending.delete(r.id),window.clearTimeout(o.timer),r.ok)o.resolve(r.result??{});else{let c=r.error,a=typeof c==="string"?c:c&&typeof c==="object"&&("message"in c)?String(c.message):"Request failed";o.reject(Error(a))}return}for(let o of this.frameListeners)o(r)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let r;try{r=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(r.length>0&&r[0]===123)i(this.textDecoder.decode(r));else{let o=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let c of this.binaryListeners)c(o)}return}for(let r of this.binaryListeners)r(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Hi=new TextDecoder;function Vn(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Wn(e){let t=0,n=0;function i(o){if(o<=23)return o;if(o===24){if(t>=e.length)return null;return e[t++]}if(o===25){if(t+2>e.length)return null;let c=e[t]<<8|e[t+1];return t+=2,c}if(o===26){if(t+4>e.length)return null;let c=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,c}return null}function s(o){if(n++,o>32||n>400000||t>=e.length)return null;let c=e[t++],a=c>>5,d=i(c&31);if(d===null)return null;switch(a){case 0:return d;case 1:return-1-d;case 2:{if(t+d>e.length)return null;let l=e.subarray(t,t+d);return t+=d,l}case 3:{if(t+d>e.length)return null;let l=Hi.decode(e.subarray(t,t+d));return t+=d,l}case 4:{if(d>e.length)return null;let l=Array(d);for(let h=0;h=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function qn(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[E]==="number"?e[E]:g,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),o=t("w",0),c=o/2,a=r===0&&o!==0,d=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new _n(d),h=[],p=[],u=0,y=0;while(l.more()){let E=l.nextU32(),g=h.length,f=1/0,w=1/0,x=-1/0,S=-1/0;if(r===2)u=u+l.nextI32()|0,y=y+l.nextI32()|0,h.push(u,y),f=x=u,w=S=y;else{let T=Math.min(l.nextU32(),1048576);for(let N=0;Nx)x=u;if(yS)S=y}}let L=(h.length-g)/2;if(L>0){let T=r===2||L===1?2:r===0?0:1,N=r===0?0:c;p.push({info:E,x0:f-N,y0:w-N,x1:x+N,y1:S+N,at:g,n:L,kind:T})}}return{layer:n,color:i,alpha:s,mode:r,r:c,own:a,pts:new Float32Array(h),pieces:p}}function zn(e,t,n){let i=(o)=>Array.isArray(o)&&o.length>=4?[Number(o[0])||0,Number(o[1])||0,Number(o[2])||0,Number(o[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let o=0;o=0&&c0){n.delete(c.h),n.set(c.h,a);while(n.size>1024){let d=n.keys().next().value;if(d!==void 0)n.delete(d);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function Kn(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),r=n.naturalWidth*s,o=n.naturalHeight*s,c=n.left+(n.width-r)/2,a=i?n.top:n.top+(n.height-o)/2,d=(e-c)/r,l=(t-a)/o;if(d<0||d>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(d*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var Jn=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function Yn(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class qt{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function Xn(e,t,n){let i=!0,s=!1,r=!1,o="",c=!1,a=!1,d=-1,l=null,h=new qt,p=document.createElement("div");p.className="bp-pane bp-browser-pane",p.setAttribute("data-testid","pane-browser");let u=document.createElement("div");u.className="bp-pane-bar bp-browser-nav";function y(q,z,A){let te=document.createElement("button");if(te.type="button",te.className="bp-v-btn",te.textContent=q,te.setAttribute("data-testid",z),A)te.title=A;return te}let E=y("←","browser-back","Back"),g=y("→","browser-forward","Forward"),f=y("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let x=document.createElement("input");x.type="text",x.className="bp-browser-input",x.placeholder="https://…",x.autocomplete="off",x.spellcheck=!1,x.setAttribute("data-testid","browser-url");let S=y("Go","browser-go","Navigate");S.type="submit",w.append(x,S);let L=y("Take over","browser-takeover");L.classList.add("is-primary"),u.append(E,g,f,w,L);let T=document.createElement("div");T.className="bp-browser-drive-bar",T.hidden=!0;let N=document.createElement("div");N.className="bp-browser-keys-row";let F=document.createElement("input");F.type="text",F.className="bp-browser-input",F.placeholder="Type text or press Enter/Tab/Arrows…",F.autocomplete="off",F.spellcheck=!1,F.setAttribute("data-testid","browser-keys");let U=y("Send","browser-type-send");N.append(F,U);let G=document.createElement("div");G.className="bp-browser-quick-keys";for(let[q,z]of Jn){let A=y(q,`browser-key-${z}`);A.addEventListener("click",()=>he("press",{key:z})),G.append(A)}T.append(N,G);let I=document.createElement("div");I.className="bp-browser-err",I.setAttribute("data-testid","browser-error"),I.hidden=!0;let we=document.createElement("div");we.className="bp-browser-stage",we.setAttribute("data-testid","browser-stage");let X=document.createElement("img");X.className="bp-browser-img",X.alt="Hub browser screen",X.draggable=!1,X.hidden=!0,X.setAttribute("data-testid","browser-frame");let re=document.createElement("div");re.className="bp-pane-empty",re.setAttribute("data-testid","browser-empty"),re.textContent="Loading browser screen…",we.append(X,re);let ne=document.createElement("div");ne.className="bp-browser-hint",ne.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ne.hidden=!0,p.append(u,T,I,we,ne),e.replaceChildren(p);function Se(q){I.textContent=q,I.hidden=!q}function ge(){T.hidden=!s,ne.hidden=!s,L.textContent=s?"Hand back":"Take over",L.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),L.classList.toggle("is-on",s),X.classList.toggle("is-driving",s)}function he(q,z={},A){h.enqueue(async()=>{if(!i)return;Se("");try{if(await t.hub.rpc("browser",{thread:n,op:q,...z}),!i)return;A?.(),le()}catch(te){if(!i)return;Se(te instanceof Error?te.message:String(te))}})}function P(q){he("toolbar",{command:q},()=>{s=!0,ge()})}E.addEventListener("click",()=>P("back")),g.addEventListener("click",()=>P("forward")),f.addEventListener("click",()=>P("reload")),w.addEventListener("submit",(q)=>{q.preventDefault();let z=Yn(x.value);if(!z)return;if(x.value=z,!s)he("takeover",{},()=>{s=!0,ge()});he("navigate",{url:z},()=>{s=!0,ge()})}),L.addEventListener("click",()=>{if(s)he("handback",{},()=>{s=!1,ge()});else he("takeover",{},()=>{s=!0,ge(),F.focus()})});function Q(){let q=F.value;if(!q)return;F.value="",he("type",{text:q})}U.addEventListener("click",Q),F.addEventListener("keydown",(q)=>{if(!s)return;if(q.key==="Enter"){if(q.preventDefault(),F.value)Q();he("press",{key:"Enter"});return}if(q.key==="Tab"||q.key==="Escape"||q.key==="ArrowUp"||q.key==="ArrowDown"||q.key==="ArrowLeft"||q.key==="ArrowRight"||q.key==="Backspace"&&F.value==="")q.preventDefault(),he("press",{key:q.key})}),X.addEventListener("click",(q)=>{if(!s||!r)return;let z=X.getBoundingClientRect(),A=Kn(q.clientX,q.clientY,{left:z.left,top:z.top,width:z.width,height:z.height,naturalWidth:X.naturalWidth,naturalHeight:X.naturalHeight});if(!A)return;he("click",A)}),X.addEventListener("wheel",(q)=>{if(!s||!r)return;q.preventDefault();let z=Math.round(q.deltaX),A=Math.round(q.deltaY);if(z===0&&A===0)return;he("scroll",{dx:z,dy:A})},{passive:!1});async function le(){if(!i)return;if(c){a=!0;return}c=!0;try{do{a=!1,l=new AbortController;let q=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(q.ok){let z=await q.blob();if(!i)return;let A=URL.createObjectURL(z),te=o;if(o=A,X.src=A,X.hidden=!1,re.hidden=!0,r=!0,te)URL.revokeObjectURL(te)}else if(!r)X.hidden=!0,re.hidden=!1,re.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&a)}catch{if(!i)return;if(!r)X.hidden=!0,re.hidden=!1,re.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,c=!1}}let ie=t.hub.onFrame((q)=>{if(!i)return;if(q.t==="shot"&&q.bot===n){if(typeof q.n==="number"){if(q.n===d)return;d=q.n}le()}});return le(),{destroy(){if(i=!1,ie(),l?.abort(),o)URL.revokeObjectURL(o),o=""}}}function D(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function Ct(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function Zn(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function $i(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function Qn(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function Ui(e){let t=Zn(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function ei(e,t,n,i){let s=!0,r="",o="",c=D("div","bp-pane bp-files-pane");c.setAttribute("data-testid","pane-files");let a=D("div","bp-pane-bar"),d=D("div","bp-files-crumbs"),l=D("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void g(r)),a.append(d,l);let h=D("div","bp-files-split"),p=D("div","bp-files-list");p.setAttribute("data-testid","files-list");let u=D("div","bp-files-preview");u.setAttribute("data-testid","files-preview"),u.append(D("div","bp-pane-empty","Select a file to preview")),h.append(p,u),c.append(a,h),e.replaceChildren(c);function y(){d.replaceChildren();let f=D("button","bp-crumb-btn","project");if(f.type="button",f.addEventListener("click",()=>void g("")),d.append(f),!r)return;let w=r.split("/").filter(Boolean),x="";for(let S of w){x=x?`${x}/${S}`:S;let L=x;d.append(D("span","bp-vh-sep","/"));let T=D("button","bp-crumb-btn",S);T.type="button",T.addEventListener("click",()=>void g(L)),d.append(T)}}async function E(f,w,x){o=f,u.replaceChildren();let S=D("div","bp-files-prev-head");S.append(D("span","bp-files-prev-name",f));let L=D("div","bp-files-prev-acts"),T=Ui(w);if(T){let G=D("button","bp-v-btn is-primary",`Open in ${T}`);G.type="button",G.setAttribute("data-testid","files-open-viewer"),G.addEventListener("click",()=>i(T,f)),L.append(G)}let N=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(f)}`,F=D("a","bp-v-btn","Download");F.href=N,F.download=w,L.append(F),S.append(L),u.append(S);let U=Zn(w);if($i(U)){let G=D("div","bp-files-img-wrap"),I=document.createElement("img");I.className="bp-files-img",I.alt=w,I.src=N,G.append(I),u.append(G);return}if(x>524288&&!Qn(U)){u.append(D("div","bp-pane-empty",`Binary file (${Ct(x)}). Use Download to save.`));return}if(Qn(U)||x<=65536){let G=D("div","bp-pane-empty","Loading…");u.append(G);try{let I=await fetch(N,{credentials:"same-origin"});if(!s||o!==f)return;if(!I.ok){G.textContent=`Could not load file (${I.status})`;return}if((I.headers.get("content-type")||"").startsWith("image/")){G.remove();let ie=document.createElement("img");ie.className="bp-files-img",ie.alt=w,ie.src=N,u.append(ie);return}let X=262144,re=[],ne=0,Se=!1;if(I.body){let ie=I.body.getReader();try{while(!0){let{done:q,value:z}=await ie.read();if(q||!z)break;if(ne+z.byteLength>X){let A=X-ne;if(A>0)re.push(z.subarray(0,A)),ne+=A;Se=!0,await ie.cancel();break}re.push(z),ne+=z.byteLength}}finally{ie.releaseLock()}}if(!s||o!==f)return;let ge=new Uint8Array(ne),he=0;for(let ie of re)ge.set(ie,he),he+=ie.byteLength;let P=!1;for(let ie=0;ieS.dir===L.dir?S.name.localeCompare(L.name):S.dir?-1:1),p.replaceChildren(),f){let S=D("button","bp-file-row is-dir");S.type="button",S.append(D("span","bp-file-icon","↰"),D("span","bp-file-name",".."));let L=f.includes("/")?f.slice(0,f.lastIndexOf("/")):"";S.addEventListener("click",()=>void g(L)),p.append(S)}if(x.length===0){p.append(D("div","bp-pane-empty","Empty folder"));return}for(let S of x){let L=f?`${f}/${S.name}`:S.name,T=D("button","bp-file-row"+(S.dir?" is-dir":"")+(L===o?" is-sel":""));T.type="button",T.setAttribute("data-testid",`file-row-${S.name}`),T.append(D("span","bp-file-icon",S.dir?"▸":"·"),D("span","bp-file-name",S.name),D("span","bp-file-size",S.dir?"":Ct(S.size))),T.addEventListener("click",()=>{if(S.dir)g(L);else p.querySelectorAll(".bp-file-row.is-sel").forEach((N)=>N.classList.remove("is-sel")),T.classList.add("is-sel"),E(L,S.name,S.size)}),p.append(T)}}catch(w){if(!s)return;p.replaceChildren(D("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return g(""),{destroy(){s=!1}}}function ti(e,t,n){let i=!0,s=D("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=D("div","bp-pane-bar"),o=D("span","bp-diff-summary","Loading diff…"),c=D("button","bp-v-btn","Refresh");c.type="button",c.addEventListener("click",()=>void d()),r.append(o,c);let a=D("div","bp-diff-body");a.setAttribute("data-testid","diff-body"),s.append(r,a),e.replaceChildren(s);async function d(){o.textContent="Loading diff…",a.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){o.textContent="Not a git repository",a.append(D("div","bp-pane-empty","This project is not a git repository."));return}let h=typeof l?.diff==="string"?l.diff:"";if(!h.trim()){o.textContent="Clean working tree",a.append(D("div","bp-pane-empty","No uncommitted changes."));return}let p=h.split(` -`),u=0,y=0,E=0,g=document.createDocumentFragment(),f=D("div","bp-diff-file");for(let w of p){if(w.startsWith("diff --git ")){if(f.childNodes.length>0)g.append(f);f=D("div","bp-diff-file"),u++;let x=w.match(/ b\/(.+)$/);f.append(D("div","bp-diff-file-head",x?x[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))f.append(D("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))f.append(D("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))y++,f.append(D("div","bp-diff-line is-add",w));else if(w.startsWith("-"))E++,f.append(D("div","bp-diff-line is-del",w));else f.append(D("div","bp-diff-line",w))}if(f.childNodes.length>0)g.append(f);o.textContent=`${u||1} file${u===1?"":"s"} · +${y} -${E}`,a.append(g)}catch(l){if(!i)return;o.textContent="Diff unavailable",a.append(D("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return d(),{destroy(){i=!1}}}function ni(e,t,n){let i=!0,s="checks",r=D("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let o=D("div","bp-pane-bar"),c=D("div","bp-review-tabs"),a=D("button","bp-v-btn is-on","Checks"),d=D("button","bp-v-btn","BOM"),l=D("button","bp-v-btn","Comments");a.type=d.type=l.type="button",c.append(a,d,l);let h=D("button","bp-v-btn","Refresh");h.type="button",h.addEventListener("click",()=>void E()),o.append(c,h);let p=D("div","bp-review-body");p.setAttribute("data-testid","review-body"),r.append(o,p),e.replaceChildren(r);function u(g){s=g,a.classList.toggle("is-on",s==="checks"),d.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),E()}a.addEventListener("click",()=>u("checks")),d.addEventListener("click",()=>u("bom")),l.addEventListener("click",()=>u("comments"));function y(g){let f=D("div","bp-review-md"),w=g.split(` -`),x=0;while(x{N.preventDefault();let F=L.value.trim();if(!F)return;T.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:F}).then(()=>{L.value="",T.disabled=!1,E()},()=>{T.disabled=!1})}),p.append(S),x.length===0){p.append(D("div","bp-pane-empty","No review comments yet."));return}for(let N of x){let F=D("div","bp-review-comment"+(N.resolved?" is-resolved":"")),U=[N.by||"review",N.file,N.layer,N.item].filter(Boolean).join(" · ");F.append(D("div","bp-review-comment-meta",U),D("div","bp-review-comment-text",N.text)),p.append(F)}return}let g=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let f=g?.report||{};if(p.replaceChildren(),f.line||f.gate){let w=D("div","bp-review-gate",[f.gate,f.line].filter(Boolean).join(" · "));p.append(w)}if(f.err)p.append(D("div","bp-review-err",f.err));if(Array.isArray(f.tasks)&&f.tasks.length>0){let w=D("div","bp-review-tasks");f.tasks.forEach((x,S)=>{let L=D("label","bp-review-task"),T=document.createElement("input");T.type="checkbox",T.checked=!!(x.done??x.checked);let N=typeof x.index==="number"?x.index:S;T.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:N}).then(()=>void E(),()=>{})}),L.append(T,D("span",void 0,x.text||x.label||`Item ${S+1}`)),w.append(L)}),p.append(w)}if(f.md&&f.md.trim())p.append(y(f.md));else if(!f.err&&(!f.tasks||f.tasks.length===0))p.append(D("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(g){if(!i)return;p.replaceChildren(D("div","bp-pane-empty",g instanceof Error?g.message:String(g)))}}return E(),{destroy(){i=!1}}}function ii(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class zt{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,r=Math.max(i-t,1000),o=Math.max(s-n,1000),c=this.canvas.getBoundingClientRect(),a=Math.max(c.width,200),d=Math.max(c.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(a/r,d/o)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),r=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==r)this.canvas.width=s,this.canvas.height=r;let o=this.ctx;o.setTransform(i,0,0,i,0,0),o.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",o.fillRect(0,0,t,n);let c=this.frame;if(!c)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let a=t*0.5,d=n*0.5,l=this.scale,h=this.cx,p=this.cy,u=h-a/l,y=h+a/l,E=p-d/l,g=p+d/l,{off:f,dim:w,lift:x}=this.masks,S=[],L=[];for(let N=0;N>>F&1)===1)continue;if(F===x)L.push(N);else S.push(N)}let T=S.concat(L);o.lineCap="round",o.lineJoin="round";for(let N=0;N>>U.layer&1)===1,I=U.alpha*(G?0.25:1);if(I<=0.01)continue;this.drawChunk(o,U,I,u,E,y,g,h,p,l,a,d)}if(this.highlights.size>0){o.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",o.fillRect(0,0,t,n);let N=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let F=0;Fr||g.y1o)continue;if(g.n<3)continue;let f=(p[g.at]-c)*d+l,w=(p[g.at+1]-a)*d+h;e.moveTo(f,w);for(let x=1;x0)e.fill()}else if(t.mode===2){let y=Math.max(0.75,t.r*d);e.fillStyle=u,e.beginPath();let E=0;for(let g=0;gr||f.y1o)continue;let w=(p[f.at]-c)*d+l,x=(p[f.at+1]-a)*d+h;e.moveTo(w+y,x),e.arc(w,x,y,0,Math.PI*2),E++}if(E>0)e.fill()}else{e.strokeStyle=u,e.lineWidth=Math.max(1,t.r*2*d),e.beginPath();let y=0;for(let E=0;Er||g.y1o)continue;let f=(p[g.at]-c)*d+l,w=(p[g.at+1]-a)*d+h;if(g.n===1)e.moveTo(f,w),e.lineTo(f+0.01,w);else{e.moveTo(f,w);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,o,c,a,d,l,h,p){let u=t.pts,y=ii(t.color,t.alpha);for(let E=0;Eo||g.y1c)continue;let f=(u[g.at]-a)*l+h,w=(u[g.at+1]-d)*l+p;if(g.kind===2){let x=Math.max(1.5,t.r*l);e.fillStyle=y,e.beginPath(),e.arc(f,w,x,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(g.kind===0&&g.n>=3){e.fillStyle=y,e.beginPath(),e.moveTo(f,w);for(let x=1;x=0;l--){let h=n.chunks[l];if(h.layer<32&&(d>>>h.layer&1)===1)continue;for(let p=0;pu.x1+o||ru.y1+o)continue;let y=(u.x1-u.x0+1)*(u.y1-u.y0+1);if(y{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,o=i/this.pinchStart.dist,c=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*o)),a=this.canvas.getBoundingClientRect(),d=this.pinchStart.midX-a.left-a.width*0.5,l=this.pinchStart.midY-a.top-a.height*0.5,h=s-a.left-a.width*0.5,p=r-a.top-a.height*0.5;this.scale=c,this.cx=this.pinchStart.cx+d/this.pinchStart.scale-h/c,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-p/c,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,r=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/r,this.cy+=i/this.scale-i/r,this.scale=r,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var si=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function ri(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function Kt(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` -`),r=(s[0]||"").split("\t");if(r[0]!=="git"||r[2]!==n)return!1;let o=s[1]||r.slice(4).join("\t");if(!o)return!1;let c=o.replace(/\\/g,"/"),a=i.replace(/\\/g,"/");if(a.startsWith("/")||/^[A-Za-z]:\//.test(a))return c===a;return c===a||c.endsWith(`/${a}`)}class Jt{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Gi=`#version 300 es +`),h=document.createElement("div");h.className="bp-code-block";let p=document.createElement("div");p.className="bp-code-head";let u=document.createElement("span");u.className="bp-code-lang",u.textContent=a||"code";let y=document.createElement("button");y.type="button",y.className="bp-btn-ghost bp-code-copy";let E=f("common.copy","Copy");y.textContent=E,y.addEventListener("click",()=>{navigator.clipboard?.writeText(l).then(()=>{y.textContent="✓",window.setTimeout(()=>{y.textContent=E},1200)}).catch(()=>{})}),p.append(u,y);let v=document.createElement("pre"),g=document.createElement("code");g.textContent=l,v.appendChild(g),h.append(p,v),t.appendChild(h);continue}if(!s.trim()){i++;continue}let r=/^(#{1,4})\s+(.+)$/.exec(s);if(r){let a=document.createElement(`h${Math.min(4,r[1].length+1)}`);a.className="bp-md-h",dt(a,r[2]),t.appendChild(a),i++;continue}if(s.startsWith("> ")){let a=document.createElement("blockquote");a.className="bp-md-quote";let d=[];while(i "))d.push(n[i].slice(2)),i++;dt(a,d.join(` +`)),t.appendChild(a);continue}if(/^\s*[-*]\s+/.test(s)){let a=document.createElement("ul");a.className="bp-md-list";while(i ")&&!/^\s*[-*]\s+/.test(n[i])&&!/^\s*\d+\.\s+/.test(n[i]))o.push(n[i]),i++;let c=document.createElement("p");c.className="bp-md-p";for(let a=0;a0)c.appendChild(document.createElement("br"));dt(c,o[a])}t.appendChild(c)}return t}var bn="http://www.w3.org/2000/svg";function fn(e){let t=document.createElementNS(bn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","12"),t.setAttribute("height","12"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(bn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function jt(e){return e<10000000000?e*1000:e}function Li(e){if(!e)return"";return new Date(jt(e)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!1})}function Ni(e){if(!Number.isFinite(e)||e<=0||e>3600000)return"";let t=Math.max(1,Math.round(e/1000));if(t<60)return`${t}s`;let n=Math.floor(t/60),i=t%60;return i>0?`${n}m ${i}s`:`${n}m`}function Rt(e){if(e.agentOnly)return!0;if(e.kind==="note"){let t=(e.text||"").trim();if(t.startsWith("Made this folder a git repository")||t.startsWith("Backplane: snapshot")||t.includes("snapshot of existing work before first use"))return!0}return!1}class Dt{bannerEl;scrollEl;listEl;olderBtn;cb;thread=null;entries=[];hasMore=!1;loadingOlder=!1;review=null;unanswered=null;btwNote=null;liveNodes=new Map;imageCache=new Map;pinnedToBottom=!0;constructor(e,t){if(this.cb=t,this.bannerEl=document.createElement("div"),this.bannerEl.className="bp-thread-banners",this.scrollEl=document.createElement("div"),this.scrollEl.className="bp-timeline-scroll",this.scrollEl.setAttribute("data-testid","timeline"),this.olderBtn=document.createElement("button"),this.olderBtn.type="button",this.olderBtn.className="bp-older-btn bp-hidden",this.olderBtn.textContent=f("android.load.earlier","Load earlier"),this.olderBtn.setAttribute("data-testid","load-older-btn"),this.olderBtn.addEventListener("click",()=>{if(!this.loadingOlder&&this.hasMore)this.loadingOlder=!0,this.cb.onLoadOlder()}),this.scrollEl.addEventListener("scroll",()=>{if(this.pinnedToBottom=this.isNearBottom(),this.hasMore&&!this.loadingOlder&&this.scrollEl.scrollTop<48)this.loadingOlder=!0,this.cb.onLoadOlder()}),typeof ResizeObserver<"u"){let n=0;new ResizeObserver(()=>{let s=this.scrollEl.clientHeight;if(n>0&&s!==n&&this.pinnedToBottom)this.scrollToBottom();n=s}).observe(this.scrollEl)}this.listEl=document.createElement("div"),this.listEl.className="bp-timeline-list",this.scrollEl.append(this.olderBtn,this.listEl),e.append(this.bannerEl,this.scrollEl)}setLoading(e){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let t=document.createElement("div");t.className="bp-empty-state",t.textContent=f("web.chat.loading","Loading messages…"),this.listEl.replaceChildren(t)}setError(e,t,n){this.thread=e,this.entries=[],this.hasMore=!1,this.loadingOlder=!1,this.review=null,this.unanswered=null,this.btwNote=null,this.liveNodes.clear(),this.renderBanners(),this.olderBtn.classList.add("bp-hidden");let i=document.createElement("div");i.className="bp-empty-state";let s=document.createElement("div");s.className="bp-bad",s.textContent=t;let r=document.createElement("button");r.type="button",r.textContent=f("tools.retry","Retry"),r.addEventListener("click",n),i.append(s,r),this.listEl.replaceChildren(i)}getEntries(){return this.entries.slice()}refreshLocale(){let e=this.scrollEl.scrollTop;if(this.olderBtn.textContent=f("android.load.earlier","Load earlier"),this.renderBanners(),this.thread&&this.entries.length>0)this.renderEntries(!1);this.scrollEl.scrollTop=e}setThread(e,t,n,i,s){this.thread=e,this.entries=t.filter((r)=>!Rt(r)),this.hasMore=n,this.loadingOlder=!1,this.review=i,this.unanswered=s,this.btwNote=null,this.renderBanners(),this.renderEntries(!0)}updateThreadMeta(e){if(!this.thread||this.thread.id!==e.id)return;this.thread=e}setReview(e){this.review=e,this.renderBanners()}setUnanswered(e){this.unanswered=e,this.renderBanners()}showBtw(e,t){this.btwNote={q:e,a:t},this.renderBanners()}prependEntries(e,t){this.loadingOlder=!1;let n=this.scrollEl.scrollHeight,i=new Set(this.entries.map((r)=>r.id)),s=e.filter((r)=>!Rt(r)&&!i.has(r.id));this.entries=[...s,...this.entries],this.hasMore=t,this.renderEntries(!1),this.scrollEl.scrollTop+=this.scrollEl.scrollHeight-n}clearLoadingOlder(){this.loadingOlder=!1}upsertEntry(e){if(Rt(e))return;let t=this.isNearBottom()||e.kind==="user"&&Boolean(e.clientId),n=this.entries.findIndex((i)=>i.id===e.id);if(n<0&&e.clientId)n=this.entries.findIndex((i)=>i.clientId&&i.clientId===e.clientId);if(n>=0)this.entries[n]=e;else this.entries.push(e);this.renderEntries(t)}goTo(e){let t=this.scrollEl.querySelector(`[data-entry-id="${CSS.escape(e)}"]`);if(!t)return!1;return t.scrollIntoView({block:"center",behavior:"smooth"}),t.classList.remove("bp-entry-flash"),t.offsetWidth,t.classList.add("bp-entry-flash"),window.setTimeout(()=>t.classList.remove("bp-entry-flash"),1200),!0}removeEntry(e){let t=this.entries.filter((n)=>n.id!==e);if(t.length!==this.entries.length)this.entries=t,this.renderEntries(!1)}appendLiveText(e,t,n){let i=this.isNearBottom(),s=this.entries.find((o)=>o.id===e);if(!s){s={id:e,kind:"assistant",text:t,at:n,live:!0},this.entries.push(s),this.renderEntries(i);return}s.text+=t,s.live=!0;let r=this.liveNodes.get(e);if(r){if(r.replaceChildren(yt(s.text)),i)this.scrollToBottom()}else this.renderEntries(i)}isNearBottom(){let e=this.scrollEl;return e.scrollHeight-e.scrollTop-e.clientHeight<80}scrollToBottom(){this.pinnedToBottom=!0,this.scrollEl.scrollTop=this.scrollEl.scrollHeight}renderBanners(){let e=document.createDocumentFragment();if(this.review&&(this.review.text||this.review.button)){let t=document.createElement("div");t.className="bp-banner bp-review-bar",t.setAttribute("data-testid","review-bar");let n=document.createElement("span");if(n.textContent=this.review.text||f("web.chat.review.mode","Review mode"),t.appendChild(n),this.review.button){let i=document.createElement("button");i.type="button",i.textContent=this.review.button,i.addEventListener("click",()=>this.cb.onToggleReview(!(this.review?.on??!0))),t.appendChild(i)}e.appendChild(t)}if(this.unanswered&&(this.unanswered.head||this.unanswered.text)){let t=document.createElement("div");t.className="bp-banner bp-unanswered",t.setAttribute("data-testid","unanswered-notice");let n=document.createElement("div");if(n.className="bp-unanswered-body",this.unanswered.head){let i=document.createElement("strong");i.textContent=this.unanswered.head,n.appendChild(i)}if(this.unanswered.text){let i=document.createElement("span");i.textContent=this.unanswered.text,n.appendChild(i)}if(t.appendChild(n),this.unanswered.buttons?.length){let i=document.createElement("div");i.className="bp-banner-actions";for(let s of this.unanswered.buttons){let r=document.createElement("button");if(r.type="button",s.primary)r.className="primary";r.textContent=s.label,r.addEventListener("click",()=>this.cb.onUnansweredAction(s.action,s.value)),i.appendChild(r)}t.appendChild(i)}e.appendChild(t)}if(this.btwNote){let t=document.createElement("div");t.className="bp-banner bp-btw-banner";let n=document.createElement("div"),i=document.createElement("div");i.className="bp-dim",i.textContent=`/btw ${this.btwNote.q}`;let s=document.createElement("div");s.appendChild(yt(this.btwNote.a)),n.append(i,s);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.btwNote=null,this.renderBanners()}),t.append(n,r),e.appendChild(t)}this.bannerEl.replaceChildren(e)}makeEntryActions(e,t,n){let i=document.createElement("div");i.className="bp-entry-foot"+(t?" user":"");let s=document.createElement("button");s.type="button",s.className="bp-entry-act";let r=f("common.copy","Copy"),o=document.createElement("span");o.textContent=r,s.append(fn(["M9 9h11v11H9z","M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"]),o),s.addEventListener("click",()=>{navigator.clipboard?.writeText(e.text||"").then(()=>{o.textContent="✓",window.setTimeout(()=>{o.textContent=r},1000)}).catch(()=>{})});let c=document.createElement("button");c.type="button",c.className="bp-entry-act";let a=document.createElement("span");a.textContent=f("reply.action","Reply"),c.append(fn(["M9 17l-5-5 5-5","M20 18v-2a4 4 0 0 0-4-4H4"]),a),c.addEventListener("click",()=>this.cb.onReplyEntry(e));let d=!e.live&&!e.id.startsWith("local-")&&!e.id.startsWith("live:"),l=document.createElement("span");l.className="bp-entry-time";let h=Li(e.at);if(t)l.textContent=h,i.append(s,...d?[c]:[],l);else{let p=n&&e.at?Ni(jt(e.at)-jt(n)):"",u=h?p?f("web.chat.finished.dur","Finished {time} · {dur}",{time:h,dur:p}):f("web.chat.finished","Finished {time}",{time:h}):"";l.textContent=e.live?f("web.chat.streaming","Streaming…"):u,i.append(l,s,...d?[c]:[])}return i}renderEntries(e){this.olderBtn.classList.toggle("bp-hidden",!this.hasMore),this.liveNodes.clear();let t=document.createDocumentFragment();if(!this.thread){let i=document.createElement("div");i.className="bp-empty-state",i.textContent=f("web.chat.choose","Choose a project thread on the left to begin."),t.appendChild(i),this.listEl.replaceChildren(t);return}if(this.entries.length===0){let i=document.createElement("div");i.className="bp-empty-state",i.textContent=f("web.chat.empty","No messages yet. Type below to start a turn."),t.appendChild(i),this.listEl.replaceChildren(t);return}let n=0;for(let i of this.entries){if(i.kind==="user"&&i.at)n=i.at;let s=document.createElement("article");if(s.className=`bp-entry bp-entry-${i.kind}`+(i.live?" is-live":""),s.setAttribute("data-entry-id",i.id),i.kind==="tool"&&i.tool){let a=document.createElement("div");a.className=`bp-tool-pill bp-tool-${i.tool.state||"done"}`;let d=document.createElement("span");if(d.className="bp-tool-name",d.textContent=i.tool.name,a.appendChild(d),i.tool.summary){let l=document.createElement("span");l.className="bp-tool-summary",l.textContent=i.tool.summary,a.appendChild(l)}s.appendChild(a),t.appendChild(s);continue}if(i.kind==="ask"&&i.ask){let a=i.ask,d=document.createElement("div");d.className="bp-ask-card",d.setAttribute("data-testid",`ask-${a.id}`);let l=document.createElement("div");if(l.className="bp-ask-q",l.textContent=a.question,d.appendChild(l),a.state==="open"){let h=document.createElement("div");if(h.className="bp-ask-opts",a.options&&a.options.length>0)for(let p of a.options){let u=document.createElement("button");u.type="button",u.textContent=p.label,u.addEventListener("click",()=>this.cb.onAnswerAsk(a.id,p.id)),h.appendChild(u)}else{let p=document.createElement("input");p.type="text",p.className="bp-input",p.placeholder=f("web.chat.answer.placeholder","Type answer…");let u=document.createElement("button");u.type="button",u.className="primary",u.textContent=f("web.chat.answer.btn","Answer"),u.addEventListener("click",()=>{if(p.value.trim())this.cb.onAnswerAsk(a.id,p.value.trim())}),h.append(p,u)}d.appendChild(h)}else{let h=document.createElement("div");h.className="bp-ask-answered",h.textContent=f("web.chat.answered","Answered: {answer}",{answer:a.answered??""}),d.appendChild(h)}s.appendChild(d),t.appendChild(s);continue}let r=Boolean(i.text&&i.text.trim().length>0),o=Boolean(i.images&&i.images.length>0),c=Boolean(i.attachments&&i.attachments.length>0);if(!r&&!o&&!c&&!i.live)continue;if(i.replyTo?.quote){let a=document.createElement("div");a.className="bp-reply-quote",a.textContent=f("gpui.b.in.reply.to","↩ In reply to: {quote}",{quote:i.replyTo.quote});let d=i.replyTo.id;a.setAttribute("role","button"),a.tabIndex=0,a.setAttribute("data-testid","entry-reply-quote");let l=()=>{if(this.cb.onGoToEntry)this.cb.onGoToEntry(d);else this.goTo(d)};a.addEventListener("click",l),a.addEventListener("keydown",(h)=>{if(h.key==="Enter"||h.key===" ")h.preventDefault(),l()}),s.appendChild(a)}if(r||i.live){let a=document.createElement("div");if(a.className="bp-entry-body",i.kind==="user")a.textContent=i.text;else a.appendChild(yt(i.text||""));if(i.live)this.liveNodes.set(i.id,a);s.appendChild(a)}if(c&&i.attachments){let a=document.createElement("div");a.className="bp-entry-images";for(let d of i.attachments)if(d.previewUrl){let l=document.createElement("img");l.className="bp-reply-img",l.src=d.previewUrl,l.alt=d.name||"attachment",a.appendChild(l)}else if(d.path||d.name){let l=document.createElement("span");l.className="bp-tool-pill",l.textContent=d.name||d.path||"image",a.appendChild(l)}if(a.childElementCount>0)s.appendChild(a)}if(i.images&&i.images.length>0){let a=document.createElement("div");a.className="bp-entry-images";for(let d of i.images){let l=document.createElement("img");l.className="bp-reply-img",l.alt=d;let h=`${i.id}|${d}`,p=this.imageCache.get(h);if(p)l.src=p;else this.cb.onLoadImage(i.id,d).then((u)=>{if(!u)return;let y=u.url??(u.mime&&u.data?`data:${u.mime};base64,${u.data}`:"");if(!y)return;this.imageCache.set(h,y),l.src=y});a.appendChild(l)}s.appendChild(a)}s.appendChild(this.makeEntryActions(i,i.kind==="user",i.kind==="assistant"?n:void 0)),t.appendChild(s)}if(this.listEl.replaceChildren(t),e)this.scrollToBottom()}}var gn="http://www.w3.org/2000/svg",vn=4,wn=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function yn(e){let t=document.createElementNS(gn,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","15"),t.setAttribute("height","15"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(gn,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function Ti(e){let t=(e||"").toLowerCase();if(t.includes("claude")||t.includes("anthropic"))return{glyph:"A",color:"#d97706",title:"Claude"};if(t.includes("codex")||t.includes("openai"))return{glyph:"O",color:"#10b981",title:"Codex"};if(t.includes("gemini")||t.includes("antigravity"))return{glyph:"G",color:"#3b82f6",title:"Gemini"};if(t.includes("grok"))return{glyph:"X",color:"#94a3b8",title:"Grok"};return{glyph:"●",color:"var(--accent)",title:e||"Model"}}class Ht{popupEl;attachStripEl;fileInput;textarea;memoryEl;memoryFill;memoryText;providerMarkEl;modelTextEl;ctxEl;attachBtn;voiceBtn;sendBtn;stopBtn;errorEl;replyEl;cb;commands=[];popupMode="none";filteredSlash=[];mentionItems=[];popupIdx=0;enabled=!1;attachments=[];constructor(e,t){this.cb=t;let n=document.createElement("div");n.className="bp-composer",n.setAttribute("data-testid","composer");let i=document.createElement("div");i.className="bp-composer-inner",this.popupEl=document.createElement("div"),this.popupEl.className="bp-composer-popup bp-hidden",this.popupEl.setAttribute("data-testid","slash-menu"),this.errorEl=document.createElement("div"),this.errorEl.className="bp-composer-err bp-hidden",this.replyEl=document.createElement("div"),this.replyEl.className="bp-reply-strip bp-hidden",this.replyEl.setAttribute("data-testid","composer-reply"),this.attachStripEl=document.createElement("div"),this.attachStripEl.className="bp-attach-strip bp-hidden",this.attachStripEl.setAttribute("data-testid","composer-attachments"),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/png,image/jpeg,image/webp,image/gif",this.fileInput.multiple=!0,this.fileInput.className="bp-hidden",this.fileInput.setAttribute("data-testid","composer-file-input"),this.fileInput.addEventListener("change",()=>{if(this.fileInput.files)this.addFiles(Array.from(this.fileInput.files));this.fileInput.value=""}),this.textarea=document.createElement("textarea"),this.textarea.className="bp-composer-input",this.textarea.rows=2,this.textarea.placeholder=f("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.textarea.setAttribute("data-testid","composer-input");let s=document.createElement("div");s.className="bp-composer-bar";let r=document.createElement("div");r.className="bp-composer-model",this.providerMarkEl=document.createElement("span"),this.providerMarkEl.className="bp-provider-mark",this.providerMarkEl.textContent="●",this.modelTextEl=document.createElement("span"),this.modelTextEl.className="bp-model-text",this.modelTextEl.textContent="default",this.ctxEl=document.createElement("span"),this.ctxEl.className="bp-ctx-pct bp-hidden",this.ctxEl.setAttribute("data-testid","composer-ctx"),r.append(this.providerMarkEl,this.modelTextEl,this.ctxEl),this.memoryEl=document.createElement("div"),this.memoryEl.className="bp-composer-memory bp-hidden",this.memoryEl.setAttribute("data-testid","composer-memory");let o=document.createElement("div");o.className="bp-memory-meter",this.memoryFill=document.createElement("div"),this.memoryFill.className="bp-memory-fill",o.appendChild(this.memoryFill),this.memoryText=document.createElement("span"),this.memoryEl.append(o,this.memoryText);let c=document.createElement("div");c.className="bp-composer-btns",this.attachBtn=document.createElement("button"),this.attachBtn.type="button",this.attachBtn.className="icon bp-composer-tool",this.attachBtn.title=f("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",f("web.composer.attach","Attach image")),this.attachBtn.setAttribute("data-testid","composer-attach"),this.attachBtn.appendChild(yn(["M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"])),this.attachBtn.addEventListener("click",()=>this.fileInput.click()),this.voiceBtn=document.createElement("button"),this.voiceBtn.type="button",this.voiceBtn.className="icon bp-composer-tool",this.voiceBtn.title=f("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",f("web.composer.voice","Voice dictation")),this.voiceBtn.setAttribute("data-testid","composer-voice"),this.voiceBtn.appendChild(yn(["M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z","M19 10v2a7 7 0 0 1-14 0v-2","M12 19v4","M8 23h8"])),this.voiceBtn.addEventListener("click",()=>this.cb.onToggleVoice?.()),this.stopBtn=document.createElement("button"),this.stopBtn.type="button",this.stopBtn.className="primary stop bp-hidden",this.stopBtn.textContent=f("composer.stop","Stop"),this.stopBtn.setAttribute("data-testid","composer-stop"),this.stopBtn.addEventListener("click",()=>this.cb.onInterrupt()),this.sendBtn=document.createElement("button"),this.sendBtn.type="button",this.sendBtn.className="primary bp-send-btn",this.sendBtn.textContent=f("composer.send","Send"),this.sendBtn.setAttribute("data-testid","composer-send"),this.sendBtn.addEventListener("click",()=>this.submit()),c.append(this.attachBtn,this.voiceBtn,this.stopBtn,this.sendBtn),s.append(r,this.memoryEl,c),i.append(this.popupEl,this.errorEl,this.replyEl,this.attachStripEl,this.fileInput,this.textarea,s),n.appendChild(i),e.appendChild(n),this.textarea.addEventListener("paste",(a)=>{let d=a.clipboardData?.items;if(!d)return;let l=[];for(let h=0;h0)a.preventDefault(),this.addFiles(l)}),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.clearError(),this.updatePopups()}),this.textarea.addEventListener("keydown",(a)=>{if(this.popupMode!=="none"){let d=this.popupMode==="slash"?this.filteredSlash.length:this.mentionItems.length;if(a.key==="ArrowDown"){a.preventDefault(),this.popupIdx=(this.popupIdx+1)%Math.max(1,d),this.renderPopup();return}if(a.key==="ArrowUp"){a.preventDefault(),this.popupIdx=(this.popupIdx-1+Math.max(1,d))%Math.max(1,d),this.renderPopup();return}if(a.key==="Tab"||a.key==="Enter"&&!a.shiftKey&&this.shouldCompleteOnEnter()){a.preventDefault(),this.applyPopupChoice(this.popupIdx);return}if(a.key==="Escape"){a.preventDefault(),this.closePopup();return}}if(a.key==="Enter"&&!a.shiftKey)a.preventDefault(),this.submit()})}setCommands(e){this.commands=e.map((t)=>({...t,word:t.word.replace(/^\//,"")}))}setModelChip(e,t,n){let i=Ti(t);if(this.providerMarkEl.textContent=i.glyph,this.providerMarkEl.style.color=i.color,this.providerMarkEl.title=i.title,this.modelTextEl.textContent=e||"default",typeof n==="number"&&Number.isFinite(n)&&n>=0)this.ctxEl.textContent=`ctx ${Math.round(n)}%`,this.ctxEl.classList.remove("bp-hidden");else this.ctxEl.textContent="",this.ctxEl.classList.add("bp-hidden")}setFeatures(e,t){this.attachBtn.classList.toggle("bp-hidden",!e),this.voiceBtn.classList.toggle("bp-hidden",!t)}setVoiceRecording(e){this.voiceBtn.classList.toggle("recording",e),this.voiceBtn.setAttribute("aria-pressed",e?"true":"false")}setVoiceLevel(e){this.voiceBtn.setAttribute("data-level",String(e))}getDraft(){return this.textarea.value}getCaret(){return this.textarea.selectionStart??this.textarea.value.length}setMemory(e){if(this.memoryEl.classList.toggle("bp-hidden",!e),!e)return;let t=e.total??0,n=t>0?Math.min(1,(e.done??0)/t):1;this.memoryFill.style.width=`${Math.round(n*100)}%`,this.memoryFill.dataset.state=e.state??"",this.memoryText.textContent=e.line??"",this.memoryEl.title=[e.status,e.lines,e.viewLine].filter(Boolean).join(` +`)}setState(e,t){this.enabled=e,this.textarea.disabled=!e,this.sendBtn.disabled=!e,this.attachBtn.disabled=!e,this.voiceBtn.disabled=!e,this.stopBtn.classList.toggle("bp-hidden",!t)}setDraft(e){this.textarea.value=e,this.autoGrow(),this.textarea.focus()}setReply(e,t,n){if(!e){this.replyEl.replaceChildren(),this.replyEl.classList.add("bp-hidden");return}let i=document.createElement("button");i.type="button",i.className="bp-reply-strip-body",i.setAttribute("data-testid","composer-reply-go");let s=document.createElement("span");s.className="bp-reply-strip-who",s.textContent=e.who;let r=document.createElement("span");if(r.className="bp-reply-strip-line",r.textContent=f("gpui.b.replying.to","↩ Replying to: {line}",{line:e.line}),i.append(s,r),t)i.addEventListener("click",t);let o=document.createElement("button");o.type="button",o.className="icon bp-reply-strip-drop",o.textContent="×";let c=f("reply.cancel","Cancel reply");if(o.title=c,o.setAttribute("aria-label",c),o.setAttribute("data-testid","composer-reply-drop"),n)o.addEventListener("click",n);this.replyEl.replaceChildren(i,o),this.replyEl.classList.remove("bp-hidden"),this.textarea.focus()}prependDraft(e){let t=this.textarea.value;this.textarea.value=t?`${e} +${t}`:e,this.autoGrow(),this.textarea.focus()}showError(e){this.errorEl.textContent=e,this.errorEl.classList.remove("bp-hidden")}clearError(){this.errorEl.textContent="",this.errorEl.classList.add("bp-hidden")}focus(){this.textarea.focus()}refreshLocale(){this.textarea.placeholder=f("composer.placeholder","Ask anything: @bot, >thread, %project, #room, $skill, /btw"),this.attachBtn.title=f("web.composer.attach","Attach image"),this.attachBtn.setAttribute("aria-label",f("web.composer.attach","Attach image")),this.voiceBtn.title=f("web.composer.voice","Voice dictation"),this.voiceBtn.setAttribute("aria-label",f("web.composer.voice","Voice dictation")),this.sendBtn.textContent=f("composer.send","Send"),this.stopBtn.textContent=f("composer.stop","Stop")}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=`${Math.min(180,Math.max(54,this.textarea.scrollHeight))}px`}shouldCompleteOnEnter(){if(this.popupMode==="mention")return!0;if(this.popupMode==="slash"){let e=this.textarea.value;return e.startsWith("/")&&!e.includes(" ")}return!1}updatePopups(){let e=this.textarea.value;if(e.startsWith("/")&&!e.includes(" ")&&!e.includes(` +`)){let n=e.slice(1).toLowerCase();if(this.filteredSlash=this.commands.filter((i)=>i.word.toLowerCase().startsWith(n)),this.filteredSlash.length>0){this.popupMode="slash",this.popupIdx=Math.min(this.popupIdx,this.filteredSlash.length-1),this.renderPopup();return}}let t=/(?:^|\s)([@>%#])([a-zA-Z0-9._-]{1,32})$/.exec(e.slice(0,this.textarea.selectionStart));if(t){let n=t[1],i=t[2];this.cb.onQueryMentions(i,n).then((s)=>{if(s.length>0)this.mentionItems=s,this.popupMode="mention",this.popupIdx=0,this.renderPopup();else if(this.popupMode==="mention")this.closePopup()});return}this.closePopup()}closePopup(){this.popupMode="none",this.popupEl.classList.add("bp-hidden"),this.popupEl.replaceChildren()}renderPopup(){let e=document.createDocumentFragment();if(this.popupMode==="slash")this.filteredSlash.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":""),i.setAttribute("data-testid",`slash-item-${t.word}`);let s=document.createElement("span");s.className="bp-popup-name",s.textContent=`/${t.word}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.desc||t.label,i.append(s,r),i.addEventListener("mousedown",(o)=>{o.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});else if(this.popupMode==="mention")this.mentionItems.forEach((t,n)=>{let i=document.createElement("button");i.type="button",i.className="bp-popup-row"+(n===this.popupIdx?" active":"");let s=document.createElement("span");s.className="bp-popup-name",s.textContent=t.word||`${t.sigil}${t.label}`;let r=document.createElement("span");r.className="bp-popup-desc",r.textContent=t.detail||t.label,i.append(s,r),i.addEventListener("mousedown",(o)=>{o.preventDefault(),this.applyPopupChoice(n)}),e.appendChild(i)});this.popupEl.replaceChildren(e),this.popupEl.classList.remove("bp-hidden")}applyPopupChoice(e){if(this.popupMode==="slash"){let t=this.filteredSlash[e];if(t)this.textarea.value=`/${t.word} `,this.autoGrow(),this.textarea.focus();this.closePopup()}else if(this.popupMode==="mention"){let t=this.mentionItems[e];if(t){let n=this.textarea.selectionStart,i=this.textarea.value.slice(0,n),s=this.textarea.value.slice(n),r=i.replace(/([@>%#][a-zA-Z0-9._-]{1,32})$/,`${t.word} `);this.textarea.value=r+s,this.textarea.selectionStart=this.textarea.selectionEnd=r.length,this.textarea.focus()}this.closePopup()}}async addFiles(e){this.clearError();for(let t of e){if(!wn.has(t.type)){this.showError(f("web.composer.unsupported","Unsupported image type: {type}",{type:t.type||t.name}));continue}if(this.attachments.length>=vn){this.showError(f("web.composer.maximages","At most {max} images per message.",{max:vn}));break}let n=await new Promise((s,r)=>{let o=new FileReader;o.onload=()=>s(String(o.result||"")),o.onerror=()=>r(Error("read failed")),o.readAsDataURL(t)}).catch(()=>""),i=n.indexOf(",");if(i<0)continue;this.attachments.push({name:t.name||`image-${this.attachments.length+1}.png`,mime:t.type,data:n.slice(i+1),previewUrl:n})}this.renderAttachments()}renderAttachments(){if(this.attachments.length===0){this.attachStripEl.classList.add("bp-hidden"),this.attachStripEl.replaceChildren();return}let e=document.createDocumentFragment();this.attachments.forEach((t,n)=>{let i=document.createElement("div");i.className="bp-attach-chip";let s=document.createElement("img");s.src=t.previewUrl,s.alt=t.name,s.className="bp-attach-thumb";let r=document.createElement("button");r.type="button",r.className="icon bp-attach-rm",r.textContent="×",r.title=f("common.remove","Remove"),r.addEventListener("click",()=>{this.attachments.splice(n,1),this.renderAttachments()}),i.append(s,r),e.appendChild(i)}),this.attachStripEl.replaceChildren(e),this.attachStripEl.classList.remove("bp-hidden")}submit(){if(!this.enabled)return;let e=this.textarea.value.trim();if(!e&&this.attachments.length===0)return;if(this.closePopup(),this.clearError(),e.startsWith("/")&&this.attachments.length===0){let n=e.slice(1).split(/\s+/)[0]?.toLowerCase()??"";if(this.commands.some((i)=>i.word.toLowerCase()===n)){this.textarea.value="",this.autoGrow(),this.cb.onRunCommand(e);return}}let t=this.attachments.map(({name:n,mime:i,data:s})=>({name:n,mime:i,data:s}));this.attachments=[],this.renderAttachments(),this.textarea.value="",this.autoGrow(),this.cb.onSend(e,t)}}async function En(e,t=fetch){let n=await t("/auth/web/logout",{method:"POST",credentials:"same-origin",redirect:"error",headers:{"Content-Type":"application/json"},body:"{}"});if(n.status!==200||(await n.json()).state!=="revoked")throw Error("Logout was not confirmed");e()}var Pi=new Set(["bom","checks","life","plan","fab"]);function Et(e){if(!e||!Array.isArray(e.panels))return[];return e.panels.filter((t)=>t&&typeof t.id==="string"&&Pi.has(t.id))}function xn(e){let t=e?.badge?.n??0;if(!Number.isFinite(t)||t<=0)return null;return{text:t>99?"99+":String(Math.floor(t)),tone:e?.badge?.tone==="bad"?"bad":"warn"}}function xt(e,t=22){let n=e.join(", ");if(n.length<=t)return n;let i="";for(let s=0;s0?` +${c}`.length:0)>t)return i?`${i} +${e.length-s}`:`${e[0]} +${e.length-1}`;i=o}return i}function et(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1000)return String(Math.round(e));if(e<1e6){let n=e/1000;return n<10?`${n.toFixed(1).replace(/\.0$/,"")}k`:`${Math.round(n)}k`}let t=e/1e6;return t<10?`${t.toFixed(1).replace(/\.0$/,"")}M`:`${Math.round(t)}M`}function tt(e){if(!Number.isFinite(e))return"";if(e>=1)return`$${e.toFixed(2)}`;let t=e.toFixed(4).replace(/0+$/,"");return(t.split(".")[1]??"").length<2?`$${e.toFixed(2)}`:`$${t}`}var Mi=new Set(["0201","0402","0603","0805","1206","1210","1812","2010","2512"]),Bi=new Set(["QFN","DFN","SOT","SOIC","SOP","SSOP","TSSOP","MSOP","QFP","LQFP","TQFP","BGA","WLCSP","SOD","TO","SON","LGA"]);function Cn(e){if(!e)return"";let t=e.indexOf(":"),i=(t>=0?e.slice(t+1):e).split("_");for(let o of i)if(Mi.has(o))return o;let s=i[0]??"",r=s.replace(/[^a-zA-Z].*$/,"").toUpperCase();if(Bi.has(r)){let o=s.split("-");if(o.length>=2&&/^\d+$/.test(o[1]))return`${o[0]}-${o[1]}`;return o[0]}return i.slice(0,2).join("_")}function kn(e){let t=e?.status??"";if(!t)return null;let n=typeof e?.stock==="number"?e.stock:-1;if(t==="checking")return{text:"…",tone:"faint"};if(t==="unknown")return{text:"?",tone:"faint"};if(t==="out")return{text:`out ${et(Math.max(n,0))}`,tone:"bad"};if(t==="low")return{text:`low ${et(n)}`,tone:"warn"};return{text:et(n),tone:"ok"}}function Sn(e,t){let n=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(n.length===0)return e;return e.filter((i)=>{let s=[(i.refs??[]).join(" "),i.value??"",i.footprint??"",i.mpn??"",i.fab??""].join(" ").toLowerCase();return n.every((r)=>r==="dnp"&&Boolean(i.dnp)||s.includes(r))})}function An(e,t){if(!t)return e;return e.filter((n)=>n.source===t)}function Ft(e){if(e==="active")return{label:"Active",tone:"ok"};if(e==="nrnd")return{label:"NRND",tone:"warn"};if(e==="eol")return{label:"EOL",tone:"bad"};return{label:"Unknown",tone:"faint"}}function Ct(e){if(!Number.isFinite(e)||e<=0)return"";let t=new Date(e*1000),n=t.getUTCFullYear(),i=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0");return`${n}-${i}-${s}`}function Ln(e){return e.state==="routed"||e.state==="verified"}function Nn(e){switch(e.state){case"approved":return"✓";case"edited":return"✎";case"verified":return"✓✓";case"routed":return"100%";case"rejected":return"✗";case"routing":return typeof e.routed==="number"&&typeof e.total==="number"&&e.total>0?`${e.routed}/${e.total}`:"…";case"blocked":return`⚠ ${Math.max(1,e.problems??1)}`;default:return""}}function Tn(e){switch(e){case"current":return{text:"The fab's limits are in the DRC rules",button:null};case"stale":return{text:"The DRC rules have older fab limits",button:"Update"};case"none":return{text:"The fab's limits are not in the DRC rules",button:"Write"};default:return{text:"No KiCad project for DRC rules",button:null}}}function Pn(e){return e==="extra"?"costs-more limits":"base-price limits"}function $t(e,t){return e.watchGen===t.watchGen&&e.editGen===t.editGen&&e.project!==""&&e.project===t.project&&e.editId!==""&&e.editId===t.editId}function Mn(e){return{project:e.project,refs:e.refs.slice(),field:e.field,value:e.was}}function Ut(e,t){return e.watchGen===t.watchGen&&e.project!==""&&e.project===t.project&&e.threadId!==""&&e.threadId===t.threadId&&e.threadGen===t.threadGen}class Gt{hostEl;panelEl;stripEl;cb;infos=new Map;digest="";project="";askedProject="";watchGen=0;openPanel="";errorMsg="";bomFilter="";bomSelectedId="";bomEditingId="";bomEditGen=0;bomEditDraft="";bomEditStatus="";bomLastUndo=null;checksSource="";checksSelectedId="";checksStatus="";lifeSelectedKey="";lifePartSamples=null;lifePartLoading=!1;planHideDone=!1;planStatus="";fabStatus="";constructor(e,t,n){this.cb=n,this.hostEl=t,this.panelEl=document.createElement("aside"),this.panelEl.className="bp-mgmt-panel bp-hidden",this.panelEl.setAttribute("aria-label","Project management panel"),this.stripEl=document.createElement("div"),this.stripEl.className="bp-mgmt-strip bp-hidden",this.stripEl.setAttribute("data-testid","mgmt-strip"),this.stripEl.setAttribute("aria-label","Project management tabs"),e.appendChild(this.panelEl),t.appendChild(this.stripEl)}openTab(e){let t=this.getStateInfo();if(!Et(t).some((n)=>n.id===e))return;if(this.openPanel!==e)this.togglePanel(e)}getTabs(){return Et(this.getStateInfo())}isOpen(){return this.openPanel!==""}closePanel(){if(!this.openPanel)return;if(this.openPanel="",this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:""}).catch(()=>{});this.render()}clear(){this.watchGen++,this.bomEditGen++,this.askedProject="",this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.checksStatus="",this.planStatus="",this.fabStatus="",this.render()}async watchProject(e){if(!e||!this.cb.hub.hasFeature("mgmt")){this.clear();return}if(e===this.askedProject&&this.digest){this.render();return}let t=++this.watchGen;if(this.askedProject=e,this.project!==e)this.bomEditGen++,this.digest="",this.project="",this.openPanel="",this.errorMsg="",this.bomSelectedId="",this.bomEditingId="",this.bomEditStatus="",this.bomLastUndo=null,this.checksSelectedId="",this.checksStatus="",this.planStatus="",this.fabStatus="",this.lifeSelectedKey="",this.lifePartSamples=null,this.render();try{let n=await this.cb.hub.rpc("mgmt.watch",{project:e});if(t!==this.watchGen)return;let i=typeof n.digest==="string"?n.digest:"";if(!i){this.render();return}if(this.digest=i,this.project=typeof n.project==="string"&&n.project?n.project:e,n.state&&typeof n.state==="object")this.infos.set(`mgmt.state.${i}`,n.state);if(n.data&&typeof n.data==="object"){for(let[s,r]of Object.entries(n.data))if(r&&typeof r==="object")this.infos.set(`mgmt.${s}.${i}`,r)}this.errorMsg="",this.render()}catch{if(t===this.watchGen)this.render()}}handleInfo(e){let t=!1;for(let[n,i]of Object.entries(e)){if(!n.startsWith("mgmt.")&&!n.startsWith("kicad.checks."))continue;if(i===""||i===null||i===void 0){if(this.infos.delete(n))t=!0;continue}if(typeof i==="string")try{let s=JSON.parse(i);if(s&&typeof s==="object")this.infos.set(n,s),t=!0}catch{}else if(typeof i==="object")this.infos.set(n,i),t=!0}if(t)this.render()}getStateInfo(){if(!this.digest)return null;return this.infos.get(`mgmt.state.${this.digest}`)??null}getPanelData(e){if(!this.digest)return null;return this.infos.get(`mgmt.${e}.${this.digest}`)??null}togglePanel(e){let t=this.openPanel===e?"":e;if(this.openPanel=t,this.errorMsg="",this.render(),this.project)this.cb.hub.rpc("mgmt.panel",{project:this.project,open:t}).catch((n)=>{this.errorMsg=n instanceof Error?n.message:"Could not update panel",this.render()})}render(){let e=this.getStateInfo(),t=Et(e);if(!this.digest||t.length===0){this.stripEl.classList.add("bp-hidden"),this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.stripEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.stripEl.classList.remove("bp-hidden");let n=document.createDocumentFragment(),i=document.createElement("div");i.className="bp-mgmt-tabs";for(let r of t){let o=document.createElement("button");o.type="button";let c=this.openPanel===r.id;o.className="bp-mgmt-tab"+(c?" active":""),o.setAttribute("data-testid",`mgmt-tab-${r.id}`),o.setAttribute("aria-pressed",c?"true":"false");let a=document.createElement("span");a.textContent=Ee(r.label),o.appendChild(a);let d=this.getPanelData(r.id),l=xn(d);if(l){let h=document.createElement("span");h.className=`bp-mgmt-badge bp-tone-${l.tone}`,h.textContent=l.text,o.appendChild(h)}o.addEventListener("click",()=>this.togglePanel(r.id)),i.appendChild(o)}if(n.appendChild(i),this.openPanel){let r=document.createElement("button");r.type="button",r.className="icon bp-mgmt-close",r.textContent="×",r.title=f("gpui.mgmt.close","Close the panel"),r.setAttribute("aria-label",f("gpui.mgmt.close","Close the panel")),r.setAttribute("data-testid","mgmt-close"),r.addEventListener("click",()=>this.closePanel()),n.appendChild(r)}if(this.stripEl.replaceChildren(n),!this.openPanel){this.panelEl.classList.add("bp-hidden"),this.panelEl.removeAttribute("data-testid"),this.panelEl.replaceChildren(),this.cb.onOpenChange?.(!1);return}this.panelEl.classList.remove("bp-hidden"),this.panelEl.setAttribute("data-testid",`mgmt-panel-${this.openPanel}`),this.cb.onOpenChange?.(!0);let s=document.createDocumentFragment();if(this.errorMsg){let r=document.createElement("div");r.className="bp-mgmt-note bp-tone-bad",r.textContent=this.errorMsg,s.appendChild(r)}switch(this.openPanel){case"bom":s.appendChild(this.renderBom());break;case"checks":s.appendChild(this.renderChecks());break;case"life":s.appendChild(this.renderLife());break;case"plan":s.appendChild(this.renderPlan());break;case"fab":s.appendChild(this.renderFab());break}this.panelEl.replaceChildren(s)}renderBom(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("bom");if(!t)return e.appendChild(this.makeEmpty("Reading the schematic…")),e;let n=Array.isArray(t.lines)?t.lines:[],i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-dim",s.textContent=`${t.parts??0} parts · ${n.length} lines`;let r=document.createElement("span"),o=t.source==="kicad";if(r.className="bp-mgmt-pill"+(o?" accent":""),r.textContent=o?"live":"saved",i.append(s,r),(t.priced??0)>0&&(t.checking??0)===0&&typeof t.cost==="number"){let d=document.createElement("span");d.className="bp-dim",d.textContent=(t.priced??0)<(t.lookups??0)?`≥ ${tt(t.cost)}/board`:`${tt(t.cost)}/board`,i.appendChild(d)}if(t.paused){let d=document.createElement("span");d.className="bp-mgmt-faint",d.textContent="Stock check paused",i.appendChild(d)}if(e.appendChild(i),t.stock_note){let d=document.createElement("div");d.className="bp-mgmt-note bp-mgmt-faint",d.textContent=Ee(t.stock_note),e.appendChild(d)}let c=this.bomEditingId?n.find((d)=>d.id===this.bomEditingId)??null:null;if(c)e.appendChild(this.renderBomEditor(c));else{let d=document.createElement("div");d.className="bp-mgmt-filter-row";let l=document.createElement("input");l.type="text",l.className="bp-mgmt-filter",l.placeholder="Filter BOM (ref, value, footprint, MPN, dnp)…",l.value=this.bomFilter,l.setAttribute("data-testid","mgmt-bom-filter"),l.addEventListener("input",()=>{this.bomFilter=l.value,this.renderBomRows(a,n)}),d.appendChild(l),e.appendChild(d)}let a=document.createElement("div");return a.className="bp-mgmt-rows",a.setAttribute("data-testid","mgmt-bom-rows"),this.renderBomRows(a,n),e.appendChild(a),e}renderBomRows(e,t){let n=Sn(t,this.bomFilter);if(n.length===0){e.replaceChildren(this.makeEmpty(t.length===0?"No parts found.":"No matching lines."));return}let i=t.some((r)=>Boolean(r.mpn)||Boolean(r.fab)),s=document.createDocumentFragment();for(let r of n){let o=Array.isArray(r.refs)?r.refs:[],c=document.createElement("div");c.className="bp-mgmt-row"+(this.bomSelectedId===r.id?" active":"")+(r.dnp?" faint":""),c.setAttribute("data-testid",`mgmt-bom-row-${r.id}`);let a=document.createElement("div");a.className="bp-mgmt-row-line";let d=document.createElement("span");if(d.className="bp-mgmt-strong bp-mgmt-flex1",d.textContent=xt(o,24),a.appendChild(d),r.dnp){let E=document.createElement("span");E.className="bp-mgmt-pill",E.textContent=f("gpui.mgmt.bom.dnp","DNP"),a.appendChild(E)}else{let E=kn(r.stock);if(E){let v=document.createElement("span");v.className=`bp-tone-${E.tone}`,v.textContent=E.text,a.appendChild(v)}}let l=document.createElement("button");l.type="button",l.className="bp-mgmt-btn",l.textContent="Edit",l.addEventListener("click",(E)=>{E.stopPropagation(),this.bomEditGen++,this.bomEditingId=r.id,this.bomEditDraft=r.mpn??"",this.bomEditStatus="",this.bomLastUndo=null,this.render()}),a.appendChild(l);let h=document.createElement("div");h.className="bp-mgmt-row-sub";let p=[`${r.qty??o.length}×`,r.value??"",Cn(r.footprint??"")].filter(Boolean).join(" · "),u=document.createElement("span");u.className="bp-dim",u.textContent=p;let y=document.createElement("span");if(y.className="bp-mgmt-flex1",r.mpn)y.textContent=r.mpn;else if(i&&!r.dnp)y.className+=" bp-tone-warn",y.textContent=f("gpui.mgmt.bom.nompn","no MPN");if(h.append(u,y),!r.dnp&&typeof r.stock?.price==="number"){let E=document.createElement("span");E.className="bp-dim",E.textContent=tt(r.stock.price),h.appendChild(E)}if(!r.dnp&&r.stock?.class){let E=document.createElement("span");E.className="bp-mgmt-faint",E.textContent=Ee(r.stock.class),h.appendChild(E)}c.append(a,h),c.addEventListener("click",()=>{this.bomSelectedId=r.id,this.renderBomRows(e,t)}),s.appendChild(c)}e.replaceChildren(s)}renderBomEditor(e){let t=document.createElement("div");t.className="bp-mgmt-editor",t.setAttribute("data-testid","mgmt-bom-edit");let n=Array.isArray(e.refs)?e.refs:[],i=document.createElement("div");i.className="bp-mgmt-row-line";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=xt(n,30);let r=document.createElement("button");r.type="button",r.className="icon",r.textContent="×",r.addEventListener("click",()=>{this.bomEditGen++,this.bomEditingId="",this.bomLastUndo=null,this.bomEditStatus="",this.render()}),i.append(s,r);let o=document.createElement("input");o.type="text",o.className="bp-mgmt-filter",o.placeholder="MPN",o.value=this.bomEditDraft,o.addEventListener("input",()=>{this.bomEditDraft=o.value});let c=()=>({watchGen:this.watchGen,editGen:this.bomEditGen,project:this.project,editId:this.bomEditingId}),a=async(p,u=!1)=>{let y=c();this.bomEditStatus="Writing…",this.render();try{let E=await this.cb.hub.rpc("mgmt.bom.edit",p);if(!$t(y,c()))return;this.bomLastUndo=!u&&(E.changed??0)>0?{project:p.project,editId:y.editId,refs:p.refs.slice(),field:p.field,was:typeof E.was==="string"?E.was:p.field==="mpn"?e.mpn??"":e.dnp?"yes":"no"}:null,this.bomEditStatus=u?"Restored":(E.changed??0)===0?"No change":E.via==="kicad"?"Updated in KiCad":"Saved to schematic"}catch(E){if(!$t(y,c()))return;this.bomEditStatus=E instanceof Error?E.message:"Could not save edit"}this.render()},d=document.createElement("div");d.className="bp-mgmt-btn-row";let l=document.createElement("button");l.type="button",l.className="primary bp-mgmt-btn",l.textContent="Save MPN",l.addEventListener("click",()=>{a({project:this.project,refs:n.slice(),field:"mpn",value:this.bomEditDraft.trim()})});let h=document.createElement("button");if(h.type="button",h.className="bp-mgmt-btn",h.textContent=e.dnp?"Clear DNP":"Mark DNP",h.addEventListener("click",()=>{a({project:this.project,refs:n.slice(),field:"dnp",value:e.dnp?"no":"yes"})}),d.append(l,h),this.bomLastUndo&&this.bomLastUndo.project===this.project&&this.bomLastUndo.editId===this.bomEditingId){let p=this.bomLastUndo,u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn",u.textContent="Undo",u.addEventListener("click",()=>{a(Mn(p),!0)}),d.appendChild(u)}if(t.append(i,o,d),this.bomEditStatus){let p=document.createElement("div");p.className="bp-mgmt-faint",p.textContent=this.bomEditStatus,t.appendChild(p)}return t}renderChecks(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("checks");if(!t)return e.appendChild(this.makeEmpty("Reading checks…")),e;let n=Array.isArray(t.groups)?t.groups:[],i=Array.from(new Set(n.map((p)=>p.source).filter(Boolean))),s=(p)=>t.sources?.[p]?.label||p.toUpperCase(),r=(p)=>t.sources?.[p]?.judged===!0,o=document.createElement("div");o.className="bp-mgmt-head bp-mgmt-scroll-x";let c=document.createElement("button");c.type="button",c.className="bp-mgmt-btn"+(this.checksSource===""?" active":""),c.textContent=f("gpui.mgmt.checks.all","All"),c.addEventListener("click",()=>{this.checksSource="",this.render()}),o.appendChild(c);for(let p of i){let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn"+(this.checksSource===p?" active":""),u.textContent=s(p)+(r(p)?" · judged":""),u.addEventListener("click",()=>{this.checksSource=this.checksSource===p?"":p,this.render()}),o.appendChild(u)}let a=document.createElement("span");a.className="bp-mgmt-flex1";let d=document.createElement("button");if(d.type="button",d.className="bp-mgmt-btn",d.textContent=f("gpui.mgmt.checks.run","Run"),d.addEventListener("click",()=>{let p=this.watchGen,u=this.project;this.checksStatus="Running checks…",this.render(),this.cb.hub.rpc("kicad.checks.run",{project:u}).then(()=>{if(p!==this.watchGen||u!==this.project)return;this.checksStatus="",this.render()}).catch((y)=>{if(p!==this.watchGen||u!==this.project)return;this.checksStatus=y instanceof Error?y.message:"Could not run checks",this.render()})}),o.append(a,d),e.appendChild(o),this.checksStatus){let p=document.createElement("div");p.className="bp-mgmt-note bp-dim",p.textContent=this.checksStatus,e.appendChild(p)}let l=document.createElement("div");l.className="bp-mgmt-rows",l.setAttribute("data-testid","mgmt-checks-rows");let h=An(n,this.checksSource);if(h.length===0)l.appendChild(this.makeEmpty("No check findings."));else for(let p of h){let u=p.severity==="error"?"bad":p.severity==="warning"?"warn":"faint",y=document.createElement("div");y.className="bp-mgmt-group-head";let E=document.createElement("span");E.className=`bp-mgmt-dot bp-tone-bg-${u}`;let v=document.createElement("span");v.className="bp-mgmt-flex1",v.textContent=`${s(p.source)} · ${p.rule}`;let g=document.createElement("span");g.className=`bp-tone-${u}`,g.textContent=String(p.n),y.append(E,v,g),l.appendChild(y);for(let w of p.rows??[]){let x=document.createElement("div");x.className="bp-mgmt-row"+(this.checksSelectedId===w.id?" active":"");let S=document.createElement("div");if(S.textContent=Ee(w.title??""),x.appendChild(S),w.names||this.checksSelectedId===w.id){let L=document.createElement("div");L.className="bp-mgmt-row-sub";let P=document.createElement("span");if(P.className="bp-dim bp-mgmt-flex1",P.textContent=w.names??"",L.appendChild(P),this.checksSelectedId===w.id){let N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn accent",N.textContent=f("gpui.mgmt.checks.fix","Fix with agent"),N.addEventListener("click",(F)=>{F.stopPropagation();let U={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};this.cb.hub.rpc("kicad.checks.fix",{project:U.project,id:w.id}).then((G)=>{let B={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Ut(U,B))return;if(G.text)this.cb.onSendText(G.text),this.checksStatus="Sent to agent",this.render()}).catch((G)=>{let B={watchGen:this.watchGen,project:this.project,threadId:this.cb.getThreadId(),threadGen:this.cb.getThreadGen()};if(!Ut(U,B))return;this.checksStatus=G instanceof Error?G.message:"Could not send finding",this.render()})}),L.appendChild(N)}x.appendChild(L)}x.addEventListener("click",()=>{this.checksSelectedId=w.id,this.cb.hub.rpc("kicad.checks.focus",{project:this.project,id:w.id}).catch(()=>{}),this.render()}),l.appendChild(x)}}return e.appendChild(l),e}renderLife(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("life");if(!t)return e.appendChild(this.makeEmpty("Reading lifecycle…")),e;let n=document.createElement("div");n.className="bp-mgmt-head";let i=t.counts??{};for(let a of["active","nrnd","eol"]){let d=i[a]??0,l=Ft(a),h=document.createElement("span");h.className=d>0?`bp-tone-${l.tone}`:"bp-mgmt-faint",h.textContent=`${l.label} ${d}`,n.appendChild(h)}if((i.unknown??0)>0){let a=document.createElement("span");a.className="bp-mgmt-faint",a.textContent=`${i.unknown} unknown`,n.appendChild(a)}if(t.since){let a=document.createElement("span");a.className="bp-mgmt-flex1";let d=document.createElement("span");d.className="bp-mgmt-faint",d.textContent=`since ${Ct(t.since)} (${t.samples??0})`,n.append(a,d)}e.appendChild(n);let s=document.createElement("div");s.className="bp-mgmt-rows",s.setAttribute("data-testid","mgmt-life-rows");let r=t.bom?.cost??[],o=t.bom?.instock??[],c=t.bom?.lines??0;if(r.length===0)s.appendChild(this.makeEmpty(c===0?"No line has an MPN or fab part number to follow yet.":"No reading of the fab's stock yet: the BOM panel's lookups start it."));else{let a=r[r.length-1],d=o[o.length-1],l=document.createElement("div");l.className="bp-mgmt-note bp-dim",l.textContent=`Parts/board: ${tt(a[1])} · ${Math.round(d?.[1]??0)}/${c} lines in stock (${Ct(a[0])})`,s.appendChild(l)}for(let a of t.parts??[]){let d=this.lifeSelectedKey===a.key,l=Ft(a.lifecycle??"unknown"),h=document.createElement("div");h.className="bp-mgmt-row"+(d?" active":"");let p=document.createElement("div");p.className="bp-mgmt-row-line";let u=document.createElement("span");u.className="bp-mgmt-strong",u.textContent=xt(a.refs??[],14);let y=document.createElement("span");y.className="bp-mgmt-flex1 bp-dim",y.textContent=a.mpn||a.key;let E=document.createElement("span");if(E.className=`bp-tone-${l.tone}`,E.textContent=l.label,p.append(u,y,E),typeof a.stock==="number"){let v=document.createElement("span");v.className="bp-dim",v.textContent=et(a.stock),p.appendChild(v)}if(h.appendChild(p),d){let v=document.createElement("div");if(v.className="bp-mgmt-row-sub bp-mgmt-faint",this.lifePartLoading)v.textContent=f("gpui.mgmt.life.reading","Reading its history…");else if(this.lifePartSamples&&this.lifePartSamples.length>0){let g=this.lifePartSamples[this.lifePartSamples.length-1];v.textContent=`${this.lifePartSamples.length} samples · latest ${g.at?Ct(g.at):""}`+(typeof g.stock==="number"?` · stock ${et(g.stock)}`:"")+(typeof g.price==="number"?` · ${tt(g.price)}`:"")}else v.textContent=f("gpui.mgmt.life.nopart","No reading of this part yet.");h.appendChild(v)}h.addEventListener("click",()=>{if(this.lifeSelectedKey===a.key){this.lifeSelectedKey="",this.lifePartSamples=null,this.render();return}this.lifeSelectedKey=a.key,this.lifePartSamples=null,this.lifePartLoading=!0,this.render(),this.cb.hub.rpc("mgmt.life.part",{project:this.project,key:a.key}).then((v)=>{if(this.lifeSelectedKey!==a.key)return;this.lifePartLoading=!1,this.lifePartSamples=Array.isArray(v.samples)?v.samples:[],this.render()}).catch(()=>{if(this.lifeSelectedKey!==a.key)return;this.lifePartLoading=!1,this.lifePartSamples=[],this.render()})}),s.appendChild(h)}return e.appendChild(s),e}renderPlan(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("plan");if(!t)return e.appendChild(this.makeEmpty("Reading the routing plan…")),e;let n=(a,d)=>{let l=this.watchGen,h=this.project;this.planStatus="",this.cb.hub.rpc(a,{pro:h,...d}).catch((p)=>{if(l!==this.watchGen||h!==this.project)return;this.planStatus=p instanceof Error?p.message:"Plan action refused",this.render()})};if(t.empty)return e.appendChild(this.makeEmpty("No routing plan for this board.")),e;let i=document.createElement("div");i.className="bp-mgmt-head";let s=t.awaiting??0,r=document.createElement("span");if(r.className="bp-mgmt-flex1 "+(s>0?"bp-tone-warn":"bp-dim"),r.textContent=s>0?`${s} awaiting approval`:"Nothing awaits your approval",i.appendChild(r),!t.live){let a=document.createElement("span");a.className="bp-mgmt-faint",a.textContent=f("gpui.mgmt.plan.saved","saved plan"),i.appendChild(a)}if(s>0){let a=document.createElement("button");a.type="button",a.className="bp-mgmt-btn",a.textContent=f("gpui.mgmt.plan.all","Approve all"),a.addEventListener("click",()=>n("plan.approve",{layer:"",ids:[],approve:!0})),i.appendChild(a)}if(t.routing){let a=document.createElement("button");a.type="button",a.className="bp-mgmt-btn",a.textContent=f("gpui.mgmt.plan.stop","Stop routing"),a.addEventListener("click",()=>n("plan.stop",{})),i.appendChild(a)}let o=document.createElement("button");if(o.type="button",o.className="bp-mgmt-btn",o.textContent=this.planHideDone?"Show done":"Hide done",o.addEventListener("click",()=>{this.planHideDone=!this.planHideDone,this.render()}),i.appendChild(o),e.appendChild(i),this.planStatus){let a=document.createElement("div");a.className="bp-mgmt-note bp-tone-bad",a.textContent=this.planStatus,e.appendChild(a)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-plan-rows");for(let a of t.layers??[]){let d=a.items??[],l=document.createElement("div");l.className="bp-mgmt-group-head";let h=document.createElement("span");h.className="bp-mgmt-strong",h.textContent=a.layer;let p=document.createElement("span");if(p.className="bp-dim bp-mgmt-flex1",p.textContent=`${a.role?`${a.role} · `:""}${a.done??0}/${d.length} done`,l.append(h,p),a.status!=="approved"&&d.length>0){let u=document.createElement("button");u.type="button",u.className="bp-mgmt-btn",u.textContent=f("gpui.mgmt.plan.layer","Approve layer"),u.addEventListener("click",()=>n("plan.approve",{layer:a.layer,ids:[],approve:!0}));let y=document.createElement("button");y.type="button",y.className="bp-mgmt-btn",y.textContent=f("gpui.mgmt.plan.reject","Reject"),y.addEventListener("click",()=>n("plan.approve",{layer:a.layer,ids:[],approve:!1})),l.append(u,y)}c.appendChild(l);for(let u of d){if(this.planHideDone&&Ln(u))continue;let y=document.createElement("div");y.className="bp-mgmt-row";let E=document.createElement("div");E.className="bp-mgmt-row-line";let v=document.createElement("span");v.className="bp-mgmt-flex1"+(u.state==="blocked"?" bp-tone-bad":u.state==="edited"?" bp-tone-warn":""),v.textContent=`${u.name||u.id}${u.locked?" \uD83D\uDD12":""}`;let g=document.createElement("span");g.className="bp-dim",g.textContent=u.kind==="plane"?u.reference?`ref ${u.reference}`:"":`${u.nets??0} nets`;let w=document.createElement("span");if(w.className=u.state==="blocked"?"bp-tone-bad":"bp-dim",w.textContent=Nn(u),E.append(v,g,w),u.state==="proposed"||u.state==="edited"){let x=document.createElement("button");x.type="button",x.className="bp-mgmt-btn",x.textContent="✓",x.addEventListener("click",(L)=>{L.stopPropagation(),n("plan.approve",{layer:"",ids:[u.id],approve:!0})});let S=document.createElement("button");S.type="button",S.className="bp-mgmt-btn",S.textContent="✗",S.addEventListener("click",(L)=>{L.stopPropagation(),n("plan.approve",{layer:"",ids:[u.id],approve:!1})}),E.append(x,S)}y.appendChild(E),y.addEventListener("click",()=>n("plan.focus",{id:u.id})),c.appendChild(y)}}return e.appendChild(c),e}renderFab(){let e=document.createElement("div");e.className="bp-mgmt-body";let t=this.getPanelData("fab");if(!t)return e.appendChild(this.makeEmpty("Reading the fab's profile…")),e;if(t.error){let w=document.createElement("div");return w.className="bp-mgmt-note bp-tone-warn",w.textContent=t.error,e.appendChild(w),e}let n=(w,x={})=>{let S=this.watchGen,L=this.project;this.fabStatus="",this.cb.hub.rpc("fab.profile",{pro:L,action:w,...x}).catch((P)=>{if(S!==this.watchGen||L!==this.project)return;this.fabStatus=P instanceof Error?P.message:"Fab action failed",this.render()})},i=document.createElement("div");i.className="bp-mgmt-head";let s=document.createElement("span");s.className="bp-mgmt-strong",s.textContent=f("gpui.mgmt.fab.thefab","The fab");let r=document.createElement("span");r.className="bp-dim bp-mgmt-flex1",r.textContent=`rev ${t.rev??0}${t.updated?` · ${t.updated}`:""}${t.board?` · ${t.board}`:""} · ${Pn(t.tier??"")}`;let o=document.createElement("button");if(o.type="button",o.className="bp-mgmt-btn",o.textContent=f("gpui.mgmt.fab.refresh","Refresh"),o.addEventListener("click",()=>n("refresh")),i.append(s,r,o),e.appendChild(i),this.fabStatus){let w=document.createElement("div");w.className="bp-mgmt-note bp-tone-bad",w.textContent=this.fabStatus,e.appendChild(w)}let c=document.createElement("div");c.className="bp-mgmt-rows",c.setAttribute("data-testid","mgmt-fab-rows");let a=t.review,d=document.createElement("div");d.className="bp-mgmt-row";let l=document.createElement("div");l.className="bp-mgmt-row-line";let h=document.createElement("span"),p=(a?.counts?.error??0)>0;if(h.className="bp-mgmt-flex1 "+(p?"bp-tone-bad":"bp-dim"),h.textContent=a?.running?"Reviewing the design…":a?.at==null?"No design review yet":`${a.counts?.error??0} must-fix · ${a.counts?.warning??0} should-fix · ${a.counts?.info??0} notes${a.scope?` (${a.scope})`:""}`,l.appendChild(h),a?.at!=null){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=f("gpui.mgmt.fab.findings","Findings"),w.addEventListener("click",()=>this.togglePanel("checks")),l.appendChild(w)}if(!a?.running){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=f("gpui.mgmt.fab.reviewbtn","Review"),w.addEventListener("click",()=>n("review")),l.appendChild(w)}if(a?.judge){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=f("gpui.mgmt.fab.judge","Datasheets"),w.addEventListener("click",()=>{if(a.judge)this.cb.onSendText(a.judge)}),l.appendChild(w)}d.appendChild(l),c.appendChild(d);let u=Tn(t.drc?.state??""),y=document.createElement("div");y.className="bp-mgmt-row";let E=document.createElement("div");E.className="bp-mgmt-row-line";let v=document.createElement("span");if(v.className="bp-mgmt-flex1 "+(u.button?"bp-tone-warn":"bp-dim"),v.textContent=u.text,E.appendChild(v),u.button){let w=document.createElement("button");w.type="button",w.className="bp-mgmt-btn",w.textContent=u.button,w.addEventListener("click",()=>n("drc")),E.appendChild(w)}y.appendChild(E),c.appendChild(y);for(let w of t.conflicts??[]){let x=document.createElement("div");x.className="bp-mgmt-row bp-tone-bad",x.textContent=w,c.appendChild(x)}for(let w of t.suggestions??[]){let x=document.createElement("div");x.className="bp-mgmt-row";let S=document.createElement("div");S.className="bp-mgmt-row-line";let L=document.createElement("span");L.className="bp-mgmt-flex1 bp-tone-warn",L.textContent=`${w.label||w.key}: board ${w.project??"?"} mm, fab ${w.fab??"?"} mm`;let P=document.createElement("button");P.type="button",P.className="bp-mgmt-btn",P.textContent=f("gpui.mgmt.fab.apply","Apply"),P.addEventListener("click",()=>n("apply",{key:w.key})),S.append(L,P),x.appendChild(S),c.appendChild(x)}if(t.stackup?.chosen){let w=document.createElement("div");w.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let S=t.stackup.by==="proposed",L=document.createElement("span");if(L.className="bp-mgmt-flex1 "+(S?"bp-tone-warn":"bp-dim"),L.textContent=`${S?"Proposed: ":""}${t.stackup.chosen}${t.stackup.outer_50_mm?` (50Ω ${t.stackup.outer_50_mm} mm)`:""}`,x.appendChild(L),S){let P=t.stackup.chosen,N=document.createElement("button");N.type="button",N.className="bp-mgmt-btn",N.textContent=f("gpui.mgmt.fab.use","Use"),N.addEventListener("click",()=>n("stackup",{id:P})),x.appendChild(N)}w.appendChild(x),c.appendChild(w)}if(Array.isArray(t.changed)&&t.changed.length>0){let w=document.createElement("div");w.className="bp-mgmt-row";let x=document.createElement("div");x.className="bp-mgmt-row-line";let S=document.createElement("span");S.className="bp-mgmt-flex1 bp-tone-warn",S.textContent=f("gpui.mgmt.fab.changed","Changed since you last looked");let L=document.createElement("button");L.type="button",L.className="bp-mgmt-btn",L.textContent=f("gpui.mgmt.fab.seen","Seen"),L.addEventListener("click",()=>n("seen")),x.append(S,L),w.appendChild(x);for(let P of t.changed.slice(0,12)){let N=document.createElement("div");N.className="bp-mgmt-faint",N.textContent=P,w.appendChild(N)}c.appendChild(w)}let g=Array.isArray(t.limits)?t.limits:[];if(g.length>0){let w=document.createElement("div");w.className="bp-mgmt-group-head";let x=document.createElement("span");x.className="bp-mgmt-flex1",x.textContent=f("gpui.mgmt.fab.limit","Limit");let S=document.createElement("span");S.className="bp-mgmt-col",S.textContent=f("gpui.mgmt.fab.free","Base price");let L=document.createElement("span");L.className="bp-mgmt-col",L.textContent=f("gpui.mgmt.fab.extra","Costs more");let P=document.createElement("span");P.className="bp-mgmt-col bp-mgmt-col-read",P.textContent=f("gpui.mgmt.fab.readcol","Read"),w.append(x,S,L,P),c.appendChild(w);for(let F of g){let U=document.createElement("div");U.className="bp-mgmt-row";let G=document.createElement("div");G.className="bp-mgmt-row-line";let B=document.createElement("span");B.className="bp-mgmt-flex1"+(F.changed?" bp-tone-warn":F.inherited?" bp-dim":""),B.textContent=`${F.changed?"• ":""}${F.label??""}`;let xe=document.createElement("span");xe.className="bp-mgmt-col",xe.textContent=F.free?.text||"—";let X=document.createElement("span");X.className="bp-mgmt-col bp-dim",X.textContent=F.extra?.text||"—";let oe=F.free&&typeof F.free==="object"?F.free:F.extra,ie=oe?.fetched??"",Ae=Boolean(ie)&&oe?.confidence!=="published",ve=ie?Ae?`${ie}*`:ie:"—",he=oe?.source??"",T;if(he.startsWith("https://")&&ie){let Q=document.createElement("a");Q.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-read-link",Q.href=he,Q.target="_blank",Q.rel="noopener noreferrer",Q.textContent=ve,T=Q}else{let Q=document.createElement("span");Q.className="bp-mgmt-col bp-mgmt-col-read bp-mgmt-faint",Q.textContent=ve,T=Q}G.append(B,xe,X,T),U.appendChild(G),c.appendChild(U)}let N=document.createElement("div");N.className="bp-mgmt-note bp-mgmt-faint",N.textContent=f("gpui.mgmt.fab.derived","* worked out from the fab's page. Dimmed: the rigid board's value. A date opens the source page."),c.appendChild(N)}return e.appendChild(c),e}makeEmpty(e){let t=document.createElement("div");return t.className="bp-mgmt-note bp-mgmt-faint",t.textContent=e,t}}var Ii={trs:(e)=>e,t:(e,t)=>t},Ri=new Set(["/settle"]);function Bn(e,t){let n=t.trim().toLowerCase();if(!n)return 1;let i=e.toLowerCase();if(i.startsWith(n))return 3;if(i.split(/[^a-z0-9]+/i).some((o)=>o.startsWith(n)))return 2;let r=0;for(let o=0;o0||e.status==="waiting")return{urgency:3,want:"waiting"};if(e.status==="asking")return{urgency:2,want:"question"};if(e.status==="failed"||e.state==="failed")return{urgency:1,want:"failed"};return{urgency:0,want:""}}function Rn(e){let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function jn(e,t){let n=t.trim().split(/\s+/)[0]?.toLowerCase()??"";if(!n)return null;let i=e.toLowerCase();if(i.length!==e.length)return null;let s=i.indexOf(n);if(s<0)return null;return[s,s+n.length]}function Dn(e,t=Ii){let{t:n,trs:i}=t,s=[],r=new Map;for(let c of e.projects)r.set(c.id,c.title||c.id);let o=e.threads.find((c)=>c.id===e.selectedThreadId)??null;for(let c of e.railItems){if(c.state==="disabled"||c.id==="commands")continue;if(!o&&c.id!=="terminal")continue;s.push({label:i(c.label),place:c.id==="terminal"?"":"viewer",kind:"action",shortcut:c.key?c.key.toUpperCase():void 0,action:{type:"rail",id:c.id}})}if(o)s.push({label:o.pinned?n("menu.unpin","Unpin"):n("menu.pin","Pin"),place:"",kind:"action",action:{type:"thread-act",action:o.pinned?"unpin":"pin"}}),s.push({label:o.settled?n("phone.unsettle","Unsettle"):n("menu.settle","Settle"),place:"",kind:"action",action:{type:"thread-act",action:o.settled?"unsettle":"settle"}}),s.push({label:o.archived?n("palette.unarchive","Unarchive"):n("palette.archive","Archive"),place:"",kind:"action",action:{type:"thread-act",action:o.archived?"unarchive":"archive"}}),s.push({label:n("sheet.rename","Rename thread"),place:"",kind:"action",action:{type:"rename"}}),s.push({label:n("gpui.previous.thread","Previous thread"),place:"",kind:"action",action:{type:"prev-thread"}}),s.push({label:n("gpui.next.thread","Next thread"),place:"",kind:"action",action:{type:"next-thread"}});if(o)for(let c of e.commands){if(!c.word)continue;let a=Ri.has(c.word.toLowerCase());s.push({label:c.label?`${c.word} — ${c.label}`:c.word,place:c.desc||"command",kind:"command",action:{type:"command",word:c.word,runDirectly:a}})}s.push({label:n("gpui.improvements","Improvements"),place:"",kind:"action",action:{type:"improvements"}}),s.push({label:n("palette.settings","Settings"),place:"",kind:"action",action:{type:"settings"}}),s.push({label:n("gpui.fold.or.unfold.the.sidebar","Fold or unfold the sidebar"),place:"",kind:"action",action:{type:"sidebar"}});for(let c of e.projects)s.push({label:`New thread in ${c.title||c.id}`,place:"",kind:"action",action:{type:"new-thread",projectId:c.id}});for(let c of e.threads){let{urgency:a,want:d}=In(c);s.push({label:c.title||"Untitled thread",place:c.project?r.get(c.project)??"":"",kind:"thread",urgency:a,want:d,dotClass:Rn(c),action:{type:"thread",id:c.id}})}for(let c of e.bots){if(!c.name||!c.thread)continue;s.push({label:c.name,place:"",kind:"bot",action:{type:"thread",id:c.thread}})}return s}function Hn(e,t,n,i=[],s=10,r=14){let o=t.trim(),c=o.length===0,a=e.slice();if(n?.threads&&n.threads.length>0){let p=new Map;for(let y of i)p.set(y.id,y.title||y.id);let u=new Set;for(let y of a)if(y.action.type==="thread")u.add(y.action.id);for(let y of n.threads){if(!y.id||u.has(y.id))continue;u.add(y.id);let{urgency:E,want:v}=In(y);a.push({label:y.title||"Untitled thread",place:y.project?p.get(y.project)??"":"",kind:"thread",urgency:E,want:v,dotClass:Rn(y),action:{type:"thread",id:y.id}})}}let d=[];for(let p=0;p0)d.push({score:v,index:p,item:u})}d.sort((p,u)=>{if(c){let v=(u.item.urgency??0)-(p.item.urgency??0);if(v!==0)return v}if(u.score!==p.score)return u.score-p.score;let y=p.item.kind==="thread"?0:1,E=u.item.kind==="thread"?0:1;if(y!==E)return y-E;return p.index-u.index});let l=new Set,h=[];for(let p of d){let u=`${p.item.label}\x00${p.item.place}\x00${p.item.kind}`;if(l.has(u))continue;if(l.add(u),h.push(p.item),h.length>=s)break}if(n?.messages&&n.messages.length>0&&h.length{if(o.target===t)this.close()}),s.addEventListener("input",()=>{this.query=s.value,this.activeIdx=0,this.renderList(),this.scheduleSearch()}),s.addEventListener("keydown",(o)=>{if(o.key==="Escape")o.preventDefault(),o.stopPropagation(),this.close();else if(o.key==="ArrowDown"){if(o.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx+1)%this.listed.length,this.renderList(!0)}else if(o.key==="ArrowUp"){if(o.preventDefault(),this.listed.length>0)this.activeIdx=(this.activeIdx-1+this.listed.length)%this.listed.length,this.renderList(!0)}else if(o.key==="Enter")o.preventDefault(),this.runAt(this.activeIdx)}),this.backdrop=t,this.inputEl=s,this.listEl=r,this.root.appendChild(t),this.renderList(),this.query.trim().length>=2)this.scheduleSearch();s.focus()}close(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;if(this.searchGen++,this.backdrop)this.backdrop.remove(),this.backdrop=null,this.inputEl=null,this.listEl=null;this.prevFocus?.focus(),this.prevFocus=null}scheduleSearch(){if(this.searchTimer!==null)window.clearTimeout(this.searchTimer),this.searchTimer=null;let e=this.query.trim();if(e.length<2){this.searchHits=null,this.searchHitsQuery="";return}if(e===this.searchHitsQuery)return;let t=++this.searchGen;this.searchTimer=window.setTimeout(()=>{this.searchTimer=null,this.cb.onSearch(e).then((n)=>{if(t!==this.searchGen||!this.backdrop)return;if(this.query.trim()!==e)return;this.searchHits=n,this.searchHitsQuery=e,this.renderList()}).catch(()=>{})},180)}runAt(e){let t=this.listed[e];if(!t)return;this.close(),this.cb.onExecute(t.action)}renderList(e=!1){if(!this.listEl)return;let t=this.cb.getState(),n=Dn(t,{t:f,trs:Ee}),i=this.query.trim()===this.searchHitsQuery?this.searchHits:null;if(this.listed=Hn(n,this.query,i,t.projects),this.activeIdx>=this.listed.length)this.activeIdx=Math.max(0,this.listed.length-1);if(this.listed.length===0){let o=document.createElement("div");o.className="bp-palette-empty",o.textContent=f("gpui.nothing.matches","Nothing matches"),this.listEl.replaceChildren(o);return}let s=document.createDocumentFragment(),r=null;for(let o=0;o0)d.appendChild(document.createTextNode(c.label.slice(0,p)));let y=document.createElement("strong");if(y.className="bp-palette-mark",y.textContent=c.label.slice(p,u),d.appendChild(y),u{if(this.activeIdx!==o)this.activeIdx=o,this.updateActiveClass()}),a.addEventListener("click",()=>this.runAt(o)),o===this.activeIdx)r=a;s.appendChild(a)}if(this.listEl.replaceChildren(s),e&&r)r.scrollIntoView({block:"nearest"})}updateActiveClass(){if(!this.listEl)return;let e=this.listEl.children;for(let t=0;tthis.onPress(e.id));return r}render(){let e=this.items.filter((o)=>o.group!=="tools"),t=this.items.filter((o)=>o.group==="tools"),n=document.createElement("div");n.className="bp-rail-pages";let i;for(let o of e){if(i!==void 0&&o.group!==i){let c=document.createElement("div");c.className="bp-rail-rule",n.appendChild(c)}i=o.group,n.appendChild(this.renderButton(o))}let s=()=>{let o=n.scrollLeft>2,c=n.scrollLeft+n.clientWidth0){let o=document.createElement("div");o.className="bp-rail-tools";for(let c of t)o.appendChild(this.renderButton(c));r.appendChild(o)}this.el.replaceChildren(r)}}var Di=new Set(["resume","raise","retry","move","signin"]);function Un(e){if(!e||typeof e!=="object")return null;let t=e,n=(r)=>typeof r==="string"?r:"",i=(Array.isArray(t.actions)?t.actions:[]).filter((r)=>Boolean(r)&&typeof r==="object").map((r)=>({label:n(r.label),act:n(r.act),room:n(r.room),thread:n(r.thread)})),s={line:n(t.line),why:n(t.why),actions:i};return s.line||i.length?s:null}function kt(e,t){if(e.act==="board")return t&&e.room?{kind:"board",room:e.room}:null;if(e.act==="open")return e.thread?{kind:"thread",id:e.thread}:null;if(Di.has(e.act)){let n={room:e.room,action:e.act};if(e.thread)n.thread=e.thread;return{kind:"call",method:"swarm.act",params:n}}return null}function Gn(e){let t=e&&typeof e==="object"?e.open:void 0;if(typeof t!=="string")return null;let n=t.indexOf(":"),i=n<0?"":t.slice(n+1);if(!i)return null;if(t.startsWith("account:"))return{kind:"account",id:i};if(t.startsWith("thread:"))return{kind:"thread",id:i};return null}class Wt{backdrop;titleEl;closeBtn;bodyEl;cb;openState=!1;constructor(e,t){this.cb=t,this.backdrop=document.createElement("div"),this.backdrop.className="bp-modal-backdrop bp-hidden",this.backdrop.setAttribute("data-testid","settings-modal");let n=document.createElement("div");n.className="bp-modal";let i=document.createElement("div");i.className="bp-modal-head",this.titleEl=document.createElement("h2"),this.titleEl.textContent=`${f("palette.settings","Settings")} · Devices`,this.closeBtn=document.createElement("button"),this.closeBtn.type="button",this.closeBtn.className="icon",this.closeBtn.textContent="×",this.closeBtn.setAttribute("aria-label",f("common.close","Close")),this.closeBtn.addEventListener("click",()=>this.close()),i.append(this.titleEl,this.closeBtn),this.bodyEl=document.createElement("div"),this.bodyEl.className="bp-modal-body",n.append(i,this.bodyEl),this.backdrop.appendChild(n),this.backdrop.addEventListener("click",(s)=>{if(s.target===this.backdrop)this.close()}),e.appendChild(this.backdrop)}isOpen(){return this.openState}async open(){this.openState=!0,this.backdrop.classList.remove("bp-hidden"),await this.refresh()}close(){this.openState=!1,this.backdrop.classList.add("bp-hidden")}refreshLocale(){if(this.titleEl.textContent=`${f("palette.settings","Settings")} · Devices`,this.closeBtn.setAttribute("aria-label",f("common.close","Close")),this.openState)this.refresh()}async refresh(){let e=document.createDocumentFragment(),t=this.cb.onGetHome?.()??null;if(t){let d=document.createElement("section");d.className="bp-set-section",d.setAttribute("data-testid","settings-home");let l=document.createElement("div");l.className="bp-set-head",l.textContent=f("home.machine","Home machine");let h=document.createElement("div");h.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let u=document.createElement("div"),y=t.kind==="local"?`${t.name||"This machine"} (this machine)`:t.kind==="boat"?`${t.name||"Boat"} (Boat)`:t.name||"Linked machine";u.textContent=y,p.appendChild(u);let E=document.createElement("div");if(E.className="bp-dim",t.moving?.state==="moving")E.textContent=t.moving.step?f("home.moving.step","Moving home to {to}: {step}").replace("{to}",t.moving.to).replace("{step}",t.moving.step):f("home.moving","Moving home to {to}…").replace("{to}",t.moving.to);else if(t.moving?.state==="failed")E.textContent=t.moving.note?f("home.move.failed.note","Home move failed: {note}").replace("{note}",t.moving.note):f("home.move.failed","Home move failed");else if(!t.online)E.textContent=t.queuedCount>0?f("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",t.name||"home").replace("{n}",String(t.queuedCount)):f("home.away","Home ({name}) is away").replace("{name}",t.name||"home");else E.textContent="Online";if(p.appendChild(E),h.appendChild(p),t.canMoveHere&&this.cb.onMoveHomeHere){let v=document.createElement("button");v.type="button",v.className="primary",v.textContent=f("home.move.here","Make this machine the home"),v.setAttribute("data-testid","home-move-here-btn"),v.addEventListener("click",()=>{v.disabled=!0,this.cb.onMoveHomeHere?.().finally(()=>{this.refresh()})}),h.appendChild(v)}d.append(l,h),e.appendChild(d)}let n=document.createElement("section");n.className="bp-set-section";let i=document.createElement("div");i.className="bp-set-head",i.textContent="This browser";let s=document.createElement("div");s.className="bp-set-row";let r=document.createElement("span");r.className="bp-dim",r.textContent="Sign out and revoke this browser's session cookie.";let o=document.createElement("button");o.type="button",o.className="primary stop",o.textContent=f("agy.signout","Sign out"),o.setAttribute("data-testid","logout-btn"),o.addEventListener("click",()=>{o.disabled=!0,this.cb.onLogout().catch(()=>{r.setAttribute("role","alert"),r.textContent=f("web.logout.failed","Could not confirm sign-out. Try again."),o.disabled=!1})}),s.append(r,o),n.append(i,s),e.appendChild(n);let c=document.createElement("section");c.className="bp-set-section";let a=document.createElement("div");a.className="bp-set-head",a.textContent="Paired devices",c.appendChild(a);try{let d=await this.cb.onLoadDevices();if(d.length===0){let l=document.createElement("div");l.className="bp-dim",l.textContent="No devices listed.",c.appendChild(l)}else for(let l of d){let h=document.createElement("div");h.className="bp-set-row";let p=document.createElement("div");p.className="bp-set-info";let u=document.createElement("div");if(u.textContent=l.title||l.head||"",p.appendChild(u),l.text||l.detail){let y=document.createElement("div");y.className="bp-dim",y.textContent=l.text||l.detail||"",p.appendChild(y)}if(h.appendChild(p),l.buttons?.length){let y=document.createElement("div");y.className="bp-set-btns";for(let E of l.buttons){let v=document.createElement("button");if(v.type="button",E.primary)v.className="primary";if(E.danger)v.className="primary stop";v.textContent=E.label||f("common.remove","Remove"),v.addEventListener("click",()=>{v.disabled=!0,this.cb.onDevicesAct(E.action,E.value).finally(()=>{this.refresh()})}),y.appendChild(v)}h.appendChild(y)}c.appendChild(h)}}catch(d){let l=document.createElement("div");l.className="bp-dim";let h=d instanceof Error&&d.message?d.message:"Not available from a browser";l.textContent=`${h} — manage paired devices in Backplane › Settings › Devices on desktop or a paired phone.`,c.appendChild(l)}e.appendChild(c),this.bodyEl.replaceChildren(e)}}function le(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n)i.textContent=n;return i}function pt(e,t,n=!1){let i=le("button",n?"primary":"bp-btn-ghost",e);return i.type="button",i.addEventListener("click",t),i}function _t(e){return le("pre","bp-context-code",e)}function Hi(e){return le("span",`bp-context-badge ${e==="Native"||e==="Enabled"?"active":e==="Untrusted"||e==="Invalid"?"warn":""}`,Ee(e))}function St(e,t){let n=le("div","bp-context-row");return n.append(le("strong",void 0,e),Hi(t)),n}class qt{fetchContext;dialog=le("dialog","bp-context");title=le("h2");cwd=le("div","bp-context-path");tabs=le("div","bp-context-tabs");body=le("div","bp-context-body");notice=le("p","bp-context-notice");current;thread="";requestId=0;tab=0;busy=!1;constructor(e,t){this.fetchContext=t;let n=le("div","bp-context-head"),i=le("div");i.append(this.title,this.cwd),this.title.id="bp-context-title",this.dialog.setAttribute("aria-labelledby",this.title.id),this.notice.setAttribute("role","status"),n.append(i,pt(f("common.refresh","Refresh"),()=>{this.load()}),pt(f("common.close","Close"),()=>this.dialog.close())),this.dialog.append(n,this.tabs,this.notice,this.body),this.dialog.addEventListener("close",()=>{this.requestId++}),e.append(this.dialog)}open(e){if(this.thread=e,this.tab=0,this.current=void 0,this.busy=!1,this.title.textContent=f("thread.context.title","Context & Prompt"),this.cwd.textContent="",!this.dialog.open)this.dialog.showModal();this.render(),this.load()}async load(e){if(this.busy)return;let t=++this.requestId;this.busy=!0,this.notice.textContent=f("thread.context.reading","Reading thread context…"),this.render();try{let n=await this.fetchContext(this.thread,e);if(t!==this.requestId)return;this.current=n,this.cwd.textContent=n.cwd,this.notice.textContent=""}catch(n){if(t===this.requestId)this.notice.textContent=String(n)}finally{if(t===this.requestId)this.busy=!1,this.render()}}render(){let e=[f("thread.context.instructions","Instructions"),f("thread.context.system","System Prompt"),f("thread.context.skills","Skills"),f("thread.context.mcp","Project MCPs")];this.tabs.replaceChildren(...e.map((n,i)=>{let s=pt(n,()=>{this.tab=i,this.render(),this.body.scrollTop=0,this.tabs.children[i].focus()});return s.setAttribute("aria-pressed",String(i===this.tab)),s})),this.body.replaceChildren();let t=this.current;if(!t)return;switch(this.tab){case 0:this.instructions(t.instructions);break;case 1:this.prompt(t);break;case 2:this.skills(t.skills);break;case 3:this.mcps(t.mcp);break}}instructions(e){if(!e.length)this.body.append(le("p","bp-dim",f("thread.context.none.instructions","No project instructions found.")));for(let t of e){let n=le("details","bp-context-card"),i=le("summary");if(i.append(St(t.path,t.status),le("small","bp-dim",f("thread.context.size","{bytes} B · ≈{tokens} tokens",{bytes:t.bytes,tokens:t.estimated_tokens}))),n.append(i,_t(t.preview)),t.note)n.append(le("small","bp-dim",t.note));this.body.append(n)}}prompt(e){let t=le("div","bp-context-row"),n=pt(f("thread.context.copy","Copy prompt"),()=>{navigator.clipboard.writeText(e.prompt).then(()=>{this.notice.textContent=f("thread.context.copied","Prompt copied.")}).catch((i)=>{this.notice.textContent=String(i)})});t.append(le("p","bp-dim",f("thread.context.native.note","Backplane’s launch prompt. Native files are loaded by the provider.")),n),this.body.append(t);for(let[i,s]of[[f("thread.context.base","Backplane"),e.sections.base],[f("thread.context.injected.label","Injected project instructions"),e.sections.instructions],[f("thread.context.index","Available skills index"),e.sections.skills]])if(s)this.body.append(le("h3",void 0,i),_t(s))}skills(e){for(let t of["Project","User","Bundled"]){let n=e.filter((i)=>i.scope===t);if(!n.length)continue;this.body.append(le("h3",void 0,Ee(t)));for(let i of n){let s=le("article","bp-context-card");s.append(St(i.name,i.status),le("p",void 0,i.description),le("small","bp-context-path",[i.source,i.provider,i.model].filter(Boolean).join(" · ")),le("small","bp-context-path",i.path)),this.body.append(s)}}}mcps(e){if(!e.length)this.body.append(le("p","bp-dim",f("thread.context.none.mcp","No project MCP configurations found.")));for(let t of e){let n=le("article","bp-context-card");n.append(St(t.path,t.state));for(let s of t.servers){let r=s.url||[s.command,...s.args].map((o)=>JSON.stringify(o)).join(" ");if(n.append(St(s.name,s.status),_t(r)),s.cwd)n.append(le("small","bp-context-path",s.cwd))}if(t.error)n.append(le("p","bp-warn",t.error));let i=t.state==="Untrusted"?"trust":t.state==="Enabled"?"disable":t.state==="Disabled"?"enable":"";if(i){let s=i==="trust"?f("thread.context.trust","Trust and enable"):i==="disable"?f("thread.context.disable","Disable"):f("thread.context.enable","Enable"),r=pt(s,()=>{this.load({action:i,path:t.path,sha256:t.sha256})},i==="trust");r.disabled=this.busy;let o=le("div","bp-context-actions");o.append(r),n.append(o)}this.body.append(n)}}}var On="http://www.w3.org/2000/svg";function Vn(){let e=document.createElementNS(On,"svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","14"),e.setAttribute("height","14"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.75"),e.setAttribute("aria-hidden","true"),e.classList.add("bp-folder-icon");let t=document.createElementNS(On,"path");return t.setAttribute("d","M3 6h6l2 2h10v11H3z"),e.appendChild(t),e}function Fi(e,t,n,i){let s=e||t||n||"";if(s==="active"||s==="working"||s==="running"||s==="run")return"bp-dot-work";if(s==="finished"||s==="done")return"bp-dot-done";if(s==="waiting"||s==="asking"||s==="blocked"||s==="needs"||s==="failed"||s==="fail"||s==="cut"||s==="interrupted"||s==="limit"||s==="monitoring"||(i??0)>0)return"bp-dot-need";return"bp-dot-idle"}function Wn(e){if(!e)return"";let t=e<10000000000?e*1000:e,n=Math.max(0,Math.floor((Date.now()-t)/1000));if(n<60)return"now";if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}class zt{el;hostLabel;homeBanner;filterInput;listEl;connEl;filterText="";showSettled=new Set;collapsedProjects=new Set;addShown=!1;sections=null;projects=[];threads=[];bots=[];rooms=[];selectedThreadId="";cb;needErr=new Map;needBusy=new Set;constructor(e,t){this.el=e,this.cb=t;let n=document.createElement("div");n.className="bp-side-host";let i=document.createElement("div");i.className="bp-side-host-left",this.hostLabel=document.createElement("span"),this.hostLabel.textContent="This computer";let s=document.createElement("span");s.className="bp-dim",s.textContent="›",i.append(this.hostLabel,s);let r=document.createElement("button");r.type="button",r.className="icon bp-side-collapse",r.textContent="‹",r.title="Collapse sidebar",r.setAttribute("aria-label","Collapse sidebar"),r.setAttribute("data-testid","sidebar-collapse"),r.addEventListener("click",()=>this.cb.onCollapseSidebar?.()),n.append(i,r);let o=document.createElement("div");o.className="bp-side-head",this.filterInput=document.createElement("input"),this.filterInput.type="search",this.filterInput.className="bp-input bp-side-search";let c=f("sidebar.search.projects","Search projects");this.filterInput.placeholder=c,this.filterInput.setAttribute("aria-label",c),this.filterInput.setAttribute("data-testid","sidebar-filter"),this.filterInput.addEventListener("input",()=>{this.filterText=this.filterInput.value.trim().toLowerCase(),this.render()});let a=document.createElement("button");a.type="button",a.className="icon bp-side-add",a.textContent="+",a.title=f("thread.new","New thread"),a.setAttribute("aria-label",f("thread.new","New thread")),a.setAttribute("data-testid","sidebar-new-thread"),a.addEventListener("click",()=>{let l=this.firstProjectId();if(l)this.cb.onNewThread(l)}),o.append(this.filterInput,a),this.homeBanner=document.createElement("div"),this.homeBanner.className="bp-side-home bp-hidden",this.homeBanner.setAttribute("data-testid","home-away-banner"),this.homeBanner.style.padding="6px 10px",this.homeBanner.style.fontSize="11px",this.homeBanner.style.borderBottom="1px solid var(--line, #2a2a2a)",this.listEl=document.createElement("div"),this.listEl.className="bp-side-list",this.listEl.setAttribute("data-testid","sidebar-list");let d=document.createElement("div");d.className="bp-side-footer",this.connEl=document.createElement("span"),this.connEl.className="bp-conn-status",this.connEl.textContent="Connecting…",this.connEl.setAttribute("data-testid","conn-status"),d.appendChild(this.connEl),this.el.append(n,o,this.homeBanner,this.listEl,d)}setHome(e){if(!e){this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";return}let t="",n=!1;if(e.moving?.state==="moving")t=e.moving.step?f("home.moving.step","Moving home to {to}: {step}").replace("{to}",e.moving.to).replace("{step}",e.moving.step):f("home.moving","Moving home to {to}…").replace("{to}",e.moving.to);else if(e.moving?.state==="failed")t=e.moving.note?f("home.move.failed.note","Home move failed: {note}").replace("{note}",e.moving.note):f("home.move.failed","Home move failed"),n=!0;else if(!e.online){let i=e.name||"home",s="";if(e.awaySince&&e.awaySince>0){let r=new Date(e.awaySince);s=`${String(r.getHours()).padStart(2,"0")}:${String(r.getMinutes()).padStart(2,"0")}`}if(s&&e.queuedCount>0)t=f("home.away.since.queued","Home ({name}) is away since {time} · {n} queued").replace("{name}",i).replace("{time}",s).replace("{n}",String(e.queuedCount));else if(s)t=f("home.away.since","Home ({name}) is away since {time}").replace("{name}",i).replace("{time}",s);else if(e.queuedCount>0)t=f("home.away.queued","Home ({name}) is away · {n} queued").replace("{name}",i).replace("{n}",String(e.queuedCount));else t=f("home.away","Home ({name}) is away").replace("{name}",i)}if(!t)this.homeBanner.classList.add("bp-hidden"),this.homeBanner.textContent="";else this.homeBanner.textContent=t,this.homeBanner.className=n?"bp-side-home bp-bad":"bp-side-home bp-dim",this.homeBanner.classList.remove("bp-hidden")}setHostName(e){this.hostLabel.textContent=e||"This computer"}setConnStatus(e,t){this.connEl.textContent=e,this.connEl.className=`bp-conn-status ${t}`.trim()}setData(e,t,n,i){this.projects=e,this.threads=t,this.bots=n,this.rooms=i,this.render()}setSections(e,t,n){this.sections=e,this.bots=t,this.rooms=n,this.render()}setSelected(e){this.selectedThreadId=e,this.render()}focusFilter(){this.filterInput.focus()}firstProjectId(){if(this.sections){for(let e of this.sections)if(e.kind==="projects"&&e.rows.length>0){let t=e.rows[0];if(t.id&&!t.off)return t.id}}return this.projects[0]?.id??""}refreshLocale(){let e=f("sidebar.search.projects","Search projects");this.filterInput.placeholder=e,this.filterInput.setAttribute("aria-label",e),this.render()}projectsHead(e){let t=document.createElement("div");if(t.className="bp-side-section-head",!this.cb.onAddProject||this.addShown)return t.textContent=e,t;this.addShown=!0,t.classList.add("bp-side-section-row");let n=document.createElement("span");n.textContent=e;let i=document.createElement("button");i.type="button",i.className="bp-side-sec-plus bp-side-sec-btn",i.textContent="+";let s=f("sidebar.add.project","Add project");return i.title=s,i.setAttribute("aria-label",s),i.setAttribute("data-testid","sidebar-add-project"),i.addEventListener("click",(r)=>{r.stopPropagation(),this.cb.onAddProject?.()}),t.append(n,i),t}renderSectionThreadRow(e,t){let n=document.createElement("div");if(n.className="bp-thread-row"+(e.id===this.selectedThreadId?" active":"")+(e.off?" bp-dim":""),n.setAttribute("data-thread-id",e.id),n.setAttribute("data-testid",`thread-row-${e.id}`),t){let h=document.createElement("span");h.className="bp-tree-branch",h.setAttribute("aria-hidden","true"),n.appendChild(h)}let i=document.createElement("span");i.className=`bp-dot ${Fi(e.status,e.word,e.state)}`;let s=document.createElement("div");if(s.className="bp-thread-title",s.textContent=e.title||"Untitled thread",n.append(i,s),e.word==="needs"){let h=document.createElement("span");if(h.className="bp-badge-need",h.textContent=e.want==="approval"?"!":"•",e.say)h.title=e.say;n.appendChild(h)}else if(e.ago){let h=document.createElement("span");if(h.className="bp-thread-age",h.textContent=e.ago,e.pinned)h.title=f("tools.pinned","Pinned");n.appendChild(h)}let r=e.nav||e.id;if(!e.off&&r&&!r.startsWith("@room:"))n.addEventListener("click",()=>this.cb.onSelectThread(r));let o=e.kind==="swarm"?Un(e.need):null;if(!o)return n;let c=document.createElement("div");c.className="bp-need-wrap";let a=document.createElement("div");a.className="bp-need"+(t?" nested":"")+(e.off?" bp-dim":""),a.setAttribute("data-testid",`need-${e.id}`);let d=document.createElement("span");d.className="bp-need-line",d.textContent=o.line,d.title=o.line,a.appendChild(d);for(let h of o.actions){if(!kt(h,Boolean(this.cb.hasRoomView)))continue;let p=document.createElement("button");p.type="button",p.className="bp-need-btn",p.textContent=h.label,p.setAttribute("data-testid",`need-${h.act}-${e.id}`),p.disabled=Boolean(e.off)||this.needBusy.has(e.id)||!this.cb.onNeedAct,p.addEventListener("click",(u)=>{u.stopPropagation();let y=this.cb.onNeedAct;if(!y)return;this.needErr.delete(e.id),this.needBusy.add(e.id),this.render(),y(h).catch((E)=>{this.needErr.set(e.id,E instanceof Error?E.message:String(E))}).finally(()=>{this.needBusy.delete(e.id),this.render()})}),a.appendChild(p)}c.append(n,a);let l=this.needErr.get(e.id);if(l){let h=document.createElement("div");h.className="bp-need-err"+(t?" nested":""),h.textContent=l,c.appendChild(h)}return c}renderHubSections(e,t){let n=this.sections??[],i=new Set;for(let o of n)if(o.kind==="threads")for(let c of o.rows)i.add(c.id);else if(o.kind==="projects")for(let c of o.rows)for(let a of c.threads??[])i.add(a.id);let s=this.selectedThreadId?this.threads.find((o)=>o.id===this.selectedThreadId)??null:null,r=!1;for(let o of n)if(o.kind==="projects"&&o.rows.length>0)r=!0;for(let o of n){if(o.kind==="bub")continue;if(o.kind==="threads"){let c=o.rows.filter((l)=>{if(!t)return!0;return`${l.title} ${l.project??""}`.toLowerCase().includes(t)});if(c.length===0)continue;let a=document.createElement("section");a.className="bp-side-section",a.setAttribute("data-section-id",o.id);let d=document.createElement("div");d.className="bp-side-section-head",d.textContent=o.title.toUpperCase(),a.appendChild(d);for(let l of c)a.appendChild(this.renderSectionThreadRow(l,!1));e.appendChild(a);continue}if(o.kind==="projects"){let c=o.rows.filter((l)=>{if(!t)return!0;if((l.title||l.id).toLowerCase().includes(t))return!0;if((l.threads??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;if((l.swarms??[]).some((h)=>h.title.toLowerCase().includes(t)))return!0;return!1}),a=Boolean(o.fold&&o.toggle);if(t&&c.length===0)continue;if(!a&&o.id!=="active"&&c.length===0)continue;let d=document.createElement("section");if(d.className="bp-side-section",d.setAttribute("data-section-id",o.id),a){let l=document.createElement("button");l.type="button",l.className="bp-side-section-head bp-side-section-toggle";let h=o.count??c.length,p=o.open?"▾":"▸";if(l.textContent=`${o.title.toUpperCase()} (${h}) ${p}`,o.hint)l.title=o.hint;l.addEventListener("click",()=>{if(o.toggle)this.cb.onToggleSection?.(o.toggle)}),d.appendChild(l)}else d.appendChild(this.projectsHead(o.title.toUpperCase()));if(!a||o.open||Boolean(t)){if(o.id==="active"&&!r&&!t){let l=document.createElement("div");l.className="bp-side-empty",l.textContent="No projects yet.",d.appendChild(l)}for(let l of c){let h=document.createElement("div");if(h.className="bp-proj-group"+(l.off?" bp-dim":""),h.setAttribute("data-project-id",l.id),l.nav||l.key)h.setAttribute("data-project-key",l.nav||l.key||"");let p=document.createElement("div");p.className="bp-proj-head";let u=document.createElement("button");u.type="button",u.className="bp-proj-toggle";let y=Vn();if(l.css)y.style.color=l.css;let E=document.createElement("span");if(E.className="bp-proj-name",E.textContent=l.title||l.id,u.append(y,E),l.fold==="project-fold"&&l.nav)u.addEventListener("click",()=>this.cb.onToggleProjectFold?.(l.nav));let v=document.createElement("button");if(v.type="button",v.className="icon bp-proj-add",v.title=f("thread.new","New thread"),v.textContent="+",v.setAttribute("data-testid",`new-thread-${l.id}`),l.off)v.disabled=!0;if(v.addEventListener("click",(g)=>{g.stopPropagation(),this.cb.onNewThread(l.id)}),p.append(u,v),h.appendChild(p),!l.folded||Boolean(t)){let g=Boolean(t)&&(l.title||l.id).toLowerCase().includes(t);for(let w of l.swarms??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(w,!0))}for(let w of l.threads??[]){if(t&&!g&&!w.title.toLowerCase().includes(t))continue;h.appendChild(this.renderSectionThreadRow(w,!0))}if(s&&s.project===l.id&&!i.has(s.id)&&(!t||g||s.title.toLowerCase().includes(t)))h.appendChild(this.renderSectionThreadRow({id:s.id,title:s.title,status:s.status,state:s.state,ago:Wn(s.updatedAt),pinned:s.pinned,nav:s.id},!0))}d.appendChild(h)}}e.appendChild(d)}}}render(){this.addShown=!1;let e=document.createDocumentFragment(),t=this.filterText;if(this.sections!==null)this.renderHubSections(e,t);else{let n=new Map;for(let i of this.threads){if(i.archived||i.swarm)continue;if(t){if(!`${i.title} ${i.preview??""}`.toLowerCase().includes(t))continue}let s=n.get(i.project)??[];s.push(i),n.set(i.project,s)}if(e.appendChild(this.projectsHead("ACTIVE")),this.projects.length===0&&this.threads.length===0){let i=document.createElement("div");i.className="bp-side-empty",i.textContent="No projects yet.",e.appendChild(i)}for(let i of this.projects){let s=n.get(i.id)??[];if(t&&s.length===0&&!i.title.toLowerCase().includes(t))continue;let r=document.createElement("section");r.className="bp-proj-group",r.setAttribute("data-project-id",i.id);let o=document.createElement("div");o.className="bp-proj-head";let c=document.createElement("button");c.type="button",c.className="bp-proj-toggle";let a=this.collapsedProjects.has(i.id)&&!t,d=Vn();if(i.css)d.style.color=i.css;let l=document.createElement("span");l.className="bp-proj-name",l.textContent=i.title||i.id,c.append(d,l),c.addEventListener("click",()=>{if(this.collapsedProjects.has(i.id))this.collapsedProjects.delete(i.id);else this.collapsedProjects.add(i.id);this.render()});let h=document.createElement("button");if(h.type="button",h.className="icon bp-proj-add",h.title=f("thread.new","New thread"),h.textContent="+",h.setAttribute("data-testid",`new-thread-${i.id}`),h.addEventListener("click",(p)=>{p.stopPropagation(),this.cb.onNewThread(i.id)}),o.append(c,h),r.appendChild(o),!a)for(let p of s)r.appendChild(this.renderSectionThreadRow({id:p.id,title:p.title,status:p.status,state:p.state,ago:Wn(p.updatedAt),pinned:p.pinned,nav:p.id},!0));e.appendChild(r)}}if(!t){let n=document.createElement("section");n.className="bp-proj-group bp-bots-group";let i=document.createElement("div");i.className="bp-side-section-head bp-side-section-row";let s=document.createElement("span");s.textContent=f("tour.title.bots","Bots").toUpperCase();let r=document.createElement("span");r.className="bp-side-sec-plus",r.textContent="+",r.setAttribute("aria-hidden","true"),i.append(s,r),n.appendChild(i);for(let l of this.bots){let h=document.createElement("div");h.className="bp-thread-row"+(l.thread===this.selectedThreadId?" active":"");let p=document.createElement("span");if(p.className="bp-dot bp-dot-idle",l.color)p.style.backgroundColor=l.color;let u=document.createElement("div");u.className="bp-thread-title",u.textContent=`@${l.name}`,h.append(p,u),h.addEventListener("click",()=>this.cb.onSelectBot(l)),n.appendChild(h)}e.appendChild(n);let o=document.createElement("section");o.className="bp-proj-group";let c=document.createElement("div");c.className="bp-side-section-head bp-side-section-row";let a=document.createElement("span");a.textContent=f("bots.rooms","Rooms").toUpperCase();let d=document.createElement("span");d.className="bp-side-sec-plus",d.textContent="+",d.setAttribute("aria-hidden","true"),c.append(a,d),o.appendChild(c);for(let l of this.rooms){let h=document.createElement("div");h.className="bp-thread-row";let p=document.createElement("div");p.className="bp-thread-title",p.textContent=`#${l.name}`,h.appendChild(p),o.appendChild(h)}e.appendChild(o)}this.listEl.replaceChildren(e)}}function $i(e){try{return new URL(e,window.location.origin).searchParams.get("s")||""}catch{return""}}function ht(e){if(!e)return;for(let t of e.getTracks())try{t.stop()}catch{}}function Ui(e,t){if(t===16000){let r=new Int16Array(e.length);for(let o=0;o0?a/d:0));s[r]=l<0?l*32768:l*32767}return s}class Kt{hub;cb;active=!1;starting=!1;sessionGen=0;activeGen=0;abortedGen=0;threadId="";sessionKey="";stream=null;audioCtx=null;processor=null;pendingPcm=[];postChain=Promise.resolve();stopDrain=Promise.resolve();mark=0;constructor(e,t){this.hub=e,this.cb=t}isRecording(){return this.active||this.starting}async toggle(){if(this.active||this.starting)await this.stop();else await this.start()}async start(){if(this.active||this.starting)return;let e=this.cb.getThreadId();if(!e)return;if(!navigator.mediaDevices?.getUserMedia){this.cb.showError("Microphone access is not available in this browser.");return}let t=++this.sessionGen;this.starting=!0,this.threadId=e,this.sessionKey="",this.pendingPcm=[],this.mark=this.cb.getCaret(),this.cb.setRecording(!0);let n;try{n=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{if(t===this.sessionGen)this.starting=!1,this.cb.setRecording(!1),this.cb.showError("Microphone permission denied.");return}if(t!==this.sessionGen||this.cb.getThreadId()!==e){ht(n);return}if(this.stream=n,await this.stopDrain,t!==this.sessionGen||this.cb.getThreadId()!==e){if(ht(n),this.stream===n)this.stream=null;return}try{let i=await this.hub.rpc("voice.start",{thread:e,draft:this.cb.getDraft(),caret:this.mark});if(t!==this.sessionGen||this.cb.getThreadId()!==e){if(ht(n),this.stream===n)this.stream=null;if(!this.active&&!this.starting)this.hub.rpc("voice.stop",{thread:e}).catch(()=>{});return}let s=i.session||(i.path?$i(i.path):"");if(!s)throw Error("Hub did not return a voice session.");this.sessionKey=s,this.activeGen=t,this.starting=!1,this.active=!0,this.startCapture(n,t)}catch(i){if(t===this.sessionGen)this.cleanupAudio(),this.starting=!1,this.active=!1,this.cb.setRecording(!1),this.cb.showError(i instanceof Error?i.message:"Could not start voice dictation.");else if(ht(n),this.stream===n)this.stream=null}}async stop(){if(!this.active&&!this.starting)return;let e=this.activeGen,t=this.active,n=this.threadId,i=this.sessionKey;this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio();let r=this.stopDrain.then(async()=>{if(t&&i){let o=new Int16Array(this.pendingPcm);this.pendingPcm=[],this.enqueuePost(i,new Uint8Array(o.buffer),!0,e),await this.postChain}else this.pendingPcm=[];if(t&&n)await this.hub.rpc("voice.stop",{thread:n}).catch(()=>{})});this.stopDrain=r,await r}cancel(){if(!this.active&&!this.starting)return;let e=this.active,t=this.threadId;if(this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.starting=!1,this.active=!1,this.sessionKey="",this.pendingPcm=[],this.cb.setRecording(!1),this.cb.setLevel(0),this.cleanupAudio(),e&&t&&this.hub.getState()==="connected")this.hub.rpc("voice.stop",{thread:t}).catch(()=>{})}handleFrame(e){let t=String(e.ev??""),n=String(e.thread??"");if(n&&this.cb.getThreadId()&&n!==this.cb.getThreadId())return;if(t==="draft"&&typeof e.text==="string")this.cb.setDraft(e.text),this.mark=e.text.length;else if(t==="edit"){let i=this.cb.getDraft(),s=Number(e.del??0),r=String(e.ins??""),o=Math.max(0,Math.min(i.length,this.mark)),c=Math.max(0,o-s),a=i.slice(0,c)+r+i.slice(o);this.mark=c+r.length,this.cb.setDraft(a)}else if(t==="level")this.cb.setLevel(Math.max(0,Math.min(100,Number(e.v??0))));else if(t==="view"){let i=e.view;if(i&&i.on===!1&&(this.active||this.starting))this.stop()}}startCapture(e,t){let i=new(window.AudioContext||window.webkitAudioContext),s=i.createMediaStreamSource(e),r=i.createScriptProcessor(4096,1,1);r.onaudioprocess=(o)=>{if(!this.active||t!==this.sessionGen||!this.sessionKey)return;let c=Ui(o.inputBuffer.getChannelData(0),i.sampleRate);for(let a=0;a=3200){let a=new Int16Array(this.pendingPcm.splice(0,3200));this.enqueuePost(this.sessionKey,new Uint8Array(a.buffer),!1,t)}},s.connect(r),r.connect(i.destination),this.audioCtx=i,this.processor=r}enqueuePost(e,t,n,i){this.postChain=this.postChain.then(async()=>{if(i<=this.abortedGen)return;try{let s={"Content-Type":"application/octet-stream","X-Voice-Session":e};if(n)s["X-Voice-End"]="1";let r=await fetch("/voice/in",{method:"POST",credentials:"same-origin",headers:s,body:t});if(!r.ok&&!n&&i===this.sessionGen&&this.active)this.failUpload(`Voice upload failed (${r.status}).`)}catch{if(!n&&i===this.sessionGen&&this.active)this.failUpload("Voice upload failed.")}})}failUpload(e){this.abortedGen=Math.max(this.abortedGen,this.sessionGen),this.sessionGen++,this.active=!1,this.starting=!1,this.sessionKey="",this.pendingPcm=[],this.cleanupAudio(),this.cb.setRecording(!1),this.cb.setLevel(0),this.cb.showError(e)}cleanupAudio(){if(this.processor)this.processor.disconnect(),this.processor.onaudioprocess=null,this.processor=null;if(this.audioCtx)this.audioCtx.close().catch(()=>{}),this.audioCtx=null;ht(this.stream),this.stream=null}}var _n=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],qn=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],zn=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],Kn=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],Gi=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];function ut(e,t){let n=new Int32Array(16),i=0;for(let c=0;c0){if(n[a]++,a>i)i=a}}let s=new Int32Array(16),r=0;for(let c=1;c<=15;c++)s[c]=r,r+=n[c];let o=new Int32Array(r);for(let c=0;c0)o[s[a]++]=c}return{counts:n,symbols:o,maxBits:i}}var Oi=(()=>{let e=new Uint8Array(288);return e.fill(8,0,144),e.fill(9,144,256),e.fill(7,256,280),e.fill(8,280,288),ut(e,288)})(),Vi=(()=>{let e=new Uint8Array(32);return e.fill(5),ut(e,32)})();class Jt{win=new Uint8Array(32768);winPos=0;feed(e,t=16777216){let n=0,i=0,s=0,r=(h)=>{while(s=e.length)throw Error("truncated deflate frame");i|=e[n++]<>>=h,s-=h,p},o=(h)=>{let p=0,u=0,y=0;for(let E=1;E<=h.maxBits;E++){p|=r(1);let v=h.counts[E];if(p-v{let p=a+h;if(p>t)throw Error("inflated frame exceeds limit");if(p<=c.length)return;let u=c.length;while(u{d(1),c[a++]=h,this.win[this.winPos]=h,this.winPos=this.winPos+1&32767};while(n0){if(n>=e.length&&s<3)break;let h=r(1),p=r(2);if(p===0){if(i=0,s=0,n+4>e.length)throw Error("truncated stored block");let u=e[n]|e[n+1]<<8,y=e[n+2]|e[n+3]<<8;if(n+=4,(u^65535)!==y)throw Error("invalid stored block length");if(n+u>e.length)throw Error("truncated stored payload");d(u);for(let E=0;E=e.length)break}else if(p===1||p===2){let u=Oi,y=Vi;if(p===2){let E=r(5)+257,v=r(5)+1,g=r(4)+4,w=new Uint8Array(19);for(let N=0;NS)throw Error("code length overflow");for(let G=0;GS)throw Error("code length overflow");P+=F}else if(N===18){let F=r(7)+11;if(P+F>S)throw Error("code length overflow");P+=F}else throw Error("invalid code length symbol")}u=ut(L,E),y=ut(L.subarray(E),v)}while(!0){let E=o(u);if(E<256)l(E);else if(E===256)break;else{let v=E-257;if(v>=_n.length)throw Error("invalid length symbol");let g=_n[v]+(qn[v]?r(qn[v]):0),w=o(y);if(w>=zn.length)throw Error("invalid distance symbol");let x=zn[w]+(Kn[w]?r(Kn[w]):0);d(g);let S=this.winPos-x&32767;for(let L=0;L{this.stateListeners.delete(e)}}onFrame(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}onBinary(e){return this.binaryListeners.add(e),()=>{this.binaryListeners.delete(e)}}rpc(e,t={},n=20000){return new Promise((i,s)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){s(Error("Not connected to hub"));return}let r=this.nextId++,o=window.setTimeout(()=>{this.pending.delete(r),s(Error(`RPC timeout: ${e}`))},n);this.pending.set(r,{resolve:i,reject:s,timer:o}),this.ws.send(JSON.stringify({id:r,m:e,p:t}))})}setState(e){this.state=e;for(let t of this.stateListeners)t(e,this.hello)}rejectAllPending(e){for(let[,t]of this.pending)window.clearTimeout(t.timer),t.reject(Error(e));this.pending.clear()}openSocket(){if(this.closed)return;this.inflater=null;let t=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws?data=1&enc=json&z=deflate`,n=new WebSocket(t);n.binaryType="arraybuffer",this.ws=n;let i=(s)=>{let r;try{r=JSON.parse(s)}catch{return}if(r.t==="hub.restarting")this.restarting={reason:String(r.reason??""),build:String(r.build??""),text:String(r.text??""),at:Date.now()};if(r.t==="hello")this.restarting=null,this.hello=r,this.features=new Set(this.hello.features??[]),this.inflater=this.hello.z==="deflate"?new Jt:null,this.reconnectDelay=500,this.setState("connected");else if(r.t==="reply"&&typeof r.id==="number"){let o=this.pending.get(r.id);if(o)if(this.pending.delete(r.id),window.clearTimeout(o.timer),r.ok)o.resolve(r.result??{});else{let c=r.error,a=typeof c==="string"?c:c&&typeof c==="object"&&("message"in c)?String(c.message):"Request failed";o.reject(Error(a))}return}for(let o of this.frameListeners)o(r)};n.addEventListener("message",(s)=>{if(s.data instanceof ArrayBuffer){if(this.inflater){let r;try{r=this.inflater.feed(new Uint8Array(s.data))}catch{n.close();return}if(r.length>0&&r[0]===123)i(this.textDecoder.decode(r));else{let o=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength);for(let c of this.binaryListeners)c(o)}return}for(let r of this.binaryListeners)r(s.data);return}if(typeof s.data!=="string")return;i(s.data)}),n.addEventListener("close",(s)=>{if(this.ws===n)this.ws=null;if(this.rejectAllPending("Connection closed"),this.closed)return;if(s.code===4001||s.code===4401||s.code===1008){this.handleRevoked();return}this.probeSessionOrReconnect()}),n.addEventListener("error",()=>{})}async probeSessionOrReconnect(){try{let t=await fetch("/",{method:"GET",credentials:"same-origin",cache:"no-store"});if(t.status===401||t.status===403){this.handleRevoked();return}if(t.ok){if((await t.text()).includes('id="pair-root"')){this.handleRevoked();return}}}catch{}this.setState("reconnecting");let e=this.reconnectDelay;this.reconnectDelay=Math.min(8000,Math.round(this.reconnectDelay*1.6)),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.openSocket()},e)}handleRevoked(){this.closed=!0,this.setState("revoked"),window.location.replace("/")}}var Wi=new TextDecoder;function Jn(e){return e.length>7&&e[0]>=160&&e[0]<=183&&e[1]===1&&e[2]===100&&e[3]===112&&e[4]===108&&e[5]===111&&e[6]===116}function Yn(e){let t=0,n=0;function i(o){if(o<=23)return o;if(o===24){if(t>=e.length)return null;return e[t++]}if(o===25){if(t+2>e.length)return null;let c=e[t]<<8|e[t+1];return t+=2,c}if(o===26){if(t+4>e.length)return null;let c=(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;return t+=4,c}return null}function s(o){if(n++,o>32||n>400000||t>=e.length)return null;let c=e[t++],a=c>>5,d=i(c&31);if(d===null)return null;switch(a){case 0:return d;case 1:return-1-d;case 2:{if(t+d>e.length)return null;let l=e.subarray(t,t+d);return t+=d,l}case 3:{if(t+d>e.length)return null;let l=Wi.decode(e.subarray(t,t+d));return t+=d,l}case 4:{if(d>e.length)return null;let l=Array(d);for(let h=0;h=this.b.length)return this.ok=!1,0;let n=this.b[this.i++],i=7*t;if(i>=28&&(n&240)!==0)return this.ok=!1,0;if(e=(e|(n&127)<>>0,n<128)return e}return this.ok=!1,0}nextI32(){let e=this.nextU32();return e>>>1^-(e&1)}}function Qn(e){let t=0xcbf29ce484222325n,n=0x100000001b3n,i=0xffffffffffffffffn;for(let s=0;stypeof e[E]==="number"?e[E]:v,n=t("l",0),i=t("c",0),s=t("a",255)/255,r=t("m",1),o=t("w",0),c=o/2,a=r===0&&o!==0,d=e.d instanceof Uint8Array?e.d:new Uint8Array(0),l=new Xn(d),h=[],p=[],u=0,y=0;while(l.more()){let E=l.nextU32(),v=h.length,g=1/0,w=1/0,x=-1/0,S=-1/0;if(r===2)u=u+l.nextI32()|0,y=y+l.nextI32()|0,h.push(u,y),g=x=u,w=S=y;else{let P=Math.min(l.nextU32(),1048576);for(let N=0;Nx)x=u;if(yS)S=y}}let L=(h.length-v)/2;if(L>0){let P=r===2||L===1?2:r===0?0:1,N=r===0?0:c;p.push({info:E,x0:g-N,y0:w-N,x1:x+N,y1:S+N,at:v,n:L,kind:P})}}return{layer:n,color:i,alpha:s,mode:r,r:c,own:a,pts:new Float32Array(h),pieces:p}}function Zn(e,t,n){let i=(o)=>Array.isArray(o)&&o.length>=4?[Number(o[0])||0,Number(o[1])||0,Number(o[2])||0,Number(o[3])||0]:[0,0,0,0],s=Array.isArray(e.cs)?e.cs:[],r=[];for(let o=0;o=0&&c0){n.delete(c.h),n.set(c.h,a);while(n.size>1024){let d=n.keys().next().value;if(d!==void 0)n.delete(d);else break}}}}return{key:typeof e.key==="string"?e.key:"",fam:typeof e.fam==="string"?e.fam:"",base:typeof e.base==="string"?e.base:"",box:i(e.box),edge:i(e.edge),thick:typeof e.thick==="number"?e.thick:1600,note:typeof e.note==="string"?e.note:"",warn:typeof e.warn==="number"?e.warn!==0:!1,chunks:r}}function ei(e,t,n,i=!0){if(n.width<=0||n.height<=0||n.naturalWidth<=0||n.naturalHeight<=0)return null;let s=Math.min(n.width/n.naturalWidth,n.height/n.naturalHeight),r=n.naturalWidth*s,o=n.naturalHeight*s,c=n.left+(n.width-r)/2,a=i?n.top:n.top+(n.height-o)/2,d=(e-c)/r,l=(t-a)/o;if(d<0||d>1||l<0||l>1)return null;return{x:Math.max(0,Math.min(1000,Math.round(d*1000))),y:Math.max(0,Math.min(1000,Math.round(l*1000)))}}var ti=[["Enter","Enter"],["Tab","Tab"],["Bksp","Backspace"],["Esc","Escape"],["↑","ArrowUp"],["↓","ArrowDown"],["←","ArrowLeft"],["→","ArrowRight"]];function ni(e){let t=e.trim();if(!t)return"";if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t))return t;return`https://${t}`}class Xt{tail=Promise.resolve();enqueue(e){let t=this.tail.then(e,e);return this.tail=t.catch(()=>{}),t}}function ii(e,t,n){let i=!0,s=!1,r=!1,o="",c=!1,a=!1,d=-1,l=null,h=new Xt,p=document.createElement("div");p.className="bp-pane bp-browser-pane",p.setAttribute("data-testid","pane-browser");let u=document.createElement("div");u.className="bp-pane-bar bp-browser-nav";function y(_,z,A){let ne=document.createElement("button");if(ne.type="button",ne.className="bp-v-btn",ne.textContent=_,ne.setAttribute("data-testid",z),A)ne.title=A;return ne}let E=y("←","browser-back","Back"),v=y("→","browser-forward","Forward"),g=y("↻","browser-reload","Reload"),w=document.createElement("form");w.className="bp-browser-url-form";let x=document.createElement("input");x.type="text",x.className="bp-browser-input",x.placeholder="https://…",x.autocomplete="off",x.spellcheck=!1,x.setAttribute("data-testid","browser-url");let S=y("Go","browser-go","Navigate");S.type="submit",w.append(x,S);let L=y("Take over","browser-takeover");L.classList.add("is-primary"),u.append(E,v,g,w,L);let P=document.createElement("div");P.className="bp-browser-drive-bar",P.hidden=!0;let N=document.createElement("div");N.className="bp-browser-keys-row";let F=document.createElement("input");F.type="text",F.className="bp-browser-input",F.placeholder="Type text or press Enter/Tab/Arrows…",F.autocomplete="off",F.spellcheck=!1,F.setAttribute("data-testid","browser-keys");let U=y("Send","browser-type-send");N.append(F,U);let G=document.createElement("div");G.className="bp-browser-quick-keys";for(let[_,z]of ti){let A=y(_,`browser-key-${z}`);A.addEventListener("click",()=>he("press",{key:z})),G.append(A)}P.append(N,G);let B=document.createElement("div");B.className="bp-browser-err",B.setAttribute("data-testid","browser-error"),B.hidden=!0;let xe=document.createElement("div");xe.className="bp-browser-stage",xe.setAttribute("data-testid","browser-stage");let X=document.createElement("img");X.className="bp-browser-img",X.alt="Hub browser screen",X.draggable=!1,X.hidden=!0,X.setAttribute("data-testid","browser-frame");let oe=document.createElement("div");oe.className="bp-pane-empty",oe.setAttribute("data-testid","browser-empty"),oe.textContent="Loading browser screen…",xe.append(X,oe);let ie=document.createElement("div");ie.className="bp-browser-hint",ie.textContent="You have the page: click to tap, scroll to wheel, type in the key box. Hand it back when done.",ie.hidden=!0,p.append(u,P,B,xe,ie),e.replaceChildren(p);function Ae(_){B.textContent=_,B.hidden=!_}function ve(){P.hidden=!s,ie.hidden=!s,L.textContent=s?"Hand back":"Take over",L.setAttribute("data-testid",s?"browser-handback":"browser-takeover"),L.classList.toggle("is-on",s),X.classList.toggle("is-driving",s)}function he(_,z={},A){h.enqueue(async()=>{if(!i)return;Ae("");try{if(await t.hub.rpc("browser",{thread:n,op:_,...z}),!i)return;A?.(),de()}catch(ne){if(!i)return;Ae(ne instanceof Error?ne.message:String(ne))}})}function T(_){he("toolbar",{command:_},()=>{s=!0,ve()})}E.addEventListener("click",()=>T("back")),v.addEventListener("click",()=>T("forward")),g.addEventListener("click",()=>T("reload")),w.addEventListener("submit",(_)=>{_.preventDefault();let z=ni(x.value);if(!z)return;if(x.value=z,!s)he("takeover",{},()=>{s=!0,ve()});he("navigate",{url:z},()=>{s=!0,ve()})}),L.addEventListener("click",()=>{if(s)he("handback",{},()=>{s=!1,ve()});else he("takeover",{},()=>{s=!0,ve(),F.focus()})});function Q(){let _=F.value;if(!_)return;F.value="",he("type",{text:_})}U.addEventListener("click",Q),F.addEventListener("keydown",(_)=>{if(!s)return;if(_.key==="Enter"){if(_.preventDefault(),F.value)Q();he("press",{key:"Enter"});return}if(_.key==="Tab"||_.key==="Escape"||_.key==="ArrowUp"||_.key==="ArrowDown"||_.key==="ArrowLeft"||_.key==="ArrowRight"||_.key==="Backspace"&&F.value==="")_.preventDefault(),he("press",{key:_.key})}),X.addEventListener("click",(_)=>{if(!s||!r)return;let z=X.getBoundingClientRect(),A=ei(_.clientX,_.clientY,{left:z.left,top:z.top,width:z.width,height:z.height,naturalWidth:X.naturalWidth,naturalHeight:X.naturalHeight});if(!A)return;he("click",A)}),X.addEventListener("wheel",(_)=>{if(!s||!r)return;_.preventDefault();let z=Math.round(_.deltaX),A=Math.round(_.deltaY);if(z===0&&A===0)return;he("scroll",{dx:z,dy:A})},{passive:!1});async function de(){if(!i)return;if(c){a=!0;return}c=!0;try{do{a=!1,l=new AbortController;let _=await fetch(`/bots/${encodeURIComponent(n)}/screen.jpg`,{credentials:"same-origin",cache:"no-store",signal:l.signal});if(!i)return;if(_.ok){let z=await _.blob();if(!i)return;let A=URL.createObjectURL(z),ne=o;if(o=A,X.src=A,X.hidden=!1,oe.hidden=!0,r=!0,ne)URL.revokeObjectURL(ne)}else if(!r)X.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}while(i&&a)}catch{if(!i)return;if(!r)X.hidden=!0,oe.hidden=!1,oe.textContent="No browser page yet. An agent opens one when it needs the web."}finally{l=null,c=!1}}let se=t.hub.onFrame((_)=>{if(!i)return;if(_.t==="shot"&&_.bot===n){if(typeof _.n==="number"){if(_.n===d)return;d=_.n}de()}});return de(),{destroy(){if(i=!1,se(),l?.abort(),o)URL.revokeObjectURL(o),o=""}}}function D(e,t,n){let i=document.createElement(e);if(t)i.className=t;if(n!==void 0)i.textContent=n;return i}function At(e){if(!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;if(e<1048576)return`${Math.round(e/1024)} KB`;return`${(e/1048576).toFixed(1)} MB`}function ri(e){let t=e.lastIndexOf(".");return t>=0?e.slice(t+1).toLowerCase():""}function qi(e){return["png","jpg","jpeg","gif","webp","svg","bmp","ico"].includes(e)}function si(e){return["txt","md","markdown","json","toml","yaml","yml","xml","csv","tsv","rs","ts","tsx","js","mjs","cjs","jsx","css","html","htm","sh","bash","py","c","h","cc","cpp","hpp","go","java","kt","swift","rb","lua","sql","ini","cfg","conf","env","gitignore","lock","log","gbr","gtl","gbl","gts","gbs","gto","gbo","gm1","drl","pos","net","kicad_pro","kicad_prl","kicad_dru","kicad_sym","kicad_mod","kicad_wks"].includes(e)}function zi(e){let t=ri(e);if(t==="kicad_pcb")return"board";if(t==="kicad_sch")return"schematic";if(t==="step"||t==="stp"||t==="glb")return"mech";return null}function oi(e,t,n,i){let s=!0,r="",o="",c=D("div","bp-pane bp-files-pane");c.setAttribute("data-testid","pane-files");let a=D("div","bp-pane-bar"),d=D("div","bp-files-crumbs"),l=D("button","bp-v-btn","Refresh");l.type="button",l.addEventListener("click",()=>void v(r)),a.append(d,l);let h=D("div","bp-files-split"),p=D("div","bp-files-list");p.setAttribute("data-testid","files-list");let u=D("div","bp-files-preview");u.setAttribute("data-testid","files-preview"),u.append(D("div","bp-pane-empty","Select a file to preview")),h.append(p,u),c.append(a,h),e.replaceChildren(c);function y(){d.replaceChildren();let g=D("button","bp-crumb-btn","project");if(g.type="button",g.addEventListener("click",()=>void v("")),d.append(g),!r)return;let w=r.split("/").filter(Boolean),x="";for(let S of w){x=x?`${x}/${S}`:S;let L=x;d.append(D("span","bp-vh-sep","/"));let P=D("button","bp-crumb-btn",S);P.type="button",P.addEventListener("click",()=>void v(L)),d.append(P)}}async function E(g,w,x){o=g,u.replaceChildren();let S=D("div","bp-files-prev-head");S.append(D("span","bp-files-prev-name",g));let L=D("div","bp-files-prev-acts"),P=zi(w);if(P){let G=D("button","bp-v-btn is-primary",`Open in ${P}`);G.type="button",G.setAttribute("data-testid","files-open-viewer"),G.addEventListener("click",()=>i(P,g)),L.append(G)}let N=`/files/get?thread=${encodeURIComponent(n)}&path=${encodeURIComponent(g)}`,F=D("a","bp-v-btn","Download");F.href=N,F.download=w,L.append(F),S.append(L),u.append(S);let U=ri(w);if(qi(U)){let G=D("div","bp-files-img-wrap"),B=document.createElement("img");B.className="bp-files-img",B.alt=w,B.src=N,G.append(B),u.append(G);return}if(x>524288&&!si(U)){u.append(D("div","bp-pane-empty",`Binary file (${At(x)}). Use Download to save.`));return}if(si(U)||x<=65536){let G=D("div","bp-pane-empty","Loading…");u.append(G);try{let B=await fetch(N,{credentials:"same-origin"});if(!s||o!==g)return;if(!B.ok){G.textContent=`Could not load file (${B.status})`;return}if((B.headers.get("content-type")||"").startsWith("image/")){G.remove();let se=document.createElement("img");se.className="bp-files-img",se.alt=w,se.src=N,u.append(se);return}let X=262144,oe=[],ie=0,Ae=!1;if(B.body){let se=B.body.getReader();try{while(!0){let{done:_,value:z}=await se.read();if(_||!z)break;if(ie+z.byteLength>X){let A=X-ie;if(A>0)oe.push(z.subarray(0,A)),ie+=A;Ae=!0,await se.cancel();break}oe.push(z),ie+=z.byteLength}}finally{se.releaseLock()}}if(!s||o!==g)return;let ve=new Uint8Array(ie),he=0;for(let se of oe)ve.set(se,he),he+=se.byteLength;let T=!1;for(let se=0;seS.dir===L.dir?S.name.localeCompare(L.name):S.dir?-1:1),p.replaceChildren(),g){let S=D("button","bp-file-row is-dir");S.type="button",S.append(D("span","bp-file-icon","↰"),D("span","bp-file-name",".."));let L=g.includes("/")?g.slice(0,g.lastIndexOf("/")):"";S.addEventListener("click",()=>void v(L)),p.append(S)}if(x.length===0){p.append(D("div","bp-pane-empty","Empty folder"));return}for(let S of x){let L=g?`${g}/${S.name}`:S.name,P=D("button","bp-file-row"+(S.dir?" is-dir":"")+(L===o?" is-sel":""));P.type="button",P.setAttribute("data-testid",`file-row-${S.name}`),P.append(D("span","bp-file-icon",S.dir?"▸":"·"),D("span","bp-file-name",S.name),D("span","bp-file-size",S.dir?"":At(S.size))),P.addEventListener("click",()=>{if(S.dir)v(L);else p.querySelectorAll(".bp-file-row.is-sel").forEach((N)=>N.classList.remove("is-sel")),P.classList.add("is-sel"),E(L,S.name,S.size)}),p.append(P)}}catch(w){if(!s)return;p.replaceChildren(D("div","bp-pane-empty",w instanceof Error?w.message:String(w)))}}return v(""),{destroy(){s=!1}}}function ai(e,t,n){let i=!0,s=D("div","bp-pane bp-diff-pane");s.setAttribute("data-testid","pane-diff");let r=D("div","bp-pane-bar"),o=D("span","bp-diff-summary","Loading diff…"),c=D("button","bp-v-btn","Refresh");c.type="button",c.addEventListener("click",()=>void d()),r.append(o,c);let a=D("div","bp-diff-body");a.setAttribute("data-testid","diff-body"),s.append(r,a),e.replaceChildren(s);async function d(){o.textContent="Loading diff…",a.replaceChildren();try{let l=await t.hub.rpc("viewer.diff",{thread:n});if(!i)return;if(l?.nogit){o.textContent="Not a git repository",a.append(D("div","bp-pane-empty","This project is not a git repository."));return}let h=typeof l?.diff==="string"?l.diff:"";if(!h.trim()){o.textContent="Clean working tree",a.append(D("div","bp-pane-empty","No uncommitted changes."));return}let p=h.split(` +`),u=0,y=0,E=0,v=document.createDocumentFragment(),g=D("div","bp-diff-file");for(let w of p){if(w.startsWith("diff --git ")){if(g.childNodes.length>0)v.append(g);g=D("div","bp-diff-file"),u++;let x=w.match(/ b\/(.+)$/);g.append(D("div","bp-diff-file-head",x?x[1]:w));continue}if(w.startsWith("index ")||w.startsWith("--- ")||w.startsWith("+++ "))g.append(D("div","bp-diff-line is-meta",w));else if(w.startsWith("@@"))g.append(D("div","bp-diff-line is-hunk",w));else if(w.startsWith("+"))y++,g.append(D("div","bp-diff-line is-add",w));else if(w.startsWith("-"))E++,g.append(D("div","bp-diff-line is-del",w));else g.append(D("div","bp-diff-line",w))}if(g.childNodes.length>0)v.append(g);o.textContent=`${u||1} file${u===1?"":"s"} · +${y} -${E}`,a.append(v)}catch(l){if(!i)return;o.textContent="Diff unavailable",a.append(D("div","bp-pane-empty",l instanceof Error?l.message:String(l)))}}return d(),{destroy(){i=!1}}}function ci(e,t,n){let i=!0,s="checks",r=D("div","bp-pane bp-review-pane");r.setAttribute("data-testid","pane-review");let o=D("div","bp-pane-bar"),c=D("div","bp-review-tabs"),a=D("button","bp-v-btn is-on","Checks"),d=D("button","bp-v-btn","BOM"),l=D("button","bp-v-btn","Comments");a.type=d.type=l.type="button",c.append(a,d,l);let h=D("button","bp-v-btn","Refresh");h.type="button",h.addEventListener("click",()=>void E()),o.append(c,h);let p=D("div","bp-review-body");p.setAttribute("data-testid","review-body"),r.append(o,p),e.replaceChildren(r);function u(v){s=v,a.classList.toggle("is-on",s==="checks"),d.classList.toggle("is-on",s==="bom"),l.classList.toggle("is-on",s==="comments"),E()}a.addEventListener("click",()=>u("checks")),d.addEventListener("click",()=>u("bom")),l.addEventListener("click",()=>u("comments"));function y(v){let g=D("div","bp-review-md"),w=v.split(` +`),x=0;while(x{N.preventDefault();let F=L.value.trim();if(!F)return;P.disabled=!0,t.hub.rpc("review.comment",{thread:n,text:F}).then(()=>{L.value="",P.disabled=!1,E()},()=>{P.disabled=!1})}),p.append(S),x.length===0){p.append(D("div","bp-pane-empty","No review comments yet."));return}for(let N of x){let F=D("div","bp-review-comment"+(N.resolved?" is-resolved":"")),U=[N.by||"review",N.file,N.layer,N.item].filter(Boolean).join(" · ");F.append(D("div","bp-review-comment-meta",U),D("div","bp-review-comment-text",N.text)),p.append(F)}return}let v=await t.hub.rpc("review.page",{thread:n,page:s});if(!i)return;let g=v?.report||{};if(p.replaceChildren(),g.line||g.gate){let w=D("div","bp-review-gate",[g.gate,g.line].filter(Boolean).join(" · "));p.append(w)}if(g.err)p.append(D("div","bp-review-err",g.err));if(Array.isArray(g.tasks)&&g.tasks.length>0){let w=D("div","bp-review-tasks");g.tasks.forEach((x,S)=>{let L=D("label","bp-review-task"),P=document.createElement("input");P.type="checkbox",P.checked=!!(x.done??x.checked);let N=typeof x.index==="number"?x.index:S;P.addEventListener("change",()=>{t.hub.rpc("review.tick",{thread:n,index:N}).then(()=>void E(),()=>{})}),L.append(P,D("span",void 0,x.text||x.label||`Item ${S+1}`)),w.append(L)}),p.append(w)}if(g.md&&g.md.trim())p.append(y(g.md));else if(!g.err&&(!g.tasks||g.tasks.length===0))p.append(D("div","bp-pane-empty",`No ${s==="bom"?"BOM":"design checks"} report available.`))}catch(v){if(!i)return;p.replaceChildren(D("div","bp-pane-empty",v instanceof Error?v.message:String(v)))}}return E(),{destroy(){i=!1}}}function li(e,t){let n=e>>>16&255,i=e>>>8&255,s=e&255;return t>=0.999?`rgb(${n},${i},${s})`:`rgba(${n},${i},${s},${t.toFixed(3)})`}class Qt{canvas;ctx;frame=null;masks={off:0,dim:0,lift:255};highlights=new Set;lightTheme=!1;cx=0;cy=0;scale=0.0001;fittedKey="";fitW=0;fitH=0;userMoved=!1;dirty=!1;rafId=0;pointers=new Map;dragStart=null;pinchStart=null;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("2d");if(!n)throw Error("Canvas2D unavailable");this.ctx=n,this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick)}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}setFrame(e){if(this.frame=e,e&&e.key!==this.fittedKey)this.fittedKey=e.key,this.fit();else this.scheduleDraw()}setLayers(e){this.masks=e,this.scheduleDraw()}setHighlights(e){this.highlights.clear();for(let[t,n]of e)this.highlights.add(`${t}:${n}`);this.scheduleDraw()}presentMask(){if(!this.frame)return 0;let e=0;for(let t of this.frame.chunks)if(t.layer<32)e=(e|1<>>0;return e>>>0}presentColors(){let e=new Map;if(!this.frame)return e;for(let t of this.frame.chunks)if(!e.has(t.layer))e.set(t.layer,t.color);return e}applyFit(e,t){if(!this.frame||e<10||t<10)return;let n=this.frame.box,i=Math.max(n[2]-n[0],1000),s=Math.max(n[3]-n[1],1000);this.cx=(n[0]+n[2])*0.5,this.cy=(n[1]+n[3])*0.5,this.scale=Math.min(e/i,t/s)*0.92,this.fitW=e,this.fitH=t,this.userMoved=!1}fit(){if(!this.frame)return;this.userMoved=!1,this.fitW=0,this.fitH=0;let e=this.canvas.getBoundingClientRect();if(e.width>=10&&e.height>=10)this.applyFit(e.width,e.height);this.scheduleDraw()}zoomToBoxMm(e){let t=e[0]*1000,n=e[1]*1000,i=e[2]*1000,s=e[3]*1000,r=Math.max(i-t,1000),o=Math.max(s-n,1000),c=this.canvas.getBoundingClientRect(),a=Math.max(c.width,200),d=Math.max(c.height,200);this.cx=(t+i)*0.5,this.cy=(n+s)*0.5,this.scale=Math.min(a/r,d/o)*0.85,this.userMoved=!0,this.scheduleDraw()}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame(()=>{this.dirty=!1,this.rafId=0,this.draw()})}draw(){let e=this.canvas.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),i=Math.min(window.devicePixelRatio||1,2),s=Math.round(t*i),r=Math.round(n*i);if(this.canvas.width!==s||this.canvas.height!==r)this.canvas.width=s,this.canvas.height=r;let o=this.ctx;o.setTransform(i,0,0,i,0,0),o.fillStyle=this.lightTheme?"#f5f4ef":"#08090b",o.fillRect(0,0,t,n);let c=this.frame;if(!c)return;if(!this.userMoved&&t>=10&&n>=10&&(Math.abs(this.fitW-t)>2||Math.abs(this.fitH-n)>2))this.applyFit(t,n);let a=t*0.5,d=n*0.5,l=this.scale,h=this.cx,p=this.cy,u=h-a/l,y=h+a/l,E=p-d/l,v=p+d/l,{off:g,dim:w,lift:x}=this.masks,S=[],L=[];for(let N=0;N>>F&1)===1)continue;if(F===x)L.push(N);else S.push(N)}let P=S.concat(L);o.lineCap="round",o.lineJoin="round";for(let N=0;N>>U.layer&1)===1,B=U.alpha*(G?0.25:1);if(B<=0.01)continue;this.drawChunk(o,U,B,u,E,y,v,h,p,l,a,d)}if(this.highlights.size>0){o.fillStyle=this.lightTheme?"rgba(245,244,239,0.72)":"rgba(8,9,11,0.72)",o.fillRect(0,0,t,n);let N=this.lightTheme?"rgba(27,29,33,0.77)":"rgba(217,221,228,0.77)";for(let F=0;Fr||v.y1o)continue;if(v.n<3)continue;let g=(p[v.at]-c)*d+l,w=(p[v.at+1]-a)*d+h;e.moveTo(g,w);for(let x=1;x0)e.fill()}else if(t.mode===2){let y=Math.max(0.75,t.r*d);e.fillStyle=u,e.beginPath();let E=0;for(let v=0;vr||g.y1o)continue;let w=(p[g.at]-c)*d+l,x=(p[g.at+1]-a)*d+h;e.moveTo(w+y,x),e.arc(w,x,y,0,Math.PI*2),E++}if(E>0)e.fill()}else{e.strokeStyle=u,e.lineWidth=Math.max(1,t.r*2*d),e.beginPath();let y=0;for(let E=0;Er||v.y1o)continue;let g=(p[v.at]-c)*d+l,w=(p[v.at+1]-a)*d+h;if(v.n===1)e.moveTo(g,w),e.lineTo(g+0.01,w);else{e.moveTo(g,w);for(let x=1;x0)e.stroke()}}drawLitPieces(e,t,n,i,s,r,o,c,a,d,l,h,p){let u=t.pts,y=li(t.color,t.alpha);for(let E=0;Eo||v.y1c)continue;let g=(u[v.at]-a)*l+h,w=(u[v.at+1]-d)*l+p;if(v.kind===2){let x=Math.max(1.5,t.r*l);e.fillStyle=y,e.beginPath(),e.arc(g,w,x,0,Math.PI*2),e.fill(),e.strokeStyle=i,e.lineWidth=1.5,e.stroke()}else if(v.kind===0&&v.n>=3){e.fillStyle=y,e.beginPath(),e.moveTo(g,w);for(let x=1;x=0;l--){let h=n.chunks[l];if(h.layer<32&&(d>>>h.layer&1)===1)continue;for(let p=0;pu.x1+o||ru.y1+o)continue;let y=(u.x1-u.x0+1)*(u.y1-u.y0+1);if(y{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===1)this.dragStart={x:e.clientX,y:e.clientY,cx:this.cx,cy:this.cy,moved:!1},this.pinchStart=null;else if(this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchStart={dist:Math.hypot(n.x-t.x,n.y-t.y)||1,midX:(t.x+n.x)*0.5,midY:(t.y+n.y)*0.5,scale:this.scale,cx:this.cx,cy:this.cy},this.dragStart=null}};onPointerMove=(e)=>{if(!this.pointers.has(e.pointerId))return;if(this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pointers.size===2&&this.pinchStart){let[t,n]=Array.from(this.pointers.values()),i=Math.hypot(n.x-t.x,n.y-t.y)||1,s=(t.x+n.x)*0.5,r=(t.y+n.y)*0.5,o=i/this.pinchStart.dist,c=Math.max(0.0000001,Math.min(2,this.pinchStart.scale*o)),a=this.canvas.getBoundingClientRect(),d=this.pinchStart.midX-a.left-a.width*0.5,l=this.pinchStart.midY-a.top-a.height*0.5,h=s-a.left-a.width*0.5,p=r-a.top-a.height*0.5;this.scale=c,this.cx=this.pinchStart.cx+d/this.pinchStart.scale-h/c,this.cy=this.pinchStart.cy+l/this.pinchStart.scale-p/c,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(this.dragStart&&this.pointers.size===1){let t=e.clientX-this.dragStart.x,n=e.clientY-this.dragStart.y;if(Math.hypot(t,n)>3)this.dragStart.moved=!0;if(this.dragStart.moved)this.cx=this.dragStart.cx-t/this.scale,this.cy=this.dragStart.cy-n/this.scale,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()}};onPointerUp=(e)=>{let t=this.dragStart&&!this.dragStart.moved&&this.pointers.size===1;if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchStart=null;if(this.pointers.size===0)this.dragStart=null;if(t&&this.cbs.onPick){let n=this.canvas.getBoundingClientRect(),i=this.hitTest(e.clientX-n.left,e.clientY-n.top);this.cbs.onPick(i)}};onWheel=(e)=>{e.preventDefault();let t=this.canvas.getBoundingClientRect(),n=e.clientX-t.left-t.width*0.5,i=e.clientY-t.top-t.height*0.5,s=e.deltaY<0?1.16:0.8620689655172414,r=Math.max(0.0000001,Math.min(2,this.scale*s));this.cx+=n/this.scale-n/r,this.cy+=i/this.scale-i/r,this.scale=r,this.userMoved=!0,this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.remove()}}var di=[{id:"fit",label:"Fit"},{id:"iso",label:"Iso"},{id:"top",label:"Top"},{id:"bottom",label:"Bottom"},{id:"front",label:"Front"},{id:"right",label:"Right"},{id:"back",label:"Back"},{id:"left",label:"Left"}];function pi(e){switch(e){case"top":return{yaw:0,pitch:Math.PI*0.499};case"bottom":return{yaw:0,pitch:-Math.PI*0.499};case"front":return{yaw:0,pitch:0};case"right":return{yaw:Math.PI*0.5,pitch:0};case"back":return{yaw:Math.PI,pitch:0};case"left":return{yaw:-Math.PI*0.5,pitch:0};case"iso":case"fit":default:return{yaw:0.6,pitch:0.7}}}function Zt(e,t,n,i){if(!e||!t||!n||!i)return!1;if(!e.startsWith(t))return!1;let s=e.slice(t.length).split(` +`),r=(s[0]||"").split("\t");if(r[0]!=="git"||r[2]!==n)return!1;let o=s[1]||r.slice(4).join("\t");if(!o)return!1;let c=o.replace(/\\/g,"/"),a=i.replace(/\\/g,"/");if(a.startsWith("/")||/^[A-Za-z]:\//.test(a))return c===a;return c===a||c.endsWith(`/${a}`)}class en{refs=[];index=-1;lastCommit="";highlightEdits=!1;playing=!1;setRefs(e){if(this.refs=e,this.index>=e.length)this.index=-1,this.highlightEdits=!1}isLive(){return this.index<0||this.index>=this.refs.length}activeRef(){return this.isLive()?null:this.refs[this.index]}step(e){if(this.refs.length===0)return!1;let t=this.index;if(e>0)this.index=Math.min(this.refs.length-1,this.index+1);else this.index=Math.max(-1,this.index-1);if(this.index===-1)this.playing=!1,this.highlightEdits=!1;else this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0;return this.index!==t}selectCommit(e){if(!e)return this.goLive();let t=this.refs.findIndex((i)=>i.commit===e);if(t<0)return!1;let n=this.index!==t||!this.highlightEdits;return this.index=t,this.lastCommit=e,this.highlightEdits=!0,n}goLive(){let e=this.index!==-1||this.playing||this.highlightEdits;return this.index=-1,this.playing=!1,this.highlightEdits=!1,e}toggleHighlight(){if(this.highlightEdits)return this.goLive(),!1;if(this.refs.length===0)return!1;let e=this.lastCommit?this.refs.findIndex((t)=>t.commit===this.lastCommit):0;return this.index=e>=0?e:0,this.lastCommit=this.refs[this.index].commit,this.highlightEdits=!0,!0}compareRequest(){let e=this.activeRef();if(!e||!this.highlightEdits)return null;return{commit:e.commit,bits:0}}}var Ki=`#version 300 es precision highp float; out vec2 vUv; void main() { @@ -18,7 +18,7 @@ void main() { vUv = vec2(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5)); gl_Position = vec4(x, y, 0.0, 1.0); } -`,Oi=`#version 300 es +`,Ji=`#version 300 es precision highp float; in vec2 vUv; uniform vec3 uBgTop; @@ -35,7 +35,7 @@ void main() { vec3 lin = mix(uBgTop, uBgBot, clamp(vUv.y, 0.0, 1.0)); outColor = vec4(linearToSrgb(clamp(lin, 0.0, 1.0)), 1.0); } -`,Vi=`#version 300 es +`,Yi=`#version 300 es precision highp float; layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; @@ -53,7 +53,7 @@ void main() { vCol = aCol; gl_Position = uMvp * vec4(aPos, 1.0); } -`,Wi=`#version 300 es +`,Xi=`#version 300 es precision highp float; in vec3 vPos; in vec3 vNrm; @@ -149,8 +149,8 @@ void main() { rgb = rgb / (vec3(1.0) + max(rgb - vec3(0.8), vec3(0.0)) * 0.28); outColor = vec4(linearToSrgb(clamp(rgb, 0.0, 1.0)), alpha * uFade); } -`;function He(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var _i=[He(77),He(83),He(94)],qi=[He(53),He(58),He(67)],zi=[He(245),He(246),He(248)],Ki=[He(225),He(228),He(233)];function oi(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function ai(e,t,n){let i=oi(e,e.VERTEX_SHADER,t),s=oi(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let o=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(o)}return r}function Ji(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function Yi(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),o=new Float32Array(16);return o[0]=s/t,o[5]=s,o[10]=(i+n)*r,o[11]=-1,o[14]=2*i*n*r,o}function ci(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function li(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function Yt(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class Xt{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=ai(n,Gi,Oi),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=ai(n,Vi,Wi),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=qn(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,r=[n.buffer,i.buffer];if(s)r.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},r)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)r++;else o++;let c=r>0?new Float32Array(r*9):null,a=r>0?new Float32Array(r*9):null,d=r>0?new Float32Array(r*12):null,l=o>0?new Float32Array(o*9):null,h=o>0?new Float32Array(o*9):null,p=o>0?new Float32Array(o*12):null,u=0,y=0;for(let f=0;f>>24&255,S=1-x/255,L=(w>>>16&255)/255,T=(w>>>8&255)/255,N=(w&255)/255,F=f*9;if(x===0&&c&&a&&d){let U=u*9;for(let I=0;I<9;I++)c[U+I]=e[F+I],a[U+I]=t[F+I];let G=u*12;for(let I=0;I<3;I++)d[G+I*4]=L,d[G+I*4+1]=T,d[G+I*4+2]=N,d[G+I*4+3]=1;u++}else if(l&&h&&p){let U=y*9;for(let I=0;I<9;I++)l[U+I]=e[F+I],h[U+I]=t[F+I];let G=y*12;for(let I=0;I<3;I++)p[G+I*4]=L,p[G+I*4+1]=T,p[G+I*4+2]=N,p[G+I*4+3]=S;y++}}let E=c&&a&&d?this.createSubBatch(c,a,d,r*3):null,g=l&&h&&p?this.createSubBatch(l,h,p,o*3):null;if(!E&&!g)return null;return{opaque:E,translucent:g,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=ri(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),r=Math.min(window.devicePixelRatio||1,2),o=Math.round(i*r),c=Math.round(s*r);if(this.canvas.width!==o||this.canvas.height!==c)this.canvas.width=o,this.canvas.height=c;if(t.viewport(0,0,o,c),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let U=this.lightTheme?zi:_i,G=this.lightTheme?Ki:qi;t.uniform3f(this.uBgTop,U[0],U[1],U[2]),t.uniform3f(this.uBgBot,G[0],G[1],G[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let a=Math.cos(this.pitch),d=Math.sin(this.pitch),l=Math.cos(this.yaw),h=Math.sin(this.yaw),p=[this.target[0]+this.dist*a*h,this.target[1]-this.dist*a*l,this.target[2]+this.dist*d],u=ci([this.target[0]-p[0],this.target[1]-p[1],this.target[2]-p[2]]),y=Math.abs(u[2])>0.99?[0,1,0]:[0,0,1],E=ci(li(u,y)),g=li(E,u),f=new Float32Array([E[0],g[0],-u[0],0,E[1],g[1],-u[1],0,E[2],g[2],-u[2],0,-Yt(E,p),-Yt(g,p),Yt(u,p),1]),w=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),S=Yi(35*Math.PI/180,o/c,w,x),L=Ji(S,f);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,L),t.uniform3f(this.uEye,p[0],p[1],p[2]),t.uniform3f(this.uRight,E[0],E[1],E[2]),t.uniform3f(this.uUp,g[0],g[1],g[2]),t.uniform3f(this.uFwd,u[0],u[1],u[2]);let T=!1,N=[],F=[];for(let U of this.partBatches){let G=e-U.fadeStartMs,I=U.fadeStartMs===0?1:Math.min(1,Math.max(0,G/300));if(I<1){if(T=!0,I>0)F.push({batch:U,fade:I})}else N.push(U)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let U of N)this.drawSubBatch(U.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let U of N)this.drawSubBatch(U.translucent);for(let{batch:U,fade:G}of F)t.uniform1f(this.uFade,G),this.drawSubBatch(U.opaque),this.drawSubBatch(U.translucent);return t.depthMask(!0),t.bindVertexArray(null),T}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,r]=Array.from(this.pointers.values()),o=Math.hypot(r.x-s.x,r.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/o)));this.pinchDist=o,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),o=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*o*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var di=64,Xi=16777216;function Qi(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function ut(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function pi(e){switch(e){case"board":return v("viewer.board","Board");case"schematic":return v("viewer.schematic","Schematic");case"3d":return v("viewer.solid","3D");case"gerbers":return v("gpui.gerbers","Gerbers");case"mech":return v("viewer.mech","Mech");case"files":return v("viewer.files","Files");case"diff":return v("viewer.diff","Diff");case"review":return v("viewer.review","Review");case"browser":return v("bots.tab.browser","Browser");case"terminal":return v("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function Qt(e){return e==="board"||e==="schematic"||e==="gerbers"}function Zi(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function Zt(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let o=document.createElement("span");o.className="bp-vh-file",o.hidden=!0,i.append(s,r,o);let c=document.createElement("div");c.className="bp-vh-actions",n.append(i,c);let a=document.createElement("div");a.className="bp-solid-bar",a.setAttribute("data-testid","solid-presets-bar"),a.hidden=!0;let d=document.createElement("div");d.className="bp-v-banner",d.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let h=document.createElement("div");h.className="bp-v-stage";let p=document.createElement("div");p.className="bp-v-overlay",p.hidden=!0;let u=document.createElement("div");u.className="bp-v-layers",u.hidden=!0;let y=document.createElement("div");y.className="bp-v-info",y.hidden=!0,l.append(h,p,u,y);let E=document.createElement("div");E.className="bp-history-bar",E.setAttribute("data-testid","viewer-history-bar"),E.hidden=!0,e.replaceChildren(n,a,d,l,E);let g="",f="",w=0,x=!1,S=new Set,L=[],T=0,N=new Map,F=new Map,U={},G=[],I="",we="",X=!1,re=!1,ne=0,Se=!1,ge=0,he="",P=0,Q=null,le=null,ie=null,q=null,z=null,A=new Jt,te=0,ue=!1,Ae="",Me="",W="",ee="";document.addEventListener("click",(M)=>{if(!ue)return;if(M.target instanceof Node&&E.contains(M.target))return;ue=!1,be()}),document.addEventListener("keydown",(M)=>{if(ue&&M.key==="Escape")ue=!1,be()});function Te(){if(te)window.clearInterval(te),te=0;A.playing=!1}function qe(){let M=f==="3d"||f==="mech";if(a.hidden=!M,!M)return;if(a.childElementCount>0)return;for(let R of si){let B=document.createElement("button");B.type="button",B.className="bp-v-btn",B.textContent=R.label,B.setAttribute("data-testid",`solid-view-${R.id}`),B.addEventListener("click",()=>{ie?.setView(R.id)}),a.append(B)}let j=document.createElement("button");j.type="button",j.className="bp-v-btn",j.textContent="Snap view",j.setAttribute("data-testid","solid-snap"),j.addEventListener("click",()=>{if(!ie)return;ie.snapPng().then((R)=>{if(!R)return;let B=URL.createObjectURL(R),H=document.createElement("a");H.href=B;let K=(de()||f||"view").replace(/[^a-zA-Z0-9._-]/g,"_");H.download=`${K}-snap.png`,H.click(),setTimeout(()=>URL.revokeObjectURL(B),1000)})}),a.append(j)}async function xe(){if(!g||f!=="board"&&f!=="schematic")return;be();let M=A.compareRequest();if(!M){Ae="",Me="",W="",ee="",await $e(!1);return}let j=`${f}|${M.commit}|${M.bits}|${we}`;if(j===ee&&S.size>0){je(A.highlightEdits?`Comparing against ${A.activeRef()?.label||M.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${A.activeRef()?.label||M.commit.slice(0,7)}`,!1);return}let R=++w;S.clear(),N.clear(),Le(),x=!0,Ae="",Me=M.commit,W="",ee=j;try{let B=we||(f==="schematic"?U.sch:U.pcb)||"";if(!B){let oe=await t.hub.rpc("viewer.files",{thread:g});if(R!==w)return;U=oe||{},se(),B=(f==="schematic"?U.sch:U.pcb)||""}if(!B)throw Error(`Unable to resolve ${f} file path for compare`);let H=await t.hub.rpc("viewer.compare",{thread:g,kind:f,commit:M.commit,bits:M.bits,...we?{path:we}:{}});if(R!==w)return;let K=typeof H?.root==="string"?H.root:"",_=f==="schematic"?"1":"0";Ae=K?`${_}|${K}|diff -`:`${_}|`,Me=M.commit,W=B.startsWith("/")||/^[A-Za-z]:[\\/]/.test(B)||!K?B:`${K.replace(/\/+$/,"")}/${B.replace(/^\/+/,"")}`,x=!1;let ce=L;Le();for(let oe of ce)if(oe.kind==="bin")Ze(oe.buf);else Re(oe.key,oe.none,oe.retryable);je(A.highlightEdits?`Comparing against ${A.activeRef()?.label||M.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${A.activeRef()?.label||M.commit.slice(0,7)}`,!1)}catch(B){if(R!==w)return;x=!1,Ae="",Me="",W="",ee="",Le(),je(B instanceof Error?B.message:String(B),!0)}}function be(){let M=f==="board"||f==="schematic";if(E.hidden=!M,!M)return;let j=document.createElement("div");j.className="bp-history-group";let R=document.createElement("button");R.type="button",R.className="bp-v-btn",R.textContent="<",R.title="Older snapshot",R.disabled=A.refs.length===0||A.index>=A.refs.length-1,R.setAttribute("data-testid","history-prev"),R.addEventListener("click",()=>{if(Te(),A.step(1))xe()});let B=document.createElement("button");B.type="button",B.className="bp-v-btn"+(A.playing?" is-on":""),B.textContent=A.playing?"⏸":"▶",B.title=A.playing?"Pause history":"Play history",B.disabled=A.refs.length===0,B.setAttribute("data-testid","history-play"),B.addEventListener("click",()=>{if(A.playing){Te(),be();return}if(A.refs.length===0)return;if(A.playing=!0,A.isLive())A.index=A.refs.length-1,xe();else be();te=window.setInterval(()=>{if(!A.playing||f!=="board"&&f!=="schematic"){Te(),be();return}if(A.step(-1))xe();else Te(),be()},1400)});let H=document.createElement("button");H.type="button",H.className="bp-v-btn",H.textContent=">",H.title="Newer snapshot",H.disabled=A.isLive(),H.setAttribute("data-testid","history-next"),H.addEventListener("click",()=>{if(Te(),A.step(-1))xe()});let K=document.createElement("button");K.type="button",K.className="bp-v-btn"+(A.isLive()?" is-on":""),K.textContent="Live",K.setAttribute("data-testid","history-live"),K.addEventListener("click",()=>{if(Te(),A.goLive())je("",!1),xe()});let _=document.createElement("span");_.className="bp-history-label",_.setAttribute("data-testid","history-label");let ce=A.activeRef();_.textContent=ce?ce.label||ce.commit.slice(0,7):A.refs.length>0?`Live (${A.refs.length} saved)`:"Live",j.append(R,B,H,K,_);let oe=document.createElement("div");oe.className="bp-history-group";let fe=document.createElement("button");fe.type="button",fe.className="bp-v-btn"+(A.highlightEdits?" is-on":""),fe.textContent="Highlight edits",fe.disabled=A.refs.length===0,fe.setAttribute("data-testid","history-highlight"),fe.addEventListener("click",()=>{Te(),A.toggleHighlight(),xe()});let Ce=document.createElement("div");Ce.className="bp-history-menu-wrap";let pe=document.createElement("button");if(pe.type="button",pe.className="bp-v-btn"+(ue||!A.isLive()?" is-on":""),pe.disabled=A.refs.length===0,pe.setAttribute("data-testid","history-compare"),pe.setAttribute("aria-haspopup","menu"),pe.setAttribute("aria-expanded",String(ue)),pe.textContent=ce?`Compare: ${ce.label||ce.commit.slice(0,7)} ▾`:"Compare ▾",pe.addEventListener("click",(Ee)=>{Ee.stopPropagation(),ue=!ue,be()}),Ce.append(pe),ue&&A.refs.length>0){let Ee=document.createElement("div");Ee.className="bp-history-menu",Ee.setAttribute("role","menu"),Ee.setAttribute("data-testid","history-compare-menu");let Be=(Ie,rt,Ge)=>{let Oe=document.createElement("button");Oe.type="button",Oe.className="bp-history-menu-item"+(Ge?" is-active":""),Oe.setAttribute("role","menuitem"),Oe.setAttribute("data-commit",rt),Oe.textContent=Ie,Oe.addEventListener("click",()=>{if(ue=!1,Te(),A.selectCommit(rt)){if(A.isLive())je("",!1);xe()}else be()}),Ee.append(Oe)};Be("Live (working tree)","",A.isLive());for(let Ie of A.refs)Be(Ie.label||Ie.commit.slice(0,7),Ie.commit,ce?.commit===Ie.commit);Ce.append(Ee)}oe.append(fe,Ce),E.replaceChildren(j,oe)}async function Ve(M){if(!M)return;try{let j=await t.hub.rpc("viewer.refs",{thread:M});if(M!==g)return;A.setRefs(Array.isArray(j?.refs)?j.refs:[]),be()}catch{if(M!==g)return;A.setRefs([]),be()}}function it(){return document.documentElement.classList.contains("light")}let st=new MutationObserver(()=>{let M=it();le?.setTheme(M),ie?.setTheme(M),z?.setTheme(M)});st.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function ye(M,j="",R=!1){if(M==="none"){p.hidden=!0,p.replaceChildren();return}p.hidden=!1,p.className=`bp-v-overlay is-${M}`;let B=document.createElement("div");B.className="bp-v-state-card";let H=document.createElement("div");if(H.className="bp-v-state-msg",H.textContent=j,B.append(H),R){let K=document.createElement("button");K.type="button",K.className="bp-v-btn is-primary",K.textContent=v("tools.retry","Retry"),K.addEventListener("click",()=>void $e(!0)),B.append(K)}p.replaceChildren(B)}function je(M,j){d.textContent=M,d.hidden=!M,d.classList.toggle("is-warn",j)}function de(){if(we)return ut(we);if(f==="board"||f==="3d")return ut(U.pcb);if(f==="schematic")return ut(U.sch);if(f==="mech")return ut(I);return""}function se(){s.textContent=pi(f);let M=de();if(r.hidden=!M,o.hidden=!M,o.textContent=M,c.replaceChildren(),f==="mech"&&G.length>1){let R=document.createElement("select");R.className="bp-v-select",R.setAttribute("aria-label",v("viewer.mech","Mech"));for(let B of G){let H=document.createElement("option");H.value=B,H.textContent=ut(B),H.selected=B===I,R.append(H)}R.addEventListener("change",()=>{I=R.value,se(),$e(!1)}),c.append(R)}if(Qt(f)){let R=document.createElement("button");R.type="button",R.className="bp-v-btn"+(Se?" is-on":""),R.textContent=Q?.layerHead||"Layers",R.setAttribute("data-testid","viewer-layers-btn"),R.addEventListener("click",()=>{if(Se=!Se,u.hidden=!Se,R.classList.toggle("is-on",Se),Se)Z("","")}),c.append(R)}if(f==="board"||f==="schematic"||f==="3d"||f==="mech"||f==="gerbers"){let R=document.createElement("button");R.type="button",R.className="bp-v-btn",R.textContent="Fit",R.setAttribute("data-testid","viewer-fit-btn"),R.addEventListener("click",()=>{le?.fit(),ie?.fit()}),c.append(R)}if((f==="board"||f==="schematic")&&t.hub.hasFeature("follow")){let R=document.createElement("button");R.type="button",R.className="bp-v-btn"+(X&&!re?" is-on":""),R.textContent=X?re?v("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",R.setAttribute("data-testid","viewer-follow-btn"),R.addEventListener("click",()=>void We()),c.append(R)}let j=document.createElement("button");j.type="button",j.className="bp-v-btn bp-v-close",j.textContent="✕",j.title=v("common.close","Close"),j.setAttribute("aria-label",v("common.close","Close")),j.setAttribute("data-testid","viewer-close-btn"),j.addEventListener("click",()=>t.closeViewer()),c.append(j)}function Xe(){if(!Q){u.replaceChildren();return}let M=document.createDocumentFragment(),j=document.createElement("div");j.className="bp-v-layers-head";let R=document.createElement("span");if(R.textContent=Q.layerHead||"Layers",j.append(R),Q.layerReset){let _=document.createElement("button");_.type="button",_.className="bp-v-btn",_.textContent="Reset",_.addEventListener("click",()=>void Z("reset","")),j.append(_)}if(M.append(j),Q.layerModes){let _=document.createElement("div");_.className="bp-v-layers-modes",["All","Dim","Only"].forEach((ce,oe)=>{let fe=document.createElement("button");fe.type="button",fe.className="bp-v-btn"+(Q?.layerMode===oe?" is-on":""),fe.textContent=ce,fe.addEventListener("click",()=>void Z("mode",String(oe))),_.append(fe)}),M.append(_)}let B=le?.presentColors()??new Map,H=(Q.layerList||[]).concat(Q.layerMarks||[]),K=document.createElement("div");K.className="bp-v-layers-list";for(let _ of H){let ce=B.get(_.layer);if(ce===void 0)continue;let oe=document.createElement("div");oe.className="bp-v-layer-row"+(_.active?" is-focus":"");let fe=document.createElement("input");fe.type="checkbox",fe.checked=_.on!==!1,fe.addEventListener("change",()=>void Z("toggle",String(_.layer)));let Ce=document.createElement("span");Ce.className="bp-v-layer-swatch";let pe=ce>>>16&255,Ee=ce>>>8&255,Be=ce&255;Ce.style.background=_.on!==!1?`rgb(${pe},${Ee},${Be})`:`rgba(${pe},${Ee},${Be},0.2)`;let Ie=document.createElement("button");Ie.type="button",Ie.className="bp-v-layer-name",Ie.textContent=_.name,Ie.addEventListener("click",()=>void Z("pick",String(_.layer))),oe.append(fe,Ce,Ie),K.append(oe)}M.append(K),u.replaceChildren(M)}async function Z(M,j){if(!Qt(f))return;let R=w;try{let B=await t.hub.rpc("viewer.layers",{kind:f,present:P,off:ge,focus:he,...M?{action:M,value:j}:{}});if(R!==w||!B)return;ge=Number(B.own)||0,he=typeof B.focus==="string"?B.focus:"",Q=B;let H={off:Number(B.off)||0,dim:Number(B.dim)||0,lift:typeof B.lift==="number"?B.lift:255};if(le?.setLayers(H),se(),Se)Xe()}catch{}}async function Qe(){if(!X||re||!g||!t.hub.hasFeature("follow"))return;re=!0,se();try{await t.hub.rpc("viewer.follow",{thread:g,action:"pause"})}catch{}}async function We(){if(!g||!t.hub.hasFeature("follow"))return;let M=!X?"on":re?"resume":"off";try{let j=await t.hub.rpc("viewer.follow",{thread:g,action:M});if(X=!!j.on,re=!!j.paused,se(),j.on&&!j.paused&&j.focus&&Array.isArray(j.focus.box)&&j.focus.box.length===4&&(j.seq||0)>ne)ne=j.seq||ne,le?.zoomToBoxMm([j.focus.box[0],j.focus.box[1],j.focus.box[2],j.focus.box[3]])}catch{}}function ze(){y.hidden=!0,y.replaceChildren(),le?.setHighlights([])}function kt(M){let j=M.split(";").filter(Boolean),R=j.shift()||M,B=[],H="",K="";for(let Ce of j){if(Ce.startsWith("g="))continue;let pe=Ce.indexOf("=");if(pe>0){let Ee=Ce.slice(0,pe),Be=Ce.slice(pe+1);if((Ee==="ref"||Ee==="symbol")&&!H)H=Be;if(Ee==="net"&&!K)K=Be;B.push([Ee,Be])}else B.push([Ce,""])}let _=document.createElement("div");_.className="bp-v-info-head";let ce=document.createElement("span");ce.className="bp-v-info-title",ce.textContent=R;let oe=document.createElement("button");oe.type="button",oe.className="bp-v-info-x",oe.textContent="×",oe.setAttribute("aria-label","Clear selection"),oe.addEventListener("click",ze),_.append(ce,oe);let fe=document.createElement("div");fe.className="bp-v-info-rows";for(let[Ce,pe]of B){let Ee=document.createElement("span");Ee.className="bp-v-info-chip",Ee.textContent=pe?`${Ce}: ${pe}`:Ce,fe.append(Ee)}return y.replaceChildren(_,...B.length>0?[fe]:[]),y.hidden=!1,{ref:H||void 0,net:K||void 0}}async function Ue(M){if(!M){ze();return}let j=Array.from(S)[0]||"";if(!j)return;let R=w;try{let B=await t.hub.rpc("viewer.info",{key:j,at:M.at,idx:M.idx});if(R!==w)return;let H=typeof B.info==="string"?B.info:"";if(!H){ze();return}let{ref:K,net:_}=kt(H),ce=[];if(K)ce.push(["ref",K]);if(_)ce.push(["net",_]);let oe=[[M.at,M.idx]];for(let[fe,Ce]of ce){let pe=await t.hub.rpc("viewer.probe",{key:j,name:fe,value:Ce});if(R!==w)return;if(Array.isArray(pe.matches))for(let Ee of pe.matches)oe.push(Ee)}le?.setHighlights(oe)}catch{ze()}}function Fe(){q?.destroy(),q=null,z?.destroy(),z=null,le?.destroy(),le=null,ie?.destroy(),ie=null,h.replaceChildren(),Se=!1,u.hidden=!0,y.hidden=!0,y.replaceChildren(),je("",!1),ye("none")}function Le(){L=[],T=0}async function $e(M){if(!g||!f)return;let j=++w;if(S.clear(),x=!1,Le(),Fe(),se(),qe(),be(),(f==="board"||f==="schematic")&&g)Ve(g);if(Zi(f)){if(t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{}),f==="files")q=ei(h,t,g,(H,K)=>{if(f=H,we=K,H==="mech")I=K;$e(!1)});else if(f==="diff")q=ti(h,t,g);else if(f==="review")q=ni(h,t,g);else if(f==="browser")q=Xn(h,t,g);else if(f==="terminal")ye("loading","Loading terminal…"),import("/assets/terminal.js").then((K)=>{if(j!==w)return;if(ye("none"),K?.mountTerminalPane)z=K.mountTerminalPane(h,t,g,it());else ye("error","Terminal chunk missing",!0)},(K)=>{if(j!==w)return;ye("error",K instanceof Error?K.message:String(K),!0)});return}if(ye("loading","Loading…"),!U.root)try{let H=await t.hub.rpc("viewer.files",{thread:g});if(j!==w)return;U=H||{},se()}catch{}if(f==="gerbers"&&U.hasGerbers===!1){ye("empty","No Gerbers in this project",!1);return}let R=it();if(f==="3d"||f==="mech")ie=new Xt(h,{onStatus:(H,K)=>{if(K)ye("none"),je(H,!1);else if(H)ye("loading",H);else ye("none"),je("",!1)},onUserMove:()=>void Qe()}),ie.setTheme(R);else if(f==="board"||f==="schematic"||f==="gerbers")le=new zt(h,{onPick:(H)=>void Ue(H),onUserMove:()=>void Qe()}),le.setTheme(R);else{ye("empty",`${pi(f)} is not available in this viewer`,!1);return}let B={thread:g};if(M)B.force=!0;if(f==="mech"){if(G.length===0)try{let H=await t.hub.rpc("mech.list",{thread:g});if(j!==w)return;if(G=Array.isArray(H.parts)?H.parts:[],!I)I=H.primary||G[0]||"";se()}catch(H){if(j!==w)return;ye("error",H instanceof Error?H.message:String(H),!0);return}if(!I){ye("empty",v("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}B.kind="3d",B.path=I}else{if(B.kind=f,we&&(f==="board"||f==="schematic"))B.path=we;if(f==="3d"&&!M&&ie){let H=ie.keptToken();if(H)B.kept=H}if((f==="board"||f==="schematic"||f==="gerbers")&&!M&&t.hub.hasFeature("keptChunks")&&F.size>0)B.keptChunks=Array.from(F.keys())}x=!0,Ae="",Me="",W="",ee="";try{let H=await t.hub.rpc("viewer.watch",B);if(j!==w)return;S=new Set(Array.isArray(H.keys)?H.keys:[]),x=!1;let K=L;Le();for(let _ of K)if(_.kind==="bin")Ze(_.buf);else Re(_.key,_.none,_.retryable)}catch(H){if(j!==w)return;x=!1,S.clear(),Le();let K=H instanceof Error?H.message:String(H),_=/no gerbers|not in this project|another machine/i.test(K);ye(_?"empty":"error",K,!_)}}function Re(M,j,R){if(x){if(L.length{if(M.t==="plot"&&typeof M.none==="string"&&typeof M.key==="string")Re(M.key,M.none,M.retryable===!0)}),et=gt(()=>{if(f)se()}),bt=(M)=>{if(M.key==="Escape"&&f&&!y.hidden)ze()};return window.addEventListener("keydown",bt),{open(M,j){if(j!==g){if(g=j,U={},G=[],I="",N.clear(),X=!1,re=!1,ne=0,ge=0,he="",P=0,Q=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:j}).then((R)=>{if(j!==g)return;if(X=!!R.on,re=!!R.paused,ne=Number(R.seq)||0,f)se()}).catch(()=>{})}if(M!==f)Te(),A.goLive(),ge=0,he="",P=0,Q=null;f=M,we="",$e(!1)},reconcileHas(M){if(f&&!Qi(f,M))t.closeViewer()},close(){if(w++,x=!1,Te(),ue=!1,Ae="",Me="",W="",ee="",A.goLive(),a.hidden=!0,E.hidden=!0,Le(),g)t.hub.rpc("viewer.watch",{thread:g,kind:""}).catch(()=>{});f="",S.clear(),Fe()}}}var hi="http://www.w3.org/2000/svg";function mt(e){let t=document.createElementNS(hi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(hi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function es(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function ui(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function mi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function ts(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function bi(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let o=document.createElement("span");o.className="bp-crumb-sep bp-hide-phone",o.textContent="/";let c=document.createElement("span");c.className="bp-crumb-proj bp-hide-phone";let a=document.createElement("span");a.className="bp-crumb-sep bp-hide-phone",a.textContent="/";let d=document.createElement("span");d.className="bp-crumb-thread",d.setAttribute("data-testid","thread-title"),i.append(s,r,o,c,a,d);let l=document.createElement("div");l.className="bp-top-state bp-hide-phone bp-hidden";let h=document.createElement("span");h.className="bp-top-state-lbl",h.textContent="STATE";let p=document.createElement("span");p.className="bp-dot bp-dot-idle";let u=document.createElement("span");u.className="bp-top-state-word",l.append(h,p,u);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let E=document.createElement("button");E.type="button",E.className="bp-btn-ghost bp-top-act";let g=document.createElement("span");g.textContent=v("menu.pin","Pin"),E.append(mt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),g);let f=document.createElement("button");f.type="button",f.className="bp-btn-ghost bp-top-act";let w=document.createElement("span");w.textContent=v("menu.settle","Settle"),f.append(mt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),w);let x=document.createElement("div");x.className="bp-menu-wrap";let S=document.createElement("button");S.type="button",S.className="bp-btn-ghost bp-top-act",S.textContent="▾",S.title="Thread menu",S.setAttribute("aria-label","Thread menu"),S.setAttribute("data-testid","thread-menu-btn");let L=document.createElement("div");L.className="bp-popover bp-hidden",L.setAttribute("data-testid","thread-menu"),x.append(S,L),y.append(E,f,x);let T=document.createElement("div");T.className="bp-top-right";let N=document.createElement("button");N.type="button",N.className="bp-btn-ghost bp-top-act bp-hide-tablet",N.setAttribute("data-testid","improvements-btn");let F=document.createElement("span");F.textContent=v("gpui.improvements","Improvements"),N.append(mt(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),F);let U=document.createElement("button");U.type="button",U.className="bp-cmd-box bp-hide-tablet",U.textContent="> Jump or run a command";let G=document.createElement("button");G.type="button",G.className="icon bp-top-icon",G.title="Search",G.setAttribute("aria-label","Search"),G.appendChild(mt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let I=document.createElement("button");I.type="button",I.className="icon bp-top-icon",I.title=v("palette.settings","Settings"),I.setAttribute("aria-label",v("palette.settings","Settings")),I.setAttribute("data-testid","settings-btn"),I.appendChild(mt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),T.append(N,U,G,I),t.append(n,i,l,y,T);let we=document.createElement("div");we.className="bp-body";let X=document.createElement("aside");X.className="bp-sidebar",X.setAttribute("data-testid","sidebar");let re=document.createElement("main");re.className="bp-center";let ne=document.createElement("div");ne.className="bp-right-area bp-hidden",ne.setAttribute("data-testid","right-area");let Se=document.createElement("div");Se.className="bp-right-top";let ge=document.createElement("section");ge.className="bp-viewer-pane bp-hidden",ge.setAttribute("data-testid","viewer-pane"),Se.appendChild(ge),ne.appendChild(Se);let he=document.createElement("nav");he.className="bp-rail",he.setAttribute("aria-label","Viewer rail"),he.setAttribute("data-testid","viewer-rail"),we.append(X,re,ne,he),e.append(t,we);let P=new _t,Q=null,le=new Set,ie=0,q=null,z=[],A=[],te=[],ue=[],Ae=[],Me=[],W="",ee=0,Te=0,qe=null,xe=null,be="",Ve=null,it=20,st={},ye=new Map;function je(m,b){ye.delete(m),ye.set(m,b);while(ye.size>it){let C=ye.keys().next().value;if(C!==void 0)ye.delete(C);else break}}let de=new Ot(X,{onSelectThread:(m)=>{if(m===W&&qe!==null){X.classList.remove("bp-sidebar-open");return}_(m)},onNewThread:(m)=>{Ce(m)},onSelectBot:(m)=>{_(m.thread)},onThreadAct:(m,b)=>{Ge(m,b)},onToggleSection:(m)=>{if(le.has(m))le.delete(m);else le.add(m);B()},onToggleProjectFold:(m)=>{P.rpc("sidebar.act",{action:"project-fold",value:m}).then(()=>B()).catch(()=>{})},onCollapseSidebar:()=>{X.classList.remove("bp-sidebar-open"),X.classList.add("bp-sidebar-collapsed")},onNeedAct:async(m)=>{let b=xt(m,!1);if(!b)return;if(b.kind==="thread"){_(b.id);return}if(b.kind!=="call")return;let C=jn(await P.rpc(b.method,b.params));if(C?.kind==="thread")_(C.id);B()},hasRoomView:!1,onAddProject:()=>Fe.open({mode:"folder"})}),se=new It(re,{onLoadOlder:()=>{fe()},onGoToEntry:(m)=>{oe(m)},onAnswerAsk:(m,b)=>{P.rpc("ask.answer",{ask:m,answer:b}).catch(()=>{})},onToggleReview:(m)=>{if(!W)return;let b=ee;P.rpc("thread.review",{thread:W,on:m}).then((C)=>{if(b===ee)se.setReview(C.review??null)}).catch(()=>{})},onUnansweredAction:(m,b)=>{if(!W)return;if(m==="again"||m==="thread-again")P.rpc("thread.again",{thread:W,value:b}).catch(()=>{});else P.rpc("thread.act",{thread:W,action:m,value:b}).catch(()=>{})},onReplyEntry:(m)=>{if(!P.hasFeature("reply")){let b=(m.text||"").split(` +`;function $e(e){let t=e/255;return t<=0.04045?t/12.92:Math.pow((t+0.055)/1.055,2.4)}var Qi=[$e(77),$e(83),$e(94)],Zi=[$e(53),$e(58),$e(67)],es=[$e(245),$e(246),$e(248)],ts=[$e(225),$e(228),$e(233)];function hi(e,t,n){let i=e.createShader(t);if(!i)throw Error("createShader failed");if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){let s=e.getShaderInfoLog(i)||"shader compile error";throw e.deleteShader(i),Error(s)}return i}function ui(e,t,n){let i=hi(e,e.VERTEX_SHADER,t),s=hi(e,e.FRAGMENT_SHADER,n),r=e.createProgram();if(!r)throw Error("createProgram failed");if(e.attachShader(r,i),e.attachShader(r,s),e.linkProgram(r),e.deleteShader(i),e.deleteShader(s),!e.getProgramParameter(r,e.LINK_STATUS)){let o=e.getProgramInfoLog(r)||"program link error";throw e.deleteProgram(r),Error(o)}return r}function ns(e,t){let n=new Float32Array(16);for(let i=0;i<4;i++)for(let s=0;s<4;s++)n[i*4+s]=e[0+s]*t[i*4+0]+e[4+s]*t[i*4+1]+e[8+s]*t[i*4+2]+e[12+s]*t[i*4+3];return n}function is(e,t,n,i){let s=1/Math.tan(e*0.5),r=1/(n-i),o=new Float32Array(16);return o[0]=s/t,o[5]=s,o[10]=(i+n)*r,o[11]=-1,o[14]=2*i*n*r,o}function mi(e){let t=Math.hypot(e[0],e[1],e[2])||1;return[e[0]/t,e[1]/t,e[2]/t]}function bi(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function tn(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}class nn{canvas;gl=null;bgProg=null;bgVao=null;uBgTop=null;uBgBot=null;prog=null;uMvp=null;uEye=null;uRight=null;uUp=null;uFwd=null;uFade=null;worker=null;boardBatch=null;partBatches=[];activeKey="";lastMeshId="";nextJobId=1;partsTotal=0;partsDone=0;center=[0,0,0];target=[0,0,0];radius=50;dist=120;yaw=0.6;pitch=0.7;lightTheme=!1;dirty=!1;rafId=0;pointers=new Map;pinchDist=0;resizeObs;cbs;constructor(e,t={}){this.cbs=t,this.canvas=document.createElement("canvas"),this.canvas.className="bp-viewer-canvas",this.canvas.style.width="100%",this.canvas.style.height="100%",this.canvas.style.display="block",this.canvas.style.touchAction="none",e.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{antialias:!0,alpha:!1,preserveDrawingBuffer:!0});if(n)this.gl=n,this.bgProg=ui(n,Ki,Ji),this.bgVao=n.createVertexArray(),this.uBgTop=n.getUniformLocation(this.bgProg,"uBgTop"),this.uBgBot=n.getUniformLocation(this.bgProg,"uBgBot"),this.prog=ui(n,Yi,Xi),this.uMvp=n.getUniformLocation(this.prog,"uMvp"),this.uEye=n.getUniformLocation(this.prog,"uEye"),this.uRight=n.getUniformLocation(this.prog,"uRight"),this.uUp=n.getUniformLocation(this.prog,"uUp"),this.uFwd=n.getUniformLocation(this.prog,"uFwd"),this.uFade=n.getUniformLocation(this.prog,"uFade"),n.enable(n.DEPTH_TEST),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA);else this.cbs.onStatus?.("WebGL2 is unavailable in this browser");try{this.worker=new Worker("/assets/mesh-worker.js",{type:"module"}),this.worker.onmessage=(i)=>this.onWorkerMessage(i.data)}catch{this.cbs.onStatus?.("3D worker unavailable")}this.resizeObs=new ResizeObserver(()=>this.scheduleDraw()),this.resizeObs.observe(this.canvas),this.canvas.addEventListener("pointerdown",this.onPointerDown),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerUp),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("dblclick",this.onDblClick),this.canvas.addEventListener("contextmenu",this.onContextMenu)}keptToken(){return this.activeKey&&this.lastMeshId?`${this.activeKey} ${this.lastMeshId}`:""}setTheme(e){if(this.lightTheme!==e)this.lightTheme=e,this.scheduleDraw()}handleFrame(e){let t=typeof e.key==="string"?e.key:"";if(!t)return;if(e.mesh instanceof Uint8Array&&typeof e.n==="number"&&!e.part){this.activeKey=t,this.lastMeshId=Qn(e.mesh),this.clearParts(),this.cbs.onStatus?.("Building 3D model…");let n=new Uint8Array(e.mesh),i=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,s=[n.buffer];if(i)s.push(i.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"solid",key:t,n:e.n,mesh:n,faces:i},s);return}if(e.parts&&typeof e.parts==="object"&&!Array.isArray(e.parts)&&!(e.parts instanceof Uint8Array)){if(this.activeKey&&t!==this.activeKey)return;if(this.activeKey=t,this.clearParts(),this.partsTotal=typeof e.parts.of==="number"?e.parts.of:0,this.partsDone=0,this.partsTotal>0)this.cbs.onStatus?.(`Loading parts 0/${this.partsTotal}…`);this.scheduleDraw();return}if(typeof e.part==="string"&&e.mesh instanceof Uint8Array&&e.at instanceof Uint8Array&&typeof e.n==="number"){if(this.activeKey&&t!==this.activeKey)return;let n=new Uint8Array(e.mesh),i=new Uint8Array(e.at),s=e.faces instanceof Uint8Array?new Uint8Array(e.faces):void 0,r=[n.buffer,i.buffer];if(s)r.push(s.buffer);this.worker?.postMessage({id:this.nextJobId++,kind:"part",key:t,partId:e.part,n:e.n,mesh:n,at:i,faces:s,refs:Array.isArray(e.refs)?e.refs:[],done:typeof e.done==="number"?e.done:0},r)}}onWorkerMessage(e){if(e.error){this.cbs.onStatus?.(e.error);return}if(e.key!==this.activeKey||!this.gl)return;if(e.kind==="solid")this.deleteBatch(this.boardBatch),this.boardBatch=this.uploadBatch(e.positions,e.normals,e.colors,0),this.center=[e.center[0],e.center[1],e.center[2]],this.target=[e.center[0],e.center[1],e.center[2]],this.radius=e.radius,this.fit(),this.cbs.onStatus?.(""),this.scheduleDraw();else if(e.kind==="part"){let t=this.uploadBatch(e.positions,e.normals,e.colors,performance.now());if(t)this.partBatches.push(t);if(this.partsDone=e.done||this.partsDone+1,this.partsTotal>0&&this.partsDone>>24===0)r++;else o++;let c=r>0?new Float32Array(r*9):null,a=r>0?new Float32Array(r*9):null,d=r>0?new Float32Array(r*12):null,l=o>0?new Float32Array(o*9):null,h=o>0?new Float32Array(o*9):null,p=o>0?new Float32Array(o*12):null,u=0,y=0;for(let g=0;g>>24&255,S=1-x/255,L=(w>>>16&255)/255,P=(w>>>8&255)/255,N=(w&255)/255,F=g*9;if(x===0&&c&&a&&d){let U=u*9;for(let B=0;B<9;B++)c[U+B]=e[F+B],a[U+B]=t[F+B];let G=u*12;for(let B=0;B<3;B++)d[G+B*4]=L,d[G+B*4+1]=P,d[G+B*4+2]=N,d[G+B*4+3]=1;u++}else if(l&&h&&p){let U=y*9;for(let B=0;B<9;B++)l[U+B]=e[F+B],h[U+B]=t[F+B];let G=y*12;for(let B=0;B<3;B++)p[G+B*4]=L,p[G+B*4+1]=P,p[G+B*4+2]=N,p[G+B*4+3]=S;y++}}let E=c&&a&&d?this.createSubBatch(c,a,d,r*3):null,v=l&&h&&p?this.createSubBatch(l,h,p,o*3):null;if(!E&&!v)return null;return{opaque:E,translucent:v,fadeStartMs:i}}deleteSubBatch(e){let t=this.gl;if(!t||!e)return;t.deleteVertexArray(e.vao),t.deleteBuffer(e.posBuf),t.deleteBuffer(e.nrmBuf),t.deleteBuffer(e.colBuf)}deleteBatch(e){if(!e)return;this.deleteSubBatch(e.opaque),this.deleteSubBatch(e.translucent)}clearParts(){for(let e of this.partBatches)this.deleteBatch(e);this.partBatches=[]}fit(){this.setView("fit")}setView(e){let t=35*Math.PI/180;this.dist=this.radius/Math.sin(t*0.5)*1.15,this.target=[this.center[0],this.center[1],this.center[2]];let{yaw:n,pitch:i}=pi(e);this.yaw=n,this.pitch=i,this.scheduleDraw()}snapPng(){return this.draw(performance.now()),new Promise((e)=>{this.canvas.toBlob((t)=>e(t),"image/png")})}scheduleDraw(){if(this.dirty)return;this.dirty=!0,this.rafId=requestAnimationFrame((e)=>{if(this.dirty=!1,this.rafId=0,this.draw(e))this.scheduleDraw()})}drawSubBatch(e){if(!e||!this.gl)return;this.gl.bindVertexArray(e.vao),this.gl.drawArrays(this.gl.TRIANGLES,0,e.vertCount)}draw(e){let t=this.gl;if(!t||!this.prog)return!1;let n=this.canvas.getBoundingClientRect(),i=Math.max(1,Math.round(n.width)),s=Math.max(1,Math.round(n.height)),r=Math.min(window.devicePixelRatio||1,2),o=Math.round(i*r),c=Math.round(s*r);if(this.canvas.width!==o||this.canvas.height!==c)this.canvas.width=o,this.canvas.height=c;if(t.viewport(0,0,o,c),!this.boardBatch&&this.partBatches.length===0)return!1;if(t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),this.bgProg&&this.bgVao){t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.depthMask(!1),t.useProgram(this.bgProg);let U=this.lightTheme?es:Qi,G=this.lightTheme?ts:Zi;t.uniform3f(this.uBgTop,U[0],U[1],U[2]),t.uniform3f(this.uBgBot,G[0],G[1],G[2]),t.bindVertexArray(this.bgVao),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindVertexArray(null)}let a=Math.cos(this.pitch),d=Math.sin(this.pitch),l=Math.cos(this.yaw),h=Math.sin(this.yaw),p=[this.target[0]+this.dist*a*h,this.target[1]-this.dist*a*l,this.target[2]+this.dist*d],u=mi([this.target[0]-p[0],this.target[1]-p[1],this.target[2]-p[2]]),y=Math.abs(u[2])>0.99?[0,1,0]:[0,0,1],E=mi(bi(u,y)),v=bi(E,u),g=new Float32Array([E[0],v[0],-u[0],0,E[1],v[1],-u[1],0,E[2],v[2],-u[2],0,-tn(E,p),-tn(v,p),tn(u,p),1]),w=Math.max(0.05,this.dist*0.01),x=Math.max(this.dist*10,this.radius*20),S=is(35*Math.PI/180,o/c,w,x),L=ns(S,g);t.useProgram(this.prog),t.uniformMatrix4fv(this.uMvp,!1,L),t.uniform3f(this.uEye,p[0],p[1],p[2]),t.uniform3f(this.uRight,E[0],E[1],E[2]),t.uniform3f(this.uUp,v[0],v[1],v[2]),t.uniform3f(this.uFwd,u[0],u[1],u[2]);let P=!1,N=[],F=[];for(let U of this.partBatches){let G=e-U.fadeStartMs,B=U.fadeStartMs===0?1:Math.min(1,Math.max(0,G/300));if(B<1){if(P=!0,B>0)F.push({batch:U,fade:B})}else N.push(U)}if(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.disable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.opaque);for(let U of N)this.drawSubBatch(U.opaque);if(t.depthMask(!1),t.enable(t.BLEND),t.uniform1f(this.uFade,1),this.boardBatch)this.drawSubBatch(this.boardBatch.translucent);for(let U of N)this.drawSubBatch(U.translucent);for(let{batch:U,fade:G}of F)t.uniform1f(this.uFade,G),this.drawSubBatch(U.opaque),this.drawSubBatch(U.translucent);return t.depthMask(!0),t.bindVertexArray(null),P}onPointerDown=(e)=>{if(this.canvas.setPointerCapture(e.pointerId),this.pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,button:e.button,shift:e.shiftKey}),this.pointers.size===2){let[t,n]=Array.from(this.pointers.values());this.pinchDist=Math.hypot(n.x-t.x,n.y-t.y)||1}};onPointerMove=(e)=>{let t=this.pointers.get(e.pointerId);if(!t)return;let n=e.clientX-t.x,i=e.clientY-t.y;if(t.x=e.clientX,t.y=e.clientY,this.pointers.size===2){let[s,r]=Array.from(this.pointers.values()),o=Math.hypot(r.x-s.x,r.y-s.y)||1;if(this.pinchDist>0)this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*(this.pinchDist/o)));this.pinchDist=o,this.cbs.onUserMove?.(),this.scheduleDraw();return}if(t.button===2||t.button===1||t.shift){let s=this.dist*0.0014,r=Math.cos(this.yaw),o=Math.sin(this.yaw);this.target[0]-=n*r*s,this.target[1]-=n*o*s,this.target[2]+=i*s}else this.yaw+=n*0.008,this.pitch=Math.max(-Math.PI*0.49,Math.min(Math.PI*0.49,this.pitch+i*0.008));this.cbs.onUserMove?.(),this.scheduleDraw()};onPointerUp=(e)=>{if(this.pointers.delete(e.pointerId),this.pointers.size<2)this.pinchDist=0};onWheel=(e)=>{e.preventDefault();let t=e.deltaY<0?0.8620689655172414:1.16;this.dist=Math.max(this.radius*0.05,Math.min(this.radius*20,this.dist*t)),this.cbs.onUserMove?.(),this.scheduleDraw()};onDblClick=()=>{this.fit()};onContextMenu=(e)=>{e.preventDefault()};destroy(){if(this.rafId)cancelAnimationFrame(this.rafId);if(this.resizeObs.disconnect(),this.canvas.removeEventListener("pointerdown",this.onPointerDown),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerUp),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("dblclick",this.onDblClick),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.deleteBatch(this.boardBatch),this.clearParts(),this.gl){if(this.bgVao)this.gl.deleteVertexArray(this.bgVao);if(this.bgProg)this.gl.deleteProgram(this.bgProg);if(this.prog)this.gl.deleteProgram(this.prog)}this.worker?.terminate(),this.canvas.remove()}}var fi=64,ss=16777216;function rs(e,t){switch(e){case"board":case"3d":return t.board!==!1;case"schematic":return t.schematic!==!1;case"mech":return t.mech!==!1;case"gerbers":return t.gerbers!==!1;default:return!0}}function mt(e){if(!e)return"";let t=e.replace(/\\/g,"/").replace(/\/+$/,""),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function gi(e){switch(e){case"board":return f("viewer.board","Board");case"schematic":return f("viewer.schematic","Schematic");case"3d":return f("viewer.solid","3D");case"gerbers":return f("gpui.gerbers","Gerbers");case"mech":return f("viewer.mech","Mech");case"files":return f("viewer.files","Files");case"diff":return f("viewer.diff","Diff");case"review":return f("viewer.review","Review");case"browser":return f("bots.tab.browser","Browser");case"terminal":return f("viewer.terminal","Terminal");default:return e?e.charAt(0).toUpperCase()+e.slice(1):""}}function sn(e){return e==="board"||e==="schematic"||e==="gerbers"}function os(e){return e==="files"||e==="diff"||e==="review"||e==="browser"||e==="terminal"}function rn(e,t){let n=document.createElement("div");n.className="bp-vh";let i=document.createElement("div");i.className="bp-vh-title";let s=document.createElement("span");s.className="bp-vh-page";let r=document.createElement("span");r.className="bp-vh-sep",r.textContent="·",r.hidden=!0;let o=document.createElement("span");o.className="bp-vh-file",o.hidden=!0,i.append(s,r,o);let c=document.createElement("div");c.className="bp-vh-actions",n.append(i,c);let a=document.createElement("div");a.className="bp-solid-bar",a.setAttribute("data-testid","solid-presets-bar"),a.hidden=!0;let d=document.createElement("div");d.className="bp-v-banner",d.hidden=!0;let l=document.createElement("div");l.className="bp-v-stage-wrap";let h=document.createElement("div");h.className="bp-v-stage";let p=document.createElement("div");p.className="bp-v-overlay",p.hidden=!0;let u=document.createElement("div");u.className="bp-v-layers",u.hidden=!0;let y=document.createElement("div");y.className="bp-v-info",y.hidden=!0,l.append(h,p,u,y);let E=document.createElement("div");E.className="bp-history-bar",E.setAttribute("data-testid","viewer-history-bar"),E.hidden=!0,e.replaceChildren(n,a,d,l,E);let v="",g="",w=0,x=!1,S=new Set,L=[],P=0,N=new Map,F=new Map,U={},G=[],B="",xe="",X=!1,oe=!1,ie=0,Ae=!1,ve=0,he="",T=0,Q=null,de=null,se=null,_=null,z=null,A=new en,ne=0,ue=!1,Le="",Re="",W="",ee="";document.addEventListener("click",(M)=>{if(!ue)return;if(M.target instanceof Node&&E.contains(M.target))return;ue=!1,fe()}),document.addEventListener("keydown",(M)=>{if(ue&&M.key==="Escape")ue=!1,fe()});function Me(){if(ne)window.clearInterval(ne),ne=0;A.playing=!1}function qe(){let M=g==="3d"||g==="mech";if(a.hidden=!M,!M)return;if(a.childElementCount>0)return;for(let j of di){let I=document.createElement("button");I.type="button",I.className="bp-v-btn",I.textContent=j.label,I.setAttribute("data-testid",`solid-view-${j.id}`),I.addEventListener("click",()=>{se?.setView(j.id)}),a.append(I)}let H=document.createElement("button");H.type="button",H.className="bp-v-btn",H.textContent="Snap view",H.setAttribute("data-testid","solid-snap"),H.addEventListener("click",()=>{if(!se)return;se.snapPng().then((j)=>{if(!j)return;let I=URL.createObjectURL(j),R=document.createElement("a");R.href=I;let q=(pe()||g||"view").replace(/[^a-zA-Z0-9._-]/g,"_");R.download=`${q}-snap.png`,R.click(),setTimeout(()=>URL.revokeObjectURL(I),1000)})}),a.append(H)}async function ke(){if(!v||g!=="board"&&g!=="schematic")return;fe();let M=A.compareRequest();if(!M){Le="",Re="",W="",ee="",await Ge(!1);return}let H=`${g}|${M.commit}|${M.bits}|${xe}`;if(H===ee&&S.size>0){De(A.highlightEdits?`Comparing against ${A.activeRef()?.label||M.commit.slice(0,7)} (edits highlighted)`:`Comparing against ${A.activeRef()?.label||M.commit.slice(0,7)}`,!1);return}let j=++w;S.clear(),N.clear(),Ne(),x=!0,Le="",Re=M.commit,W="",ee=H;try{let I=xe||(g==="schematic"?U.sch:U.pcb)||"";if(!I){let ae=await t.hub.rpc("viewer.files",{thread:v});if(j!==w)return;U=ae||{},re(),I=(g==="schematic"?U.sch:U.pcb)||""}if(!I)throw Error(`Unable to resolve ${g} file path for compare`);let R=await t.hub.rpc("viewer.compare",{thread:v,kind:g,commit:M.commit,bits:M.bits,...xe?{path:xe}:{}});if(j!==w)return;let q=typeof R?.root==="string"?R.root:"",K=g==="schematic"?"1":"0";Le=q?`${K}|${q}|diff +`:`${K}|`,Re=M.commit,W=I.startsWith("/")||/^[A-Za-z]:[\\/]/.test(I)||!q?I:`${q.replace(/\/+$/,"")}/${I.replace(/^\/+/,"")}`,x=!1;let te=L;Ne();for(let ae of te)if(ae.kind==="bin")st(ae.buf);else je(ae.key,ae.none,ae.retryable);De(A.highlightEdits?`Comparing against ${A.activeRef()?.label||M.commit.slice(0,7)} (edits highlighted)`:`Viewing snapshot: ${A.activeRef()?.label||M.commit.slice(0,7)}`,!1)}catch(I){if(j!==w)return;x=!1,Le="",Re="",W="",ee="",Ne(),De(I instanceof Error?I.message:String(I),!0)}}function fe(){let M=g==="board"||g==="schematic";if(E.hidden=!M,!M)return;let H=document.createElement("div");H.className="bp-history-group";let j=document.createElement("button");j.type="button",j.className="bp-v-btn",j.textContent="<",j.title="Older snapshot",j.disabled=A.refs.length===0||A.index>=A.refs.length-1,j.setAttribute("data-testid","history-prev"),j.addEventListener("click",()=>{if(Me(),A.step(1))ke()});let I=document.createElement("button");I.type="button",I.className="bp-v-btn"+(A.playing?" is-on":""),I.textContent=A.playing?"⏸":"▶",I.title=A.playing?"Pause history":"Play history",I.disabled=A.refs.length===0,I.setAttribute("data-testid","history-play"),I.addEventListener("click",()=>{if(A.playing){Me(),fe();return}if(A.refs.length===0)return;if(A.playing=!0,A.isLive())A.index=A.refs.length-1,ke();else fe();ne=window.setInterval(()=>{if(!A.playing||g!=="board"&&g!=="schematic"){Me(),fe();return}if(A.step(-1))ke();else Me(),fe()},1400)});let R=document.createElement("button");R.type="button",R.className="bp-v-btn",R.textContent=">",R.title="Newer snapshot",R.disabled=A.isLive(),R.setAttribute("data-testid","history-next"),R.addEventListener("click",()=>{if(Me(),A.step(-1))ke()});let q=document.createElement("button");q.type="button",q.className="bp-v-btn"+(A.isLive()?" is-on":""),q.textContent="Live",q.setAttribute("data-testid","history-live"),q.addEventListener("click",()=>{if(Me(),A.goLive())De("",!1),ke()});let K=document.createElement("span");K.className="bp-history-label",K.setAttribute("data-testid","history-label");let te=A.activeRef();K.textContent=te?te.label||te.commit.slice(0,7):A.refs.length>0?`Live (${A.refs.length} saved)`:"Live",H.append(j,I,R,q,K);let ae=document.createElement("div");ae.className="bp-history-group";let ge=document.createElement("button");ge.type="button",ge.className="bp-v-btn"+(A.highlightEdits?" is-on":""),ge.textContent="Highlight edits",ge.disabled=A.refs.length===0,ge.setAttribute("data-testid","history-highlight"),ge.addEventListener("click",()=>{Me(),A.toggleHighlight(),ke()});let Se=document.createElement("div");Se.className="bp-history-menu-wrap";let we=document.createElement("button");if(we.type="button",we.className="bp-v-btn"+(ue||!A.isLive()?" is-on":""),we.disabled=A.refs.length===0,we.setAttribute("data-testid","history-compare"),we.setAttribute("aria-haspopup","menu"),we.setAttribute("aria-expanded",String(ue)),we.textContent=te?`Compare: ${te.label||te.commit.slice(0,7)} ▾`:"Compare ▾",we.addEventListener("click",(me)=>{me.stopPropagation(),ue=!ue,fe()}),Se.append(we),ue&&A.refs.length>0){let me=document.createElement("div");me.className="bp-history-menu",me.setAttribute("role","menu"),me.setAttribute("data-testid","history-compare-menu");let Fe=(Te,rt,gt)=>{let Be=document.createElement("button");Be.type="button",Be.className="bp-history-menu-item"+(gt?" is-active":""),Be.setAttribute("role","menuitem"),Be.setAttribute("data-commit",rt),Be.textContent=Te,Be.addEventListener("click",()=>{if(ue=!1,Me(),A.selectCommit(rt)){if(A.isLive())De("",!1);ke()}else fe()}),me.append(Be)};Fe("Live (working tree)","",A.isLive());for(let Te of A.refs)Fe(Te.label||Te.commit.slice(0,7),Te.commit,te?.commit===Te.commit);Se.append(me)}ae.append(ge,Se),E.replaceChildren(H,ae)}async function Ve(M){if(!M)return;try{let H=await t.hub.rpc("viewer.refs",{thread:M});if(M!==v)return;A.setRefs(Array.isArray(H?.refs)?H.refs:[]),fe()}catch{if(M!==v)return;A.setRefs([]),fe()}}function nt(){return document.documentElement.classList.contains("light")}let it=new MutationObserver(()=>{let M=nt();de?.setTheme(M),se?.setTheme(M),z?.setTheme(M)});it.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});function Ce(M,H="",j=!1){if(M==="none"){p.hidden=!0,p.replaceChildren();return}p.hidden=!1,p.className=`bp-v-overlay is-${M}`;let I=document.createElement("div");I.className="bp-v-state-card";let R=document.createElement("div");if(R.className="bp-v-state-msg",R.textContent=H,I.append(R),j){let q=document.createElement("button");q.type="button",q.className="bp-v-btn is-primary",q.textContent=f("tools.retry","Retry"),q.addEventListener("click",()=>void Ge(!0)),I.append(q)}p.replaceChildren(I)}function De(M,H){d.textContent=M,d.hidden=!M,d.classList.toggle("is-warn",H)}function pe(){if(xe)return mt(xe);if(g==="board"||g==="3d")return mt(U.pcb);if(g==="schematic")return mt(U.sch);if(g==="mech")return mt(B);return""}function re(){s.textContent=gi(g);let M=pe();if(r.hidden=!M,o.hidden=!M,o.textContent=M,c.replaceChildren(),g==="mech"&&G.length>1){let j=document.createElement("select");j.className="bp-v-select",j.setAttribute("aria-label",f("viewer.mech","Mech"));for(let I of G){let R=document.createElement("option");R.value=I,R.textContent=mt(I),R.selected=I===B,j.append(R)}j.addEventListener("change",()=>{B=j.value,re(),Ge(!1)}),c.append(j)}if(sn(g)){let j=document.createElement("button");j.type="button",j.className="bp-v-btn"+(Ae?" is-on":""),j.textContent=Q?.layerHead||"Layers",j.setAttribute("data-testid","viewer-layers-btn"),j.addEventListener("click",()=>{if(Ae=!Ae,u.hidden=!Ae,j.classList.toggle("is-on",Ae),Ae)Z("","")}),c.append(j)}if(g==="board"||g==="schematic"||g==="3d"||g==="mech"||g==="gerbers"){let j=document.createElement("button");j.type="button",j.className="bp-v-btn",j.textContent="Fit",j.setAttribute("data-testid","viewer-fit-btn"),j.addEventListener("click",()=>{de?.fit(),se?.fit()}),c.append(j)}if((g==="board"||g==="schematic")&&t.hub.hasFeature("follow")){let j=document.createElement("button");j.type="button",j.className="bp-v-btn"+(X&&!oe?" is-on":""),j.textContent=X?oe?f("gpui.follow.paused","Follow (paused)"):"Follow agent":"Follow agent",j.setAttribute("data-testid","viewer-follow-btn"),j.addEventListener("click",()=>void We()),c.append(j)}let H=document.createElement("button");H.type="button",H.className="bp-v-btn bp-v-close",H.textContent="✕",H.title=f("common.close","Close"),H.setAttribute("aria-label",f("common.close","Close")),H.setAttribute("data-testid","viewer-close-btn"),H.addEventListener("click",()=>t.closeViewer()),c.append(H)}function Xe(){if(!Q){u.replaceChildren();return}let M=document.createDocumentFragment(),H=document.createElement("div");H.className="bp-v-layers-head";let j=document.createElement("span");if(j.textContent=Q.layerHead||"Layers",H.append(j),Q.layerReset){let K=document.createElement("button");K.type="button",K.className="bp-v-btn",K.textContent="Reset",K.addEventListener("click",()=>void Z("reset","")),H.append(K)}if(M.append(H),Q.layerModes){let K=document.createElement("div");K.className="bp-v-layers-modes",["All","Dim","Only"].forEach((te,ae)=>{let ge=document.createElement("button");ge.type="button",ge.className="bp-v-btn"+(Q?.layerMode===ae?" is-on":""),ge.textContent=te,ge.addEventListener("click",()=>void Z("mode",String(ae))),K.append(ge)}),M.append(K)}let I=de?.presentColors()??new Map,R=(Q.layerList||[]).concat(Q.layerMarks||[]),q=document.createElement("div");q.className="bp-v-layers-list";for(let K of R){let te=I.get(K.layer);if(te===void 0)continue;let ae=document.createElement("div");ae.className="bp-v-layer-row"+(K.active?" is-focus":"");let ge=document.createElement("input");ge.type="checkbox",ge.checked=K.on!==!1,ge.addEventListener("change",()=>void Z("toggle",String(K.layer)));let Se=document.createElement("span");Se.className="bp-v-layer-swatch";let we=te>>>16&255,me=te>>>8&255,Fe=te&255;Se.style.background=K.on!==!1?`rgb(${we},${me},${Fe})`:`rgba(${we},${me},${Fe},0.2)`;let Te=document.createElement("button");Te.type="button",Te.className="bp-v-layer-name",Te.textContent=K.name,Te.addEventListener("click",()=>void Z("pick",String(K.layer))),ae.append(ge,Se,Te),q.append(ae)}M.append(q),u.replaceChildren(M)}async function Z(M,H){if(!sn(g))return;let j=w;try{let I=await t.hub.rpc("viewer.layers",{kind:g,present:T,off:ve,focus:he,...M?{action:M,value:H}:{}});if(j!==w||!I)return;ve=Number(I.own)||0,he=typeof I.focus==="string"?I.focus:"",Q=I;let R={off:Number(I.off)||0,dim:Number(I.dim)||0,lift:typeof I.lift==="number"?I.lift:255};if(de?.setLayers(R),re(),Ae)Xe()}catch{}}async function Qe(){if(!X||oe||!v||!t.hub.hasFeature("follow"))return;oe=!0,re();try{await t.hub.rpc("viewer.follow",{thread:v,action:"pause"})}catch{}}async function We(){if(!v||!t.hub.hasFeature("follow"))return;let M=!X?"on":oe?"resume":"off";try{let H=await t.hub.rpc("viewer.follow",{thread:v,action:M});if(X=!!H.on,oe=!!H.paused,re(),H.on&&!H.paused&&H.focus&&Array.isArray(H.focus.box)&&H.focus.box.length===4&&(H.seq||0)>ie)ie=H.seq||ie,de?.zoomToBoxMm([H.focus.box[0],H.focus.box[1],H.focus.box[2],H.focus.box[3]])}catch{}}function ze(){y.hidden=!0,y.replaceChildren(),de?.setHighlights([])}function Lt(M){let H=M.split(";").filter(Boolean),j=H.shift()||M,I=[],R="",q="";for(let Se of H){if(Se.startsWith("g="))continue;let we=Se.indexOf("=");if(we>0){let me=Se.slice(0,we),Fe=Se.slice(we+1);if((me==="ref"||me==="symbol")&&!R)R=Fe;if(me==="net"&&!q)q=Fe;I.push([me,Fe])}else I.push([Se,""])}let K=document.createElement("div");K.className="bp-v-info-head";let te=document.createElement("span");te.className="bp-v-info-title",te.textContent=j;let ae=document.createElement("button");ae.type="button",ae.className="bp-v-info-x",ae.textContent="×",ae.setAttribute("aria-label","Clear selection"),ae.addEventListener("click",ze),K.append(te,ae);let ge=document.createElement("div");ge.className="bp-v-info-rows";for(let[Se,we]of I){let me=document.createElement("span");me.className="bp-v-info-chip",me.textContent=we?`${Se}: ${we}`:Se,ge.append(me)}return y.replaceChildren(K,...I.length>0?[ge]:[]),y.hidden=!1,{ref:R||void 0,net:q||void 0}}async function Oe(M){if(!M){ze();return}let H=Array.from(S)[0]||"";if(!H)return;let j=w;try{let I=await t.hub.rpc("viewer.info",{key:H,at:M.at,idx:M.idx});if(j!==w)return;let R=typeof I.info==="string"?I.info:"";if(!R){ze();return}let{ref:q,net:K}=Lt(R),te=[];if(q)te.push(["ref",q]);if(K)te.push(["net",K]);let ae=[[M.at,M.idx]];for(let[ge,Se]of te){let we=await t.hub.rpc("viewer.probe",{key:H,name:ge,value:Se});if(j!==w)return;if(Array.isArray(we.matches))for(let me of we.matches)ae.push(me)}de?.setHighlights(ae)}catch{ze()}}function Ue(){_?.destroy(),_=null,z?.destroy(),z=null,de?.destroy(),de=null,se?.destroy(),se=null,h.replaceChildren(),Ae=!1,u.hidden=!0,y.hidden=!0,y.replaceChildren(),De("",!1),Ce("none")}function Ne(){L=[],P=0}async function Ge(M){if(!v||!g)return;let H=++w;if(S.clear(),x=!1,Ne(),Ue(),re(),qe(),fe(),(g==="board"||g==="schematic")&&v)Ve(v);if(os(g)){if(t.hub.rpc("viewer.watch",{thread:v,kind:""}).catch(()=>{}),g==="files")_=oi(h,t,v,(R,q)=>{if(g=R,xe=q,R==="mech")B=q;Ge(!1)});else if(g==="diff")_=ai(h,t,v);else if(g==="review")_=ci(h,t,v);else if(g==="browser")_=ii(h,t,v);else if(g==="terminal")Ce("loading","Loading terminal…"),import("/assets/terminal.js").then((q)=>{if(H!==w)return;if(Ce("none"),q?.mountTerminalPane)z=q.mountTerminalPane(h,t,v,nt());else Ce("error","Terminal chunk missing",!0)},(q)=>{if(H!==w)return;Ce("error",q instanceof Error?q.message:String(q),!0)});return}if(Ce("loading","Loading…"),!U.root)try{let R=await t.hub.rpc("viewer.files",{thread:v});if(H!==w)return;U=R||{},re()}catch{}if(g==="gerbers"&&U.hasGerbers===!1){Ce("empty","No Gerbers in this project",!1);return}let j=nt();if(g==="3d"||g==="mech")se=new nn(h,{onStatus:(R,q)=>{if(q)Ce("none"),De(R,!1);else if(R)Ce("loading",R);else Ce("none"),De("",!1)},onUserMove:()=>void Qe()}),se.setTheme(j);else if(g==="board"||g==="schematic"||g==="gerbers")de=new Qt(h,{onPick:(R)=>void Oe(R),onUserMove:()=>void Qe()}),de.setTheme(j);else{Ce("empty",`${gi(g)} is not available in this viewer`,!1);return}let I={thread:v};if(M)I.force=!0;if(g==="mech"){if(G.length===0)try{let R=await t.hub.rpc("mech.list",{thread:v});if(H!==w)return;if(G=Array.isArray(R.parts)?R.parts:[],!B)B=R.primary||G[0]||"";re()}catch(R){if(H!==w)return;Ce("error",R instanceof Error?R.message:String(R),!0);return}if(!B){Ce("empty",f("gpui.rail.no.mech","No mechanical parts in this project"),!1);return}I.kind="3d",I.path=B}else{if(I.kind=g,xe&&(g==="board"||g==="schematic"))I.path=xe;if(g==="3d"&&!M&&se){let R=se.keptToken();if(R)I.kept=R}if((g==="board"||g==="schematic"||g==="gerbers")&&!M&&t.hub.hasFeature("keptChunks")&&F.size>0)I.keptChunks=Array.from(F.keys())}x=!0,Le="",Re="",W="",ee="";try{let R=await t.hub.rpc("viewer.watch",I);if(H!==w)return;S=new Set(Array.isArray(R.keys)?R.keys:[]),x=!1;let q=L;Ne();for(let K of q)if(K.kind==="bin")st(K.buf);else je(K.key,K.none,K.retryable)}catch(R){if(H!==w)return;x=!1,S.clear(),Ne();let q=R instanceof Error?R.message:String(R),K=/no gerbers|not in this project|another machine/i.test(q);Ce(K?"empty":"error",q,!K)}}function je(M,H,j){if(x){if(L.length{if(M.t==="plot"&&typeof M.none==="string"&&typeof M.key==="string")je(M.key,M.none,M.retryable===!0)}),Ke=wt(()=>{if(g)re()}),Ze=(M)=>{if(M.key==="Escape"&&g&&!y.hidden)ze()};return window.addEventListener("keydown",Ze),{open(M,H){if(H!==v){if(v=H,U={},G=[],B="",N.clear(),X=!1,oe=!1,ie=0,ve=0,he="",T=0,Q=null,t.hub.hasFeature("follow"))t.hub.rpc("viewer.follow",{thread:H}).then((j)=>{if(H!==v)return;if(X=!!j.on,oe=!!j.paused,ie=Number(j.seq)||0,g)re()}).catch(()=>{})}if(M!==g)Me(),A.goLive(),ve=0,he="",T=0,Q=null;g=M,xe="",Ge(!1)},reconcileHas(M){if(g&&!rs(g,M))t.closeViewer()},close(){if(w++,x=!1,Me(),ue=!1,Le="",Re="",W="",ee="",A.goLive(),a.hidden=!0,E.hidden=!0,Ne(),v)t.hub.rpc("viewer.watch",{thread:v,kind:""}).catch(()=>{});g="",S.clear(),Ue()}}}var vi="http://www.w3.org/2000/svg";function bt(e){let t=document.createElementNS(vi,"svg");t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","13"),t.setAttribute("height","13"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.8"),t.setAttribute("aria-hidden","true");for(let n of e){let i=document.createElementNS(vi,"path");i.setAttribute("d",n),t.appendChild(i)}return t}function as(e){if(!e)return"bp-dot-idle";let t=e.status||e.state;if(t==="active"||t==="working")return"bp-dot-work";if(t==="finished")return"bp-dot-done";if(t==="waiting"||t==="asking"||t==="blocked"||t==="failed"||(e.waiting??0)>0)return"bp-dot-need";return"bp-dot-idle"}function wi(e,t){if(!e)return!0;if(t==="board"||t==="3d")return e.board!==!1;if(t==="schematic")return e.schematic!==!1;if(t==="mech")return e.mech!==!1;if(t==="gerbers")return e.gerbers!==!1;return!0}function yi(e){if(!e)return;let t=e==="light";document.documentElement.classList.toggle("light",t);try{localStorage.setItem("bp.theme",t?"light":"dark")}catch{}}function cs(){return`web-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function Ei(){let e=document.getElementById("root");if(!e)return;try{if(localStorage.getItem("bp.theme")==="light")document.documentElement.classList.add("light")}catch{}let t=document.createElement("header");t.className="bp-topbar",t.setAttribute("data-testid","topbar");let n=document.createElement("button");n.type="button",n.className="icon bp-side-toggle",n.textContent="☰",n.title="Toggle sidebar",n.setAttribute("aria-label","Toggle sidebar");let i=document.createElement("div");i.className="bp-brand";let s=document.createElement("img");s.src="/assets/favicon.svg",s.alt="Backplane",s.className="bp-logo";let r=document.createElement("span");r.className="bp-brand-name bp-hide-phone",r.textContent="Backplane";let o=document.createElement("span");o.className="bp-crumb-sep bp-hide-phone",o.textContent="/";let c=document.createElement("span");c.className="bp-crumb-proj bp-hide-phone";let a=document.createElement("span");a.className="bp-crumb-sep bp-hide-phone",a.textContent="/";let d=document.createElement("span");d.className="bp-crumb-thread",d.setAttribute("data-testid","thread-title"),i.append(s,r,o,c,a,d);let l=document.createElement("div");l.className="bp-top-state bp-hide-phone bp-hidden";let h=document.createElement("span");h.className="bp-top-state-lbl",h.textContent="STATE";let p=document.createElement("span");p.className="bp-dot bp-dot-idle";let u=document.createElement("span");u.className="bp-top-state-word",l.append(h,p,u);let y=document.createElement("div");y.className="bp-top-acts bp-hide-phone bp-hidden";let E=document.createElement("button");E.type="button",E.className="bp-btn-ghost bp-top-act";let v=document.createElement("span");v.textContent=f("menu.pin","Pin"),E.append(bt(["M12 17v5","M9 3h6l1 7 3 3H5l3-3 1-7z"]),v);let g=document.createElement("button");g.type="button",g.className="bp-btn-ghost bp-top-act";let w=document.createElement("span");w.textContent=f("menu.settle","Settle"),g.append(bt(["M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20z","M9 12l2 2 4-4"]),w);let x=document.createElement("div");x.className="bp-menu-wrap";let S=document.createElement("button");S.type="button",S.className="bp-btn-ghost bp-top-act",S.textContent="▾",S.title="Thread menu",S.setAttribute("aria-label","Thread menu"),S.setAttribute("data-testid","thread-menu-btn");let L=document.createElement("div");L.className="bp-popover bp-hidden",L.setAttribute("data-testid","thread-menu"),x.append(S,L),y.append(E,g,x);let P=document.createElement("div");P.className="bp-top-right";let N=document.createElement("button");N.type="button",N.className="bp-btn-ghost bp-top-act bp-hide-tablet",N.setAttribute("data-testid","improvements-btn");let F=document.createElement("span");F.textContent=f("gpui.improvements","Improvements"),N.append(bt(["M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 16.8l-6.2 4.5 2.4-7.4L2 9.4h7.6z"]),F);let U=document.createElement("button");U.type="button",U.className="bp-cmd-box bp-hide-tablet",U.textContent="> Jump or run a command";let G=document.createElement("button");G.type="button",G.className="icon bp-top-icon",G.title="Search",G.setAttribute("aria-label","Search"),G.appendChild(bt(["M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16z","M21 21l-4.3-4.3"]));let B=document.createElement("button");B.type="button",B.className="icon bp-top-icon",B.title=f("palette.settings","Settings"),B.setAttribute("aria-label",f("palette.settings","Settings")),B.setAttribute("data-testid","settings-btn"),B.appendChild(bt(["M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z","M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9c.26.6.85 1 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"])),P.append(N,U,G,B),t.append(n,i,l,y,P);let xe=document.createElement("div");xe.className="bp-body";let X=document.createElement("aside");X.className="bp-sidebar",X.setAttribute("data-testid","sidebar");let oe=document.createElement("main");oe.className="bp-center";let ie=document.createElement("div");ie.className="bp-right-area bp-hidden",ie.setAttribute("data-testid","right-area");let Ae=document.createElement("div");Ae.className="bp-right-top";let ve=document.createElement("section");ve.className="bp-viewer-pane bp-hidden",ve.setAttribute("data-testid","viewer-pane"),Ae.appendChild(ve),ie.appendChild(Ae);let he=document.createElement("nav");he.className="bp-rail",he.setAttribute("aria-label","Viewer rail"),he.setAttribute("data-testid","viewer-rail"),xe.append(X,oe,ie,he),e.append(t,xe);let T=new Yt,Q=null,de=new Set,se=0,_=null,z=[],A=[],ne=[],ue=[],Le=[],Re=[],W="",ee=0,Me=0,qe=null,ke=null,fe="",Ve=null,nt=20,it={},Ce=new Map;function De(m,b){Ce.delete(m),Ce.set(m,b);while(Ce.size>nt){let C=Ce.keys().next().value;if(C!==void 0)Ce.delete(C);else break}}let pe=new zt(X,{onSelectThread:(m)=>{if(m===W&&qe!==null){X.classList.remove("bp-sidebar-open");return}te(m)},onNewThread:(m)=>{we(m)},onSelectBot:(m)=>{te(m.thread)},onThreadAct:(m,b)=>{Be(m,b)},onToggleSection:(m)=>{if(de.has(m))de.delete(m);else de.add(m);R()},onToggleProjectFold:(m)=>{T.rpc("sidebar.act",{action:"project-fold",value:m}).then(()=>R()).catch(()=>{})},onCollapseSidebar:()=>{X.classList.remove("bp-sidebar-open"),X.classList.add("bp-sidebar-collapsed")},onNeedAct:async(m)=>{let b=kt(m,!1);if(!b)return;if(b.kind==="thread"){te(b.id);return}if(b.kind!=="call")return;let C=Gn(await T.rpc(b.method,b.params));if(C?.kind==="thread")te(C.id);R()},hasRoomView:!1,onAddProject:()=>Ue.open({mode:"folder"})}),re=new Dt(oe,{onLoadOlder:()=>{Se()},onGoToEntry:(m)=>{ge(m)},onAnswerAsk:(m,b)=>{T.rpc("ask.answer",{ask:m,answer:b}).catch(()=>{})},onToggleReview:(m)=>{if(!W)return;let b=ee;T.rpc("thread.review",{thread:W,on:m}).then((C)=>{if(b===ee)re.setReview(C.review??null)}).catch(()=>{})},onUnansweredAction:(m,b)=>{if(!W)return;if(m==="again"||m==="thread-again")T.rpc("thread.again",{thread:W,value:b}).catch(()=>{});else T.rpc("thread.act",{thread:W,action:m,value:b}).catch(()=>{})},onReplyEntry:(m)=>{if(!T.hasFeature("reply")){let b=(m.text||"").split(` `)[0]?.slice(0,100)??"";if(b)Z.prependDraft(`> ${b} -`);return}if(!m.text||!m.text.trim()||m.live||m.id.startsWith("local-"))return;Be({id:m.id,text:m.text,role:m.kind==="user"?"user":"assistant"})},onLoadImage:async(m,b)=>{try{let C={entry:m,path:b};if(P.hasFeature("blobs"))C.metaOnly=!0;let k=await P.rpc("message.image",C);if(k.blob&&k.blob.startsWith("/blob/"))return{url:k.blob};if(k.mime&&k.data)return{mime:k.mime,data:k.data}}catch{}return null}}),Xe,Z=new Rt(re,{onSend:(m,b)=>{Ie(m,b)},onRunCommand:(m)=>{rt(m)},onInterrupt:()=>{if(W)P.rpc("turn.interrupt",{thread:W}).catch(()=>{})},onQueryMentions:async(m,b)=>{try{return(await P.rpc("mentions.list",{q:m,kind:b,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{Xe.toggle()}});Xe=new Vt(P,{getThreadId:()=>W,getDraft:()=>Z.getDraft(),getCaret:()=>Z.getCaret(),setDraft:(m)=>Z.setDraft(m),setRecording:(m)=>Z.setVoiceRecording(m),setLevel:(m)=>Z.setVoiceLevel(m),showError:(m)=>Z.showError(m)});function Qe(){let m=be!=="",b=We.isOpen();ne.classList.toggle("bp-hidden",!m&&!b),ne.classList.toggle("bp-has-viewer",m),ne.classList.toggle("bp-has-mgmt",b)}let We=new Ft(Se,ne,{hub:P,getThreadId:()=>W,getThreadGen:()=>ee,onSendText:(m)=>{Ie(m)},onOpenChange:()=>Qe()});function ze(m){let b=window.prompt("Rename thread",m.title||"");if(!b||!b.trim())return;P.rpc("thread.act",{thread:m.id,action:"rename",title:b.trim()}).then((C)=>{if(C.thread)A=A.map((k)=>k.id===C.thread.id?C.thread:k),De(),B()}).catch((C)=>{Z.showError(C instanceof Error?C.message:"Could not rename thread")})}function kt(m){switch(m.type){case"thread":_(m.id);break;case"rail":if(!W&&m.id!=="terminal")break;if(be===m.id)Ke();else et(m.id);break;case"thread-act":if(W)Ge(W,m.action);break;case"new-thread":Ce(m.projectId);break;case"rename":{let b=A.find((C)=>C.id===W);if(b)ze(b);break}case"prev-thread":case"next-thread":{let b=A.filter((J)=>!J.archived&&!J.swarm);if(b.length<2)break;let C=b.findIndex((J)=>J.id===W),k=m.type==="next-thread"?1:-1,O=b[(C<0?0:C+k+b.length)%b.length];if(O)_(O.id);break}case"command":if(m.runDirectly)rt(m.word);else Z.setDraft(`${m.word} `),Z.focus();break;case"improvements":Ze();break;case"settings":Re.open();break;case"sidebar":X.classList.toggle("bp-sidebar-open"),X.classList.toggle("bp-sidebar-collapsed");break}}let Ue=new $t(e,{getState:()=>({selectedThreadId:W,threads:A,projects:z,bots:te,railItems:Ae,commands:Me}),onSearch:async(m)=>{if(!P.hasFeature("search"))return{threads:[],projects:[],messages:[]};return P.rpc("search",{q:m,limit:20})},onExecute:kt}),Fe=new Pt(e,{hub:P,onProjectAdded:(m)=>{if(B(),m.id)Ce(m.id)},onCloneDone:(m)=>{if(B(),m.thread)_(m.thread)}}),Le=new Ut(he,(m)=>{if(m==="commands"){Ue.open();return}if(!W)return;if(be===m)Ke();else et(m)}),$e=null,Re=new Gt(e,{onLoadDevices:async()=>(await P.rpc("devices.page",{})).rows??[],onDevicesAct:async(m,b)=>{await P.rpc("devices.page.act",{action:m,value:b})},onGetHome:()=>$e,onMoveHomeHere:async()=>{await P.rpc("home.move",{to:"back"})},onLogout:()=>bn(()=>{P.disconnect(),window.location.replace("/")})});E.addEventListener("click",()=>{let m=A.find((b)=>b.id===W);if(m)Ge(m.id,m.pinned?"unpin":"pin")}),f.addEventListener("click",()=>{let m=A.find((b)=>b.id===W);if(m)Ge(m.id,m.settled?"unsettle":"settle")}),S.addEventListener("click",(m)=>{m.stopPropagation();let b=A.find((O)=>O.id===W);if(!b)return;if(!L.classList.contains("bp-hidden")){L.classList.add("bp-hidden");return}let C=[{label:"Rename…",run:()=>ze(b)},{label:b.pinned?v("menu.unpin","Unpin"):v("menu.pin","Pin"),run:()=>{Ge(b.id,b.pinned?"unpin":"pin")}},{label:b.settled?v("phone.unsettle","Unsettle"):v("menu.settle","Settle"),run:()=>{Ge(b.id,b.settled?"unsettle":"settle")}},{label:b.archived?"Unarchive":"Archive",run:()=>{Ge(b.id,b.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Ge(b.id,"delete")}}],k=document.createDocumentFragment();for(let O of C){let J=document.createElement("button");J.type="button",J.className="bp-popover-item"+(O.danger?" danger":""),J.textContent=O.label,J.addEventListener("click",()=>{L.classList.add("bp-hidden"),O.run()}),k.appendChild(J)}L.replaceChildren(k),L.classList.remove("bp-hidden")}),document.addEventListener("click",()=>L.classList.add("bp-hidden"));async function Ze(){let m=document.createElement("div");m.className="bp-modal-backdrop",m.setAttribute("data-testid","improvements-modal");let b=document.createElement("div");b.className="bp-modal";let C=document.createElement("div");C.className="bp-modal-head";let k=document.createElement("h2");k.textContent=v("gpui.improvements","Improvements");let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>m.remove()),C.append(k,O);let J=document.createElement("div");J.className="bp-modal-body",J.textContent="Loading…",b.append(C,J),m.appendChild(b),m.addEventListener("click",(ae)=>{if(ae.target===m)m.remove()}),e.appendChild(m);try{let ae=await P.rpc("improvements.projects",{}),Ne=ae.projects??[];if(Ne.length===0){J.textContent="No projects available for Improvements.";return}let Je=document.createDocumentFragment();for(let me of Ne){let Y=document.createElement("div");Y.className="bp-set-row";let _e=document.createElement("div");_e.className="bp-set-info",_e.textContent=me.title||me.name||me.id;let Ye=document.createElement("button");Ye.type="button",Ye.className=me.id===ae.project?"primary":"",Ye.textContent=me.id===ae.project?"Active":"Select",Ye.addEventListener("click",()=>{P.rpc("improvements.project",{project:me.id}).then(()=>m.remove()).catch(()=>{})}),Y.append(_e,Ye),Je.appendChild(Y)}J.replaceChildren(Je)}catch(ae){J.textContent=ae instanceof Error?ae.message:"Could not load Improvements."}}N.addEventListener("click",()=>{Ze()}),U.addEventListener("click",()=>Ue.open()),G.addEventListener("click",()=>Ue.open()),I.addEventListener("click",()=>{Re.open()}),n.addEventListener("click",()=>{X.classList.toggle("bp-sidebar-open"),X.classList.toggle("bp-sidebar-collapsed")});function De(){let m=A.find((C)=>C.id===W)??null,b=m?z.find((C)=>C.id===m.project):void 0;if(c.textContent=b?.title??"",o.classList.toggle("bp-hidden",!b),a.classList.toggle("bp-hidden",!m),d.textContent=m?m.title||"Untitled thread":"",l.classList.toggle("bp-hidden",!m),y.classList.toggle("bp-hidden",!m),m){p.className=`bp-dot ${es(m)}`,u.textContent=m.status||m.state||"idle",g.textContent=m.pinned?v("menu.unpin","Unpin"):v("menu.pin","Pin"),w.textContent=m.settled?v("phone.unsettle","Unsettle"):v("menu.settle","Settle");let C=m;Z.setModelChip(m.chip||m.model||"default",m.provider,C.ctxPct??C.contextPct),Z.setMemory(m.memory)}else Z.setModelChip("default"),Z.setMemory(null)}function Ke(m=!0){if(Te++,be="",Le.setActive(""),ge.classList.add("bp-hidden"),Ve?.close(),Qe(),m&&W&&P.getState()==="connected")P.rpc("viewer.watch",{thread:W,kind:""}).catch(()=>{})}function et(m){if(Te++,be=m,Le.setActive(m),ge.classList.remove("bp-hidden"),Qe(),!Ve&&typeof Zt==="function")Ve=Zt(ge,{hub:P,getThreadId:()=>W,closeViewer:()=>Ke(!0)});if(Ve)Ve.open(m,W);else{let b=document.createElement("div");b.className="bp-viewer-placeholder";let C=document.createElement("div");C.className="bp-viewer-bar";let k=document.createElement("span");k.textContent=m.toUpperCase();let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>Ke(!0)),C.append(k,O);let J=document.createElement("div");J.className="bp-dim bp-viewer-msg",J.textContent=`Viewer pane (${m}).`,b.append(C,J),ge.replaceChildren(b)}}async function bt(m,b){if(!m||!P.hasFeature("rail")){if(b===ee)Ae=[],Le.setItems([]);return}let C=++Te;try{let k=await P.rpc("viewer.rail",{thread:m,page:be});if(b!==ee||C!==Te)return;let O=Array.isArray(k.rail)?k.rail:Array.isArray(k.items)?k.items:[];if(Ae=O,Le.setItems(O),k.has){if(Ve?.reconcileHas?.(k.has),be&&!ui(k.has,be))Ke(!0)}}catch{if(b===ee&&C===Te)Ae=[],Le.setItems([])}}function M(m){for(let b of m)if(b.kind==="threads"){for(let C of b.rows)if(!C.off&&(C.nav||C.id)&&!(C.nav||"").startsWith("@room:"))return C.nav||C.id}else if(b.kind==="projects"){for(let C of b.rows)for(let k of C.threads??[])if(!k.off&&(k.nav||k.id)&&!(k.nav||"").startsWith("@room:"))return k.nav||k.id}return""}function j(m,b){for(let C of m)if(C.kind==="threads"){if(C.rows.some((k)=>(k.nav||k.id)===b))return!0}else if(C.kind==="projects"){for(let k of C.rows)if((k.threads??[]).some((O)=>(O.nav||O.id)===b))return!0}return!1}function R(m){let b=[];for(let C of m){if(C.kind!=="projects")continue;for(let k of C.rows)b.push({id:k.id,title:k.title,css:k.css,color:k.color})}if(b.length>0)z=b}async function B(){if(!P.hasFeature("sections"))return!1;let m=++ie;try{let b=await P.rpc("sidebar.sections",{open:Array.from(le)});if(m!==ie)return!0;let C=Array.isArray(b.sections)?b.sections:[];return Q=C,R(C),de.setData(z,A,te,ue),de.setSections(C,te,ue),De(),!0}catch{return!1}}function H(){if(!P.hasFeature("sections"))return;if(q!==null)window.clearTimeout(q);q=window.setTimeout(()=>{q=null,B()},150)}async function K(){if(qe=null,P.hasFeature("bots"))try{let b=await P.rpc("bots.list",{});te=b.bots??[],ue=b.rooms??[]}catch{}if(P.hasFeature("shell")){let b=await P.rpc("shell.sync",{have:st,settled:25}),C=new Set(b.removed??[]),k=new Set((b.projects??[]).map((O)=>O.id));if(C.size>0||k.size>0)z=[...z.filter((O)=>!C.has(O.id)&&!k.has(O.id)),...b.projects??[]],A=[...A.filter((O)=>!C.has(O.project)&&!k.has(O.project)),...b.threads??[]];else if(Array.isArray(b.threads)&&b.threads.length>0){let O=new Map(A.map((J)=>[J.id,J]));for(let J of b.threads)O.set(J.id,J);A=Array.from(O.values())}if(b.sections!==void 0){let O=Array.isArray(b.sections)?b.sections:Array.isArray(b.sections?.sections)?b.sections.sections:null;if(O)Q=O,R(O)}if(b.h)st=b.h;de.setData(z,A,te,ue),de.setSections(Q,te,ue)}else if(P.hasFeature("sections")){let[b,C]=await Promise.all([P.rpc("sidebar.sections",{open:Array.from(le)}).catch(()=>null),P.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(A=C.threads??[],b&&Array.isArray(b.sections)){let k=b.sections;if(!k.some((J)=>J.kind==="projects"&&J.rows.length>0)){let J=k.find((ae)=>ae.kind==="projects"&&ae.fold&&ae.toggle&&(ae.count??0)>0);if(J?.toggle&&!le.has(J.toggle)){le.add(J.toggle);let ae=await P.rpc("sidebar.sections",{open:Array.from(le)}).catch(()=>null);if(ae&&Array.isArray(ae.sections))k=ae.sections}}Q=k,R(k),de.setData(z,A,te,ue),de.setSections(k,te,ue)}else Q=null,z=(await P.rpc("projects.list",{limit:100})).projects??[],de.setSections(null,te,ue),de.setData(z,A,te,ue);await P.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{Q=null;let[b,C]=await Promise.all([P.rpc("projects.list",{limit:100}),P.rpc("threads.list",{limit:200,archived:!1})]);z=b.projects??[],A=C.threads??[],de.setSections(null,te,ue),de.setData(z,A,te,ue),await P.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let m=W;if(!m){let b="";try{b=localStorage.getItem("bp.lastThread")||""}catch{}if(b&&(Q&&j(Q,b)||A.some((C)=>C.id===b)))m=b;else if(Q)m=M(Q);if(!m)m=(A.find((k)=>!k.archived&&!k.swarm&&!k.settled)??A.find((k)=>!k.archived&&!k.swarm))?.id??""}if(m&&(Q&&j(Q,m)||A.some((b)=>b.id===m)))await _(m);else W="",Ae=[],Le.setItems([]),Z.setState(!1,!1),De()}async function _(m){if(W&&W!==m){Xe.cancel();let me=se.getEntries();if(me.length>0){let Y=ye.get(W);je(W,{entries:me,ids:Y?.ids??me.map((_e)=>_e.id),olderCursor:xe,review:Y?.review??null,unanswered:Y?.unanswered??null,rail:Y?.rail??Ae,hashes:Y?.hashes??{}})}}let b=++ee;Te++,Be(null);let C=qe;if(qe=null,C!==null)P.rpc("unsubscribe",{sub:C}).catch(()=>{});W=m;let k=ye.get(m);xe=k?.olderCursor??null;try{localStorage.setItem("bp.lastThread",m)}catch{}de.setSelected(m),X.classList.remove("bp-sidebar-open"),De();let O=A.find((me)=>me.id===m)??null;if(k)se.setThread(O,k.entries,Boolean(k.olderCursor),k.review,k.unanswered),Ae=k.rail,Le.setItems(k.rail);else se.setLoading(O),Ae=[],Le.setItems([]);if(Z.setState(!0,O?.state==="working"),P.hasFeature("open")){let me={};if(k){for(let[ve,at]of Object.entries(k.hashes))me[ve]=at;for(let ve of k.entries)if(ve.h)me[ve.id]=ve.h}let Y;try{Y=await P.rpc("thread.open",{thread:m,limit:40,have:me})}catch(ve){if(b===ee){let at=ve instanceof Error&&ve.message?ve.message:"Could not load messages.";se.setError(O,at,()=>{_(m)})}return}if(b!==ee){if(Y.sub!==void 0&&Y.sub!==null)P.rpc("unsubscribe",{sub:Y.sub}).catch(()=>{});return}if(qe=Y.sub??null,Y.thread){O=Y.thread;let ve=A.findIndex((at)=>at.id===Y.thread.id);if(ve>=0)A[ve]=Y.thread;else A.unshift(Y.thread);De(),Z.setState(!0,O.state==="working")}if("next"in Y)xe=Y.next??null;let _e=new Map;if(k)for(let ve of k.entries)_e.set(ve.id,ve);for(let ve of Y.entries??[])_e.set(ve.id,ve);let Ye=Y.ids??k?.ids??(Y.entries??[]).map((ve)=>ve.id),en=Ye.map((ve)=>_e.get(ve)).filter((ve)=>Boolean(ve)),ot=k?.rail??[];if(Y.rail!==void 0){if(Array.isArray(Y.rail))ot=Y.rail;else if(ot=Array.isArray(Y.rail?.rail)?Y.rail.rail:Array.isArray(Y.rail?.items)?Y.rail.items:[],Y.rail?.has){if(Ve?.reconcileHas?.(Y.rail.has),be&&!ui(Y.rail.has,be))Ke(!0)}}Ae=ot,Le.setItems(ot);let St=k?.review??null;if(P.hasFeature("reviewmode"))try{let ve=await P.rpc("thread.review",{thread:m});if(b!==ee)return;St=ve.review??null}catch{}if(b!==ee)return;let tn="unanswered"in Y?Y.unanswered??null:k?.unanswered??null,fi=Y.h??k?.hashes??{};if(je(m,{entries:en,ids:Ye,olderCursor:xe,review:St,unanswered:tn,rail:ot,hashes:fi}),se.setThread(O,en,Boolean(xe),St,tn),ce(m,b),be)et(be);return}let J;try{J=await P.rpc("thread.entries",{thread:m,limit:40})}catch(me){if(b===ee){let Y=me instanceof Error&&me.message?me.message:"Could not load messages.";se.setError(O,Y,()=>{_(m)})}return}if(b!==ee)return;if(J.thread){let me=A.findIndex((Y)=>Y.id===J.thread.id);if(me>=0)A[me]=J.thread;else A.unshift(J.thread);De()}xe=J.next??null;let ae=null;if(P.hasFeature("reviewmode"))try{let me=await P.rpc("thread.review",{thread:m});if(b!==ee)return;ae=me.review??null}catch{}if(b!==ee)return;let Ne=J.entries??[],Je=J.unanswered??null;je(m,{entries:Ne,ids:Ne.map((me)=>me.id),olderCursor:xe,review:ae,unanswered:Je,rail:k?.rail??[],hashes:k?.hashes??{}}),se.setThread(O,Ne,Boolean(xe),ae,Je);try{let Y=(await P.rpc("subscribe",{topic:"thread",thread:m})).sub??null;if(Y!==null){if(b!==ee){P.rpc("unsubscribe",{sub:Y}).catch(()=>{});return}qe=Y}}catch{}if(b!==ee)return;if(bt(m,b),ce(m,b),be)et(be)}async function ce(m,b){if(!m||!P.hasFeature("mgmt")){if(b===ee)We.clear();return}let C=A.find((O)=>O.id===m),k=C?.project?z.find((O)=>O.id===C.project)?.root??"":"";if(!k&&P.hasFeature("viewers"))try{let O=await P.rpc("viewer.files",{thread:m});if(b!==ee)return;k=O.pcb||O.sch||O.root||""}catch{}if(b!==ee)return;if(k)await We.watchProject(k);else We.clear()}async function oe(m){let b=ee;for(let C=0;C<25&&b===ee;C++){if(se.goTo(m))return;if(!xe)return;let k=xe;if(await fe(),xe===k)return}}async function fe(){if(!W||!xe){se.clearLoadingOlder();return}let m=ee,b=W,C=xe;try{let k=await P.rpc("thread.entries",{thread:b,limit:40,before:C});if(m!==ee||W!==b)return;xe=k.next??null,se.prependEntries(k.entries??[],Boolean(xe))}catch{if(m===ee)se.clearLoadingOlder()}}async function Ce(m){try{let b=await P.rpc("thread.create",{project:m});if(b.thread)A=[b.thread,...A.filter((C)=>C.id!==b.thread.id)],de.setData(z,A,te,ue),B(),await _(b.thread.id),Z.focus()}catch(b){Z.showError(b instanceof Error?b.message:"Could not create thread")}}let pe=null;function Ee(m){return(m.split(` -`).map((b)=>b.trim()).find((b)=>b.length>0)??"").slice(0,200)}function Be(m){pe=m,Z.setReply(m?{who:m.role==="user"?v("secret.you","You"):v("model.col.agent","Agent"),line:Ee(m.text)}:null,()=>{if(pe)oe(pe.id)},()=>Be(null))}async function Ie(m,b=[]){if(!W)return;let C=ee,k=W,O=ts(),J=`local-${O}`,ae=pe&&m.trim()&&P.hasFeature("reply")?pe:null;if(ae)Be(null);se.upsertEntry({id:J,kind:"user",text:m,at:Date.now(),clientId:O,...ae?{replyTo:{id:ae.id,quote:Ee(ae.text)}}:{},attachments:b.map((Ne)=>({name:Ne.name,mime:Ne.mime,previewUrl:`data:${Ne.mime};base64,${Ne.data}`}))});try{let Ne={thread:k,text:m,clientId:O};if(b.length>0)Ne.attachments=b;if(ae)Ne.replyTo={id:ae.id,text:ae.text};let Je=await P.rpc("message.send",Ne);if(C!==ee||W!==k)return;if(Je.entry)se.upsertEntry(Je.entry)}catch(Ne){if(C===ee&&W===k){if(se.removeEntry(J),Z.setDraft(m),ae&&!pe)Be(ae);Z.showError(Ne instanceof Error?Ne.message:"Failed to send message")}}}async function rt(m){if(!W)return;let b=ee,C=W;try{let k=await P.rpc("composer.run",{thread:C,text:m});if(b!==ee||W!==C)return;if(k.error)Z.setDraft(m),Z.showError(k.error);else if(k.kind==="edit"&&typeof k.text==="string")Z.setDraft(k.text);else if(k.kind==="project")Fe.open({mode:"folder"});else if(k.kind==="clone")Fe.open({mode:"clone",repo:k.repo??"",text:k.text??""})}catch(k){if(b===ee&&W===C)Z.setDraft(m),Z.showError(k instanceof Error?k.message:"Command refused")}}async function Ge(m,b){try{let C=await P.rpc("thread.act",{thread:m,action:b});if(C.thread){if(A=A.map((k)=>k.id===C.thread.id?C.thread:k),de.setData(z,A,te,ue),C.thread.id===W)se.updateThreadMeta(C.thread),De()}B()}catch(C){Z.showError(C instanceof Error?C.message:`Action "${b}" not allowed`)}}function Oe(m,b){if(!m||!m.text||b-m.at>=300000)return"";let C=m.build.split("-").pop()??"";if(m.reason==="build"&&C)return v("hub.restarting.build",m.text,{build:C});if(m.reason==="stop")return v("hub.stopped",m.text);return v("hub.restarting",m.text)}function ft(m){if(m==="connected")de.setConnStatus(v("gpui.acct.connected","Connected"),"bp-ok");else if(m==="reconnecting"&&Oe(P.restarting,Date.now()))de.setConnStatus(Oe(P.restarting,Date.now()),"");else if(m==="reconnecting")de.setConnStatus("Reconnecting…","bp-warn");else if(m==="revoked")de.setConnStatus(v("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else de.setConnStatus("Connecting…","")}gt(()=>{ft(P.getState()),F.textContent=v("gpui.improvements","Improvements"),I.title=v("palette.settings","Settings"),I.setAttribute("aria-label",v("palette.settings","Settings")),De(),de.refreshLocale(),se.refreshLocale(),Z.refreshLocale(),Le.render(),Re.refreshLocale(),Fe.refreshLocale()}),P.onState((m,b)=>{if(m==="connected"&&b){if(b.locale)cn(b.locale);if(b.theme)mi(b.theme);if(b.name)de.setHostName(b.name);if($e=b.home??null,de.setHome($e),Re.isOpen())Re.refresh();ft(m);let C=typeof b.hubBack==="string"?String(b.hubBack):"";if(C)try{let k=JSON.parse(C);if(k.reason==="crash")de.setConnStatus(v("hub.back.crash",k.text??""),"bp-warn"),window.setTimeout(()=>ft(P.getState()),6000)}catch{}if(Z.setFeatures(P.hasFeature("images"),P.hasFeature("voice")),Array.isArray(b.commands))Me=b.commands,Z.setCommands(Me);else Me=[];K(),Fe.reconcile()}else Xe.cancel(),ft(m)}),P.onFrame((m)=>{if(m.t==="voice"){Xe.handleFrame(m);return}if(m.t==="info"&&m.info&&typeof m.info==="object"){We.handleInfo(m.info);return}if(m.t!=="d")return;let b=m;if(b.k==="clone"||b.k==="clone.repos"||b.k==="clone.signin"){Fe.handleFrame(b);return}switch(b.k){case"project":{let C=b.project;if(!C)break;let k=z.findIndex((O)=>O.id===C.id);if(k>=0)z[k]=C;else z.unshift(C);de.setData(z,A,te,ue),De(),H();break}case"thread":{let C=b.thread;if(!C)break;let k=A.findIndex((O)=>O.id===C.id);if(k>=0)A[k]=C;else A.unshift(C);if(de.setData(z,A,te,ue),C.id===W)se.updateThreadMeta(C),De(),Z.setState(!0,C.state==="working");H();break}case"thread.removed":{let C=String(b.id??"");A=A.filter((k)=>k.id!==C),de.setData(z,A,te,ue),H();break}case"entry":{if(b.thread===W&&b.entry)se.upsertEntry(b.entry);break}case"text":{if(b.thread===W)se.appendLiveText(String(b.entry??""),String(b.append??""),Number(b.at??Date.now()));break}case"turn":{if(b.thread===W){let C=String(b.state??"idle");Z.setState(!0,C==="working"),bt(W,ee)}H();break}case"btw":{if(b.thread===W)se.showBtw(String(b.q??""),String(b.a??""));break}case"unanswered":{if(b.thread===W)se.setUnanswered(b.unanswered??null);break}case"theme":{if(typeof b.theme==="string")mi(b.theme);break}case"home":{if($e=b.home??null,de.setHome($e),Re.isOpen())Re.refresh();break}default:break}}),window.addEventListener("keydown",(m)=>{let b=m.key.toLowerCase();if((m.ctrlKey||m.metaKey)&&(b==="k"||m.shiftKey&&b==="p"))if(m.preventDefault(),Ue.isOpen())Ue.close();else Ue.open();else if(m.key==="Escape"){if(Ue.isOpen())Ue.close();else if(Fe.isOpen())Fe.escape();else if(Re.isOpen())Re.close();else if(We.isOpen())We.closePanel()}}),P.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",bi);else bi(); +`);return}if(!m.text||!m.text.trim()||m.live||m.id.startsWith("local-"))return;Te({id:m.id,text:m.text,role:m.kind==="user"?"user":"assistant"})},onLoadImage:async(m,b)=>{try{let C={entry:m,path:b};if(T.hasFeature("blobs"))C.metaOnly=!0;let k=await T.rpc("message.image",C);if(k.blob&&k.blob.startsWith("/blob/"))return{url:k.blob};if(k.mime&&k.data)return{mime:k.mime,data:k.data}}catch{}return null}}),Xe,Z=new Ht(oe,{onSend:(m,b)=>{rt(m,b)},onRunCommand:(m)=>{gt(m)},onInterrupt:()=>{if(W)T.rpc("turn.interrupt",{thread:W}).catch(()=>{})},onQueryMentions:async(m,b)=>{try{return(await T.rpc("mentions.list",{q:m,kind:b,limit:10})).items??[]}catch{return[]}},onToggleVoice:()=>{Xe.toggle()}});Xe=new Kt(T,{getThreadId:()=>W,getDraft:()=>Z.getDraft(),getCaret:()=>Z.getCaret(),setDraft:(m)=>Z.setDraft(m),setRecording:(m)=>Z.setVoiceRecording(m),setLevel:(m)=>Z.setVoiceLevel(m),showError:(m)=>Z.showError(m)});function Qe(){let m=fe!=="",b=We.isOpen();ie.classList.toggle("bp-hidden",!m&&!b),ie.classList.toggle("bp-has-viewer",m),ie.classList.toggle("bp-has-mgmt",b)}let We=new Gt(Ae,ie,{hub:T,getThreadId:()=>W,getThreadGen:()=>ee,onSendText:(m)=>{rt(m)},onOpenChange:()=>Qe()});function ze(m){let b=window.prompt("Rename thread",m.title||"");if(!b||!b.trim())return;T.rpc("thread.act",{thread:m.id,action:"rename",title:b.trim()}).then((C)=>{if(C.thread)A=A.map((k)=>k.id===C.thread.id?C.thread:k),He(),R()}).catch((C)=>{Z.showError(C instanceof Error?C.message:"Could not rename thread")})}function Lt(m){switch(m.type){case"thread":te(m.id);break;case"rail":if(!W&&m.id!=="terminal")break;if(fe===m.id)Ke();else Ze(m.id);break;case"thread-act":if(W)Be(W,m.action);break;case"new-thread":we(m.projectId);break;case"rename":{let b=A.find((C)=>C.id===W);if(b)ze(b);break}case"prev-thread":case"next-thread":{let b=A.filter((J)=>!J.archived&&!J.swarm);if(b.length<2)break;let C=b.findIndex((J)=>J.id===W),k=m.type==="next-thread"?1:-1,O=b[(C<0?0:C+k+b.length)%b.length];if(O)te(O.id);break}case"command":if(m.runDirectly)gt(m.word);else Z.setDraft(`${m.word} `),Z.focus();break;case"improvements":ft();break;case"settings":je.open();break;case"sidebar":X.classList.toggle("bp-sidebar-open"),X.classList.toggle("bp-sidebar-collapsed");break}}let Oe=new Ot(e,{getState:()=>({selectedThreadId:W,threads:A,projects:z,bots:ne,railItems:Le,commands:Re}),onSearch:async(m)=>{if(!T.hasFeature("search"))return{threads:[],projects:[],messages:[]};return T.rpc("search",{q:m,limit:20})},onExecute:Lt}),Ue=new It(e,{hub:T,onProjectAdded:(m)=>{if(R(),m.id)we(m.id)},onCloneDone:(m)=>{if(R(),m.thread)te(m.thread)}}),Ne=new Vt(he,(m)=>{if(m==="commands"){Oe.open();return}if(!W)return;if(fe===m)Ke();else Ze(m)}),Ge=null,je=new Wt(e,{onLoadDevices:async()=>(await T.rpc("devices.page",{})).rows??[],onDevicesAct:async(m,b)=>{await T.rpc("devices.page.act",{action:m,value:b})},onGetHome:()=>Ge,onMoveHomeHere:async()=>{await T.rpc("home.move",{to:"back"})},onLogout:()=>En(()=>{T.disconnect(),window.location.replace("/")})});E.addEventListener("click",()=>{let m=A.find((b)=>b.id===W);if(m)Be(m.id,m.pinned?"unpin":"pin")}),g.addEventListener("click",()=>{let m=A.find((b)=>b.id===W);if(m)Be(m.id,m.settled?"unsettle":"settle")});let st=new qt(e,(m,b)=>b?T.rpc("thread.context.mcp",{thread:m,...b}):T.rpc("thread.context",{thread:m}));S.addEventListener("click",(m)=>{m.stopPropagation();let b=A.find((O)=>O.id===W);if(!b)return;if(!L.classList.contains("bp-hidden")){L.classList.add("bp-hidden");return}let C=[{label:"Rename…",run:()=>ze(b)},{label:b.pinned?f("menu.unpin","Unpin"):f("menu.pin","Pin"),run:()=>{Be(b.id,b.pinned?"unpin":"pin")}},{label:b.settled?f("phone.unsettle","Unsettle"):f("menu.settle","Settle"),run:()=>{Be(b.id,b.settled?"unsettle":"settle")}},{label:b.archived?"Unarchive":"Archive",run:()=>{Be(b.id,b.archived?"unarchive":"archive")}},{label:"Delete",danger:!0,run:()=>{if(window.confirm("Delete this thread?"))Be(b.id,"delete")}}];if(T.hasFeature("threadContext"))C.unshift({label:f("thread.context.title","Context & Prompt"),run:()=>st.open(b.id)});let k=document.createDocumentFragment();for(let O of C){let J=document.createElement("button");J.type="button",J.className="bp-popover-item"+(O.danger?" danger":""),J.textContent=O.label,J.addEventListener("click",()=>{L.classList.add("bp-hidden"),O.run()}),k.appendChild(J)}L.replaceChildren(k),L.classList.remove("bp-hidden")}),document.addEventListener("click",()=>L.classList.add("bp-hidden"));async function ft(){let m=document.createElement("div");m.className="bp-modal-backdrop",m.setAttribute("data-testid","improvements-modal");let b=document.createElement("div");b.className="bp-modal";let C=document.createElement("div");C.className="bp-modal-head";let k=document.createElement("h2");k.textContent=f("gpui.improvements","Improvements");let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>m.remove()),C.append(k,O);let J=document.createElement("div");J.className="bp-modal-body",J.textContent="Loading…",b.append(C,J),m.appendChild(b),m.addEventListener("click",(ce)=>{if(ce.target===m)m.remove()}),e.appendChild(m);try{let ce=await T.rpc("improvements.projects",{}),Pe=ce.projects??[];if(Pe.length===0){J.textContent="No projects available for Improvements.";return}let Je=document.createDocumentFragment();for(let be of Pe){let Y=document.createElement("div");Y.className="bp-set-row";let _e=document.createElement("div");_e.className="bp-set-info",_e.textContent=be.title||be.name||be.id;let Ye=document.createElement("button");Ye.type="button",Ye.className=be.id===ce.project?"primary":"",Ye.textContent=be.id===ce.project?"Active":"Select",Ye.addEventListener("click",()=>{T.rpc("improvements.project",{project:be.id}).then(()=>m.remove()).catch(()=>{})}),Y.append(_e,Ye),Je.appendChild(Y)}J.replaceChildren(Je)}catch(ce){J.textContent=ce instanceof Error?ce.message:"Could not load Improvements."}}N.addEventListener("click",()=>{ft()}),U.addEventListener("click",()=>Oe.open()),G.addEventListener("click",()=>Oe.open()),B.addEventListener("click",()=>{je.open()}),n.addEventListener("click",()=>{X.classList.toggle("bp-sidebar-open"),X.classList.toggle("bp-sidebar-collapsed")});function He(){let m=A.find((C)=>C.id===W)??null,b=m?z.find((C)=>C.id===m.project):void 0;if(c.textContent=b?.title??"",o.classList.toggle("bp-hidden",!b),a.classList.toggle("bp-hidden",!m),d.textContent=m?m.title||"Untitled thread":"",l.classList.toggle("bp-hidden",!m),y.classList.toggle("bp-hidden",!m),m){p.className=`bp-dot ${as(m)}`,u.textContent=m.status||m.state||"idle",v.textContent=m.pinned?f("menu.unpin","Unpin"):f("menu.pin","Pin"),w.textContent=m.settled?f("phone.unsettle","Unsettle"):f("menu.settle","Settle");let C=m;Z.setModelChip(m.chip||m.model||"default",m.provider,C.ctxPct??C.contextPct),Z.setMemory(m.memory)}else Z.setModelChip("default"),Z.setMemory(null)}function Ke(m=!0){if(Me++,fe="",Ne.setActive(""),ve.classList.add("bp-hidden"),Ve?.close(),Qe(),m&&W&&T.getState()==="connected")T.rpc("viewer.watch",{thread:W,kind:""}).catch(()=>{})}function Ze(m){if(Me++,fe=m,Ne.setActive(m),ve.classList.remove("bp-hidden"),Qe(),!Ve&&typeof rn==="function")Ve=rn(ve,{hub:T,getThreadId:()=>W,closeViewer:()=>Ke(!0)});if(Ve)Ve.open(m,W);else{let b=document.createElement("div");b.className="bp-viewer-placeholder";let C=document.createElement("div");C.className="bp-viewer-bar";let k=document.createElement("span");k.textContent=m.toUpperCase();let O=document.createElement("button");O.type="button",O.className="icon",O.textContent="×",O.addEventListener("click",()=>Ke(!0)),C.append(k,O);let J=document.createElement("div");J.className="bp-dim bp-viewer-msg",J.textContent=`Viewer pane (${m}).`,b.append(C,J),ve.replaceChildren(b)}}async function M(m,b){if(!m||!T.hasFeature("rail")){if(b===ee)Le=[],Ne.setItems([]);return}let C=++Me;try{let k=await T.rpc("viewer.rail",{thread:m,page:fe});if(b!==ee||C!==Me)return;let O=Array.isArray(k.rail)?k.rail:Array.isArray(k.items)?k.items:[];if(Le=O,Ne.setItems(O),k.has){if(Ve?.reconcileHas?.(k.has),fe&&!wi(k.has,fe))Ke(!0)}}catch{if(b===ee&&C===Me)Le=[],Ne.setItems([])}}function H(m){for(let b of m)if(b.kind==="threads"){for(let C of b.rows)if(!C.off&&(C.nav||C.id)&&!(C.nav||"").startsWith("@room:"))return C.nav||C.id}else if(b.kind==="projects"){for(let C of b.rows)for(let k of C.threads??[])if(!k.off&&(k.nav||k.id)&&!(k.nav||"").startsWith("@room:"))return k.nav||k.id}return""}function j(m,b){for(let C of m)if(C.kind==="threads"){if(C.rows.some((k)=>(k.nav||k.id)===b))return!0}else if(C.kind==="projects"){for(let k of C.rows)if((k.threads??[]).some((O)=>(O.nav||O.id)===b))return!0}return!1}function I(m){let b=[];for(let C of m){if(C.kind!=="projects")continue;for(let k of C.rows)b.push({id:k.id,title:k.title,css:k.css,color:k.color})}if(b.length>0)z=b}async function R(){if(!T.hasFeature("sections"))return!1;let m=++se;try{let b=await T.rpc("sidebar.sections",{open:Array.from(de)});if(m!==se)return!0;let C=Array.isArray(b.sections)?b.sections:[];return Q=C,I(C),pe.setData(z,A,ne,ue),pe.setSections(C,ne,ue),He(),!0}catch{return!1}}function q(){if(!T.hasFeature("sections"))return;if(_!==null)window.clearTimeout(_);_=window.setTimeout(()=>{_=null,R()},150)}async function K(){if(qe=null,T.hasFeature("bots"))try{let b=await T.rpc("bots.list",{});ne=b.bots??[],ue=b.rooms??[]}catch{}if(T.hasFeature("shell")){let b=await T.rpc("shell.sync",{have:it,settled:25}),C=new Set(b.removed??[]),k=new Set((b.projects??[]).map((O)=>O.id));if(C.size>0||k.size>0)z=[...z.filter((O)=>!C.has(O.id)&&!k.has(O.id)),...b.projects??[]],A=[...A.filter((O)=>!C.has(O.project)&&!k.has(O.project)),...b.threads??[]];else if(Array.isArray(b.threads)&&b.threads.length>0){let O=new Map(A.map((J)=>[J.id,J]));for(let J of b.threads)O.set(J.id,J);A=Array.from(O.values())}if(b.sections!==void 0){let O=Array.isArray(b.sections)?b.sections:Array.isArray(b.sections?.sections)?b.sections.sections:null;if(O)Q=O,I(O)}if(b.h)it=b.h;pe.setData(z,A,ne,ue),pe.setSections(Q,ne,ue)}else if(T.hasFeature("sections")){let[b,C]=await Promise.all([T.rpc("sidebar.sections",{open:Array.from(de)}).catch(()=>null),T.rpc("threads.list",{limit:200,archived:!1}).catch(()=>({threads:[]}))]);if(A=C.threads??[],b&&Array.isArray(b.sections)){let k=b.sections;if(!k.some((J)=>J.kind==="projects"&&J.rows.length>0)){let J=k.find((ce)=>ce.kind==="projects"&&ce.fold&&ce.toggle&&(ce.count??0)>0);if(J?.toggle&&!de.has(J.toggle)){de.add(J.toggle);let ce=await T.rpc("sidebar.sections",{open:Array.from(de)}).catch(()=>null);if(ce&&Array.isArray(ce.sections))k=ce.sections}}Q=k,I(k),pe.setData(z,A,ne,ue),pe.setSections(k,ne,ue)}else Q=null,z=(await T.rpc("projects.list",{limit:100})).projects??[],pe.setSections(null,ne,ue),pe.setData(z,A,ne,ue);await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}else{Q=null;let[b,C]=await Promise.all([T.rpc("projects.list",{limit:100}),T.rpc("threads.list",{limit:200,archived:!1})]);z=b.projects??[],A=C.threads??[],pe.setSections(null,ne,ue),pe.setData(z,A,ne,ue),await T.rpc("subscribe",{topic:"lists"}).catch(()=>{})}let m=W;if(!m){let b="";try{b=localStorage.getItem("bp.lastThread")||""}catch{}if(b&&(Q&&j(Q,b)||A.some((C)=>C.id===b)))m=b;else if(Q)m=H(Q);if(!m)m=(A.find((k)=>!k.archived&&!k.swarm&&!k.settled)??A.find((k)=>!k.archived&&!k.swarm))?.id??""}if(m&&(Q&&j(Q,m)||A.some((b)=>b.id===m)))await te(m);else W="",Le=[],Ne.setItems([]),Z.setState(!1,!1),He()}async function te(m){if(W&&W!==m){Xe.cancel();let be=re.getEntries();if(be.length>0){let Y=Ce.get(W);De(W,{entries:be,ids:Y?.ids??be.map((_e)=>_e.id),olderCursor:ke,review:Y?.review??null,unanswered:Y?.unanswered??null,rail:Y?.rail??Le,hashes:Y?.hashes??{}})}}let b=++ee;Me++,Te(null);let C=qe;if(qe=null,C!==null)T.rpc("unsubscribe",{sub:C}).catch(()=>{});W=m;let k=Ce.get(m);ke=k?.olderCursor??null;try{localStorage.setItem("bp.lastThread",m)}catch{}pe.setSelected(m),X.classList.remove("bp-sidebar-open"),He();let O=A.find((be)=>be.id===m)??null;if(k)re.setThread(O,k.entries,Boolean(k.olderCursor),k.review,k.unanswered),Le=k.rail,Ne.setItems(k.rail);else re.setLoading(O),Le=[],Ne.setItems([]);if(Z.setState(!0,O?.state==="working"),T.hasFeature("open")){let be={};if(k){for(let[ye,at]of Object.entries(k.hashes))be[ye]=at;for(let ye of k.entries)if(ye.h)be[ye.id]=ye.h}let Y;try{Y=await T.rpc("thread.open",{thread:m,limit:40,have:be})}catch(ye){if(b===ee){let at=ye instanceof Error&&ye.message?ye.message:"Could not load messages.";re.setError(O,at,()=>{te(m)})}return}if(b!==ee){if(Y.sub!==void 0&&Y.sub!==null)T.rpc("unsubscribe",{sub:Y.sub}).catch(()=>{});return}if(qe=Y.sub??null,Y.thread){O=Y.thread;let ye=A.findIndex((at)=>at.id===Y.thread.id);if(ye>=0)A[ye]=Y.thread;else A.unshift(Y.thread);He(),Z.setState(!0,O.state==="working")}if("next"in Y)ke=Y.next??null;let _e=new Map;if(k)for(let ye of k.entries)_e.set(ye.id,ye);for(let ye of Y.entries??[])_e.set(ye.id,ye);let Ye=Y.ids??k?.ids??(Y.entries??[]).map((ye)=>ye.id),an=Ye.map((ye)=>_e.get(ye)).filter((ye)=>Boolean(ye)),ot=k?.rail??[];if(Y.rail!==void 0){if(Array.isArray(Y.rail))ot=Y.rail;else if(ot=Array.isArray(Y.rail?.rail)?Y.rail.rail:Array.isArray(Y.rail?.items)?Y.rail.items:[],Y.rail?.has){if(Ve?.reconcileHas?.(Y.rail.has),fe&&!wi(Y.rail.has,fe))Ke(!0)}}Le=ot,Ne.setItems(ot);let Nt=k?.review??null;if(T.hasFeature("reviewmode"))try{let ye=await T.rpc("thread.review",{thread:m});if(b!==ee)return;Nt=ye.review??null}catch{}if(b!==ee)return;let cn="unanswered"in Y?Y.unanswered??null:k?.unanswered??null,xi=Y.h??k?.hashes??{};if(De(m,{entries:an,ids:Ye,olderCursor:ke,review:Nt,unanswered:cn,rail:ot,hashes:xi}),re.setThread(O,an,Boolean(ke),Nt,cn),ae(m,b),fe)Ze(fe);return}let J;try{J=await T.rpc("thread.entries",{thread:m,limit:40})}catch(be){if(b===ee){let Y=be instanceof Error&&be.message?be.message:"Could not load messages.";re.setError(O,Y,()=>{te(m)})}return}if(b!==ee)return;if(J.thread){let be=A.findIndex((Y)=>Y.id===J.thread.id);if(be>=0)A[be]=J.thread;else A.unshift(J.thread);He()}ke=J.next??null;let ce=null;if(T.hasFeature("reviewmode"))try{let be=await T.rpc("thread.review",{thread:m});if(b!==ee)return;ce=be.review??null}catch{}if(b!==ee)return;let Pe=J.entries??[],Je=J.unanswered??null;De(m,{entries:Pe,ids:Pe.map((be)=>be.id),olderCursor:ke,review:ce,unanswered:Je,rail:k?.rail??[],hashes:k?.hashes??{}}),re.setThread(O,Pe,Boolean(ke),ce,Je);try{let Y=(await T.rpc("subscribe",{topic:"thread",thread:m})).sub??null;if(Y!==null){if(b!==ee){T.rpc("unsubscribe",{sub:Y}).catch(()=>{});return}qe=Y}}catch{}if(b!==ee)return;if(M(m,b),ae(m,b),fe)Ze(fe)}async function ae(m,b){if(!m||!T.hasFeature("mgmt")){if(b===ee)We.clear();return}let C=A.find((O)=>O.id===m),k=C?.project?z.find((O)=>O.id===C.project)?.root??"":"";if(!k&&T.hasFeature("viewers"))try{let O=await T.rpc("viewer.files",{thread:m});if(b!==ee)return;k=O.pcb||O.sch||O.root||""}catch{}if(b!==ee)return;if(k)await We.watchProject(k);else We.clear()}async function ge(m){let b=ee;for(let C=0;C<25&&b===ee;C++){if(re.goTo(m))return;if(!ke)return;let k=ke;if(await Se(),ke===k)return}}async function Se(){if(!W||!ke){re.clearLoadingOlder();return}let m=ee,b=W,C=ke;try{let k=await T.rpc("thread.entries",{thread:b,limit:40,before:C});if(m!==ee||W!==b)return;ke=k.next??null,re.prependEntries(k.entries??[],Boolean(ke))}catch{if(m===ee)re.clearLoadingOlder()}}async function we(m){try{let b=await T.rpc("thread.create",{project:m});if(b.thread)A=[b.thread,...A.filter((C)=>C.id!==b.thread.id)],pe.setData(z,A,ne,ue),R(),await te(b.thread.id),Z.focus()}catch(b){Z.showError(b instanceof Error?b.message:"Could not create thread")}}let me=null;function Fe(m){return(m.split(` +`).map((b)=>b.trim()).find((b)=>b.length>0)??"").slice(0,200)}function Te(m){me=m,Z.setReply(m?{who:m.role==="user"?f("secret.you","You"):f("model.col.agent","Agent"),line:Fe(m.text)}:null,()=>{if(me)ge(me.id)},()=>Te(null))}async function rt(m,b=[]){if(!W)return;let C=ee,k=W,O=cs(),J=`local-${O}`,ce=me&&m.trim()&&T.hasFeature("reply")?me:null;if(ce)Te(null);re.upsertEntry({id:J,kind:"user",text:m,at:Date.now(),clientId:O,...ce?{replyTo:{id:ce.id,quote:Fe(ce.text)}}:{},attachments:b.map((Pe)=>({name:Pe.name,mime:Pe.mime,previewUrl:`data:${Pe.mime};base64,${Pe.data}`}))});try{let Pe={thread:k,text:m,clientId:O};if(b.length>0)Pe.attachments=b;if(ce)Pe.replyTo={id:ce.id,text:ce.text};let Je=await T.rpc("message.send",Pe);if(C!==ee||W!==k)return;if(Je.entry)re.upsertEntry(Je.entry)}catch(Pe){if(C===ee&&W===k){if(re.removeEntry(J),Z.setDraft(m),ce&&!me)Te(ce);Z.showError(Pe instanceof Error?Pe.message:"Failed to send message")}}}async function gt(m){if(!W)return;let b=ee,C=W;try{let k=await T.rpc("composer.run",{thread:C,text:m});if(b!==ee||W!==C)return;if(k.error)Z.setDraft(m),Z.showError(k.error);else if(k.kind==="edit"&&typeof k.text==="string")Z.setDraft(k.text);else if(k.kind==="project")Ue.open({mode:"folder"});else if(k.kind==="clone")Ue.open({mode:"clone",repo:k.repo??"",text:k.text??""})}catch(k){if(b===ee&&W===C)Z.setDraft(m),Z.showError(k instanceof Error?k.message:"Command refused")}}async function Be(m,b){try{let C=await T.rpc("thread.act",{thread:m,action:b});if(C.thread){if(A=A.map((k)=>k.id===C.thread.id?C.thread:k),pe.setData(z,A,ne,ue),C.thread.id===W)re.updateThreadMeta(C.thread),He()}R()}catch(C){Z.showError(C instanceof Error?C.message:`Action "${b}" not allowed`)}}function on(m,b){if(!m||!m.text||b-m.at>=300000)return"";let C=m.build.split("-").pop()??"";if(m.reason==="build"&&C)return f("hub.restarting.build",m.text,{build:C});if(m.reason==="stop")return f("hub.stopped",m.text);return f("hub.restarting",m.text)}function vt(m){if(m==="connected")pe.setConnStatus(f("gpui.acct.connected","Connected"),"bp-ok");else if(m==="reconnecting"&&on(T.restarting,Date.now()))pe.setConnStatus(on(T.restarting,Date.now()),"");else if(m==="reconnecting")pe.setConnStatus("Reconnecting…","bp-warn");else if(m==="revoked")pe.setConnStatus(f("gpui.acct.sign.in.expired","Sign-in expired"),"bp-bad");else pe.setConnStatus("Connecting…","")}wt(()=>{vt(T.getState()),F.textContent=f("gpui.improvements","Improvements"),B.title=f("palette.settings","Settings"),B.setAttribute("aria-label",f("palette.settings","Settings")),He(),pe.refreshLocale(),re.refreshLocale(),Z.refreshLocale(),Ne.render(),je.refreshLocale(),Ue.refreshLocale()}),T.onState((m,b)=>{if(m==="connected"&&b){if(b.locale)mn(b.locale);if(b.theme)yi(b.theme);if(b.name)pe.setHostName(b.name);if(Ge=b.home??null,pe.setHome(Ge),je.isOpen())je.refresh();vt(m);let C=typeof b.hubBack==="string"?String(b.hubBack):"";if(C)try{let k=JSON.parse(C);if(k.reason==="crash")pe.setConnStatus(f("hub.back.crash",k.text??""),"bp-warn"),window.setTimeout(()=>vt(T.getState()),6000)}catch{}if(Z.setFeatures(T.hasFeature("images"),T.hasFeature("voice")),Array.isArray(b.commands))Re=b.commands,Z.setCommands(Re);else Re=[];K(),Ue.reconcile()}else Xe.cancel(),vt(m)}),T.onFrame((m)=>{if(m.t==="voice"){Xe.handleFrame(m);return}if(m.t==="info"&&m.info&&typeof m.info==="object"){We.handleInfo(m.info);return}if(m.t!=="d")return;let b=m;if(b.k==="clone"||b.k==="clone.repos"||b.k==="clone.signin"){Ue.handleFrame(b);return}switch(b.k){case"project":{let C=b.project;if(!C)break;let k=z.findIndex((O)=>O.id===C.id);if(k>=0)z[k]=C;else z.unshift(C);pe.setData(z,A,ne,ue),He(),q();break}case"thread":{let C=b.thread;if(!C)break;let k=A.findIndex((O)=>O.id===C.id);if(k>=0)A[k]=C;else A.unshift(C);if(pe.setData(z,A,ne,ue),C.id===W)re.updateThreadMeta(C),He(),Z.setState(!0,C.state==="working");q();break}case"thread.removed":{let C=String(b.id??"");A=A.filter((k)=>k.id!==C),pe.setData(z,A,ne,ue),q();break}case"entry":{if(b.thread===W&&b.entry)re.upsertEntry(b.entry);break}case"text":{if(b.thread===W)re.appendLiveText(String(b.entry??""),String(b.append??""),Number(b.at??Date.now()));break}case"turn":{if(b.thread===W){let C=String(b.state??"idle");Z.setState(!0,C==="working"),M(W,ee)}q();break}case"btw":{if(b.thread===W)re.showBtw(String(b.q??""),String(b.a??""));break}case"unanswered":{if(b.thread===W)re.setUnanswered(b.unanswered??null);break}case"theme":{if(typeof b.theme==="string")yi(b.theme);break}case"home":{if(Ge=b.home??null,pe.setHome(Ge),je.isOpen())je.refresh();break}default:break}}),window.addEventListener("keydown",(m)=>{let b=m.key.toLowerCase();if((m.ctrlKey||m.metaKey)&&(b==="k"||m.shiftKey&&b==="p"))if(m.preventDefault(),Oe.isOpen())Oe.close();else Oe.open();else if(m.key==="Escape"){if(Oe.isOpen())Oe.close();else if(Ue.isOpen())Ue.escape();else if(je.isOpen())je.close();else if(We.isOpen())We.closePanel()}}),T.connect()}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",Ei);else Ei(); diff --git a/web/dist/assets/pair.js b/web/dist/assets/pair.js index 57481f4efd..3f3eba6862 100644 --- a/web/dist/assets/pair.js +++ b/web/dist/assets/pair.js @@ -1 +1 @@ -var F={en:{"agy.signout":"Sign out","android.load.earlier":"load earlier","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.stop":"Stop routing","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection."},es:{"agy.signout":"Cerrar sesión","android.load.earlier":"cargar anteriores","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.stop":"Detener ruteo","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet."},ja:{"agy.signout":"サインアウト","android.load.earlier":"以前のメッセージを読み込む","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.stop":"配線を止める","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。"}};function Y(n,t){if(!t)return n;return n.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(c,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):c)}var O=te(),_=new Set,W=new Map;for(let[n,t]of Object.entries(F.en||{}))if(typeof t==="string"&&!W.has(t))W.set(t,n);function te(){let n=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(n.startsWith("ja"))return"ja";if(n.startsWith("es"))return"es";return"en"}function J(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=O}J();function me(n){return _.add(n),()=>{_.delete(n)}}function ue(n){if(!n)return!1;let t=n.toLowerCase(),c=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!c)return!1;let r=c!==O;if(O=c,J(),r)for(let d of _)d(O);return r}function p(n,t,c){let d=(F[O]||F.en||{})[n]??F.en?.[n]??t??n;return Y(d,c)}function ge(n){if(!n)return"";let t=W.get(n);if(!t)return n;return p(t,n)}var ne=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],z=new Uint8Array(512),V=new Uint8Array(256);{let n=1;for(let t=0;t<255;t++)if(z[t]=n,V[n]=t,n<<=1,n&256)n^=285;for(let t=255;t<512;t++)z[t]=z[t-255]}function K(n,t){return n===0||t===0?0:z[V[n]+V[t]]}function ae(n){let t=new Uint8Array([1]);for(let c=0;c{let m=e-i*a;return Math.ceil((12+t.length*8)/8)<=m});if(!c)return null;let[r,d,u,f,E]=c,w=d-u*f,g=[],j=(e,i)=>{for(let a=i-1;a>=0;a--)g.push(e>>>a&1)};j(4,4),j(t.length,8);for(let e of t)j(e,8);for(let e=0;e<4&&g.length{if(e<0||i<0||e>=s||i>=s)return;G[e*s+i]=a?1:0,C[e*s+i]=1},N=(e,i)=>{for(let a=-1;a<=7;a++)for(let m=-1;m<=7;m++){let k=e+a,l=i+m,o=a>=0&&a<=6&&m>=0&&m<=6&&(a===0||a===6||m===0||m===6||a>=2&&a<=4&&m>=2&&m<=4);b(k,l,o)}};N(0,0),N(0,s-7),N(s-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let i=(e+1&2)===0;for(let a=0;a>>3]>>>7-(S&7)&1,S++;let o=(m+l&1)===0?h^1:h;G[m*s+l]=o}}}let R=30660;for(let e=0;e<=5;e++)b(8,e,(R>>>14-e&1)===1);b(8,7,(R>>>8&1)===1),b(8,8,(R>>>7&1)===1),b(7,8,(R>>>6&1)===1);for(let e=0;e<=5;e++)b(5-e,8,(R>>>5-e&1)===1);for(let e=0;e<8;e++)b(8,s-1-e,(R>>>e&1)===1);for(let e=0;e<7;e++)b(s-7+e,8,(R>>>14-e&1)===1);return{size:s,modules:G}}function X(n){let t=oe(n);if(!t)return null;let c=2,r=t.size+c*2,d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("viewBox",`0 0 ${r} ${r}`),d.setAttribute("role","img"),d.setAttribute("aria-label",`QR code for ${n}`),d.setAttribute("shape-rendering","crispEdges"),d.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),d.appendChild(u);let f="";for(let w=0;w{let h=l.trim();if(!h)return;let o=h.startsWith("https://")?h:`https://${h}`;if(!o.startsWith("https://")||o.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=p("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=o,y.setAttribute("data-testid","pair-address");let q=document.createElement("button");q.type="button",q.className="bp-pair-copy";let H=p("common.copy","Copy");q.textContent=H,q.addEventListener("click",()=>{navigator.clipboard?.writeText(o).then(()=>{q.textContent=p("web.clone.copied","Copied"),window.setTimeout(()=>{q.textContent=H},1200)}).catch(()=>{})}),x.append(v,y,q);let U=document.createDocumentFragment();U.appendChild(x);let Q=X(o);if(Q){let I=document.createElement("div");I.className="bp-pair-qr",I.setAttribute("data-testid","pair-qr"),I.appendChild(Q),U.appendChild(I)}s.replaceChildren(U),s.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(l)=>{if(!l.ok)return;let h=await l.json();if(typeof h.address==="string")G(h.address)}).catch(()=>{}),t.append(c,u,f,j,A,s),n.appendChild(t);let C=null,b=null,N=null,S=0,D=0,R=150,e=1000;function i(){if(S++,N)N.abort(),N=null;if(C!==null)window.clearTimeout(C),C=null;if(b!==null)window.clearInterval(b),b=null}function a(l="",h=!1){i(),f.classList.remove("bp-hidden"),j.classList.add("bp-hidden"),g.disabled=!1,A.textContent=l,A.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let l=D-Date.now();if(l<=0){a(p("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}B.textContent=p("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:se(l)})}async function k(l){if(l!==S)return;if(D>0&&Date.now()>=D){a(p("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;N=h;try{let o=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(l!==S)return;if(e=1000,o.status===202){C=window.setTimeout(()=>{k(l)},150);return}if(o.status===200||o.status===204){let v={};if(o.status===200)try{v=await o.json()}catch{}if(l!==S)return;let y=(v.state||v.status||"").toLowerCase();if(o.status===204||v.approved===!0||y==="approved"||y==="ok"){i(),A.textContent=p("web.pair.approved","Approved. Opening Backplane…"),A.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){a(p("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){a(p("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}C=window.setTimeout(()=>{k(l)},150);return}if(o.status===429){let v=Number(o.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);C=window.setTimeout(()=>{k(l)},y);return}if(o.status===401||o.status===403||o.status===404||o.status===410){let v="";try{let y=await o.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(l!==S)return;if(v==="denied"||v==="rejected"||o.status===403)a(p("web.pair.denied","Pairing request was denied."),!0);else a(p("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),C=window.setTimeout(()=>{k(l)},x)}catch{if(l!==S)return;let o=e;e=Math.min(1e4,Math.round(e*1.8)),C=window.setTimeout(()=>{k(l)},o)}finally{if(N===h)N=null}}L.addEventListener("click",()=>{a(p("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(l)=>{l.preventDefault();let h=w.value.trim()||Z();g.disabled=!0,A.textContent=p("web.pair.requesting","Requesting pairing code…"),A.className="bp-pair-status";try{let o=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!o.ok){let H=p("web.pair.failed","Pairing request failed ({status})",{status:o.status});try{let U=await o.json();if(U.error)H=U.error}catch{}if(o.status===429)H=p("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");a(H,!0);return}let x=await o.json(),v=x.code||x.checkCode||"";if(!v){a(p("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();D=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),i();let q=S;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,M.textContent=re(v),f.classList.add("bp-hidden"),j.classList.remove("bp-hidden"),A.textContent="",m(),b=window.setInterval(m,1000),C=window.setTimeout(()=>{k(q)},R)}catch{a(p("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); +var F={en:{"agy.signout":"Sign out","android.load.earlier":"load earlier","bots.rooms":"Rooms","bots.tab.browser":"Browser","common.cancel":"Cancel","common.close":"Close","common.copy":"Copy","common.delete":"Delete","common.refresh":"Refresh","common.remove":"Remove","common.save":"Save","composer.placeholder":"Ask anything: @bot, >thread, %project, #room, $skill, /btw","composer.send":"Send","composer.stop":"Stop","gpui.acct.connected":"Connected","gpui.acct.not.connected":"Not connected","gpui.acct.sign.in.expired":"Sign-in expired","gpui.b.in.reply.to":"↩ In reply to: {quote}","gpui.b.replying.to":"↩ Replying to: {line}","gpui.commands":"Commands","gpui.e.open.folder":"Open folder","gpui.filter.projects.and.threads":"Filter projects and threads","gpui.fold.or.unfold.the.sidebar":"Fold or unfold the sidebar","gpui.follow.paused":"Following paused","gpui.follow.wait":"Following: waiting for the agent's next edit","gpui.gerbers":"Gerbers","gpui.improvements":"Improvements","gpui.jump.to.a.thread.run":"Jump to a thread, run a command or find what was said","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"no MPN","gpui.mgmt.checks.all":"All","gpui.mgmt.checks.fix":"Fix with agent","gpui.mgmt.checks.run":"Run","gpui.mgmt.close":"Close the panel","gpui.mgmt.fab.apply":"Apply","gpui.mgmt.fab.changed":"Changed since you last looked","gpui.mgmt.fab.derived":"* worked out from the fab's page (a mil in mm, a ring from a diameter). Dimmed: the rigid board's value, where this board's page says nothing else. A date opens the page it was read from.","gpui.mgmt.fab.extra":"Costs more","gpui.mgmt.fab.findings":"Findings","gpui.mgmt.fab.free":"Base price","gpui.mgmt.fab.judge":"Datasheets","gpui.mgmt.fab.limit":"Limit","gpui.mgmt.fab.readcol":"Read","gpui.mgmt.fab.refresh":"Refresh","gpui.mgmt.fab.reviewbtn":"Review","gpui.mgmt.fab.seen":"Seen","gpui.mgmt.fab.thefab":"The fab","gpui.mgmt.fab.use":"Use","gpui.mgmt.life.nopart":"No reading of this part yet.","gpui.mgmt.life.reading":"Reading its history…","gpui.mgmt.plan.all":"Approve all","gpui.mgmt.plan.layer":"Approve layer","gpui.mgmt.plan.reject":"Reject","gpui.mgmt.plan.saved":"saved plan","gpui.mgmt.plan.stop":"Stop routing","gpui.next.thread":"Next thread","gpui.nothing.matches":"Nothing matches","gpui.previous.thread":"Previous thread","gpui.rail.no.board":"No board in this project","gpui.rail.no.mech":"No mechanical parts in this project","gpui.rail.no.schematic":"No schematic in this project","gpui.rail.split.needs.both":"Split needs a board and a schematic","home.away":"Home ({name}) is away","home.away.queued":"Home ({name}) is away · {n} queued","home.away.since":"Home ({name}) is away since {time}","home.away.since.queued":"Home ({name}) is away since {time} · {n} queued","home.machine":"Home machine","home.move.failed":"Home move failed","home.move.failed.note":"Home move failed: {note}","home.move.here":"Make this machine the home","home.moving":"Moving home to {to}…","home.moving.step":"Moving home to {to}: {step}","hub.back.crash":"Backplane is back after it stopped unexpectedly","hub.restarting":"Restarting Backplane…","hub.restarting.build":"Restarting Backplane… (new build {build})","hub.stopped":"Backplane stopped","ios.hub.address.field":"Hub address","menu.pin":"Pin","menu.settle":"Settle","menu.unpin":"Unpin","model.col.agent":"Agent","notify.settled":"Settled","palette.archive":"Archive thread","palette.command.placeholder":"Type a command or a thread","palette.diff":"Diff: what this thread changed","palette.newthread":"New thread","palette.settings":"Settings","palette.terminal":"Terminal","palette.unarchive":"Unarchive thread","phone.unsettle":"Unsettle","reply.action":"Reply","reply.cancel":"Cancel reply","reply.to":"In reply to:","secret.you":"You","settings.lang":"Language","sheet.rename":"Rename thread","sidebar.add.project":"Add project","sidebar.search.projects":"Search projects","thread.context.base":"Backplane","thread.context.copied":"Prompt copied.","thread.context.copy":"Copy prompt","thread.context.disable":"Disable","thread.context.enable":"Enable","thread.context.index":"Available skills index","thread.context.injected.label":"Injected project instructions","thread.context.instructions":"Instructions","thread.context.mcp":"Project MCPs","thread.context.native.note":"Backplane’s launch prompt. Native files are loaded by the provider.","thread.context.none.instructions":"No project instructions found.","thread.context.none.mcp":"No project MCP configurations found.","thread.context.reading":"Reading thread context…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Skills","thread.context.system":"System Prompt","thread.context.title":"Context & Prompt","thread.context.trust":"Trust and enable","thread.new":"New thread","tools.pinned":"Pinned","tools.retry":"Retry","tour.title.bots":"Bots","viewer.board":"Board","viewer.diff":"Diff","viewer.files":"Files","viewer.mech":"Mech","viewer.review":"Review","viewer.schematic":"Schematic","viewer.solid":"3D","web.chat.answer.btn":"Answer","web.chat.answer.placeholder":"Type answer…","web.chat.answered":"Answered: {answer}","web.chat.choose":"Choose a project thread on the left to begin.","web.chat.empty":"No messages yet. Type below to start a turn.","web.chat.finished":"Finished {time}","web.chat.finished.dur":"Finished {time} · {dur}","web.chat.loading":"Loading messages…","web.chat.review.mode":"Review mode","web.chat.streaming":"Streaming…","web.clone.add.dir":"Add {dir}","web.clone.back":"Back","web.clone.change.folder":"Change folder","web.clone.cloned":"Cloned {repo} into {dest}","web.clone.cloning":"Cloning {repo} into {dest}","web.clone.copied":"Copied","web.clone.first":"First message: {text}","web.clone.folder.name":"Folder name","web.clone.go":"Clone","web.clone.loading":"Loading…","web.clone.no.folders":"No folders here","web.clone.open.project":"Open the project","web.clone.open.thread":"Open the thread","web.clone.private":"private","web.clone.repo.placeholder":"https or ssh URL, or owner/repo","web.clone.retry":"Try again","web.clone.same":"Already cloned there: it is added as it is.","web.clone.signin":"Sign in to GitHub","web.clone.signin.done":"Signed in to GitHub","web.clone.signin.enter":"Enter this code on GitHub:","web.clone.signin.wait":"Starting GitHub sign-in…","web.clone.start.thread":"Start a thread","web.clone.stopped":"Stopped cloning {repo}","web.clone.tab":"Clone from git","web.clone.up":"Up","web.clone.use.dir":"Use {dir}","web.composer.attach":"Attach image","web.composer.maximages":"At most {max} images per message.","web.composer.unsupported":"Unsupported image type: {type}","web.composer.voice":"Voice dictation","web.logout.failed":"Could not confirm sign-out. Try again.","web.pair.approve.in":"Approve on desktop or paired phone · expires in {time}","web.pair.approved":"Approved. Opening Backplane…","web.pair.cancelled":"Cancelled.","web.pair.code":"Comparison code","web.pair.denied":"Pairing request was denied.","web.pair.expired":"Pairing code expired. Request a new code to try again.","web.pair.failed":"Pairing request failed ({status})","web.pair.name":"Browser name","web.pair.nocode":"Hub did not return a comparison code.","web.pair.ratelimited":"Too many pairing attempts. Wait a moment and try again.","web.pair.request":"Request pairing","web.pair.requesting":"Requesting pairing code…","web.pair.subtitle":"Pair this browser with your hub. Approve the 6-digit code in Backplane › Settings › Devices.","web.pair.unreachable":"Could not reach the hub. Check your tailnet connection."},es:{"agy.signout":"Cerrar sesión","android.load.earlier":"cargar anteriores","bots.rooms":"Salas","bots.tab.browser":"Navegador","common.cancel":"Cancelar","common.close":"Cerrar","common.copy":"Copiar","common.delete":"Eliminar","common.refresh":"Actualizar","common.remove":"Quitar","common.save":"Guardar","composer.placeholder":"Pregunta lo que sea: @bot, >hilo, %proyecto, #sala, $skill, /btw","composer.send":"Enviar","composer.stop":"Detener","gpui.acct.connected":"Conectado","gpui.acct.not.connected":"No conectado","gpui.acct.sign.in.expired":"Sesión caducada","gpui.b.in.reply.to":"↩ En respuesta a: {quote}","gpui.b.replying.to":"↩ Respondiendo a: {line}","gpui.commands":"Comandos","gpui.e.open.folder":"Abrir carpeta","gpui.filter.projects.and.threads":"Filtrar proyectos e hilos","gpui.fold.or.unfold.the.sidebar":"Plegar o desplegar la barra lateral","gpui.follow.paused":"Seguimiento en pausa","gpui.follow.wait":"Siguiendo: esperando la próxima edición del agente","gpui.gerbers":"Gerbers","gpui.improvements":"Mejoras","gpui.jump.to.a.thread.run":"Saltar a un hilo, ejecutar un comando o buscar lo dicho","gpui.mgmt.bom.dnp":"DNP","gpui.mgmt.bom.nompn":"sin MPN","gpui.mgmt.checks.all":"Todas","gpui.mgmt.checks.fix":"Corregir con agente","gpui.mgmt.checks.run":"Ejecutar","gpui.mgmt.close":"Cerrar el panel","gpui.mgmt.fab.apply":"Aplicar","gpui.mgmt.fab.changed":"Cambió desde la última vez que miraste","gpui.mgmt.fab.derived":"* calculado desde la página del fabricante (un mil en mm, un anillo desde un diámetro). Atenuado: el valor de la placa rígida, cuando la página de esta placa no dice otra cosa. Una fecha abre la página de la que se leyó.","gpui.mgmt.fab.extra":"Cuesta más","gpui.mgmt.fab.findings":"Hallazgos","gpui.mgmt.fab.free":"Precio base","gpui.mgmt.fab.judge":"Hojas de datos","gpui.mgmt.fab.limit":"Límite","gpui.mgmt.fab.readcol":"Leído","gpui.mgmt.fab.refresh":"Actualizar","gpui.mgmt.fab.reviewbtn":"Revisar","gpui.mgmt.fab.seen":"Visto","gpui.mgmt.fab.thefab":"El fabricante","gpui.mgmt.fab.use":"Usar","gpui.mgmt.life.nopart":"Sin lectura de esta pieza aún.","gpui.mgmt.life.reading":"Leyendo su historial…","gpui.mgmt.plan.all":"Aprobar todo","gpui.mgmt.plan.layer":"Aprobar capa","gpui.mgmt.plan.reject":"Rechazar","gpui.mgmt.plan.saved":"plan guardado","gpui.mgmt.plan.stop":"Detener ruteo","gpui.next.thread":"Hilo siguiente","gpui.nothing.matches":"Nada coincide","gpui.previous.thread":"Hilo anterior","gpui.rail.no.board":"Este proyecto no tiene placa","gpui.rail.no.mech":"Este proyecto no tiene piezas mecánicas","gpui.rail.no.schematic":"Este proyecto no tiene esquema","gpui.rail.split.needs.both":"La vista dividida requiere una placa y un esquema","home.away":"El inicio ({name}) no está disponible","home.away.queued":"El inicio ({name}) no está disponible · {n} en cola","home.away.since":"El inicio ({name}) no está disponible desde las {time}","home.away.since.queued":"El inicio ({name}) no está disponible desde las {time} · {n} en cola","home.machine":"Máquina de inicio","home.move.failed":"No se pudo mover el inicio","home.move.failed.note":"No se pudo mover el inicio: {note}","home.move.here":"Hacer de esta máquina el inicio","home.moving":"Moviendo el inicio a {to}…","home.moving.step":"Moviendo el inicio a {to}: {step}","hub.back.crash":"Backplane volvió tras detenerse de forma inesperada","hub.restarting":"Reiniciando Backplane…","hub.restarting.build":"Reiniciando Backplane… (nueva compilación {build})","hub.stopped":"Backplane se detuvo","ios.hub.address.field":"Dirección del hub","menu.pin":"Fijar","menu.settle":"Cerrar","menu.unpin":"Desfijar","model.col.agent":"Agente","notify.settled":"Cerrado","palette.archive":"Archivar hilo","palette.command.placeholder":"Escribe un comando o un hilo","palette.diff":"Diff: qué cambió este hilo","palette.newthread":"Nuevo hilo","palette.settings":"Ajustes","palette.terminal":"Terminal","palette.unarchive":"Desarchivar hilo","phone.unsettle":"Reabrir","reply.action":"Responder","reply.cancel":"Cancelar respuesta","reply.to":"En respuesta a:","secret.you":"Tú","settings.lang":"Idioma","sheet.rename":"Renombrar hilo","sidebar.add.project":"Añadir proyecto","sidebar.search.projects":"Buscar proyectos","thread.context.base":"Backplane","thread.context.copied":"Se copiaron las instrucciones.","thread.context.copy":"Copiar instrucciones","thread.context.disable":"Desactivar","thread.context.enable":"Activar","thread.context.index":"Índice de habilidades disponibles","thread.context.injected.label":"Instrucciones del proyecto añadidas","thread.context.instructions":"Instrucciones","thread.context.mcp":"MCP del proyecto","thread.context.native.note":"Instrucciones de inicio de Backplane. El proveedor carga los archivos nativos.","thread.context.none.instructions":"No se encontraron instrucciones del proyecto.","thread.context.none.mcp":"No se encontraron configuraciones MCP del proyecto.","thread.context.reading":"Leyendo el contexto del hilo…","thread.context.size":"{bytes} B · ≈{tokens} tokens","thread.context.skills":"Habilidades","thread.context.system":"Instrucciones del sistema","thread.context.title":"Contexto e instrucciones","thread.context.trust":"Confiar y activar","thread.new":"Nuevo hilo","tools.pinned":"Fijado","tools.retry":"Reintentar","tour.title.bots":"Bots","viewer.board":"Placa","viewer.diff":"Diff","viewer.files":"Archivos","viewer.mech":"Mech","viewer.review":"Revisión","viewer.schematic":"Esquemático","viewer.solid":"3D","web.chat.answer.btn":"Responder","web.chat.answer.placeholder":"Escribe una respuesta…","web.chat.answered":"Respondido: {answer}","web.chat.choose":"Elige un hilo de proyecto a la izquierda para empezar.","web.chat.empty":"Aún no hay mensajes. Escribe abajo para iniciar un turno.","web.chat.finished":"Terminado {time}","web.chat.finished.dur":"Terminado {time} · {dur}","web.chat.loading":"Cargando mensajes…","web.chat.review.mode":"Modo de revisión","web.chat.streaming":"Transmitiendo…","web.clone.add.dir":"Añadir {dir}","web.clone.back":"Atrás","web.clone.change.folder":"Cambiar carpeta","web.clone.cloned":"{repo} clonado en {dest}","web.clone.cloning":"Clonando {repo} en {dest}","web.clone.copied":"Copiado","web.clone.first":"Primer mensaje: {text}","web.clone.folder.name":"Nombre de la carpeta","web.clone.go":"Clonar","web.clone.loading":"Cargando…","web.clone.no.folders":"No hay carpetas aquí","web.clone.open.project":"Abrir el proyecto","web.clone.open.thread":"Abrir el hilo","web.clone.private":"privado","web.clone.repo.placeholder":"URL https o ssh, o propietario/repositorio","web.clone.retry":"Reintentar","web.clone.same":"Ya está clonado ahí: se añade tal cual.","web.clone.signin":"Iniciar sesión en GitHub","web.clone.signin.done":"Sesión iniciada en GitHub","web.clone.signin.enter":"Introduce este código en GitHub:","web.clone.signin.wait":"Iniciando sesión en GitHub…","web.clone.start.thread":"Empezar un hilo","web.clone.stopped":"Se detuvo la clonación de {repo}","web.clone.tab":"Clonar desde git","web.clone.up":"Subir","web.clone.use.dir":"Usar {dir}","web.composer.attach":"Adjuntar imagen","web.composer.maximages":"Como máximo {max} imágenes por mensaje.","web.composer.unsupported":"Tipo de imagen no compatible: {type}","web.composer.voice":"Dictado por voz","web.logout.failed":"No se pudo confirmar el cierre de sesión. Inténtalo de nuevo.","web.pair.approve.in":"Aprueba en el escritorio o en un teléfono vinculado · caduca en {time}","web.pair.approved":"Aprobado. Abriendo Backplane…","web.pair.cancelled":"Cancelado.","web.pair.code":"Código de comparación","web.pair.denied":"Se rechazó la solicitud de vinculación.","web.pair.expired":"El código de vinculación caducó. Solicita uno nuevo para intentarlo otra vez.","web.pair.failed":"Falló la solicitud de vinculación ({status})","web.pair.name":"Nombre del navegador","web.pair.nocode":"El hub no devolvió un código de comparación.","web.pair.ratelimited":"Demasiados intentos de vinculación. Espera un momento e inténtalo de nuevo.","web.pair.request":"Solicitar vinculación","web.pair.requesting":"Solicitando código de vinculación…","web.pair.subtitle":"Vincula este navegador con tu hub. Aprueba el código de 6 dígitos en Backplane › Ajustes › Dispositivos.","web.pair.unreachable":"No se pudo conectar con el hub. Comprueba tu conexión de tailnet."},ja:{"agy.signout":"サインアウト","android.load.earlier":"以前のメッセージを読み込む","bots.rooms":"ルーム","bots.tab.browser":"ブラウザ","common.cancel":"キャンセル","common.close":"閉じる","common.copy":"コピー","common.delete":"削除","common.refresh":"更新","common.remove":"削除","common.save":"保存","composer.placeholder":"何でも質問:@bot、>thread、%project、#room、$skill、/btw","composer.send":"送信","composer.stop":"停止","gpui.acct.connected":"接続済み","gpui.acct.not.connected":"未接続","gpui.acct.sign.in.expired":"サインインの期限切れ","gpui.b.in.reply.to":"↩ 返信先:{quote}","gpui.b.replying.to":"↩ 返信中:{line}","gpui.commands":"コマンド","gpui.e.open.folder":"フォルダを開く","gpui.filter.projects.and.threads":"プロジェクトとスレッドを絞り込む","gpui.fold.or.unfold.the.sidebar":"サイドバーを折りたたむ/開く","gpui.follow.paused":"追従を一時停止中","gpui.follow.wait":"追従中: エージェントの次の編集を待っています","gpui.gerbers":"ガーバー","gpui.improvements":"改善","gpui.jump.to.a.thread.run":"スレッドへ移動、コマンドを実行、または発言を検索","gpui.mgmt.bom.dnp":"実装しない","gpui.mgmt.bom.nompn":"MPNなし","gpui.mgmt.checks.all":"すべて","gpui.mgmt.checks.fix":"エージェントに直してもらう","gpui.mgmt.checks.run":"実行","gpui.mgmt.close":"パネルを閉じる","gpui.mgmt.fab.apply":"適用","gpui.mgmt.fab.changed":"前回見てから変わったところ","gpui.mgmt.fab.derived":"* 製造元のページから計算した値です(milをmmに、径からランドを)。薄い色の項目はリジッド基板の値です(この基板のページに記載がないもの)。日付を押すと読んだページが開きます。","gpui.mgmt.fab.extra":"追加料金","gpui.mgmt.fab.findings":"指摘","gpui.mgmt.fab.free":"基本料金","gpui.mgmt.fab.judge":"データシート","gpui.mgmt.fab.limit":"項目","gpui.mgmt.fab.readcol":"読んだ日","gpui.mgmt.fab.refresh":"再読み込み","gpui.mgmt.fab.reviewbtn":"レビュー","gpui.mgmt.fab.seen":"確認済み","gpui.mgmt.fab.thefab":"製造元","gpui.mgmt.fab.use":"使う","gpui.mgmt.life.nopart":"この部品の記録はまだありません。","gpui.mgmt.life.reading":"履歴を読んでいます…","gpui.mgmt.plan.all":"すべて承認","gpui.mgmt.plan.layer":"層を承認","gpui.mgmt.plan.reject":"却下","gpui.mgmt.plan.saved":"保存された計画","gpui.mgmt.plan.stop":"配線を止める","gpui.next.thread":"次のスレッド","gpui.nothing.matches":"一致するものはありません","gpui.previous.thread":"前のスレッド","gpui.rail.no.board":"このプロジェクトには基板がありません","gpui.rail.no.mech":"このプロジェクトには機械部品がありません","gpui.rail.no.schematic":"このプロジェクトには回路図がありません","gpui.rail.split.needs.both":"分割表示には基板と回路図が必要です","home.away":"ホーム({name})はオフラインです","home.away.queued":"ホーム({name})はオフラインです · {n} 件待機中","home.away.since":"ホーム({name})は {time} からオフラインです","home.away.since.queued":"ホーム({name})は {time} からオフラインです · {n} 件待機中","home.machine":"ホームマシン","home.move.failed":"ホームの移動に失敗しました","home.move.failed.note":"ホームの移動に失敗しました: {note}","home.move.here":"このマシンをホームにする","home.moving":"ホームを {to} へ移動中…","home.moving.step":"ホームを {to} へ移動中: {step}","hub.back.crash":"予期せず停止したBackplaneが戻りました","hub.restarting":"Backplaneを再起動しています…","hub.restarting.build":"Backplaneを再起動しています…(新しいビルド {build})","hub.stopped":"Backplaneは停止しました","ios.hub.address.field":"ハブのアドレス","menu.pin":"ピン留め","menu.settle":"完了","menu.unpin":"ピン留めを解除","model.col.agent":"エージェント","notify.settled":"完了","palette.archive":"スレッドをアーカイブ","palette.command.placeholder":"コマンドまたはスレッドを入力","palette.diff":"差分:このスレッドの変更","palette.newthread":"新しいスレッド","palette.settings":"設定","palette.terminal":"ターミナル","palette.unarchive":"スレッドのアーカイブを解除","phone.unsettle":"未完了に戻す","reply.action":"返信","reply.cancel":"返信をやめる","reply.to":"返信先:","secret.you":"あなた","settings.lang":"言語","sheet.rename":"スレッド名を変更","sidebar.add.project":"プロジェクトを追加","sidebar.search.projects":"プロジェクトを検索","thread.context.base":"Backplane","thread.context.copied":"プロンプトをコピーしました。","thread.context.copy":"プロンプトをコピー","thread.context.disable":"無効にする","thread.context.enable":"有効にする","thread.context.index":"利用可能なスキルの一覧","thread.context.injected.label":"追加されたプロジェクトの指示","thread.context.instructions":"指示","thread.context.mcp":"プロジェクトの MCP","thread.context.native.note":"Backplane が起動時に渡すプロンプトです。ネイティブファイルはプロバイダーが読み込みます。","thread.context.none.instructions":"プロジェクトの指示が見つかりません。","thread.context.none.mcp":"プロジェクトの MCP 設定が見つかりません。","thread.context.reading":"スレッドのコンテキストを読み込み中…","thread.context.size":"{bytes} B・約{tokens}トークン","thread.context.skills":"スキル","thread.context.system":"システムプロンプト","thread.context.title":"コンテキストとプロンプト","thread.context.trust":"承認して有効にする","thread.new":"新しいスレッド","tools.pinned":"固定中","tools.retry":"再試行","tour.title.bots":"ボット","viewer.board":"基板","viewer.diff":"差分","viewer.files":"ファイル","viewer.mech":"Mech","viewer.review":"レビュー","viewer.schematic":"回路図","viewer.solid":"3D","web.chat.answer.btn":"回答","web.chat.answer.placeholder":"回答を入力…","web.chat.answered":"回答済み: {answer}","web.chat.choose":"左側からプロジェクトのスレッドを選んで開始してください。","web.chat.empty":"まだメッセージはありません。下に入力して開始してください。","web.chat.finished":"完了 {time}","web.chat.finished.dur":"完了 {time} · {dur}","web.chat.loading":"メッセージを読み込んでいます…","web.chat.review.mode":"レビューモード","web.chat.streaming":"受信中…","web.clone.add.dir":"{dir} を追加","web.clone.back":"戻る","web.clone.change.folder":"フォルダを変更","web.clone.cloned":"{repo} を {dest} にクローンしました","web.clone.cloning":"{repo} を {dest} にクローン中","web.clone.copied":"コピーしました","web.clone.first":"最初のメッセージ: {text}","web.clone.folder.name":"フォルダ名","web.clone.go":"クローン","web.clone.loading":"読み込み中…","web.clone.no.folders":"フォルダがありません","web.clone.open.project":"プロジェクトを開く","web.clone.open.thread":"スレッドを開く","web.clone.private":"非公開","web.clone.repo.placeholder":"https / ssh の URL、または owner/repo","web.clone.retry":"もう一度","web.clone.same":"すでにそこにクローンされています: そのまま追加します。","web.clone.signin":"GitHub にサインイン","web.clone.signin.done":"GitHub にサインインしました","web.clone.signin.enter":"このコードを GitHub に入力してください:","web.clone.signin.wait":"GitHub のサインインを開始しています…","web.clone.start.thread":"スレッドを開始","web.clone.stopped":"{repo} のクローンを中止しました","web.clone.tab":"git からクローン","web.clone.up":"上へ","web.clone.use.dir":"{dir} を使う","web.composer.attach":"画像を添付","web.composer.maximages":"1 件のメッセージに添付できる画像は最大 {max} 枚です。","web.composer.unsupported":"未対応の画像形式です: {type}","web.composer.voice":"音声入力","web.logout.failed":"サインアウトを確認できませんでした。もう一度お試しください。","web.pair.approve.in":"デスクトップまたはペアリング済みの端末で承認してください · 有効期限 {time}","web.pair.approved":"承認されました。Backplane を開いています…","web.pair.cancelled":"キャンセルしました。","web.pair.code":"確認コード","web.pair.denied":"ペアリングのリクエストが拒否されました。","web.pair.expired":"ペアリングコードの有効期限が切れました。新しいコードをリクエストしてください。","web.pair.failed":"ペアリングのリクエストに失敗しました ({status})","web.pair.name":"ブラウザー名","web.pair.nocode":"ハブから確認コードが返されませんでした。","web.pair.ratelimited":"ペアリングの試行回数が多すぎます。しばらく待ってからやり直してください。","web.pair.request":"ペアリングをリクエスト","web.pair.requesting":"ペアリングコードをリクエストしています…","web.pair.subtitle":"このブラウザーをハブとペアリングします。Backplane › 設定 › デバイス で 6 桁のコードを承認してください。","web.pair.unreachable":"ハブに接続できませんでした。tailnet の接続を確認してください。"}};function Y(n,t){if(!t)return n;return n.replace(/\{([a-zA-Z0-9_.-]+)\}/g,(c,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):c)}var z=te(),_=new Set,W=new Map;for(let[n,t]of Object.entries(F.en||{}))if(typeof t==="string"&&!W.has(t))W.set(t,n);function te(){let n=typeof navigator<"u"&&navigator.language?navigator.language.toLowerCase():"en";if(n.startsWith("ja"))return"ja";if(n.startsWith("es"))return"es";return"en"}function J(){if(typeof document<"u"&&document.documentElement)document.documentElement.lang=z}J();function me(n){return _.add(n),()=>{_.delete(n)}}function ue(n){if(!n)return!1;let t=n.toLowerCase(),c=t.startsWith("ja")?"ja":t.startsWith("es")?"es":t.startsWith("en")?"en":"";if(!c)return!1;let r=c!==z;if(z=c,J(),r)for(let l of _)l(z);return r}function p(n,t,c){let l=(F[z]||F.en||{})[n]??F.en?.[n]??t??n;return Y(l,c)}function be(n){if(!n)return"";let t=W.get(n);if(!t)return n;return p(t,n)}var ne=[[1,26,7,1,[]],[2,44,10,1,[6,18]],[3,70,15,1,[6,22]],[4,100,20,1,[6,26]],[5,134,26,1,[6,30]],[6,172,18,2,[6,34]]],I=new Uint8Array(512),V=new Uint8Array(256);{let n=1;for(let t=0;t<255;t++)if(I[t]=n,V[n]=t,n<<=1,n&256)n^=285;for(let t=255;t<512;t++)I[t]=I[t-255]}function K(n,t){return n===0||t===0?0:I[V[n]+V[t]]}function ae(n){let t=new Uint8Array([1]);for(let c=0;c{let m=e-o*a;return Math.ceil((12+t.length*8)/8)<=m});if(!c)return null;let[r,l,u,f,S]=c,w=l-u*f,b=[],E=(e,o)=>{for(let a=o-1;a>=0;a--)b.push(e>>>a&1)};E(4,4),E(t.length,8);for(let e of t)E(e,8);for(let e=0;e<4&&b.length{if(e<0||o<0||e>=s||o>=s)return;G[e*s+o]=a?1:0,A[e*s+o]=1},N=(e,o)=>{for(let a=-1;a<=7;a++)for(let m=-1;m<=7;m++){let k=e+a,d=o+m,i=a>=0&&a<=6&&m>=0&&m<=6&&(a===0||a===6||m===0||m===6||a>=2&&a<=4&&m>=2&&m<=4);g(k,d,i)}};N(0,0),N(0,s-7),N(s-7,0);for(let e=8;e=1;e-=2){if(e===6)e=5;let o=(e+1&2)===0;for(let a=0;a>>3]>>>7-(j&7)&1,j++;let i=(m+d&1)===0?h^1:h;G[m*s+d]=i}}}let R=30660;for(let e=0;e<=5;e++)g(8,e,(R>>>14-e&1)===1);g(8,7,(R>>>8&1)===1),g(8,8,(R>>>7&1)===1),g(7,8,(R>>>6&1)===1);for(let e=0;e<=5;e++)g(5-e,8,(R>>>5-e&1)===1);for(let e=0;e<8;e++)g(8,s-1-e,(R>>>e&1)===1);for(let e=0;e<7;e++)g(s-7+e,8,(R>>>14-e&1)===1);return{size:s,modules:G}}function X(n){let t=ie(n);if(!t)return null;let c=2,r=t.size+c*2,l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.setAttribute("viewBox",`0 0 ${r} ${r}`),l.setAttribute("role","img"),l.setAttribute("aria-label",`QR code for ${n}`),l.setAttribute("shape-rendering","crispEdges"),l.classList.add("bp-qr-svg");let u=document.createElementNS("http://www.w3.org/2000/svg","rect");u.setAttribute("width",String(r)),u.setAttribute("height",String(r)),u.setAttribute("fill","#ffffff"),l.appendChild(u);let f="";for(let w=0;w{let h=d.trim();if(!h)return;let i=h.startsWith("https://")?h:`https://${h}`;if(!i.startsWith("https://")||i.length<=8)return;let x=document.createElement("div");x.className="bp-pair-addr-meta";let v=document.createElement("div");v.className="bp-pair-code-label",v.textContent=p("ios.hub.address.field","Hub address");let y=document.createElement("code");y.className="bp-pair-addr-url",y.textContent=i,y.setAttribute("data-testid","pair-address");let P=document.createElement("button");P.type="button",P.className="bp-pair-copy";let H=p("common.copy","Copy");P.textContent=H,P.addEventListener("click",()=>{navigator.clipboard?.writeText(i).then(()=>{P.textContent=p("web.clone.copied","Copied"),window.setTimeout(()=>{P.textContent=H},1200)}).catch(()=>{})}),x.append(v,y,P);let U=document.createDocumentFragment();U.appendChild(x);let Q=X(i);if(Q){let O=document.createElement("div");O.className="bp-pair-qr",O.setAttribute("data-testid","pair-qr"),O.appendChild(Q),U.appendChild(O)}s.replaceChildren(U),s.classList.remove("bp-hidden")};fetch("/auth/web/info",{credentials:"same-origin"}).then(async(d)=>{if(!d.ok)return;let h=await d.json();if(typeof h.address==="string")G(h.address)}).catch(()=>{}),t.append(c,u,f,E,C,s),n.appendChild(t);let A=null,g=null,N=null,j=0,D=0,R=150,e=1000;function o(){if(j++,N)N.abort(),N=null;if(A!==null)window.clearTimeout(A),A=null;if(g!==null)window.clearInterval(g),g=null}function a(d="",h=!1){o(),f.classList.remove("bp-hidden"),E.classList.add("bp-hidden"),b.disabled=!1,C.textContent=d,C.className=h?"bp-pair-status bp-bad":"bp-pair-status"}function m(){let d=D-Date.now();if(d<=0){a(p("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}q.textContent=p("web.pair.approve.in","Approve on desktop or paired phone · expires in {time}",{time:se(d)})}async function k(d){if(d!==j)return;if(D>0&&Date.now()>=D){a(p("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let h=new AbortController;N=h;try{let i=await fetch("/auth/web/poll",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:"{}",signal:h.signal});if(d!==j)return;if(e=1000,i.status===202){A=window.setTimeout(()=>{k(d)},150);return}if(i.status===200||i.status===204){let v={};if(i.status===200)try{v=await i.json()}catch{}if(d!==j)return;let y=(v.state||v.status||"").toLowerCase();if(i.status===204||v.approved===!0||y==="approved"||y==="ok"){o(),C.textContent=p("web.pair.approved","Approved. Opening Backplane…"),C.className="bp-pair-status bp-ok",window.location.replace("/");return}if(y==="denied"||y==="rejected"){a(p("web.pair.denied","Pairing request was denied."),!0);return}if(y==="expired"){a(p("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}A=window.setTimeout(()=>{k(d)},150);return}if(i.status===429){let v=Number(i.headers.get("Retry-After")||"5"),y=Math.max(2000,(Number.isFinite(v)?v:5)*1000);A=window.setTimeout(()=>{k(d)},y);return}if(i.status===401||i.status===403||i.status===404||i.status===410){let v="";try{let y=await i.json();v=(y.state||y.status||y.error||"").toLowerCase()}catch{}if(d!==j)return;if(v==="denied"||v==="rejected"||i.status===403)a(p("web.pair.denied","Pairing request was denied."),!0);else a(p("web.pair.expired","Pairing code expired. Request a new code to try again."),!0);return}let x=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(d)},x)}catch{if(d!==j)return;let i=e;e=Math.min(1e4,Math.round(e*1.8)),A=window.setTimeout(()=>{k(d)},i)}finally{if(N===h)N=null}}M.addEventListener("click",()=>{a(p("web.pair.cancelled","Cancelled."))}),f.addEventListener("submit",async(d)=>{d.preventDefault();let h=w.value.trim()||Z();b.disabled=!0,C.textContent=p("web.pair.requesting","Requesting pairing code…"),C.className="bp-pair-status";try{let i=await fetch("/auth/web/request",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h})});if(!i.ok){let H=p("web.pair.failed","Pairing request failed ({status})",{status:i.status});try{let U=await i.json();if(U.error)H=U.error}catch{}if(i.status===429)H=p("web.pair.ratelimited","Too many pairing attempts. Wait a moment and try again.");a(H,!0);return}let x=await i.json(),v=x.code||x.checkCode||"";if(!v){a(p("web.pair.nocode","Hub did not return a comparison code."),!0);return}let y=Date.now();D=x.expiresAt?x.expiresAt<10000000000?x.expiresAt*1000:x.expiresAt:y+(x.expiresIn?x.expiresIn*1000:120000),o();let P=j;e=1000,R=x.pollMs&&x.pollMs>=100?x.pollMs:150,L.textContent=re(v),f.classList.add("bp-hidden"),E.classList.remove("bp-hidden"),C.textContent="",m(),g=window.setInterval(m,1000),A=window.setTimeout(()=>{k(P)},R)}catch{a(p("web.pair.unreachable","Could not reach the hub. Check your tailnet connection."),!0)}})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",ee);else ee(); diff --git a/web/dist/assets/style.css b/web/dist/assets/style.css index 2dc49d16ef..73dc79c7ce 100644 --- a/web/dist/assets/style.css +++ b/web/dist/assets/style.css @@ -1362,6 +1362,47 @@ html.light .bp-code-block { background: var(--panel); } @keyframes bp-ap-slide { from { left: -30%; } to { left: 100%; } } .bp-ap-notes { margin: 0; padding-left: 18px; display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--dim); } +/* Thread context inspector */ +.bp-context { + width: min(820px, calc(100vw - 36px)); + max-height: min(760px, calc(100dvh - 36px)); + margin: auto; + padding: 0; + color: var(--text); + background: var(--panel); + border: 1px solid var(--rule); + box-shadow: 0 20px 60px #0005; +} +.bp-context[open] { display: flex; flex-direction: column; } +.bp-context::backdrop { background: #0009; } +.bp-context-head, .bp-context-tabs { + display: flex; + align-items: start; + padding: 14px 18px; + gap: 8px; +} +.bp-context-head > div { min-width: 0; flex: 1; } +.bp-context-head h2 { margin: 0 0 4px; font-size: 17px; } +.bp-context-tabs { padding-top: 0; flex-wrap: wrap; border-bottom: 1px solid var(--rule); } +.bp-context-tabs button[aria-pressed="true"] { background: var(--raise); color: var(--accent); border-color: var(--line); } +.bp-context-body { min-height: 150px; overflow-y: auto; padding: 16px 18px; display: grid; align-content: start; gap: 10px; } +.bp-context-body h3 { font-size: 13px; margin: 6px 0 0; } +.bp-context-body p { margin: 0; } +.bp-context-card { border: 1px solid var(--line); padding: 12px; display: grid; gap: 8px; } +.bp-context-card summary { cursor: pointer; } +.bp-context-card summary .bp-context-row { display: inline-flex; width: calc(100% - 20px); } +.bp-context-card summary small { display: block; margin-block-start: 4px; } +.bp-context-card[open] summary { margin-bottom: 10px; } +.bp-context-row { display: flex; justify-content: space-between; align-items: center; gap: 12px; overflow-wrap: anywhere; } +.bp-context-path { color: var(--dim); font: 11px/1.5 var(--mono); overflow-wrap: anywhere; } +.bp-context-code { background: var(--raise); margin: 0; padding: 12px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px/1.55 var(--mono); } +.bp-context-badge { flex-shrink: 0; background: var(--raise); color: var(--dim); padding: 3px 7px; font-size: 11px; } +.bp-context-badge.active { color: var(--accent); } +.bp-context-badge.warn { color: var(--warn); } +.bp-context-actions { display: flex; justify-content: end; } +.bp-context-notice { color: var(--dim); font-size: 12px; padding: 8px 18px 0; margin: 0; } +.bp-context-notice:empty { display: none; } + /* Web viewer pane + 1440 / 820 / 390 px responsive styles. Auto-concatenated into web/dist/assets/style.css by web/build.ts. diff --git a/web/dist/manifest.json b/web/dist/manifest.json index 4d516b5fce..d25e7f2600 100644 --- a/web/dist/manifest.json +++ b/web/dist/manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "totalAssetGzipBytes": 172579, + "totalAssetGzipBytes": 176221, "styleTokensSha256": "a4fed1b1c7bc676acc328907343eb5dcf87e426383d05617c632e48c0c3f2b80", "i18nKeys": [ "agy.signout", @@ -11,6 +11,7 @@ "common.close", "common.copy", "common.delete", + "common.refresh", "common.remove", "common.save", "composer.placeholder", @@ -100,6 +101,24 @@ "sheet.rename", "sidebar.add.project", "sidebar.search.projects", + "thread.context.base", + "thread.context.copied", + "thread.context.copy", + "thread.context.disable", + "thread.context.enable", + "thread.context.index", + "thread.context.injected.label", + "thread.context.instructions", + "thread.context.mcp", + "thread.context.native.note", + "thread.context.none.instructions", + "thread.context.none.mcp", + "thread.context.reading", + "thread.context.size", + "thread.context.skills", + "thread.context.system", + "thread.context.title", + "thread.context.trust", "thread.new", "tools.pinned", "tools.retry", @@ -168,10 +187,10 @@ "web.pair.subtitle", "web.pair.unreachable" ], - "i18nSubsetSha256": "38a5aa169aa24805f1fed0da8b6fbc45af2f985fe9081a3bab809b2a5226acc6", + "i18nSubsetSha256": "69725b96676d71f43196609aaa8ac5ff48f24a97663c94077a72c3624be5961f", "inputs": { "web/src/addproject.ts": "06a7ff3e13cd78d993ebca7f638d5d623da06c0099186ad534bae8f184dbe44f", - "web/src/app.ts": "f04a51107c373383ebdffa4c0d88ded6e2379edf22f0770613e440df5b79560b", + "web/src/app.ts": "0ece95ecbbb502b1f09b6073209c1c38d58161d0304d43bbd30ab63b2506ca20", "web/src/chat.ts": "f9a496a25d0a71e1ffb0da2ce53aba60eeb253d67084aa836fc7270e000a7ac6", "web/src/clone-model.ts": "d265df49436e14f415bbeb2a271ffa3552f9163be62bdc0158cecc10c3cdae45", "web/src/composer.ts": "11e5b7e09743821f83c05201cebd8a9fbfbef0ce3c38e3f3a22000a4fabe1976", @@ -190,9 +209,10 @@ "web/src/qr.ts": "04b634557884b8f512a7b03ad9638c1c15a299ffaea0103d1bdeec6338d9b9d3", "web/src/rail.ts": "5fb391094992578cb6f54d35d53559951a584c43fcfc2ee6f4f2cc3897acfe46", "web/src/settings.ts": "7b4d8be26fabc6c2a0b8af94a64572a0e3c1e589bf079bfa58c8985a8acd984a", - "web/src/shell.css": "4fbaa672080d666bf43fa9d3eec89cccf0b06ae75740fd3baaba8217778d0b9c", + "web/src/shell.css": "a1ef4f799cc6a25c22c1bc0a64706a4735f0fcc8e549889c40f6fc8599aee17c", "web/src/sidebar.ts": "a75a47cfe576f4d637fcddee6981ac597d1e6ab79c1046d241375a3213e03909", "web/src/swarm-need.ts": "503bbf5ffe0389f068847571c792321b0ad5c8d26a18c73b8e41c0a8989e227f", + "web/src/thread-context.ts": "b9fbd5b3ef0b1357b5a4444a1e9a0ac0606afe1c8a5377c4777752e918af0ac2", "web/src/viewers/browser-input.ts": "2be7672b8bfaded19f385ef56196793b9125130bffee7ac70afd493a3a91a9ab", "web/src/viewers/browser.ts": "44ba909e0e7d4c2d31672c97d41ad7e8039a8654e9929c2ba2650c7581f398ba", "web/src/viewers/cbor.ts": "0d2778a46998ab0c22c607dbca757494ad2ff6640b43a833356d227c09b80483", @@ -218,9 +238,9 @@ }, "outputs": { "assets/app.js": { - "bytes": 253737, - "gzipBytes": 72561, - "sha256": "e60f4f5664ab848583641d31ae060203a2e5f8f8b7ac4d612b62da90ee119ec5" + "bytes": 262037, + "gzipBytes": 74997, + "sha256": "303dd9435d4345a553d3fa24d777d3e802e3e413c81a6ba5f8bbb60f085cd24b" }, "assets/favicon-light.svg": { "bytes": 1207, @@ -238,14 +258,14 @@ "sha256": "123b6a27f255d339b505c8fd83609674f0bddf9b46c0e907fce23befa96b1eec" }, "assets/pair.js": { - "bytes": 34914, - "gzipBytes": 11433, - "sha256": "a820e5c76e88dc79ace136fcbbcce483cac7579906c4bec776233f05a049989e" + "bytes": 38015, + "gzipBytes": 12198, + "sha256": "245dbc584241743e229c382512534c6d3da10571a5a325767e07c9ab63823deb" }, "assets/style.css": { - "bytes": 56184, - "gzipBytes": 10286, - "sha256": "793b208b97d22f0c865b6a44266029a26de8a6416f2d237d69222005a131f668" + "bytes": 58368, + "gzipBytes": 10727, + "sha256": "0badc1c201f166b2922120ad78b7f2cae8969be606b736c6ba6e2f957a9b7359" }, "assets/terminal.js": { "bytes": 296616, diff --git a/web/src/app.ts b/web/src/app.ts index 5766b11e80..7db9203cc7 100644 --- a/web/src/app.ts +++ b/web/src/app.ts @@ -13,6 +13,7 @@ import { CommandPalette, type PaletteAction, type PaletteSearchResult } from "./ import { RailView, type RailEntry } from "./rail"; import { needAfter, needPress } from "./swarm-need"; import { SettingsModal, type SettingsRow } from "./settings"; +import { ThreadContextDialog } from "./thread-context"; import { SidebarView, type BotItem, @@ -566,6 +567,8 @@ function mountApp(): void { const th = threads.find((x) => x.id === selectedThreadId); if (th) void runThreadAct(th.id, th.settled ? "unsettle" : "settle"); }); + const threadContext = new ThreadContextDialog(root, (thread, decision) => + decision ? hub.rpc("thread.context.mcp", { thread, ...decision }) : hub.rpc("thread.context", { thread })); threadMenuBtn.addEventListener("click", (e) => { e.stopPropagation(); const th = threads.find((x) => x.id === selectedThreadId); @@ -590,6 +593,7 @@ function mountApp(): void { }, }, ]; + if (hub.hasFeature("threadContext")) items.unshift({ label: t("thread.context.title", "Context & Prompt"), run: () => threadContext.open(th.id) }); const frag = document.createDocumentFragment(); for (const it of items) { const btn = document.createElement("button"); diff --git a/web/src/shell.css b/web/src/shell.css index 0c290b5a1f..b90da5ddae 100644 --- a/web/src/shell.css +++ b/web/src/shell.css @@ -1268,3 +1268,44 @@ html.light .bp-code-block { background: var(--panel); } .bp-ap-bar.indeterminate .bp-ap-bar-fill { position: absolute; width: 30%; animation: bp-ap-slide 1.2s ease-in-out infinite; } @keyframes bp-ap-slide { from { left: -30%; } to { left: 100%; } } .bp-ap-notes { margin: 0; padding-left: 18px; display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--dim); } + +/* Thread context inspector */ +.bp-context { + width: min(820px, calc(100vw - 36px)); + max-height: min(760px, calc(100dvh - 36px)); + margin: auto; + padding: 0; + color: var(--text); + background: var(--panel); + border: 1px solid var(--rule); + box-shadow: 0 20px 60px #0005; +} +.bp-context[open] { display: flex; flex-direction: column; } +.bp-context::backdrop { background: #0009; } +.bp-context-head, .bp-context-tabs { + display: flex; + align-items: start; + padding: 14px 18px; + gap: 8px; +} +.bp-context-head > div { min-width: 0; flex: 1; } +.bp-context-head h2 { margin: 0 0 4px; font-size: 17px; } +.bp-context-tabs { padding-top: 0; flex-wrap: wrap; border-bottom: 1px solid var(--rule); } +.bp-context-tabs button[aria-pressed="true"] { background: var(--raise); color: var(--accent); border-color: var(--line); } +.bp-context-body { min-height: 150px; overflow-y: auto; padding: 16px 18px; display: grid; align-content: start; gap: 10px; } +.bp-context-body h3 { font-size: 13px; margin: 6px 0 0; } +.bp-context-body p { margin: 0; } +.bp-context-card { border: 1px solid var(--line); padding: 12px; display: grid; gap: 8px; } +.bp-context-card summary { cursor: pointer; } +.bp-context-card summary .bp-context-row { display: inline-flex; width: calc(100% - 20px); } +.bp-context-card summary small { display: block; margin-block-start: 4px; } +.bp-context-card[open] summary { margin-bottom: 10px; } +.bp-context-row { display: flex; justify-content: space-between; align-items: center; gap: 12px; overflow-wrap: anywhere; } +.bp-context-path { color: var(--dim); font: 11px/1.5 var(--mono); overflow-wrap: anywhere; } +.bp-context-code { background: var(--raise); margin: 0; padding: 12px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px/1.55 var(--mono); } +.bp-context-badge { flex-shrink: 0; background: var(--raise); color: var(--dim); padding: 3px 7px; font-size: 11px; } +.bp-context-badge.active { color: var(--accent); } +.bp-context-badge.warn { color: var(--warn); } +.bp-context-actions { display: flex; justify-content: end; } +.bp-context-notice { color: var(--dim); font-size: 12px; padding: 8px 18px 0; margin: 0; } +.bp-context-notice:empty { display: none; } diff --git a/web/src/thread-context.ts b/web/src/thread-context.ts new file mode 100644 index 0000000000..1bc745f549 --- /dev/null +++ b/web/src/thread-context.ts @@ -0,0 +1,233 @@ +import { t, trs } from "./i18n"; + +interface Instruction { + path: string; + bytes: number; + estimated_tokens: number; + status: string; + preview: string; + note: string; +} + +interface Skill { + scope: string; + status: string; + name: string; + description: string; + path: string; + source: string; + provider: string; + model: string; +} + +interface Server { + name: string; + command: string; + args: string[]; + url: string; + cwd: string; + status: string; +} + +interface Config { + path: string; + sha256: string; + state: string; + error: string; + servers: Server[]; +} + +interface Context { + cwd: string; + instructions: Instruction[]; + skills: Skill[]; + mcp: Config[]; + prompt: string; + sections: { base: string; instructions: string; skills: string }; +} + +interface Decision { action: string; path: string; sha256: string } + +function el(tag: K, css?: string, text?: string): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + if (css) node.className = css; + if (text) node.textContent = text; + return node; +} + +function button(label: string, click: () => void, primary = false): HTMLButtonElement { + const node = el("button", primary ? "primary" : "bp-btn-ghost", label); + node.type = "button"; + node.addEventListener("click", click); + return node; +} + +function code(text: string): HTMLElement { + return el("pre", "bp-context-code", text); +} + +function badge(status: string): HTMLElement { + const tone = status === "Native" || status === "Enabled" ? "active" : status === "Untrusted" || status === "Invalid" ? "warn" : ""; + return el("span", `bp-context-badge ${tone}`, trs(status)); +} + +function heading(title: string, status: string): HTMLElement { + const node = el("div", "bp-context-row"); + node.append(el("strong", undefined, title), badge(status)); + return node; +} + +export class ThreadContextDialog { + private dialog = el("dialog", "bp-context"); + private title = el("h2"); + private cwd = el("div", "bp-context-path"); + private tabs = el("div", "bp-context-tabs"); + private body = el("div", "bp-context-body"); + private notice = el("p", "bp-context-notice"); + private current?: Context; + private thread = ""; + private requestId = 0; + private tab = 0; + private busy = false; + + constructor(root: HTMLElement, private fetchContext: (thread: string, decision?: Decision) => Promise) { + const head = el("div", "bp-context-head"); + const caption = el("div"); + caption.append(this.title, this.cwd); + this.title.id = "bp-context-title"; + this.dialog.setAttribute("aria-labelledby", this.title.id); + this.notice.setAttribute("role", "status"); + head.append(caption, button(t("common.refresh", "Refresh"), () => { void this.load(); }), button(t("common.close", "Close"), () => this.dialog.close())); + this.dialog.append(head, this.tabs, this.notice, this.body); + this.dialog.addEventListener("close", () => { this.requestId++; }); + root.append(this.dialog); + } + + open(thread: string): void { + this.thread = thread; + this.tab = 0; + this.current = undefined; + this.busy = false; + this.title.textContent = t("thread.context.title", "Context & Prompt"); + this.cwd.textContent = ""; + if (!this.dialog.open) this.dialog.showModal(); + this.render(); + void this.load(); + } + + private async load(decision?: Decision): Promise { + if (this.busy) return; + const id = ++this.requestId; + this.busy = true; + this.notice.textContent = t("thread.context.reading", "Reading thread context…"); + this.render(); + try { + const snapshot = await this.fetchContext(this.thread, decision); + if (id !== this.requestId) return; + this.current = snapshot; + this.cwd.textContent = snapshot.cwd; + this.notice.textContent = ""; + } catch (error) { + if (id === this.requestId) this.notice.textContent = String(error); + } finally { + if (id === this.requestId) { + this.busy = false; + this.render(); + } + } + } + + private render(): void { + const labels = [t("thread.context.instructions", "Instructions"), t("thread.context.system", "System Prompt"), + t("thread.context.skills", "Skills"), t("thread.context.mcp", "Project MCPs")]; + this.tabs.replaceChildren(...labels.map((label, index) => { + const tab = button(label, () => { + this.tab = index; + this.render(); + this.body.scrollTop = 0; + (this.tabs.children[index] as HTMLElement).focus(); + }); + tab.setAttribute("aria-pressed", String(index === this.tab)); + return tab; + })); + this.body.replaceChildren(); + const data = this.current; + if (!data) return; + switch (this.tab) { + case 0: this.instructions(data.instructions); break; + case 1: this.prompt(data); break; + case 2: this.skills(data.skills); break; + case 3: this.mcps(data.mcp); break; + } + } + + private instructions(files: Instruction[]): void { + if (!files.length) this.body.append(el("p", "bp-dim", t("thread.context.none.instructions", "No project instructions found."))); + for (const file of files) { + const card = el("details", "bp-context-card"); + const summary = el("summary"); + summary.append(heading(file.path, file.status), el("small", "bp-dim", t("thread.context.size", "{bytes} B · ≈{tokens} tokens", + { bytes: file.bytes, tokens: file.estimated_tokens }))); + card.append(summary, code(file.preview)); + if (file.note) card.append(el("small", "bp-dim", file.note)); + this.body.append(card); + } + } + + private prompt(data: Context): void { + const header = el("div", "bp-context-row"); + const copy = button(t("thread.context.copy", "Copy prompt"), () => { + void navigator.clipboard.writeText(data.prompt).then(() => { + this.notice.textContent = t("thread.context.copied", "Prompt copied."); + }).catch(error => { this.notice.textContent = String(error); }); + }); + header.append(el("p", "bp-dim", t("thread.context.native.note", "Backplane’s launch prompt. Native files are loaded by the provider.")), copy); + this.body.append(header); + for (const [label, value] of [ + [t("thread.context.base", "Backplane"), data.sections.base], + [t("thread.context.injected.label", "Injected project instructions"), data.sections.instructions], + [t("thread.context.index", "Available skills index"), data.sections.skills], + ]) { + if (value) this.body.append(el("h3", undefined, label), code(value)); + } + } + + private skills(skills: Skill[]): void { + for (const scope of ["Project", "User", "Bundled"]) { + const group = skills.filter(skill => skill.scope === scope); + if (!group.length) continue; + this.body.append(el("h3", undefined, trs(scope))); + for (const skill of group) { + const card = el("article", "bp-context-card"); + card.append(heading(skill.name, skill.status), el("p", undefined, skill.description), + el("small", "bp-context-path", [skill.source, skill.provider, skill.model].filter(Boolean).join(" · ")), el("small", "bp-context-path", skill.path)); + this.body.append(card); + } + } + } + + private mcps(configs: Config[]): void { + if (!configs.length) this.body.append(el("p", "bp-dim", t("thread.context.none.mcp", "No project MCP configurations found."))); + for (const config of configs) { + const card = el("article", "bp-context-card"); + card.append(heading(config.path, config.state)); + for (const server of config.servers) { + const endpoint = server.url || [server.command, ...server.args].map(word => JSON.stringify(word)).join(" "); + card.append(heading(server.name, server.status), code(endpoint)); + if (server.cwd) card.append(el("small", "bp-context-path", server.cwd)); + } + if (config.error) card.append(el("p", "bp-warn", config.error)); + const action = config.state === "Untrusted" ? "trust" : config.state === "Enabled" ? "disable" : config.state === "Disabled" ? "enable" : ""; + if (action) { + const label = action === "trust" ? t("thread.context.trust", "Trust and enable") : action === "disable" + ? t("thread.context.disable", "Disable") : t("thread.context.enable", "Enable"); + const apply = button(label, () => { void this.load({ action, path: config.path, sha256: config.sha256 }); }, action === "trust"); + apply.disabled = this.busy; + const buttons = el("div", "bp-context-actions"); + buttons.append(apply); + card.append(buttons); + } + this.body.append(card); + } + } +}